Rise 5.99 Speed module 2 files, 2273 lines

Rise 5.99 Speed: Full Source Analysis

Rise 5.99's Speed is a thirty-plus-mode movement module that spreads its logic across five event handlers: onPreMotion is the master tick switch that implements most modes, onMove runs the Mineplex…

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

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

Packets This Module Uses

Analysis

Overview

Rise 5.99's Speed is a thirty-plus-mode movement module that spreads its logic across five event handlers: onPreMotion is the master tick switch that implements most modes, onMove runs the Mineplex and Verus Low/YPort strafe sequences, onStrafe executes the friction-tuned modes (Cubecraft, Hypixel2/3, NCP Latest, Hypixel) from the client's strafe event, onPacketSend cancels or re-buffers outgoing packets, and onPacketReceive eats or reacts to S08 teleports. The default Custom mode is a full toolkit: jump control, per-tick horizontal strafe pins with randomized jitter, onGround flag spoofing, extra grounded C04 duplicates, fast-fall, void teleports and a timer multiplier. The per-server modes range from near-vanilla bhops (Strafe Hop, Minemenclub Hop) to packet-spam converters (Vulcan2, Convert Ground), timer abuse (Timer Bypass, NCP, Hypixel), and ground-spoofed hops that fly on the vertical axis (Verus Float, Predictive).

Architecture

The module carries a huge settings tower (Custom, Hypixel, NCP Latest, Verus, Timer Bypass and Vape parameter groups) and a handful of state fields: ticks, offGroundTicks, onGroundTicks, stage, startY, speed, jumped, bool, touchedGround, verusEpicBypassBooleanTM, and an ArrayDeque<Packet> used by Timer Bypass. onPreMotion increments ticks and ticksDisable, and everything is gated behind a 50-tick grace period: below 50 the handler returns, at exactly 50 onEnable() re-initializes the state. The module refuses to run while the Fly module is enabled, and onPacketReceive reacts to every S08PacketPlayerPosLook: with disableOnFlag (default on) a teleport sets ticksDisable = 0, calls onDisable() and shows a notification, so the module re-arms after the grace period instead of staying flagged; the Zonecraft mode instead eats the S08 and re-sends the teleport target as a C04 with onGround true, Hypixel2 cancels a single S08, and Vulcan2 cancels any S08 within 10 blocks. onDisable restores speedInAir 0.02, jumpMovementFactor 0.02 and timer 1.0, flushes any buffered packets through sendPacketWithoutEvent, and with Stop on Disable zeroes the motion. The smoothCamera setting hides the hop visually by driving EntityPlayer.enableCameraYOffset and cameraYPosition from startY whenever posY rises above it.

Custom mode toolkit

Custom is the mode the user is expected to tune, and each toggle attacks a different server-side envelope. On a ground tick while moving it jumps with customMotionY (the value is snapped to exactly 0.42f when it is within 1.0E-3 of vanilla, so the default jump is indistinguishable from a real one) and pins the horizontal speed with MoveUtil.strafe(customSpeed + randomize), where randomize is a symmetric jitter drawn from randomizeSpeed/100. With Abide Friction enabled the pin is replaced by a momentum-preserving strafe: ground ticks re-apply customSpeed, air ticks call strafe() with the current magnitude so friction decays it naturally. groundDisabler alternates the reported ground flag (event.setGround(ticks % 2 == 0)), Extra OnGround Packets injects up to ten duplicate C04 positions with onGround true per tick, fastFall drops motionY to -customFallMotion on the chosen off-ground tick, VoidTP sends a C04 at posY - 16 - Math.random() every N ticks to keep the server's move window open, and the timer setting (plus timerRandom jitter) multiplies client ticks. groundSpoofMode completes the set with three rewrites of the packet flag: On forces ground true every tick, Air forces it false, and Tick forces it true on a chosen interval.

Packet, timer and air-strafe modes

Timer Bypass is the purest timer exploit in the file: onPacketSend buffers every outgoing packet into the deque, cancels it, runs mc.timer.timerSpeed at the speedTimer setting (2.0 by default), and every pulse ticks (default 20) flushes the whole buffer through sendPacketWithoutEvent, which bypasses the event bus so the re-sent packets are not re-buffered - 40 ticks of movement compressed into a 20-tick burst. Vulcan2 fires five C06/C04 packets per ground tick (midpoint pairs at y - 0.0784, onGround alternating) on top of a 2.5x base strafe. Convert Ground re-emits up to `distance` (2-200) C06 packets every howOften ticks, each spaced speed*(i+1) blocks along the movement vector with randomized yaw and pitch. NCP Latest jumps with 0.4 + rand/500 motion, multiplies ground motionX/Z by speedMultiplierNCP (1.05 default, up to 1.35), raises speedInAir to 0.02-0.06, and its smartTimer computes timerSpeed = 1.337 - current speed (clamped 0.6-1.5). The Hypixel mode low-hops with 0.4/0.42 jumps shaped by lowHopYModification (a lookup keyed to the rounded y-fraction that returns 0.31, 0.04, -0.2 or -0.14 at the canonical hop heights), strafes at baseMoveSpeed * 1.6 on ground (2x on ice), bleeds speed with bunny = (0.84 + rand/50) * (lastDist - base), and runs the timer at hypixelTimer - rand/50. Verus Hop jumps and strafes 0.55/0.349, cancels every C0F in onPacketSend, and spams C0B sneak/sprint every 200ms; Verus Float ground-spoofs with setGround(true) and motionY 0.42 at timer 2.1 on the ground, then holds motionY 0 and timer 0.9 in the air with the ground flag forced true (and the onGround field itself set true), throttling to strafe 0.2865 after ten air ticks.

source Speed.java (module)

Speed.java1921 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 dev.rise.Rise;
10
import dev.rise.event.impl.motion.PreMotionEvent;
11
import dev.rise.event.impl.other.*;
12
import dev.rise.event.impl.packet.PacketReceiveEvent;
13
import dev.rise.event.impl.packet.PacketSendEvent;
14
import dev.rise.event.impl.render.Render2DEvent;
15
import dev.rise.font.CustomFont;
16
import dev.rise.module.Module;
17
import dev.rise.module.api.ModuleInfo;
18
import dev.rise.module.enums.Category;
19
import dev.rise.module.impl.combat.Aura;
20
import dev.rise.module.impl.player.Scaffold;
21
import dev.rise.setting.impl.BooleanSetting;
22
import dev.rise.setting.impl.ModeSetting;
23
import dev.rise.setting.impl.NumberSetting;
24
import dev.rise.util.math.TimeUtil;
25
import dev.rise.util.player.MoveUtil;
26
import dev.rise.util.player.PacketUtil;
27
import dev.rise.util.player.PlayerUtil;
28
import net.minecraft.block.*;
29
import net.minecraft.client.gui.ScaledResolution;
30
import net.minecraft.client.settings.KeyBinding;
31
import net.minecraft.entity.player.EntityPlayer;
32
import net.minecraft.item.Item;
33
import net.minecraft.item.ItemStack;
34
import net.minecraft.network.Packet;
35
import net.minecraft.network.login.server.S00PacketDisconnect;
36
import net.minecraft.network.play.client.*;
37
import net.minecraft.network.play.server.S08PacketPlayerPosLook;
38
import net.minecraft.potion.Potion;
39
import net.minecraft.util.AxisAlignedBB;
40
import net.minecraft.util.BlockPos;
41
import net.minecraft.util.MathHelper;
42
import org.lwjgl.input.Keyboard;
43
44
import java.awt.*;
45
import java.math.BigDecimal;
46
import java.math.RoundingMode;
47
import java.util.ArrayDeque;
48
import java.util.Deque;
49
import java.util.Objects;
50
51
import static dev.rise.module.impl.movement.Fly.roundToOnGround;
52
53
/**
54
 * Gives you a boost of speed or an improved strafing.
55
 */
56
@ModuleInfo(name = "Speed", description = "Lets you move faster", category = Category.MOVEMENT)
57
public final class Speed extends Module {
58
59
    private final ModeSetting mode = new ModeSetting("Mode", this, "Custom", "Custom", "Mineplex", "Strafe Hop",
60
            "Vulcan", "Mineplex Low", "Mineplex Smooth", "Hypixel", "Hypixel2", "Hypixel3", "Hypixel Smooth", "Cubecraft", "CraftPlay", "NCP",
61
            "Timer Bypass", "Taka", "Verus", "Spartan", "Redesky", "Zonecraft", "Bridger Land", "Exempted Value", "NCP Latest",
62
            "Convert Ground", "AAC 4 Simple", "Invadedlands", "Minemenclub Hop", "Intave", "Teleport", "Predictive",
63
            "Vulcan2"/*, "Vape", "MineBox"*/, "BlocksMC", "KoksCraft");
64
    private final BooleanSetting craftplayTimer = new BooleanSetting("Timer", this, false);
65
    private final BooleanSetting koksStrafe = new BooleanSetting("Strafe", this, false);
66
    private final ModeSetting exemptedValueType = new ModeSetting("Value", this, "1", "1", "2", "3");
67
    private final ModeSetting vapeMode = new ModeSetting("Vape Mode", this, "AntiCheat A", "AntiCheat A", "AntiCheat B", "Bhop", "Y-Port");
68
    private final NumberSetting vapeSteps = new NumberSetting("Vape Steps", this, 43.5, 10, 180, 0.1);
69
    private final ModeSetting verusMode = new ModeSetting("Verus Mode", this, "Hop", "Hop", "Low", "Float", "YPort");
70
71
    private final ModeSetting groundSpoofMode = new ModeSetting("GroundSpoof", this, "Off", "Off", "On", "Air", "Tick");
72
    private final NumberSetting customSpeed = new NumberSetting("Custom Speed", this, 0.35, 0.0, 4.0, 0.01);
73
    private final NumberSetting customMotionY = new NumberSetting("Custom MotionY", this, 0.42F, 0.0, 1.0, 0.01);
74
    private final NumberSetting customFallMotion = new NumberSetting("Custom Fall Motion", this, 0.4, 0.0, 1.0, 0.01);
75
    private final NumberSetting fallTick = new NumberSetting("Custom Fall Tick", this, 2, 0.0, 12, 1);
76
    private final NumberSetting extraGround = new NumberSetting("Extra OnGround Packets", this, 0, 0, 10, 1);
77
    private final NumberSetting randomizeSpeed = new NumberSetting("Randomize Speed", this, 0.0, 0.0, 10, 0.1);
78
    private final NumberSetting voidTpTicks = new NumberSetting("Void TP Ticks", this, 0.0, 0.0, 50, 1);
79
    private final NumberSetting timer = new NumberSetting("Timer", this, 1.0, 0.1, 10, 0.1);
80
    private final NumberSetting timerRandom = new NumberSetting("Timer Random", this, 0.0, 0.0, 10, 0.1);
81
    private final NumberSetting groundSpoofTick = new NumberSetting("GroundSpoof Ticks", this, 0.0, 0.0, 10, 1);
82
83
    private final NumberSetting teleportDistance = new NumberSetting("Teleport Distance", this, 0.03, 0.0, 1, 0.01);
84
    private final BooleanSetting strafe = new BooleanSetting("Strafe", this, false);
85
86
    private final BooleanSetting mmcVL = new BooleanSetting("MMC VL Abuse", this, false);
87
88
    private final BooleanSetting friction = new BooleanSetting("Abide Friciton", this, false);
89
    private final BooleanSetting strafeOnGround = new BooleanSetting("Only Strafe On Ground", this, false);
90
    private final BooleanSetting groundDisabler = new BooleanSetting("Ground Disabler", this, false);
91
    private final BooleanSetting fastFall = new BooleanSetting("FastFall", this, false);
92
    private final BooleanSetting voidTP = new BooleanSetting("VoidTP", this, false);
93
    private final BooleanSetting voidTPMove = new BooleanSetting("VoidTP only Move", this, false);
94
    private final BooleanSetting cancelC0F = new BooleanSetting("Cancel C0F", this, false);
95
    private final BooleanSetting cancelC00 = new BooleanSetting("Cancel C00", this, false);
96
97
    private final NumberSetting speedTimer = new NumberSetting("Speed", this, 2, 0.1, 6.0, 0.1);
98
    private final NumberSetting pulse = new NumberSetting("Pulse", this, 20, 4, 100, 0.1);
99
100
    private final BooleanSetting damageBoost = new BooleanSetting("Damage Boost", this, false);
101
102
    private final NumberSetting speedMulti = new NumberSetting("Speed Multiplier", this, 1.1, 1, 2, 0.1);
103
    private final NumberSetting timerBoost = new NumberSetting("Timer Boost", this, 1.1, 1, 4, 0.1);
104
105
    private final NumberSetting tick = new NumberSetting("Tick", this, 1, 0.0, 12, 0.1);
106
    private final BooleanSetting groundSpoof = new BooleanSetting("GroundSpoof", this, false);
107
108
    private final BooleanSetting smoothCamera = new BooleanSetting("Hide Jumps", this, false);
109
110
    private final NumberSetting speedMultiplierNCP = new NumberSetting("Speed Multiplier No Speed", this, 1.05, 1,
111
            1.35, 0.01);
112
    private final NumberSetting speedMultiplierNCPSpeed1 = new NumberSetting("Speed Multiplier Speed 1", this, 1.05, 1
113
            , 1.35, 0.01);
114
    private final NumberSetting speedMultiplierNCPSpeed2 = new NumberSetting("Speed Multiplier Speed 2", this, 1.05, 1
115
            , 1.35, 0.01);
116
    private final NumberSetting timerNcp = new NumberSetting("General Timer", this, 1, 1, 1.4, 0.1);
117
    private final NumberSetting speedInAirNcp = new NumberSetting("SpeedInAir No Speed", this, 0.02, 0.02, 0.06, 0.01);
118
    private final NumberSetting speedInAirNcpSpeed1 = new NumberSetting("SpeedInAir Speed 1", this, 0.02, 0.02, 0.06,
119
            0.01);
120
    private final NumberSetting speedInAirNcpSpeed2 = new NumberSetting("SpeedInAir Speed 2", this, 0.02, 0.02, 0.06,
121
            0.01);
122
    private final BooleanSetting smartTimer = new BooleanSetting("Smart Timer", this, false);
123
    private final BooleanSetting revertNcpSpeed = new BooleanSetting("Revert to fastest on default config", this,
124
            false);
125
126
    private final NumberSetting howOften = new NumberSetting("How Often", this, 1, 1, 50, 0.01);
127
    private final NumberSetting distance = new NumberSetting("Distance", this, 2, 2, 200, 0.01);
128
129
    private final BooleanSetting disableOnFlag = new BooleanSetting("Disable on flag", this, true);
130
    private final BooleanSetting stopOnDisable = new BooleanSetting("Stop on Disable", this, true);
131
    private final BooleanSetting disableOnWorldChange = new BooleanSetting("Disable on World Change", this, false);
132
133
    private final BooleanSetting hypixeldamageBoost = new BooleanSetting("Damage Boost", this, false);
134
    private final NumberSetting hypixelTimer = new NumberSetting("Hypixel Timer", this, 1, 1, 2.25, 0.05);
135
    private final NumberSetting hypixelCombatTimer = new NumberSetting("Hypixel Combat Timer", this, 1, 1, 2.25, 0.05);
136
137
    private long balance, lastPreMotion;
138
    private int ticks, offGroundTicks, onGroundTicks, stage, ticksDisable;
139
    private double startY, speed;
140
    private boolean jumped, bool, verusEpicBypassBooleanTM, touchedGround;
141
    private final Deque<Packet<?>> packets = new ArrayDeque<>();
142
143
    private float targetYaw;
144
145
    boolean firstEnable;
146
    private boolean boost;
147
    private float lastYaw;
148
    private float yaw;
149
150
    // Vape AntiCheat A
151
    private float v;
152
    private int x = 0;
153
154
    // Vape Speed parent
155
    private double z, vapeSpeedVar;
156
    private int parentX = 2;
157
158
    private final TimeUtil stopwatch = new TimeUtil();
159
160
    @Override
161
    protected void onEnable() {
162
        ticks = 0;
163
        offGroundTicks = 0;
164
        speed = 0;
165
        onGroundTicks = 0;
166
        startY = mc.thePlayer.posY;
167
        packets.clear();
168
169
        stage = 0;
170
        verusEpicBypassBooleanTM = false;
171
        touchedGround = false;
172
        bool = false;
173
        jumped = false;
174
        ticksDisable = 60;
175
//        switch (mode.getMode()) {
176
//            case "Hypixel":
177
//                targetYaw = mc.thePlayer.rotationYaw;
178
//                break;
179
//        }
180
        if(mode.getMode().equals("KoksCraft")) {
181
            if(koksStrafe.isEnabled()) {
182
                if (!firstEnable) {
183
                    firstEnable = true;
184
                    this.registerNotification("Strafe Is Flagless");
185
                }
186
            }
187
        }
188
        if (mode.getMode().equals("Vape") && vapeMode.getMode().equals("AntiCheat A")) {
189
            parentX = 1;
190
            x = 0;
191
            z = 0.0D;
192
193
            double var1 = 0.2873F;
194
            if (mc.thePlayer.isPotionActive(1) && mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getDuration() > 10) {
195
                int var4 = mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier();
196
                var1 *= 1.0D + 0.15D * (double) (var4 + 1);
197
            }
198
199
            this.vapeSpeedVar = var1;
200
        }
201
    }
202
203
    @Override
204
    protected void onDisable() {
205
        boost = false;
206
        mc.thePlayer.speedInAir = 0.02f;
207
        mc.thePlayer.jumpMovementFactor = 0.02f;
208
209
        mc.timer.timerSpeed = 1;
210
211
        EntityPlayer.enableCameraYOffset = false;
212
//        EntityPlayer.movementYaw = null;
213
214
        if (stopOnDisable.isEnabled())
215
            MoveUtil.stop();
216
217
        if (packets.isEmpty()) return;
218
219
        packets.forEach(PacketUtil::sendPacketWithoutEvent);
220
        packets.clear();
221
    }
222
223
    @Override
224
    public void onUpdateAlwaysInGui() {
225
        fallTick.hidden = customFallMotion.hidden = !fastFall.isEnabled() || !mode.is("Custom");
226
227
        voidTPMove.hidden = voidTpTicks.hidden = !voidTP.isEnabled() || !mode.is("Custom");
228
229
        strafeOnGround.hidden = voidTP.hidden = groundSpoofTick.hidden = groundSpoofMode.hidden = cancelC00.hidden =
230
                cancelC0F.hidden = timerRandom.hidden = randomizeSpeed.hidden = customSpeed.hidden =
231
                        customMotionY.hidden = friction.hidden = groundDisabler.hidden = fastFall.hidden =
232
                                customFallMotion.hidden = fallTick.hidden = extraGround.hidden = !mode.is("Custom");
233
234
        timer.hidden = !(mode.is("Vape") || mode.is("Custom"));
235
236
        groundSpoofTick.hidden = !groundSpoofMode.is("Tick") && mode.is("Custom") || !mode.is("Custom");
237
238
        speedTimer.hidden = pulse.hidden = !mode.is("Timer Bypass");
239
240
        damageBoost.hidden = !mode.is("Verus") || !verusMode.is("Hop");
241
242
        speedMulti.hidden = timerBoost.hidden = !mode.is("NCP");
243
244
        craftplayTimer.hidden = !mode.is("CraftPlay");
245
246
        koksStrafe.hidden = !mode.is("KoksCraft");
247
248
        tick.hidden = strafe.hidden = groundSpoof.hidden = !mode.is("Exempted Value");
249
250
        strafe.hidden = !(mode.is("Strafe Hop") || mode.is("Exempted Value") || mode.is("Teleport"));
251
252
        verusMode.hidden = !(mode.is("Verus"));
253
254
        speedMultiplierNCP.hidden = speedMultiplierNCPSpeed1.hidden = speedMultiplierNCPSpeed2.hidden =
255
                speedInAirNcp.hidden = speedInAirNcpSpeed1.hidden = speedInAirNcpSpeed2.hidden =
256
                        revertNcpSpeed.hidden = !mode.is("NCP Latest");
257
        vapeMode.hidden = !mode.is("Vape");
258
        vapeSteps.hidden = !(mode.is("Vape") && vapeMode.is("AntiCheat A"));
259
260
        timerNcp.hidden = !(mode.is("NCP Latest") && !smartTimer.isEnabled());
261
262
        smartTimer.hidden = !mode.is("NCP Latest");
263
264
        hypixelTimer.hidden = !mode.is("Hypixel") && !mode.is("Hypixel2") && !mode.is("Hypixel3") && !mode.is("Hypixel Smooth");
265
266
        hypixelCombatTimer.hidden = !mode.is("Hypixel") && !mode.is("Hypixel2") && !mode.is("Hypixel3") && !mode.is("Hypixel Smooth");
267
268
        hypixeldamageBoost.hidden = !mode.is("Hypixel2");
269
270
        howOften.hidden = distance.hidden = !mode.is("Convert Ground");
271
272
        exemptedValueType.hidden = !mode.is("Exempted Value");
273
274
        teleportDistance.hidden = !mode.is("Teleport");
275
276
        mmcVL.hidden = !mode.is("Minemenclub Hop");
277
278
        if (revertNcpSpeed.isEnabled()) {
279
            revertNcpSpeed.setEnabled(false);
280
281
            speedMultiplierNCP.setValue(1.07);
282
            speedMultiplierNCPSpeed2.setValue(1.1);
283
            speedMultiplierNCPSpeed1.setValue(1.1);
284
            timerNcp.setValue(1.07);
285
            speedInAirNcp.setValue(0.02);
286
            speedInAirNcpSpeed1.setValue(0.025);
287
            speedInAirNcpSpeed2.setValue(0.03);
288
            smartTimer.setEnabled(true);
289
        }
290
291
        if (!Rise.devMode && mode.getMode().equals("Vape")) mode.set("Custom");
292
    }
293
294
    @Override
295
    public void onUpdateAlways() {
296
297
    }
298
299
    @Override
300
    public void onPreMotion(final PreMotionEvent event) {
301
302
        ++ticks;
303
        ticksDisable++;
304
305
        if (ticksDisable < 50) {
306
            return;
307
        }
308
309
        if (ticksDisable == 50) onEnable();
310
311
        if (mc.thePlayer.ticksExisted == 1) toggleModule();
312
        if (Objects.requireNonNull(Rise.INSTANCE.getModuleManager().getModule("Fly")).isEnabled()) return;
313
314
        if (mc.thePlayer.onGround) {
315
            offGroundTicks = 0;
316
            onGroundTicks += 1;
317
            if (!verusMode.is("Float"))
318
                startY = mc.thePlayer.posY - 0.01;
319
        } else {
320
            offGroundTicks += 1;
321
            onGroundTicks = 0;
322
        }
323
324
        EntityPlayer.enableCameraYOffset = false;
325
326
        if (mc.thePlayer.posY > startY && smoothCamera.isEnabled()) {
327
            EntityPlayer.enableCameraYOffset = true;
328
            EntityPlayer.cameraYPosition = startY;
329
        }
330
331
        switch (mode.getMode()) {
332
333
            case "Custom":
334
                if (MoveUtil.isMoving()) {
335
                    final double randomConst =
336
                            randomizeSpeed.getValue() < 0.1 ? 0.0 : randomDouble(0.0, randomizeSpeed.getValue() / 100);
337
                    final double randomize = (random() < 0.5 ? -randomConst : randomConst);
338
339
                    if (mc.thePlayer.onGround) {
340
                        final double jumpValue = customMotionY.getValue();
341
342
                        mc.thePlayer.motionY = (Math.abs(jumpValue - 0.42F) < 1.0E-3) ? 0.42f : jumpValue;
343
344
                        if (friction.isEnabled()) {
345
                            MoveUtil.strafe(customSpeed.getValue() + randomize);
346
                        }
347
348
                        if (groundDisabler.isEnabled()) {
349
                            event.setGround(ticks % 2 == 0);
350
                        }
351
352
                        for (int i = 0; i < extraGround.getValue(); i++) {
353
                            PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
354
                        }
355
                    }
356
357
                    if (!friction.isEnabled()) {
358
                        if (strafeOnGround.isEnabled()) {
359
                            if (mc.thePlayer.onGround) {
360
                                MoveUtil.strafe(customSpeed.getValue() + randomize);
361
                            }
362
                        } else {
363
                            MoveUtil.strafe(customSpeed.getValue() + randomize);
364
                        }
365
                    } else {
366
                        if (strafeOnGround.isEnabled()) {
367
                            if (mc.thePlayer.onGround) {
368
                                MoveUtil.strafe();
369
                            }
370
                        } else {
371
                            MoveUtil.strafe();
372
                        }
373
                    }
374
375
                    if (fastFall.isEnabled()) {
376
                        if (offGroundTicks == Math.round(fallTick.getValue())) {
377
                            mc.thePlayer.motionY = -customFallMotion.getValue();
378
                        }
379
                    }
380
                } else {
381
                    mc.thePlayer.motionZ = mc.thePlayer.motionX = 0;
382
                }
383
384
                if (voidTP.isEnabled()) {
385
                    if (voidTpTicks.getValue() >= 0.5 && ticks % Math.round(voidTpTicks.getValue()) == 0) {
386
                        if (voidTPMove.isEnabled()) {
387
                            if (MoveUtil.isMoving()) {
388
                                mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX,
389
                                        mc.thePlayer.posY - 16 - Math.random(), mc.thePlayer.posZ, event.isGround()));
390
                            }
391
                        } else {
392
                            mc.getNetHandler().addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX,
393
                                    mc.thePlayer.posY - 16 - Math.random(), mc.thePlayer.posZ, event.isGround()));
394
                        }
395
                    }
396
                }
397
398
                final float timerRandomConst = (float) (timerRandom.getValue() < 0.1 ? 0.0 :
399
                        randomDouble(0.0, timerRandom.getValue() / 100)
400
                );
401
                final float timerRandomize = (random() < 0.5 ? -timerRandomConst : timerRandomConst);
402
403
                final boolean timerReset = timer.getValue() - 1.0 < 1E-3 && timer.getValue() - 1.0 > -1E-3;
404
405
                mc.timer.timerSpeed = timerReset ? 1.0F : (float) timer.getValue();
406
                mc.timer.timerSpeed += timerRandomize;
407
408
                switch (groundSpoofMode.getMode().toLowerCase()) {
409
                    case "off":
410
                        break;
411
412
                    case "on": {
413
                        event.setGround(true);
414
                        break;
415
                    }
416
417
                    case "air": {
418
                        event.setGround(false);
419
                        break;
420
                    }
421
422
                    case "tick": {
423
                        if (groundSpoofTick.getValue() > 0.5 && ticks % Math.round(groundSpoofTick.getValue()) == 0) {
424
                            event.setGround(true);
425
                        }
426
427
                        break;
428
                    }
429
                }
430
                break;
431
432
            case "BlocksMC":
433
434
                if (mc.thePlayer.onGround) {
435
                    ticks++;
436
                    MoveUtil.strafe(MoveUtil.getBaseMoveSpeed());
437
                    mc.thePlayer.jump();
438
439
                    if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
440
                        MoveUtil.strafe(MoveUtil.getSpeed() * 1.2);
441
                    }
442
                }
443
444
                mc.timer.timerSpeed = (float) (1.09f - Math.random() / 100f);
445
446
                MoveUtil.strafe();
447
448
                break;
449
450
            case "MineBox": {
451
                if (mc.thePlayer.onGround && MoveUtil.isMoving()) {
452
                    mc.thePlayer.motionY = 0.42F;
453
                    MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 2);
454
455
//                    PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
456
                }
457
458
                MoveUtil.strafe();
459
460
                break;
461
            }
462
463
            case "Vulcan2":
464
                if (mc.thePlayer.onGround && !this.getModule(Scaffold.class).isEnabled() &&
465
                        mc.thePlayer.motionY > -.2) {
466
                    PacketUtil.sendPacket(new C03PacketPlayer.C04PacketPlayerPosition(
467
                            (mc.thePlayer.posX + mc.thePlayer.lastTickPosX) / 2,
468
                            ((mc.thePlayer.posY + mc.thePlayer.lastTickPosY) / 2) - 0.0784000015258789,
469
                            (mc.thePlayer.posZ + mc.thePlayer.lastTickPosZ) / 2, false));
470
                    PacketUtil.sendPacket(new C03PacketPlayer.C06PacketPlayerPosLook(
471
                            (mc.thePlayer.posX + mc.thePlayer.lastTickPosX) / 2,
472
                            (mc.thePlayer.posY + mc.thePlayer.lastTickPosY) / 2,
473
                            (mc.thePlayer.posZ + mc.thePlayer.lastTickPosZ) /
474
                                    2, mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch, true));
475
476
                    PacketUtil.sendPacket(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX,
477
                            mc.thePlayer.posY, mc.thePlayer.posZ, false));
478
                    PacketUtil.sendPacket(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX,
479
                            mc.thePlayer.posY - 0.0784000015258789, mc.thePlayer.posZ, false));
480
                    PacketUtil.sendPacket(new C03PacketPlayer.C06PacketPlayerPosLook(mc.thePlayer.posX,
481
                            mc.thePlayer.posY, mc.thePlayer.posZ, mc.thePlayer.rotationYaw,
482
                            mc.thePlayer.rotationPitch, true));
483
484
                    MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 1.25 * 2);
485
486
                } else if (offGroundTicks == 1) {
487
                    MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 0.91f);
488
                }
489
                break;
490
491
            case "CraftPlay":
492
                if (mc.thePlayer.onGround && MoveUtil.isMoving()) {
493
                    mc.thePlayer.jump();
494
                    MoveUtil.strafe(MoveUtil.getSpeed() * 1.01);
495
                }
496
                if (offGroundTicks == 5) {
497
                    mc.thePlayer.motionY = -0.1964000015258789;
498
                    speed = mc.thePlayer.motionY;
499
                    mc.thePlayer.motionY = speed;
500
                }
501
                if(craftplayTimer.isEnabled()) {
502
                    if (offGroundTicks == 8) {
503
                        mc.timer.timerSpeed = 1.15f;
504
                    }
505
                    if (offGroundTicks == 1) {
506
                        mc.timer.timerSpeed = 1f;
507
                    }
508
                }
509
                break;
510
511
            case "Hypixel":
512
513
                final double xDist = mc.thePlayer.lastTickPosX - mc.thePlayer.posX;
514
                final double zDist = mc.thePlayer.lastTickPosZ - mc.thePlayer.posZ;
515
                final double lastDist = Math.sqrt(xDist * xDist + zDist * zDist);
516
517
                if (MoveUtil.isMoving()) {
518
519
                    // I cannot believe we have six full time developers and not a single one made this speed work in liquid
520
                    // maybe because any of those developers dont give a shit
521
                    if (mc.thePlayer.isInLiquid()) {
522
                        if (mc.thePlayer.isInWater()) {
523
                            mc.timer.timerSpeed = (float) (hypixelTimer.getValue() * 1.75);
524
                            MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 0.3);
525
                        } else if (mc.thePlayer.isInLava()) {
526
                            mc.timer.timerSpeed = (float) (hypixelTimer.getValue() * 2);
527
                            MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 0.25);
528
                        }
529
530
                        return;
531
                    }
532
533
                    mc.gameSettings.keyBindJump.setKeyPressed(false);
534
                    mc.gameSettings.keyBindSneak.setKeyPressed(false);
535
536
                    final double baseMoveSpeed = MoveUtil.getBaseMoveSpeed();
537
                    //strafe check dont remove
538
                    event.setYaw(getMovementDirection(mc.thePlayer.moveForward, mc.thePlayer.moveStrafing,
539
                            mc.thePlayer.rotationYaw));
540
541
                    if (!mc.thePlayer.onGround && mc.thePlayer.fallDistance < 0.24) {
542
                        mc.thePlayer.motionY = this.lowHopYModification(mc.thePlayer.motionY, round(
543
                                mc.thePlayer.posY - (int) mc.thePlayer.posY, 3, 0.001)) + Math.random() / 100000f;
544
                    }
545
546
                    if (mc.thePlayer.onGround) {
547
                        boolean doInitialLowHop =
548
                                !mc.thePlayer.isPotionActive(Potion.jump) && !mc.thePlayer.isCollidedHorizontally;
549
550
                        mc.thePlayer.motionY = doInitialLowHop ? 0.4f : 0.42f;
551
552
                        Block under = PlayerUtil.getBlockRelativeToPlayer(0, -1, 0);
553
                        MoveUtil.strafe(baseMoveSpeed * 1.6);
554
555
                        Block block = PlayerUtil.getBlockRelativeToPlayer(0, -1, 0);
556
                        if (block instanceof BlockIce || block instanceof BlockPackedIce) {
557
                            MoveUtil.strafe(baseMoveSpeed * 2);
558
                        }
559
                        bool = true;
560
                    } else if (bool) {
561
                        bool = false;
562
563
                        final double bunny = (0.84 + Math.random() / 50f) * (lastDist - baseMoveSpeed);
564
565
                        MoveUtil.strafe(lastDist - bunny);
566
567
                        event.setY(event.getY() + Math.random() / 1000000);
568
                    }
569
                } else {
570
                    if (mc.thePlayer.onGround) MoveUtil.stop();
571
572
                    mc.gameSettings.keyBindJump.setKeyPressed(Keyboard.isKeyDown(mc.gameSettings.keyBindJump.getKeyCode()));
573
                    mc.gameSettings.keyBindSneak.setKeyPressed(Keyboard.isKeyDown(mc.gameSettings.keyBindSneak.getKeyCode()));
574
                }
575
576
                mc.timer.timerSpeed = (float) (hypixelTimer.getValue() - Math.random() / 50);
577
578
                if (mc.thePlayer.isCollidedHorizontally || mc.thePlayer.fallDistance > 0.8)
579
                    MoveUtil.strafe(MoveUtil.getSpeed() * 0.9);
580
581
                if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
582
                    if (mc.thePlayer.onGround) {
583
                        mc.thePlayer.motionX *= 1.04 - Math.random() / 100;
584
                        mc.thePlayer.motionZ *= 1.04 - Math.random() / 100;
585
                    } else {
586
                        mc.thePlayer.motionX *= 1.005 - Math.random() / 100;
587
                        mc.thePlayer.motionZ *= 1.005 - Math.random() / 100;
588
                    }
589
                }
590
591
                if (PlayerUtil.getBlockRelativeToPlayer(0,-1,0) instanceof BlockAir) {
592
                    MoveUtil.strafe(MoveUtil.getSpeed() * 0.92);
593
                }
594
595
                break;
596
597
            case "KoksCraft": {
598
                if (mc.thePlayer.onGround && MoveUtil.isMoving()) {
599
                    mc.thePlayer.jump();
600
                    MoveUtil.strafe(MoveUtil.getSpeed() * (1.01));
601
                    mc.timer.timerSpeed = 1f;
602
                }
603
                if (offGroundTicks == 6) {
604
                    mc.thePlayer.motionY = -0.199999999999999;
605
606
                    speed = mc.thePlayer.motionY;
607
                    mc.thePlayer.motionY = speed;
608
                }
609
                //liquid check
610
                if (mc.thePlayer.isInLiquid()) {
611
                    if (mc.thePlayer.isInWater()) {
612
                        MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 0.35);
613
                    } else if (mc.thePlayer.isInLava()) {
614
                        MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 0.3);
615
                    }
616
                }
617
            }
618
            //strafe
619
            if(koksStrafe.isEnabled()) {
620
                if (offGroundTicks == 3) {
621
                    MoveUtil.strafe();
622
                }
623
            }
624
            break;
625
626
            case "Predictive":
627
                if (mc.thePlayer.onGround) {
628
                    mc.thePlayer.jump();
629
                }
630
631
                if (offGroundTicks == 2) {
632
                    event.setGround(true);
633
                    mc.thePlayer.motionY = -0.0784000015258789;
634
                    mc.thePlayer.onGround = true;
635
636
                    speed = mc.thePlayer.motionY;
637
                    mc.thePlayer.jump();
638
                    mc.thePlayer.motionY = speed;
639
                }
640
                break;
641
642
            case "Strafe Hop":
643
                if (mc.thePlayer.onGround && MoveUtil.isMoving()) {
644
                    mc.thePlayer.jump();
645
                }
646
647
                if (strafe.isEnabled())
648
                    MoveUtil.strafe();
649
                break;
650
651
            case "Vulcan":
652
                if (MoveUtil.isMoving()) {
653
                    if (mc.thePlayer.onGround) {
654
655
                        double speed = MoveUtil.getBaseMoveSpeed() - 0.01;
656
                        MoveUtil.strafe(speed - (Math.random() / 2000));
657
658
                        mc.thePlayer.jump();
659
660
                        bool = true;
661
                    } else {
662
                        if (bool) {
663
                            if (offGroundTicks > 3)
664
                                mc.thePlayer.motionY = MoveUtil.getPredictedMotionY(mc.thePlayer.motionY);
665
666
                            if (!(PlayerUtil.getBlockRelativeToPlayer(0, 2, 0) instanceof BlockAir))
667
                                MoveUtil.strafe(MoveUtil.getSpeed() * (1.1 - (Math.random() / 500)));
668
                        }
669
670
                        if (mc.thePlayer.isInLiquid() || mc.thePlayer.hurtTime == 9)
671
                            MoveUtil.strafe();
672
                    }
673
                } else
674
                    MoveUtil.stop();
675
                break;
676
677
            case "Mineplex Low":
678
                ticks--;
679
680
                if (mc.gameSettings.keyBindJump.isKeyDown()) {
681
                    ticks = 0;
682
                    return;
683
                }
684
685
                if (!jumped && mc.thePlayer.onGround) {
686
                    mc.thePlayer.jump();
687
                    mc.thePlayer.motionY = 0.21546;
688
                    MoveUtil.strafe(0.1);
689
                    jumped = true;
690
                    ticks++;
691
                }
692
693
                if (!mc.thePlayer.onGround) {
694
                    speed = (float) MoveUtil.getSpeed();
695
                }
696
697
                if (offGroundTicks == 1 && jumped) {
698
                    MoveUtil.strafe(0.6);
699
                }
700
701
                if (jumped && mc.thePlayer.onGround) {
702
                    MoveUtil.strafe(speed);
703
                }
704
705
                if (jumped)
706
                    speed -= 0.009;
707
708
                if (onGroundTicks > 2) {
709
                    offGroundTicks = 0;
710
                    jumped = false;
711
                    speed = 0;
712
                    onGroundTicks = 0;
713
                    startY = mc.thePlayer.posY;
714
                    packets.clear();
715
                }
716
717
                if (!MoveUtil.isMoving())
718
                    ticks = 0;
719
720
                MoveUtil.strafe();
721
722
                break;
723
724
            /**
725
             * IMPORTANT TO ANYONE WHO SEES THIS:
726
             *
727
             * All raw, decompiled and unrefined sources from Vape V4.07
728
             * This code is awful because it's been deobfuscated and decompiled.
729
             * Please do not try to "clean up" or "fix these" sources. I don't care if warnings bother you
730
             * This perfectly matches the original source.
731
             *
732
             * These only exist for testing, and my own curiosity/interest
733
             *
734
             * Private. These modes are only usable by developers.
735
             * Do. Not. Share. This. Code.
736
             * !!! Do not share that we have this source !!!
737
             * Thank you.
738
             *
739
             * - Hazsi
740
             */
741
            case "Vape": {
742
                switch (vapeMode.getMode()) {
743
                    case "AntiCheat A": {
744
                        double var1 = 0.2873F;
745
                        if (mc.thePlayer.isPotionActive(1) && mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getDuration() > 10) {
746
                            int var4 = mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier();
747
                            var1 *= 1.0D + 0.15D * (double) (var4 + 1);
748
                        }
749
750
                        if ((mc.thePlayer.movementInput.moveForward != 0 || mc.thePlayer.movementInput.moveStrafe != 0) && this.z > 0.0D && this.parentX > 0 && event.isGround()) {
751
                            if (this.x > 0) {
752
                                mc.thePlayer.motionY += 0.004999999888241291D + 9.999999747378752E-5D * Math.random();
753
                            }
754
755
                            ++this.x;
756
                        }
757
758
                        double var3 = mc.thePlayer.posX - mc.thePlayer.lastTickPosX;
759
                        double var5 = mc.thePlayer.posZ - mc.thePlayer.lastTickPosZ;
760
                        this.z = 0.1;
761
762
                        if (this.parentX < 0) {
763
                            ++this.parentX;
764
                            this.z = 0.0D;
765
                        } else {
766
                            if ((mc.thePlayer.movementInput.moveForward == 0.0F && mc.thePlayer.movementInput.moveStrafe == 0.0F)) {
767
                                this.vapeSpeedVar = var1;
768
                            }
769
770
                            boolean isMoving = mc.thePlayer.movementInput.moveForward != 0 || mc.thePlayer.movementInput.moveStrafe != 0;
771
                            double var4 = vapeSpeedVar = var1;
772
                            double var6;
773
                            double var8;
774
                            float var12;
775
776
                            if (this.parentX == 1 && isMoving && mc.thePlayer.isCollidedVertically) {
777
                                vapeSpeedVar = var1;
778
                                this.x = 0;
779
                            } else if (this.parentX == 2 && isMoving && mc.thePlayer.isCollidedVertically/* && mc.thePlayer.q()*/) {
780
                                var6 = this.x > 0 ? 0.424F + 0.0001F * Math.random() : 0.42F;
781
                                if (mc.thePlayer.isPotionActive(8)) {
782
                                    var6 += (double) ((mc.thePlayer.getActivePotionEffect(Potion.jump).getAmplifier() + 1) * 0.1F);
783
                                }
784
785
//                                event.setY(event.getY() + var6);
786
                                mc.thePlayer.motionY = var6;
787
788
//                                vapeSpeedVar = var4 * 2.1475D;
789
                                var8 = (double) mc.thePlayer.movementInput.moveForward;
790
                                double var10 = (double) mc.thePlayer.movementInput.moveStrafe;
791
                                var12 = mc.thePlayer.rotationYaw;
792
793
                                if (var8 == 0.0D && var10 == 0.0D) {
794
//                                    thePlayer.d(thePlayer.ae() + 1.0D, thePlayer.g(), thePlayer.Y() + 1.0D);
795
//                                    thePlayer.d(thePlayer.x(), thePlayer.F(), thePlayer.aq());
796
797
                                    mc.thePlayer.motionX = 0.0D;
798
                                    mc.thePlayer.motionZ = 0.0D;
799
800
//                                    if (thePlayer.q()) {
801
//                                        this.v = var12;
802
//                                    }
803
                                } else if (var8 != 0.0D) {
804
                                    if (var8 < 0.0D) {
805
                                        var12 -= 180.0F;
806
                                    }
807
808
                                    if (var10 > 0.0D) {
809
                                        var12 += var8 > 0.0D ? -43.51F : 43.51F;
810
                                    } else if (var10 < 0.0D) {
811
                                        var12 += var8 > 0.0D ? 43.51F : -43.51F;
812
                                    }
813
                                } else if (var10 > 0.0D) {
814
                                    var12 += -88.58F;
815
                                } else if (var10 < 0.0D) {
816
                                    var12 += 88.58F;
817
                                }
818
819
                                float var13 = MathHelper.wrapAngleTo180_float(-(this.v - var12));
820
                                float var14 = 180.0F;
821
                                if (Math.abs(var13) >= var14) {
822
                                    var13 = MathHelper.clamp_float(var13, -var14, var14);
823
                                }
824
825
                                this.v += var13;
826
                            } else if (this.parentX == 3) {
827
                                var6 = 0.825D;
828
//                                if (thePlayer.b(fD.r())) {
829
//                                    if (thePlayer.a(fD.r()).g() == 0) {
830
//                                        var6 = 0.8D;
831
//                                    } else {
832
//                                        var6 = 0.75D;
833
//                                    }
834
//                                }
835
836
                                var8 = var6 * (this.z - var4);
837
                                this.vapeSpeedVar = this.z - var8;
838
                            } else {
839
//                                f1 var17;
840
//                                if (FV.c() == 13) {
841
//                                    var17 = thePlayer.ad().h().d(0.0D, thePlayer.aj(), 0.0D);
842
//                                } else {
843
//                                    var17 = thePlayer.ad().d(0.0D, thePlayer.aj(), 0.0D);
844
//                                }
845
//
846
//                                List var7 = dE.P().a(thePlayer, var17);
847
                                if (/*(var7.size() > 0 || */mc.thePlayer.isCollidedVertically && this.x > 0) {
848
                                    this.parentX = mc.thePlayer.movementInput.moveForward == 0.0F && mc.thePlayer.movementInput.moveStrafe == 0.0F ? 0 : 1;
849
                                }
850
851
                                this.vapeSpeedVar = this.z - this.z / 159.0D;
852
                            }
853
854
                            this.vapeSpeedVar = Math.max(this.vapeSpeedVar, var4);
855
                            if (this.parentX > 0) {
856
                                var6 = (double) mc.thePlayer.movementInput.moveForward;
857
                                var8 = (double) mc.thePlayer.movementInput.moveStrafe;
858
                                float var18 = mc.thePlayer.rotationYaw;
859
                                if (var6 == 0.0D && var8 == 0.0D) {
860
                                    mc.thePlayer.motionX = 0.0D;
861
                                    mc.thePlayer.motionZ = 0.0D;
862
                                } else if (var6 != 0.0D) {
863
                                    if (var8 > 0.0D) {
864
                                        var18 += (float) (var6 > 0.0D ? -45 : 45);
865
                                    } else if (var8 < 0.0D) {
866
                                        var18 += (float) (var6 > 0.0D ? 45 : -45);
867
                                    }
868
869
                                    if (var6 > 0.0D) {
870
                                        var6 = 1.0D;
871
                                    } else if (var6 < 0.0D) {
872
                                        var6 = 1.0D;
873
                                        var18 -= 180.0F;
874
                                    }
875
                                } else {
876
                                    if (var8 > 0.0D) {
877
                                        var18 += -90.0F;
878
                                    } else if (var8 < 0.0D) {
879
                                        var18 += 90.0F;
880
                                    }
881
882
                                    var6 = 1.0D;
883
                                }
884
885
                                float var11 = MathHelper.wrapAngleTo180_float(-(this.v - var18));
886
                                var12 = (float) this.vapeSteps.getValue();
887
                                if (Math.abs(var11) >= var12) {
888
                                    var11 = MathHelper.clamp_float(var11, -var12, var12);
889
                                }
890
891
                                this.v += var11;
892
                                double var19 = Math.cos(Math.toRadians((double) (this.v + 90.0F)));
893
                                double var15 = Math.sin(Math.toRadians((double) (this.v + 90.0F)));
894
                                mc.thePlayer.motionX = var6 * vapeSpeedVar * var19;
895
                                mc.thePlayer.motionZ = var6 * vapeSpeedVar * var15;
896
897
                                if (mc.thePlayer.movementInput.moveForward != 0.0F || mc.thePlayer.movementInput.moveStrafe != 0.0F) {
898
                                    ++this.parentX;
899
                                }
900
                            }
901
                        }
902
903
                        break;
904
                    }
905
                    case "AntiCheat B": {
906
                        double var2 = 0.4199999868869781494140625;
907
908
                        if ((mc.thePlayer.movementInput.moveForward != 0 || mc.thePlayer.movementInput.moveStrafe != 0) && mc.thePlayer.isCollidedVertically) {
909
                            mc.thePlayer.motionY = var2;
910
                        }
911
912
                        double var5 = (double) mc.thePlayer.movementInput.moveForward;
913
                        double var7 = (double) mc.thePlayer.movementInput.moveStrafe;
914
                        float var9 = mc.thePlayer.rotationYaw;
915
916
                        if (var5 == 0.0D && var7 == 0.0D) {
917
                            mc.thePlayer.motionX = 0.0D;
918
                            mc.thePlayer.motionZ = 0.0D;
919
                        } else if (var5 != 0.0D) {
920
                            if (var7 != 0.0D) {
921
                                if (var7 > 0.0D) {
922
                                    var9 += var5 > 0.0D ? -45.0F : 45.0F;
923
                                    var7 = 0.0D;
924
                                } else {
925
                                    var9 += var5 > 0.0D ? 45.0F : -45.0F;
926
                                    var7 = 0.0D;
927
                                }
928
                            }
929
930
                            if (var5 > 0.0D) {
931
                                var5 = 1.0D;
932
                            } else {
933
                                var5 = -1.0D;
934
                            }
935
                        }
936
937
                        double var10 = Math.cos(Math.toRadians(var9 + 90.0F));
938
                        double var12 = Math.sin(Math.toRadians(var9 + 90.0F));
939
                        mc.thePlayer.motionX = var5 * var2 * var10 + var7 * var2 * var12;
940
                        mc.thePlayer.motionZ = var5 * var2 * var12 - var7 * var2 * var10;
941
942
943
                        break;
944
                    }
945
                    case "Y-Port": {
946
947
                        break;
948
                    }
949
                }
950
951
                break;
952
            }
953
            /**
954
             * PLEASE READ THE ABOVE COMMENT BEFORE THIS MODE!
955
             */
956
957
            case "Teleport": {
958
                if (!MoveUtil.isMoving()) return;
959
960
                speed = teleportDistance.getValue();
961
                final float yaw = (float) MoveUtil.getDirection();
962
                final double posX = -MathHelper.sin(yaw) * speed + mc.thePlayer.posX;
963
                final double posZ = MathHelper.cos(yaw) * speed + mc.thePlayer.posZ;
964
965
                if (offGroundTicks > 1 && offGroundTicks < 11) mc.thePlayer.setPosition(posX, mc.thePlayer.posY, posZ);
966
967
                if (mc.thePlayer.onGround) {
968
                    mc.thePlayer.jump();
969
                }
970
                break;
971
            }
972
973
            case "NCP": {
974
                if (MoveUtil.isMoving()) {
975
                    if (mc.thePlayer.onGround) {
976
                        mc.thePlayer.jump();
977
                        MoveUtil.strafe(MoveUtil.getSpeed() * speedMulti.getValue() + Math.random() / 100);
978
                    } else {
979
                        MoveUtil.strafe(MoveUtil.getSpeed() * 1.0035);
980
                    }
981
982
                    mc.thePlayer.jumpMovementFactor = 0.02725F;
983
                }
984
985
                if (ticks < 20) {
986
                    mc.timer.timerSpeed = 0.98f;
987
                }
988
989
                if (ticks == 20)
990
                    ticks = 0;
991
992
                if (ticks < 9) {
993
                    mc.timer.timerSpeed = (float) (timerBoost.getValue() + Math.random() / 100);
994
                }
995
                break;
996
            }
997
998
            case "Taka": {
999
                if (MoveUtil.isMoving()) {
1000
                    if (mc.thePlayer.onGround) {
1001
                        mc.thePlayer.jump();
1002
                    } else {
1003
1004
                        mc.thePlayer.speedInAir = (float) (0.02f + Math.random() / 300);
1005
                        if (mc.thePlayer.fallDistance > 0) {
1006
                            mc.thePlayer.motionY += 0.04;
1007
                        }
1008
1009
                    }
1010
1011
                    mc.timer.timerSpeed = (float) (1 + Math.random() / 3);
1012
                } else {
1013
                    mc.timer.timerSpeed = 1;
1014
                }
1015
                break;
1016
            }
1017
1018
            case "Spartan": {
1019
                if (MoveUtil.isMoving()) {
1020
                    MoveUtil.strafe();
1021
1022
                    mc.thePlayer.speedInAir = (float) (0.04 + Math.random() / 5000);
1023
1024
                    if (mc.thePlayer.onGround) {
1025
                        mc.thePlayer.jump();
1026
                        ticks++;
1027
1028
                        speed = 0.5 + Math.random() / 500;
1029
1030
                        if (MoveUtil.getSpeed() < speed)
1031
                            MoveUtil.strafe(speed);
1032
                    }
1033
1034
                    mc.thePlayer.setSprinting(false);
1035
                    mc.gameSettings.keyBindSprint.setKeyPressed(false);
1036
                }
1037
                break;
1038
            }
1039
1040
            case "Redesky": {
1041
1042
                if (mc.thePlayer.onGround) {
1043
                    MoveUtil.strafe(0.5);
1044
                }
1045
1046
                if (mc.thePlayer.ticksExisted % 40 == 0) {
1047
                    event.setY(event.getY() - 0.5);
1048
                    event.setGround(false);
1049
                    MoveUtil.strafe(0);
1050
                }
1051
1052
                break;
1053
            }
1054
1055
            case "Mineplex Smooth": {
1056
1057
                if (MoveUtil.isMoving()) {
1058
                    if (mc.thePlayer.onGround) {
1059
                        mc.thePlayer.jump();
1060
1061
                        if (speed < 0.5)
1062
                            speed = 0.1f;
1063
                    } else {
1064
                        if (offGroundTicks == 1 && speed < 0.3) {
1065
                            speed = 0.55f;
1066
                        }
1067
                    }
1068
                }
1069
1070
                if (mc.thePlayer.hurtTime == 9) {
1071
                    speed = 0.7f;
1072
                }
1073
1074
                speed -= speed / 70;
1075
1076
1077
                MoveUtil.strafe(speed);
1078
1079
1080
                break;
1081
            }
1082
            case "Zonecraft": {
1083
1084
                if (mc.thePlayer.onGround) {
1085
                    mc.thePlayer.jump();
1086
                    MoveUtil.strafe(1);
1087
                }
1088
                mc.timer.timerSpeed = 0.9f;
1089
1090
                if (offGroundTicks == 1) {
1091
                    mc.thePlayer.motionY = -0.0784000015258789;
1092
                }
1093
1094
                MoveUtil.strafe();
1095
1096
                /*
1097
                if (mc.thePlayer.onGround) {
1098
                    speed = (float) MoveUtil.getBaseMoveSpeed() + 0.1f;
1099
                    mc.thePlayer.jump();
1100
                }
1101
1102
                speed -= speed / 79;
1103
                MoveUtil.strafe(speed);*/
1104
1105
                break;
1106
            }
1107
            case "Exempted Value": {
1108
1109
                if (mc.thePlayer.onGround) {
1110
                    mc.thePlayer.jump();
1111
                } else {
1112
                    if (offGroundTicks == (int) tick.getValue()) {
1113
                        double v = 0;
1114
                        switch (exemptedValueType.getMode()) {
1115
                            case "1":
1116
                                v = -0.0784000015258789;
1117
                                break;
1118
                            case "2":
1119
                                v = -0.09800000190734864;
1120
                                break;
1121
                            case "3":
1122
                                v = -0.09800000190735147;
1123
                                break;
1124
                        }
1125
1126
                        mc.thePlayer.motionY = v;
1127
                        if (groundSpoof.isEnabled()) {
1128
                            event.setGround(true);
1129
                        }
1130
                    }
1131
                }
1132
1133
                if (strafe.isEnabled()) {
1134
                    MoveUtil.strafe();
1135
                }
1136
1137
                break;
1138
            }
1139
1140
            case "Convert Ground": {
1141
1142
                if (mc.thePlayer.ticksExisted % (int) howOften.getValue() == 0) {
1143
                    speed = (float) MoveUtil.getSpeed();
1144
1145
                    final double direction2 = MoveUtil.getDirection();
1146
                    double posX2 = -Math.sin(direction2) * speed;
1147
                    double posZ2 = Math.cos(direction2) * speed;
1148
1149
                    if (!MoveUtil.isMoving())
1150
                        posX2 = posZ2 = 0;
1151
1152
                    if (MoveUtil.isMoving())
1153
                        for (int i = 0; i <= (int) distance.getValue(); ++i) {
1154
1155
                            MoveUtil.strafe(speed * (i + 1));
1156
                            PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C06PacketPlayerPosLook(
1157
                                    mc.thePlayer.posX + posX2 * i, mc.thePlayer.posY,
1158
                                    mc.thePlayer.posZ + posZ2 * i, (float) (mc.thePlayer.rotationYaw + Math.random()
1159
                            ), (float) (mc.thePlayer.rotationPitch + Math.random()), mc.thePlayer.onGround));
1160
1161
                        }
1162
1163
1164
                } else {
1165
                    MoveUtil.stop();
1166
                    MoveUtil.strafe(0.14);
1167
                    mc.timer.timerSpeed = 0.6f;
1168
                }
1169
1170
                break;
1171
            }
1172
1173
//            case "Hypixel": {
1174
//                event.setYaw(yaw);
1175
//                mc.thePlayer.renderYawOffset = yaw;
1176
//                mc.thePlayer.rotationYawHead = yaw;
1177
//
1178
//                EntityPlayer.movementYaw = yaw;
1179
//
1180
//                lastYaw = yaw;
1181
//                break;
1182
//            }
1183
1184
            case "Hypixel Smooth": {
1185
                double deltaYaw = MathHelper.wrapAngleTo180_double(Math.toDegrees(MoveUtil.getDirection()) - lastYaw);
1186
//                double angle = lastYaw + deltaYaw / (4 - Math.abs(deltaYaw / 90));
1187
                double maxAngle = 20;
1188
                double angle = lastYaw + (deltaYaw > 0 ? maxAngle : -maxAngle);
1189
1190
                if (Math.abs(deltaYaw) < maxAngle) angle = Math.toDegrees(MoveUtil.getDirection());
1191
1192
//                Rise.addChatMessage(angle + "    " + Math.abs(deltaYaw));
1193
//                Rise.addChatMessage("ANGLE: " + angle + "   DELTA: " + deltaYaw + "   LAST: " + lastYaw);
1194
1195
                boolean hasSpeed = mc.thePlayer.isPotionActive(Potion.moveSpeed);
1196
                int speedLevel =
1197
                        hasSpeed ? (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier() + 1) : 0;
1198
                mc.thePlayer.setSprinting(true);
1199
                mc.timer.timerSpeed =
1200
                        (mc.thePlayer.motionX == 0 && mc.thePlayer.motionZ == 0) ? 1 : (float) hypixelTimer.getValue();
1201
1202
                if (mc.thePlayer.onGround && MoveUtil.isMoving()) {
1203
                    stage = (int) Math.round(mc.thePlayer.posY);
1204
                    mc.thePlayer.jump();
1205
                    mc.thePlayer.motionY -= 0.02;
1206
1207
                    double groundSpeed = 0.47;
1208
                    groundSpeed += speedLevel * 0.15;
1209
1210
                    angle = lastYaw = (float) Math.toDegrees(MoveUtil.getDirection());
1211
1212
                    MoveUtil.strafe(groundSpeed, Math.toRadians(angle));
1213
                }
1214
                if (MoveUtil.isMoving()) {
1215
                    KeyBinding.setKeyBindState(mc.gameSettings.keyBindJump.getKeyCode(), false);
1216
                    MoveUtil.strafe(MoveUtil.getSpeed(), Math.toRadians(angle));
1217
1218
                    if (MoveUtil.getSpeed() < 0.2) {
1219
                        MoveUtil.strafe(Math.max(0.05, MoveUtil.getSpeed() * 1.1));
1220
                    }
1221
                    if (MoveUtil.getSpeed() < 0.05) {
1222
                        //angle = strafeAngle = MoveUtil.getDirection();
1223
                    }
1224
                } else {
1225
                    KeyBinding.setKeyBindState(mc.gameSettings.keyBindJump.getKeyCode(), (
1226
                            Keyboard.isKeyDown(mc.gameSettings.keyBindJump.getKeyCode()) && mc.currentScreen == null
1227
                    ));
1228
                }
1229
1230
                mc.thePlayer.jumpMovementFactor = 0.028f;
1231
                lastYaw = MathHelper.wrapAngleTo180_float((float) angle);
1232
                event.setYaw((float) angle);
1233
//                mc.thePlayer.renderYawOffset = mc.thePlayer.rotationYawHead = event.getYaw();
1234
1235
                break;
1236
            }
1237
1238
            case "AAC 4 Simple": {
1239
1240
                mc.timer.timerSpeed = 1.02f;
1241
                if (mc.thePlayer.onGround && MoveUtil.isMoving()) {
1242
                    mc.thePlayer.jump();
1243
                    mc.thePlayer.motionZ *= 1.05;
1244
                    mc.thePlayer.motionX *= 1.05;
1245
                    mc.thePlayer.motionY = MoveUtil.getJumpMotion(0.4F);
1246
                }
1247
1248
1249
                break;
1250
            }
1251
            case "Invadedlands": {
1252
1253
                if (mc.thePlayer.onGround) {
1254
                    mc.thePlayer.jump();
1255
                    mc.thePlayer.motionY = 0.1;
1256
                    MoveUtil.strafe(5);
1257
                } else {
1258
                    MoveUtil.stop();
1259
                    MoveUtil.strafe(MoveUtil.getBaseMoveSpeedOther() * 0.4);
1260
                }
1261
1262
                break;
1263
            }
1264
1265
            case "Intave":
1266
                if (mc.thePlayer.onGround) {
1267
                    MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 1.2);
1268
                    mc.thePlayer.jump();
1269
                } else if (offGroundTicks == 4) {
1270
                    mc.thePlayer.motionY = -0.0784000015258789;
1271
                }
1272
1273
                MoveUtil.strafe();
1274
                break;
1275
            case "Mineplex":
1276
                if (mc.thePlayer.onGround) {
1277
                    MoveUtil.strafe(0);
1278
                }
1279
                if (ticks < 0) {
1280
                    Rise.addChatMessage("gliding");
1281
//                    mc.thePlayer.motionY += 0.0355f;
1282
                }
1283
                break;
1284
            case "Minemenclub Hop":
1285
1286
                if (mc.thePlayer.onGround) {
1287
                    mc.thePlayer.jump();
1288
                }
1289
1290
                MoveUtil.strafe();
1291
                break;
1292
        }
1293
1294
        if (mode.is("Verus"))
1295
            switch (verusMode.getMode()) {
1296
                case "Hop":
1297
                    if (mc.thePlayer.onGround) {
1298
                        mc.thePlayer.jump();
1299
                        MoveUtil.strafe(0.55);
1300
                    } else {
1301
                        MoveUtil.strafe(0.349);
1302
                    }
1303
1304
                    if (stopwatch.hasReached(200)) {
1305
                        PacketUtil.sendPacketWithoutEvent(new C0BPacketEntityAction(mc.thePlayer, C0BPacketEntityAction.Action.START_SNEAKING));
1306
                        PacketUtil.sendPacketWithoutEvent(new C0BPacketEntityAction(mc.thePlayer, C0BPacketEntityAction.Action.STOP_SPRINTING));
1307
                        stopwatch.reset();
1308
                    }
1309
                    break;
1310
1311
                case "Float": {
1312
                    if (!mc.gameSettings.keyBindJump.isKeyDown()) {
1313
                        if (mc.thePlayer.onGround) {
1314
                            event.setGround(true);
1315
                            ticks = 0;
1316
                            MoveUtil.strafe(0.44f);
1317
                            mc.thePlayer.motionY = 0.42F;
1318
                            mc.timer.timerSpeed = 2.1f;
1319
1320
                        } else {
1321
1322
                            if (ticks >= 10) {
1323
                                verusEpicBypassBooleanTM = true;
1324
                                MoveUtil.strafe(0.2865f);
1325
                                return;
1326
                            }
1327
1328
                            if (verusEpicBypassBooleanTM) {
1329
                                if (ticks <= 1) {
1330
                                    MoveUtil.strafe(0.45f);
1331
                                }
1332
1333
                                if (ticks >= 2) {
1334
                                    MoveUtil.strafe(0.69f - (ticks - 2) * 0.019f);
1335
                                }
1336
                            }
1337
1338
                            mc.thePlayer.motionY = 0;
1339
                            mc.timer.timerSpeed = 0.9f;
1340
1341
                            event.setGround(true);
1342
                            mc.thePlayer.onGround = true;
1343
                        }
1344
                    }
1345
1346
                    break;
1347
                }
1348
            }
1349
1350
        if (!hypixelCombatTimer.hidden && Aura.target != null) {
1351
            mc.timer.timerSpeed = (float) hypixelCombatTimer.getValue();
1352
        }
1353
    }
1354
1355
//    @Override
1356
//    public void onRender3DEvent(final Render3DEvent event) {
1357
//        if (mode.is("Hypixel")) {
1358
//            targetYaw = (float) (MoveUtil.getDirection() * (180 / Math.PI));
1359
//            this.calculateHypixelYaw();
1360
//        }
1361
//    }
1362
//
1363
//    private void calculateHypixelYaw() {
1364
//        final int fps = (int) (Minecraft.getDebugFPS() / 20.0F);
1365
//
1366
//        final float rotationSpeed = 15 * 6F / fps;
1367
//
1368
//        final float deltaYaw = (((targetYaw - lastYaw) + 540) % 360) - 180;
1369
//
1370
//        final float distanceYaw = MathHelper.clamp_float(deltaYaw, -rotationSpeed, rotationSpeed);
1371
//
1372
//        yaw = lastYaw + distanceYaw;
1373
//
1374
//        final float[] currentRotations = new float[]{yaw, mc.thePlayer.rotationPitch};
1375
//        final float[] lastRotations = new float[]{lastYaw, mc.thePlayer.rotationPitch};
1376
//
1377
//        final float[] fixedRotations = RotationUtil.getFixedRotation(currentRotations, lastRotations);
1378
//
1379
//        yaw = fixedRotations[0];
1380
//    }
1381
1382
    @Override
1383
    public void onBlockCollide(final BlockCollideEvent event) {
1384
//        switch (mode.getMode()) {
1385
//            case "Verus": {
1386
//                if (event.getBlock() instanceof BlockAir && !mc.thePlayer.isSneaking() && verusMode.getMode().equals("Hop")) {
1387
//                    final double x = event.getX(), y = event.getY(), z = event.getZ();
1388
//
1389
//                    if (y < mc.thePlayer.posY) {
1390
//                        event.setCollisionBoundingBox(AxisAlignedBB.fromBounds(-15, -1, -15, 15, 1, 15).offset(x, y, z));
1391
//                    }
1392
//                }
1393
//            }
1394
//            break;
1395
//        }
1396
    }
1397
1398
    public static double round(final double value, final int scale, final double inc) {
1399
        final double halfOfInc = inc / 2.0;
1400
        final double floored = Math.floor(value / inc) * inc;
1401
1402
        if (value >= floored + halfOfInc)
1403
            return new BigDecimal(Math.ceil(value / inc) * inc)
1404
                    .setScale(scale, RoundingMode.HALF_UP)
1405
                    .doubleValue();
1406
        else return new BigDecimal(floored)
1407
                .setScale(scale, RoundingMode.HALF_UP)
1408
                .doubleValue();
1409
    }
1410
1411
    public void onMove(final MoveEvent event) {
1412
1413
        if (ticksDisable <= 20) {
1414
            return;
1415
        }
1416
1417
        if (mode.is("Verus"))
1418
            switch (verusMode.getMode()) {
1419
                case "YPort":
1420
                    if (MoveUtil.isMoving()) {
1421
                        if (mc.thePlayer.onGround) {
1422
                            MoveUtil.strafe(0.69);
1423
                            event.setY(0.42F);
1424
                            mc.thePlayer.motionY = 0;
1425
                        }
1426
                        MoveUtil.strafe(0.41);
1427
                    }
1428
                    break;
1429
1430
                case "Low": {
1431
//                    Rise.addChatMessage(stage);
1432
1433
//                    if (ticks % 10 == 0 && stage == 0) {
1434
//                        stage = 1;
1435
//                    } else {
1436
//                        switch (stage) {
1437
//                            case 0: {
1438
//                                MoveUtil.strafe(1);
1439
//                                break;
1440
//                            }
1441
//                            case 1: {
1442
//                                MoveUtil.strafe(0.0675);
1443
//                                break;
1444
//                            }
1445
//                            case 2: {
1446
//                                MoveUtil.strafe(0.0675);
1447
//                                break;
1448
//                            }
1449
//                            case 3: {
1450
//                                MoveUtil.strafe(0.066);
1451
//                                break;
1452
//                            }
1453
//                        }
1454
//
1455
//                        if (stage < 3 && stage != 0) {
1456
//                            stage++;
1457
//                        } else {
1458
//                            stage = 0;
1459
//                        }
1460
//                    }
1461
1462
                    if (!MoveUtil.isMoving()) {
1463
                        return;
1464
                    }
1465
1466
                    if (ticks % 12 == 0 && mc.thePlayer.onGround) {
1467
                        MoveUtil.strafe(0.69);
1468
                        event.setY(0.42F);
1469
//                        PacketUtil.sendPacketWithoutEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY + 0.42F, mc.thePlayer.posZ, false));
1470
                        mc.thePlayer.motionY = -(mc.thePlayer.posY - roundToOnGround(mc.thePlayer.posY));
1471
                    } else {
1472
                        if (mc.thePlayer.onGround) {
1473
                            MoveUtil.strafe(1.01);
1474
                        } else {
1475
                            MoveUtil.strafe(0.41);
1476
                        }
1477
                    }
1478
1479
                    break;
1480
                }
1481
            }
1482
1483
        switch (mode.getMode()) {
1484
            case "Mineplex":
1485
1486
                if (!MoveUtil.isMoving()) {
1487
                    if (mc.thePlayer.onGround) stage = 0;
1488
                    return;
1489
                }
1490
1491
                if (mc.thePlayer.isCollidedHorizontally) {
1492
                    stage = 0;
1493
                }
1494
1495
                if (mc.thePlayer.onGround) {
1496
                    event.setY(mc.thePlayer.motionY = 0.42f);
1497
                    stage++;
1498
                }
1499
1500
                if (offGroundTicks == 1) {
1501
                    final float nextSpeed = 0.2f;
1502
                    speed += MoveUtil.getBaseMoveSpeed() / 2;
1503
                    if (speed > 1) speed = 1;
1504
                }
1505
1506
                speed *= 0.985;
1507
1508
//                if (offGroundTicks > 1 && offGroundTicks <= 15) mc.thePlayer.motionY += 0.02999;
1509
//
1510
//                if (offGroundTicks == 1) mc.thePlayer.motionY += 0.04f;
1511
//
1512
//                if (offGroundTicks == 17) mc.thePlayer.motionY -= 0.04f;
1513
1514
                if (stage >= 1 && !mc.thePlayer.onGround) {
1515
                    final double baseSpeed = Math.max(MoveUtil.getBaseMoveSpeedOther(), speed);
1516
                    MoveUtil.setMoveEventSpeed(event, (Math.max(speed, baseSpeed)));
1517
                }
1518
1519
                break;
1520
1521
        }
1522
    }
1523
1524
    @Override
1525
    public void onPacketSend(final PacketSendEvent event) {
1526
        if (ticksDisable <= 20) {
1527
            return;
1528
        }
1529
1530
        final Packet<?> p = event.getPacket();
1531
1532
        switch (mode.getMode()) {
1533
            case "Verus": {
1534
                if (verusMode.is("Hop") && p instanceof C0FPacketConfirmTransaction) {
1535
                    event.setCancelled(true);
1536
                }
1537
                break;
1538
            }
1539
            case "Custom":
1540
                if (cancelC0F.isEnabled()) {
1541
                    if (p instanceof C0FPacketConfirmTransaction) {
1542
                        event.setCancelled(true);
1543
                    }
1544
                }
1545
1546
                if (cancelC00.isEnabled()) {
1547
                    if (p instanceof C00PacketKeepAlive) {
1548
                        event.setCancelled(true);
1549
                    }
1550
                }
1551
                break;
1552
1553
            case "MineBox":
1554
                if (PlayerUtil.generalAntiPacketLog() && PlayerUtil.isOnServer("minebox") && p instanceof C03PacketPlayer) {
1555
                    event.setCancelled(true);
1556
                }
1557
                break;
1558
1559
//            case "Verus": {
1560
//                if (event.getPacket() instanceof C03PacketPlayer.C04PacketPlayerPosition && verusMode.getMode().equals("Hop")) {
1561
//                    C03PacketPlayer.C04PacketPlayerPosition packet = (C03PacketPlayer.C04PacketPlayerPosition) event.getPacket();
1562
//
1563
//                    switch (stage) {
1564
//                        case 1: {
1565
//                            packet.setY(packet.getY() + 0.42F);
1566
//                            packet.setOnGround(false);
1567
//                            break;
1568
//                        }
1569
//                        case 2: {
1570
//                            packet.setY(packet.getY() + 0.3415999853611);
1571
//                            packet.setOnGround(false);
1572
//                            break;
1573
//                        }
1574
//                        case 3: {
1575
//                            packet.setY(packet.getY() + 0.1863679808445);
1576
//                            packet.setOnGround(false);
1577
//                            break;
1578
//                        }
1579
//                    }
1580
//
1581
//                    event.setPacket(packet);
1582
////                    Rise.addChatMessage(stage + "   " + packet.getPositionY());
1583
//                }
1584
//            }
1585
        }
1586
1587
        if (!mode.is("Timer Bypass") || mc.isIntegratedServerRunning() || mc.thePlayer == null || mc.thePlayer.isDead)
1588
            return;
1589
1590
        if (mc.thePlayer.ticksExisted < 10) {
1591
            packets.clear();
1592
            mc.timer.timerSpeed = 1;
1593
            return;
1594
        }
1595
1596
        mc.timer.timerSpeed = (float) speedTimer.getValue();
1597
1598
        packets.add(p);
1599
1600
        event.setCancelled(true);
1601
1602
        if (!packets.isEmpty() && mc.thePlayer.ticksExisted % (int) pulse.getValue() != 0) return;
1603
1604
        packets.forEach(PacketUtil::sendPacketWithoutEvent);
1605
        packets.clear();
1606
1607
    }
1608
1609
    @Override
1610
    public void onStrafe(final StrafeEvent event) {
1611
        if (ticksDisable <= 20) {
1612
            return;
1613
        }
1614
1615
        if (mode.getMode().toLowerCase().contains("ncp")) {
1616
            MoveUtil.strafe();
1617
        }
1618
1619
        switch (mode.getMode()) {
1620
1621
            case "Strafe":
1622
                MoveUtil.strafe();
1623
                break;
1624
1625
            case "Vulcan":
1626
                if (offGroundTicks <= 2) MoveUtil.strafe();
1627
                break;
1628
1629
            case "Cubecraft":
1630
                if (MoveUtil.isMoving()) {
1631
                    final double baseSpeed = MoveUtil.getBaseMoveSpeed();
1632
                    switch (offGroundTicks) {
1633
                        case 0:
1634
                            if (mc.thePlayer.onGround) {
1635
                                /*
1636
                                 * Sets speed on ground
1637
                                 */
1638
                                speed = baseSpeed * (1.9 - (Math.random() / 500));
1639
1640
                                /*
1641
                                 * Automatically jumps
1642
                                 */
1643
                                mc.thePlayer.motionY = MoveUtil.getJumpMotion(0.42F);
1644
                            }
1645
                            break;
1646
1647
                        case 5:
1648
                            /*
1649
                             * Makes you go down faster
1650
                             */
1651
                            mc.thePlayer.motionY = MoveUtil.getPredictedMotionY(mc.thePlayer.motionY);
1652
                            break;
1653
                    }
1654
1655
                    /*
1656
                     * Sets the timer speed
1657
                     */
1658
                    mc.timer.timerSpeed = (float) (1.1 - Math.random() / 100);
1659
1660
                    /*
1661
                     * Sets the players speed
1662
                     */
1663
                    if (mc.thePlayer.onGround) {
1664
                        event.setFriction((float) Math.max(baseSpeed,
1665
                                event.getForward() != 0 && event.getStrafe() != 0 ? speed * 0.91F : speed));
1666
                        MoveUtil.stop();
1667
                    } else
1668
                        MoveUtil.strafe();
1669
                } else if (mc.currentScreen == null) {
1670
                    MoveUtil.stop();
1671
                    mc.timer.timerSpeed = 1;
1672
                }
1673
                break;
1674
1675
            case "Hypixel2":
1676
                if(hypixeldamageBoost.isEnabled() && !mc.thePlayer.onGround) {
1677
                    if (mc.thePlayer.hurtTime > 0 && mc.thePlayer.hurtTime < 5) {
1678
                        boost = true;
1679
                        if (boost && !mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
1680
                            MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 1.7 - (mc.thePlayer.hurtTime / 10) - Math.random() / 100f);
1681
                        } else if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
1682
                            MoveUtil.strafe(MoveUtil.getBaseMoveSpeed() * 1.6 - (mc.thePlayer.hurtTime / 10) - Math.random() / 100f);
1683
                        }
1684
                    } else {
1685
                        boost = false;
1686
                    }
1687
                }
1688
                if (mc.thePlayer.onGround && MoveUtil.isMoving()) {
1689
                    MoveUtil.strafe(MoveUtil.getAllowedHorizontalDistance() - Math.random() / 100);
1690
                    mc.thePlayer.jump();
1691
1692
                    if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
1693
                        MoveUtil.strafe(MoveUtil.getSpeed() * 1.1 - Math.random() / 100);
1694
                    }
1695
                }
1696
1697
                double motionX = mc.thePlayer.motionX;
1698
                double motionZ = mc.thePlayer.motionZ;
1699
1700
                MoveUtil.strafe();
1701
1702
                if (!mc.thePlayer.onGround) {
1703
                    mc.thePlayer.motionX = (mc.thePlayer.motionX * 3 + motionX) / 4;
1704
                    mc.thePlayer.motionZ = (mc.thePlayer.motionZ * 3 + motionZ) / 4;
1705
                }
1706
1707
                if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
1708
                    MoveUtil.strafe(MoveUtil.getSpeed() * 1.03 - Math.random() / 100);
1709
                }
1710
1711
                mc.timer.timerSpeed = (float) hypixelTimer.getValue();
1712
                break;
1713
            case "Hypixel3":
1714
                if (mc.thePlayer.onGround && MoveUtil.isMoving()) {
1715
                    MoveUtil.strafe(MoveUtil.getAllowedHorizontalDistance() - Math.random() / 100);
1716
                    if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
1717
                        MoveUtil.strafe(MoveUtil.getSpeed() * 1.1 - Math.random() / 100);
1718
                    }
1719
                    mc.thePlayer.jump();
1720
1721
                }
1722
                if (mc.thePlayer.motionY < 0.1D && mc.thePlayer.motionY > -0.21D && mc.thePlayer.motionY != 0) {
1723
                    mc.thePlayer.motionY -= 0.05D;
1724
1725
                }
1726
1727
                MoveUtil.strafe();
1728
1729
1730
                if (offGroundTicks == 5) {
1731
                    mc.thePlayer.motionY = MoveUtil.getPredictedMotionY(mc.thePlayer.motionY);
1732
                }
1733
1734
                if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
1735
                }
1736
                if (mc.thePlayer.hurtTime > 0) {
1737
                    MoveUtil.strafe(MoveUtil.getSpeed() * 1.03 - Math.random() / 100);
1738
                }
1739
1740
                mc.timer.timerSpeed = (float) hypixelTimer.getValue();
1741
                break;
1742
1743
1744
            case "Teleport":
1745
                if (strafe.isEnabled()) MoveUtil.strafe();
1746
                break;
1747
1748
            case "NCP Latest":
1749
                mc.timer.timerSpeed = (float) timerNcp.getValue();
1750
1751
                if (mc.thePlayer.onGround && MoveUtil.isMoving()) {
1752
                    mc.thePlayer.jump();
1753
                    mc.thePlayer.motionY = MoveUtil.getJumpMotion((float) (0.4 + Math.random() / 500));
1754
1755
                    mc.thePlayer.speedInAir = (float) speedInAirNcp.getValue();
1756
                    if (mc.thePlayer.isPotionActive(Potion.moveSpeed) &&
1757
                            (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier() + 1) == 2) {
1758
                        mc.thePlayer.motionX *= speedMultiplierNCPSpeed2.getValue();
1759
                        mc.thePlayer.motionZ *= speedMultiplierNCPSpeed2.getValue();
1760
                        mc.thePlayer.speedInAir = (float) speedInAirNcpSpeed2.getValue();
1761
                    } else if (mc.thePlayer.isPotionActive(Potion.moveSpeed) &&
1762
                            (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier() + 1) == 1) {
1763
                        mc.thePlayer.motionX *= speedMultiplierNCPSpeed1.getValue();
1764
                        mc.thePlayer.motionZ *= speedMultiplierNCPSpeed1.getValue();
1765
                        mc.thePlayer.speedInAir = (float) speedInAirNcpSpeed1.getValue();
1766
                    } else {
1767
                        mc.thePlayer.motionX *= speedMultiplierNCP.getValue();
1768
                        mc.thePlayer.motionZ *= speedMultiplierNCP.getValue();
1769
                    }
1770
                }
1771
1772
                if (MoveUtil.isMoving() && smartTimer.isEnabled()) {
1773
                    float timerSpeed = (float) (1.1 + 0.5 - MoveUtil.getSpeed());
1774
1775
                    if (!jumped) {
1776
                        timerSpeed = (float) (1.337 - MoveUtil.getSpeed());
1777
                    }
1778
1779
                    if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
1780
                        timerSpeed += (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier() + 1) / 12f;
1781
                    }
1782
1783
                    if (timerSpeed > 1.5) timerSpeed = 1.5f;
1784
                    if (timerSpeed < 0.6) timerSpeed = 0.6f;
1785
                    mc.timer.timerSpeed = timerSpeed;
1786
                }
1787
1788
                MoveUtil.strafe();
1789
1790
                break;
1791
1792
            case "Hypixel":
1793
                double motionX2 = mc.thePlayer.motionX;
1794
                double motionZ2 = mc.thePlayer.motionZ;
1795
1796
                MoveUtil.strafe();
1797
1798
                if (!mc.thePlayer.onGround && offGroundTicks != 1) {
1799
                    mc.thePlayer.motionX = (mc.thePlayer.motionX * 3 + motionX2) / 4;
1800
                    mc.thePlayer.motionZ = (mc.thePlayer.motionZ * 3 + motionZ2) / 4;
1801
                }
1802
1803
                mc.thePlayer.motionX *= 0.99;
1804
                mc.thePlayer.motionZ *= 0.99;
1805
                break;
1806
        }
1807
    }
1808
1809
    public float getMovementDirection(float forward, float strafing, float yaw) {
1810
        if (forward == 0.0F && strafing == 0.0F) return yaw;
1811
        boolean reversed = (forward < 0.0F);
1812
        float strafingYaw = 90.0F * ((forward > 0.0F) ? 0.5F : (reversed ? -0.5F : 1.0F));
1813
        if (reversed) yaw += 180.0F;
1814
        if (strafing > 0.0F) {
1815
            yaw -= strafingYaw;
1816
        } else if (strafing < 0.0F) {
1817
            yaw += strafingYaw;
1818
        }
1819
        return yaw;
1820
    }
1821
1822
    private double lowHopYModification(final double baseMotionY, final double yDistFromGround) {
1823
        if (yDistFromGround == lowhopy[0]) {
1824
            return 0.31;
1825
        } else if (yDistFromGround == lowhopy[1]) {
1826
            return 0.04;
1827
        } else if (yDistFromGround == lowhopy[2]) {
1828
            return -0.2;
1829
        } else if (yDistFromGround == lowhopy[3]) {
1830
            return -0.14;
1831
        } else if (yDistFromGround == lowhopy[4]) {
1832
            return -0.2;
1833
        }
1834
        return baseMotionY;
1835
    }
1836
1837
    public static final double[] lowhopy = {
1838
            round(0.4, 3, 0.001),
1839
            round(0.71, 3, 0.001),
1840
            round(0.75, 3, 0.001),
1841
            round(0.55, 3, 0.001),
1842
            round(0.41, 3, 0.001),
1843
    };
1844
1845
1846
    @Override
1847
    public void onRender2DEvent(final Render2DEvent event) {
1848
        switch (mode.getMode()) {
1849
1850
        }
1851
    }
1852
1853
    @Override
1854
    public void onWorldChanged(final WorldChangedEvent event) {
1855
        if (disableOnWorldChange.isEnabled()) {
1856
            this.toggleModule();
1857
            this.registerNotification("Disabled " + this.getModuleInfo().name() + " due to world change.");
1858
        }
1859
    }
1860
1861
    @Override
1862
    public void onPacketReceive(final PacketReceiveEvent event) {
1863
        if (ticksDisable <= 20) {
1864
            return;
1865
        }
1866
1867
        final Packet<?> p = event.getPacket();
1868
        if (mc.thePlayer.ticksExisted <= 1)
1869
            return;
1870
1871
        switch (mode.getMode()) {
1872
            case "Zonecraft":
1873
                if (mc.thePlayer.ticksExisted > 20) {
1874
                    if (p instanceof S08PacketPlayerPosLook) {
1875
                        event.setCancelled(true);
1876
                        mc.thePlayer.sendQueue.addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(((S08PacketPlayerPosLook) p).x, ((S08PacketPlayerPosLook) p).y, ((S08PacketPlayerPosLook) p).z, true));
1877
                    }
1878
                }
1879
                break;
1880
1881
            case "Minemenclub Hop":
1882
                if (p instanceof S08PacketPlayerPosLook) {
1883
                    balance = 0;
1884
                }
1885
                break;
1886
1887
            case "Vulcan2":
1888
                if (p instanceof S08PacketPlayerPosLook && mc.thePlayer.ticksExisted > 20) {
1889
                    S08PacketPlayerPosLook s08 = ((S08PacketPlayerPosLook) p);
1890
                    if (mc.thePlayer.getDistanceSq(s08.getX(), s08.getY(), s08.getZ()) < 25 * 4) {
1891
                        event.setCancelled(true);
1892
                    }
1893
                }
1894
                break;
1895
1896
            case "Hypixel2":
1897
1898
                if (p instanceof S08PacketPlayerPosLook && mc.thePlayer.ticksExisted > 20) {
1899
                    if (!bool) {
1900
                        event.setCancelled(true);
1901
//                        Rise.addChatMessage("test");
1902
                        bool = true;
1903
                    }
1904
                }
1905
1906
                break;
1907
1908
        }
1909
1910
        if (p instanceof S08PacketPlayerPosLook && disableOnFlag.isEnabled()) {
1911
            ticksDisable = 0;
1912
1913
            onDisable();
1914
            this.registerNotification("Temporarily disabled speed due to a teleport.");
1915
        }
1916
1917
        if (event.getPacket() instanceof S00PacketDisconnect) {
1918
            balance = 0;
1919
        }
1920
    }
1921
}

What this file does

The whole module is this file, and the handlers split the work by event type. onPreMotion is the mode switch: it maintains the ground/air tick counters, performs the Custom toolkit, the bhop-family modes (Strafe Hop, Minemenclub Hop, Mineplex Low/Smooth, CraftPlay, KoksCraft, BlocksMC, Taka, Spartan, Zonecraft, Exempted Value, Predictive, Intave, Invadedlands, AAC 4 Simple, Redesky, Vulcan) and the Verus Hop/Float sub-modes. onMove carries the Verus Low/YPort sequences and the Mineplex stage machine (0.42 jump, speed += base/2 capped at 1, 0.985 decay, air strafe at max(base, speed)). onStrafe implements the friction-manipulating modes: Cubecraft sets the ground friction to max(base, speed * 0.91) on the strafe event itself, Hypixel2/3 and Hypixel blend the strafe vector (motionX = (motionX*3 + old)/4) and apply potion multipliers, and NCP Latest runs its speedInAir and smartTimer logic there. onPacketSend is where packets are cancelled: Verus Hop cancels every C0F, Custom cancels C0F (cancelC0F) and C00 (cancelC00), MineBox cancels every C03 on minebox servers, and Timer Bypass re-buffers everything. onPacketReceive handles S08 teleports (disableOnFlag self-disable, Zonecraft eater, Hypixel2 single cancel, Vulcan2 radius cancel) and the S00 disconnect that resets the balance counter.

source MoveUtil.java (strafe math)

MoveUtil.java352 lines · JavaOriginal ↗
1
/*
2
 * LiquidBounce Hacked Client
3
 * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
4
 * https://github.com/CCBlueX/LiquidBounce/
5
 * Ty for borrow lol
6
 */
7
package dev.rise.util.player;
8
9
import dev.rise.Rise;
10
import dev.rise.event.impl.other.MoveEvent;
11
import dev.rise.event.impl.other.StrafeEvent;
12
import dev.rise.module.impl.player.Scaffold;
13
import lombok.experimental.UtilityClass;
14
import net.minecraft.block.Block;
15
import net.minecraft.block.BlockWeb;
16
import net.minecraft.client.Minecraft;
17
import net.minecraft.entity.player.EntityPlayer;
18
import net.minecraft.init.Blocks;
19
import net.minecraft.network.play.client.C03PacketPlayer;
20
import net.minecraft.potion.Potion;
21
import net.minecraft.util.MathHelper;
22
import net.minecraft.util.MovementInput;
23
24
import javax.vecmath.Vector2d;
25
26
/**
27
 * MoveUtils, used to move in modules
28
 *
29
 * @author Liquidbounce
30
 * @since 13/02/2021
31
 */
32
33
@UtilityClass
34
public final class MoveUtil {
35
36
    private final Minecraft mc = Minecraft.getMinecraft();
37
38
    /**
39
     * Used to get the players speed
40
     */
41
    public double getSpeed() {
42
        // nigga hypot heavy
43
        return Math.hypot(mc.thePlayer.motionX, mc.thePlayer.motionZ);
44
    }
45
46
    /**
47
     * Sets current speed to itself make strafe
48
     */
49
    public void strafe() {
50
        strafe(getSpeed());
51
    }
52
53
    /**
54
     * Checks if the player is moving
55
     */
56
    public boolean isMoving() {
57
        return mc.thePlayer != null && (mc.thePlayer.movementInput.moveForward != 0F || mc.thePlayer.movementInput.moveStrafe != 0F);
58
    }
59
60
    public void stop() {
61
        mc.thePlayer.motionX = mc.thePlayer.motionZ = 0;
62
    }
63
64
    /**
65
     * Sets players speed, with floats
66
     */
67
    public void strafe(final float speed) {
68
        if (!isMoving()) return;
69
70
        final double yaw = getDirection();
71
72
        mc.thePlayer.motionX = -MathHelper.sin((float) yaw) * speed;
73
        mc.thePlayer.motionZ = MathHelper.cos((float) yaw) * speed;
74
    }
75
76
    /**
77
     * Used to get the players speed, with doubles
78
     */
79
    public void strafe(final double speed) {
80
        if (!isMoving()) return;
81
82
        final double yaw = getDirection();
83
        mc.thePlayer.motionX = -MathHelper.sin((float) yaw) * speed;
84
        mc.thePlayer.motionZ = MathHelper.cos((float) yaw) * speed;
85
    }
86
87
    public void forward(final double speed) {
88
        final double yaw = getDirection();
89
90
        mc.thePlayer.motionX = -Math.sin(yaw) * speed;
91
        mc.thePlayer.motionZ = Math.cos(yaw) * speed;
92
    }
93
94
    /**
95
     * Basically calculates allowed horizontal distance just like NCP does
96
     *
97
     * @return allowed horizontal distance in one tick
98
     */
99
    public double getAllowedHorizontalDistance() {
100
        double horizontalDistance;
101
        boolean useBaseModifiers = false;
102
103
        if (PlayerUtil.getBlockRelativeToPlayer(0, 0, 0) instanceof BlockWeb) {
104
            horizontalDistance = 0.105;
105
        } else if (mc.thePlayer.isInLiquid()) {
106
            horizontalDistance = 0.115F;
107
        } else if (mc.thePlayer.isSneaking()) {
108
            horizontalDistance = 0.3F * 0.221;
109
        } else {
110
            horizontalDistance = 0.221;
111
            useBaseModifiers = true;
112
        }
113
114
        if (useBaseModifiers) {
115
            if (Math.abs(mc.thePlayer.moveForward) >= 0.8F || Math.abs(mc.thePlayer.moveStrafing) >= 0.8F) {
116
                horizontalDistance *= 1.3F;
117
            }
118
119
            final Scaffold scaffold = (Scaffold) Rise.INSTANCE.getModuleManager().getModule("Scaffold");
120
121
            if (mc.thePlayer.isPotionActive(Potion.moveSpeed) && mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getDuration() > 0) {
122
                horizontalDistance *= 1 + (0.2 * (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier() + 1));
123
            }
124
125
            if (mc.thePlayer.isPotionActive(Potion.moveSlowdown)) {
126
                horizontalDistance = 0.29;
127
            }
128
        }
129
130
        final Block below = PlayerUtil.getBlockRelativeToPlayer(0, -1, 0);
131
        if (below == Blocks.ice || below == Blocks.packed_ice) {
132
            horizontalDistance *= 2.5F;
133
        }
134
135
        return horizontalDistance;
136
    }
137
138
139
    public double moveSpeed() {
140
        if (mc.gameSettings.keyBindSprint.isKeyDown()) {
141
            if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
142
                if (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier() + 1 == 1) {
143
                    return 0.18386012061481244;
144
                } else {
145
                    return 0.21450346015841276;
146
                }
147
            } else {
148
                return 0.15321676228437875;
149
            }
150
        } else {
151
            if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
152
                if (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier() + 1 == 1) {
153
                    return 0.14143085686761;
154
                } else {
155
                    return 0.16500264553372018;
156
                }
157
            } else {
158
                return 0.11785905094607611;
159
            }
160
        }
161
    }
162
163
    /**
164
     * Used to get the players speed with a custom yaw
165
     */
166
    public void strafe(final double speed, double yaw) {
167
        if (!isMoving()) return;
168
169
        if (EntityPlayer.movementYaw != null) {
170
            yaw = EntityPlayer.movementYaw;
171
        }
172
173
        mc.thePlayer.motionX = -MathHelper.sin((float) yaw) * speed;
174
        mc.thePlayer.motionZ = MathHelper.cos((float) yaw) * speed;
175
    }
176
177
    /**
178
     * Gets the direction of were the player is looking
179
     */
180
    public double getDirection() {
181
        float rotationYaw = mc.thePlayer.rotationYaw;
182
183
        if (mc.thePlayer.moveForward < 0F) rotationYaw += 180F;
184
185
        float forward = 1F;
186
187
        if (mc.thePlayer.moveForward < 0F) forward = -0.5F;
188
        else if (mc.thePlayer.moveForward > 0F) forward = 0.5F;
189
190
        if (mc.thePlayer.moveStrafing > 0F) rotationYaw -= 90F * forward;
191
        if (mc.thePlayer.moveStrafing < 0F) rotationYaw += 90F * forward;
192
193
        return Math.toRadians(rotationYaw);
194
    }
195
196
    public double getDirectionWrappedTo90() {
197
        float rotationYaw = mc.thePlayer.rotationYaw;
198
199
        if (mc.thePlayer.moveForward < 0F && mc.thePlayer.moveStrafing == 0F) rotationYaw += 180F;
200
201
        final float forward = 1F;
202
203
        if (mc.thePlayer.moveStrafing > 0F) rotationYaw -= 90F * forward;
204
        if (mc.thePlayer.moveStrafing < 0F) rotationYaw += 90F * forward;
205
206
        return Math.toRadians(rotationYaw);
207
    }
208
209
    public double getDirection(final float yaw) {
210
        float rotationYaw = yaw;
211
212
        if (EntityPlayer.movementYaw != null) {
213
            rotationYaw = EntityPlayer.movementYaw;
214
        }
215
216
        if (mc.thePlayer.moveForward < 0F) rotationYaw += 180F;
217
218
        float forward = 1F;
219
220
        if (mc.thePlayer.moveForward < 0F) forward = -0.5F;
221
        else if (mc.thePlayer.moveForward > 0F) forward = 0.5F;
222
223
        if (mc.thePlayer.moveStrafing > 0F) rotationYaw -= 90F * forward;
224
        if (mc.thePlayer.moveStrafing < 0F) rotationYaw += 90F * forward;
225
226
        return Math.toRadians(rotationYaw);
227
    }
228
229
    /**
230
     * Used to get base movement speed
231
     */
232
    public double getBaseMoveSpeed() {
233
        double baseSpeed = 0.2873D;
234
235
        if (mc.thePlayer.isPotionActive(Potion.moveSpeed))
236
            baseSpeed *= 1.0D + 0.2D * (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier() + 1);
237
238
        return baseSpeed;
239
    }
240
241
    public double getBaseMoveSpeedOther() {
242
        double baseSpeed = 0.2875D;
243
244
        if (mc.thePlayer.isPotionActive(Potion.moveSpeed))
245
            baseSpeed *= 1.0D + 0.2D * (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed).getAmplifier() + 1);
246
247
        return baseSpeed;
248
    }
249
250
    public double getJumpMotion(float motionY) {
251
        final Potion potion = Potion.jump;
252
253
        if (mc.thePlayer.isPotionActive(potion)) {
254
            final int amplifier = mc.thePlayer.getActivePotionEffect(potion).getAmplifier();
255
            motionY += (amplifier + 1) * 0.1F;
256
        }
257
258
        return motionY;
259
    }
260
261
    public double getPredictedMotionY(final double motionY) {
262
        return (motionY - 0.08) * 0.98F;
263
    }
264
265
    public void setMoveEventSpeed(final MoveEvent moveEvent, final double moveSpeed) {
266
        setMoveEvent(moveEvent, moveSpeed, mc.thePlayer.rotationYaw, mc.thePlayer.movementInput.moveStrafe, mc.thePlayer.movementInput.moveForward);
267
    }
268
269
    // jumps without setting motionY to 0.42F
270
    // in other words, increases motionX/Z and everything else that the jump method does, allowing a custom motionY
271
    public void jumpNoMotionY() {
272
        double motionY = mc.thePlayer.motionY;
273
        mc.thePlayer.jump();
274
        mc.thePlayer.motionY = motionY;
275
    }
276
277
    public void sendMotion(final double speed, final double dist) {
278
        final Vector2d motion = getMotion(dist);
279
        double d = dist;
280
        while (d < speed) {
281
            mc.thePlayer.moveEntityNoEvent(motion.x, 0, motion.y);
282
            PacketUtil.sendPacket(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
283
            d += dist;
284
        }
285
    }
286
287
    public Vector2d getMotion(final double moveSpeed) {
288
        final MovementInput movementInput = mc.thePlayer.movementInput;
289
290
        double moveForward = movementInput.moveForward;
291
        double moveStrafe = movementInput.moveStrafe;
292
293
        double rotationYaw = mc.thePlayer.rotationYaw;
294
        if (moveForward != 0.0D || moveStrafe != 0.0D) {
295
            if (moveStrafe > 0) {
296
                moveStrafe = 1;
297
            } else if (moveStrafe < 0) {
298
                moveStrafe = -1;
299
            }
300
            if (moveForward != 0.0D) {
301
                if (moveStrafe > 0.0D) {
302
                    rotationYaw += moveForward > 0.0D ? -45 : 45;
303
                } else if (moveStrafe < 0.0D) {
304
                    rotationYaw += moveForward > 0.0D ? 45 : -45;
305
                }
306
                moveStrafe = 0.0D;
307
                if (moveForward > 0.0D) {
308
                    moveForward = 1.0D;
309
                } else if (moveForward < 0.0D) {
310
                    moveForward = -1.0D;
311
                }
312
            }
313
            rotationYaw *= 0.995;
314
            final double cos = Math.cos(Math.toRadians(rotationYaw + 90.0F));
315
            final double sin = Math.sin(Math.toRadians(rotationYaw + 90.0F));
316
            return new Vector2d(moveForward * moveSpeed * cos
317
                    + moveStrafe * moveSpeed * sin, moveForward * moveSpeed * sin
318
                    - moveStrafe * moveSpeed * cos);
319
        }
320
        return new Vector2d(0, 0);
321
    }
322
323
    public void setMoveEvent(final MoveEvent moveEvent, final double moveSpeed, final float pseudoYaw, final double pseudoStrafe, final double pseudoForward) {
324
        double forward = pseudoForward;
325
        double strafe = pseudoStrafe;
326
        float yaw = pseudoYaw;
327
328
        if (forward != 0.0D) {
329
            if (strafe > 0.0D) {
330
                yaw += ((forward > 0.0D) ? -45 : 45);
331
            } else if (strafe < 0.0D) {
332
                yaw += ((forward > 0.0D) ? 45 : -45);
333
            }
334
            strafe = 0.0D;
335
            if (forward > 0.0D) {
336
                forward = 1.0D;
337
            } else if (forward < 0.0D) {
338
                forward = -1.0D;
339
            }
340
        }
341
        if (strafe > 0.0D) {
342
            strafe = 1.0D;
343
        } else if (strafe < 0.0D) {
344
            strafe = -1.0D;
345
        }
346
        final double mx = Math.cos(Math.toRadians((yaw + 90.0F)));
347
        final double mz = Math.sin(Math.toRadians((yaw + 90.0F)));
348
        moveEvent.setX(forward * moveSpeed * mx + strafe * moveSpeed * mz);
349
        moveEvent.setZ(forward * moveSpeed * mz - strafe * moveSpeed * mx);
350
    }
351
352
}

What this file does

MoveUtil (ported from LiquidBounce) is the shared math behind every mode. strafe(speed) writes motionX = -sin(yaw) * speed and motionZ = cos(yaw) * speed using getDirection(), which flips the yaw 180 degrees when moving backward and offsets it 90 * forward per strafe key; strafe() with no argument preserves the current magnitude from getSpeed(). getBaseMoveSpeed returns 0.2873 scaled by 1 + 0.2 * (amplifier + 1) per speed-potion level, and getAllowedHorizontalDistance re-derives NCP's own model (0.221 base, 1.3 sprint factor, potion scaling, 2.5x on ice) so the Hypixel2/3 modes can strafe exactly at the server's allowance. getPredictedMotionY implements (motionY - 0.08) * 0.98 (the gravity step the modes use for their re-jump and fast-fall packets), getJumpMotion adds 0.1 per jump-potion level, and setMoveEvent writes the event delta with the 45-degree diagonal blend so the reported C03 vector matches the motion fields the physics step will consume.

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 rebuilds the client's physics from the world. In check() the horizontal allowance comes from prepareSpeedEstimation (line 683), which picks friction and acceleration by medium (on-ground friction cubed vs Magic.AIR_ACCELERATION) and feeds estimateNextSpeed to predict the per-tick distance; the vertical allowance comes from vDistRel, and the violation is (max(hDistanceAboveLimit, 0) + max(yDistanceAboveLimit, 0)) * 100 with a set-back to the stored location. Critically, fromOnGround and toOnGround come from RichBoundsLocation.isOnGround(), a block ray trace, not the packet's flag, so every ground-spoofing switch in the Custom mode (groundDisabler, groundSpoofMode on/air/tick, the extraGround C04s with onGround true) cannot relax the envelope. The Custom pin at the default 0.35 blocks per tick already exceeds the ~0.28-0.31 sprint prediction, so hdistrel is around 0.04-0.07 and the violation fires on the first move; the Hypixel mode's 1.6x ground strafe (0.4597 bpt), the NCP mode's speedMulti 1.1 re-pin, and Vulcan2's 2.5x base strafe breach it by far more. The 0.42 jump and the 0.4 low hops stay inside the vertical jump envelope (vDistRel accepts jump motion and arms a 10-tick jumpDelay), so the vertical side is clean - the hdistrel tag is the signal.

anticheat MorePackets (movement packet rate)

MorePackets.java127 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.List;
19
20
import org.bukkit.Location;
21
import org.bukkit.entity.Player;
22
23
import fr.neatmonster.nocheatplus.actions.ParameterName;
24
import fr.neatmonster.nocheatplus.checks.Check;
25
import fr.neatmonster.nocheatplus.checks.CheckType;
26
import fr.neatmonster.nocheatplus.checks.ViolationData;
27
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
28
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
29
import fr.neatmonster.nocheatplus.checks.net.NetStatic;
30
import fr.neatmonster.nocheatplus.players.IPlayerData;
31
import fr.neatmonster.nocheatplus.utilities.StringUtil;
32
import fr.neatmonster.nocheatplus.utilities.location.PlayerLocation;
33
34
/**
35
 * The MorePackets check will try to identify players that send more than the usual
36
 * amount of move-packets to the server to be able to move faster than normal, without getting caught by the other
37
 * checks (flying/running).
38
 */
39
public class MorePackets extends Check {
40
41
    private final List<String> tags = new ArrayList<String>();
42
43
    /**
44
     * Instantiates a new more packets check.
45
     */
46
    public MorePackets() {
47
        super(CheckType.MOVING_MOREPACKETS);
48
    }
49
50
    /**
51
     * Check for speeding by sending too many packets. We assume 22 packets per
52
     * second to be legitimate, while 20 would be ideal. See
53
     * PlayerData.morePacketsFreq for the monitored amount of time and the
54
     * resolution. See NetStatic for the actual check code.
55
     * 
56
     * @param player
57
     * @param from
58
     * @param to
59
     * @param allowSetSetBack
60
     *            If to allow setting the set back location.
61
     * @param data
62
     * @param cc
63
     * @return
64
     */
65
    public Location check(final Player player, final PlayerLocation from, final PlayerLocation to, 
66
            final boolean allowSetSetBack, final MovingData data, final MovingConfig cc,
67
            final IPlayerData pData) {
68
        // Take time once, first:
69
        final long time = System.currentTimeMillis();
70
        final boolean debug = pData.isDebugActive(type);
71
72
        //    	if (from.isSamePos(to)) {
73
        //    		// Ignore moves with "just look" for now.
74
        //    		// TODO: Extra ActionFrequency for "just look" + use to burn, maybe also check individually.
75
        //    		return null;
76
        //    	}
77
78
        // Ensure we have a set back location.
79
        if (allowSetSetBack && !data.hasMorePacketsSetBack()){
80
            // TODO: Check if other set back is appropriate or if to set/reset on other events.
81
            if (data.hasSetBack()) {
82
                data.setMorePacketsSetBackFromSurvivalfly();
83
            }
84
            else {
85
                data.setMorePacketsSetBack(from);
86
            }
87
        }
88
89
        // Check for a violation of the set limits.
90
        tags.clear();
91
        final double violation = NetStatic.morePacketsCheck(data.morePacketsFreq, time, 1f, cc.morePacketsEPSMax, cc.morePacketsEPSIdeal, data.morePacketsBurstFreq, cc.morePacketsBurstPackets, cc.morePacketsBurstDirect, cc.morePacketsBurstEPM, tags);
92
93
        // Process violation result.
94
        if (violation > 0.0) {
95
            // Increment violation level.
96
            data.morePacketsVL = violation; // TODO: Accumulate somehow [e.g. always += 1, decrease with continuous moving without violation]?
97
98
            // Violation handling.
99
            final ViolationData vd = new ViolationData(this, player, data.morePacketsVL, violation, cc.morePacketsActions);
100
            if (debug || vd.needsParameters()) {
101
                vd.setParameter(ParameterName.PACKETS, Integer.toString(new Double(violation).intValue()));
102
                vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
103
            }
104
            if (executeActions(vd).willCancel()) {
105
                // Set to cancel the move.
106
                /*
107
                 * TODO: Harmonize with MovingUtil.getApplicableSetBackLocation
108
                 * (somehow include the desired set back type / loc / context).
109
                 */
110
                return data.hasMorePacketsSetBack() ? data.getMorePacketsSetBack() : data.getSetBack(to); // TODO
111
            }
112
        } 
113
        else if (allowSetSetBack && data.getMorePacketsSetBackAge() > cc.morePacketsSetBackAge) {
114
            // Update the set back location. (CHANGED to only update, if not a violation.)
115
            // (Might update whenever newTo == null)
116
            data.setMorePacketsSetBack(from);
117
            if (debug) {
118
                debug(player, "Update set back (morepackets) to from.");
119
            }
120
        }
121
122
        // No set back.
123
        return null;
124
125
    }
126
127
}

How it counteracts this module

MorePackets counts the raw serverbound move rate, content-blind. Every processed move is scored into data.morePacketsFreq, an ActionFrequency with 500ms buckets, and NetStatic.morePacketsCheck accumulates the window score against cc.morePacketsEPSMax (22/s, 20 ideal) plus a burst path on the newest half-second bucket (default 15 packets, 10 direct-violation). This is the direct hit on the packet-spam modes. Vulcan2 fires five C06/C04 packets per ground tick - roughly 100/s while hopping - so the window accumulator runs at nearly five times the ceiling and the half-second burst path trips on the very first hop. Convert Ground's burst of up to 200 C06 packets in a single tick is a textbook burst violation, and the Custom mode's extraGround (up to 10 C04 per tick) and voidTP C04s pile onto the same counter. Timer Bypass is caught on the flush: the whole deque is re-emitted in one tick, so even though the buffering keeps the *average* rate near normal, the pulse flush is a burst of 40 packets in one half-second bucket. Because the check never inspects positions, none of the module's ground-spoofing or jitter hides the count.

anticheat Speed (BunnyHop / onGround expected)

Speed.java238 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.CheckType;
6
import me.vrekt.arc.data.moving.MovingData;
7
import me.vrekt.arc.data.moving.VelocityData;
8
import me.vrekt.arc.utilties.ConnectionUtility;
9
import me.vrekt.arc.utilties.LocationHelper;
10
import org.bukkit.ChatColor;
11
import org.bukkit.Location;
12
import org.bukkit.block.BlockFace;
13
import org.bukkit.entity.Player;
14
import org.bukkit.material.Step;
15
import org.bukkit.potion.PotionEffect;
16
import org.bukkit.potion.PotionEffectType;
17
import org.bukkit.util.Vector;
18
19
public class Speed extends Check {
20
21
    private double iceBlockMax, ice;
22
    private double blockMoveMax, stepMax;
23
24
    public Speed() {
25
        super(CheckType.SPEED);
26
27
        iceBlockMax = Arc.getCheckManager().getValueDouble(CheckType.SPEED, "ice_block");
28
        ice = Arc.getCheckManager().getValueDouble(CheckType.SPEED, "ice");
29
        blockMoveMax = Arc.getCheckManager().getValueDouble(CheckType.SPEED, "block");
30
        stepMax = Arc.getCheckManager().getValueDouble(CheckType.SPEED, "step_modifier");
31
32
    }
33
34
    public boolean check(Player player, MovingData data) {
35
        result.reset();
36
        Location from = data.getPreviousLocation();
37
        Location to = data.getCurrentLocation();
38
39
        boolean slab = to.getBlock().getRelative(BlockFace.DOWN).getType().getData().equals(Step.class);
40
        boolean velocityModifier = (LocationHelper.isOnSlab(to) || slab) || (LocationHelper.isOnStair(to) ||
41
                LocationHelper
42
                        .isOnStairJump(to));
43
44
        boolean onGround = data.isOnGround();
45
        int groundTicks = data.getGroundTime();
46
47
        double thisMove = LocationHelper.distanceHorizontal(from, to);
48
        double baseMove = getBaseMoveSpeed(player);
49
        double vertical = data.getVerticalSpeed();
50
51
        int playerPing = ConnectionUtility.getPlayerPing(player);
52
53
        // cancel large movements.
54
        if (thisMove > 8) {
55
            return true;
56
        }
57
58
        // handle groundTick stuff.
59
        if (onGround) {
60
            groundTicks++;
61
            data.setGroundTime(groundTicks >= 8 ? 8 : groundTicks);
62
        }
63
64
        if (!onGround) {
65
            data.setGroundTime(0);
66
            groundTicks = 0;
67
        }
68
69
        // handle ice/slimeblock stuff.
70
        boolean isOnIce = LocationHelper.isOnIce(to);
71
        boolean isOnSlimeblock = LocationHelper.isOnSlimeblock(to);
72
73
        int iceTime = data.getIceTime();
74
        if (!isOnIce) {
75
            // update data.
76
            data.setIceTime(iceTime > 0 ? iceTime - 1 : 0);
77
        } else {
78
            data.setIceTime(8);
79
        }
80
81
        int slimeblockTime = data.getSlimeblockTime();
82
        if (!isOnSlimeblock) {
83
            // update data.
84
            data.setSlimeblockTime(slimeblockTime > 0 ? slimeblockTime - 1 : 0);
85
        } else {
86
            data.setSlimeblockTime(8);
87
        }
88
89
        if (onGround) {
90
            // Check if we have a block above us.
91
            boolean hasBlock = LocationHelper.isUnderBlock(to);
92
93
            // modify ground time.
94
            if (hasBlock) {
95
                if (vertical > 0.0) {
96
                    groundTicks = isOnIce ? 0 : 2;
97
                    data.setGroundTime(groundTicks);
98
                }
99
            }
100
101
            // this does not account for jumping.
102
            double expected = thisMove / data.getGroundTime() + baseMove;
103
104
            if (hasBlock) {
105
                // TODO: Instead of magic values try to calculate an expected?
106
                // we have a block, check if we are jumping.
107
                if (vertical > 0.0) {
108
                    // check if we are on ice.
109
                    if (isOnIce) {
110
                        // we have ice and we are jumping lets adjust and check.
111
                        if (thisMove > iceBlockMax) {
112
                            getCheck().setCheckName("Speed " + ChatColor.GRAY + "(Ice)");
113
                            result.set(checkViolation(player, "Moving too fast, onground_ice_block m=" + thisMove + " e=" + iceBlockMax));
114
                        }
115
                    }
116
117
                    if (!isOnIce && data.getIceTime() <= 3) {
118
                        // no ice and jumping.
119
                        if (thisMove > blockMoveMax) {
120
                            getCheck().setCheckName("Speed " + ChatColor.GRAY + "(BunnyHop)");
121
                            result.set(checkViolation(player, "Moving too fast, onground_block m=" + thisMove + " e=" + blockMoveMax));
122
                        }
123
                    }
124
                }
125
            }
126
127
128
            // make sure we've actually been onGround, without block jumps, etc.
129
            if (groundTicks >= 5 && data.getIceTime() == 0) {
130
                boolean hadModifier = from.getBlock().getRelative(BlockFace.DOWN).getType().getData().equals(Step.class);
131
                double stepModifier = velocityModifier ? stepMax + expected : expected;
132
                // no block, normal check.
133
                if (velocityModifier || hadModifier) {
134
                    if (thisMove > stepModifier) {
135
                        getCheck().setCheckName("Speed " + ChatColor.GRAY + "(onGround)");
136
                        result.set(checkViolation(player, "Moving too fast, onground_expected_velocity m=" + thisMove + " e=" + stepModifier));
137
                    }
138
                } else {
139
                    if (vertical > 0.41) {
140
                        // we jumped but we're still onGround.
141
                        expected += vertical / thisMove;
142
                    }
143
                    if (thisMove > expected) {
144
                        getCheck().setCheckName("Speed " + ChatColor.GRAY + "(onGround)");
145
                        result.set(checkViolation(player, "Moving too fast, onground_expected m=" + thisMove + " e=" + expected));
146
                    }
147
                }
148
149
            }
150
151
            // ice speed
152
            if (isOnIce && groundTicks >= 3) {
153
                if (thisMove > expected + 0.01) {
154
                    getCheck().setCheckName("Speed " + ChatColor.GRAY + "(onGround)");
155
                    result.set(checkViolation(player, "Moving too fast, onground_expected_ice m=" + thisMove + " e=" + expected));
156
                }
157
            }
158
159
        }
160
161
        if (!onGround) {
162
            // if we are on a slimeblock.
163
            if (isOnSlimeblock) {
164
                // get the jump stage
165
                double stage = vertical == 0.0 ? 0.1018 : vertical < 0.34 ? 0.1504 : 0.28;
166
                double expected = (baseMove + stage);
167
                if (thisMove > expected) {
168
                    getCheck().setCheckName("Speed " + ChatColor.GRAY + "(BunnyHop Slimeblock)");
169
                    result.set(checkViolation(player, "Moving too fast, offground_slime m=" + thisMove + " e=" + expected));
170
                }
171
            }
172
173
            if (isOnIce) {
174
                // check if we have been 'launched' by ice.
175
                if (thisMove > ice) {
176
                    getCheck().setCheckName("Speed " + ChatColor.GRAY + "(BunnyHop Ice)");
177
                    result.set(checkViolation(player, "Moving too fast, offground_ice m=" + thisMove + " e=" + ice));
178
                }
179
180
            }
181
182
            boolean hasModifier = (isOnIce || iceTime > 0) || (isOnSlimeblock || slimeblockTime > 0);
183
            if (!hasModifier) {
184
                // get the jump stage
185
                double stage = vertical == 0.0 ? 0.049 : vertical < 0.34 ? 0.08 : 0.3261;
186
                double expected = (baseMove + stage);
187
188
                VelocityData velocityData = data.getVelocityData();
189
                playerPing = Math.min(playerPing, 300); // cap the ping.
190
191
                Vector velocity = velocityData.getRecentVelocity(playerPing);
192
                player.sendMessage("PING: " + playerPing);
193
194
                if (velocity != null) {
195
                    double length = velocity.lengthSquared() + stage;
196
                    double expLength = expected * length;
197
                    expected = getBaseMoveSpeed(player) + expLength;
198
                    player.sendMessage("E: " + expected);
199
                    velocityData.removeVelocity(velocity);
200
                }
201
202
                // too fast, flag.
203
                if (thisMove > expected) {
204
                    getCheck().setCheckName("Speed " + ChatColor.GRAY + "(BunnyHop)");
205
                    result.set(checkViolation(player, "Moving too fast, offground_expected m=" +
206
                            thisMove + " e=" + expected));
207
                }
208
            }
209
        }
210
211
        // if we didnt fail set our setback.
212
        if (!result.failed()) {
213
            data.setSetback(from);
214
        }
215
216
        getCheck().setCheckName("Speed");
217
        return result.failed();
218
    }
219
220
    /**
221
     * Return our base move speed.
222
     *
223
     * @param player the player
224
     * @return players move speed
225
     */
226
    private double getBaseMoveSpeed(Player player) {
227
        double baseSpeed = 0.2873;
228
229
        for (PotionEffect ef : player.getActivePotionEffects()) {
230
            if (ef.getType().equals(PotionEffectType.SPEED)) {
231
                baseSpeed *= 1.0 + 0.2 * ef.getAmplifier() + 1;
232
            }
233
        }
234
235
        return baseSpeed;
236
    }
237
238
}

How it counteracts this module

Arc v2's Speed compares thisMove against expectations built from getBaseMoveSpeed (0.2873) plus a stage chosen by vertical speed: 0.049 at zero vertical, 0.08 while descending below 0.34, 0.3261 while still rising. The default Custom speed of 0.35 sits just under the descending expectation of 0.3673, so the mode only evades at its floor value - raising Custom Speed, enabling randomizeSpeed, or switching to a multiplier mode crosses it immediately: the Hypixel 1.6x ground strafe produces 0.4597 on the descending half of every hop, the NCP mode's speedMulti 1.1 re-pin and Vulcan2's 2.5x base do the same, and all of them trip the BunnyHop offground_expected branch with the measured and expected values in the message. The ground branch (expected = thisMove / groundTime + baseMove, groundTime capped at 8, active after 5+ grounded ticks) catches the pinned-speed modes whenever the player stops hopping and runs on the surface, and the onground_block branch (block above + jumping + thisMove > blockMoveMax 0.6699) catches the overdriven hops. Every non-failing move stores the from location as the set-back, so a flagged hop snaps the player back a full tick.

anticheat Speed (momentum model, discrepancy accumulator)

Speed.java280 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.Event;
25
import me.islandscout.hawk.event.HawkEventListener;
26
import me.islandscout.hawk.event.ItemSwitchEvent;
27
import me.islandscout.hawk.event.MoveEvent;
28
import me.islandscout.hawk.util.*;
29
import me.islandscout.hawk.wrap.entity.WrappedEntity;
30
import org.bukkit.ChatColor;
31
import org.bukkit.Material;
32
import org.bukkit.enchantments.Enchantment;
33
import org.bukkit.entity.Player;
34
import org.bukkit.event.Listener;
35
import org.bukkit.util.Vector;
36
37
import java.util.*;
38
39
public class Speed extends MovementCheck implements Listener {
40
41
    //I legit hate this game's movement.
42
    //Do you realize how much easier it would be if
43
    //the server handled movement?
44
45
    //TODO False flag with pistons
46
47
    //Basically, this check is doing, "if your previous speed was X then your current speed must not exceed f(X)"
48
49
    private static final double EPSILON = 0.000001;
50
    //Now what we can do is predict how far a player could have travelled
51
    //if the move doesn't have a deltaPos due to insignificance.
52
    private static final double MAX_NO_MOVE_DISTANCE = 0.03;
53
    private final double DISCREPANCY_THRESHOLD;
54
    private final double VL_FAIL_DISCREPANCY_FACTOR;
55
    private final boolean RESET_DISCREPANCY_ON_FAIL;
56
    private final int RELEASE_ITEM_OVER_VL;
57
    private final boolean CHECK_FLYING;
58
    private final boolean DEBUG;
59
60
    private final Map<UUID, Double> prevSpeed;
61
    private final Map<UUID, Double> discrepancies;
62
    private final Map<UUID, Integer> noMovesMap;
63
    private final Map<UUID, Double> lastNegativeDiscrepancies;
64
    private final Map<UUID, Double> negativeDiscrepanciesCumulative;
65
    private final Map<UUID, Integer> slotSwitchQuirkTicksMap; //I hate this game.
66
    private final Map<UUID, Long> lastSlotSwitchTickMap;
67
68
    public Speed() {
69
        super("speed", true, 0, 5, 0.99, 5000, "%player% failed movement speed, VL: %vl%", null);
70
        prevSpeed = new HashMap<>();
71
        discrepancies = new HashMap<>();
72
        noMovesMap = new HashMap<>();
73
        lastNegativeDiscrepancies = new HashMap<>();
74
        negativeDiscrepanciesCumulative = new HashMap<>();
75
        slotSwitchQuirkTicksMap = new HashMap<>();
76
        lastSlotSwitchTickMap = new HashMap<>();
77
        DISCREPANCY_THRESHOLD = (double) customSetting("discrepancyThreshold", "", 0.1D);
78
        VL_FAIL_DISCREPANCY_FACTOR = (double) customSetting("vlFailDiscrepancyFactor", "", 10D);
79
        RESET_DISCREPANCY_ON_FAIL = (boolean) customSetting("resetDiscrepancyOnFail", "", true);
80
        RELEASE_ITEM_OVER_VL = (int) customSetting("releaseItemOverVl", "", 4);
81
        CHECK_FLYING = (boolean) customSetting("checkFlying", "", true);
82
        DEBUG = (boolean) customSetting("debug", "", false);
83
    }
84
85
    @Override
86
    protected void check(MoveEvent event) {
87
        Player p = event.getPlayer();
88
        HawkPlayer pp = event.getHawkPlayer();
89
90
        int noMoves = noMovesMap.getOrDefault(p.getUniqueId(), 0);
91
        double lastSpeed;
92
        double speed;
93
        if(event.isUpdatePos()) {
94
            lastSpeed = prevSpeed.getOrDefault(p.getUniqueId(), 0D);
95
            if(noMoves > 0) {
96
                //Players don't update position unless they've moved at least 0.03 blocks (or if 20 ticks passed)
97
                lastSpeed = Math.min(lastSpeed, MAX_NO_MOVE_DISTANCE);
98
            }
99
            speed = MathPlus.distance2d(event.getTo().getX() - event.getFrom().getX(), event.getTo().getZ() - event.getFrom().getZ());
100
        }
101
        else {
102
            speed = prevSpeed.getOrDefault(p.getUniqueId(), 0D) - (lastNegativeDiscrepancies.getOrDefault(p.getUniqueId(), 0D) + EPSILON);
103
            lastSpeed = speed;
104
        }
105
106
        if(event.isUpdatePos())
107
            noMoves = 0;
108
        else
109
            noMoves++;
110
111
        boolean flying = pp.isFlying();
112
        boolean swimming = pp.isInWater(); //this needs improvement
113
        //it is possible that the player has pressed the jump key even if this move is "stepped" (only while sprinting)
114
        boolean jump = event.isJump() || (event.isStep() && pp.isOnGround() && pp.isSprinting());
115
116
        float friction = event.getFriction();
117
        float maxForce = event.getMaxExpectedInputForce();
118
        float maxForceNoItemUse = event.getMaxExpectedInputForceNoItemUse();
119
120
        //It represents the previous location. Block collision is done after moving the entity.
121
        Set<Material> touchedBlocks = WrappedEntity.getWrappedEntity(p).getCollisionBox(event.getFrom().toVector()).getMaterials(pp.getWorld());
122
123
        //handle any pending knockbacks
124
        if(event.hasAcceptedKnockback() || (flying && !CHECK_FLYING)) {
125
            prepareNextMove(pp, noMoves, speed, touchedBlocks);
126
            return;
127
        }
128
129
        double lastSpeedCompare = lastSpeed;
130
        //Handle other things in the game that multiply velocity.
131
        //These affect velocity first (coincidentally, these are all multiplication operations)
132
        double handleMultipliers = 1;
133
        if(event.hasHitSlowdown())
134
            handleMultipliers *= 0.6;
135
        if(touchedBlocks.contains(Material.SOUL_SAND) && !flying)
136
            handleMultipliers *= 0.4;
137
        if(touchedBlocks.contains(Material.WEB) && !flying)
138
            handleMultipliers *= 0.25;
139
        if(Hawk.getServerVersion() > 7 && touchedBlocks.contains(Material.SLIME_BLOCK)) {
140
            //TODO I believe webs affect this mot Y too.
141
            if (Math.abs(pp.getVelocity().getY()) < 0.1 && !pp.isSneaking()) {
142
                handleMultipliers *= 0.4 + Math.abs(pp.getVelocity().getY()) * 0.2;
143
            }
144
        }
145
        //Handle other things in the game that add to velocity.
146
        //These affect velocity later (coincidentally, these are all addition operations)
147
        double handleAdders = 0;
148
        if(pp.isSprinting() && jump) {
149
            handleAdders += 0.2;
150
        }
151
        if(swimming && !flying) { //This is actually a terrible way of handling horizontal water flow.
152
            Vector move = new Vector(event.getTo().getX() - event.getFrom().getX(), 0, event.getTo().getZ() - event.getFrom().getZ());
153
            Vector waterForce = event.getWaterFlowForce().clone().setY(0);
154
            double waterForceLength = waterForce.length() + 0.003; //add epsilon to allow room for error
155
            double moveLength = move.length();
156
            double computedForce = moveLength == 0 ? waterForceLength : (move.dot(waterForce) / moveLength);
157
158
            handleAdders += computedForce;
159
        }
160
161
        //Finally, the expected speed calculation. There's another "expected" because of a dumb quirk when switching slots while using an item.
162
        //Optimize later.
163
        double expected = friction * lastSpeedCompare * handleMultipliers + (maxForce + handleAdders + EPSILON);
164
        double expectedNoItemUse = friction * lastSpeedCompare * handleMultipliers + (maxForceNoItemUse + handleAdders + EPSILON);
165
166
        //I hate this game. Handle slot switching quirk. The slot switch packet is delayed by a tick.
167
        //This sort of "event listening" must be done because Hawk's MoveEvents can be skipped under certain conditions.
168
        long slotSwitchTick = pp.getLastSlotSwitchTick();
169
        boolean switchedSlot = slotSwitchTick != lastSlotSwitchTickMap.getOrDefault(p.getUniqueId(), slotSwitchTick);
170
        int slotSwitchQuirkTicks = slotSwitchQuirkTicksMap.getOrDefault(p.getUniqueId(), 0);
171
        if(switchedSlot) {
172
            slotSwitchQuirkTicks = 0;
173
        }
174
        lastSlotSwitchTickMap.put(p.getUniqueId(), slotSwitchTick);
175
176
        //Calculate discrepancy.
177
        Discrepancy discrepancy; //This is the one that will be used for final comparison. It is the value of either discrepancyBase or discrepancyNoItemUse.
178
        Discrepancy discrepancyBase; //Used for pretty much 99.99% of moves.
179
        Discrepancy discrepancyNoItemUse; //Similar to discrepancyBase, but doesn't consider item-use slowdown.
180
181
        discrepancyBase = new Discrepancy(expected, speed);
182
        discrepancyNoItemUse = new Discrepancy(expectedNoItemUse, speed);
183
        if((pp.isBlocking() || pp.isConsumingItem() || pp.isPullingBow()) && Math.abs(discrepancyNoItemUse.value) < Math.abs(discrepancyBase.value)) {
184
            //This means that they're using an item, but they're moving at normal speed. This COULD be due to that
185
            //dumb item switch quirk, so we'll grant them only one extra tick. It resets when they switch their slot.
186
            if(slotSwitchQuirkTicks < 1) {
187
                //Allow them to move at normal speed for 1 tick.
188
                discrepancy = discrepancyNoItemUse;
189
                slotSwitchQuirkTicks++;
190
            } else {
191
                discrepancy = discrepancyBase;
192
            }
193
        } else {
194
            discrepancy = discrepancyBase;
195
        }
196
197
        //Client told server that it updated its position. Checking time.
198
        if (event.isUpdatePos()) {
199
            double haltDistanceExpected = negativeDiscrepanciesCumulative.getOrDefault(p.getUniqueId(), 0D);
200
            lastNegativeDiscrepancies.put(p.getUniqueId(), 0D);
201
            if(discrepancy.value < 0 || speed > haltDistanceExpected)
202
                discrepancies.put(p.getUniqueId(), Math.max(discrepancies.getOrDefault(p.getUniqueId(), 0D) + discrepancy.value, 0));
203
            double totalDiscrepancy = discrepancies.getOrDefault(p.getUniqueId(), 0D);
204
205
            if(DEBUG) {
206
                p.sendMessage((totalDiscrepancy > DISCREPANCY_THRESHOLD ? ChatColor.RED : ChatColor.GREEN) + "" + totalDiscrepancy);
207
            }
208
209
            if(discrepancy.value > 0 && totalDiscrepancy > DISCREPANCY_THRESHOLD && !event.isPossiblePistonPush()) {
210
                punishAndTryRubberband(pp, discrepancy.value * VL_FAIL_DISCREPANCY_FACTOR, event);
211
                if(RESET_DISCREPANCY_ON_FAIL)
212
                    discrepancies.put(p.getUniqueId(), 0D);
213
                if(RELEASE_ITEM_OVER_VL > -1 && (pp.isPullingBow() || pp.isConsumingItem() || pp.isBlocking()) && pp.getVL(this) > RELEASE_ITEM_OVER_VL)
214
                    pp.releaseItem();
215
            }
216
            else {
217
                reward(pp);
218
            }
219
220
            lastNegativeDiscrepancies.put(p.getUniqueId(), 0D);
221
            negativeDiscrepanciesCumulative.put(p.getUniqueId(), 0D);
222
        }
223
        //Client sent a flying packet, but didn't update position.
224
        //The move might have not been significant enough, so we need
225
        //to prepare for when the client decides it's time to update
226
        //position.
227
        else {
228
            lastNegativeDiscrepancies.put(p.getUniqueId(), discrepancy.value);
229
230
            //TODO improve these two lines...
231
            double val = negativeDiscrepanciesCumulative.getOrDefault(p.getUniqueId(), 0D);
232
            negativeDiscrepanciesCumulative.put(p.getUniqueId(), Math.min(val + speed, MAX_NO_MOVE_DISTANCE + speed));
233
            //negativeDiscrepanciesCumulative.put(p.getUniqueId(), negativeDiscrepanciesCumulative.getOrDefault(p.getUniqueId(), 0D) + speed);
234
        }
235
236
        slotSwitchQuirkTicksMap.put(p.getUniqueId(), slotSwitchQuirkTicks);
237
        prepareNextMove(pp, noMoves, speed, touchedBlocks);
238
    }
239
240
    private void prepareNextMove(HawkPlayer pp, int noMoves, double currentSpeed, Set<Material> touchedBlocks) {
241
        if(touchedBlocks.contains(Material.WEB) && !pp.isFlying()) {
242
            currentSpeed = 0;
243
        }
244
        UUID uuid = pp.getUuid();
245
        prevSpeed.put(uuid, currentSpeed);
246
        noMovesMap.put(uuid, noMoves);
247
    }
248
249
    public void removeData(Player p) {
250
        UUID uuid = p.getUniqueId();
251
        prevSpeed.remove(uuid);
252
        discrepancies.remove(uuid);
253
        noMovesMap.remove(uuid);
254
        lastNegativeDiscrepancies.remove(uuid);
255
        negativeDiscrepanciesCumulative.remove(uuid);
256
        slotSwitchQuirkTicksMap.remove(uuid);
257
        lastSlotSwitchTickMap.remove(uuid);
258
    }
259
260
    //speed potions do not affect swimming
261
    private Discrepancy waterMapping(double lastSpeed, double currentSpeed, double waterFlowForce) {
262
        double expected = 0.800001 * lastSpeed + 0.020001 + waterFlowForce;
263
        return new Discrepancy(expected, currentSpeed);
264
    }
265
266
    private Discrepancy lavaMapping(double lastSpeed, double currentSpeed) {
267
        double expected = 0.500001 * lastSpeed + 0.020001;
268
        return new Discrepancy(expected, currentSpeed);
269
    }
270
271
    private class Discrepancy {
272
273
        double value;
274
275
        Discrepancy(double expectedSpeed, double currentSpeed) {
276
            value = currentSpeed - expectedSpeed;
277
        }
278
279
    }
280
}

How it counteracts this module

Hawk's Speed treats movement as momentum conservation: expected = friction * lastSpeed * handleMultipliers + (maxForce + handleAdders + EPSILON), where friction is the block slipperiness (0.6 on ground, 0.91 in air), maxForce is the maximum input acceleration the move could receive, and sprint-jumping adds a 0.2 adder. The difference between the current speed and expected is a Discrepancy that accumulates across moves, and when the total passes DISCREPANCY_THRESHOLD (0.1) the check punishes with VL = discrepancy * 10 and rubber-bands the player to the server position. Rise's Custom pin works against this model because the expected value is built from the previous move: with ground friction 0.6 and a pinned lastSpeed of 0.35, expected lands near 0.31, so each hop tick contributes a discrepancy of a few hundredths and the accumulator crosses 0.1 within a few hops; at the default 0.35 it takes a handful of hops, and at any higher setting or in the multiplier modes it is immediate. The jump and step exemptions only forgive the vanilla sprint-jump adder, not a magnitude pinned above the friction-reconciled value.

← Back to Analysis Hub