Rise 5.99 Fly module 1 files, 2141 lines

Rise 5.99 Fly: Full Source Analysis

Rise 5.99's Fly is a single 2100-line class with more than thirty modes dispatched from a ModeSetting, making it one of the largest movement modules in the client.

dev/rise/module/impl/movement/Fly.java · GitHub source ↗

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

Analysis

Overview

Rise 5.99's Fly is a single 2100-line class with more than thirty modes dispatched from a ModeSetting, making it one of the largest movement modules in the client. The mode list spans vanilla capability flight (Vanilla, Creative), velocity-based flight (Jetpack, Damage, Wait for Damage, Mush, Viper), anticheat-targeted exploits (Verus, Verus Lag, VerusBlack, Verus AirJump, Spartan, Aac3, Vulcan, Vulcan2, Matrix1.17, Redesky, Kauri, Taka, Vicnix, Exempted Value, ACR, ACR2), block-assisted flight (BlockFly, Block Drop, MineBox, Hycraft, Bow Longjump, Bow Fly), and packet-buffer modes (Hypixel, Hypixel Fast Lag, Hypixel Blink, Hypixel Infinite, Minemenclub, Minemenclub 2, MCCentral, Air Walk, Collide, Old NCP). The class implements onPreMotion for per-tick motion writes, onPacketSend and onPacketReceive for packet rewriting and cancellation, and a vanilla kick-bypass helper that streams position packets to a ground scan and back.

Architecture

The module's state is a large field block: tick counters, stage and boost ticks, the starting location triple, a ConcurrentLinkedQueue of buffered packets, a lastMotion vector, and per-mode flags like hypixelStart, fly, dmged and setback. onEnable snapshots the position, stores the starting location, resets counters, optionally fakes damage by sending a health-update byte, and runs mode-specific setup such as the C0B sprint injection for Verus or the teleport-down position packet for Hycraft. onDisable restores the fov, speedInAir, fly capability and timer speed, then flushes any buffered packets through sendPacketWithoutEvent. onUpdateAlwaysInGui hides settings that do not apply to the active mode, which is how the enormous setting surface stays usable.

Key techniques

onPacketSend is where several modes hide their traffic. Block Drop cancels every outgoing C03 and injects a C06 pos-look when a C02 use-entity goes out; Hycraft cancels all C03 packets; MineBox cancels C03 packets while on the Minebox server; Vicnix rate-limits outgoing movement; Hypixel Blink and Spartan buffer outgoing packets and flush them on a timer or tick pattern; Minemenclub buffers everything except chat after a jump; and the Hypixel mode rewrites the onGround flag of outgoing C03 packets to true once the fly state and stage are active. onPacketReceive handles S08 teleports per mode (Hypixel sets a setback flag, Hycraft cancels and re-sends the teleport target as a C06, Minemenclub cancels, Vulcan resets its tick counter, Verus disables the module on flag, Block Drop cancels and records the teleport), cancels S12 knockback for most modes, and converts the knockback into a jump for Bow Fly.

Representative modes

The Vanilla and MineBox modes pin motionY to the fly speed setting (or a random sub-unit value for kick bypass) and strafe at the same speed; the optional Vanilla Kick Bypass in Packet mode runs handleVanillaKickBypass, which scans down to the ground in 8-block steps sending a C04 per step, then climbs back the same way, so the server sees a continuous grounded path. The Verus mode injects a sprint action packet on enable and disables itself when a teleport arrives; Verus Lag drops the event y by 20 plus a random amount every 20 ticks and fakes ground near 1/64 block boundaries. The Vulcan mode pins posY to the starting location and runs a timed motionY and strafe sequence on fixed hypixelTicks. The Hypixel mode sets timer speed to 2, finds a slime block in the inventory, places it to push itself up, and then flies with a fake ground flag, pitch near 90 and an 0.42 jump.

source Fly.java (module)

Fly.java2141 lines · JavaOriginal ↗
1
/*
2
 Copyright Alan Wood 2021
3
 None of this code to be reused without my written permission
4
 Intellectual Rights owned by Alan Wood
5
 */
6
package dev.rise.module.impl.movement;
7
8
import de.gerrygames.viarewind.utils.ChatUtil;
9
import de.gerrygames.viarewind.utils.math.Vector3d;
10
import dev.rise.Rise;
11
import dev.rise.event.impl.motion.PostMotionEvent;
12
import dev.rise.event.impl.motion.PreMotionEvent;
13
import dev.rise.event.impl.other.*;
14
import dev.rise.event.impl.packet.PacketReceiveEvent;
15
import dev.rise.event.impl.packet.PacketSendEvent;
16
import dev.rise.module.Module;
17
import dev.rise.module.api.ModuleInfo;
18
import dev.rise.module.enums.Category;
19
import dev.rise.setting.impl.BooleanSetting;
20
import dev.rise.setting.impl.ModeSetting;
21
import dev.rise.setting.impl.NumberSetting;
22
import dev.rise.util.Vector;
23
import dev.rise.util.math.MathUtil;
24
import dev.rise.util.math.RandomUtil;
25
import dev.rise.util.math.TimeUtil;
26
import dev.rise.util.player.*;
27
import net.minecraft.block.Block;
28
import net.minecraft.block.BlockAir;
29
import net.minecraft.block.BlockSlime;
30
import net.minecraft.client.Minecraft;
31
import net.minecraft.client.entity.EntityPlayerSP;
32
import net.minecraft.entity.player.EntityPlayer;
33
import net.minecraft.item.*;
34
import net.minecraft.network.Packet;
35
import net.minecraft.network.play.client.*;
36
import net.minecraft.network.play.server.S08PacketPlayerPosLook;
37
import net.minecraft.network.play.server.S12PacketEntityVelocity;
38
import net.minecraft.network.play.server.S27PacketExplosion;
39
import net.minecraft.potion.Potion;
40
import net.minecraft.potion.PotionEffect;
41
import net.minecraft.util.*;
42
import org.apache.commons.lang3.RandomUtils;
43
import org.lwjgl.util.vector.Vector2f;
44
45
import java.util.concurrent.ConcurrentLinkedQueue;
46
47
/**
48
 * This module allows you to fly like a bird. Pretty self explanatory.
49
 */
50
@ModuleInfo(name = "Fly", description = "Lets you fly", category = Category.MOVEMENT)
51
public final class Fly extends Module {
52
53
    public static boolean hypixelDisable;
54
    private final ModeSetting mode = new ModeSetting("Fly Mode", this, "Vanilla", "Vanilla", "Damage"/*, "Custom"*/, "Creative",
55
            "Jetpack", "Hypixel", "Hypixel Fast Lag", "Verus", "Verus Lag", "VerusBlack", "Verus AirJump", "Air Walk", "Bow Longjump", "Mush", "Viper", "Bow Fly", "ACR", "ACR2", "Collide",
56
            "Spartan", "Aac3", "MCCentral", "Exempted Value", "Kauri", "Taka", "Vicnix", "Wait for Damage", "Old NCP", "Minemenclub", "Minemenclub 2",
57
            "Redesky", "BlockFly", "Matrix1.17", "Vulcan", "Vulcan2", "MineBox", "Hycraft", "Block Drop");
58
59
    private final ModeSetting exemptedValueType = new ModeSetting("Value", this, "1", "1", "2", "3");
60
    private final ModeSetting redeskyMode = new ModeSetting("Mode", this, "Stable", "Stable", "Fast");
61
    private final NumberSetting flySpeed = new NumberSetting("Fly Speed", this, 1, 0.1, 9.5, 0.1);
62
    private final BooleanSetting autoStop = new BooleanSetting("Auto Stop", this, true);
63
    private final NumberSetting bowFlyHBoost1 = new NumberSetting("H Boost first tick", this, 4, 0, 8.5, 0.1);
64
    private final NumberSetting bowFlyVBoost1 = new NumberSetting("V Boost first tick", this, 4, 0, 8.5, 0.1);
65
    private final NumberSetting bowFlyHBoost2 = new NumberSetting("H Boost second tick", this, 4, 0, 8.5, 0.1);
66
    private final NumberSetting bowFlyVBoost2 = new NumberSetting("V Boost second tick", this, 4, 0, 8.5, 0.1);
67
    private final NumberSetting multiplierInAir = new NumberSetting("Multiplier In Air", this, 1.08, 1, 1.4, 0.1);
68
    private final NumberSetting glide = new NumberSetting("Glide", this, 0.03, 0, 0.1, 0.01);
69
    private final NumberSetting timer = new NumberSetting("Timer Speed", this, 1, 0.1, 2, 0.1);
70
    private final BooleanSetting strafe = new BooleanSetting("Strafe", this, true);
71
    private final BooleanSetting sprint = new BooleanSetting("Sprint", this, true);
72
    private final BooleanSetting inf = new BooleanSetting("Infinite", this, false);
73
    private final ModeSetting vanillaBypass = new ModeSetting("Vanilla Kick Bypass", this, "Off", "Off", "Motion", "Packet");
74
    private final BooleanSetting delayKickBypass = new BooleanSetting("Delay Kick Bypass", this, false);
75
    private final BooleanSetting fakeDamage = new BooleanSetting("Fake Damage", this, false);
76
    private final BooleanSetting sigmaFastFly = new BooleanSetting("Sigma Fast Fly", this, false);
77
    private final BooleanSetting smoothCamera = new BooleanSetting("Smooth Camera", this, false);
78
    private final BooleanSetting groundSpoof = new BooleanSetting("Ground Spoof", this, false);
79
    private final BooleanSetting damage = new BooleanSetting("Damage", this, false);
80
    private final BooleanSetting disableOnWorldChange = new BooleanSetting("Disable on World Change", this, false);
81
    private final NumberSetting viewBobbing = new NumberSetting("View Bobbing", this, 0, 0, 0.1, 0.01);
82
    private final ConcurrentLinkedQueue<Packet<?>> packets = new ConcurrentLinkedQueue<>();
83
84
//    private final NumberSetting customSpeedH = new NumberSetting("Custom Speed Horizontal", this, 1, 0.1, 9.5, 0.1);
85
//    private final NumberSetting customSpeedV = new NumberSetting("Custom Speed Vertical", this, 1, 0.1, 9.5, 0.1);
86
//    private final NumberSetting customFall = new NumberSetting("Custom Fall Speed", this, 0, 0, 0.2, 0.005);
87
//    private final NumberSetting customTimer = new NumberSetting("Custom Timer", this, 1, 0.1, 5, 0.1);
88
//    private final ModeSetting customGround = new ModeSetting("Custom Ground State", this, "Real", "Real", "On Ground", "Off Ground");
89
//    private final ModeSetting customDamageMode = new ModeSetting("Custom Damage", this, "None", "None", "Fake", "Fall", "VClip");
90
//    private final BooleanSetting customBlink = new BooleanSetting("Custom Blink", this, false);
91
//    private final BooleanSetting customForceMovement = new BooleanSetting("Custom Force Movement", this, false);
92
//    private final BooleanSetting customLockY = new BooleanSetting("Custom Lock Y Input", this, false);
93
94
    private int i = 0;
95
    private int ticks, wasos, offGroundTicks, onGroundTicks, hypixelTicks, pearlSlot = -1;
96
    private boolean hypixelStart, jumped, flag, pearlFly, startFlyingCapability;
97
    private float speed, startSpeed = 0.05F;
98
    private int saveSlot = -1;
99
    private float oPositionY;
100
    private float fov = mc.gameSettings.fovSetting;
101
    private double moveSpeed, lastDist, d;
102
    private int stage;
103
    private double startingLocationX, startingLocationY, startingLocationZ, buffer;
104
    private boolean movingTowardsStartingLocation;
105
106
    private boolean bool;
107
    private int ticksSinceFlag, boostTicks;
108
109
    private boolean dmged;
110
    private boolean beingDmged;
111
    private boolean clipped;
112
113
    private final TimeUtil pearlTimer = new TimeUtil();
114
115
    private Vector lastMotion = new Vector(0, 0, 0);
116
    private long groundTimer;
117
    boolean firstEnable;
118
    boolean nearEntity;
119
120
    private de.gerrygames.viarewind.utils.math.Vector3d position;
121
    private Vector2f rotation;
122
123
    private final Vec3 lastReportedPosition = new Vec3(0, 0, 0);
124
    private int packet = 0;
125
    private final int tick = 0;
126
127
    private boolean setback, fly;
128
129
    public static double roundToOnGround(final double posY) {
130
        return posY - (posY % 0.015625);
131
    }
132
133
    @Override
134
    protected void onDisable() {
135
        mc.gameSettings.fovSetting = fov;
136
        clipped = false;
137
        hypixelStart = false;
138
        mc.thePlayer.speedInAir = 0.02f;
139
        mc.thePlayer.capabilities.isFlying = false;
140
        mc.thePlayer.capabilities.flySpeed = startSpeed;
141
142
        mc.timer.timerSpeed = 1;
143
144
        dmged = false;
145
        beingDmged = false;
146
147
        saveSlot = -1;
148
        speed = 0.0f;
149
        jumped = false;
150
151
        EntityPlayer.enableCameraYOffset = false;
152
153
        switch (mode.getMode()) {
154
            case "Creative":
155
                mc.thePlayer.capabilities.allowFlying = startFlyingCapability;
156
                break;
157
158
            case "Minemenclub 2": {
159
                if (mc.thePlayer.inventory.currentItem != i)
160
                    PacketUtil.sendPacketWithoutEvent(new C09PacketHeldItemChange(mc.thePlayer.inventory.currentItem));
161
            }
162
163
            case "Bow Longjump":
164
                if (flag) {
165
                    if (mc.thePlayer.inventory.currentItem != i)
166
                        PacketUtil.sendPacketWithoutEvent(new C09PacketHeldItemChange(mc.thePlayer.inventory.currentItem));
167
                }
168
169
                MoveUtil.stop();
170
                break;
171
            case "Air Walk":
172
                viewBobbing.value = 0.0f;
173
                MoveUtil.stop();
174
                break;
175
            case "Vicnix":
176
                mc.thePlayer.motionY = 0;
177
                break;
178
179
            case "Verus":
180
                PacketUtil.sendPacketWithoutEvent(new C0BPacketEntityAction(mc.thePlayer, C0BPacketEntityAction.Action.STOP_SPRINTING));
181
                MoveUtil.strafe(0);
182
                break;
183
184
            case "Hycraft":
185
            case "MineBox":
186
            case "Damage":
187
            case "VerusBlack":
188
            case "Verus Lag":
189
            case "Vanilla":
190
                MoveUtil.stop();
191
                break;
192
193
            case "Minemenclub":
194
                MoveUtil.stop();
195
                break;
196
197
            case "Hypixel Fast Lag":
198
                if (PlayerUtil.isOnServer("Hypixel"))
199
                    PacketUtil.sendPacketWithoutEvent(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));
200
                MoveUtil.stop();
201
                break;
202
203
            case "Hypixel":
204
            case "Hypixel Blink":
205
            case "Hypixel Infinite":
206
                if (pearlSlot != -1) {
207
                    MoveUtil.stop();
208
                    pearlSlot = -1;
209
                    pearlFly = false;
210
                }
211
                break;
212
213
            case "Matrix1.17":
214
                PacketUtil.sendPacketWithoutEvent(new C09PacketHeldItemChange(mc.thePlayer.inventory.currentItem));
215
                break;
216
217
            case "Dev":
218
                mc.thePlayer.motionY = -0.09800000190735147;
219
                MoveUtil.stop();
220
                MoveUtil.strafe(0.1);
221
                break;
222
            case "Vulcan":
223
                mc.thePlayer.motionY = -0.09800000190735147;
224
                MoveUtil.stop();
225
                MoveUtil.strafe(0.1);
226
                break;
227
        }
228
229
        if (packets.isEmpty()) return;
230
        packets.forEach(PacketUtil::sendPacketWithoutEvent);
231
        packets.clear();
232
    }
233
234
    @Override
235
    protected void onEnable() {
236
        this.position = new de.gerrygames.viarewind.utils.math.Vector3d(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ);
237
        this.rotation = new Vector2f(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch);
238
        boostTicks = 0;
239
        fov = mc.gameSettings.fovSetting;
240
        clipped = false;
241
        hypixelStart = false;
242
        hypixelTicks = 0;
243
        flag = false;
244
        wasos = 0;
245
        hypixelDisable = false;
246
        dmged = false;
247
        oPositionY = (float) mc.thePlayer.posY;
248
        moveSpeed = 0.18D;
249
        stage = 0;
250
        jumped = false;
251
        startSpeed = mc.thePlayer.capabilities.flySpeed;
252
        startFlyingCapability = mc.thePlayer.capabilities.allowFlying;
253
        packet = 0;
254
        bool = false;
255
        ticks = 0;
256
        startingLocationX = mc.thePlayer.posX;
257
        startingLocationZ = mc.thePlayer.posZ;
258
        startingLocationY = mc.thePlayer.posY;
259
        movingTowardsStartingLocation = false;
260
        ticksSinceFlag = 999;
261
        mc.timer.timerSpeed = 1.0F;
262
        speed = 0;
263
        buffer = 0;
264
        ticksSinceFlag = -99999999;
265
        fly = false;
266
267
        // Good code?, Who cares.
268
        if (fakeDamage.isEnabled() && !(mode.is("Verus") || mode.is("Minemenclub") || mode.is("Old NCP") || mode.is("Bow Longjump") || mode.is("Minemenclub 2") || mode.is("Vulcan2") || mode.is("Damage") || mode.is("Wait for Damage") || mode.is("Bow Fly") || mode.is("ACR") || mode.is("Aac3") || mode.is("Taka"))) {
269
            mc.thePlayer.handleHealthUpdate((byte) 2);
270
        }
271
272
        switch (mode.getMode()) {
273
274
            case "Air Walk": {
275
                viewBobbing.value = 0.1f;
276
                if (!firstEnable) {
277
                    firstEnable = true;
278
                    Rise.addChatMessage("Verus Air Lin.. Air Walks");
279
                }
280
            }
281
            case "Redesky":
282
                if (!firstEnable) {
283
                    firstEnable = true;
284
                    this.registerNotification("Credits to Dort for the fly.");
285
                }
286
                break;
287
288
            case "Hycraft": {
289
                flag = false;
290
                pearlTimer.reset();
291
292
                if (!mc.thePlayer.onGround) {
293
                    this.toggleModule();
294
                    Rise.INSTANCE.getNotificationManager().registerNotification("You need to be on ground!");
295
                    return;
296
                }
297
298
                PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY - 2 + Math.random() / 2, mc.thePlayer.posZ, false));
299
300
                break;
301
            }
302
303
            case "Vulcan":
304
                if (inf.isEnabled() && !firstEnable) {
305
                    firstEnable = true;
306
                    this.registerNotification("Having inf on might flag.");
307
                }
308
                break;
309
310
            case "Verus Lag":
311
                flag = true;
312
                break;
313
314
            case "Verus":
315
                PacketUtil.sendPacketWithoutEvent(new C0BPacketEntityAction(mc.thePlayer, C0BPacketEntityAction.Action.START_SPRINTING));
316
                break;
317
        }
318
    }
319
320
321
    @Override
322
    public void onUpdateAlwaysInGui() {
323
        bowFlyHBoost1.hidden = bowFlyHBoost2.hidden = bowFlyVBoost1.hidden = bowFlyVBoost2.hidden = glide.hidden = timer.hidden = multiplierInAir.hidden = strafe.hidden = !(mode.is("Bow Longjump"));
324
325
        autoStop.hidden = !mode.is("Verus");
326
327
        sprint.hidden = !mode.is("Air Walk");
328
329
        flySpeed.hidden = !(mode.is("Vanilla") || mode.is("MineBox") || mode.is("Hypixel") || mode.is("Hypixel Fast Lag") || mode.is("Taka") || mode.is("Minemenclub 2") || mode.is("Minemenclub") || mode.is("Old NCP") || mode.is("Mush") || mode.is("Viper") || mode.is("Verus Lag") || mode.is("Verus") || mode.is("Collide") || mode.is("Creative") || mode.is("Damage") || mode.is("Hypixel Infinite") || mode.is("Hypixel Blink") || mode.is("Hypixel"));
330
331
        fakeDamage.hidden = (mode.is("Verus") || mode.is("Hypixel") || mode.is("Minemenclub") || mode.is("Custom") || mode.is("Old NCP") || mode.is("Bow Longjump") || mode.is("Minemenclub 2") || mode.is("Vulcan2") || mode.is("Damage") || mode.is("Wait for Damage") || mode.is("Bow Fly") || mode.is("ACR") || mode.is("Aac3") || mode.is("Taka"));
332
333
        groundSpoof.hidden = !mode.is("Exempted Value");
334
335
        damage.hidden = !mode.is("Old NCP");
336
337
        inf.hidden = !mode.is("Vulcan");
338
339
        redeskyMode.hidden = !mode.is("Redesky");
340
341
        timer.hidden = !(mode.is("Hypixel Blink") || mode.is("Old NCP") || mode.is("Bow Longjump"));
342
343
        vanillaBypass.hidden = !mode.is("Vanilla");
344
345
        delayKickBypass.hidden = !(mode.is("Vanilla") && vanillaBypass.is("Packet"));
346
347
        exemptedValueType.hidden = !mode.is("Exempted Value");
348
349
        smoothCamera.hidden = sigmaFastFly.hidden = mode.is("Custom");
350
    }
351
352
    @Override
353
    public void onPreMotion(final PreMotionEvent event) {
354
        ticks++;
355
        if (sigmaFastFly.isEnabled()) mc.gameSettings.fovSetting = 150;
356
357
        ++ticks;
358
359
        if (vanillaBypass.is("Packet")) {
360
            if (!delayKickBypass.isEnabled() || mc.thePlayer.ticksExisted % 10 == 0)
361
                handleVanillaKickBypass();
362
        }
363
364
        final double x = mc.thePlayer.posX - mc.thePlayer.prevPosX;
365
        final double z = mc.thePlayer.posZ - mc.thePlayer.prevPosZ;
366
        lastDist = Math.hypot(x, z);
367
368
        if (mc.thePlayer.onGround) {
369
            offGroundTicks = 0;
370
            ++onGroundTicks;
371
        } else {
372
            onGroundTicks = 0;
373
            ++offGroundTicks;
374
        }
375
376
        if (mc.thePlayer.ticksExisted < 2) {
377
            packets.clear();
378
            mc.timer.timerSpeed = 1;
379
            toggleModule();
380
        }
381
382
        mc.thePlayer.cameraYaw = (float) viewBobbing.getValue();
383
        EntityPlayer.enableCameraYOffset = false;
384
385
        if (smoothCamera.isEnabled()) {
386
            if (mc.thePlayer.posY > oPositionY || mode.is("Aac3")) {
387
                EntityPlayer.enableCameraYOffset = true;
388
                EntityPlayer.cameraYPosition = oPositionY;
389
            }
390
        }
391
392
        final Vector motion = new Vector(mc.thePlayer.motionX, 0, mc.thePlayer.motionZ);
393
394
        final Vector lastMotion = this.lastMotion;
395
        this.lastMotion = motion;
396
397
        switch (mode.getMode()) {
398
            case "Hypixel Fast Lag": {
399
                hypixelDisabler();
400
                break;
401
            }
402
403
            case "Block Drop": {
404
                mc.thePlayer.motionY = mc.gameSettings.keyBindJump.isKeyDown() ? 2 : mc.gameSettings.keyBindSneak.isKeyDown() ? -2 : 0;
405
406
                for (int i = 0; i < 3; ++i) {
407
                    PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C06PacketPlayerPosLook(position.getX(), position.getY(), position.getZ(), rotation.getX(), rotation.getY(), false));
408
                }
409
                break;
410
            }
411
412
            case "Hypixel": {
413
                mc.timer.timerSpeed = 2;
414
                if (ticks == 11 && mc.thePlayer.onGround) {
415
                    hypixelStart = true;
416
                    fly = true;
417
                }
418
                if (bool) {
419
                    wasos++;
420
421
                    if (wasos == 1) {
422
                    }
423
                }
424
425
                ticks--;
426
427
                event.setYaw((float) Math.toDegrees(MoveUtil.getDirection()));
428
429
                if (!fly) {
430
                    if (PlayerUtil.isOnServer("hypixel")) {
431
                        event.setPitch((float) (89 + Math.random() / 100f));
432
                    }
433
434
                    if (mc.thePlayer.onGround) {
435
                        mc.thePlayer.motionY = 0.42f;
436
                    }
437
438
                    if (mc.thePlayer.posY > startingLocationY + 1) {
439
                        int slot = -1;
440
441
                        for (int i = 0; i < 9; i++) {
442
                            if (mc.thePlayer.inventory.getStackInSlot(i) != null &&
443
                                    mc.thePlayer.inventory.getStackInSlot(i).getItem() instanceof ItemBlock) {
444
                                slot = PlayerUtil.findSlimeBlock();
445
                                break;
446
                            }
447
                        }
448
449
                        if (slot == -1) {
450
                            this.registerNotification("You need a slime block to make fly work!");
451
                            this.toggleModule();
452
                            return;
453
                        }
454
455
                        if (ticks > 5) {
456
                            int oldSlot = mc.thePlayer.inventory.currentItem;
457
                            mc.thePlayer.inventory.currentItem = slot;
458
459
                            MovingObjectPosition movingObjectPosition = mc.thePlayer.rayTraceCustom(4.5f, mc.thePlayer.rotationYaw, 90.0F);
460
                            if (movingObjectPosition == null) return;
461
                            if (movingObjectPosition.typeOfHit != MovingObjectPosition.MovingObjectType.BLOCK) return;
462
463
                            BlockPos blockPos = movingObjectPosition.getBlockPos();
464
                            EnumFacing enumFacing = movingObjectPosition.sideHit;
465
                            Vec3 hitVec = movingObjectPosition.hitVec;
466
467
                            if (mc.playerController.onPlayerRightClick(mc.thePlayer, mc.theWorld, mc.thePlayer.getHeldItem(), blockPos, enumFacing, hitVec)) {
468
                                mc.thePlayer.sendQueue.addToSendQueue(new C0APacketAnimation());
469
                            }
470
471
                            mc.thePlayer.inventory.currentItem = oldSlot;
472
                        }
473
                    }
474
                } else {
475
                    hypixelStart = true;
476
477
478
                    if (ticks <= 3) {
479
                    }
480
481
                    switch (ticks) {
482
                        case 0:
483
                            break;
484
485
                        case 3:
486
487
                            if (PlayerUtil.isOnServer("hypixel")) {
488
                                fly = true;
489
490
                            }
491
                            break;
492
493
                        default:
494
                            if (hypixelStart) {
495
                                boostTicks++;
496
                                mc.thePlayer.motionY = 0;
497
//                                mc.thePlayer.onGround = true;
498
                                event.setGround(true);
499
                            }
500
                            break;
501
                    }
502
503
                    ticks++;
504
                }
505
                break;
506
            }
507
508
            case "Hycraft": {
509
                MoveUtil.strafe(1.2 + Math.random() / 10D);
510
                mc.thePlayer.motionY = (mc.gameSettings.keyBindJump.isKeyDown() ? 0.42F : mc.gameSettings.keyBindSneak.isKeyDown() ? -0.42F : 0);
511
512
                if (!MoveUtil.isMoving()) MoveUtil.stop();
513
514
                if (pearlTimer.hasReached((long) (150 + Math.random() * 50)) && MoveUtil.isMoving()) {
515
                    pearlTimer.reset();
516
                    PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
517
                }
518
519
                break;
520
            }
521
522
            case "Vulcan2":
523
                ticksSinceFlag++;
524
                if (!(PlayerUtil.getBlockRelativeToPlayer(0, -0.2, 0) instanceof BlockAir) && mc.thePlayer.getDistanceSq(startingLocationX, startingLocationY, startingLocationZ) > 4 * 4) {
525
                    mc.thePlayer.jump();
526
                    ticksSinceFlag = 0;
527
                }
528
529
                if (!(ticksSinceFlag <= 20 && ticksSinceFlag >= 0)) {
530
                    mc.thePlayer.motionY = 0;
531
                    switch (offGroundTicks) {
532
                        case 1:
533
                            mc.thePlayer.motionY = mc.gameSettings.keyBindJump.isKeyDown() ? 1 : 0.5;
534
                            break;
535
                        case 2:
536
                            mc.thePlayer.motionY = mc.gameSettings.keyBindSneak.isKeyDown() ? -1 : -0.5;
537
                            break;
538
                        case 3:
539
                            mc.thePlayer.motionY = 0;
540
                            offGroundTicks = 0;
541
                            break;
542
                    }
543
                } else if (ticksSinceFlag >= 4) {
544
                    mc.thePlayer.motionY = 0;
545
                    mc.thePlayer.setPosition(mc.thePlayer.posX, Math.round(event.getY() / 0.5) * 0.5, mc.thePlayer.posZ);
546
                }
547
548
                if ((ticksSinceFlag <= 20 && ticksSinceFlag >= 0 && ticksSinceFlag >= 4) || mc.thePlayer.posY % 0.5 == 0) {
549
                    if (PlayerUtil.generalAntiPacketLog()) {
550
                        final double mathGround2 = Math.round(event.getY() / 0.015625) * 0.015625;
551
                        MoveUtil.strafe(0.2974 - 0.128);
552
553
                        mc.thePlayer.setPosition(mc.thePlayer.posX, mathGround2, mc.thePlayer.posZ);
554
555
                        event.setY(mathGround2);
556
                        event.setGround(true);
557
                        mc.thePlayer.onGround = true;
558
                    }
559
                }
560
561
                if (bool || (!PlayerUtil.generalAntiPacketLog() && ticks > 15)) {
562
                    if (PlayerUtil.generalAntiPacketLog())
563
                        PacketUtil.sendPacket(new C03PacketPlayer.C04PacketPlayerPosition((mc.thePlayer.posX + mc.thePlayer.lastTickPosX) / 2, (mc.thePlayer.posY + mc.thePlayer.lastTickPosY) / 2, (mc.thePlayer.posZ + mc.thePlayer.lastTickPosZ) / 2, true));
564
                    MoveUtil.strafe(MoveUtil.moveSpeed() * 1.5 * 2);
565
                    mc.timer.timerSpeed = 1.2f + mc.thePlayer.hurtTime / 3f;
566
                } else {
567
                    MoveUtil.strafe(MoveUtil.moveSpeed());
568
                }
569
                break;
570
571
            case "Jetpack": {
572
573
                if (mc.gameSettings.keyBindJump.isKeyDown()) {
574
575
                    if (mc.thePlayer.motionY < 0) {
576
                        mc.thePlayer.motionY += ticks / 30D;
577
                    } else {
578
                        mc.thePlayer.motionY = ticks / 30D;
579
                    }
580
581
                    mc.thePlayer.motionX *= 1.02;
582
                    mc.thePlayer.motionZ *= 1.02;
583
                } else {
584
                    ticks = 0;
585
                }
586
587
                break;
588
            }
589
590
            case "Vulcan":
591
                hypixelTicks++;
592
                mc.thePlayer.posY = startingLocationY;
593
                if (ticks == 1) {
594
                    event.setY(event.getY() - 0.1);
595
                }
596
597
                if (hypixelTicks == -9) {
598
                    if (inf.isEnabled()) mc.thePlayer.motionY = 2.9 / 3f;
599
                    else mc.thePlayer.motionY = 3.7;
600
                    MoveUtil.strafe(3.4);
601
                }
602
603
                if (inf.isEnabled()) {
604
                    if (MoveUtil.getSpeed() > 1 && hypixelTicks > -6) MoveUtil.strafe(0.34);
605
                }
606
607
                if (hypixelTicks == -6) {
608
                    MoveUtil.strafe(0.32);
609
                    mc.thePlayer.motionY = 0.24813599859094576 - 0.313605186719;
610
                }
611
612
                if (hypixelTicks > -6 && mc.thePlayer.ticksExisted % 2 == 0) {
613
                    mc.thePlayer.motionY = -0.09800000190735147;
614
                }
615
616
                if (inf.isEnabled()) {
617
                    if (hypixelStart && hypixelTicks % 35 == 0) mc.thePlayer.motionY = 2.9;
618
                }
619
620
                if (!MoveUtil.isMoving()) MoveUtil.stop();
621
                break;
622
623
            case "Matrix1.17": {
624
                final Integer item = PlayerUtil.findItem(null);
625
                if (item == null) return;
626
                PacketUtil.sendPacketWithoutEvent(new C09PacketHeldItemChange(item));
627
628
                mc.timer.timerSpeed = 1.6F;
629
630
                if (mc.thePlayer.movementInput.jump && mc.thePlayer.ticksExisted % 3 == 0) {
631
                    mc.timer.timerSpeed = 0.6F;
632
                    mc.thePlayer.motionY = 0.42F;
633
                }
634
635
                if (mc.thePlayer.onGround) {
636
                    mc.thePlayer.jump();
637
                }
638
639
                if (mc.thePlayer.fallDistance > 1) {
640
                    PacketUtil.sendPacket(new C08PacketPlayerBlockPlacement(null));
641
                    mc.thePlayer.motionY = -((mc.thePlayer.posY) - Math.floor(mc.thePlayer.posY));
642
                }
643
644
                if (mc.thePlayer.ticksExisted % 4 == 0) {
645
                    if (mc.thePlayer.ticksExisted % 24 == 0) {
646
                        PacketUtil.sendPacket(new C03PacketPlayer.C06PacketPlayerPosLook(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch, true));
647
                    }
648
                    PacketUtil.sendPacket(new C08PacketPlayerBlockPlacement(null));
649
                }
650
651
                if (mc.thePlayer.motionY == 0) {
652
                    mc.thePlayer.motionY = 0.42f;
653
                    mc.thePlayer.fallDistance = 0;
654
                }
655
                break;
656
            }
657
658
            case "MineBox":
659
            case "Vanilla": {
660
                float kickBypassMotion = (float) 0.0626D;
661
662
                if (mc.thePlayer.ticksExisted % 2 == 0)
663
                    kickBypassMotion = -kickBypassMotion;
664
665
                mc.thePlayer.motionY = mc.gameSettings.keyBindJump.isKeyDown() ? flySpeed.getValue() : mc.gameSettings.keyBindSneak.isKeyDown() ? -flySpeed.getValue() : vanillaBypass.is("Motion") ? kickBypassMotion : Math.random() / 1000;
666
667
                if (MoveUtil.isMoving())
668
                    MoveUtil.strafe(flySpeed.getValue() + Math.random() / 100);
669
                else
670
                    MoveUtil.stop();
671
                break;
672
            }
673
674
            case "Verus Lag": {
675
                if (flag || mc.thePlayer.ticksExisted % 20 == 0) { // I have no idea why this works but it does
676
                    event.setY(event.getY() - 20 - Math.random());
677
                    flag = false;
678
                }
679
680
                if (mc.thePlayer.posY % (1.0F / 64.0F) < 0.005)
681
                    event.setGround(true);
682
683
                mc.thePlayer.motionY = mc.gameSettings.keyBindJump.isKeyDown() ? flySpeed.getValue() : mc.gameSettings.keyBindSneak.isKeyDown() ? -flySpeed.getValue() : 0;
684
685
                if (MoveUtil.isMoving())
686
                    MoveUtil.strafe(flySpeed.getValue());
687
                else
688
                    MoveUtil.stop();
689
                break;
690
            }
691
692
            case "Verus": {
693
                if (ticks == 1) {
694
                    if (mc.thePlayer.isPotionActive(Potion.jump)) {
695
                        this.registerNotification("Cannot enable " + this.getModuleInfo().name() + " with Jump Boost.");
696
                        this.setEnabled(false);
697
                        return;
698
                    }
699
700
                    if (!mc.thePlayer.onGround) {
701
                        this.registerNotification("Cannot enable " + this.getModuleInfo().name() + " in air.");
702
                        this.setEnabled(false);
703
                        return;
704
                    }
705
                }
706
707
                if (offGroundTicks >= 2 && !mc.gameSettings.keyBindSneak.isKeyDown()) {
708
                    if (mc.gameSettings.keyBindJump.isKeyDown()) {
709
                        if (mc.thePlayer.ticksExisted % 2 == 0)
710
                            mc.thePlayer.motionY = 0.42F;
711
                    } else {
712
                        if (mc.thePlayer.onGround) {
713
                            mc.thePlayer.jump();
714
                        }
715
716
                        if (mc.thePlayer.fallDistance > 1) {
717
                            mc.thePlayer.motionY = -((mc.thePlayer.posY) - Math.floor(mc.thePlayer.posY));
718
                        }
719
720
                        if (mc.thePlayer.motionY == 0) {
721
                            mc.thePlayer.jump();
722
723
                            mc.thePlayer.onGround = true;
724
                            mc.thePlayer.fallDistance = 0;
725
                            event.setGround(true);
726
                        }
727
                    }
728
                }
729
730
                if (ticks > 30 && autoStop.isEnabled())
731
                    MoveUtil.strafe();
732
                else
733
                    MoveUtil.strafe(flySpeed.getValue());
734
735
                if ((ticks == 30 && autoStop.isEnabled()) || !MoveUtil.isMoving())
736
                    MoveUtil.stop();
737
738
                if (ticks == 1) {
739
                    mc.timer.timerSpeed = 0.15F;
740
                    DamageUtil.damagePlayer(DamageUtil.DamageType.POSITION, 3.42F, 1, true, false);
741
                    mc.thePlayer.jump();
742
                    event.setGround(true);
743
                } else
744
                    mc.timer.timerSpeed = 1;
745
                break;
746
            }
747
748
            case "Minemenclub": {
749
                if (MoveUtil.isMoving() && (PlayerUtil.isOnServer("minemen") || PlayerUtil.isOnServer("mineman"))) {
750
                    if (mc.thePlayer.onGround) {
751
                        if (!beingDmged) {
752
                            event.setY(event.getY() - (2.5 - Math.random() / 100));
753
                            jumped = false;
754
                            mc.timer.timerSpeed = 0.6f;
755
                        } else if (!jumped) {
756
                            mc.thePlayer.motionY = 0.6F;
757
                            jumped = true;
758
                        }
759
                    }
760
761
                    if (jumped) {
762
                        if (MoveUtil.isMoving())
763
                            MoveUtil.strafe(flySpeed.getValue());
764
                        else
765
                            MoveUtil.stop();
766
                    }
767
                }
768
769
                beingDmged = mc.thePlayer.onGround && mc.thePlayer.hurtTime > 0;
770
771
//                if (offGroundTicks == 7) {
772
//                    packets.forEach(PacketUtil::sendPacketWithoutEvent);
773
//                    packets.clear();
774
//                }
775
//
776
//                if (mc.thePlayer.onGround) {
777
//                    mc.thePlayer.jump();
778
//                }
779
//
780
//                if (mc.thePlayer.fallDistance > 1) {
781
//                    mc.thePlayer.motionY = -((mc.thePlayer.posY) - Math.floor(mc.thePlayer.posY));
782
//                }
783
//
784
//                if (mc.thePlayer.motionY == 0) {
785
//                    mc.thePlayer.jump();
786
//
787
//                    offGroundTicks = 0;
788
//                    mc.thePlayer.onGround = true;
789
//                    mc.thePlayer.fallDistance = 0;
790
//                    event.setGround(true);
791
//                }
792
//
793
//                MoveUtil.strafe();
794
                break;
795
            }
796
797
            case "Hypixel Blink":
798
                if (pearlTimer.hasReached(3500L) && pearlSlot != -1) {
799
                    mc.thePlayer.motionY = mc.gameSettings.keyBindJump.isKeyDown() ? flySpeed.getValue() : mc.gameSettings.keyBindSneak.isKeyDown() ? -flySpeed.getValue() : 0;
800
801
                    if (mc.thePlayer.posY % (1.0F / 64.0F) < 0.005)
802
                        event.setGround(true);
803
804
                    if (MoveUtil.isMoving())
805
                        MoveUtil.strafe(flySpeed.getValue());
806
                    else
807
                        MoveUtil.stop();
808
                } else if (stage == 2 && mode.is("Hypixel") && PlayerUtil.isOnServer("Hypixel")) {
809
                }
810
811
                if (pearlFly) {
812
                    event.setPitch(RandomUtils.nextFloat(89, 90));
813
                    PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C06PacketPlayerPosLook(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, mc.thePlayer.rotationYaw, RandomUtils.nextFloat(89, 90), mc.thePlayer.onGround));
814
                    PacketUtil.sendPacket(new C09PacketHeldItemChange(pearlSlot));
815
                    PacketUtil.sendPacket(new C08PacketPlayerBlockPlacement(mc.thePlayer.inventory.getStackInSlot(pearlSlot)));
816
                    PacketUtil.sendPacket(new C09PacketHeldItemChange(mc.thePlayer.inventory.currentItem));
817
                    pearlFly = false;
818
                }
819
                break;
820
821
            case "Vicnix":
822
                final double speed = 0.6;
823
824
                if (MoveUtil.isMoving()) {
825
                    MoveUtil.strafe(speed);
826
                    moveSpeed += speed;
827
                } else {
828
                    MoveUtil.stop();
829
                }
830
831
                if (mc.gameSettings.keyBindJump.isKeyDown()) {
832
                    mc.thePlayer.motionY = speed;
833
                    moveSpeed += speed;
834
                } else if (mc.gameSettings.keyBindSneak.isKeyDown()) {
835
                    mc.thePlayer.motionY = -speed;
836
                    moveSpeed += speed;
837
                } else {
838
                    mc.thePlayer.motionY = 0 - Math.random() / 100;
839
                }
840
841
                moveSpeed += mc.thePlayer.getDistance(mc.thePlayer.lastTickPosX, mc.thePlayer.lastTickPosY, mc.thePlayer.lastTickPosZ);
842
                break;
843
844
            case "Damage": {
845
                mc.timer.timerSpeed = 1;
846
                if (ticks == 1) {
847
                    mc.timer.timerSpeed = 0.25f;
848
                    mc.thePlayer.sendQueue.addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY + 3.42f, mc.thePlayer.posZ, false));
849
                    mc.thePlayer.sendQueue.addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, false));
850
                    mc.thePlayer.sendQueue.addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
851
                    mc.thePlayer.jump();
852
                } else {
853
                    if (mc.thePlayer.moveForward != 0.0 || mc.thePlayer.moveStrafing != 0.0) {
854
                        MoveUtil.strafe(flySpeed.getValue());
855
                    } else {
856
                        MoveUtil.stop();
857
                    }
858
859
                    if (mc.gameSettings.keyBindJump.isKeyDown()) {
860
                        mc.thePlayer.motionY = flySpeed.getValue();
861
                    } else if (mc.gameSettings.keyBindSneak.isKeyDown()) {
862
                        mc.thePlayer.motionY = -flySpeed.getValue();
863
                    } else {
864
                        mc.thePlayer.motionY = 0.0;
865
                    }
866
                }
867
868
                break;
869
            }
870
            case "Creative": {
871
                mc.thePlayer.capabilities.isFlying = true;
872
                mc.thePlayer.capabilities.flySpeed = (float) (flySpeed.getValue() / 16);
873
                break;
874
            }
875
876
            case "Minemenclub 2": {
877
                ItemStack itemStack;
878
879
                ticks--;
880
881
                if (!jumped) {
882
                    event.setPitch(-RandomUtils.nextFloat(89, 90));
883
                    bool = false;
884
                }
885
886
                int sexySlot = -1;
887
                int shitSlot = -1;
888
889
                //Jumped is just saying the the bow or rod has been shot
890
                if (!jumped) {
891
                    MoveUtil.stop();
892
893
                    for (i = 0; i < 9; ++i) {
894
                        itemStack = mc.thePlayer.inventoryContainer.getSlot(i + 36).getStack();
895
896
                        if (itemStack != null) {
897
                            final Item item = itemStack.getItem();
898
899
                            if (itemStack.getItem() instanceof ItemBow) {
900
                                for (int i = 0; i < mc.thePlayer.inventory.mainInventory.length; i++) {
901
                                    final ItemStack stack = mc.thePlayer.inventory.mainInventory[i];
902
903
                                    if (stack != null) {
904
                                        if (stack.getItem().getUnlocalizedName().contains("arrow")) {
905
                                            sexySlot = this.i;
906
                                        }
907
                                    }
908
                                }
909
                            }
910
911
                            if (item instanceof ItemFishingRod || item instanceof ItemSnowball || item instanceof ItemEgg) {
912
                                flag = true;
913
                                shitSlot = i;
914
                            }
915
                        }
916
                    }
917
918
                    if (sexySlot != -1) {
919
                        itemStack = mc.thePlayer.inventoryContainer.getSlot(sexySlot + 36).getStack();
920
921
                        if (mc.thePlayer.inventory.currentItem != sexySlot && ticks == 1)
922
                            PacketUtil.sendPacketWithoutEvent(new C09PacketHeldItemChange(sexySlot));
923
924
                        if (ticks == 5 + randomInt(0, 1))
925
                            mc.thePlayer.sendQueue.addToSendQueue(new C08PacketPlayerBlockPlacement(itemStack));
926
927
                        ticks++;
928
929
                        if (ticks == 9 + randomInt(1, 2)) {
930
                            PacketUtil.sendPacketWithoutEvent(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));
931
                            jumped = true;
932
                        }
933
                    } else if (shitSlot != -1) {
934
                        itemStack = mc.thePlayer.inventoryContainer.getSlot(shitSlot + 36).getStack();
935
936
                        if (mc.thePlayer.inventory.currentItem != shitSlot)
937
                            PacketUtil.sendPacketWithoutEvent(new C09PacketHeldItemChange(shitSlot));
938
939
                        mc.thePlayer.sendQueue.addToSendQueue(new C08PacketPlayerBlockPlacement(itemStack));
940
941
                        jumped = true;
942
                    }
943
                }
944
945
                if (mc.thePlayer.hurtTime == 9) {
946
                    mc.thePlayer.setPosition(mc.thePlayer.posX, mc.thePlayer.posY + 0.42F, mc.thePlayer.posZ);
947
                    mc.thePlayer.motionY = 1;
948
                    bool = true;
949
                }
950
951
                // actual fly
952
                if (bool) {
953
//                    mc.thePlayer.motionY *= 0.9;
954
                    mc.thePlayer.motionY = 0;
955
                    MoveUtil.strafe(flySpeed.getValue() * Math.max(0.1, (400 - offGroundTicks) / 400d));
956
957
                    if (!MoveUtil.isMoving()) {
958
                        MoveUtil.stop();
959
                        toggleModule();
960
                    }
961
                } else {
962
                    MoveUtil.stop();
963
//                    Rise.addChatMessage("??");
964
                }
965
966
                break;
967
            }
968
969
            case "Bow Longjump": {
970
                ItemStack itemStack;
971
972
                ticks--;
973
974
                if (!jumped) {
975
                    event.setPitch(-RandomUtils.nextFloat(89, 90));
976
                }
977
978
                if (mc.thePlayer.posY % 1 == 0 && mc.thePlayer.posY < mc.thePlayer.lastTickPosY) {
979
                    MoveUtil.stop();
980
                    this.toggleModule();
981
                    mc.timer.timerSpeed = 1;
982
                    return;
983
                }
984
985
                int sexySlot = -1;
986
                int shitSlot = -1;
987
988
                //Jumped is just saying the the bow or rod has been shot
989
                if (!jumped) {
990
                    for (i = 0; i < 9; ++i) {
991
                        itemStack = mc.thePlayer.inventoryContainer.getSlot(i + 36).getStack();
992
993
                        if (itemStack != null) {
994
                            final Item item = itemStack.getItem();
995
996
                            if (itemStack.getItem() instanceof ItemBow) {
997
                                for (int i = 0; i < mc.thePlayer.inventory.mainInventory.length; i++) {
998
                                    final ItemStack stack = mc.thePlayer.inventory.mainInventory[i];
999
1000
                                    if (stack != null) {
1001
                                        if (stack.getItem().getUnlocalizedName().contains("arrow")) {
1002
                                            sexySlot = this.i;
1003
                                        }
1004
                                    }
1005
                                }
1006
                            }
1007
1008
                            if (item instanceof ItemFishingRod || item instanceof ItemSnowball || item instanceof ItemEgg) {
1009
                                flag = true;
1010
                                shitSlot = i;
1011
                            }
1012
                        }
1013
                    }
1014
1015
                    if (sexySlot != -1) {
1016
                        itemStack = mc.thePlayer.inventoryContainer.getSlot(sexySlot + 36).getStack();
1017
1018
                        if (mc.thePlayer.inventory.currentItem != sexySlot && ticks == 1)
1019
                            PacketUtil.sendPacketWithoutEvent(new C09PacketHeldItemChange(sexySlot));
1020
1021
                        if (ticks == 5 + randomInt(0, 1))
1022
                            mc.thePlayer.sendQueue.addToSendQueue(new C08PacketPlayerBlockPlacement(itemStack));
1023
1024
                        ticks++;
1025
1026
                        if (ticks == 9 + randomInt(1, 2)) {
1027
                            PacketUtil.sendPacketWithoutEvent(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));
1028
                            jumped = true;
1029
                        }
1030
                    } else if (shitSlot != -1) {
1031
                        itemStack = mc.thePlayer.inventoryContainer.getSlot(shitSlot + 36).getStack();
1032
1033
                        if (mc.thePlayer.inventory.currentItem != shitSlot)
1034
                            PacketUtil.sendPacketWithoutEvent(new C09PacketHeldItemChange(shitSlot));
1035
1036
                        mc.thePlayer.sendQueue.addToSendQueue(new C08PacketPlayerBlockPlacement(itemStack));
1037
1038
                        jumped = true;
1039
                    }
1040
                }
1041
1042
                //Bow longjump
1043
1044
                if (!jumped)
1045
                    mc.timer.timerSpeed = (float) timer.getValue();
1046
1047
                if (mc.thePlayer.hurtTime == 9) {
1048
1049
                    if (mc.thePlayer.inventory.currentItem != i)
1050
                        PacketUtil.sendPacketWithoutEvent(new C09PacketHeldItemChange(mc.thePlayer.inventory.currentItem));
1051
1052
                    hypixelStart = true;
1053
                    mc.thePlayer.jump();
1054
1055
                    if (bowFlyVBoost1.getValue() != 0)
1056
                        mc.thePlayer.motionY = bowFlyVBoost1.getValue();
1057
1058
                    if (bowFlyHBoost1.getValue() != 0)
1059
                        MoveUtil.strafe(bowFlyHBoost1.getValue());
1060
1061
                }
1062
1063
                if (mc.thePlayer.hurtTime == 8) {
1064
                    if (bowFlyVBoost2.getValue() != 0)
1065
                        mc.thePlayer.motionY = bowFlyVBoost2.getValue();
1066
1067
                    if (bowFlyHBoost2.getValue() != 0)
1068
                        MoveUtil.strafe(bowFlyHBoost2.getValue());
1069
                }
1070
1071
                if (offGroundTicks <= 5 && !mc.thePlayer.onGround) {
1072
                    mc.thePlayer.motionY += glide.getValue();
1073
                }
1074
1075
                if (offGroundTicks <= 5 && !mc.thePlayer.onGround) {
1076
                    MoveUtil.strafe(MoveUtil.getSpeed() * (1 + (multiplierInAir.getValue() - 1) / 5));
1077
                }
1078
1079
                if (strafe.isEnabled())
1080
                    MoveUtil.strafe();
1081
1082
                //NCP Longjump part, only have this part uncommented for it to work
1083
                /*
1084
                if (mc.thePlayer.hurtTime == 9) {
1085
                    hypixelStart = true;
1086
                }
1087
1088
                if (hypixelStart) {
1089
1090
                    if (mc.thePlayer.hurtTime == 8) {
1091
                        mc.thePlayer.motionY = 0.45f;
1092
                        MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 2.59);
1093
                    }
1094
1095
                    if (mc.thePlayer.hurtTime == 7) {
1096
                        mc.thePlayer.motionY += 0.03;
1097
                    }
1098
1099
                    if (mc.thePlayer.hurtTime <= 6) {
1100
                        mc.thePlayer.motionY += 0.015;
1101
                    }
1102
1103
                }
1104
1105
                MoveUtil.strafe();
1106
                 */
1107
1108
                break;
1109
            }
1110
1111
            case "Bow Fly": {
1112
                ItemStack itemStack;
1113
1114
                ticks--;
1115
1116
                if (!jumped) {
1117
                    event.setPitch(-90.0F);
1118
                }
1119
1120
                int sexySlot = -1;
1121
                int shitSlot = -1;
1122
1123
                //Jumped is just saying the the bow or rod has been shot
1124
                if (!jumped) {
1125
                    for (i = 0; i < 9; ++i) {
1126
                        itemStack = mc.thePlayer.inventoryContainer.getSlot(i + 36).getStack();
1127
1128
                        if (itemStack != null) {
1129
                            final Item item = itemStack.getItem();
1130
1131
                            if (itemStack.getItem() instanceof ItemBow) {
1132
                                for (int i = 0; i < mc.thePlayer.inventory.mainInventory.length; i++) {
1133
                                    final ItemStack stack = mc.thePlayer.inventory.mainInventory[i];
1134
1135
                                    if (stack != null) {
1136
                                        if (stack.getItem().getUnlocalizedName().contains("arrow")) {
1137
                                            sexySlot = this.i;
1138
                                        }
1139
                                    }
1140
                                }
1141
                            }
1142
1143
                            if (item instanceof ItemFishingRod || item instanceof ItemSnowball || item instanceof ItemEgg) {
1144
                                flag = true;
1145
                                shitSlot = i;
1146
                            }
1147
                        }
1148
                    }
1149
1150
                    if (offGroundTicks <= 3 && !mc.thePlayer.onGround) {
1151
                        mc.thePlayer.motionY += glide.getValue();
1152
                        MoveUtil.strafe(MoveUtil.getSpeed() * multiplierInAir.getValue());
1153
                    }
1154
1155
                    if (sexySlot != -1) {
1156
                        itemStack = mc.thePlayer.inventoryContainer.getSlot(sexySlot + 36).getStack();
1157
1158
                        if (mc.thePlayer.inventory.currentItem != sexySlot && ticks == 1)
1159
                            PacketUtil.sendPacketWithoutEvent(new C09PacketHeldItemChange(sexySlot));
1160
1161
                        if (ticks == 5 + randomInt(0, 1))
1162
                            mc.thePlayer.sendQueue.addToSendQueue(new C08PacketPlayerBlockPlacement(itemStack));
1163
1164
                        ticks++;
1165
1166
                        if (ticks == 9 + randomInt(0, 1)) {
1167
                            PacketUtil.sendPacketWithoutEvent(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));
1168
                            jumped = true;
1169
                        }
1170
                    } else if (shitSlot != -1) {
1171
                        itemStack = mc.thePlayer.inventoryContainer.getSlot(shitSlot + 36).getStack();
1172
1173
                        if (mc.thePlayer.inventory.currentItem != shitSlot)
1174
                            PacketUtil.sendPacketWithoutEvent(new C09PacketHeldItemChange(shitSlot));
1175
1176
                        mc.thePlayer.sendQueue.addToSendQueue(new C03PacketPlayer.C06PacketPlayerPosLook(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, mc.thePlayer.rotationYaw, -90, mc.thePlayer.onGround));
1177
                        mc.thePlayer.sendQueue.addToSendQueue(new C08PacketPlayerBlockPlacement(itemStack));
1178
1179
                        jumped = true;
1180
                    }
1181
                }
1182
1183
                if (dmged) {
1184
                    MoveUtil.strafe();
1185
1186
                    if (mc.thePlayer.hurtTime == 9) {
1187
                        MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 2.13);
1188
                    } else {
1189
                        MoveUtil.strafe(MoveUtil.getBaseMoveSpeed());
1190
                    }
1191
1192
                    mc.thePlayer.motionY = 0;
1193
                }
1194
                break;
1195
            }
1196
1197
            case "ACR": {
1198
                mc.timer.timerSpeed = 1.0F;
1199
1200
                if (mc.thePlayer.fallDistance > 4.5) {
1201
                    event.setGround(true);
1202
1203
                    mc.thePlayer.motionY = 0.42f;
1204
                    ticks = -5;
1205
                    MoveUtil.stop();
1206
1207
                    mc.timer.timerSpeed = 0.15f;
1208
                    mc.thePlayer.fallDistance = 0;
1209
                }
1210
1211
                if (ticks == -4) {
1212
                    mc.thePlayer.motionY = 0.99;
1213
                }
1214
1215
                break;
1216
            }
1217
            case "ACR2": {
1218
                MoveUtil.strafe(0.06);
1219
                if (mc.thePlayer.ticksExisted % 3 == 0) {
1220
                    mc.thePlayer.motionY = 0.40444491418477213;
1221
                    offGroundTicks = 0;
1222
                }
1223
1224
                if (offGroundTicks == 1) {
1225
                    MoveUtil.strafe(0.36);
1226
                    mc.thePlayer.motionY = 0.33319999363422365;
1227
                }
1228
1229
                break;
1230
            }
1231
1232
            case "Hypixel Infinite":
1233
                if (pearlTimer.hasReached(3500L) && pearlSlot != -1) {
1234
                    mc.thePlayer.motionY = mc.gameSettings.keyBindJump.isKeyDown() ? flySpeed.getValue() : mc.gameSettings.keyBindSneak.isKeyDown() ? -flySpeed.getValue() : 0;
1235
1236
                    if (mc.thePlayer.posY % (1.0F / 64.0F) < 0.005)
1237
                        event.setGround(true);
1238
1239
                    if (MoveUtil.isMoving())
1240
                        MoveUtil.strafe(flySpeed.getValue());
1241
                    else
1242
                        MoveUtil.stop();
1243
                } else if (stage == 2 && mode.is("Hypixel") && PlayerUtil.isOnServer("Hypixel")) {
1244
                    mc.thePlayer.setPosition(mc.thePlayer.posX, mc.thePlayer.posY + RandomUtils.nextDouble(7E-8, 9E-8), mc.thePlayer.posZ);
1245
                }
1246
1247
                if (pearlFly) {
1248
                    event.setPitch(RandomUtils.nextFloat(89, 90));
1249
                    PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C06PacketPlayerPosLook(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, mc.thePlayer.rotationYaw, RandomUtils.nextFloat(89, 90), mc.thePlayer.onGround));
1250
                    PacketUtil.sendPacket(new C09PacketHeldItemChange(pearlSlot));
1251
                    PacketUtil.sendPacket(new C08PacketPlayerBlockPlacement(mc.thePlayer.inventory.getStackInSlot(pearlSlot)));
1252
                    PacketUtil.sendPacket(new C09PacketHeldItemChange(mc.thePlayer.inventory.currentItem));
1253
                    pearlFly = false;
1254
                }
1255
1256
                if (pearlSlot != -1)
1257
                    return;
1258
1259
                if (!mc.thePlayer.onGround) {
1260
                    if (PlayerUtil.isOnServer("Hypixel")) {
1261
                        event.setY(event.getY() - 1.89 + Math.random() / 500);
1262
                        event.setGround(true);
1263
                    } else {
1264
                        PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C04PacketPlayerPosition(-1, -1, -1, true));
1265
                        PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C04PacketPlayerPosition());
1266
                        PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
1267
                    }
1268
                }
1269
                mc.timer.timerSpeed = (float) (0.3 - Math.random() / 500);
1270
                break;
1271
1272
            case "Verus AirJump": {
1273
                MoveUtil.strafe();
1274
                if (!mc.gameSettings.keyBindSneak.isKeyDown()) {
1275
                    if (mc.gameSettings.keyBindJump.isKeyDown()) {
1276
                        if (mc.thePlayer.ticksExisted % 2 == 0)
1277
                            mc.thePlayer.motionY = 0.42F;
1278
                    } else {
1279
                        if (mc.thePlayer.onGround) {
1280
                            mc.thePlayer.jump();
1281
                        }
1282
1283
                        if (mc.thePlayer.fallDistance > 1) {
1284
                            mc.thePlayer.motionY = -((mc.thePlayer.posY) - Math.floor(mc.thePlayer.posY));
1285
                        }
1286
1287
                        if (mc.thePlayer.motionY == 0) {
1288
                            mc.thePlayer.jump();
1289
1290
                            mc.thePlayer.onGround = true;
1291
                            mc.thePlayer.fallDistance = 0;
1292
                            event.setGround(true);
1293
                        }
1294
                    }
1295
                }
1296
                break;
1297
            }
1298
1299
            case "Air Walk": {
1300
                // SPRINT BYPASSE
1301
                if(sprint.isEnabled()) {
1302
                    mc.thePlayer.setSprinting(true);
1303
                } else {
1304
                    mc.thePlayer.setSprinting(false);
1305
                }
1306
                if (!mc.gameSettings.keyBindSneak.isKeyDown()) {
1307
                    mc.thePlayer.motionY = -(mc.thePlayer.posY - roundToOnGround(mc.thePlayer.posY));
1308
                    if (MoveUtil.isMoving()) {
1309
                        MoveUtil.strafe(0.255);
1310
                    } else {
1311
                        MoveUtil.stop();
1312
                    }
1313
                }
1314
                break;
1315
            }
1316
            case "Collide": {
1317
                if (!mc.gameSettings.keyBindSneak.isKeyDown()) {
1318
                    if (MoveUtil.isMoving()) {
1319
                        MoveUtil.strafe(flySpeed.getValue());
1320
                    } else {
1321
                        MoveUtil.stop();
1322
                    }
1323
1324
                    if (mc.gameSettings.keyBindJump.isKeyDown()) {
1325
                        mc.thePlayer.motionY = -(mc.thePlayer.posY - roundToOnGround(mc.thePlayer.posY + 0.5));
1326
                    } else {
1327
                        mc.thePlayer.motionY = -(mc.thePlayer.posY - roundToOnGround(mc.thePlayer.posY));
1328
                    }
1329
1330
                    if (mc.thePlayer.posY % (1.0F / 64.0F) < 0.005) {
1331
                        event.setGround(true);
1332
                    }
1333
                }
1334
1335
                break;
1336
            }
1337
1338
            case "Viper": {
1339
                if (!mc.gameSettings.keyBindSneak.isKeyDown()) {
1340
                    if (mc.gameSettings.keyBindJump.isKeyDown())
1341
                        mc.thePlayer.motionY = -(mc.thePlayer.posY - roundToOnGround(mc.thePlayer.posY + 0.5));
1342
                    else
1343
                        mc.thePlayer.motionY = -(mc.thePlayer.posY - roundToOnGround(mc.thePlayer.posY));
1344
1345
                    if (mc.thePlayer.posY % (1.0F / 64.0F) < 0.005)
1346
                        event.setGround(true);
1347
                } else
1348
                    MoveUtil.strafe();
1349
1350
                if (MoveUtil.isMoving())
1351
                    MoveUtil.sendMotion(flySpeed.getValue(), 0.2873);
1352
                else
1353
                    MoveUtil.stop();
1354
                break;
1355
            }
1356
1357
            case "Spartan": {
1358
                if (mc.thePlayer.onGround) {
1359
                    mc.thePlayer.jump();
1360
                }
1361
1362
                if (mc.thePlayer.fallDistance > 1) {
1363
                    mc.thePlayer.motionY = -((mc.thePlayer.posY) - Math.floor(mc.thePlayer.posY));
1364
                }
1365
1366
                if (mc.thePlayer.motionY == 0) {
1367
                    mc.thePlayer.jump();
1368
1369
                    mc.thePlayer.onGround = true;
1370
                    event.setGround(true);
1371
                    mc.thePlayer.fallDistance = 0;
1372
                }
1373
                break;
1374
            }
1375
            case "Aac3": {
1376
                mc.timer.timerSpeed = 1f;
1377
                if (mc.thePlayer.posY < -75) {
1378
                    mc.thePlayer.motionY = 6.9;
1379
                }
1380
                mc.thePlayer.motionY -= 0.0001;
1381
                break;
1382
            }
1383
1384
            case "MCCentral": {
1385
                if (mc.thePlayer.posY < oPositionY + 0.6 && !mc.gameSettings.keyBindSneak.isKeyDown() || mc.gameSettings.keyBindJump.isKeyDown() && !mc.gameSettings.keyBindSneak.isKeyDown()) {
1386
                    mc.thePlayer.motionY += 0.12;
1387
1388
                    if (MoveUtil.isMoving()) {
1389
                        mc.thePlayer.motionX *= 1.1;
1390
                        mc.thePlayer.motionZ *= 1.1;
1391
                    }
1392
1393
                    if (mc.gameSettings.keyBindJump.isKeyDown() || mc.gameSettings.keyBindSneak.isKeyDown()) {
1394
                        oPositionY = (float) mc.thePlayer.posY;
1395
                    }
1396
                }
1397
                if (ticks == 1) {
1398
                    mc.thePlayer.motionX *= 1.4;
1399
                    mc.thePlayer.motionZ *= 1.4;
1400
                }
1401
1402
                break;
1403
            }
1404
1405
            case "Exempted Value": {
1406
                if (mc.thePlayer.onGround) {
1407
                    mc.thePlayer.jump();
1408
                } else {
1409
                    if (mc.thePlayer.fallDistance > 0) {
1410
1411
                        double v = 0;
1412
                        switch (exemptedValueType.getMode()) {
1413
                            case "1":
1414
                                v = -0.0784000015258789;
1415
                                break;
1416
                            case "2":
1417
                                v = -0.09800000190734864;
1418
                                break;
1419
                            case "3":
1420
                                v = -0.09800000190735147;
1421
                                break;
1422
                        }
1423
1424
                        if (mc.thePlayer.motionY < v) {
1425
                            mc.thePlayer.motionY = v;
1426
                            if (groundSpoof.isEnabled())
1427
                                event.setGround(true);
1428
                        }
1429
                    }
1430
                }
1431
1432
                MoveUtil.strafe();
1433
                break;
1434
            }
1435
            case "Kauri": {
1436
                mc.timer.timerSpeed = 1.0F;
1437
1438
                if (!mc.gameSettings.keyBindSneak.isKeyDown()) {
1439
                    ticks = 0;
1440
1441
                    if (MoveUtil.isMoving()) {
1442
                        MoveUtil.strafe(mc.thePlayer.ticksExisted % 5 != 0 ? 0.25 : 0.625);
1443
                    } else {
1444
                        MoveUtil.stop();
1445
                    }
1446
1447
                    if (mc.gameSettings.keyBindJump.isKeyDown()) {
1448
                        mc.thePlayer.motionY = 0.42F;
1449
                    } else {
1450
                        mc.thePlayer.motionY = -(mc.thePlayer.posY - roundToOnGround(mc.thePlayer.posY));
1451
                    }
1452
1453
                    event.setGround(true);
1454
                } else {
1455
                    if (ticks == 1) {
1456
                        event.setGround(true);
1457
                    }
1458
                }
1459
            }
1460
1461
            case "Taka": {
1462
                if (stage > 2) mc.thePlayer.motionY = -0.005;
1463
                mc.timer.timerSpeed = 1.0f;
1464
1465
                if (stage > 2) {
1466
                    ticks++;
1467
1468
                    if (ticks <= 2) {
1469
                        mc.thePlayer.setPosition(mc.thePlayer.posX, mc.thePlayer.posY + 2.02069E-14, mc.thePlayer.posZ);
1470
                    } else if (ticks == 4) {
1471
                        mc.thePlayer.setPosition(mc.thePlayer.posX, mc.thePlayer.posY + 1.62029E-6, mc.thePlayer.posZ);
1472
                    } else if (ticks >= 5) {
1473
                        mc.thePlayer.setPosition(mc.thePlayer.posX, mc.thePlayer.posY - 2.12039E-44, mc.thePlayer.posZ);
1474
                        ticks = 0;
1475
                    }
1476
1477
                }
1478
1479
                break;
1480
            }
1481
1482
            case "New": {
1483
                mc.thePlayer.motionY = 0;
1484
                break;
1485
            }
1486
1487
            case "VerusBlack": {
1488
                if (mc.gameSettings.keyBindJump.isKeyDown()) {
1489
                    if (mc.thePlayer.ticksExisted % 2 == 0) {
1490
                        mc.thePlayer.motionY = 0.42F;
1491
                        MoveUtil.strafe(0.3);
1492
                    }
1493
                }
1494
                break;
1495
            }
1496
1497
            case "Wait for Damage": {
1498
                if (mc.thePlayer.hurtTime > 0) {
1499
                    if (mc.thePlayer.moveForward != 0.0 || mc.thePlayer.moveStrafing != 0.0) {
1500
                        MoveUtil.strafe(flySpeed.getValue());
1501
                    } else {
1502
                        MoveUtil.stop();
1503
                    }
1504
1505
                    if (mc.gameSettings.keyBindJump.isKeyDown()) {
1506
                        mc.thePlayer.motionY = flySpeed.getValue();
1507
                    } else if (mc.gameSettings.keyBindSneak.isKeyDown()) {
1508
                        mc.thePlayer.motionY = -flySpeed.getValue();
1509
                    } else {
1510
                        mc.thePlayer.motionY = 0.0;
1511
                    }
1512
                }
1513
1514
                break;
1515
            }
1516
            case "Old NCP": {
1517
                if (mc.thePlayer.isCollidedHorizontally || !MoveUtil.isMoving() || (stage >= 15 && !jumped && !damage.isEnabled())) {
1518
                    moveSpeed = MoveUtil.getBaseMoveSpeed();
1519
                    mc.timer.timerSpeed = 1;
1520
                }
1521
1522
                if (mc.thePlayer.hurtTime > 0)
1523
                    jumped = true;
1524
1525
1526
                if (stage > 2) {
1527
                    hypixelTicks++;
1528
1529
                    double value = RandomUtils.nextDouble(10E-8, 12E-8);
1530
1531
                    if (mc.thePlayer.ticksExisted % 2 == 0)
1532
                        value = -value;
1533
1534
                    if (!mc.thePlayer.onGround)
1535
                        mc.thePlayer.setPosition(mc.thePlayer.posX, mc.thePlayer.posY + value, mc.thePlayer.posZ);
1536
1537
                    mc.thePlayer.motionY = 0;
1538
                }
1539
                break;
1540
            }
1541
            case "Mush": {
1542
                if (stage > 2) {
1543
                    hypixelTicks++;
1544
                    mc.thePlayer.motionY = mc.gameSettings.keyBindJump.isKeyDown() ? moveSpeed : mc.gameSettings.keyBindSneak.isKeyDown() ? -moveSpeed : 0;
1545
                }
1546
                break;
1547
            }
1548
            case "BlockFly": {
1549
                final BlockPos down = new BlockPos(mc.thePlayer.posX, mc.thePlayer.posY - 1, mc.thePlayer.posZ);
1550
                if (mc.theWorld.getBlockState(down).getBlock() instanceof BlockAir && (mc.thePlayer.inventory.getCurrentItem() != null && mc.thePlayer.inventory.getCurrentItem().getItem() instanceof ItemBlock) && mc.playerController.onPlayerRightClick(mc.thePlayer, mc.theWorld, mc.thePlayer.getHeldItem(), down, EnumFacing.UP, new Vec3(0.5, 0.5, 0.5)))
1551
                    mc.thePlayer.swingItem();
1552
                break;
1553
            }
1554
        }
1555
1556
    }
1557
1558
    @Override
1559
    public void onPostMotion(PostMotionEvent event) {
1560
1561
        if (mode.is("Block Drop")) {
1562
            for (int i = 0; i < 1; ++i) {
1563
                PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C06PacketPlayerPosLook(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, rotation.getX(), rotation.getY(), false));
1564
            }
1565
        }
1566
    }
1567
1568
    @Override
1569
    public void onMove(final MoveEvent event) {
1570
        switch (mode.getMode()) {
1571
//            case "Custom": {
1572
//
1573
//                MoveUtil.strafe(customSpeedH.getValue());
1574
//                if (!customLockY.isEnabled()) {
1575
//                    mc.thePlayer.motionY = (mc.gameSettings.keyBindJump.isKeyDown() ? customSpeedV.getValue() : mc.gameSettings.keyBindSneak.isKeyDown() ? -customSpeedV.getValue() : 0) - customFall.getValue();
1576
//                } else {
1577
//                    mc.thePlayer.motionY = -customFall.getValue();
1578
//                }
1579
//
1580
//                break;
1581
//            }
1582
1583
            case "Hypixel": {
1584
                MoveUtil.strafe();
1585
                if (!hypixelStart || !MoveUtil.isMoving()) {
1586
                    MoveUtil.setMoveEventSpeed(event, .00);
1587
                }
1588
1589
                break;
1590
            }
1591
1592
            case "Old NCP":
1593
                switch (stage) {
1594
                    case 1:
1595
                        if (mc.thePlayer.onGround)
1596
                            event.setY(mc.thePlayer.motionY = MoveUtil.getJumpMotion(0.42F));
1597
1598
                        if (damage.isEnabled())
1599
                            DamageUtil.damagePlayer(DamageUtil.DamageType.POSITION, 0.0625, true, true);
1600
1601
                        moveSpeed = 0.398 - Math.random() / 500;
1602
                        break;
1603
1604
                    case 3:
1605
                        moveSpeed = flySpeed.getValue() + Math.random() / 100;
1606
                        mc.timer.timerSpeed = (float) timer.getValue();
1607
                        break;
1608
1609
                    default:
1610
                        moveSpeed -= moveSpeed / RandomUtils.nextDouble(159, 159.1);
1611
                        mc.timer.timerSpeed = (float) Math.max(1, mc.timer.timerSpeed - (Math.random() / 50));
1612
                        break;
1613
                }
1614
1615
                MoveUtil.setMoveEventSpeed(event, Math.max(moveSpeed, MoveUtil.getBaseMoveSpeed()));
1616
                stage++;
1617
                break;
1618
1619
            case "Hypixel Infinite":
1620
                if (pearlSlot == -1) {
1621
                    event.setY(mc.thePlayer.motionY = 0);
1622
                    MoveUtil.setMoveEventSpeed(event, mc.thePlayer.onGround ? MoveUtil.getBaseMoveSpeed() : 3.9);
1623
                }
1624
1625
                if (pearlSlot != -1 && !pearlTimer.hasReached(3500L))
1626
                    event.setCancelled(true);
1627
                break;
1628
1629
            case "VerusBlack": {
1630
                if (mc.thePlayer.onGround && ticks % 14 == 0) {
1631
                    event.setY(0.42F);
1632
                    MoveUtil.strafe(0.69);
1633
                    mc.thePlayer.motionY = -(mc.thePlayer.posY - roundToOnGround(mc.thePlayer.posY));
1634
                } else {
1635
                    if (mc.thePlayer.onGround) {
1636
                        MoveUtil.strafe(1.01);
1637
                    } else MoveUtil.strafe(0.41);
1638
                }
1639
                ticks++;
1640
1641
                break;
1642
            }
1643
1644
            case "Hypixel Blink":
1645
                if (pearlSlot == -1) {
1646
                    switch (stage) {
1647
                        case 0:
1648
                            stage++;
1649
                            break;
1650
1651
                        case 1:
1652
                            event.setY(mc.thePlayer.motionY = MoveUtil.getJumpMotion((float) (0.2 + Math.random() / 100)));
1653
                            mc.timer.timerSpeed = (float) (timer.getValue() - Math.random() / 100);
1654
                            moveSpeed = MoveUtil.getBaseMoveSpeed() + (0.2 + Math.random() / 500);
1655
                            stage++;
1656
                            break;
1657
1658
                        case 2:
1659
                            if (MoveUtil.isMoving() && !mc.thePlayer.isCollidedHorizontally) {
1660
                                moveSpeed = moveSpeed - (MoveUtil.getBaseMoveSpeed() / RandomUtils.nextDouble(49, 49.1));
1661
                                mc.timer.timerSpeed = (float) Math.max(1, mc.timer.timerSpeed - (Math.random() / 100));
1662
                            } else {
1663
                                mc.timer.timerSpeed = 1;
1664
                                moveSpeed = 0;
1665
                            }
1666
1667
                            event.setY(mc.thePlayer.motionY = (0.001 + Math.random() / 5000));
1668
                            MoveUtil.setMoveEventSpeed(event, Math.max(MoveUtil.getBaseMoveSpeed(), moveSpeed));
1669
                            break;
1670
                    }
1671
                }
1672
1673
                if (pearlSlot != -1 && !pearlTimer.hasReached(3500L))
1674
                    event.setCancelled(true);
1675
                break;
1676
1677
            case "Mush":
1678
                switch (stage) {
1679
                    case 1:
1680
                        if (mc.thePlayer.onGround)
1681
                            event.setY(mc.thePlayer.motionY = MoveUtil.getJumpMotion(0.42F));
1682
                        moveSpeed = MoveUtil.getBaseMoveSpeed();
1683
                        break;
1684
1685
                    case 3:
1686
                        moveSpeed = flySpeed.getValue() + Math.random() / 100;
1687
                        break;
1688
1689
                    default:
1690
                        moveSpeed -= RandomUtils.nextDouble(10E-8, 12E-8);
1691
                        break;
1692
                }
1693
1694
                MoveUtil.setMoveEventSpeed(event, Math.max(moveSpeed, MoveUtil.getBaseMoveSpeed()));
1695
                stage++;
1696
                break;
1697
1698
            case "Bow Fly":
1699
                if (!dmged)
1700
                    event.setCancelled(true);
1701
                break;
1702
1703
            case "Bow Longjump":
1704
                if (!hypixelStart)
1705
                    event.setCancelled(true);
1706
                break;
1707
1708
            case "Taka": {
1709
                final float jump = (0.42f);
1710
1711
                switch (stage) {
1712
                    case 0:
1713
                        if (mc.thePlayer.onGround) {
1714
                            mc.timer.timerSpeed = 0.15F;
1715
                            DamageUtil.damagePlayer(DamageUtil.DamageType.POSITION, 0.42F, true, true);
1716
                        }
1717
                        break;
1718
                    case 1:
1719
                        if (mc.thePlayer.onGround && mc.thePlayer.isCollidedVertically) event.setY(jump);
1720
1721
                        mc.thePlayer.motionY = jump;
1722
                        moveSpeed = 0.2889634 - (Math.random() / 500);
1723
1724
                        break;
1725
                }
1726
1727
                stage++;
1728
1729
                if (stage < 19) {
1730
                    MoveUtil.strafe(flySpeed.getValue());
1731
                } else {
1732
                    MoveUtil.strafe(Math.max(moveSpeed, MoveUtil.getBaseMoveSpeed()));
1733
                }
1734
1735
                if (mc.thePlayer.isCollidedHorizontally || !MoveUtil.isMoving()) {
1736
                    moveSpeed = MoveUtil.getBaseMoveSpeed();
1737
                }
1738
                break;
1739
            }
1740
1741
            case "Minemenclub": {
1742
                if (!jumped)
1743
                    event.setCancelled(true);
1744
                break;
1745
            }
1746
1747
            case "Redesky": {
1748
                double speed = 4.5f;
1749
                mc.timer.timerSpeed = 0.5f;
1750
1751
                if (redeskyMode.is("Fast")) {
1752
                    speed = 8.5;
1753
                    mc.timer.timerSpeed = 2;
1754
                }
1755
1756
                if (!mc.isIntegratedServerRunning()) {
1757
                    mc.thePlayer.sendQueue.addToSendQueue(new C03PacketPlayer.C06PacketPlayerPosLook(mc.thePlayer.posX, mc.thePlayer.posY - 1.0E159, mc.thePlayer.posZ + 10, 0, 0, true));
1758
                    mc.thePlayer.sendQueue.addToSendQueue(new C03PacketPlayer.C06PacketPlayerPosLook(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, 0, 0, true));
1759
                }
1760
1761
                MoveUtil.setMoveEventSpeed(event, speed);
1762
                event.setY(mc.thePlayer.motionY = (mc.thePlayer.movementInput.jump ? speed : mc.thePlayer.movementInput.sneak ? -speed : 0) * 0.5);
1763
1764
                break;
1765
            }
1766
        }
1767
    }
1768
1769
    private boolean aboveVoidPredicted() {
1770
1771
        final float multi = 8;
1772
1773
        for (int i = 0; i <= ((mc.thePlayer.onGround) ? 1.7 : 6); i++) {
1774
1775
            final BlockPos pos1 = new BlockPos(mc.thePlayer.posX + mc.thePlayer.motionX * multi + 0.3, mc.thePlayer.posY - i + mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ + mc.thePlayer.motionZ * multi);
1776
            final BlockPos pos2 = new BlockPos(mc.thePlayer.posX + mc.thePlayer.motionX * multi - 0.3, mc.thePlayer.posY - i + mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ + mc.thePlayer.motionZ * multi);
1777
            final BlockPos pos3 = new BlockPos(mc.thePlayer.posX + mc.thePlayer.motionX * multi, mc.thePlayer.posY - i + mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ + mc.thePlayer.motionZ * multi + 0.3);
1778
            final BlockPos pos4 = new BlockPos(mc.thePlayer.posX + mc.thePlayer.motionX * multi, mc.thePlayer.posY - i + mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ + mc.thePlayer.motionZ * multi - 0.3);
1779
1780
            if (!(mc.theWorld.getBlockState(pos1).getBlock() instanceof BlockAir && mc.theWorld.getBlockState(pos2).getBlock() instanceof BlockAir && mc.theWorld.getBlockState(pos3).getBlock() instanceof BlockAir && mc.theWorld.getBlockState(pos4).getBlock() instanceof BlockAir)) {
1781
                return false;
1782
            }
1783
1784
        }
1785
1786
        return true;
1787
    }
1788
1789
    @Override
1790
    public void onStrafe(final StrafeEvent event) {
1791
        switch (mode.getMode()) {
1792
            case "Hypixel Fast Lag": {
1793
                mc.thePlayer.motionY = mc.gameSettings.keyBindJump.isKeyDown() ? 0.42F : mc.gameSettings.keyBindSneak.isKeyDown() ? mc.thePlayer.motionY : 0;
1794
                event.setFriction((float) (mc.thePlayer.moveForward != 0 && mc.thePlayer.moveStrafing != 0 ? flySpeed.getValue() * 0.91F : flySpeed.getValue()));
1795
1796
                MoveUtil.stop();
1797
                break;
1798
            }
1799
1800
            case "Block Drop":
1801
                final float speed = 2;
1802
1803
                event.setSpeed(speed);
1804
                break;
1805
1806
        }
1807
    }
1808
1809
    @Override
1810
    public void onMoveButton(final MoveButtonEvent event) {
1811
        if (!mode.is("Creative") && !mode.is("Redesky"))
1812
            event.setSneak(false);
1813
1814
        switch (mode.getMode()) {
1815
            case "Vulcan2":
1816
                if (ticksSinceFlag <= 20 && ticksSinceFlag > 0) {
1817
                    event.setBackward(false);
1818
                    event.setForward(false);
1819
                    event.setLeft(false);
1820
                    event.setRight(false);
1821
                    MoveUtil.stop();
1822
                }
1823
                event.setJump(false);
1824
                break;
1825
        }
1826
    }
1827
1828
    @Override
1829
    public void onPacketSend(final PacketSendEvent event) {
1830
        if (mc.isIntegratedServerRunning()) return;
1831
1832
        final Packet<?> p = event.getPacket();
1833
1834
        switch (mode.getMode()) {
1835
            case "Hypixel": {
1836
//                mc.timer.timerSpeed = (float) (0.5f + (Math.sin(offGroundTicks) + 1) / 8f);
1837
                if (p instanceof C03PacketPlayer && setback && fly && stage > 10) {
1838
                    ((C03PacketPlayer) p).setOnGround(true);
1839
                }
1840
1841
                break;
1842
            }
1843
            case "Block Drop":
1844
                if (p instanceof C03PacketPlayer) {
1845
                    event.setCancelled(true);
1846
                } else if (p instanceof C02PacketUseEntity) {
1847
                    PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C06PacketPlayerPosLook(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch, false));
1848
                }
1849
                break;
1850
1851
            case "Hycraft": {
1852
                if (p instanceof C03PacketPlayer) {
1853
                    event.setCancelled(true);
1854
                }
1855
            }
1856
1857
            case "MineBox":
1858
                if (PlayerUtil.generalAntiPacketLog() && PlayerUtil.isOnServer("minebox") && p instanceof C03PacketPlayer) {
1859
                    event.setCancelled(true);
1860
                }
1861
                break;
1862
1863
            case "Vicnix":
1864
                if (moveSpeed < 9.5 - MoveUtil.getSpeed() * 1.1) {
1865
                    event.setCancelled(true);
1866
                } else {
1867
                    moveSpeed = 0;
1868
                }
1869
                break;
1870
1871
            case "Hypixel Blink":
1872
                if (!(p instanceof C01PacketChatMessage) && pearlSlot == -1) {
1873
                    packets.add(p);
1874
                    event.setCancelled(true);
1875
                }
1876
                break;
1877
1878
            case "Spartan":
1879
                if (flag) {
1880
                    event.setCancelled(true);
1881
                    if (!(p instanceof C00PacketKeepAlive) && !(p instanceof C0FPacketConfirmTransaction)) {
1882
                        packets.add(p);
1883
                    }
1884
1885
                    if (!packets.isEmpty() && mc.thePlayer.ticksExisted % 13 + (redeskyMode.is("Fast") ? 20 : 0) == 0) {
1886
                        packets.forEach(PacketUtil::sendPacketWithoutEvent);
1887
                        packets.clear();
1888
                    }
1889
                }
1890
                break;
1891
1892
            case "Minemenclub":
1893
                if (!jumped || mc.thePlayer == null) {
1894
                    packets.clear();
1895
                    return;
1896
                }
1897
1898
                if (!(p instanceof C01PacketChatMessage)) {
1899
                    packets.add(p);
1900
                    event.setCancelled(true);
1901
                }
1902
                break;
1903
1904
            case "Verus":
1905
                if (ticks < 30 || !autoStop.isEnabled()) {
1906
                    if (p instanceof C0BPacketEntityAction) {
1907
                        final C0BPacketEntityAction c0B = (C0BPacketEntityAction) p;
1908
1909
                        if (c0B.getAction().equals(C0BPacketEntityAction.Action.START_SPRINTING)) {
1910
                            if (EntityPlayerSP.serverSprintState) {
1911
                                PacketUtil.sendPacketWithoutEvent(new C0BPacketEntityAction(mc.thePlayer, C0BPacketEntityAction.Action.STOP_SPRINTING));
1912
                                EntityPlayerSP.serverSprintState = false;
1913
                            }
1914
                            event.setCancelled(true);
1915
                        }
1916
1917
                        if (c0B.getAction().equals(C0BPacketEntityAction.Action.STOP_SPRINTING)) {
1918
                            event.setCancelled(true);
1919
                        }
1920
                    }
1921
                }
1922
                break;
1923
1924
            case "Hypixel Fast Lag":
1925
                packets.add(p);
1926
                event.setCancelled(true);
1927
                break;
1928
        }
1929
    }
1930
1931
    @Override
1932
    public void onBlockCollide(final BlockCollideEvent event) {
1933
        switch (mode.getMode()) {
1934
            case "VerusBlack": {
1935
                if (event.getBlock() instanceof BlockAir && !mc.thePlayer.isSneaking()) {
1936
                    final double x = event.getX(), y = event.getY(), z = event.getZ();
1937
1938
                    if (y < mc.thePlayer.posY) {
1939
                        event.setCollisionBoundingBox(AxisAlignedBB.fromBounds(-15, -1, -15, 15, 1, 15).offset(x, y, z));
1940
                    }
1941
                }
1942
            }
1943
            break;
1944
        }
1945
    }
1946
1947
    @Override
1948
    public void onPacketReceive(final PacketReceiveEvent event) {
1949
        final Packet<?> p = event.getPacket();
1950
1951
        if (mode.getMode().equals("Hypixel") && p instanceof S08PacketPlayerPosLook) setback = true;
1952
1953
        if (mode.getMode().equals("Hycraft") && p instanceof S08PacketPlayerPosLook) {
1954
            if (!flag) {
1955
                S08PacketPlayerPosLook packet = (S08PacketPlayerPosLook) p;
1956
1957
                double deltaX = packet.getX() - mc.thePlayer.posX;
1958
                double deltaY = packet.getY() - mc.thePlayer.posY;
1959
                double deltaZ = packet.getZ() - mc.thePlayer.posZ;
1960
1961
                if (Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) < 10) {
1962
                    event.setCancelled(true);
1963
                    PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C06PacketPlayerPosLook(packet.getX(), packet.getY(), packet.getZ(), packet.getYaw(), packet.getPitch(), false));
1964
                }
1965
            }
1966
        }
1967
1968
        if (p instanceof S12PacketEntityVelocity && ((S12PacketEntityVelocity) p).getEntityID() == mc.thePlayer.getEntityId()) {
1969
            if (mode.is("Bow Fly")) {
1970
                dmged = true;
1971
                speed = 0.6f;
1972
                mc.thePlayer.motionY = 0.42;
1973
            }
1974
1975
            event.setCancelled(true);
1976
        }
1977
1978
        if (mode.is("Minemenclub") && (p instanceof S12PacketEntityVelocity || p instanceof S27PacketExplosion)) {
1979
            event.setCancelled(true);
1980
        }
1981
1982
        if (p instanceof S08PacketPlayerPosLook) {
1983
            final S08PacketPlayerPosLook s08 = (S08PacketPlayerPosLook) p;
1984
            switch (mode.getMode()) {
1985
                case "Redesky":
1986
                    flag = true;
1987
                    break;
1988
1989
                case "Verus":
1990
                    this.toggleModule();
1991
                    this.registerNotification("Disabled " + this.getModuleInfo().name() + " due to flag.");
1992
                    break;
1993
1994
                case "Minemenclub":
1995
                    event.setCancelled(true);
1996
                    break;
1997
1998
                case "Vulcan":
1999
                    hypixelTicks = -10;
2000
                    hypixelStart = true;
2001
                    break;
2002
2003
                case "Block Drop":
2004
                    if (mc.thePlayer.ticksExisted > 20) {
2005
                        event.setCancelled(true);
2006
                        this.position = new Vector3d(s08.getX(), s08.getY(), s08.getZ());
2007
                        this.rotation = new Vector2f(s08.getYaw(), s08.getPitch());
2008
                    }
2009
                    break;
2010
2011
                case "Hypixel":
2012
2013
                    bool = true;
2014
2015
                    break;
2016
2017
                case "Vulcan2":
2018
                    if (mc.thePlayer.ticksExisted > 20) {
2019
                        if (Math.abs(s08.x - startingLocationX) + Math.abs(s08.y - startingLocationY) + Math.abs(s08.z - startingLocationZ) < 4) {
2020
                            if (PlayerUtil.generalAntiPacketLog()) event.setCancelled(true);
2021
                            if (!bool) {
2022
                                mc.thePlayer.hurtTime = 9;
2023
                                bool = true;
2024
                                //        Rise.addChatMessage("Sent S40");
2025
                            }
2026
                        } else {
2027
                            this.toggleModule();
2028
                        }
2029
                    }
2030
                    break;
2031
            }
2032
        }
2033
    }
2034
2035
    @Override
2036
    public void onWorldChanged(final WorldChangedEvent event) {
2037
        if (disableOnWorldChange.isEnabled()) {
2038
            this.toggleModule();
2039
            this.registerNotification("Disabled " + this.getModuleInfo().name() + " due to world change.");
2040
        }
2041
    }
2042
2043
    private void handleVanillaKickBypass() {
2044
        if (System.currentTimeMillis() - groundTimer < 1000) return;
2045
2046
        final double x = mc.thePlayer.posX;
2047
        final double y = mc.thePlayer.posY;
2048
        final double z = mc.thePlayer.posZ;
2049
2050
        final double ground = calculateGround();
2051
2052
        for (double posY = y; posY > ground; posY -= 8D) {
2053
            mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(x, posY, z, true));
2054
2055
            if (posY - 8D < ground) break; // Prevent next step
2056
        }
2057
2058
        mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(x, ground, z, true));
2059
2060
2061
        for (double posY = ground; posY < y; posY += 8D) {
2062
            mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(x, posY, z, true));
2063
2064
            if (posY + 8D > y) break; // Prevent next step
2065
        }
2066
2067
        mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(x, y, z, true));
2068
2069
        groundTimer = System.currentTimeMillis();
2070
    }
2071
2072
    public double calculateGround() {
2073
        final double y = mc.thePlayer.posY;
2074
2075
        final AxisAlignedBB playerBoundingBox = mc.thePlayer.getEntityBoundingBox();
2076
        double blockHeight = 1D;
2077
2078
        for (double ground = y; ground > 0D; ground -= blockHeight) {
2079
            final AxisAlignedBB customBox = new AxisAlignedBB(playerBoundingBox.maxX, ground + blockHeight, playerBoundingBox.maxZ, playerBoundingBox.minX, ground, playerBoundingBox.minZ);
2080
2081
            if (mc.theWorld.checkBlockCollision(customBox)) {
2082
                if (blockHeight <= 0.05D)
2083
                    return ground + blockHeight;
2084
2085
                ground += blockHeight;
2086
                blockHeight = 0.05D;
2087
            }
2088
        }
2089
2090
        return 0F;
2091
    }
2092
2093
    public double getFlightSpeed() {
2094
        double baseSpeed = 0.262;
2095
2096
        if (Minecraft.getMinecraft().thePlayer.isPotionActive(Potion.moveSpeed)) {
2097
            final int amplifier = Minecraft.getMinecraft().thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier();
2098
            baseSpeed *= 1.0 + (0.15 * amplifier);
2099
        }
2100
2101
        return baseSpeed;
2102
    }
2103
2104
    private void hypixelDisabler() {
2105
        int newSlot = -1;
2106
2107
        for (int i = 0; i < 8; i++) {
2108
            if (mc.thePlayer.inventory.currentItem == i)
2109
                continue;
2110
2111
            final ItemStack itemStack = mc.thePlayer.inventory.getStackInSlot(i);
2112
2113
            if (itemStack == null) {
2114
                newSlot = i;
2115
                continue;
2116
            }
2117
2118
            final Item item = itemStack.getItem();
2119
2120
            if (!(itemStack.getDisplayName().contains("Right Click") || (item instanceof ItemPotion && ItemPotion.isSplash(itemStack.getMetadata()) || item instanceof ItemSword ||
2121
                    item instanceof ItemEgg || item instanceof ItemSnowball || item instanceof ItemEnderPearl || item instanceof ItemEnderEye || item instanceof ItemFireball || item instanceof ItemFishingRod ||
2122
                    item instanceof ItemEditableBook || item instanceof ItemExpBottle)))
2123
                newSlot = i;
2124
        }
2125
2126
        if (newSlot != -1) {
2127
            PacketUtil.sendPacket(new C09PacketHeldItemChange(newSlot));
2128
            PacketUtil.sendPacket(new C08PacketPlayerBlockPlacement(mc.thePlayer.inventory.getStackInSlot(newSlot)));
2129
            PacketUtil.sendPacket(new C09PacketHeldItemChange(mc.thePlayer.inventory.currentItem));
2130
            return;
2131
        }
2132
2133
        final int nextSlot = mc.thePlayer.inventory.currentItem == 8 ? 0 : mc.thePlayer.inventory.currentItem + 1;
2134
        final ItemStack stack = mc.thePlayer.inventory.getStackInSlot(nextSlot);
2135
        if (stack == null || !stack.getDisplayName().contains("Right Click")) {
2136
            PacketUtil.sendPacket(new C09PacketHeldItemChange(nextSlot));
2137
            PacketUtil.sendPacket(new C08PacketPlayerBlockPlacement(mc.thePlayer.inventory.getStackInSlot(nextSlot)));
2138
            PacketUtil.sendPacket(new C09PacketHeldItemChange(mc.thePlayer.inventory.currentItem));
2139
        }
2140
    }
2141
}

What this file does

The entire module is this one file. onPreMotion contains the giant mode switch: Vanilla and MineBox write motionY and strafe from the fly speed, Verus and Verus Lag use the y-drop and ground-fake pair, Vulcan runs its timed motionY sequence against the pinned starting Y, Hypixel places slime blocks and fakes ground, Matrix1.17 swaps to a block item and sends C08 placements on a tick pattern, Jetpack and Mush accelerate motion directly, and the block modes (BlockFly, Block Drop, Hycraft) combine motion writes with position packets. onPacketSend then filters the outgoing stream per mode: C03 cancellations for Block Drop, Hycraft, MineBox and Vicnix, packet buffering for Hypixel Blink, Spartan, Minemenclub and Hypixel Infinite, and the onGround rewrite for Hypixel.

onPacketReceive is where the module defends itself. The S08 branch is per-mode: setback tracking for Hypixel, cancellation plus C06 re-send for Hycraft, cancellation for Minemenclub, timer reset for Vulcan, auto-disable for Verus, and position recording for Block Drop. The S12 branch cancels every knockback for the player entity and, in Bow Fly mode, converts it into a 0.42 vertical motion, while Minemenclub also cancels S27 explosions. The receive handler is also what makes the Hypixel mode resilient: every teleport sets setback, and outgoing C03 packets only get the onGround rewrite when setback, fly and stage are all active.

handleVanillaKickBypass is the file's third notable piece. It scans from the current y down to a computed ground in 8-block steps, sending one C04 position packet per step, then climbs back with the same step pattern and a final C04 at the original y, all gated by a 1-second groundTimer. The Vanilla mode's kick-bypass stream is therefore a burst of position packets every second, which is exactly the traffic pattern that movement checks see as a teleport ladder.

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 SurvivalFly (movement physics envelope)

SurvivalFly.java2531 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.moving.player;
16
17
import java.util.ArrayList;
18
import java.util.Collection;
19
import java.util.Locale;
20
21
import org.bukkit.ChatColor;
22
import org.bukkit.Location;
23
import org.bukkit.Material;
24
import org.bukkit.entity.LivingEntity;
25
import org.bukkit.entity.Player;
26
import org.bukkit.util.Vector;
27
28
import fr.neatmonster.nocheatplus.NCPAPIProvider;
29
import fr.neatmonster.nocheatplus.actions.ParameterName;
30
import fr.neatmonster.nocheatplus.checks.Check;
31
import fr.neatmonster.nocheatplus.checks.CheckType;
32
import fr.neatmonster.nocheatplus.checks.ViolationData;
33
import fr.neatmonster.nocheatplus.checks.combined.CombinedData;
34
import fr.neatmonster.nocheatplus.checks.combined.Improbable;
35
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
36
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
37
import fr.neatmonster.nocheatplus.checks.moving.envelope.PhysicsEnvelope;
38
import fr.neatmonster.nocheatplus.checks.moving.envelope.PhysicsGroundResolver;
39
import fr.neatmonster.nocheatplus.checks.moving.envelope.workaround.LostGround;
40
import fr.neatmonster.nocheatplus.checks.moving.envelope.workaround.MagicWorkarounds;
41
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerKeyboardInput;
42
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerKeyboardInput.ForwardDirection;
43
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerKeyboardInput.StrafeDirection;
44
import fr.neatmonster.nocheatplus.checks.moving.model.LiftOffEnvelope;
45
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerMoveData;
46
import fr.neatmonster.nocheatplus.checks.workaround.WRPT;
47
import fr.neatmonster.nocheatplus.compat.AlmostBoolean;
48
import fr.neatmonster.nocheatplus.compat.Bridge1_13;
49
import fr.neatmonster.nocheatplus.compat.Bridge1_9;
50
import fr.neatmonster.nocheatplus.compat.BridgeMisc;
51
import fr.neatmonster.nocheatplus.compat.SchedulerHelper;
52
import fr.neatmonster.nocheatplus.compat.blocks.changetracker.BlockChangeTracker;
53
import fr.neatmonster.nocheatplus.compat.blocks.changetracker.BlockChangeTracker.Direction;
54
import fr.neatmonster.nocheatplus.compat.versions.ClientVersion;
55
import fr.neatmonster.nocheatplus.components.modifier.IAttributeAccess;
56
import fr.neatmonster.nocheatplus.components.registry.event.IGenericInstanceHandle;
57
import fr.neatmonster.nocheatplus.logging.Streams;
58
import fr.neatmonster.nocheatplus.players.DataManager;
59
import fr.neatmonster.nocheatplus.players.IPlayerData;
60
import fr.neatmonster.nocheatplus.utilities.CheckUtils;
61
import fr.neatmonster.nocheatplus.utilities.StringUtil;
62
import fr.neatmonster.nocheatplus.utilities.collision.CollisionUtil;
63
import fr.neatmonster.nocheatplus.utilities.collision.supportingblock.SupportingBlockUtils;
64
import fr.neatmonster.nocheatplus.utilities.location.PlayerLocation;
65
import fr.neatmonster.nocheatplus.utilities.map.BlockFlags;
66
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
67
import fr.neatmonster.nocheatplus.utilities.math.MathUtil;
68
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
69
import fr.neatmonster.nocheatplus.utilities.moving.Magic;
70
import fr.neatmonster.nocheatplus.utilities.moving.MovingUtil;
71
72
/**
73
 * The counterpart to the CreativeFly check, designed for ordinary gameplay (Survival/Adventure)
74
 */
75
@SuppressWarnings({"UnstableApiUsage", "StatementWithEmptyBody"})
76
public class SurvivalFly extends Check {
77
78
    // TODO: Unification of vertical and horizontal motion. Also to reduce the number of RichEntityLocation#collide() calls.
79
80
    /** To join some tags with moving check violations. */
81
    private final ArrayList<String> tags = new ArrayList<>(15);
82
    
83
    private final ArrayList<String> justUsedWorkarounds = new ArrayList<>();
84
    
85
    private final BlockChangeTracker blockChangeTracker;
86
    
87
    private final IGenericInstanceHandle<IAttributeAccess> attributeAccess = NCPAPIProvider.getNoCheatPlusAPI().getGenericInstanceHandle(IAttributeAccess.class);
88
    
89
    /**
90
     * The vertical component of liquid push (water/lava).
91
     * This is computed in hdistrel and then used by vidstrel to avoid having to call the getLiquidPush() method twice.
92
     * When computing the horizontal liquid push, the way Mojang coded the function to get the liquid's flowing force
93
     * to calculate horizontal speed with, also affects the vertical speed (See comment in {@link fr.neatmonster.nocheatplus.utilities.location.RichEntityLocation#getFlowForceVector(int, int, int, long)}.
94
     */
95
    private double verticalLiquidPushComponent = 0.0;
96
    
97
    
98
    public SurvivalFly() {
99
        super(CheckType.MOVING_SURVIVALFLY);
100
        blockChangeTracker = NCPAPIProvider.getNoCheatPlusAPI().getBlockChangeTracker();
101
    }
102
    
103
    
104
    /**
105
     * Checks a player
106
     *
107
     * @param multiMoveCount
108
     *            0: Ordinary, 1/2/(...): first/second/(...) part of a split move.
109
     * @param isNormalOrPacketSplitMove
110
     *           Flag to indicate if the packet-based split move mechanic is used instead of the Bukkit-based one (or the move was not split)
111
     *
112
     * @return The Location where to set back the player to. Null in case of no violation.
113
     */
114
    public Location check(final Player player, final PlayerLocation from, final PlayerLocation to,
115
                          final int multiMoveCount, final MovingData data, final MovingConfig cc,
116
                          final IPlayerData pData, final int tick, final long now,
117
                          final boolean useBlockChangeTracker, final boolean isNormalOrPacketSplitMove) {
118
        /*
119
          TODO: Ideally, all this data should really be set outside SurvivalFly (in the MovingListener), since they can be useful
120
          for other checks / stuff.
121
         */
122
        tags.clear();
123
        justUsedWorkarounds.clear();
124
        // Shortcuts:
125
        final boolean debug = pData.isDebugActive(type);
126
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
127
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
128
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
129
        /*
130
         * Actually forgot what this does. But quick guess might be idle move (0,0,0) on count 1 and riptide on count 2.
131
         * TODO: Is this supposed to be here? (Move in MovingListener at the beginning of checkPayerMove?)
132
         */
133
        if (lastMove.tridentRelease.decideOptimistically() && multiMoveCount == 2 && lastMove.yDistance == 0.0) {
134
            thisMove.tridentRelease = AlmostBoolean.YES;
135
            lastMove.tridentRelease = AlmostBoolean.NO;
136
        }
137
        /* Regular and past fromOnGround */
138
        final boolean fromOnGround = from.isOnGround() || useBlockChangeTracker && from.isOnGroundOpportune(cc.yOnGround, 0L, blockChangeTracker, data.blockChangeRef, tick);
139
        /* Regular and past toOnGround */
140
        final boolean toOnGround = to.isOnGround() || useBlockChangeTracker && to.isOnGroundOpportune(cc.yOnGround, 0L, blockChangeTracker, data.blockChangeRef, tick);  // TODO: Work in the past ground stuff differently (thisMove, touchedGround?, from/to ...)
141
        /* Moving onto/into everything that isn't in air (liquids, stuck-speed, ground, ALL) */
142
        final boolean resetTo = toOnGround || to.isResetCond();
143
        /* Moving off from anything that is not air (liquids, stuck-speed, ground, ALL). */
144
        final boolean resetFrom = fromOnGround || from.isResetCond();
145
        // Run lostground checks.
146
        LostGround.runLostGroundChecks(player, from, to, thisMove.hDistance, thisMove.yDistance, lastMove, data, cc, useBlockChangeTracker ? blockChangeTracker : null, tags);
147
148
        // Set workarounds for the registry
149
        data.ws.setJustUsedIds(justUsedWorkarounds);
150
151
        // Recover from data removal (somewhat random insertion point).
152
        if (data.liftOffEnvelope == LiftOffEnvelope.UNKNOWN) {
153
            data.adjustLiftOffEnvelope(from);
154
        }
155
156
        // Adjust block properties (friction, block speed etc...)
157
        data.adjustMediumProperties(player, from);
158
        
159
        // Ground somehow appeared out of thin air (block place).
160
        // This move is registered as "coming from ground" despite the player not having moved onto ground with the previous move, which was fully in air.
161
        if (thisMove.touchedGround) {
162
            if (multiMoveCount == 0 && thisMove.from.onGround && PhysicsEnvelope.inAir(lastMove) 
163
                && TrigUtil.isSamePosAndLook(thisMove.from, lastMove.to)) {
164
                data.setSetBack(from);
165
                if (debug) {
166
                    debug(player, "Ground appeared due to a block-place: adjust set-back location.");
167
                }
168
            }
169
        }
170
171
        // Decrease bunnyhop delay counter
172
        if (data.jumpDelay > 0) {
173
            data.jumpDelay--;
174
        }
175
      
176
177
178
        /////////////////////////////////////
179
        // Horizontal move                ///
180
        /////////////////////////////////////
181
        double hAllowedDistance, hDistanceAboveLimit, hFreedom;
182
        double[] resGlide = processGliding(from, to, pData, data, player, isNormalOrPacketSplitMove, fromOnGround, toOnGround, debug);
183
        // Set the allowed distance and determine the distance above limit
184
        double[] hRes = Bridge1_9.isGliding(player) ? resGlide : prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, false);
185
        hAllowedDistance = hRes[0];
186
        hDistanceAboveLimit = hRes[1];
187
        // Beyond limit? Check if there may have been a reason for this (and try to re-estimate if needed)
188
        if (hDistanceAboveLimit > 0.0) {
189
            double[] res = hDistAfterFailure(player, from, to, hAllowedDistance, hDistanceAboveLimit, thisMove, lastMove, debug, data, cc, pData, tick, useBlockChangeTracker, fromOnGround, toOnGround, isNormalOrPacketSplitMove);
190
            hAllowedDistance = res[0];
191
            hDistanceAboveLimit = res[1];
192
            hFreedom = res[2];
193
        }
194
        else {
195
            // Clear active velocity if the distance is within limit (clearly not needed. :))
196
            //data.clearActiveHorVel();
197
            hFreedom = 0.0;
198
        }
199
200
201
        /////////////////////////////////////
202
        // Vertical move                  ///
203
        /////////////////////////////////////
204
        // Order of checking in EntityLiving.java water -> lava -> gliding -> air
205
        // TODO: Clean-up this left-over bit of the old implementation (respect MC's order)
206
        double yAllowedDistance, yDistanceAboveLimit;
207
        if (Bridge1_9.isGliding(player)) {
208
            yAllowedDistance = resGlide[2];
209
            yDistanceAboveLimit = resGlide[3];
210
        }
211
        else {
212
            final double[] res = vDistRel(player, from, fromOnGround, resetFrom, to, toOnGround, resetTo, thisMove.yDistance, isNormalOrPacketSplitMove, lastMove, data, pData, false, debug, useBlockChangeTracker );
213
            yAllowedDistance = res[0];
214
            yDistanceAboveLimit = res[1];
215
        }
216
217
        ////////////////////////////
218
        // Debug output.          //
219
        ////////////////////////////
220
        final int tagsLength;
221
        if (debug) {
222
            outputDebug(player, to, from, data, thisMove.hDistance, hAllowedDistance, hFreedom, thisMove.yDistance, yAllowedDistance, fromOnGround, resetFrom, toOnGround, resetTo, thisMove);
223
            tagsLength = tags.size();
224
            data.ws.setJustUsedIds(null);
225
        }
226
        else tagsLength = 0; // JIT vs. IDE.
227
228
229
        //////////////////////////////////////
230
        // Handle violations               ///
231
        //////////////////////////////////////
232
        final boolean inAir = PhysicsEnvelope.inAir(thisMove);
233
        final double result = (Math.max(hDistanceAboveLimit, 0.0) + Math.max(yDistanceAboveLimit, 0.0)) * 100D;
234
        if (result > 0.0) {
235
            final Location vLoc = handleViolation(result, player, from, to, data, cc);
236
            if (inAir) {
237
                data.sfVLInAir = true;
238
            }
239
            // Request a new to-location
240
            if (vLoc != null) {
241
                return vLoc;
242
            }
243
        }
244
        else {
245
            if (canRelaxVL(data, cc, inAir, lastMove, thisMove)) {
246
                // Relax VL.
247
                data.survivalFlyVL *= 0.95;
248
            }
249
        }
250
251
252
        //////////////////////////////////////////////////////////////////////////////////////////////
253
        //  Set data for normal move or violation without cancel (cancel would have returned above) //
254
        //////////////////////////////////////////////////////////////////////////////////////////////
255
        // Adjust lift off envelope to medium
256
        if (thisMove.to.inPowderSnow) {
257
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_POWDER_SNOW;
258
        }
259
        else if (thisMove.to.inWeb) {
260
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_WEBS;
261
        }
262
        else if (thisMove.to.inBerryBush) {
263
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_SWEET_BERRY;
264
        }
265
        else if (thisMove.to.onHoneyBlock) {
266
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_HONEY_BLOCK;
267
        }
268
        else if (resetTo) {
269
            data.liftOffEnvelope = LiftOffEnvelope.NORMAL;
270
        }
271
        else if (thisMove.from.inPowderSnow) {
272
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_POWDER_SNOW;
273
        }
274
        else if (thisMove.from.inWeb) {
275
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_WEBS;
276
        }
277
        else if (thisMove.from.inBerryBush) {
278
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_SWEET_BERRY;
279
        }
280
        else if (thisMove.from.onHoneyBlock) {
281
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_HONEY_BLOCK;
282
        }
283
        else if (resetFrom || thisMove.touchedGround) {
284
            data.liftOffEnvelope = LiftOffEnvelope.NORMAL;
285
        }
286
        else {
287
            // Air, Keep medium.
288
        }
289
290
        // Apply reset conditions.
291
        if (resetTo) {
292
            // Reset data.
293
            data.setSetBack(to);
294
            data.sfJumpPhase = 0;
295
        }
296
        // The player moved from ground.
297
        else if (resetFrom) {
298
            data.setSetBack(from);
299
            data.sfJumpPhase = 1; // This event is already in air.
300
        }
301
        else {
302
            data.sfJumpPhase ++;
303
            if (!Double.isInfinite(Bridge1_9.getLevitationAmplifier(player))
304
                || Bridge1_13.isRiptiding(player)
305
                || Bridge1_9.isGliding(player)) {
306
                data.setSetBack(to);
307
            }
308
        }
309
310
        // Adjust not in-air stuff.
311
        if (!inAir) {
312
            data.ws.resetConditions(WRPT.G_RESET_NOTINAIR);
313
            data.sfVLInAir = false;
314
        }
315
316
        // Update unused velocity tracking.
317
        // TODO: Hide and seek with API.
318
        // TODO: Pull down tick / timing data (perhaps add an API object for millis + source + tick + sequence count (+ source of sequence count).
319
        if (debug) {
320
            // TODO: Only update, if velocity is queued at all.
321
            data.getVerticalVelocityTracker().updateBlockedState(tick,
322
                    // Assume blocked with being in web/water, despite not entirely correct.
323
                    thisMove.headObstructed || thisMove.from.resetCond,
324
                    // (Similar here.)
325
                    thisMove.touchedGround || thisMove.to.resetCond);
326
            // TODO: TEST: Check unused velocity here too. (Should have more efficient process, pre-conditions for checking.)
327
            UnusedVelocity.checkUnusedVelocity(player, type, data, cc);
328
        }
329
330
        // Adjust various speed/friction factors (both h/v).
331
        data.lastFrictionVertical = data.nextFrictionVertical;
332
        data.lastFrictionHorizontal = data.nextFrictionHorizontal;
333
        data.lastStuckInBlockVertical = data.nextStuckInBlockVertical;
334
        data.lastStuckInBlockHorizontal = data.nextStuckInBlockHorizontal;
335
        data.lastBlockSpeedMultiplier = data.nextBlockSpeedMultiplier;
336
        data.lastInertia = data.nextInertia;
337
        data.lastLevitationLevel = !Double.isInfinite(Bridge1_9.getLevitationAmplifier(player)) ? Bridge1_9.getLevitationAmplifier(player) + 1 : 0.0;
338
        data.lastGravity = data.nextGravity;
339
        data.lastCollidingEntitiesLocations = CollisionUtil.getCollidingEntitiesLocations(player);
340
        cData.wasSprinting = pData.isSprinting();
341
        cData.wasPressingShift = pData.isShiftKeyPressed();
342
        cData.wasSlowFalling = !Double.isInfinite(Bridge1_13.getSlowfallingAmplifier(player));
343
        cData.wasLevitating = !Double.isInfinite(Bridge1_9.getLevitationAmplifier(player));
344
        // Log tags added after violation handling.
345
        if (debug && tags.size() > tagsLength) {
346
            logPostViolationTags(player);
347
        }
348
        // Nothing to do, newTo (MovingListener) stays null
349
        return null;
350
    }
351
    
352
    
353
    /**
354
     * Check if the violation level may decrease.
355
     * 
356
     * @param data
357
     * @param cc
358
     * @param inAir
359
     * @param lastMove
360
     * @param thisMove
361
     * @return
362
     */
363
    private boolean canRelaxVL(MovingData data, MovingConfig cc, boolean inAir, PlayerMoveData lastMove, PlayerMoveData thisMove) {
364
        // Slowly reduce the level with each event, if violations have not recently happened.
365
        return data.getPlayerMoveCount() - data.sfVLMoveCount > cc.survivalFlyVLFreezeCount
366
                && (!cc.survivalFlyVLFreezeInAir || !inAir
367
                // Favor bunny-hopping slightly: clean descend.
368
                || !data.sfVLInAir
369
                && data.liftOffEnvelope == LiftOffEnvelope.NORMAL
370
                && lastMove.toIsValid
371
                && lastMove.yDistance < -Magic.GRAVITY_MIN
372
                && thisMove.yDistance - lastMove.yDistance < -Magic.GRAVITY_MIN);
373
    }
374
    
375
    
376
    /**
377
     * A check to prevent players from bed-flying.
378
     * To be called on PlayerBedLeaveEvent(s)
379
     * (This increases VL and sets tag only. Setback is done in MovingListener).
380
     *
381
     * @return If to prevent action (use the setback location of survivalfly).
382
     */
383
    public boolean checkBed(final Player player, final MovingConfig cc, final MovingData data) {
384
        boolean cancel = false;
385
        // Check if the player had been in bed at all.
386
        if (!data.wasInBed) {
387
            // Violation ...
388
            tags.add("bedfly");
389
            data.survivalFlyVL += 100D;
390
            Improbable.check(player, (float) 5.0, System.currentTimeMillis(), "moving.survivalfly.bedfly", DataManager.getPlayerData(player));
391
            final ViolationData vd = new ViolationData(this, player, data.survivalFlyVL, 100D, cc.survivalFlyActions);
392
            if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
393
            cancel = executeActions(vd).willCancel();
394
        }
395
        // Nothing detected.
396
        else data.wasInBed = false;
397
        return cancel;
398
    }
399
400
401
    /**
402
     * Check for push/pull by pistons, alter data appropriately (blockChangeId).
403
     */
404
    private double[] getVerticalBlockMoveResult(final double yDistance, final PlayerLocation from, final PlayerLocation to, final MovingData data) {
405
        /*
406
         * TODO: Pistons pushing horizontally allow similar/same upwards
407
         * (downwards?) moves (possibly all except downwards, which is hard to
408
         * test :p).
409
         */
410
        // TODO: Allow push up to 1.0 (or 0.65 something) even beyond block borders, IF COVERED [adapt PlayerLocation].
411
        // TODO: Other conditions/filters ... ?
412
        // Push (/pull) up.
413
        if (yDistance > 0.0) {
414
            if (yDistance <= 1.015) {
415
                /*
416
                 * (Full blocks: slightly more possible, ending up just above
417
                 * the block. Bounce allows other end positions.)
418
                 */
419
                // TODO: Is the air block wich the slime block is pushed onto really in? 
420
                if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, Direction.Y_POS, Math.min(yDistance, 1.0))) {
421
                    if (yDistance > 1.0) {
422
                        if (to.getY() - to.getBlockY() >= 0.015) {
423
                            // Exclude ordinary cases for this condition.
424
                            return null;
425
                        }
426
                    }
427
                    tags.add("blkmv_y_pos");
428
                    final double maxDistYPos = yDistance; //1.0 - (from.getY() - from.getBlockY()); // TODO: Margin ?
429
                    return new double[]{maxDistYPos, 0.0};
430
                }
431
            }
432
        }
433
        // Push (/pull) down.
434
        else if (yDistance < 0.0 && yDistance >= -1.0) {
435
            if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, Direction.Y_NEG, -yDistance)) {
436
                tags.add("blkmv_y_neg");
437
                final double maxDistYNeg = yDistance; // from.getY() - from.getBlockY(); // TODO: Margin ?
438
                return new double[]{maxDistYNeg, 0.0};
439
            }
440
        }
441
        // Nothing found.
442
        return null;
443
    }
444
445
446
    /**
447
     * Determine the allowed h / v distance for gliding.
448
     * Handled in its own method because of vertical and horizontal motion being too intertwined to separate (y-distance changes relate to h-distance changes). <br>
449
     * Consistency checks are done within the {@link fr.neatmonster.nocheatplus.checks.combined.CombinedListener}.<br>
450
     * <li> NOTE: this should be called with {@link Bridge1_9#isGliding(LivingEntity)} not {@link Bridge1_9#isGlidingWithElytra(Player)}, because the client does not check for elytra to apply the corresponding motion (EntityLiving, travel())</li>
451
     *
452
     * @return the allowed xyz distances + distances above limit.
453
     */
454
    private double[] processGliding(final PlayerLocation from, final PlayerLocation to, final IPlayerData pData, final MovingData data,
455
                                    final Player player, boolean isNormalOrPacketSplitMove, final boolean fromOnGround, final boolean toOnGround, final boolean debug) {
456
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
457
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
458
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
459
        double yDistanceAboveLimit = 0.0, hDistanceAboveLimit = 0.0;
460
        // TODO: What with gliding + rocket boosting + riptiding + bouncing on slimes/beds while riptiding? LMAO
461
        // Beats me why Mojang keeps letting players perform such ridiculous moves.
462
        if (!Bridge1_9.isGliding(player)) {
463
            // No Gliding, no deal
464
            return new double[] {thisMove.hDistance, 0.0, thisMove.yDistance, 0.0};
465
        }
466
        // Note: WASD key presses, as well as sneaking and item-use are irrelevant when gliding.
467
        // Initialize speed.
468
        thisMove.xAllowedDistance = lastMove.toIsValid ? lastMove.xDistance : 0.0;
469
        thisMove.yAllowedDistance = lastMove.toIsValid ? lastMove.yDistance : 0.0;
470
        thisMove.zAllowedDistance = lastMove.toIsValid ? lastMove.zDistance : 0.0;
471
        // Reset momentum if collided with something on the previous tick.
472
        doWallCollision(lastMove, thisMove);
473
        // Throttle speed if stuck in a block.
474
        if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) {
475
            if (data.lastStuckInBlockVertical != 1.0) {
476
                thisMove.yAllowedDistance = 0.0;
477
            }
478
            if (data.lastStuckInBlockHorizontal != 1.0) {
479
                thisMove.xAllowedDistance = thisMove.zAllowedDistance = 0.0;
480
            }
481
        }
482
        // Reset speed if judged to be negligible.
483
        checkNegligibleMomentum(pData, thisMove);
484
        checkNegligibleMomentumVertical(pData, thisMove, null);
485
        // Yes, players can glide and riptide at the same time, increasing speed at a faster rate than chunks can load...
486
        // Surely a questionable decision on Mojang's part.
487
        // NOTE: For the elytra, this has to be done before applying gravity and other motion changes.
488
        if (thisMove.tridentRelease.decideOptimistically()) {
489
            thisMove.tridentRelease = AlmostBoolean.YES;
490
            Vector riptideVelocity = to.getRiptideVelocity(false); // Cannot glide while on ground, so no need to check for it.
491
            thisMove.xAllowedDistance += riptideVelocity.getX();
492
            thisMove.yAllowedDistance += riptideVelocity.getY();
493
            thisMove.zAllowedDistance += riptideVelocity.getZ();
494
        }
495
        // TODO: Reduce verbosity (at least, make it easier to look at)
496
        Vector viewVector = TrigUtil.getLookingDirection(to, player);
497
        float radianPitch = to.getPitch() * TrigUtil.toRadians;
498
        // Horizontal length of the look direction
499
        double viewVecHorizontalLength = MathUtil.dist(viewVector.getX(), viewVector.getZ());
500
        // Horizontal length of the movement
501
        double thisMoveHDistance = MathUtil.dist(thisMove.xAllowedDistance, thisMove.zAllowedDistance); // NOTE: MUST BE the ALLOWED distances.
502
        // Overall length of the look direction.
503
        double viewVectorLength = viewVector.length();
504
        // Mojang switched from their own cosine function to the standard Math.cos() one in 1.18.2
505
        double cosPitch = pData.getClientVersion().isAtMost(ClientVersion.V_1_18_2) ? TrigUtil.cos((double)radianPitch) : Math.cos((double)radianPitch);
506
        cosPitch = cosPitch * cosPitch * Math.min(1.0, viewVectorLength / 0.4);
507
        // Base gravity when gliding.
508
        thisMove.yAllowedDistance += (cData.wasSlowFalling && lastMove.yDistance <= 0.0 ? Magic.SLOW_FALL_GRAVITY : Magic.DEFAULT_GRAVITY) * (-1.0 + cosPitch * 0.75);
509
        double baseSpeed;
510
        if (thisMove.yAllowedDistance < 0.0 && viewVecHorizontalLength > 0.0) {
511
            // Slow down.
512
            baseSpeed = thisMove.yAllowedDistance * -0.1 * cosPitch;
513
            thisMove.xAllowedDistance += viewVector.getX() * baseSpeed / viewVecHorizontalLength;
514
            thisMove.yAllowedDistance += baseSpeed;
515
            thisMove.zAllowedDistance += viewVector.getZ() * baseSpeed / viewVecHorizontalLength;
516
        }
517
        if (radianPitch < 0.0 && viewVecHorizontalLength > 0.0) {
518
            // Looking down speeds up the player.
519
            baseSpeed = thisMoveHDistance * (double) (-TrigUtil.sin(radianPitch)) * 0.04;
520
            thisMove.xAllowedDistance += -viewVector.getX() * baseSpeed / viewVecHorizontalLength;
521
            thisMove.yAllowedDistance += baseSpeed * 3.2;
522
            thisMove.zAllowedDistance += -viewVector.getZ() * baseSpeed / viewVecHorizontalLength;
523
        }
524
        if (viewVecHorizontalLength > 0.0) {
525
            // Accelerate
526
            thisMove.xAllowedDistance += (viewVector.getX() / viewVecHorizontalLength * thisMoveHDistance - thisMove.xAllowedDistance) * 0.1;
527
            thisMove.zAllowedDistance += (viewVector.getZ() / viewVecHorizontalLength * thisMoveHDistance - thisMove.zAllowedDistance) * 0.1;
528
        }
529
        // Boosted with a firework: propel the player.
530
        if (data.fireworksBoostDuration > 0) {
531
            // TODO: Firework netcode is horrible (a single firework can tick twice on the same tick, skipping the subsequent one), so simply applying the increase of speed won't cut it.
532
            // Not even sure if we can predict this at all without some kind of hacks / workarounds.
533
            thisMove.xAllowedDistance += viewVector.getX() * 0.1 + (viewVector.getX() * 1.5 - thisMove.xAllowedDistance) * 0.5;
534
            thisMove.yAllowedDistance += viewVector.getY() * 0.1 + (viewVector.getY() * 1.5 - thisMove.yAllowedDistance) * 0.5;
535
            thisMove.zAllowedDistance += viewVector.getZ() * 0.1 + (viewVector.getZ() * 1.5 - thisMove.zAllowedDistance) * 0.5;
536
        }
537
        // Friction here. (TEST)
538
        // Note about inertia: the game assigns the radian pitch to the "f" variable, which is the variable used to apply friction at the end of the tick, _normally_.
539
        // However, with gliding, the game does not use the f variable at the end of the tick, but instead applies the magic value of 0.99.
540
        thisMove.xAllowedDistance *= 0.99;
541
        thisMove.yAllowedDistance *= data.lastFrictionVertical;
542
        thisMove.zAllowedDistance *= 0.99;
543
        // Stuck-speed with the updated multiplier (both at the end)
544
        if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
545
            thisMove.xAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
546
            thisMove.yAllowedDistance *= (double) data.nextStuckInBlockVertical;
547
            thisMove.zAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
548
        }
549
        // Collisions last.
550
        Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, thisMove.yAllowedDistance, thisMove.zAllowedDistance), fromOnGround || thisMove.fromLostGround, from.getBoundingBox());
551
        thisMove.collideX = collisionVector.getX() != thisMove.xAllowedDistance;
552
        thisMove.collideY = collisionVector.getY() != thisMove.yAllowedDistance;
553
        thisMove.collideZ = collisionVector.getZ() != thisMove.zAllowedDistance;
554
        thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
555
        thisMove.xAllowedDistance = collisionVector.getX();
556
        thisMove.yAllowedDistance = collisionVector.getY();
557
        thisMove.zAllowedDistance = collisionVector.getZ();
558
559
        // Can a vertical workaround apply? If so, override the prediction.
560
        if (MagicWorkarounds.checkPostPredictWorkaround(data, fromOnGround, toOnGround, from, to, thisMove.yAllowedDistance, player, isNormalOrPacketSplitMove)) {
561
            thisMove.yAllowedDistance = thisMove.yDistance;
562
        }
563
        
564
        ////////////////////////////
565
        /// Calculate offests     //
566
        ////////////////////////////
567
        /* Expected difference from current to allowed */
568
        final double offsetV = thisMove.yDistance - thisMove.yAllowedDistance;
569
        if (Math.abs(offsetV) < Magic.PREDICTION_EPSILON) {
570
            // Accuracy margin.
571
        }
572
        else {
573
            // If velocity can be used for compensation, use it.
574
            if (data.getOrUseVerticalVelocity(thisMove.yDistance).isEmpty()) {
575
                yDistanceAboveLimit = Math.max(yDistanceAboveLimit, Math.abs(offsetV));
576
                tags.add("vdistrel");
577
            }
578
        }
579
580
        thisMove.hAllowedDistance = MathUtil.dist(thisMove.xAllowedDistance, thisMove.zAllowedDistance);
581
        final double offsetH = thisMove.hDistance - thisMove.hAllowedDistance;
582
        if (offsetH < Magic.PREDICTION_EPSILON) {
583
            // Accuracy margin.
584
        }
585
        else {
586
            hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offsetH);
587
            if (hDistanceAboveLimit > 0.0) {
588
                tags.add("hdistrel");
589
            }
590
        }
591
        if (debug) {
592
            player.sendMessage(ChatColor.RED + "[SurvivalFly] vdistrel: predict=" + StringUtil.fdec6.format(thisMove.yAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.yDistance) + ", offset=" + StringUtil.fdec6.format(offsetV));
593
            player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] hdistrel: predict=" + StringUtil.fdec6.format(thisMove.hAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.hDistance) + ", offset=" + StringUtil.fdec6.format(offsetH));
594
        }
595
        return new double[]{thisMove.hAllowedDistance, hDistanceAboveLimit, thisMove.yAllowedDistance, yDistanceAboveLimit};
596
    }
597
    
598
    /**
599
     * Reset the given speed upon wall collision.
600
     * 
601
     * @param lastMove
602
     * @param thisMove
603
     */
604
    private void doWallCollision(PlayerMoveData lastMove, PlayerMoveData thisMove) {
605
        if (lastMove.collideX) {
606
            thisMove.xAllowedDistance = 0.0;
607
        }
608
        if (lastMove.collideZ) {
609
            thisMove.zAllowedDistance = 0.0;
610
        }
611
    }
612
    
613
    /**
614
     * Check if the allowed speed set in thisMove should be canceled due to it being lower than the negligible speed threshold. <br>
615
     * (Horizontal only)
616
     * 
617
     * @param pData
618
     * @param thisMove
619
     */
620
    private void checkNegligibleMomentum(IPlayerData pData, PlayerMoveData thisMove) {
621
        if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_21_5)) {
622
            // This condition was added on 1.21.5. If the horizontal distance squared is below 0.000009 and the entity is a player, both horizontal momenta are set to 0.0.
623
            // This means that both x/z momenta can be reset even if one of them is above the threshold, as long as the overall horizontal momentum is below the threshold.
624
            // EntityLiving.java -> aiStep
625
            // We use the unchecked hDistance for performance reasons (no sqrt needed).
626
            if (thisMove.hDistance < Magic.NEGLIGIBLE_SPEED_THRESHOLD) {
627
                thisMove.xAllowedDistance = 0.0;
628
                thisMove.zAllowedDistance = 0.0;
629
            }
630
        }
631
        else if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_9)) {
632
            if (Math.abs(thisMove.xAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD) {
633
                thisMove.xAllowedDistance = 0.0;
634
            }
635
            if (Math.abs(thisMove.zAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD) {
636
                thisMove.zAllowedDistance = 0.0;
637
            }
638
        }
639
        else {
640
            // In 1.8 and lower, momentum is compared to 0.005 instead.
641
            if (Math.abs(thisMove.xAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD_LEGACY) {
642
                thisMove.xAllowedDistance = 0.0;
643
            }
644
            if (Math.abs(thisMove.zAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD_LEGACY) {
645
                thisMove.zAllowedDistance = 0.0;
646
            }
647
        }
648
    }
649
    
650
    /**
651
     * Check if the allowed speed set in thisMove should be canceled due to it being lower than the negligible speed threshold. <br>
652
     * (Vertical only).
653
     * 
654
     * @param pData
655
     * @param thisMove
656
     * @param yTheoreticalDistance
657
     */
658
    private void checkNegligibleMomentumVertical(IPlayerData pData, PlayerMoveData thisMove, double[] yTheoreticalDistance) {
659
        final double threshold = pData.getClientVersion().isAtLeast(ClientVersion.V_1_9) ? Magic.NEGLIGIBLE_SPEED_THRESHOLD : Magic.NEGLIGIBLE_SPEED_THRESHOLD_LEGACY;
660
        final boolean direct = yTheoreticalDistance == null;
661
        if (direct) {
662
            if (Math.abs(thisMove.yAllowedDistance) < threshold) {
663
                thisMove.yAllowedDistance = 0.0;
664
            }
665
        } else {
666
            for (int i = 0; i < yTheoreticalDistance.length; i++) {
667
                if (Math.abs(yTheoreticalDistance[i]) < threshold) {
668
                    yTheoreticalDistance[i] = 0.0;
669
                }
670
            }
671
        }
672
    }
673
    
674
    /**
675
     * Prepares the estimation for horizontal speed of the player based on various conditions.
676
     *
677
     * @param forceSetOnGround Whether to forcibly consider the ground status of the player (despite being off ground).
678
     * @param forceSetOffGround Whether to forcibly ignore the ground status of the player (despite being on the ground).
679
     * @param isNormalOrPacketSplitMove Whether this movement has been corrected due to a faulty PlayerMoveEvent or is normal (no correction needed)
680
     *
681
     * @return hAllowedDistance, hDistanceAboveLimit
682
     */
683
    private double[] prepareSpeedEstimation(final PlayerLocation from, final PlayerLocation to, final IPlayerData pData, final Player player,
684
                                            final MovingData data, final PlayerMoveData thisMove, final PlayerMoveData lastMove,
685
                                            final boolean fromOnGround, final boolean toOnGround, final boolean debug,
686
                                            final boolean isNormalOrPacketSplitMove, boolean forceSetOnGround, boolean forceSetOffGround) {
687
        double hDistanceAboveLimit;
688
        //////////////////////////
689
        // Early return(s)      //
690
        //////////////////////////
691
        if (!isNormalOrPacketSplitMove) {
692
            // Bukkit-based split move: predicting the next speed is not possible due to coordinates not being reported correctly by Bukkit (and without ProtocolLib, it's nearly impossible to achieve precision here)
693
            thisMove.xAllowedDistance = thisMove.xDistance;
694
            thisMove.zAllowedDistance = thisMove.zDistance;
695
            thisMove.hAllowedDistance = thisMove.hDistance;
696
            hDistanceAboveLimit = 0.0;
697
            return new double[]{thisMove.hAllowedDistance, hDistanceAboveLimit};
698
        }
699
        
700
        boolean onGround = PhysicsGroundResolver.resolvePhysicsOnGround(from, thisMove, lastMove, forceSetOnGround, forceSetOffGround);
701
        /* All moves are assumed to be predictable, unless there are technical limitations / bugs / glitches that we cannot solve */
702
        boolean isPredictable;
703
        //////////////////////////////////////////////////////////////
704
        // Estimate the horizontal speed (per-move distance check)  //                      
705
        //////////////////////////////////////////////////////////////
706
        // Determine inertia and acceleration to calculate speed with.
707
        // Only check using the 'from' position because it is the current location of the player (NMS-wise)
708
        if (from.isInWater()) {
709
            data.nextInertia = Bridge1_13.isSwimming(player) ? Magic.HORIZONTAL_SWIMMING_INERTIA : Magic.WATER_HORIZONTAL_INERTIA;
710
            /* Per-tick speed gain. */
711
            float acceleration = Magic.LIQUID_ACCELERATION;
712
            float StriderLevel = attributeAccess.getHandle().getWaterMovementEfficiency(player);
713
            if (!onGround) {
714
                StriderLevel *= Magic.STRIDER_OFF_GROUND_MULTIPLIER;
715
            }
716
            if (StriderLevel > 0.0) {
717
                // (Less speed conservation (or in other words, more friction))
718
                data.nextInertia += (0.54600006f - data.nextInertia) * StriderLevel / (pData.getClientVersion().isAtMost(ClientVersion.V_1_20_6) ? 3.0f : 1.0f); // Mojang removed this / by 3 in 1.21 and switched to the WATER_MOVEMENT_EFFICIENCY attribute
719
                // (More per-tick speed gain)
720
                acceleration += (data.walkSpeed - acceleration) * StriderLevel / (pData.getClientVersion().isAtMost(ClientVersion.V_1_20_6) ? 3.0f : 1.0f);
721
            }
722
            if (!Double.isInfinite(Bridge1_13.getDolphinGraceAmplifier(player))) {
723
                // (Much more speed conservation (or in other words, much less friction))
724
                // (Overrides swimming AND depth strider friction)
725
                data.nextInertia = Magic.DOLPHIN_GRACE_INERTIA;
726
            }
727
            // Run through all operations
728
            isPredictable = estimateNextSpeed(player, acceleration, pData, tags, to, from, debug, fromOnGround, toOnGround, onGround, forceSetOffGround);
729
        }
730
        else if (from.isInLava()) {
731
            data.nextInertia = Magic.LAVA_HORIZONTAL_INERTIA;
732
            isPredictable = estimateNextSpeed(player, Magic.LIQUID_ACCELERATION, pData, tags, to, from, debug, fromOnGround, toOnGround, onGround, forceSetOffGround);
733
        }
734
        else {
735
            data.nextInertia = onGround ? data.nextFrictionHorizontal * Magic.AIR_HORIZONTAL_INERTIA : Magic.AIR_HORIZONTAL_INERTIA;
736
            // 1.12 (and below) clients will use cubed inertia, not cubed friction here. The difference isn't significant except for blocking speed and bunnyhopping on soul sand, which are both slower on 1.8
737
            float frictionMediumFactor = pData.getClientVersion().isAtLeast(ClientVersion.V_1_13) ? data.nextFrictionHorizontal : data.nextFrictionHorizontal * Magic.AIR_HORIZONTAL_INERTIA;
738
            float acceleration = onGround ? data.walkSpeed * ((pData.getClientVersion().isAtLeast(ClientVersion.V_1_13) ? Magic.DEFAULT_FRICTION_CUBED : Magic.DEFAULT_FRICTION_MULTIPLIED_BY_091_CUBED) / (frictionMediumFactor * frictionMediumFactor * frictionMediumFactor)) : Magic.AIR_ACCELERATION;
739
            if (pData.isSprinting()) {
740
                // (We don't use the attribute here due to desync issues, just detect when the player is sprinting and apply the multiplier manually)
741
                acceleration += acceleration * 0.3f; // 0.3 is the effective sprinting speed (EntityLiving).
742
            }
743
            isPredictable = estimateNextSpeed(player, acceleration, pData, tags, to, from, debug, fromOnGround, toOnGround, onGround, forceSetOffGround);
744
        }
745
        
746
        /////////////////////////////////////////////////
747
        // Set the combined allowed horizontal speed   //
748
        /////////////////////////////////////////////////
749
        thisMove.hAllowedDistance = MathUtil.dist(thisMove.xAllowedDistance, thisMove.zAllowedDistance);
750
        
751
        ////////////////////////
752
        // Calculate offsets  //
753
        ////////////////////////
754
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
755
        if (isPredictable) {
756
            hDistanceAboveLimit = handlePredictableMove(thisMove, cc.survivalFlyStrictHorizontal); 
757
        }
758
        else hDistanceAboveLimit = handleUnpredictableMove(thisMove, cc.survivalFlyStrictHorizontal);
759
        hDistanceAboveLimit = applyEdgeCornerResolvedTolerance(thisMove, hDistanceAboveLimit, cc.survivalFlyStrictHorizontal);
760
        hDistanceAboveLimit = HiddenMotionReconstructor.applyEdgeSneakBypass(player, pData, data, from, lastMove, thisMove, hDistanceAboveLimit, tags);
761
        if (hDistanceAboveLimit > 0.0) {
762
            tags.add("hdistrel");
763
            if (debug) {
764
                player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] hdistrel: predicted=" + StringUtil.fdec6.format(thisMove.hAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.hDistance));
765
            }
766
        }
767
        return new double[]{thisMove.hAllowedDistance, hDistanceAboveLimit};
768
    }
769
    
770
    
771
    /**
772
     * Estimates the player's horizontal speed based on the given data and Minecraft's movement logic.<br>
773
     * Order of operations is essential. Do not shuffle things around unless you know what you're doing.
774
     *<hr>
775
     * <p>Order of client-movement operations (as per MCP tool):
776
     * <ul>
777
     * <li>{@code EntityLiving.tick()}
778
     * <li>{@code [Entity].tick()}
779
     *   <ul>
780
     *     <li>{@code baseTick()}
781
     *     <li>{@code updateInWaterStateAndDoFluidPushing()}
782
     *   </ul>
783
     * <li>{@code EntityLiving.aiStep()}
784
     *   <ul>
785
     *     <li>Decrease the jump delay counter if it is active ({@code this.noJumpDelay > 0})
786
     *     <li>Negligible speed reset (0.003)
787
     *     <li>Apply liquid motion if the player is pressing the space bar (vertical axis only)
788
     *     <li>Multiply the input vector (= the vector containing the player's WASD impulse) by 0.98</li>
789
     *     <li>{@code jumpFromGround()} is called if the player is on ground and has pressed the space bar.
790
     *   </ul>
791
     * <li>Begin executing {@code EntityLiving.travel()} ({@code In EntityLiving.aiStep()})<p> <b>Note:</b> from 1.21.2 and onwards, Mojang split the travel function into different helper methods to better
792
     * distinguish between media (we now have {@code travelInAir()}, {@code travelInFluid()} and {@code travelFallFlying()})</p><br>
793
     *   <ul>
794
     *     <li>Invoke {@code [Entity].moveRelative()} (WASD inputs are transformed to acceleration vectors, call {@code getInputVector()})
795
     *     <li>If not in liquid or gliding, limit motion when on climbable via {@code handleRelativeFrictionAndCalculateMovement()}
796
     *     <li>Invoke {@code [Entity].move()}
797
     *       <ul>
798
     *         <li>Apply stuck speed multiplier
799
     *         <li>Invoke {@code EntityHuman.maybeBackOffFromEdge()}
800
     *         <li>Handle wall collisions via {@code Entity.collide()} (speed is cut-off and the collision flag is set) <br>
801
     * <em><strong>After {@code [Entity].collide()} is called, the next movement is prepared. Every subsequent operation 
802
     *           applies to the next move for the client.</strong></em>
803
     *         <li>Set the supporting block data; call {@code setGroundWithMovement()}</li>
804
     *         <li>Handle horizontal collisions (speed is now reset to 0 on the colliding axis); <em><strong>NCP STARTS ESTIMATING FROM HERE ON (!)</strong></em>
805
     *         <li>Invoke {@code checkFallDamage()} (apply fluid pushing if not previously in water)
806
     *         <li>Invoke {@code [Block].updateEntityAfterFallOn()} (for slime bouncing)
807
     *         <li>Invoke {@code [Block].stepOn()} (for slime blocks only, currently)
808
     *         <li>Invoke {@code tryCheckInsideBlocks()} (for honey blocks slide-down and bubble columns)
809
     *         <li>Invoke {@code [Entity].getBlockSpeedFactor()} (soul sand, honey blocks)
810
     *       </ul>
811
     *   </ul>
812
     * <li>Complete executing {@code EntityLiving.travel()}
813
     *   <ul>
814
     *     <li>{@code handleRelativeFrictionAndCalculateMovement()} (for snow climbing speed)
815
     *     <li>Apply gravity.
816
     *     <li>Apply friction/inertia.
817
     *     <li>Handle fluid falling function if in liquid (vertical axis only)
818
     *     <li>Handle jumping out of liquids (vertical axis only)
819
     *     <li>Handle entity pushing
820
     *   </ul>
821
     * <li>Complete {@code EntityLiving.aiStep()}
822
     * <li>Complete {@code EntityLiving.tick()}
823
     * <li> Finally, send movement to the server.
824
     * </ul>
825
     * <hr>
826
     * The logic is split into different sections:
827
     * <li>Firstly, we perform some preliminary checks to quickly catch specific ways of cheating.</li>
828
     * <li>If no blatant cheating is detected, the movement speed estimate is calculated starting from the horizontal collision reset, calculating the client’s actions on the next move and then processing the actions performed prior.</li>
829
     * <li>If needed, the player's impulse (acceleration) is brute-forced (see {@link BridgeMisc#isWASDImpulseKnown(Player)}</li>
830
     * @return {@code true}, if the move has been deemed to be predictable. {@code false} otherwise.
831
     */
832
    private boolean estimateNextSpeed(final Player player, float movementSpeed, final IPlayerData pData, final Collection<String> tags,
833
                                      final PlayerLocation to, final PlayerLocation from, final boolean debug,
834
                                      final boolean fromOnGround, final boolean toOnGround, final boolean onGround, boolean forceSetOffGround) {
835
        /*
836
         * TODO: This is a mess, clean-up pending / needed. Get rid of code duplication
837
         */
838
        final MovingData data = pData.getGenericInstance(MovingData.class);
839
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
840
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
841
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
842
        final boolean envelopeFromOnGround = PhysicsGroundResolver.resolveEnvelopeFromOnGround(thisMove, fromOnGround);
843
        final boolean envelopeToOnGround = PhysicsGroundResolver.resolveEnvelopeToOnGround(thisMove, toOnGround);
844
        
845
        // Reference commit of this piece of code: https://github.com/NoCheatPlus/NoCheatPlus/commit/1c024c072c9f6ebe5371c113916c6a2414e635a6
846
        /////////////////////////////////////////////////////
847
        // Horizontal push/pull is put on top priority     //
848
        /////////////////////////////////////////////////////
849
        // With the current implementation, the prediction will run for the axis even if a push/pull is detected on it.
850
        // We'll have to somehow skip predicting that specfic axis, but it requires some refactoring to do it.
851
        // This is not ideal, but it's better than flagging players for being pushed by pistons.
852
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
853
        boolean xPush = false;
854
        boolean zPush = false;
855
        // TODO: Get rid of this config option. Why would someone want to disable piston push detection and cause false positives?
856
        if (cc.trackBlockMove) {
857
            if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, thisMove.xDistance < 0.0 ? Direction.X_NEG : Direction.X_POS, 0.05)) {
858
                tags.add("blkmv_x");
859
                xPush = true;
860
            }
861
            if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, thisMove.zDistance < 0.0 ? Direction.Z_NEG : Direction.Z_POS, 0.05)) {
862
                tags.add("blkmv_z");
863
                zPush = true;
864
            }
865
            if (xPush && zPush) {
866
                thisMove.xAllowedDistance = thisMove.xDistance;
867
                thisMove.zAllowedDistance = thisMove.zDistance;
868
                // A push/pull happened on both axes, no need to continue the prediction.
869
                return true;
870
            }
871
        }
872
        
873
        ////////////////////////////////////////////////////////
874
        // Test for specific cheat implementation types first //
875
        ////////////////////////////////////////////////////////
876
        // These checks don't need specific data from the prediction, so they can be performed ex-ante and save some performance.
877
        if (cData.isHackingRI) {
878
            tags.add("noslowpacket");
879
            cData.isHackingRI = false;
880
            Improbable.check(player, (float) thisMove.hDistance, System.currentTimeMillis(), "moving.survivalfly.noslow", pData);
881
            data.resetHorizontalData();
882
            return true;
883
        }
884
        // If impulses don't need to be inferred from the prediction, illegal sprinting checks can be performed here.
885
        if (BridgeMisc.isWASDImpulseKnown(player) && pData.isSprinting()
886
            && (data.input.getForwardDir() != ForwardDirection.FORWARD && data.input.getStrafeDir() != StrafeDirection.NONE && data.input.getForwardDir() != ForwardDirection.NONE
887
                || player.getFoodLevel() <= 5) // must be checked here as well (besides on toggle sprinting) because players will immediately lose the ability to sprint if food level drops below 5
888
            ) { 
889
            // || inputs[i].getForward() < 0.8 // hasEnoughImpulseToStartSprinting, in LocalPlayer,java -> aiStep()
890
            tags.add("illegalsprint");
891
            Improbable.check(player, (float) thisMove.hDistance, System.currentTimeMillis(), "moving.survivalfly.illegalsprint", pData);
892
            data.resetHorizontalData();
893
            return true;
894
        }
895
        
896
        
897
        //////////////////////////////////////////
898
        // Setup theoretical inputs, if needed  //
899
        //////////////////////////////////////////
900
        PlayerKeyboardInput input = null; // Precise input
901
        PlayerKeyboardInput[] theorInputs = null; // All brute-forced inputs.
902
        /* Index for accessing speed combinations. If you need to perform an operation for/with each speed, set it to 0 and loop until it 8 */
903
        int i = 0;
904
        if (BridgeMisc.isWASDImpulseKnown(player)) {
905
            // Clone for safety as this data is consumed. 
906
            input = data.input.clone();
907
            // In EntityLiving.java -> aiStep() the game multiplies input values by 0.98 before dispatching them to the travel() function.
908
            input.operationToInt(0.98f, 0.98f, 1);
909
            // From KeyboardInput.java and LocalPlayer.java (MC-Reborn tool)
910
            // Sneaking and item-use aren't directly applied to the player's motion. The game reduces the force of the input instead.
911
            if (pData.isInCrouchingPose()) {
912
                // Note that this is determined by player poses, not shift key presses.
913
                input.operationToInt(attributeAccess.getHandle().getPlayerSneakingFactor(player), attributeAccess.getHandle().getPlayerSneakingFactor(player), 1);
914
                tags.add("crouching");
915
            }
916
            // From LocalPlayer.java.aiStep()
917
            if (BridgeMisc.isSlowedDownByUsingAnItem(player)) {
918
                input.operationToInt(Magic.USING_ITEM_MULTIPLIER, Magic.USING_ITEM_MULTIPLIER, 1);
919
                tags.add("usingitem");
920
            }
921
        }
922
        else {
923
            // The input's matrix is: NONE, LEFT, RIGHT, FORWARD, FORWARD_LEFT, FORWARD_RIGHT, BACKWARD, BACKWARD_LEFT, BACKWARD_RIGHT.
924
            theorInputs = new PlayerKeyboardInput[9];
925
            // Loop through all combinations otherwise.
926
            for (int strafe = -1; strafe <= 1; strafe++) {
927
                for (int forward = -1; forward <= 1; forward++) {
928
                    // Multiply all 
929
                    theorInputs[i] = new PlayerKeyboardInput(strafe * 0.98f, forward * 0.98f);
930
                    i++;
931
                }
932
            }
933
            if (pData.isInCrouchingPose()) {
934
                tags.add("crouching");
935
                for (i = 0; i < 9; i++) {
936
                    // Multiply all combinations
937
                    theorInputs[i].operationToInt(attributeAccess.getHandle().getPlayerSneakingFactor(player), attributeAccess.getHandle().getPlayerSneakingFactor(player), 1);
938
                }
939
            }
940
            // From LocalPlayer.java.aiStep()
941
            if (BridgeMisc.isSlowedDownByUsingAnItem(player)) {
942
                tags.add("usingitem");
943
                for (i = 0; i < 9; i++) {
944
                    theorInputs[i].operationToInt(Magic.USING_ITEM_MULTIPLIER, Magic.USING_ITEM_MULTIPLIER, 1);
945
                }
946
            }
947
        }
948
949
        /*
950
         * This bit of vertical distance computation is needed for the supporting block mechanism, which needs Minecraft-calculated on-ground status.
951
         * Normally, these would be computed at the same time, however, since NCP handles horizontal and vertical speed estimation separately, we need to duplicate this bit of code here.
952
         * TODO: Unify predictions somehow.
953
         */
954
        final boolean slimeYbcChain = from.isOnBouncyBlock();
955
        double yDistanceBeforeCollide;
956
        if (slimeYbcChain) {
957
            yDistanceBeforeCollide = lastMove.motionY;
958
        }
959
        else {
960
            yDistanceBeforeCollide = lastMove.toIsValid ? lastMove.yDistance : 0.0;
961
            if (lastMove.yCorrectedDistancePre != 0.0) {
962
                yDistanceBeforeCollide = lastMove.yCorrectedDistancePre;
963
            }
964
            if (envelopeToOnGround) yDistanceBeforeCollide = 0.0;
965
        }
966
        // Refine yDistanceBeforeCollide (seed set above for edge-sneak momentum carry).
967
        if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) {
968
            if (data.lastStuckInBlockVertical != 1.0) {
969
                yDistanceBeforeCollide = 0.0;
970
            }
971
        }
972
        if (!pData.isShiftKeyPressed()) {
973
            if (yDistanceBeforeCollide < 0.0 && thisMove.yDistance >= 0.0) {
974
                if (from.isOnBouncyBlock()) {
975
                    // The effect works by inverting the distance.
976
                    // Beds have a weaker bounce effect (BedBlock.java).
977
                    yDistanceBeforeCollide = from.isOnSlimeBlock() ? -yDistanceBeforeCollide : -yDistanceBeforeCollide * 0.66;
978
                }
979
            }
980
        }
981
        if (lastMove.from.inWater) {
982
            yDistanceBeforeCollide *= data.lastFrictionVertical;
983
            if (BridgeMisc.hasGravity(player)) {
984
                // Legacy: clients older than 1.13 have some kind of gravity effect applied to them even in liquids, if they don't press the space bar.
985
                // On 1.13 and above, only friction gets applied, resulting in a much slower descending speed when not pressing the space bar pressed.
986
                if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
987
                    yDistanceBeforeCollide -= Magic.LEGACY_LIQUID_GRAVITY;
988
                }
989
                else {
990
                    // In 1.13 the gravity effect in liquids was removed and this function got added.
991
                    Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yDistanceBeforeCollide <= 0.0, new Vector(0.0, yDistanceBeforeCollide, 0.0), cData.wasSprinting);
992
                    yDistanceBeforeCollide = fluidFallingAdjustMovement.getY();
993
                }
994
            }
995
        }
996
        else if (lastMove.from.inLava) {
997
            if (data.lastFrictionVertical != Magic.LAVA_VERTICAL_INERTIA) {
998
                yDistanceBeforeCollide *= data.lastFrictionVertical;
999
                if (BridgeMisc.hasGravity(player)) {
1000
                    if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
1001
                        yDistanceBeforeCollide -= Magic.LEGACY_LIQUID_GRAVITY;
1002
                    }
1003
                    else {
1004
                        // In 1.13 the gravity effect in liquids was removed and this function got added.
1005
                        Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yDistanceBeforeCollide <= 0.0, new Vector(0.0, yDistanceBeforeCollide, 0.0), cData.wasSprinting);
1006
                        yDistanceBeforeCollide = fluidFallingAdjustMovement.getY();
1007
                    }
1008
                }
1009
            }
1010
            else {
1011
                yDistanceBeforeCollide *= data.lastFrictionVertical;
1012
            }
1013
            if (data.lastGravity != 0.0) {
1014
                yDistanceBeforeCollide += -data.lastGravity / 4.0;
1015
            }
1016
        }
1017
        else {
1018
            // Air motion
1019
            if (cData.wasLevitating) {
1020
                yDistanceBeforeCollide += (0.05 * data.lastLevitationLevel - yDistanceBeforeCollide) * 0.2;
1021
            }
1022
            else {
1023
                yDistanceBeforeCollide -= data.lastGravity;
1024
            }
1025
            yDistanceBeforeCollide *= data.lastFrictionVertical;
1026
        }
1027
        if (from.isInLiquid() && verticalLiquidPushComponent != 0.0) {
1028
            // Liquid vertical push component calculated in hdistrel.
1029
            yDistanceBeforeCollide += verticalLiquidPushComponent;
1030
        }
1031
        if (from.isInWater() && pData.getClientVersion().isHigherThan(ClientVersion.V_1_12_2)) {
1032
            // *----------LocalPlayer.aiStep(), goDownInWater()----------*
1033
            if (pData.isShiftKeyPressed()) {
1034
                yDistanceBeforeCollide -= Magic.LIQUID_SPEED_GAIN;
1035
            }
1036
        }
1037
        if (Math.abs(yDistanceBeforeCollide) < (pData.getClientVersion().isHigherThan(ClientVersion.V_1_12_2) ? 0.003 : 0.005)) yDistanceBeforeCollide = 0.0;
1038
        if (!from.isInLiquid() && from.isOnClimbable() && from.canClimbUp(data.liftOffEnvelope.getMaxJumpHeight(data.jumpAmplifier))) {
1039
            // Should replicate the condition: !this.getInBlockState().is(Blocks.SCAFFOLDING)
1040
            final Material typeId = from.getBlockType();
1041
            final long theseFlags = BlockFlags.getBlockFlags(typeId);
1042
            yDistanceBeforeCollide = Math.max(yDistanceBeforeCollide, -Magic.CLIMBABLE_MAX_SPEED);
1043
            if (yDistanceBeforeCollide < 0.0 && pData.isShiftKeyPressed() && from.getEntity() instanceof Player
1044
                && (theseFlags & BlockFlags.F_SCAFFOLDING) == 0 && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
1045
                yDistanceBeforeCollide = 0.0;
1046
            }
1047
        }
1048
        thisMove.motionY = yDistanceBeforeCollide;
1049
        //End of yDistanceBeforeCollide getter
1050
1051
        //////////////////////////////////////
1052
        // Next move for the client         //
1053
        //////////////////////////////////////
1054
        /*
1055
          All moves are assumed to be predictable, unless we explicitly state otherwise. 
1056
          A move is considered to be predictable if there aren't any particular client-side issues/limitations that prevent it.
1057
         */
1058
        boolean isPredictable = true;
1059
        final boolean edgeSneakNow = !player.isFlying() && pData.isShiftKeyPressed() && from.isAboveGround() && yDistanceBeforeCollide <= 0.0;
1060
        // Initialize horizontal momentum; at an edge use stored internal momentum while still shift-sneaking.
1061
        if (lastMove.toIsValid) {
1062
            if (edgeSneakNow && lastMove.edgeBackoffApplied) {
1063
                thisMove.xAllowedDistance = lastMove.motionX;
1064
                thisMove.zAllowedDistance = lastMove.motionZ;
1065
            } else if (HiddenMotionReconstructor.shouldUseEdgeHiddenCarry(edgeSneakNow, from, yDistanceBeforeCollide, lastMove)) {
1066
                thisMove.xAllowedDistance = lastMove.motionX;
1067
                thisMove.zAllowedDistance = lastMove.motionZ;
1068
            } else {
1069
                thisMove.xAllowedDistance = lastMove.xDistance;
1070
                thisMove.zAllowedDistance = lastMove.zDistance;
1071
            }
1072
            // Edge: packet may show 0 on a clipped axis while internal momentum (motionX/Z) is still large.
1073
            if (lastMove.edgeBackoffApplied && lastMove.edgeAxisClamped) {
1074
                final double pktSuppressH = HiddenMotionReconstructor.packetSuppressThresholdH(pData);
1075
                if (Math.abs(lastMove.xDistance) < pktSuppressH) {
1076
                    thisMove.xAllowedDistance = lastMove.motionX;
1077
                }
1078
                if (Math.abs(lastMove.zDistance) < pktSuppressH) {
1079
                    thisMove.zAllowedDistance = lastMove.motionZ;
1080
                }
1081
            }
1082
        } else {
1083
            thisMove.xAllowedDistance = 0.0;
1084
            thisMove.zAllowedDistance = 0.0;
1085
        }
1086
        // !lastMove.possibleStopMotion is dummy flag to flip false on failure and retry
1087
        // Check if there had been a hidden move on the prebious tick(s) due to 0.03 threshold.
1088
        // If so, the initial speed is initialized by the corrected distance. xDistance/zDistance would report a wrong speed value.
1089
        if (!lastMove.possibleStopMotion && (lastMove.xCorrectedDistancePre != 0.0 || lastMove.zCorrectedDistancePre != 0.0)) {
1090
            // Edge-sneak internal momentum overrides generic hidden pre-correct when still at an edge.
1091
            if (!(edgeSneakNow && lastMove.edgeBackoffApplied)) {
1092
                thisMove.xAllowedDistance = lastMove.xCorrectedDistancePre;
1093
                thisMove.zAllowedDistance = lastMove.zCorrectedDistancePre;
1094
                // Distinguish source of CorrectedDistance that only come from hidden move not from stop motion
1095
                if (lastMove.hiddenDistanceIndex != -1) {
1096
                    thisMove.possibleStopMotion = true;
1097
                }
1098
                tags.add("hidden");
1099
            }
1100
        }
1101
        // Stuck speed reset (the game resets momentum each tick the player is in a stuck-speed block)
1102
        if (data.lastStuckInBlockHorizontal != 1.0) {
1103
            if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) { // (Vanilla check, don't ask)
1104
                // Throttle speed if stuck in.
1105
                thisMove.xAllowedDistance = thisMove.zAllowedDistance = 0.0;
1106
            }
1107
        }
1108
        // If the player collided with something on the previous tick, start with 0 momentum now.
1109
        doWallCollision(lastMove, thisMove);
1110
        // (The game calls a checkFallDamage() function, which, as you can imagine, handles fall damage. But also handles liquids' flow force, thus we need to apply this 2 times.)
1111
        if (from.isInWater() && !lastMove.from.inWater) {
1112
            Vector liquidFlowVector = from.getLiquidPushingVector(thisMove.xAllowedDistance, thisMove.zAllowedDistance, BlockFlags.F_WATER);
1113
            thisMove.xAllowedDistance += liquidFlowVector.getX();
1114
            thisMove.zAllowedDistance += liquidFlowVector.getZ();
1115
        }
1116
        // Slime stepOn: throttle momentum carried from last tick (client stepOn at end of last tick).
1117
        if (from.isOnSlimeBlock() && thisMove.hasClientFromOnGround && thisMove.clientFromOnGround && Math.abs(lastMove.motionY) < 0.1 && !pData.isShiftKeyPressed()) {
1118
            double slimeStepMul = 0.4 + Math.abs(lastMove.motionY) * 0.2;
1119
            thisMove.xAllowedDistance *= slimeStepMul;
1120
            thisMove.zAllowedDistance *= slimeStepMul;
1121
            tags.add("slime_step");
1122
        }
1123
        // Sliding speed (honey block)
1124
        if (from.isSlidingDown()) { // TODO: lastMove.from.slideDown or something?
1125
            if (lastMove.yDistance < -Magic.SLIDE_START_AT_VERTICAL_MOTION_THRESHOLD) {
1126
                thisMove.xAllowedDistance *= -Magic.SLIDE_SPEED_THROTTLE / lastMove.yDistance;
1127
                thisMove.zAllowedDistance *= -Magic.SLIDE_SPEED_THROTTLE / lastMove.yDistance;
1128
            }
1129
        }
1130
        
1131
        // Block speed
1132
        thisMove.xAllowedDistance *= (double) data.nextBlockSpeedMultiplier;
1133
        thisMove.zAllowedDistance *= (double) data.nextBlockSpeedMultiplier;
1134
        // Friction next, with special case for riptide at the start of the movement tick (when the riptide move is "unified" and not split into two updates; friction of the next move is used here)
1135
        boolean newFriction = false;
1136
        if (lastMove.tridentRelease.decide() && lastMove.toIsValid) {
1137
            final PlayerMoveData secondLastMove = data.playerMoves.getSecondPastMove();
1138
            if (lastMove.from.onGround || secondLastMove.tridentRelease.decideOptimistically() 
1139
                || (secondLastMove.toIsValid && secondLastMove.yDistance <= 0.0 && (secondLastMove.from.onGround || secondLastMove.fromLostGround))) {
1140
                newFriction = true;
1141
            }
1142
        }
1143
        thisMove.xAllowedDistance *= (double) (newFriction ? data.nextInertia : data.lastInertia);
1144
        thisMove.zAllowedDistance *= (double) (newFriction ? data.nextInertia : data.lastInertia);
1145
        // Apply entity-pushing speed
1146
        // From Entity.java.push()
1147
        // The entity's location is in the past.
1148
        if (player.getGameMode() != BridgeMisc.GAME_MODE_SPECTATOR) { // noPhysics check in vanilla.
1149
            Vector push = from.doPush(new Vector(thisMove.xAllowedDistance, 0.0, thisMove.zAllowedDistance));
1150
            thisMove.xAllowedDistance = push.getX();
1151
            thisMove.zAllowedDistance = push.getZ();
1152
            if (data.lastCollidingEntitiesLocations != null && !data.lastCollidingEntitiesLocations.isEmpty()) {
1153
                isPredictable = false;
1154
            }
1155
        }
1156
1157
1158
1159
        //////////////////////////////////
1160
        // Last move for the client     //
1161
        //////////////////////////////////
1162
        // See CombinedListener.java for more details
1163
        // This is done before liquid pushing...
1164
        if (thisMove.hasAttackSlowDown) {
1165
            thisMove.zAllowedDistance *= Magic.ATTACK_SLOWDOWN;
1166
            thisMove.xAllowedDistance *= Magic.ATTACK_SLOWDOWN;
1167
        }
1168
        // Apply liquid pushing speed (2nd call).
1169
        if (from.isInLiquid()) {
1170
            Vector liquidFlowVector = from.getLiquidPushingVector(thisMove.xAllowedDistance, thisMove.zAllowedDistance, from.isInWater() ? BlockFlags.F_WATER : BlockFlags.F_LAVA);
1171
            thisMove.xAllowedDistance += liquidFlowVector.getX();
1172
            verticalLiquidPushComponent = liquidFlowVector.getY();
1173
            thisMove.zAllowedDistance += liquidFlowVector.getZ();
1174
        }
1175
        // Before calculating the acceleration, check if momentum is below the negligible speed threshold and cancel it.
1176
        checkNegligibleMomentum(pData, thisMove);
1177
        // Sprint-jumping...
1178
        // IMPORTANT NOTE: when working **exclusively** with rotations (like in the following cases), you must use the TO location, not the FROM one, as TO contains the most recent rotation. Using FROM lags behind a few ticks, causing false positives when switching looking direction.
1179
        if (PhysicsEnvelope.isBunnyhop(from, to, pData, envelopeFromOnGround, envelopeToOnGround, player, forceSetOffGround)) {
1180
            thisMove.xAllowedDistance += (double) (-TrigUtil.sin(to.getYaw() * TrigUtil.toRadians) * Magic.BUNNYHOP_BOOST);
1181
            thisMove.zAllowedDistance += (double) (TrigUtil.cos(to.getYaw() * TrigUtil.toRadians) * Magic.BUNNYHOP_BOOST);
1182
            thisMove.bunnyHop = true;
1183
            tags.add("bunnyhop");
1184
        }
1185
1186
        // *--------------------------------------------------------------------------------------------------------------------*
1187
        // *--------- If we know the player's impulse, brute-forcing acceleration and everything after it isn't needed ---------* 
1188
        // *--------------------------------------------------------------------------------------------------------------------*
1189
        if (BridgeMisc.isWASDImpulseKnown(player)) {
1190
            // Transform the input into an acceleration vector (getInputVector, entity.java)
1191
            double inputSq = MathUtil.square((double) input.getStrafe()) + MathUtil.square((double) input.getForward()); // Cast to a double because the client does it
1192
            if (inputSq >= 1.0E-7) {
1193
                if (inputSq > 1.0) {
1194
                    double inputForce = Math.sqrt(inputSq);
1195
                    if (inputForce < 1.0E-4) {
1196
                        // Not enough force, reset.
1197
                        input.operationToInt(0, 0, 0);
1198
                    }
1199
                    // Normalize
1200
                    else input.operationToInt(inputForce, inputForce, 2);
1201
                }
1202
                // Multiply the input by movement speed.
1203
                input.operationToInt(movementSpeed, movementSpeed, 1);
1204
                // The acceleration vector is added to the current momentum...
1205
                thisMove.xAllowedDistance += input.getStrafe() * (double) TrigUtil.cos(to.getYaw() * TrigUtil.toRadians) - input.getForward() * (double) TrigUtil.sin(to.getYaw() * TrigUtil.toRadians);
1206
                thisMove.zAllowedDistance += input.getForward() * (double) TrigUtil.cos(to.getYaw() * TrigUtil.toRadians) + input.getStrafe() * (double) TrigUtil.sin(to.getYaw() * TrigUtil.toRadians);
1207
            }
1208
            // Minecraft caps horizontal speed if on climbable, for whatever reason.
1209
            if (from.isOnClimbable() && !from.isInLiquid()) {
1210
                //data.clearActiveHorVel(); // Might want to clear ALL horizontal vel.
1211
                thisMove.xAllowedDistance = MathUtil.clamp(thisMove.xAllowedDistance, -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1212
                thisMove.zAllowedDistance = MathUtil.clamp(thisMove.zAllowedDistance, -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1213
            }
1214
            // Stuck-speed multiplier.
1215
            if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
1216
                thisMove.xAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
1217
                thisMove.zAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
1218
            }
1219
            // Riptide works by propelling the player after releasing the trident (the effect only pushes the player, unless is on ground)
1220
            if (thisMove.tridentRelease.decideOptimistically()) {
1221
                thisMove.tridentRelease = AlmostBoolean.YES;
1222
                Vector riptideVelocity = to.getRiptideVelocity(onGround);
1223
                thisMove.xAllowedDistance += riptideVelocity.getX();
1224
                thisMove.zAllowedDistance += riptideVelocity.getZ();
1225
            }
1226
            // Lunging forward if applicable: the effect only adds the lunging motion on the current delta.
1227
            // TODO: TOTALLY RANDOM PLACEMENT !
1228
            // The addition is called on any left click, provided the player has a Spear in hand with Lunge enchant.
1229
            // NOTE: Does not need to be brute forced, since lunging is supported only by clients that can send WASD inputs.
1230
            if (thisMove.lungingForward) {
1231
                Vector lungeVelocity = to.tryApplyLungingMotion(); // Use to as we're working with rotations here
1232
                thisMove.xAllowedDistance += lungeVelocity.getX();
1233
                thisMove.zAllowedDistance += lungeVelocity.getZ();
1234
            }
1235
            // Try to back off players from edges, if sneaking.
1236
            // NOTE: this is after the riptiding propelling force.
1237
            // NOTE: here the game uses isShiftKeyDown (so this is shifting not sneaking, using Bukkit's isShift is correct)
1238
            if (edgeSneakNow) {
1239
                thisMove.edgeBackoffApplied = true;
1240
                final double preEdgeX = thisMove.xAllowedDistance;
1241
                final double preEdgeZ = thisMove.zAllowedDistance;
1242
                final double pktSuppressH = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1243
                        ? Magic.Minecraft_minMoveSqDistance_legacy : Math.sqrt(Magic.Minecraft_minMoveSqDist_modern);
1244
                Vector backOff = from.maybeBackOffFromEdge(new Vector(preEdgeX, yDistanceBeforeCollide, preEdgeZ));
1245
                HiddenMotionReconstructor.storeEdgeHiddenMotion(thisMove, preEdgeX, preEdgeZ, backOff.getX(), backOff.getZ(), pktSuppressH);
1246
                thisMove.xAllowedDistance = backOff.getX();
1247
                thisMove.zAllowedDistance = backOff.getZ();
1248
                if (!thisMove.edgeAxisClamped) {
1249
                    thisMove.motionX = thisMove.xDistance;
1250
                    thisMove.motionZ = thisMove.zDistance;
1251
                }
1252
            }
1253
            // Collision next.
1254
            // NOTE: Passing the unchecked y-distance is fine in this case. Vertical collision is checked with vdistrel (just separately).
1255
            // TODO: Perhaps after this use collisionVector to store onGround? Also can not restore minecraft ground state with step and jump movement(like stairs)!
1256
            Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, yDistanceBeforeCollide, thisMove.zAllowedDistance), onGround, from.getBoundingBox());
1257
            // Set the supporting block data.
1258
            if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1259
                // This is called with setOnGroundWithMovement at the same time of setting the ground flag but before setting the horizontal collision flags.
1260
                // NOTE: here the bounding box of the TO location must be used.
1261
                pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(thisMove.xAllowedDistance, thisMove.yDistance, thisMove.zAllowedDistance), to.getBoundingBox(), yDistanceBeforeCollide < 0.0 && yDistanceBeforeCollide != collisionVector.getY()));
1262
            }
1263
            // NOTE: Collision flags must be set before setting speed in thisMove.
1264
            thisMove.collideX = thisMove.xAllowedDistance != collisionVector.getX();
1265
            thisMove.collideZ = thisMove.zAllowedDistance != collisionVector.getZ();
1266
            thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
1267
            // Set speed.
1268
            thisMove.xAllowedDistance = collisionVector.getX();
1269
            thisMove.zAllowedDistance = collisionVector.getZ();
1270
            // More edge data...
1271
            thisMove.negligibleHorizontalCollision = thisMove.collidesHorizontally && CollisionUtil.isHorizontalCollisionNegligible(new Vector(thisMove.xAllowedDistance, thisMove.yDistance, thisMove.zAllowedDistance), to, input.getStrafe(), input.getForward());
1272
            // Check for block push.
1273
            // TODO: Unoptimized insertion point... Waste of resources to just override everything at the end. See note at the start of the method.
1274
            if (xPush) {
1275
               thisMove.xAllowedDistance = thisMove.xDistance;
1276
            }
1277
            if (zPush) {
1278
                thisMove.zAllowedDistance = thisMove.zDistance;
1279
            }
1280
            //////////////
1281
            // Set data //
1282
            //////////////
1283
            thisMove.hasImpulse = AlmostBoolean.match(input.getForwardDir() != ForwardDirection.NONE || input.getStrafeDir() != StrafeDirection.NONE);
1284
            thisMove.strafeImpulse = input.getStrafeDir();
1285
            thisMove.forwardImpulse = input.getForwardDir();
1286
            if (debug) {
1287
                player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] (postPredict) Direction: " + input.getForwardDir() +" | "+ input.getStrafeDir());
1288
            }
1289
            // If-else instead of an early return... Matter of preference. This makes code slightly easier to look at, as it avoids yet another indentation
1290
            return isPredictable;
1291
        }
1292
        
1293
        // *----------------------------------------------------------------------------------------------------*
1294
        // *-------Can't know / read player inputs, loop through everything after looping the acceleration------*
1295
        // *----------------------------------------------------------------------------------------------------*
1296
        // Transform theoretical inputs into acceleration vectors (getInputVector, entity.java)
1297
        float sinYaw = TrigUtil.sin(to.getYaw() * TrigUtil.toRadians);
1298
        float cosYaw = TrigUtil.cos(to.getYaw() * TrigUtil.toRadians);
1299
        /* List of predicted X distances. Size is the number of possible inputs (left/right/backwards/forward etc...) */
1300
        double[] xTheoreticalDistance = new double[9];
1301
        /* To keep track which theoretical speed would result in a collision on the X axis */
1302
        boolean[] collideX = new boolean[9];
1303
        /* List of predicted Z distances. Size is the number of possible inputs (left/right/backwards/forward etc...) */
1304
        double[] zTheoreticalDistance = new double[9];
1305
        /* To keep track which theoretical speed would result in a collision on the Z axis */
1306
        boolean[] collideZ = new boolean[9];
1307
        /* To keep track which theoretical speed would result in a collision on the Y axis */
1308
        boolean[] collideY = new boolean[9];
1309
        for (i = 0; i < 9; i++) {
1310
            // Each slot in the array is initialized with the same momentum first.
1311
            xTheoreticalDistance[i] = thisMove.xAllowedDistance;
1312
            zTheoreticalDistance[i] = thisMove.zAllowedDistance;
1313
            // Then we proceed to compute all possible accelerations with all theoretical inputs and apply subsequent modifiers.
1314
            double inputSq = MathUtil.square((double)theorInputs[i].getStrafe()) + MathUtil.square((double)theorInputs[i].getForward());
1315
            if (inputSq >= 1.0E-7) {
1316
                if (inputSq > 1.0) {
1317
                    double inputForce = Math.sqrt(inputSq);
1318
                    if (inputForce < 1.0E-4) {
1319
                        theorInputs[i].operationToInt(0, 0, 0);
1320
                    }
1321
                    else {
1322
                        theorInputs[i].operationToInt(inputForce, inputForce, 2);
1323
                    }
1324
                }
1325
                theorInputs[i].operationToInt(movementSpeed, movementSpeed, 1);
1326
                xTheoreticalDistance[i] += theorInputs[i].getStrafe() * (double)cosYaw - theorInputs[i].getForward() * (double)sinYaw;
1327
                zTheoreticalDistance[i] += theorInputs[i].getForward() * (double)cosYaw + theorInputs[i].getStrafe() * (double)sinYaw;
1328
            }
1329
        }
1330
        // All later modifiers get applied to each theoretical speed...
1331
        if (from.isOnClimbable() && !from.isInLiquid()) {
1332
            for (i = 0; i < 9; i++) {
1333
                xTheoreticalDistance[i] = MathUtil.clamp(xTheoreticalDistance[i], -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1334
                zTheoreticalDistance[i] = MathUtil.clamp(zTheoreticalDistance[i], -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1335
            }
1336
        }
1337
        if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
1338
            for (i = 0; i < 9; i++) {
1339
                xTheoreticalDistance[i] *= (double) data.nextStuckInBlockHorizontal;
1340
                zTheoreticalDistance[i] *= (double) data.nextStuckInBlockHorizontal;
1341
            }
1342
        }
1343
        if (thisMove.tridentRelease.decideOptimistically()) {
1344
            thisMove.tridentRelease = AlmostBoolean.YES;
1345
            Vector riptideVelocity = to.getRiptideVelocity(onGround);
1346
            for (i = 0; i < 9; i++) {
1347
                xTheoreticalDistance[i] += riptideVelocity.getX();
1348
                zTheoreticalDistance[i] += riptideVelocity.getZ();
1349
            }
1350
        }
1351
        
1352
        double[] xMotionBeforeEdge = new double[9];
1353
        double[] zMotionBeforeEdge = new double[9];
1354
        double[] xBackOffAfterEdge = new double[9];
1355
        double[] zBackOffAfterEdge = new double[9];
1356
        for (i = 0; i < 9; i++) {
1357
            xMotionBeforeEdge[i] = xTheoreticalDistance[i];
1358
            zMotionBeforeEdge[i] = zTheoreticalDistance[i];
1359
            xBackOffAfterEdge[i] = xTheoreticalDistance[i];
1360
            zBackOffAfterEdge[i] = zTheoreticalDistance[i];
1361
        }        
1362
        
1363
        final double hiddenThresholdSqBrute = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1364
                ? Magic.Minecraft_minMoveSqDistance_legacy : Magic.Minecraft_minMoveSqDist_modern;
1365
        final double hiddenThresholdHBrute = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1366
                ? hiddenThresholdSqBrute : Math.sqrt(hiddenThresholdSqBrute);
1367
        boolean activeCornerClamp = false;
1368
        if (edgeSneakNow) {
1369
            thisMove.edgeBackoffApplied = true;
1370
            // Single backoff probe replaces back-to-back edgeStillClampsCorner + edgeStillClamps on the same vector.
1371
            final Vector seedBackOff = from.maybeBackOffFromEdge(new Vector(thisMove.xAllowedDistance, yDistanceBeforeCollide, thisMove.zAllowedDistance));
1372
            activeCornerClamp = HiddenMotionReconstructor.edgeStillClampsCornerCached(thisMove.xAllowedDistance,
1373
                    thisMove.zAllowedDistance, seedBackOff.getX(), seedBackOff.getZ());
1374
            if (!HiddenMotionReconstructor.edgeStillClampsCached(thisMove.xAllowedDistance,
1375
                    thisMove.zAllowedDistance, seedBackOff.getX(), seedBackOff.getZ())) {
1376
                thisMove.motionX = thisMove.xDistance;
1377
                thisMove.motionZ = thisMove.zDistance;
1378
            }
1379
            for (i = 0; i < 9; i++) {
1380
                // TODO: Optimize. Brute forcing collisions with all 9 speed combinations will tank performance.
1381
                final double preEdgeX = xTheoreticalDistance[i];
1382
                final double preEdgeZ = zTheoreticalDistance[i];
1383
                Vector backOff = from.maybeBackOffFromEdge(new Vector(preEdgeX, yDistanceBeforeCollide, preEdgeZ));
1384
                HiddenMotionReconstructor.storeEdgeHiddenMotionCandidate(thisMove, xMotionBeforeEdge, zMotionBeforeEdge, i, preEdgeX, preEdgeZ, backOff.getX(), backOff.getZ(),
1385
                        thisMove.xDistance, thisMove.zDistance, hiddenThresholdHBrute);
1386
                xBackOffAfterEdge[i] = backOff.getX();
1387
                zBackOffAfterEdge[i] = backOff.getZ();
1388
                xTheoreticalDistance[i] = backOff.getX();
1389
                zTheoreticalDistance[i] = backOff.getZ();
1390
            }
1391
            if (HiddenMotionReconstructor.anyEdgeCandidateClipped(xMotionBeforeEdge, zMotionBeforeEdge, xBackOffAfterEdge, zBackOffAfterEdge)) {
1392
                thisMove.edgeAxisClamped = true;
1393
            }
1394
        }
1395
        // TODO: Optimize. Brute forcing collisions with all 9 speed combinations will tank performance.
1396
        // TODO: If sprinting detected correctly, Might not need to loop backward, only 6 left to check
1397
        for (i = 0; i < 9; i++) {
1398
            // TODO: Perhaps after this use collisionVector to store onGround?
1399
            Vector collisionVector = from.collide(new Vector(xTheoreticalDistance[i], yDistanceBeforeCollide, zTheoreticalDistance[i]), onGround, from.getBoundingBox());
1400
            if (xTheoreticalDistance[i] != collisionVector.getX()) {
1401
                // This theoretical speed would result in a collision. Remember it.
1402
                collideX[i] = true;
1403
            }
1404
            if (yDistanceBeforeCollide != collisionVector.getY()) {
1405
                // This theoretical speed would result in a collision. Remember it.
1406
                // Only needed for supporting block detection.
1407
                collideY[i] = true;
1408
            }
1409
            if (zTheoreticalDistance[i] != collisionVector.getZ()) {
1410
                // This theoretical speed would result in a collision. Remember it.
1411
                collideZ[i] = true;
1412
            }
1413
            xTheoreticalDistance[i] = collisionVector.getX();
1414
            zTheoreticalDistance[i] = collisionVector.getZ();
1415
            if (lastMove.xCorrectedDistancePost != 0 || lastMove.zCorrectedDistancePost != 0) {
1416
                xTheoreticalDistance[i] += lastMove.xCorrectedDistancePost;
1417
                zTheoreticalDistance[i] += lastMove.zCorrectedDistancePost;
1418
            }
1419
        }
1420
        // Check for block push.
1421
        // TODO: Unoptimized insertion point... Waste of resources to just override everything at the end. See note at the start of the method.
1422
        if (xPush) {
1423
            for (i = 0; i < 9; i++) {
1424
                // Override all theoretical speeds.
1425
                xTheoreticalDistance[i] = thisMove.xDistance;
1426
            }
1427
        }
1428
        if (zPush) {
1429
            for (i = 0; i < 9; i++) {
1430
                zTheoreticalDistance[i] = thisMove.zDistance;
1431
            }
1432
        }
1433
        /////////////////////////////////////////////////////////////////////////////
1434
        // Determine which (and IF) theoretical speed should be set in this move   //
1435
        /////////////////////////////////////////////////////////////////////////////
1436
        /*
1437
           True, if the offset between predicted and actual speed is smaller than the accuracy margin (0.0001).
1438
        */
1439
        boolean found = false;
1440
        /*
1441
           True will check if BOTH axis have an offset smaller than 0.0001 (against strafe-like cheats and anything of that sort that relies on the specific direction of the move).
1442
           Otherwise, only the combined horizontal distance will be checked against the offset.
1443
        */
1444
        boolean strict = cc.survivalFlyStrictHorizontal;
1445
        final double hiddenThresholdSq = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1446
                ? Magic.Minecraft_minMoveSqDistance_legacy : Magic.Minecraft_minMoveSqDist_modern;
1447
        final double hiddenThresholdH = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1448
                ? hiddenThresholdSq : Math.sqrt(hiddenThresholdSq);
1449
        final boolean yDistanceSuppressed = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1450
                ? thisMove.yDistance < hiddenThresholdSq : thisMove.yDistance * thisMove.yDistance < hiddenThresholdSq;
1451
        for (i = 0; i < 9; i++) {
1452
            // If this theoretical candidate results in a post-collision horizontal
1453
            // displacement smaller than the client's packet-suppression threshold,
1454
            // it means that the client may have omitted (suppressed) the intermediate
1455
            // packet(s) for this motion. Record the WASD candidate index so it can
1456
            // be used as a seed for the hidden-tick reconstructor.
1457
            // Note: if multiple candidates match, the last matching index will
1458
            // overwrite earlier ones (thisMove.hiddenDistanceIndex holds only one
1459
            // seed candidate).
1460
            if (!collideX[i] && !collideZ[i] && yDistanceSuppressed) {
1461
                final double postH = MathUtil.dist(xTheoreticalDistance[i], zTheoreticalDistance[i]);
1462
                final boolean suppressedPost = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1463
                        ? postH < hiddenThresholdSq : postH * postH < hiddenThresholdSq;
1464
                final boolean edgeSuppressedPacket = thisMove.edgeBackoffApplied
1465
                        && (thisMove.hDistance < hiddenThresholdH
1466
                                || Math.abs(thisMove.xDistance) < hiddenThresholdH
1467
                                || Math.abs(thisMove.zDistance) < hiddenThresholdH)
1468
                        && i < xBackOffAfterEdge.length
1469
                        && (xBackOffAfterEdge[i] != xMotionBeforeEdge[i] || zBackOffAfterEdge[i] != zMotionBeforeEdge[i]);
1470
                if (suppressedPost || edgeSuppressedPacket) {
1471
                    thisMove.hiddenDistanceIndex = i;
1472
                }
1473
            }
1474
            if (strict) {
1475
                if (MathUtil.almostEqual(thisMove.xDistance, xTheoreticalDistance[i], Magic.PREDICTION_EPSILON) 
1476
                    && MathUtil.almostEqual(thisMove.zDistance, zTheoreticalDistance[i], Magic.PREDICTION_EPSILON)) {
1477
                    found = true;
1478
                }
1479
            }
1480
            else {
1481
                double theoreticalHDistance = MathUtil.dist(xTheoreticalDistance[i], zTheoreticalDistance[i]);
1482
                if (MathUtil.almostEqual(theoreticalHDistance, thisMove.hDistance, Magic.PREDICTION_EPSILON)) {
1483
                    found = true;
1484
                }
1485
            }
1486
            
1487
            /*
1488
               True it will force a violation even if there's a matching theoretical speed.
1489
             */
1490
            boolean forceViolation = false;
1491
            if (found) {
1492
                // These checks must be performed ex-post because they rely on data that is set after the prediction.
1493
                if (pData.isSprinting() 
1494
                    && (theorInputs[i].getForwardDir() != ForwardDirection.FORWARD && theorInputs[i].getStrafeDir() != StrafeDirection.NONE && theorInputs[i].getForwardDir() != ForwardDirection.NONE
1495
                        || player.getFoodLevel() <= 5)) { 
1496
                    tags.add("illegalsprint");
1497
                    Improbable.check(player, (float) thisMove.hDistance, System.currentTimeMillis(), "moving.survivalfly.illegalsprint", pData);
1498
                    // Keep looping
1499
                    forceViolation = true;
1500
                }
1501
                if (thisMove.possibleStopMotion) {
1502
                    double[] result = HiddenMotionReconstructor.simulateStoppingMotion(sinYaw, cosYaw, theorInputs[i], data, pData, from, to, onGround, player.isFlying(), yDistanceBeforeCollide);
1503
                    thisMove.xCorrectedDistancePre = result[0];
1504
                    thisMove.zCorrectedDistancePre = result[1];
1505
                }
1506
                if (!forceViolation) {
1507
                    // Found a candidate to set in this move; these collisions are valid.
1508
                    // Also set the supporting block.
1509
                    if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1510
                        pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to.getBoundingBox(), collideY[i] && yDistanceBeforeCollide < 0.0));
1511
                    }
1512
                    thisMove.collideX = collideX[i];
1513
                    thisMove.collideZ = collideZ[i];
1514
                    thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
1515
                    thisMove.negligibleHorizontalCollision = thisMove.collidesHorizontally && CollisionUtil.isHorizontalCollisionNegligible(new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to, theorInputs[i].getStrafe(), theorInputs[i].getForward());
1516
                    break;
1517
                }
1518
            }
1519
        }
1520
        if (!found) {
1521
            // If we couldn't find a direct match for the observed movement, but
1522
            // we previously recorded a candidate that would have been suppressed
1523
            // by the client (hiddenDistanceIndex), attempt to reconstruct the
1524
            // missing intermediate ticks. The reconstructor is seeded with the
1525
            // selected WASD candidate and its post-collision displacement and
1526
            // will return cumulative displacements for the hidden ticks. Those
1527
            // results are then folded into the theoretical distances or stored
1528
            // in the "corrected distance" fields for use across ticks.
1529
            int hiddenSeed = thisMove.hiddenDistanceIndex;
1530
            if (hiddenSeed < 0 && thisMove.edgeBackoffApplied
1531
                    && (lastMove.edgeAxisClamped || lastMove.edgeCornerResolved
1532
                            || lastMove.xCorrectedDistancePost != 0.0 || lastMove.zCorrectedDistancePost != 0.0
1533
                            || Math.abs(thisMove.xDistance) < hiddenThresholdH
1534
                            || Math.abs(thisMove.zDistance) < hiddenThresholdH)) {
1535
                hiddenSeed = MathUtil.findClosestHorizontalIndex(xTheoreticalDistance, zTheoreticalDistance, thisMove.xDistance, thisMove.zDistance);
1536
            }
1537
            if (hiddenSeed >= 0 && !thisMove.edgeBackoffApplied) {
1538
                final int hiddenResolved = tryFoldHiddenTickExplanation(player, hiddenSeed, xTheoreticalDistance, zTheoreticalDistance,
1539
                        xMotionBeforeEdge, zMotionBeforeEdge, theorInputs, sinYaw, cosYaw, movementSpeed, data, pData, from, onGround,
1540
                        yDistanceBeforeCollide, strict, tags);
1541
                if (hiddenResolved >= 0) {
1542
                    i = hiddenResolved;
1543
                    found = true;
1544
                    if (thisMove.edgeBackoffApplied) {
1545
                        tags.add("edge_hidden");
1546
                    }
1547
                }
1548
            }
1549
            else if (lastMove.hiddenDistanceIndex != -1 && (lastMove.xCorrectedDistancePre != 0 || lastMove.zCorrectedDistancePre != 0)) {
1550
                // Hidden move was found and sum match lastMove but the component of the sum didn't right as there another direction that also make the sum correct!
1551
                isPredictable = false;
1552
            }
1553
            if (!found && thisMove.edgeBackoffApplied && activeCornerClamp) {
1554
                double cornerRefSpeed = thisMove.hDistance;
1555
                for (int c = 0; c < 9; c++) {
1556
                    cornerRefSpeed = Math.max(cornerRefSpeed, MathUtil.dist(xTheoreticalDistance[c], zTheoreticalDistance[c]));
1557
                    cornerRefSpeed = Math.max(cornerRefSpeed, MathUtil.dist(xBackOffAfterEdge[c], zBackOffAfterEdge[c]));
1558
                }
1559
                final double cornerMatchTolerance = HiddenMotionReconstructor.edgeCornerMatchTolerance(cornerRefSpeed);
1560
                final int cornerIdx = HiddenMotionReconstructor.findBestEdgeCornerCandidate(thisMove.xDistance, thisMove.zDistance, thisMove.hDistance,
1561
                        xTheoreticalDistance, zTheoreticalDistance, xBackOffAfterEdge, zBackOffAfterEdge, strict, cornerMatchTolerance);
1562
                if (cornerIdx >= 0) {
1563
                    i = cornerIdx;
1564
                    found = true;
1565
                    isPredictable = false;
1566
                    thisMove.edgeCornerResolved = true;
1567
                    tags.add("edge_corner");
1568
                    if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1569
                        pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to.getBoundingBox(), collideY[i] && yDistanceBeforeCollide < 0.0));
1570
                    }
1571
                    thisMove.collideX = collideX[i];
1572
                    thisMove.collideZ = collideZ[i];
1573
                    thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
1574
                    thisMove.negligibleHorizontalCollision = thisMove.collidesHorizontally && CollisionUtil.isHorizontalCollisionNegligible(new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to, theorInputs[i].getStrafe(), theorInputs[i].getForward());
1575
                }
1576
            }
1577
            // Note: Always set no matter what, prevent desync
1578
            if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1579
                pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(thisMove.xDistance, thisMove.yDistance, thisMove.zDistance), to.getBoundingBox(), from.isOnGround()));
1580
            }
1581
        }
1582
        //////////////////////////////////////////////////////////////
1583
        // Finish. Check if the move had been predictable at all    //
1584
        //////////////////////////////////////////////////////////////
1585
        /* The index representing the input associated with the pair of speed to set in this move. */
1586
        int indexPair = i;
1587
        int xIdx = -1;
1588
        int zIdx = -1;
1589
        if (indexPair >= 9) {
1590
            // Cheating: prevent an index out of bounds (we couldn't find the correct pair of speed to set)
1591
            indexPair = 4;
1592
        }
1593
        // If the move is unpredictable, the x/z speeds cannot be associated to a specific input, thus we set them independently.
1594
        // TODO: How can we know the impulse if the move is uncertain? ...
1595
        if (!isPredictable) {
1596
            // In this case, instead of setting the predicted speed with the smallest delta from the actual speed (0.0001), we select the speed that is closest to the current one, effectively allowing for the maximum predicted speed (just limits speed then).
1597
            if (thisMove.edgeBackoffApplied && activeCornerClamp) {
1598
                // Corner: both axes clipped on the actual seed; one combined candidate for packet match.
1599
                xIdx = MathUtil.findClosestHorizontalIndex(xTheoreticalDistance, zTheoreticalDistance, thisMove.xDistance, thisMove.zDistance);
1600
                zIdx = xIdx;
1601
            } else {
1602
                xIdx = MathUtil.findClosestIndex(xTheoreticalDistance, thisMove.xDistance);
1603
                zIdx = MathUtil.findClosestIndex(zTheoreticalDistance, thisMove.zDistance);
1604
            }
1605
        }
1606
        final int motionIdx = !isPredictable ? xIdx : indexPair;
1607
        int momentumStorageIdx = motionIdx;
1608
        if (thisMove.edgeBackoffApplied) {
1609
            if (found && indexPair >= 0 && indexPair < 9) {
1610
                momentumStorageIdx = indexPair;
1611
            } else if (thisMove.hiddenDistanceIndex >= 0) {
1612
                momentumStorageIdx = thisMove.hiddenDistanceIndex;
1613
            } else {
1614
                final int edgeMomIdx = HiddenMotionReconstructor.findBestEdgeMomentumIndex(
1615
                        xMotionBeforeEdge, zMotionBeforeEdge, xBackOffAfterEdge, zBackOffAfterEdge, motionIdx);
1616
                if (edgeMomIdx >= 0) {
1617
                    momentumStorageIdx = edgeMomIdx;
1618
                }
1619
            }
1620
            // Use cached back-off arrays from the brute loop above instead of recomputing.
1621
            final boolean selectedClipped = momentumStorageIdx >= 0 && momentumStorageIdx < 9
1622
                    && HiddenMotionReconstructor.edgeStillClampsCached(xMotionBeforeEdge[momentumStorageIdx],
1623
                            zMotionBeforeEdge[momentumStorageIdx], xBackOffAfterEdge[momentumStorageIdx], zBackOffAfterEdge[momentumStorageIdx]);
1624
            thisMove.edgeAxisClamped = selectedClipped;
1625
            thisMove.edgeCornerClamp = selectedClipped && momentumStorageIdx >= 0 && momentumStorageIdx < 9
1626
                    && HiddenMotionReconstructor.edgeStillClampsCornerCached(xMotionBeforeEdge[momentumStorageIdx],
1627
                            zMotionBeforeEdge[momentumStorageIdx], xBackOffAfterEdge[momentumStorageIdx], zBackOffAfterEdge[momentumStorageIdx]);
1628
        }
1629
        if (thisMove.edgeBackoffApplied && thisMove.edgeAxisClamped) {
1630
            thisMove.motionX = xMotionBeforeEdge[momentumStorageIdx];
1631
            thisMove.motionZ = zMotionBeforeEdge[momentumStorageIdx];
1632
        } else if (!thisMove.edgeBackoffApplied) {
1633
            thisMove.motionX = xMotionBeforeEdge[motionIdx];
1634
            thisMove.motionZ = zMotionBeforeEdge[motionIdx];
1635
        } else {
1636
            thisMove.motionX = thisMove.xDistance;
1637
            thisMove.motionZ = thisMove.zDistance;
1638
        }
1639
        // Done, set in this move.
1640
        thisMove.xAllowedDistance = xTheoreticalDistance[motionIdx];
1641
        thisMove.zAllowedDistance = zTheoreticalDistance[motionIdx];
1642
        thisMove.hasImpulse = !isPredictable ? AlmostBoolean.MAYBE // We don't know the direction in this case.
1643
                              : AlmostBoolean.match(theorInputs[indexPair].getForwardDir() != ForwardDirection.NONE || theorInputs[indexPair].getStrafeDir() != StrafeDirection.NONE);
1644
        thisMove.strafeImpulse = theorInputs[motionIdx].getStrafeDir();
1645
        thisMove.forwardImpulse = theorInputs[motionIdx].getForwardDir();
1646
        if (debug) {
1647
            player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] (postPredict) " + (!isPredictable ? "Uncertain" : "Predicted") + " direction: " + theorInputs[motionIdx].getForwardDir() +" | "+ theorInputs[motionIdx].getStrafeDir());
1648
        }
1649
        return isPredictable;
1650
    }
1651
    
1652
    
1653
    /**
1654
     * Reconstruct suppressed ticks (including {@code maybeBackOffFromEdge} in the simulator) and fold into prediction.
1655
     *
1656
     * @return Matched candidate index, or {@code -1}.
1657
     */
1658
    private int tryFoldHiddenTickExplanation(final Player player, final int hiddenSeed, final double[] xTheoreticalDistance, final double[] zTheoreticalDistance,
1659
            final double[] xMotionBeforeEdge, final double[] zMotionBeforeEdge, final PlayerKeyboardInput[] theorInputs, final float sinYaw,
1660
            final float cosYaw, final float movementSpeed, final MovingData data, final IPlayerData pData, final PlayerLocation from,
1661
            final boolean onGround, final double yDistanceBeforeCollide, final boolean strict, final Collection<String> tags) {
1662
        if (hiddenSeed < 0 || hiddenSeed >= xTheoreticalDistance.length) {
1663
            return -1;
1664
        }
1665
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
1666
        final double seedX = xMotionBeforeEdge[hiddenSeed];
1667
        final double seedZ = zMotionBeforeEdge[hiddenSeed];
1668
        final double[] result = HiddenMotionReconstructor.findBestHiddenTickExplanation(sinYaw, cosYaw, movementSpeed, theorInputs[hiddenSeed],
1669
                seedX, seedZ, data, pData, from, pData.isInCrouchingPose(),
1670
                attributeAccess.getHandle().getPlayerSneakingFactor(player), BridgeMisc.isSlowedDownByUsingAnItem(player), onGround,
1671
                xTheoreticalDistance[hiddenSeed], zTheoreticalDistance[hiddenSeed], yDistanceBeforeCollide, player.isFlying());
1672
        if (thisMove.xDistance == 0 && thisMove.zDistance == 0) {
1673
            thisMove.xCorrectedDistancePost = xTheoreticalDistance[hiddenSeed];
1674
            thisMove.zCorrectedDistancePost = zTheoreticalDistance[hiddenSeed];
1675
            xTheoreticalDistance[hiddenSeed] = 0.0;
1676
            zTheoreticalDistance[hiddenSeed] = 0.0;
1677
            tags.add("hdistzero");
1678
        } else {
1679
            xTheoreticalDistance[hiddenSeed] += result[0];
1680
            zTheoreticalDistance[hiddenSeed] += result[1];
1681
        }
1682
        final double matchTol = thisMove.edgeBackoffApplied
1683
                ? HiddenMotionReconstructor.edgeCornerMatchTolerance(Math.max(thisMove.hDistance, MathUtil.dist(seedX, seedZ)))
1684
                : Magic.PREDICTION_EPSILON;
1685
        if (strict) {
1686
            if (MathUtil.almostEqual(thisMove.xDistance, xTheoreticalDistance[hiddenSeed], matchTol)
1687
                    && MathUtil.almostEqual(thisMove.zDistance, zTheoreticalDistance[hiddenSeed], matchTol)) {
1688
                thisMove.xCorrectedDistancePre = result[0];
1689
                thisMove.zCorrectedDistancePre = result[1];
1690
                return hiddenSeed;
1691
            }
1692
        } else {
1693
            final double theoreticalHDistance = MathUtil.dist(xTheoreticalDistance[hiddenSeed], zTheoreticalDistance[hiddenSeed]);
1694
            if (MathUtil.almostEqual(theoreticalHDistance, thisMove.hDistance, matchTol)) {
1695
                return hiddenSeed;
1696
            }
1697
        }
1698
        return -1;
1699
    }
1700
1701
    /**
1702
     * After a corner candidate is applied, allow only a speed-scaled offset vs the matched allowed distance
1703
     */
1704
    private static double applyEdgeCornerResolvedTolerance(final PlayerMoveData thisMove, final double hDistanceAboveLimit, final boolean strict) {
1705
        if (hDistanceAboveLimit <= 0.0 || !thisMove.edgeCornerResolved) {
1706
            return hDistanceAboveLimit;
1707
        }
1708
        final double tolerance = HiddenMotionReconstructor.edgeCornerMatchTolerance(
1709
                Math.max(thisMove.hAllowedDistance, thisMove.hDistance));
1710
        if (strict) {
1711
            if (Math.abs(thisMove.xDistance - thisMove.xAllowedDistance) <= tolerance
1712
                    && Math.abs(thisMove.zDistance - thisMove.zAllowedDistance) <= tolerance) {
1713
                return 0.0;
1714
            }
1715
        } else if (Math.abs(thisMove.hDistance - thisMove.hAllowedDistance) <= tolerance) {
1716
            return 0.0;
1717
        }
1718
        return hDistanceAboveLimit;
1719
    }
1720
1721
    /**
1722
     * In case we couldn't predict speed, just ensure that actual speed is below what we estimated.
1723
     * This allows for minor deviations below the allowed speed limit, thus players/cheaters may execute movements 
1724
     * that are technically invalid, but do not provide any [significant] gameplay advantage.
1725
     *
1726
     * @param thisMove
1727
     * @param strict If true, only the combined speed (hDistance) is required to be below the allowed one.
1728
     * @return The horizontal distance above limit.
1729
     */
1730
    private double handleUnpredictableMove(final PlayerMoveData thisMove, boolean strict) {
1731
        double hDistanceAboveLimit = 0.0;
1732
        double offset = thisMove.hDistance - thisMove.hAllowedDistance;
1733
        if (strict) {
1734
            // both axes must be below-allowed distance if strict.
1735
            if (MathUtil.exceedsAllowedDistance(thisMove.xDistance, thisMove.xAllowedDistance) 
1736
                || MathUtil.exceedsAllowedDistance(thisMove.zDistance, thisMove.zAllowedDistance)) {
1737
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1738
            }
1739
        } 
1740
        else {
1741
            // Otherwise, only the combined distance needs to be below the limit.
1742
            if (thisMove.hDistance > thisMove.hAllowedDistance) {
1743
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1744
            }
1745
        }
1746
        return hDistanceAboveLimit;
1747
    }
1748
    
1749
    
1750
    /**
1751
     * If the move was predictable, ensure that the difference between actual and allowed speed is below the {@link Magic#PREDICTION_EPSILON}.
1752
     * 
1753
     * @param thisMove
1754
     * @param strict If true, the offset of each axis (x/z) must be below the epsilon, otherwise, only the combined offset (h) will be checked.
1755
     *               Needed against cheats that rely on the specific direction of a move.
1756
     * @return The horizontal distance above limit.
1757
     */
1758
    private double handlePredictableMove(final PlayerMoveData thisMove, boolean strict) {
1759
        double hDistanceAboveLimit = 0.0;
1760
        double offset = thisMove.hDistance - thisMove.hAllowedDistance;
1761
        if (strict) {
1762
            if (!MathUtil.isOffsetWithinPredictionEpsilon(thisMove.xDistance, thisMove.xAllowedDistance) 
1763
                || !MathUtil.isOffsetWithinPredictionEpsilon(thisMove.zDistance, thisMove.zAllowedDistance)) {
1764
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1765
            }
1766
        } 
1767
        else {
1768
            if (!MathUtil.isOffsetWithinPredictionEpsilon(thisMove.hDistance, thisMove.hAllowedDistance)) {
1769
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1770
            }
1771
        }
1772
        return hDistanceAboveLimit;
1773
    }
1774
    
1775
    private enum Operation {
1776
        SET,
1777
        ADD,
1778
        SUBTRACT,
1779
        MULTIPLY,
1780
        DIVIDE
1781
    }
1782
    private void configVerticalAllowedValue(PlayerMoveData thisMove, double[] yTheoreticalDistance, double value, Operation operation) {
1783
        final boolean direct = yTheoreticalDistance == null;
1784
        if (direct) {
1785
            switch (operation) {
1786
            case ADD:
1787
                thisMove.yAllowedDistance += value;
1788
                break;
1789
            case DIVIDE:
1790
                thisMove.yAllowedDistance /= value;
1791
                break;
1792
            case MULTIPLY:
1793
                thisMove.yAllowedDistance *= value;
1794
                break;
1795
            case SET:
1796
                thisMove.yAllowedDistance = value;
1797
                break;
1798
            case SUBTRACT:
1799
                thisMove.yAllowedDistance -= value;
1800
                break;
1801
            }
1802
        } else {
1803
            switch (operation) {
1804
            case ADD:
1805
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1806
                    yTheoreticalDistance[i] += value;
1807
                }
1808
                break;
1809
            case DIVIDE:
1810
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1811
                    yTheoreticalDistance[i] /= value;
1812
                }
1813
                break;
1814
            case MULTIPLY:
1815
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1816
                    yTheoreticalDistance[i] *= value;
1817
                }
1818
                break;
1819
            case SET:
1820
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1821
                    yTheoreticalDistance[i] = value;
1822
                }
1823
                break;
1824
            case SUBTRACT:
1825
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1826
                    yTheoreticalDistance[i] -= value;
1827
                }
1828
                break;
1829
            }
1830
        }
1831
    }
1832
1833
    /**
1834
     * Relative (to workarounds) vertical distance checking.
1835
     *
1836
     * @param forceResetMomentum    Whether the check should start with 0.0 speed on applying air friction.
1837
     * @param useBlockChangeTracker
1838
     */
1839
    private double[] vDistRel(final Player player, final PlayerLocation from,
1840
                              final boolean fromOnGround, final boolean resetFrom, final PlayerLocation to,
1841
                              final boolean toOnGround, final boolean resetTo,
1842
                              final double yDistance, boolean isNormalOrPacketSplitMove,
1843
                              final PlayerMoveData lastMove,
1844
                              final MovingData data, final IPlayerData pData,
1845
                              boolean forceResetMomentum, final boolean debug, boolean useBlockChangeTracker) {
1846
        double yDistanceAboveLimit = 0.0;
1847
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
1848
        final boolean yDirectionSwitch = lastMove.toIsValid && lastMove.yDistance != yDistance && (yDistance <= 0.0 && lastMove.yDistance >= 0.0 || yDistance >= 0.0 && lastMove.yDistance <= 0.0);
1849
        /* Not on ground, not on climbable, not in liquids, not in stuck-speed, no lostground (...) */
1850
        final boolean fullyInAir = !thisMove.touchedGroundWorkaround && !resetFrom && !resetTo;
1851
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
1852
        final boolean onGround = PhysicsGroundResolver.resolvePhysicsOnGround(from, thisMove, lastMove, false, false);
1853
        /*
1854
         * 1: Simulate the reset of speed that the client should have sent to the server.
1855
         * [Client lands on the ground but does not come to a "rest" on top of the block (and thus, reset the vertical speed), instead they'll immediately descend right after, but with speed that is still based on a previous move of 0.0]
1856
         * Can be noticed when stepping down stair of slabs or noob-towering upwards.
1857
         * See: https://gyazo.com/0f748030296aebc0484564629abe6864
1858
         * After interpolating the ground status, notice how the player immediately proceeds to descend with speed as if they actually landed on the ground with the previous move (-0.0784)
1859
         */
1860
        // After completing a "touch-down" (toOnGround), the next move should always come *from* ground
1861
        // Thus, such cases can be generalised by checking for negative motion and last move landing on ground, but this move not *starting back* from a ground position.
1862
        boolean touchDownIsLost = !thisMove.couldStepUp && thisMove.yDistance < 0.0 && (lastMove.toLostGround || lastMove.to.onGround) && !thisMove.from.onGround;
1863
        
1864
        ///////////////////////////////////////////////////
1865
        // Vertical push/pull is put on top priority     //
1866
        ///////////////////////////////////////////////////
1867
        if (useBlockChangeTracker) {
1868
            double[] res = getVerticalBlockMoveResult(thisMove.yDistance, from, to, data);
1869
            if (res != null) {
1870
                thisMove.yAllowedDistance = res[0];
1871
                yDistanceAboveLimit = res[1];
1872
                // Nothing else to do here; allow the movement as-is.
1873
                return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1874
            }
1875
        }
1876
        
1877
        
1878
        //////////////////////////////////////////////////////////////////////////////
1879
        // Test if this movement can fit into any pre-set envelope                  //
1880
        //////////////////////////////////////////////////////////////////////////////
1881
        // NOTE: order of these checks should be from most common to least common.
1882
        if (thisMove.yDistance == 0.0 && fromOnGround) {
1883
            // No vertical motion in this case, as the player is on ground.
1884
            thisMove.yAllowedDistance = 0.0;
1885
            yDistanceAboveLimit = 0.0;
1886
            tags.add("onground_env");
1887
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1888
        }
1889
        if (PhysicsEnvelope.isJumpMotion(from, to, player, fromOnGround, toOnGround, true)) {
1890
            // After stepping, jumping comes second.
1891
            // Players can jump anywhere through air, so this must be checked before the actual prediction.
1892
            thisMove.yAllowedDistance = thisMove.yDistance;
1893
            yDistanceAboveLimit = 0.0;
1894
            thisMove.isJump = true;
1895
            data.jumpDelay = Magic.MAX_JUMP_DELAY;
1896
            tags.add("jump_env");
1897
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1898
        }
1899
        if (PhysicsEnvelope.isStepUpByNCPDefinition(pData, fromOnGround, toOnGround, player)) {
1900
            // Players can step anywhere, both in liquid and in air, so this must be checked before everything else.
1901
            thisMove.yAllowedDistance = thisMove.yDistance;
1902
            yDistanceAboveLimit = 0.0;
1903
            thisMove.isStepUp = true;
1904
            tags.add("step_env");
1905
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1906
        }
1907
        if (onGround && thisMove.tridentRelease.decideOptimistically() && thisMove.multiMoveCount == 1 
1908
            && !isNormalOrPacketSplitMove && MathUtil.isOffsetWithinPredictionEpsilon(thisMove.yDistance, Magic.RIPTIDE_ON_GROUND_MOVE)) {
1909
            // Riptide from ground launch at the end of the movement stack; the actual riptide push will come next. Allowed this move as-is.
1910
            // IMPORTANT NOTE: this move specifically will always cause NCP to fire a Bukkit-based split move on the first split move, no matter what.
1911
            thisMove.yAllowedDistance = Magic.RIPTIDE_ON_GROUND_MOVE;
1912
            // The riptide move was split into two moves: 1.2 upwards from ground and then the actual riptide push.
1913
            // We can therefore set the flag to YES from here on. The push will be handled below.
1914
            data.setTridentReleaseEvent(AlmostBoolean.YES);
1915
            yDistanceAboveLimit = 0.0;
1916
            tags.add("gnd_riptide_pre");
1917
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1918
        }
1919
        
1920
        
1921
        ///////////////////////////////////////////////////////////////////////////////////
1922
        // Estimate the allowed yDistance (per-move distance check)                      //
1923
        ///////////////////////////////////////////////////////////////////////////////////
1924
        /* 
1925
           0: With space bar pressed. 
1926
           1: with space bar not pressed 
1927
           2: swimming not applied at all
1928
         */
1929
        double[] yTheoreticalDistance = null;
1930
        boolean[] collideLiquidY = null;
1931
        // Initialize with momentum (or lack thereof)
1932
        thisMove.yAllowedDistance = forceResetMomentum || touchDownIsLost 
1933
                                    || (lastMove.yDistance < 0.0 && (fromOnGround || thisMove.fromLostGround))
1934
                                    || !lastMove.toIsValid ? 0.0 : lastMove.yDistance;
1935
        if (lastMove.headObstructed) thisMove.yAllowedDistance = 0.0;
1936
        if (lastMove.yCorrectedDistancePre != 0.0) thisMove.yAllowedDistance = lastMove.yCorrectedDistancePre;
1937
        // *----------stuck-speed-momentum-reset----------*
1938
        if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) {
1939
            if (data.lastStuckInBlockVertical != 1.0) {
1940
                thisMove.yAllowedDistance = 0.0;
1941
            }
1942
        }
1943
        // TODO: Optimize to only split when need detect jump
1944
        if (!BridgeMisc.isSpaceBarImpulseKnown(player)) {
1945
            // *----------------------------------*
1946
            // *--- Loop the space bar impulse ---*
1947
            // *----------------------------------*
1948
            // Initialize with the momentum that has hitherto been calculated.
1949
            yTheoreticalDistance = new double[3];
1950
            collideLiquidY = new boolean[3];
1951
            // With space bar pressed
1952
            yTheoreticalDistance[0] = thisMove.yAllowedDistance;
1953
            // With space bar not pressed
1954
            yTheoreticalDistance[1] = thisMove.yAllowedDistance;
1955
            // With swimming speed not applied
1956
            yTheoreticalDistance[2] = thisMove.yAllowedDistance;
1957
        }
1958
        // *----------updateEntityAfterFallOn()----------*
1959
        // NOTE: pressing space bar on a bouncy block will override the bounce (in that case, vdistrel will fall back to the jump check above).
1960
        // updateEntityAfterFallOn(), this function is called on the next move
1961
        if (pData.isShiftKeyPressed() && lastMove.collideY) {
1962
            if (yTheoreticalDistance != null) {
1963
                boolean bounceUp = false;
1964
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1965
                    if (yTheoreticalDistance[i] < 0.0) { // NOTE: Must be the allowed distance, not the actual one (exploit)
1966
                        if (from.isOnBouncyBlock()) {
1967
                            // The effect works by inverting the distance.
1968
                            // Beds have a weaker bounce effect (BedBlock.java).
1969
                            yTheoreticalDistance[i] = from.isOnSlimeBlock() ? -yTheoreticalDistance[i] : -yTheoreticalDistance[i] * 0.66;
1970
                            bounceUp = true;
1971
                        }
1972
                    }
1973
                }
1974
                if (bounceUp) tags.add("bounceup");
1975
            } else {
1976
                if (thisMove.yAllowedDistance < 0.0) { // NOTE: Must be the allowed distance, not the actual one (exploit)
1977
                    if (from.isOnBouncyBlock()) {
1978
                        // The effect works by inverting the distance.
1979
                        // Beds have a weaker bounce effect (BedBlock.java).
1980
                        thisMove.yAllowedDistance = from.isOnSlimeBlock() ? -thisMove.yAllowedDistance : -thisMove.yAllowedDistance * 0.66;
1981
                        tags.add("bounceup");
1982
                    }
1983
                }
1984
            }
1985
        }
1986
        // *----------tryCheckInsideBlocks()----------*
1987
        // Bubble columns are checked in the tryCheckInsideBlocks method, so it comes after updateEntityAfterFallOn()...
1988
        from.tryApplyBubbleColumnMotion(thisMove, yTheoreticalDistance);
1989
        // Honey block sliding mechanic...
1990
        if (from.isSlidingDown()) {
1991
            // Speed is static in this case
1992
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, -Magic.SLIDE_SPEED_THROTTLE, Operation.SET);
1993
        }
1994
        // *----------Finalization of handleRelativeFrictionAndCalculateMovement; this check/condition is called after having called the move() function. The former method is called only when the player is traveling in air, thus the liquid and gliding checks ----------*
1995
        if (!lastMove.from.inLiquid) {
1996
            // TODO: We have to loop the jumping state for 1.21.1 and below... No other way to put it unfortunately. This will make the code an ugly mess than it already is.
1997
            final boolean jumpedOrCollided = lastMove.collidesHorizontally || data.input.wasSpaceBarPressed() && BridgeMisc.isSpaceBarImpulseKnown(player);
1998
            if (thisMove.from.onClimbable || thisMove.from.touchedPowderSnow && BridgeMisc.canStandOnPowderSnow(player)) {
1999
                if (jumpedOrCollided) {
2000
                    configVerticalAllowedValue(thisMove, yTheoreticalDistance, 0.2, Operation.SET);
2001
                } else if (yTheoreticalDistance != null) {
2002
                    yTheoreticalDistance[0] = 0.2;
2003
                }
2004
            }
2005
        }
2006
        // *----------Gravity, friction and other medium-dependent modifiers in LivingEntity.travel() (water first, then lava and finally air)----------*
2007
        data.nextGravity = attributeAccess.getHandle().getGravity(player);
2008
        if (lastMove.from.inWater) {
2009
            if (lastMove.collidesHorizontally && lastMove.from.onClimbable && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
2010
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, 0.2, Operation.SET);
2011
            }
2012
            // Water applies friction before calling the fluidFalling function.
2013
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2014
            if (BridgeMisc.hasGravity(player)) {
2015
                // Legacy: clients older than 1.13 have some kind of gravity effect applied to them even in liquids, if they don't press the space bar.
2016
                // On 1.13 and above, only friction gets applied, resulting in a much slower descending speed when not pressing the space bar pressed.
2017
                if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
2018
                    configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.LEGACY_LIQUID_GRAVITY, Operation.SUBTRACT);
2019
                } 
2020
                else {
2021
                    // In 1.13 the gravity effect in liquids was removed and this function got added.
2022
                    if (yTheoreticalDistance != null) {
2023
                        for (int i =0; i < yTheoreticalDistance.length; i++) {
2024
                            Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yTheoreticalDistance[i] <= 0.0, new Vector(0.0, yTheoreticalDistance[i], 0.0), cData.wasSprinting);
2025
                            yTheoreticalDistance[i] = fluidFallingAdjustMovement.getY();
2026
                        }
2027
                    }
2028
                }
2029
            }
2030
            tags.add("v_water");
2031
        }
2032
        else if (lastMove.from.inLava) {
2033
            // Lava friction is quite odd. Depending on specified thresholds, it can be 0.5 or 0.8
2034
            if (data.lastFrictionVertical != Magic.LAVA_VERTICAL_INERTIA) { // Note that this condition is not vanilla. It's just a shortcut to avoid replicating the condition contained in BlockProperties.getBlockFrictionFactor.
2035
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2036
                if (BridgeMisc.hasGravity(player)) {
2037
                    if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
2038
                        configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.LEGACY_LIQUID_GRAVITY, Operation.SUBTRACT);
2039
                    } 
2040
                    else {
2041
                        // getFluidFallingAdjustedMovement is only applied if friction is 0.8.
2042
                        if (yTheoreticalDistance != null) {
2043
                            for (int i =0; i < yTheoreticalDistance.length; i++) {
2044
                                Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yTheoreticalDistance[i] <= 0.0, new Vector(0.0, yTheoreticalDistance[i], 0.0), cData.wasSprinting);
2045
                                yTheoreticalDistance[i] = fluidFallingAdjustMovement.getY();
2046
                            }
2047
                        }
2048
                    }
2049
                }
2050
            }
2051
            else {
2052
                // Otherwise, 0.5
2053
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2054
            }
2055
            if (data.lastGravity != 0.0) {
2056
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, -data.lastGravity / 4.0, Operation.ADD);
2057
            }
2058
            tags.add("v_lava");
2059
        }
2060
        else {
2061
            // Air motion
2062
            if (cData.wasLevitating) {
2063
                // Levitation forces players to ascend and does not work in liquids, so thankfully we don't have to account for that, other than stuck-speed.
2064
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, (0.05 * data.lastLevitationLevel - lastMove.yAllowedDistance) * 0.2, Operation.ADD);
2065
            }
2066
            else configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastGravity, Operation.SUBTRACT);
2067
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2068
            tags.add("v_air");
2069
        }
2070
        // *----------Finalize LivingEntity.travel; isFree() check----------*
2071
        // Try making the player jump out of the liquid... 
2072
        // This condition is the same for both lava and water, and is always done at the end of the travel() function.
2073
        //TODO: Still broken as thisMove.collidesHorizontally not working properly!
2074
        if (from.isInLiquid() && lastMove.collidesHorizontally) {
2075
            if (yTheoreticalDistance != null) {
2076
                for (int i =0; i < yTheoreticalDistance.length; i++) {
2077
                    if (from.isUnobstructed(yTheoreticalDistance[i])) yTheoreticalDistance[i] = 0.3;
2078
                }
2079
            } else if (from.isUnobstructed(thisMove.yAllowedDistance)) thisMove.yAllowedDistance = 0.3;
2080
            tags.add("v_exiting_liquid");
2081
        }
2082
        
2083
        
2084
        //////////////////////////////////
2085
        // Last client-tick/move        //
2086
        //////////////////////////////////
2087
        if (from.isInLiquid() && verticalLiquidPushComponent != 0.0) {
2088
            // Liquid vertical push component calculated in hdistrel.
2089
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, verticalLiquidPushComponent, Operation.ADD);
2090
        }
2091
        // *----------TridentItem.releaseUsing(), apply trident motion----------*
2092
        if (thisMove.tridentRelease.decideOptimistically()) {
2093
            thisMove.tridentRelease = AlmostBoolean.YES;
2094
            // Riptide works by propelling the player in air after releasing the trident (the effect only pushes the player, unless is on ground)
2095
            final Vector riptideVelocity = to.getRiptideVelocity(onGround);
2096
            final double fric = getLastYGroundRipTide(from, lastMove, data, cData);
2097
            if (fric != 0.0) {
2098
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, riptideVelocity.getY() + fric, Operation.SET);
2099
            } 
2100
            else {
2101
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, riptideVelocity.getY(), Operation.ADD);
2102
            }
2103
        }
2104
        //  Special case for riptide at the start of the movement tick (when the riptide move is "unified" and not split into two updates; friction of the next move is used here)
2105
        if (lastMove.tridentRelease.decide() && lastMove.toIsValid) {
2106
            final PlayerMoveData secondLastMove = data.playerMoves.getSecondPastMove();
2107
            if (lastMove.from.onGround || (secondLastMove.toIsValid && secondLastMove.yDistance <= 0.0 && (secondLastMove.from.onGround || secondLastMove.fromLostGround))) {
2108
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.RIPTIDE_ON_GROUND_MOVE * data.lastFrictionVertical, Operation.SUBTRACT);
2109
            }
2110
        }
2111
        if (from.isInWater() && pData.getClientVersion().isHigherThan(ClientVersion.V_1_12_2)) {
2112
            // *----------LocalPlayer.aiStep(), goDownInWater()----------*
2113
            if (pData.isShiftKeyPressed()) {
2114
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.LIQUID_SPEED_GAIN, Operation.SUBTRACT);
2115
            }
2116
        }
2117
        // *----------LivingEntity.aiStep(), negligible speed----------*
2118
        checkNegligibleMomentumVertical(pData, thisMove, yTheoreticalDistance);
2119
        // *----------EntityLiving.aiStep(), apply liquid motion----------*
2120
        if (from.isInLiquid()) {
2121
            // *----------------------------------------------------------------------------------------------------------------------------*
2122
            // *----- When in liquid, the game doesn't care about players being on ground, only if they press the space bar.   -------------*
2123
            // *----- When they do press it, the game sets the jumping field to true.   ----------------------------------------------------*
2124
            // *----- However, up until MC 1.21.2 we couldn't know this, because the player used to not send anything about it -------------*
2125
            // *----- Solution: if the client/server does not support input reading/sending, loop the space bar impulse   ------------------*
2126
            // *----------------------------------------------------------------------------------------------------------------------------* 
2127
            if (yTheoreticalDistance == null) {
2128
                // From: EntityLiving.java -> aiStep() and KeyboardInput.java.
2129
                if (data.input.isSpaceBarPressed()) {
2130
                    boolean isSubmergedInWater = from.isInWater() && thisMove.submergedWaterHeight > 0.0;
2131
                    double fluidJumpThreshold = from.getEyeHeight() < 0.4D ? 0.0D : 0.4D;
2132
                    if (isSubmergedInWater && (!onGround || thisMove.submergedWaterHeight > fluidJumpThreshold)) {
2133
                        thisMove.yAllowedDistance += Magic.LIQUID_SPEED_GAIN; // The game distinguishes liquid tagkeys, but the motion is the same...
2134
                    } 
2135
                    else if (from.isInLava() && (!onGround || thisMove.submergedLavaHeight > fluidJumpThreshold)) {
2136
                        thisMove.yAllowedDistance += Magic.LIQUID_SPEED_GAIN;
2137
                    } 
2138
                    else if ((onGround || isSubmergedInWater && thisMove.submergedWaterHeight <= fluidJumpThreshold) && data.jumpDelay == 0) {
2139
                        thisMove.yAllowedDistance = data.liftOffEnvelope.getJumpGain(data.jumpAmplifier) * attributeAccess.getHandle().getJumpGainMultiplier(player);
2140
                        data.jumpDelay = Magic.MAX_JUMP_DELAY;
2141
                        thisMove.hasImpulse = AlmostBoolean.YES; // Minecraft explicitly tells us that there's impulse in this case.
2142
                        thisMove.isJump = true;
2143
                    }
2144
                } 
2145
                else {
2146
                    data.jumpDelay = 0;
2147
                }
2148
                //*--------Player.java, travel(). Apply swimming speed-------*
2149
                // 1.13 swimming speed depends on the looking direction vector of the player.
2150
                // Small note: the game here does NOT explicitly ensure that the player is also in water. Thus, this should be checked outside the from.isInLiquid() condition
2151
                if (Bridge1_13.isSwimming(player) && from.getEntity() instanceof Player) { // inside vehicle checking would always return false, since Sf doesn't run for vehicles, but in the future, we might merge vehicle checks
2152
                    Vector lookVector = TrigUtil.getLookingDirection(to, player);
2153
                    double swimmingScalar = lookVector.getY() < -0.2 ? 0.085 : 0.06;
2154
                    if (lookVector.getY() <= 0.0 || data.input.isSpaceBarPressed()
2155
                        || BlockProperties.getLiquidHeightAt(from.getBlockCache(), Location.locToBlock(from.getX()), Location.locToBlock(from.getY() + 1.0 - 0.1), Location.locToBlock(from.getZ()), BlockFlags.F_WATER, true) != 0.0) {
2156
                        thisMove.yAllowedDistance += (lookVector.getY() - thisMove.yAllowedDistance) * swimmingScalar;
2157
                    }
2158
                }
2159
            }
2160
            else {
2161
                boolean isSubmergedInWater = from.isInWater() && thisMove.submergedWaterHeight > 0.0;
2162
                double fluidJumpThreshold = from.getEyeHeight() < 0.4D ? 0.0D : 0.4D;
2163
                if (isSubmergedInWater && (!onGround || thisMove.submergedWaterHeight > fluidJumpThreshold)) {
2164
                    yTheoreticalDistance[0] += Magic.LIQUID_SPEED_GAIN;
2165
                }
2166
                else if (from.isInLava() && (!onGround || thisMove.submergedLavaHeight > fluidJumpThreshold)) {
2167
                    yTheoreticalDistance[0] += Magic.LIQUID_SPEED_GAIN;
2168
                }
2169
                else if ((onGround || isSubmergedInWater && thisMove.submergedWaterHeight <= fluidJumpThreshold) && data.jumpDelay == 0) {
2170
                    yTheoreticalDistance[0] = data.liftOffEnvelope.getJumpGain(data.jumpAmplifier) * attributeAccess.getHandle().getJumpGainMultiplier(player);
2171
                    data.jumpDelay = Magic.MAX_JUMP_DELAY;
2172
                    thisMove.hasImpulse = AlmostBoolean.YES;
2173
                    // (Can't set thisMove.isJump yet.)
2174
                }
2175
                if (Bridge1_13.isSwimming(player) && !player.isInsideVehicle()) {
2176
                    Vector lookVector = TrigUtil.getLookingDirection(to, player);
2177
                    double swimmingScalar = lookVector.getY() < -0.2 ? 0.085 : 0.06;
2178
                    // Note: Since thisMove.isJump is always false because not been set yet, make these conditions unusable, result in brute force
2179
                    //if (lookVector.getY() <= 0.0 || thisMove.isJump 
2180
                    //    || BlockProperties.getLiquidHeightAt(from.getBlockCache(), Location.locToBlock(from.getX()), Location.locToBlock(from.getY()+1.0-0.1), Location.locToBlock(from.getZ()), BlockFlags.F_WATER, true) != 0.0) {
2181
                    yTheoreticalDistance[0] += (lookVector.getY() - yTheoreticalDistance[0]) * swimmingScalar;
2182
                    yTheoreticalDistance[1] += (lookVector.getY() - yTheoreticalDistance[1]) * swimmingScalar;
2183
                    //}
2184
                }
2185
            }
2186
        }
2187
        // *----------LivingEntity.travel(), handleRelativeFrictionAndCalculateMovement() -> handleOnClimbable()----------*
2188
        if (!from.isInLiquid() && from.isOnClimbable() && from.canClimbUp(data.liftOffEnvelope.getMaxJumpHeight(data.jumpAmplifier))) {
2189
            // Should replicate the condition: !this.getInBlockState().is(Blocks.SCAFFOLDING)
2190
            final Material typeId = from.getBlockType();
2191
            final long theseFlags = BlockFlags.getBlockFlags(typeId);
2192
            if (yTheoreticalDistance != null) {
2193
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
2194
                    yTheoreticalDistance[i] = Math.max(yTheoreticalDistance[i], -Magic.CLIMBABLE_MAX_SPEED);
2195
                    if (yTheoreticalDistance[i] < 0.0 && pData.isShiftKeyPressed() && from.getEntity() instanceof Player
2196
                        && (theseFlags & BlockFlags.F_SCAFFOLDING) == 0 && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
2197
                        yTheoreticalDistance[i] = 0.0;
2198
                    }
2199
                }
2200
            } else {
2201
                thisMove.yAllowedDistance = Math.max(thisMove.yAllowedDistance, -Magic.CLIMBABLE_MAX_SPEED);
2202
                if (thisMove.yAllowedDistance < 0.0 && pData.isShiftKeyPressed() && from.getEntity() instanceof Player
2203
                    && (theseFlags & BlockFlags.F_SCAFFOLDING) == 0 && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
2204
                    thisMove.yAllowedDistance = 0.0;
2205
                }
2206
            }
2207
            tags.add("v_climbable");
2208
        }
2209
        // *----------Beginning call of Entity.move(); apply stuck speed multipliers----------*
2210
        if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
2211
            // If we looped the space bar impulse, all later modifiers are applied to each speed.
2212
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.nextStuckInBlockVertical, Operation.MULTIPLY);
2213
        }
2214
        // *----------Entity.move(), call the collide() function----------*
2215
        // Include horizontal motion to account for stepping: there are cases where NCP's isStep definition fails to catch it.
2216
        // (In which case, isStep will return false and fall-back to friction here)
2217
        // It is imperative that you pass yAllowedDistance as argument here (not the real yDistance), because if the player isn't on ground, the current motion will be used to determine it (collideY && motionY < 0.0). Passing an uncontrolled yDistance will be easily exploitable.
2218
        if (yTheoreticalDistance == null) {
2219
            Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, thisMove.yAllowedDistance, thisMove.zAllowedDistance), fromOnGround || thisMove.fromLostGround && lastMove.yDistance < 0.0, from.getBoundingBox());
2220
            thisMove.headObstructed = thisMove.yAllowedDistance != collisionVector.getY() && thisMove.yDistance >= 0.0 && !fromOnGround;  // New definition of head obstruction: yDistance is checked because Minecraft considers players to be on ground when motion is explicitly negative
2221
            // If this vertical move resulted in a collision, remember it.
2222
            thisMove.collideY = collisionVector.getY() != thisMove.yAllowedDistance;
2223
            thisMove.yAllowedDistance = collisionVector.getY();
2224
        }
2225
        else {
2226
            for (int i = 0; i < yTheoreticalDistance.length; i++) {
2227
                Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, yTheoreticalDistance[i], thisMove.zAllowedDistance), fromOnGround || thisMove.fromLostGround && lastMove.yDistance < 0.0, from.getBoundingBox());
2228
                if (yTheoreticalDistance[i] != collisionVector.getY()) {
2229
                    // This theoretical speed would result in a collision. Remember it.
2230
                    collideLiquidY[i] = true;
2231
                }
2232
                //TODO: Might wrong if underliquid as not all moves are headObstructed
2233
                thisMove.headObstructed = yTheoreticalDistance[i] != collisionVector.getY() && thisMove.yDistance >= 0.0 && !fromOnGround;
2234
                yTheoreticalDistance[i] = collisionVector.getY();
2235
            }
2236
        }
2237
        
2238
        
2239
        ////////////////////////////////////////////////////////////////////////////
2240
        // Calculate the offset: check for velocity and workarounds on violations // 
2241
        ////////////////////////////////////////////////////////////////////////////
2242
        if (yTheoreticalDistance != null) {
2243
            final double hiddenThreshold = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2) ? Magic.Minecraft_minMoveSqDistance_legacy : Magic.Minecraft_minMoveSqDist_modern;
2244
            if (thisMove.hDistance < hiddenThreshold) {
2245
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
2246
                    if (yTheoreticalDistance[i] < hiddenThreshold && !collideLiquidY[i]) {
2247
                        thisMove.hiddenYDistanceIndex = i;
2248
                        break;
2249
                    }
2250
                }
2251
            }
2252
            boolean found = false;
2253
            for (int i = 0; i < yTheoreticalDistance.length; i++) {
2254
                if (MathUtil.isOffsetWithinPredictionEpsilon(thisMove.yDistance, yTheoreticalDistance[i])) {
2255
                    thisMove.yAllowedDistance = yTheoreticalDistance[i];
2256
                    thisMove.collideY = collideLiquidY[i];
2257
                    found = true;
2258
                    break;
2259
                }
2260
            }
2261
            if (!found && thisMove.hiddenYDistanceIndex != -1) {
2262
                final double result[] = HiddenMotionReconstructor.findBestHiddenTickExplanation(yTheoreticalDistance[thisMove.hiddenYDistanceIndex], player, data, cData, pData, from, to, attributeAccess.getHandle().getJumpGainMultiplier(player), 
2263
                                                                                                verticalLiquidPushComponent, onGround, yTheoreticalDistance[thisMove.hiddenYDistanceIndex]);
2264
                yTheoreticalDistance[thisMove.hiddenYDistanceIndex] += result[0];
2265
                if (MathUtil.isOffsetWithinPredictionEpsilon(thisMove.yDistance, yTheoreticalDistance[thisMove.hiddenYDistanceIndex])) {
2266
                    thisMove.yAllowedDistance = yTheoreticalDistance[thisMove.hiddenYDistanceIndex];
2267
                    thisMove.collideY = collideLiquidY[thisMove.hiddenYDistanceIndex];
2268
                    thisMove.yCorrectedDistancePre = result[0];
2269
                    found = true;
2270
                    tags.add("v_hidden");
2271
                }
2272
            }
2273
        }
2274
        /* Expected difference from current to allowed */
2275
        final double offset = thisMove.yDistance - thisMove.yAllowedDistance;
2276
        if (Math.abs(offset) < Magic.PREDICTION_EPSILON) {
2277
            // Accuracy margin.
2278
        }
2279
        else {
2280
            // Check for workarounds at the end and override the prediction if needed (just allow the movement in this case.)
2281
            if (MagicWorkarounds.checkPostPredictWorkaround(data, fromOnGround, toOnGround, from, to, thisMove.yAllowedDistance, player, isNormalOrPacketSplitMove)) {
2282
                thisMove.yAllowedDistance = thisMove.yDistance;
2283
                if (debug) {
2284
                    player.sendMessage("[SurvivalFly] Workaround ID used: " + (!justUsedWorkarounds.isEmpty() ? StringUtil.join(justUsedWorkarounds, " , ") : ""));
2285
                }
2286
            }
2287
            else if (data.getOrUseVerticalVelocity(yDistance).isEmpty()) {
2288
                // If velocity can be used for compensation, use it.
2289
                yDistanceAboveLimit = Math.max(yDistanceAboveLimit, Math.abs(offset));
2290
                tags.add("vdistrel");
2291
                if (debug) {
2292
                    player.sendMessage(ChatColor.RED + "[SurvivalFly] vdistrel: predicted=" + StringUtil.fdec6.format(thisMove.yAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.yDistance) + ", offset=" + StringUtil.fdec6.format(offset));
2293
                }
2294
            }
2295
        }
2296
        return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
2297
    }
2298
2299
    private double getLastYGroundRipTide(PlayerLocation from, PlayerMoveData lastMove, MovingData data, CombinedData cData) {
2300
        double tmp = 0.0;
2301
        if (lastMove.tridentRelease == AlmostBoolean.MAYBE) {
2302
            if (lastMove.from.inWater) {
2303
                return from.getFluidFallingAdjustedMovement(data.lastGravity, true, new Vector(0.0, 0.0, 0.0), false).getY();
2304
            }
2305
            else if (lastMove.from.inLava) {
2306
                // Lava friction is quite odd. Depending on specified thresholds, it can be 0.5 or 0.8
2307
                if (data.lastFrictionVertical != Magic.LAVA_VERTICAL_INERTIA) {
2308
                    tmp = from.getFluidFallingAdjustedMovement(data.lastGravity, true, new Vector(0.0, 0.0, 0.0), false).getY();
2309
                }
2310
                else {
2311
                    // Otherwise, 0.5
2312
                    tmp *= data.lastFrictionVertical;
2313
                }
2314
                if (data.lastGravity != 0.0) {
2315
                    tmp += -data.lastGravity / 4.0;
2316
                }
2317
            }
2318
            else {
2319
                // Air motion
2320
                if (cData.wasLevitating) {
2321
                    // Levitation forces players to ascend and does not work in liquids, so thankfully we don't have to account for that, other than stuck-speed.
2322
                    tmp += (0.05 * data.lastLevitationLevel - lastMove.yAllowedDistance) * 0.2;
2323
                }
2324
                else tmp -= data.lastGravity;
2325
                tmp *= data.lastFrictionVertical;
2326
            }
2327
        }
2328
        return tmp;
2329
    }
2330
2331
2332
    /**
2333
     * After-horizontal-failure checks.
2334
     *
2335
     * @return hAllowedDistance, hDistanceAboveLimit, hFreedom
2336
     */
2337
    private double[] hDistAfterFailure(final Player player,
2338
                                       final PlayerLocation from, final PlayerLocation to,
2339
                                       double hAllowedDistance, double hDistanceAboveLimit,
2340
                                       final PlayerMoveData thisMove, final PlayerMoveData lastMove, final boolean debug,
2341
                                       final MovingData data, final MovingConfig cc, final IPlayerData pData, final int tick,
2342
                                       boolean useBlockChangeTracker, final boolean fromOnGround, final boolean toOnGround,
2343
                                       final boolean isNormalOrPacketSplitMove) {
2344
        /*
2345
         * 0: If we got a speed violation and the player is using an item, assume it to be a "noslowdown" violation.
2346
         */
2347
        if (cc.survivalFlyResetItem && BridgeMisc.isSlowedDownByUsingAnItem(player) && !Bridge1_9.isGliding(player)) {
2348
            // Forcibly release the item in use.
2349
            pData.requestItemUseResync();
2350
            tags.add("itemresync");
2351
            if (!BridgeMisc.isSlowedDownByUsingAnItem(player) && hDistanceAboveLimit > 0.0) {
2352
                // Re-estimate with released item (if it still throws a VL, the player is actually cheating, if the item is still in use, then it wasn't desync'ed).
2353
                double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, false);
2354
                hAllowedDistance = res[0];
2355
                hDistanceAboveLimit = res[1];
2356
            }
2357
        }
2358
        /*
2359
         *  Because this move is not sent by the client and cannot be predicted through normal means, we have to brute force it.
2360
         */
2361
        if (hDistanceAboveLimit > 0.0 && lastMove.possibleStopMotion) {
2362
            lastMove.possibleStopMotion = false;
2363
            tags.add("stop_motion");
2364
            double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, false);
2365
            hAllowedDistance = res[0];
2366
            hDistanceAboveLimit = res[1];
2367
        }
2368
        /*
2369
         * 2: Undetectable jump (must brute force here): player failed with the onGround flag, lets try with off-ground then.
2370
         */
2371
        if (PhysicsEnvelope.isVerticallyConstricted(from, to, pData) && hDistanceAboveLimit > 0.0) {
2372
            tags.add("vert_constricted");
2373
            double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, true);
2374
            hAllowedDistance = res[0];
2375
            hDistanceAboveLimit = res[1];
2376
        }
2377
        /*
2378
         * 3: Above limit again? Check for past onGround states caused by block changes (i.e.: ground was pulled off from the player's feet)
2379
         */
2380
        if (useBlockChangeTracker && hDistanceAboveLimit > 0.0) {
2381
            // Be sure to test this only if the player is seemingly off ground
2382
            if (!thisMove.fromLostGround && !from.isOnGround() && from.isOnGroundOpportune(cc.yOnGround, 0L, blockChangeTracker, data.blockChangeRef, tick)) {
2383
                tags.add("onground_tracked");
2384
                double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, true, false);
2385
                hAllowedDistance = res[0];
2386
                hDistanceAboveLimit = res[1];
2387
            }
2388
        }
2389
        /* 
2390
         * 4: Distance is still above limit; last resort: check if the distance above limit can be covered with velocity
2391
         */
2392
        // TODO: Implement Asofold's fix to prevent too easy abuse:
2393
        // See: https://github.com/NoCheatPlus/Issues/issues/374#issuecomment-296172316
2394
        //double hFreedom = 0.0; // Horizontal velocity used.
2395
        //if (hDistanceAboveLimit > 0.0) {
2396
        //    hFreedom = data.getHorizontalFreedom();
2397
        //    if (hFreedom < hDistanceAboveLimit) {
2398
        //        // Distance above limit is still greater. Try using queued velocity if possible.
2399
        //        hFreedom += data.useHorizontalVelocity(hDistanceAboveLimit - hFreedom);
2400
        //    }
2401
        //    if (hFreedom > 0.0) {
2402
        //        tags.add("hvel");
2403
        //        hDistanceAboveLimit = Math.max(0.0, hDistanceAboveLimit - hFreedom);
2404
        //    }
2405
        //}
2406
        return new double[]{hAllowedDistance, hDistanceAboveLimit, 0.0};
2407
    }
2408
    
2409
    /**
2410
     * Handles a violation for Survivalfly.
2411
     * 
2412
     * @return The Location where the player will be set backed to.
2413
     */
2414
    private Location handleViolation(final double result,
2415
                                     final Player player, final PlayerLocation from, final PlayerLocation to,
2416
                                     final MovingData data, final MovingConfig cc) {
2417
        // Increment violation level.
2418
        data.survivalFlyVL += result;
2419
        data.sfVLMoveCount = data.getPlayerMoveCount();
2420
        final ViolationData vd = new ViolationData(this, player, data.survivalFlyVL, result, cc.survivalFlyActions);
2421
        if (vd.needsParameters()) {
2422
            vd.setParameter(ParameterName.LOCATION_FROM, String.format(Locale.US, "%.2f, %.2f, %.2f", from.getX(), from.getY(), from.getZ()));
2423
            vd.setParameter(ParameterName.LOCATION_TO, String.format(Locale.US, "%.2f, %.2f, %.2f", to.getX(), to.getY(), to.getZ()));
2424
            vd.setParameter(ParameterName.DISTANCE, String.format(Locale.US, "%.2f", TrigUtil.distance(from, to)));
2425
            vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
2426
        }
2427
        // Some resetting is done in MovingListener.
2428
        if (executeActions(vd).willCancel()) {
2429
            // Set back + view direction of to (more smooth).
2430
            return MovingUtil.getApplicableSetBackLocation(player, to.getYaw(), to.getPitch(), to, data, cc);
2431
        }
2432
        else {
2433
            data.sfJumpPhase = 0;
2434
            // Cancelled by other plugin, or no cancel set by configuration.
2435
            return null;
2436
        }
2437
    }
2438
2439
2440
    /**
2441
     * Hover violations have to be handled in this check, because they are handled as SurvivalFly violations (needs executeActions).
2442
     */
2443
    public final void handleHoverViolation(final Player player, final PlayerLocation loc, final MovingConfig cc, final MovingData data) {
2444
        data.survivalFlyVL += cc.sfHoverViolation;
2445
        // TODO: Extra options for set back / kick, like vl?
2446
        data.sfVLMoveCount = data.getPlayerMoveCount();
2447
        data.sfVLInAir = true;
2448
        final ViolationData vd = new ViolationData(this, player, data.survivalFlyVL, cc.sfHoverViolation, cc.survivalFlyActions);
2449
        if (vd.needsParameters()) {
2450
            vd.setParameter(ParameterName.LOCATION_FROM, String.format(Locale.US, "%.2f, %.2f, %.2f", loc.getX(), loc.getY(), loc.getZ()));
2451
            vd.setParameter(ParameterName.LOCATION_TO, "(HOVER)");
2452
            vd.setParameter(ParameterName.DISTANCE, "0.0(HOVER)");
2453
            vd.setParameter(ParameterName.TAGS, "hover");
2454
        }
2455
        if (executeActions(vd).willCancel()) {
2456
            // Set back or kick.
2457
            final Location newTo = MovingUtil.getApplicableSetBackLocation(player, loc.getYaw(), loc.getPitch(), loc, data, cc);
2458
            if (newTo != null) {
2459
                data.prepareSetBack(newTo);
2460
                SchedulerHelper.teleportEntity(player, newTo, BridgeMisc.TELEPORT_CAUSE_CORRECTION_OF_POSITION);
2461
            }
2462
            else {
2463
                // Solve by extra actions ? Special case (probably never happens)?
2464
                player.kickPlayer("Hovering?");
2465
            }
2466
        }
2467
        else {
2468
            // Ignore.
2469
        }
2470
    }
2471
2472
2473
    /**
2474
     * Debug output.
2475
     */
2476
    private void outputDebug(final Player player, final PlayerLocation to, final PlayerLocation from,
2477
                             final MovingData data,
2478
                             final double hDistance, final double hAllowedDistance, final double hFreedom,
2479
                             final double yDistance, final double yAllowedDistance,
2480
                             final boolean fromOnGround, final boolean resetFrom,
2481
                             final boolean toOnGround, final boolean resetTo,
2482
                             final PlayerMoveData thisMove) {
2483
2484
        // TODO: Show player name once (!)
2485
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
2486
        final double yDistDiffEx = yDistance - yAllowedDistance;
2487
        final double hDistDiffEx = thisMove.hDistance - thisMove.hAllowedDistance;
2488
        final StringBuilder builder = new StringBuilder(500);
2489
        builder.append(CheckUtils.getLogMessagePrefix(player, type));
2490
        final String hVelUsed = hFreedom > 0 ? " / hVelUsed: " + StringUtil.fdec3.format(hFreedom) : "";
2491
        builder.append("\nOnGround: " + (thisMove.headObstructed ? "(head obstr.) " : from.isSlidingDown() ? "(sliding down) " : "") + (thisMove.touchedGroundWorkaround ? "(lost ground) " : "") + (fromOnGround ? "onground -> " : (resetFrom ? "resetcond -> " : "--- -> ")) + (toOnGround ? "onground" : (resetTo ? "resetcond" : "---")) + ", jumpPhase: " + data.sfJumpPhase + ", LiftOff: " + data.liftOffEnvelope.name());
2492
        final String dHDist = lastMove.toIsValid ? "(" + StringUtil.formatDiff(hDistance, lastMove.hDistance) + ")" : "";
2493
        final String dYDist = lastMove.toIsValid ? "(" + StringUtil.formatDiff(yDistance, lastMove.yDistance)+ ")" : "";
2494
        builder.append("\n" + " hDist: " + StringUtil.fdec6.format(hDistance) + dHDist + " / offset: " + hDistDiffEx + " / predicted: " + StringUtil.fdec6.format(hAllowedDistance) + hVelUsed +
2495
                "\n" + " vDist: " + StringUtil.fdec6.format(yDistance) + dYDist + " / offset: " + yDistDiffEx + " / predicted: " + StringUtil.fdec6.format(yAllowedDistance) + " , setBackY: " + (data.hasSetBack() ? (data.getSetBackY() + " (jump height: " + StringUtil.fdec3.format(to.getY() - data.getSetBackY()) + " / max jump height: " + data.liftOffEnvelope.getMaxJumpHeight(data.jumpAmplifier) + ")") : "?"));
2496
        if (lastMove.toIsValid) {
2497
            builder.append("\n fdsq: " + StringUtil.fdec3.format(thisMove.distanceSquared / lastMove.distanceSquared));
2498
        }
2499
        if (!lastMove.toIsValid) {
2500
            builder.append("\n Invalid last move (data reset)");
2501
        }
2502
        if (!lastMove.valid) {
2503
            builder.append("\n Invalid last move (missing data)");
2504
        }
2505
        if (!thisMove.verVelUsed.isEmpty()) {
2506
            builder.append(" , vVelUsed: " + thisMove.verVelUsed + " ");
2507
        }
2508
        data.addVerticalVelocity(builder);
2509
        data.addHorizontalVelocity(builder);
2510
        if (player.isSleeping()) {
2511
            tags.add("sleeping");
2512
        }
2513
        if (Bridge1_9.isWearingElytra(player)) {
2514
            // Just wearing (not isGliding).
2515
            tags.add("elytra_off");
2516
        }
2517
        if (!tags.isEmpty()) {
2518
            builder.append("\n" + " Tags: " + StringUtil.join(tags, "+"));
2519
        }
2520
        if (!justUsedWorkarounds.isEmpty()) {
2521
            builder.append("\n" + " Workaround ID: " + StringUtil.join(justUsedWorkarounds, " , "));
2522
        }
2523
        builder.append("\n");
2524
        NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, builder.toString());
2525
    }
2526
2527
2528
    private void logPostViolationTags(final Player player) {
2529
        debug(player, "SurvivalFly Post violation handling tag update:\n" + StringUtil.join(tags, "+"));
2530
    }
2531
}

How it counteracts this module

SurvivalFly compares every move against a physics envelope rebuilt from the world. The horizontal allowance comes from a speed estimation based on sprint state and potion effects, and the vertical allowance from vDistRel, which inherits momentum from the previous move and only accepts named envelopes: a zero-y move on ground, a jump, a step-up and a riptide launch. Ground is derived from a block ray trace, not the packet flag, so the module's ground fakes do not relax anything. A violation is (max(hDistanceAboveLimit, 0) + max(yDistanceAboveLimit, 0)) * 100 with a set-back to a stored location.

The fast horizontal modes hit the horizontal side immediately. Vanilla and MineBox strafe at the fly speed setting, which defaults to 1.0 and can go to 9.5, versus a sprint prediction near 0.31, so hDistanceAboveLimit is several blocks and the violation is in the hundreds on the first move. Verus Lag's y-drop of 20 plus a random amount presents a vertical delta of roughly 20 blocks against an allowed descent of a few tenths, an immediate yDistanceAboveLimit of about 19.7 and a violation over 1900. The Vulcan mode's 3.7 motionY spike is a legal single jump magnitude but the sustained flight around it, with posY pinned and motionY zeroed, produces the airborne zero-y hover the envelope does not name.

The kick-bypass ladder is the clearest case. Each C04 in the 8-block fall and climb pair is an 8-block vertical move with onGround true; NCP's ray trace says the claimed spot is air, so the ground flag is ignored and yDistanceAboveLimit lands near 7.7 per packet, with the whole ladder crossing the violation threshold on the first step. The block-assisted modes (BlockFly, Matrix1.17's C08 stream, Hycraft's C03 cancellation) fare no better, because SurvivalFly measures actual position deltas, and the module's own teleport or block-place tricks show up as unexplained position jumps.

anticheat Flight (hover, ascension, glide)

Flight.java356 lines · Java
1
package me.vrekt.arc.check.moving;
2
3
import me.vrekt.arc.Arc;
4
import me.vrekt.arc.check.Check;
5
import me.vrekt.arc.check.CheckResult;
6
import me.vrekt.arc.check.CheckType;
7
import me.vrekt.arc.data.moving.MovingData;
8
import me.vrekt.arc.utilties.LocationHelper;
9
import org.bukkit.ChatColor;
10
import org.bukkit.Location;
11
import org.bukkit.Material;
12
import org.bukkit.block.Block;
13
import org.bukkit.block.BlockFace;
14
import org.bukkit.entity.Player;
15
import org.bukkit.material.Step;
16
import org.bukkit.potion.PotionEffectType;
17
18
import java.util.List;
19
20
public class Flight extends Check {
21
22
    private double maxAscendSpeed, maxDescendSpeed, maxHeight, maxHover, maxAscendDistance;
23
    private int maxAscendTime;
24
25
    public Flight() {
26
        super(CheckType.FLIGHT);
27
28
        maxAscendSpeed = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "ascend-ladder");
29
        maxDescendSpeed = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "descend-ladder");
30
        maxHeight = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "max-jump");
31
        maxHover = Arc.getCheckManager().getValueInt(CheckType.FLIGHT, "max-hover-time");
32
        maxAscendDistance = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "ascend-distance");
33
34
        maxAscendTime = Arc.getCheckManager().getValueInt(CheckType.FLIGHT, "ascend-time");
35
    }
36
37
    private boolean hoverCheck(Player player, MovingData data) {
38
        result.reset();
39
40
        // Check if we are actually hovering.
41
        double vertical = data.getVerticalSpeed();
42
        boolean actuallyHovering = data.getLastVerticalSpeed() == 0.0 && vertical == 0.0 && player.getVehicle() == null;
43
44
        if (actuallyHovering) {
45
            // check how long we've been hovering for.
46
            if (data.getAirTicks() >= maxHover) {
47
                // too long, flag.
48
                getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Hover)");
49
                result.set(checkViolation(player, "hovering off the ground, hover"));
50
            }
51
        }
52
53
        return result.failed();
54
    }
55
56
    public CheckResult runBlockChecks(Player player, MovingData data) {
57
        result.reset();
58
59
        if (!data.wasOnGround()) {
60
            result.set(hoverCheck(player, data));
61
        }
62
63
        double vertical = data.getVerticalSpeed();
64
65
        // ladder and vertical velocity stuff.
66
        boolean isAscending = data.isAscending();
67
        boolean isDescending = data.isDescending();
68
        boolean isClimbing = data.isClimbing();
69
70
        int airTicks = data.getAirTicks();
71
72
        // make sure we're actually in the air.
73
        boolean actuallyInAir = airTicks >= 20 && data.getLadderTime() >= 8;
74
75
        // fastladder check, make sure were ascending, climbing and in-air.
76
        if (isAscending && isClimbing && actuallyInAir) {
77
            // check if we are climbing too fast.
78
            if (vertical > maxAscendSpeed) {
79
                getCheck().setCheckName("Flight " + ChatColor.GRAY + "(FastLadder)");
80
                result.set(checkViolation(player, "ascending too fast, ladder_ascend"), data.getPreviousLocation());
81
            }
82
        }
83
84
        // patch for instant ladder
85
        double difference = vertical - maxAscendSpeed;
86
        if (isAscending && isClimbing && difference > 1.0) {
87
            getCheck().setCheckName("Flight " + ChatColor.GRAY + "(FastLadder)");
88
            result.set(checkViolation(player, "ascending too fast, ladder_instant"), data.getPreviousLocation());
89
        }
90
91
        // descending check.
92
        if (isDescending && isClimbing && actuallyInAir) {
93
            // too fast, flag.
94
            if (vertical > maxDescendSpeed) {
95
                getCheck().setCheckName("Flight " + ChatColor.GRAY + "(FastLadder)");
96
                result.set(checkViolation(player, "descending too fast, ladder_descend"), data.getPreviousLocation());
97
            }
98
        }
99
100
        getCheck().setCheckName("Flight");
101
        return result;
102
    }
103
104
    public CheckResult check(Player player, MovingData data) {
105
        result.reset();
106
107
        Location from = data.getPreviousLocation();
108
        Location to = data.getCurrentLocation();
109
        Location ground = data.getGroundLocation();
110
        if (ground == null) {
111
            ground = from;
112
        }
113
114
115
        double lastVertical = data.getLastVerticalSpeed();
116
        double vertical = data.getVerticalSpeed();
117
118
        boolean onGround = data.isOnGround();
119
        boolean isAscending = data.isAscending();
120
        boolean isDescending = data.isDescending();
121
        boolean isClimbing = data.isClimbing();
122
123
        boolean isOnSlab = to.getBlock().getRelative(BlockFace.DOWN).getType().getData().equals(Step.class);
124
        boolean isOnStep = (LocationHelper.isOnSlab(to) || isOnSlab) || LocationHelper.isOnStair(to);
125
        boolean isOnSlimeblock = LocationHelper.isOnSlimeblock(to);
126
        boolean isInLiquid = LocationHelper.isInLiquid(to);
127
        boolean isOnTrapdoor = to.getBlock().getRelative(BlockFace.SELF).getType() == Material.TRAP_DOOR;
128
        boolean isUnderBlock = LocationHelper.isUnderBlock(to);
129
        boolean velocityBoost = isOnTrapdoor && isUnderBlock;
130
131
        boolean hasVelocity = data.getVelocityData().hasVelocity();
132
        double velocity = data.getVelocityData().getCurrentVelocity();
133
        double lastVelocity = data.getVelocityData().getLastVelocity();
134
135
        boolean wasVerticalMove = (isAscending || isDescending);
136
        boolean validVerticalMove = player.getVehicle() == null && !hasVelocity && !isOnStep && !isClimbing && !isInLiquid;
137
138
        int ascendingMoves = data.getAscendingMoves();
139
        int descendingMoves = data.getDescendingMoves();
140
        int ladderTime = data.getLadderTime();
141
142
        // if we are on ground lets reset some data.
143
        if (onGround) {
144
            ascendingMoves = 0;
145
            descendingMoves = 0;
146
147
            data.setAscendingMoves(ascendingMoves);
148
            data.setDescendingMoves(descendingMoves);
149
            data.getVelocityData().clear();
150
151
            if (hasVelocity) {
152
                hasVelocity = false;
153
                data.getVelocityData().setHasVelocity(false);
154
                validVerticalMove = wasVerticalMove && player.getVehicle() == null && !isOnStep;
155
            }
156
157
            if (isOnSlimeblock) {
158
                // we landed on a slimeblock, lets update our velocity if out vertical has increased.
159
                if (vertical > 0.0 && !data.wasOnGround()) {
160
                    data.getVelocityData().setHasVelocity(true);
161
                    hasVelocity = true;
162
                    validVerticalMove = false;
163
                }
164
            }
165
166
        }
167
168
        // update our ascending data and reset our descending data.
169
        if (isAscending) {
170
            descendingMoves = 0;
171
            data.setDescendingMoves(descendingMoves);
172
            if (!isClimbing) {
173
                ascendingMoves++;
174
                data.setAscendingMoves(ascendingMoves);
175
            }
176
        }
177
178
        // update our descending data and reset the ascending data, also account for slimeblock velocity.
179
        if (isDescending) {
180
            ascendingMoves = 0;
181
            data.setAscendingMoves(ascendingMoves);
182
183
            descendingMoves++;
184
            data.setDescendingMoves(descendingMoves);
185
            data.getVelocityData().clear();
186
        }
187
188
        // update our climbing data.
189
        if (isClimbing) {
190
            if (wasVerticalMove) {
191
                data.setLadderTime(14);
192
            } else {
193
                data.setLadderTime(6);
194
            }
195
        } else {
196
            ladderTime = ladderTime >= 0 ? ladderTime - 1 : 0;
197
            data.setLadderTime(ladderTime);
198
        }
199
200
        if (wasVerticalMove) {
201
            // start with the vclip check, we want this first to make sure nobody is clipping through anything.
202
            if (vertical >= 0.99 && validVerticalMove && !isOnSlimeblock) {
203
                // update our safe location.
204
                Location safeLocation = data.getSafe();
205
                if (safeLocation == null) {
206
                    data.setSafe(from);
207
                    safeLocation = from;
208
                }
209
210
                // get our locations for checking.
211
                int minY = Math.min(safeLocation.getBlockY(), to.getBlockY());
212
                int maxY = Math.max(safeLocation.getBlockY(), to.getBlockY() + 1);
213
                for (int y = minY; y <= maxY; y++) {
214
                    // loop through all the possible y coordinates and get the block at that location.
215
                    Block blockTo = to.getWorld().getBlockAt(to.getBlockX(), y, to.getBlockZ());
216
                    if (blockTo.getType().isSolid()) {
217
                        // if its solid flag.
218
                        getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Vertical Clip)");
219
                        boolean failed = checkViolation(player, "clipped through a solid block, vclip_solid");
220
                        result.set(failed, safeLocation);
221
                    }
222
                }
223
224
            }
225
226
            // reset our safe location.
227
            if (!result.failed()) {
228
                data.setSafe(to);
229
            }
230
231
232
            if (!onGround) {
233
                if (hasVelocity && isAscending && ladderTime == 0) {
234
                    // we were on a slimeblock, watch our velocity.
235
                    data.getVelocityData().addVelocity(velocity);
236
                    if (data.getVelocityData().getSlimeblockVelocity().size() >= maxAscendTime) {
237
                        List<Double> velocityData = data.getVelocityData().getSlimeblockVelocity();
238
239
                        // get our "last" velocities.
240
                        double lastChange = Math.abs(velocity - lastVelocity);
241
                        double lastVelocityMove = lastVelocity;
242
                        int validMoves = 0;
243
244
                        // loop through all of the recent moves.
245
                        for (double move : velocityData) {
246
                            if (move < lastVelocityMove) {
247
                                // get the difference and add a valid move if we are decreasing in velocity.
248
                                double difference = Math.abs(move - lastVelocityMove);
249
                                if (difference < lastChange) {
250
                                    validMoves++;
251
                                }
252
                                lastChange = difference;
253
                            }
254
                            lastVelocityMove = move;
255
                        }
256
257
                        // no valid moves, flag.
258
                        if (validMoves <= 3) {
259
                            getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Glide)");
260
                            result.set(checkViolation(player, "ascending too high after slimeblock velocity, sb_velocity_watch"));
261
                        }
262
                        data.getVelocityData().clear();
263
                    }
264
                }
265
266
                if (isInLiquid) {
267
                    // check if the client is onGround, if so flag.
268
                    boolean ccGround = data.isPositionClientOnGround();
269
                    if (ccGround && vertical > 0.0) {
270
                        getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Jesus)");
271
                        result.set(checkViolation(player, "walking on water, ccground_liquid"));
272
                    }
273
                }
274
275
            }
276
277
            // check how we are ascending.
278
            boolean walkedOnFence = LocationHelper.walkedOnFence(to);
279
            double distanceFrom = LocationHelper.distanceVertical(ground, to);
280
            if (validVerticalMove && isAscending && !walkedOnFence && ladderTime == 0) {
281
                // valid move, check.
282
                // first get our distance we have traveled.
283
                if (distanceFrom >= maxAscendDistance) {
284
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Ascension)");
285
                    result.set(checkViolation(player, "ascending too high, ascending_distance"));
286
                }
287
288
                // ascending for too long.
289
                if (ascendingMoves > maxAscendTime) {
290
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Ascension)");
291
                    result.set(checkViolation(player, "ascending for too long, ascending_time"));
292
                }
293
294
                // ascending too fast.
295
                double max = getMaxJump(player);
296
                if (vertical > max) {
297
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Ascension)");
298
                    result.set(checkViolation(player, "Ascending too fast, ascending_vertical"));
299
                }
300
301
            }
302
303
            // check how we are descending.
304
            if (validVerticalMove && isDescending && ladderTime == 0 && !isOnSlimeblock && !velocityBoost) {
305
                double glideDelta = Math.abs(vertical - lastVertical);
306
307
                // check if we are descending at the same speed.
308
                if (glideDelta == 0.0) {
309
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Glide)");
310
                    result.set(checkViolation(player, "vertical not changing, descend_difference"));
311
                }
312
313
                // check the speed of how we are descending.
314
                int airTicks = data.getAirTicks();
315
                if (distanceFrom > 1.6 && descendingMoves > 2) {
316
                    double expected;
317
                    // calculate our expected difference based on air.
318
                    if (airTicks > 100) {
319
                        expected = -0.9908 * 1e-6 * Math.pow(airTicks, 2) + 3.4538 * 1e-7 * airTicks + 0.0189;
320
                    } else {
321
                        expected = 5.4246 * 1e-6 * Math.pow(airTicks, 2) - 0.0011 * airTicks + 0.0659;
322
                    }
323
324
                    double difference = Math.abs(glideDelta - expected);
325
                    if (difference > 0.02 || difference < 0.001) {
326
                        getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Glide)");
327
                        result.set(checkViolation(player, "vertical not expected, descend_expected"));
328
                    }
329
                }
330
331
            }
332
333
        }
334
335
        getCheck().setCheckName("Flight");
336
        return result;
337
    }
338
339
    /**
340
     * Return max distance we can ascend.
341
     *
342
     * @param player the player
343
     * @return the max jump height.
344
     */
345
    private double getMaxJump(Player player) {
346
347
        double max = maxHeight;
348
349
        if (player.hasPotionEffect(PotionEffectType.JUMP)) {
350
            max += 0.4;
351
        }
352
        return max;
353
354
    }
355
356
}

How it counteracts this module

Arc v2's Flight checks the vertical profile of every move. The hover check fires when both the last and current vertical speeds are exactly 0.0 and airTicks passes maxHover. Most Rise 5.99 modes hover by design: Vanilla pins motionY to 0 when no key is held, Vulcan zeroes motionY after its spike sequence, Jetpack resets ticks when the jump key is released, and the Hypixel mode sets motionY to 0 every tick while airborne, so the vertical speed is exactly 0.0 tick after tick and the hover flag fires once the air-time threshold is crossed.

The ascension branch compares the rising vertical speed against the jump cap. Vanilla's motionY of flySpeed (up to 9.5), Jetpack's ticks/30 acceleration, Vulcan's 3.7 spike and the 0.42 jumps in Hypixel all exceed the jump-derived cap on the first rising move, flagging ascending_too_fast. The descending branch requires the vertical change to match a gravity-derived polynomial; Verus Lag's 20-block drop and the immediate ground fakes make the glide delta enormous, tripping the glide or descend flags. Even the small timer-speed abuse in Redesky and Old NCP shows up as vertical profile changes the polynomial does not explain.

The check has a blind spot worth naming: horizontal-only modes that never change y (MCCentral's hover at a fixed y, Air Walk) avoid the ascension and descent branches entirely, and only the hover branch can touch them. That is why the module's own modes that fly with a constant y, such as Air Walk and Collide, are the ones that survive Arc the longest; everything with a vertical component gets flagged.

anticheat Fly (predicted-velocity discrepancy)

Fly.java412 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.movement.position;
20
21
import me.islandscout.hawk.Hawk;
22
import me.islandscout.hawk.HawkPlayer;
23
import me.islandscout.hawk.check.MovementCheck;
24
import me.islandscout.hawk.event.MoveEvent;
25
import me.islandscout.hawk.util.*;
26
import me.islandscout.hawk.wrap.block.WrappedBlock;
27
import me.islandscout.hawk.wrap.entity.WrappedEntity;
28
import org.bukkit.Location;
29
import org.bukkit.Material;
30
import org.bukkit.block.Block;
31
import org.bukkit.entity.Boat;
32
import org.bukkit.entity.Entity;
33
import org.bukkit.entity.Player;
34
import org.bukkit.util.Vector;
35
36
import java.util.*;
37
38
public class Fly extends MovementCheck {
39
40
    //TODO perhaps have a ground checking mode? clientside vs serverside? doing it server side can allow GroundSpoof to not cancel, yet Gravity will still catch groundspoof-based flys
41
42
    private static final float MIN_VELOCITY = 0.005F;
43
    private static final int MAX_NO_MOVES = 20;
44
    private static final double NO_MOVE_THRESHOLD = 0.03;
45
    private static final float DISCREPANCY_THRESHOLD = 0.0001F;
46
47
    private final Map<UUID, Float> estimatedPositionMap;
48
    private final Map<UUID, Float> estimatedVelocityMap;
49
    private final Map<UUID, Float> estimatedPositionAltMap;
50
    private final Map<UUID, Float> estimatedVelocityAltMap;
51
    private final Map<UUID, Integer> noMovesMap;
52
    private final Map<UUID, Integer> ticksSinceNoPosUpdateMap;
53
    private final Set<UUID> wasFlyingSet;
54
    private final Set<UUID> wasInLavaSet;
55
56
    public Fly() {
57
        super("fly", true, 0, 10, 0.995, 5000, "&7%player% failed fly, VL: %vl%", null);
58
        estimatedPositionMap = new HashMap<>();
59
        estimatedVelocityMap = new HashMap<>();
60
        estimatedPositionAltMap = new HashMap<>();
61
        estimatedVelocityAltMap = new HashMap<>();
62
        noMovesMap = new HashMap<>();
63
        ticksSinceNoPosUpdateMap = new HashMap<>();
64
        wasFlyingSet = new HashSet<>();
65
        wasInLavaSet = new HashSet<>();
66
    }
67
68
    @Override
69
    protected void check(MoveEvent e) {
70
        HawkPlayer pp = e.getHawkPlayer();
71
        Player p = e.getPlayer();
72
73
        Vector from = pp.hasSentPosUpdate() ? e.getFrom().toVector() : pp.getPositionPredicted(); //must predict where a player was previously if they didn't send a pos update then.
74
75
        float dY = (float) (e.getTo().getY() - from.getY());
76
77
        boolean moved = e.isUpdatePos();
78
79
        int noMoves = noMovesMap.getOrDefault(pp.getUuid(), 0);
80
        int ticksSinceNoPosUpdate = ticksSinceNoPosUpdateMap.getOrDefault(pp.getUuid(), 0);
81
82
        float estimatedPosition = estimatedPositionMap.getOrDefault(pp.getUuid(), (float) from.getY()),
83
              prevEstimatedVelocity = estimatedVelocityMap.getOrDefault(pp.getUuid(), (float) pp.getVelocity().getY()),
84
              estimatedPositionAlt = estimatedPositionAltMap.getOrDefault(pp.getUuid(), (float) from.getY()),
85
              prevEstimatedVelocityAlt = estimatedVelocityAltMap.getOrDefault(pp.getUuid(), (float) pp.getVelocity().getY());
86
87
        Set<Material> touchedBlocks = WrappedEntity.getWrappedEntity(p).getCollisionBox(from).getMaterials(pp.getWorld());
88
89
        boolean opposingForce = e.isJump() || e.hasAcceptedKnockback() || e.isTeleportAccept() || e.isStep();
90
91
        boolean wasInLava = wasInLavaSet.contains(p.getUniqueId());
92
93
        if((!e.isOnGround() || !pp.isOnGround()) && !opposingForce && !e.isLiquidExit() &&
94
                !p.isInsideVehicle() && !pp.isFlying() && !wasFlyingSet.contains(p.getUniqueId()) &&
95
                !p.isSleeping() && !isInClimbable(from.toLocation(pp.getWorld())) && //TODO: uh oh! make sure to have a fastladder check, otherwise hackers can "pop" off them
96
                !isOnBoat(p, e.getTo())) {
97
98
            //count "no-moves"
99
            if(!moved) {
100
                noMoves++;
101
            } else {
102
                noMoves = 0;
103
            }
104
105
            float estimatedVelocity;
106
            float estimatedVelocityAlt;
107
            boolean velResetA = false;
108
            boolean velResetB = false;
109
110
            //compute next expected velocity
111
            //TODO make this prediction better, i.e. do liquid/web collision checks. It shouldn't be using the liquid functions when the predicted position gets out of water.
112
            if(pp.isSwimming()) { //water functions
113
114
                estimatedVelocity = (prevEstimatedVelocity * 0.8F) + (float)(-0.02 + computeVerticalWaterFlowForce(estimatedPosition, pp));
115
                estimatedVelocityAlt = (prevEstimatedVelocityAlt * 0.8F) + (float)(-0.02 + computeVerticalWaterFlowForce(estimatedPositionAlt, pp));
116
117
                if(Math.abs(estimatedVelocity) < MIN_VELOCITY) {
118
                    estimatedVelocity = 0;
119
                }
120
                if(Math.abs(estimatedVelocityAlt) < MIN_VELOCITY) {
121
                    estimatedVelocityAlt = 0;
122
                }
123
                estimatedVelocityAlt += 0.04; //add swimming-up force
124
                if(e.isInWeb()) {
125
                    estimatedVelocity *= 0.05;
126
                    estimatedVelocityAlt *= 0.05;
127
                }
128
            } else if(wasInLava) { //lava functions
129
130
                estimatedVelocity = (prevEstimatedVelocity * 0.5F) - 0.02F;
131
                estimatedVelocityAlt = (prevEstimatedVelocityAlt * 0.5F) - 0.02F;
132
133
                if(Math.abs(estimatedVelocity) < MIN_VELOCITY) {
134
                    estimatedVelocity = 0;
135
                }
136
                if(Math.abs(estimatedVelocityAlt) < MIN_VELOCITY) {
137
                    estimatedVelocityAlt = 0;
138
                }
139
                estimatedVelocityAlt += 0.04; //add swimming-up force
140
                if(e.isInWeb()) {
141
                    estimatedVelocity *= 0.05;
142
                    estimatedVelocityAlt *= 0.05;
143
                }
144
            } else { //air function
145
146
                estimatedVelocity = estimatedVelocityAlt = (prevEstimatedVelocity - 0.08F) * 0.98F;
147
148
                if(Math.abs(estimatedVelocity) < MIN_VELOCITY) {
149
                    estimatedVelocity = 0;
150
                }
151
                if(Math.abs(estimatedVelocityAlt) < MIN_VELOCITY) {
152
                    estimatedVelocityAlt = 0;
153
                }
154
                if(e.isInWeb()) {
155
                    estimatedVelocity *= 0.05;
156
                    estimatedVelocityAlt *= 0.05;
157
                }
158
159
                if(pp.isInWater() || pp.isInLava()) { //Entering liquid. You could take two paths depending if you're holding the jump button or not.
160
161
                    estimatedVelocity = (prevEstimatedVelocity + (float)computeVerticalWaterFlowForce(estimatedPosition, pp) - 0.08F) * 0.98F;
162
                    estimatedVelocity += computeVerticalWaterFlowForce(estimatedPosition, pp);
163
164
                    estimatedVelocityAlt = (prevEstimatedVelocityAlt + (float)computeVerticalWaterFlowForce(estimatedPositionAlt, pp) - 0.08F) * 0.98F;
165
                    estimatedVelocityAlt += computeVerticalWaterFlowForce(estimatedPositionAlt, pp);
166
167
                    if(Math.abs(estimatedVelocity) < MIN_VELOCITY) {
168
                        estimatedVelocity = 0;
169
                    }
170
                    if(Math.abs(estimatedVelocityAlt) < MIN_VELOCITY) {
171
                        estimatedVelocityAlt = 0;
172
                    }
173
                    estimatedVelocityAlt += 0.04; //add swimming-up force
174
                    if(e.isInWeb()) {
175
                        estimatedVelocity *= 0.05;
176
                        estimatedVelocityAlt *= 0.05;
177
                    }
178
                }
179
            }
180
181
            //handle teleport
182
            if (pp.getCurrentTick() - pp.getLastTeleportAcceptTick() < 2) {
183
                estimatedVelocity = 0;
184
                estimatedVelocityAlt = 0;
185
                velResetA = true;
186
                velResetB = true;
187
            }
188
189
            //add velocities to expected positions
190
            estimatedPositionAlt += estimatedVelocityAlt;
191
            estimatedPosition += estimatedVelocity;
192
193
            //check if hit head
194
            boolean hasHitHead = pp.getBoxSidesTouchingBlocks().contains(Direction.TOP);
195
            if(e.getTo().getY() < estimatedPosition && (e.isTouchingCeiling() && !hasHitHead)) { //standard pos/vel
196
                estimatedPosition = (float) e.getTo().getY();
197
                estimatedVelocity = 0;
198
                velResetA = true;
199
            }
200
201
            //check if hit head while swimming
202
            if(e.getTo().getY() < estimatedPositionAlt && e.getTo().getY() > estimatedPosition &&
203
                    (pp.isInWater() || pp.isInLava() || pp.isSwimming()) && (e.isTouchingCeiling() || hasHitHead)) { //alt. pos/vel
204
                estimatedPositionAlt = (float) e.getTo().getY();
205
                estimatedVelocityAlt = 0;
206
                velResetB = true;
207
            }
208
209
            //check landing
210
            if(e.isOnGround() && !pp.isOnGround()) {
211
                //Pretty much check if the Y is within reasonable bounds.
212
                //Doesn't need to be so precise i.e. 0.0001 within bounds, leave that for GroundSpoof and Phase.
213
                //However, if it becomes a problem, you know how to expand this code.
214
                float y;
215
216
                if(moved) {
217
                    y = (float) e.getTo().getY();
218
                } else {
219
                    y = (float) pp.getPositionPredicted().getY();
220
                }
221
222
                double fromY = MathPlus.round(from.getY(), 10);
223
224
                float discrepancy = y - estimatedPosition;
225
                //y must be between last Y and estimatedPosition, and dY must be <= 0 (MAYBE that's already inherent with the former, but I have this for redundancy).
226
                if (Math.abs(discrepancy) > DISCREPANCY_THRESHOLD && !e.isPossiblePistonPush() &&
227
                        ((y - pp.getPreviousPositionPredicted().getY()) > 0 || y < Math.min(estimatedPosition, fromY) || y > Math.max(estimatedPosition, fromY))) {
228
                    punishAndTryRubberband(pp, e);
229
                } else {
230
                    reward(pp);
231
                }
232
233
                //If you've landed, then that must mean these should reset.
234
                estimatedPosition = y;
235
                estimatedPositionAlt = y;
236
237
                if(e.isNextSlimeBlockBounce()) {
238
                    prevEstimatedVelocity = -estimatedVelocity;
239
                } else {
240
                    prevEstimatedVelocity = 0;
241
                }
242
243
                prevEstimatedVelocityAlt = prevEstimatedVelocity;
244
            }
245
246
            //check for Y discrepancy in air
247
            else {
248
249
                //bool alt determines if we're using the alternate path for comparison
250
                boolean alt;
251
252
                if(moved || noMoves > MAX_NO_MOVES || (Math.abs(estimatedPosition - e.getTo().getY()) > NO_MOVE_THRESHOLD && Math.abs(estimatedPositionAlt - e.getTo().getY()) > NO_MOVE_THRESHOLD)) {
253
254
                    float discrepancy;
255
256
                    if(ticksSinceNoPosUpdate < 2 && noMoves <= MAX_NO_MOVES) {
257
                        //Handle stupid-moves with a range check.
258
                        //Honestly, I don't care about an error of 0.03 in liquids while the client isn't updating its position.
259
                        float y = (float) e.getTo().getY();
260
                        float max = Math.max(estimatedPositionAlt, estimatedPosition);
261
                        float min = Math.min(estimatedPositionAlt, estimatedPosition);
262
                        if(y > max) {
263
                            discrepancy = y - max;
264
                        } else if(y < min) {
265
                            discrepancy = y - min;
266
                        } else {
267
                            discrepancy = 0;
268
                        }
269
                    } else {
270
                        float discrepancyA = (float) e.getTo().getY() - estimatedPosition;
271
                        float discrepancyB = (float) e.getTo().getY() - estimatedPositionAlt;
272
                        //choose discrepancy closer to 0
273
                        alt = Math.abs(discrepancyA) - Math.abs(discrepancyB) > 0;
274
                        discrepancy = alt ? discrepancyB : discrepancyA;
275
                    }
276
277
                    boolean onSlimeBlock;
278
                    if(Hawk.getServerVersion() > 7) {
279
                        //-0.1 is arbitrary
280
                        Block block = ServerUtils.getBlockAsync(e.getFrom().clone().add(0, -0.2, 0));
281
                        onSlimeBlock = block != null && block.getType() == Material.SLIME_BLOCK
282
                                && Math.abs(dY) < 0.1;
283
                    } else {
284
                        onSlimeBlock = false;
285
                    }
286
287
                    if(Math.abs(discrepancy) > DISCREPANCY_THRESHOLD && !e.isPossiblePistonPush() && !onSlimeBlock) {
288
                        punishAndTryRubberband(pp, e);
289
                    }
290
                    else {
291
                        reward(pp);
292
                    }
293
                }
294
295
                //TODO limit these estimatedVelocities to 0.03 if this is a no-move. Likewise, limit the estimated positions, too.
296
297
                if(moved) {
298
                    //we can use these for next move, since the client has sent a pos update
299
                    estimatedPosition = estimatedPositionAlt = (float) e.getTo().getY();
300
                    if(ticksSinceNoPosUpdate > 0) {
301
                        estimatedVelocity = velResetA ? estimatedVelocity : dY;
302
                        estimatedVelocityAlt = velResetB ? estimatedVelocityAlt : dY;
303
                    }
304
                }
305
306
                //keep estimating
307
                if (e.isInWeb()) {
308
                    prevEstimatedVelocity = prevEstimatedVelocityAlt = 0;
309
                } else {
310
                    prevEstimatedVelocity = estimatedVelocity;
311
                    prevEstimatedVelocityAlt = estimatedVelocityAlt;
312
                }
313
            }
314
        } else {
315
            if(moved) {
316
                estimatedPosition = estimatedPositionAlt = (float) e.getTo().getY();
317
            } else {
318
                estimatedPosition = estimatedPositionAlt = (float) pp.getPositionPredicted().getY();
319
            }
320
321
            if(e.isOnGround() || (e.isTouchingCeiling() && dY > 0) || touchedBlocks.contains(Material.WEB)) {
322
                prevEstimatedVelocity = prevEstimatedVelocityAlt = 0;
323
            } else {
324
                prevEstimatedVelocity = prevEstimatedVelocityAlt = dY;
325
            }
326
        }
327
        //Debug.broadcastMessage((moved ? ChatColor.GREEN : ChatColor.RED) + "" + e.getTo().getY() + " " + estimatedPosition + " " + pp.getPositionPredicted().getY() + " prevEstDY: " + prevEstimatedVelocity);
328
329
        estimatedVelocityMap.put(pp.getUuid(), prevEstimatedVelocity);
330
        estimatedVelocityAltMap.put(pp.getUuid(), prevEstimatedVelocityAlt);
331
        estimatedPositionMap.put(pp.getUuid(), estimatedPosition);
332
        estimatedPositionAltMap.put(pp.getUuid(), estimatedPositionAlt);
333
334
        noMovesMap.put(pp.getUuid(), noMoves);
335
336
        if(!moved) {
337
            ticksSinceNoPosUpdate = 0;
338
        } else {
339
            ticksSinceNoPosUpdate++;
340
        }
341
342
        ticksSinceNoPosUpdateMap.put(p.getUniqueId(), ticksSinceNoPosUpdate);
343
344
        if(pp.isFlying()) {
345
            wasFlyingSet.add(p.getUniqueId());
346
        } else {
347
            wasFlyingSet.remove(p.getUniqueId());
348
        }
349
350
        if(pp.isInLava()) {
351
            wasInLavaSet.add(p.getUniqueId());
352
        } else {
353
            wasInLavaSet.remove(p.getUniqueId());
354
        }
355
    }
356
357
    private boolean isOnBoat(Player p, Location loc) {
358
        Set<Entity> trackedEntities = hawk.getLagCompensator().getPositionTrackedEntities();
359
        int ping = ServerUtils.getPing(p);
360
        for(Entity entity : trackedEntities) {
361
            if (entity instanceof Boat) {
362
                AABB boatBB = WrappedEntity.getWrappedEntity(entity).getCollisionBox(hawk.getLagCompensator().getHistoryLocation(ping, entity).toVector());
363
                AABB feet = new AABB(
364
                        new Vector(-0.3, -0.4, -0.3).add(loc.toVector()),
365
                        new Vector(0.3, 0, 0.3).add(loc.toVector()));
366
                feet.expand(0.5, 0.5, 0.5);
367
                if (feet.isColliding(boatBB))
368
                    return true;
369
            }
370
        }
371
        return false;
372
    }
373
374
    private boolean isInClimbable(Location loc) {
375
        Block b = ServerUtils.getBlockAsync(loc);
376
        return b != null && (b.getType() == Material.VINE || b.getType() == Material.LADDER);
377
    }
378
379
    private double computeVerticalWaterFlowForce(double y, HawkPlayer pp) {
380
        Vector vec = new Vector();
381
        AABB liquidTest = AABB.playerWaterCollisionBox.clone();
382
        liquidTest.translate(new Vector(pp.getPosition().getX(), y, pp.getPosition().getZ()));
383
        List<Block> blocks = liquidTest.getBlocks(pp.getPlayer().getWorld());
384
        Vector waterFlow = new Vector();
385
        for(Block b : blocks) {
386
            if(b.getType() == Material.WATER || b.getType() == Material.STATIONARY_WATER) {
387
                //game version doesn't really matter for this
388
                Vector direction = WrappedBlock.getWrappedBlock(b, 8).getFlowDirection();
389
                waterFlow.add(direction);
390
            }
391
        }
392
        if(waterFlow.lengthSquared() > 0 && !pp.isFlying()) {
393
            waterFlow.normalize();
394
            waterFlow.multiply(0.014);
395
            vec.add(waterFlow);
396
        }
397
        return vec.getY();
398
    }
399
400
401
    @Override
402
    public void removeData(Player p) {
403
        UUID uuid = p.getUniqueId();
404
        estimatedPositionMap.remove(uuid);
405
        estimatedVelocityMap.remove(uuid);
406
        estimatedPositionAltMap.remove(uuid);
407
        estimatedVelocityAltMap.remove(uuid);
408
        noMovesMap.remove(uuid);
409
        ticksSinceNoPosUpdateMap.remove(uuid);
410
        wasFlyingSet.remove(uuid);
411
    }
412
}

How it counteracts this module

Hawk's Fly runs a per-player vertical simulation. In air it predicts the next velocity as (previous estimated velocity - 0.08) * 0.98 and integrates it into an estimated position; the reported Y is compared against that estimate, and any discrepancy over the 0.0001 threshold is punished with a rubberband set-back. The hover modes fail the model immediately: Vanilla's zero motionY while airborne diverges from the predicted fall of about 0.0784 per tick within one or two ticks, and the module's motionY writes of several blocks per tick produce discrepancies of multiple blocks.

The trajectory modes fail differently. Verus Lag's 20-block drop is a position delta no gravity simulation produces, so the estimated position and the reported position separate by tens of blocks and the rubberband fires on the first drop. Vulcan's pinned posY with periodic 3.7 spikes creates a sawtooth profile that the integrator never matches. The Hypixel mode's timer speed of 2 doubles the tick rate, so even its small motion writes are reported at twice the rate the simulation expects. When the client reports onGround, the check also requires the reported Y to fall between the previous Y and the estimated position, so the ground fakes in Verus Lag, Vulcan2 and the Exempted Value modes, which claim ground while the position is mid-air, land outside that window.

The check tolerates at most 20 ticks without a position update, so the packet-buffer modes (Hypixel Blink, Spartan, Minemenclub) cannot hide by holding back movement packets. The modes that convert flight into block interaction, such as BlockFly and Matrix1.17 with their C08 placement streams, produce movement that the vertical model partly explains, but the horizontal acceleration from the placement is still outside the gravity-only prediction.

← Back to Analysis Hub