LiquidSense Dev Aura module 2 files, 1359 lines

LiquidSense Dev Aura: Full Source Analysis

LiquidSense's Aura is a full-featured kill aura driven by the client event bus.

net/ccbluex/liquidbounce/features/module/modules/combat/Aura.kt · GitHub source ↗

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

Analysis

Overview

LiquidSense's Aura is a full-featured kill aura driven by the client event bus. Target selection runs from the pre-motion update, scoring every loaded entity by a configurable priority (Health, Distance, Direction, LivingTime) under FOV, hurt-time, range and team filters, then committing the first candidate whose rotations can be computed. The attack clock lives on Render3D, so clicks queue at the frame rate and are drained on the next update event, with the delay randomized between MinCPS and MaxCPS each cycle. Attacks leave as C02PacketUseEntity ATTACK behind an optional raycast hitable gate, and a six-mode autoblock subsystem (Vanilla, Pos, Both, Click, AAC, Interact) surrounds them with C08 block placements, keybind holds and C02 interacts. Silent rotations are the default, computed against the server rotation in RotationUtils and clamped by a randomized turn speed, with velocity prediction on the target bounding box and three rotation backends (Vanilla, BackTrack, Other).

Event-driven architecture

The module is split across five event handlers plus one packet interceptor. onMotion POST refreshes the hitable flag and starts blocking when the delayed-block switch is on, while the PRE phase calls update() which re-selects the target and binds currentTarget. onRender3D is the attack clock: when attackTimer has passed attackDelay and the target's hurtTime is at or below the HurtTime setting it increments the clicks counter and resets the timer with a fresh randomClickDelay between MinCPS and MaxCPS. onUpdate drains those clicks through runAttack() in a while loop, so the actual packet emission is decoupled from the render clock that schedules it. onStrafe rewrites strafe and forward inputs against the target rotation for the OldStrict, NewStrict and Silent strafe modes, and onEntityMove re-runs updateHitable whenever the tracked target changes its bounding box. onPacket intercepts C07PacketPlayerDigging only for the AAC autoblock mode, cancelling and re-queuing alternating release packets. A cancelRun guard (spectator, dead, Blink or FreeCam active) plus the NoInvAttack window freeze the whole pipeline, and the AAC mode also gates on the inventory screen state.

Target selection and rotation backends

updateTarget scans mc.theWorld.loadedEntityList and applies isEnemy, which composes the global EntityUtils filters with LiquidSense's own AntiBot, NoHurt, Teams and NoFriends checks, then keeps entities whose box distance is within maxRange (the larger of Range and BlockRange), whose rotation difference is within FOV, and whose hurtTime is at or below the threshold. The survivors are sorted by the Priority setting and each candidate is passed to updateRotations, which must succeed for the entity to become the target; when every candidate fails, prevTargetEntities is cleared and the scan retries. The Vanilla backend calls RotationUtils.searchCenter on the entity bounding box, optionally offset by the entity velocity times a random factor in [MinPredictSize, MaxPredictSize] when Predict is on, with random-center and outborder sampling; BackTrack uses RotationUtils.OtherRotation the same way; Other uses OtherRotationUtils.searchCenter and latches a Rotationhit boolean when the limited rotation lands within 5 degrees. Every backend funnels through limitAngleChange against serverRotation with a random per-tick cap between MinTurnSpeed and MaxTurnSpeed, and the result is applied either silently through setTargetRotation (with a 15ms lag when the AAC switch is on) or visibly by writing the angles into the player.

Attack execution and autoblock modes

runAttack checks the hitable flag, which is set by a RaycastUtils.raycastEntity sweep at reach = min(maxRange, box distance) + 1.4 when RayCast is on or by RotationUtils.isFaced otherwise, and randomly skips the hit when FailRate rolls, emitting only a swing when FakeSwing is enabled. A real hit sends swingItem plus C02PacketUseEntity ATTACK; the KeepSprint path plays the critical and enchantment particles locally, while the vanilla path calls attackTargetEntityWithCurrentItem. Multi mode iterates every enemy within range and attacks them in one pass, stopping at LimitedMultiTargets when set. The autoblock modes differ only in how the block state is asserted: Vanilla sends C08 with the held item, Pos sends C08 against BlockPos(-1,-1,-1) with facing 255, Both sends two C08 packets, Click holds the use-item key binding, and AAC toggles the binding and relies on the C07 cancellation flip. InteractAutoBlock additionally sends a C02 INTERACT with the entity position vector before blocking. The AAC mode also closes and re-opens the inventory around each attack (C0D close, C16 open) to mask the cooldown reset, and FakeSharp forces the enchantment critical effect even without a sharpness enchant.

source Aura.kt (module logic)

Aura.kt905 lines · JavaOriginal ↗
1
package net.ccbluex.liquidbounce.features.module.modules.combat
2
3
import me.AquaVit.liquidSense.modules.misc.NoHurt
4
import net.ccbluex.liquidbounce.LiquidBounce
5
import net.ccbluex.liquidbounce.event.*
6
import net.ccbluex.liquidbounce.features.module.Module
7
import net.ccbluex.liquidbounce.features.module.ModuleCategory
8
import net.ccbluex.liquidbounce.features.module.ModuleInfo
9
import net.ccbluex.liquidbounce.features.module.modules.misc.AntiBot
10
import net.ccbluex.liquidbounce.features.module.modules.misc.Teams
11
import net.ccbluex.liquidbounce.features.module.modules.player.Blink
12
import net.ccbluex.liquidbounce.features.module.modules.render.FreeCam
13
import net.ccbluex.liquidbounce.utils.EntityUtils
14
import net.ccbluex.liquidbounce.utils.OtherRotationUtils
15
import net.ccbluex.liquidbounce.utils.RaycastUtils
16
import net.ccbluex.liquidbounce.utils.RotationUtils
17
import net.ccbluex.liquidbounce.utils.extensions.getDistanceToEntityBox
18
import net.ccbluex.liquidbounce.utils.misc.RandomUtils
19
import net.ccbluex.liquidbounce.utils.render.RenderUtils
20
import net.ccbluex.liquidbounce.utils.timer.MSTimer
21
import net.ccbluex.liquidbounce.utils.timer.TimeUtils
22
import net.ccbluex.liquidbounce.value.BoolValue
23
import net.ccbluex.liquidbounce.value.FloatValue
24
import net.ccbluex.liquidbounce.value.IntegerValue
25
import net.ccbluex.liquidbounce.value.ListValue
26
import net.minecraft.client.Minecraft
27
import net.minecraft.client.gui.inventory.GuiContainer
28
import net.minecraft.client.gui.inventory.GuiInventory
29
import net.minecraft.client.settings.KeyBinding
30
import net.minecraft.enchantment.EnchantmentHelper
31
import net.minecraft.entity.Entity
32
import net.minecraft.entity.EntityLivingBase
33
import net.minecraft.entity.item.EntityArmorStand
34
import net.minecraft.entity.player.EntityPlayer
35
import net.minecraft.item.ItemSword
36
import net.minecraft.network.play.client.*
37
import net.minecraft.potion.Potion
38
import net.minecraft.util.BlockPos
39
import net.minecraft.util.EnumFacing
40
import net.minecraft.util.MathHelper
41
import net.minecraft.world.WorldSettings
42
import org.lwjgl.input.Keyboard
43
import java.awt.Color
44
import java.util.*
45
import kotlin.math.max
46
import kotlin.math.min
47
48
@ModuleInfo(name = "Aura", description = "Automatically attacks targets around you.",
49
        category = ModuleCategory.COMBAT, keyBind = Keyboard.KEY_R)
50
class Aura : Module() {
51
52
    /**
53
     * OPTIONS
54
     */
55
56
    // CPS - Attack speed
57
    private val maxCPS: IntegerValue = object : IntegerValue("MaxCPS", 8, 1, 20) {
58
        override fun onChanged(oldValue: Int, newValue: Int) {
59
            val i = minCPS.get()
60
            if (i > newValue) set(i)
61
62
            attackDelay = TimeUtils.randomClickDelay(minCPS.get(), this.get())
63
        }
64
    }
65
66
    private val minCPS: IntegerValue = object : IntegerValue("MinCPS", 5, 1, 20) {
67
        override fun onChanged(oldValue: Int, newValue: Int) {
68
            val i = maxCPS.get()
69
            if (i < newValue) set(i)
70
71
            attackDelay = TimeUtils.randomClickDelay(this.get(), maxCPS.get())
72
        }
73
    }
74
75
    private val hurtTimeValue = IntegerValue("HurtTime", 10, 0, 10)
76
77
    // Range
78
    private val rangeValue = FloatValue("Range", 3.7f, 1f, 8f)
79
    private var BlockRangeValue = FloatValue("BlockRange", 3f, 0f, 8f)
80
    private val throughwallValue = FloatValue("ThroughWallRange", 2f, 0f, 8f)
81
    private val rangeSprintReducementValue = FloatValue("RangeSprintReducement", 0f, 0f, 0.4f)
82
83
    // Modes
84
    private val priorityValue = ListValue("Priority", arrayOf("Health", "Distance", "Direction", "LivingTime"), "Distance")
85
    private val targetModeValue = ListValue("TargetMode", arrayOf("Single", "Switch", "Multi"), "Switch")
86
    private val rotations = ListValue("RotationMode", arrayOf("Vanilla", "Other", "BackTrack"), "BackTrack")
87
    private val AutoBlockValue =
88
            object : ListValue("AutoBlockMode",
89
                    arrayOf("Off", "Vanilla", "Both", "Pos", "Click", "AAC"), "Vanilla") {
90
                override fun changeElement() {
91
                    BlockRangeValue.isSupported = (get() == "Off").also {
92
                        delayedBlockValue.isSupported = it;blockRate.isSupported = it;interactAutoBlockValue.isSupported = it
93
                    }
94
                }
95
96
            }
97
    // Bypass
98
    private val swingValue = BoolValue("Swing", true)
99
    private val keepSprintValue = BoolValue("KeepSprint", true)
100
101
    // AutoBlock
102
    private var interactAutoBlockValue = BoolValue("InteractAutoBlock", true)
103
    private var delayedBlockValue = BoolValue("DelayedBlock", true)
104
    private var blockRate = IntegerValue("BlockRate", 100, 1, 100)
105
106
    // Raycast
107
    private val raycastValue =
108
            object : BoolValue("RayCast", true){
109
110
    }
111
    private val raycastIgnoredValue = BoolValue("RayCastIgnored", false)
112
    private val livingRaycastValue = BoolValue("LivingRayCast", true)
113
114
    // Bypass
115
    private val aacValue = BoolValue("AAC", false)
116
    //switchdelay
117
    private val switchdelayValue = IntegerValue("SwitchDelay", 10, 0, 100)
118
    // Turn Speed
119
    private val maxTurnSpeed: FloatValue = object : FloatValue("MaxTurnSpeed", 180f, 0f, 180f) {
120
        override fun onChanged(oldValue: Float, newValue: Float) {
121
            val v = minTurnSpeed.get()
122
            if (v > newValue) set(v)
123
        }
124
    }
125
126
    private val minTurnSpeed: FloatValue = object : FloatValue("MinTurnSpeed", 180f, 0f, 180f) {
127
        override fun onChanged(oldValue: Float, newValue: Float) {
128
            val v = maxTurnSpeed.get()
129
            if (v < newValue) set(v)
130
        }
131
    }
132
133
    private val silentRotationValue = BoolValue("SilentRotation", true)
134
    private val rotationStrafeValue = ListValue("Strafe", arrayOf("Off", "OldStrict","NewStrict", "Silent"), "Off")
135
    private val randomCenterValue = BoolValue("RandomCenter", true)
136
    private val outborderValue = BoolValue("Outborder", false)
137
    private val fovValue = FloatValue("FOV", 180f, 0f, 180f)
138
139
    // Predict
140
    private val predictValue = BoolValue("Predict", true)
141
142
    private val maxPredictSize: FloatValue = object : FloatValue("MaxPredictSize", 1f, 0.1f, 5f) {
143
        override fun onChanged(oldValue: Float, newValue: Float) {
144
            val v = minPredictSize.get()
145
            if (v > newValue) set(v)
146
        }
147
    }
148
149
    private val minPredictSize: FloatValue = object : FloatValue("MinPredictSize", 1f, 0.1f, 5f) {
150
        override fun onChanged(oldValue: Float, newValue: Float) {
151
            val v = maxPredictSize.get()
152
            if (v < newValue) set(v)
153
        }
154
    }
155
156
    // Bypass
157
    private val failRateValue = FloatValue("FailRate", 0f, 0f, 100f)
158
    private val fakeSwingValue = BoolValue("FakeSwing", true)
159
    private val noInventoryAttackValue = BoolValue("NoInvAttack", false)
160
    private val noInventoryDelayValue = IntegerValue("NoInvDelay", 200, 0, 500)
161
    private val limitedMultiTargetsValue = IntegerValue("LimitedMultiTargets", 0, 0, 50)
162
163
    private val fakeSharpValue = BoolValue("FakeSharp", true)
164
165
    /**
166
     * MODULE
167
     */
168
169
    // Target
170
    var target: EntityLivingBase? = null
171
    private var currentTarget: EntityLivingBase? = null
172
    private var hitable = false
173
    private val prevTargetEntities = mutableListOf<Int>()
174
175
    // Attack delay
176
    private val attackTimer = MSTimer()
177
    private var attackDelay = 0L
178
    private var clicks = 0
179
    private var flag = false
180
181
182
    var Rotationhit = false;
183
    val Timer = MSTimer()
184
    // Container Delay
185
    private var containerOpen = -1L
186
187
    // Fake block status
188
    var blockingStatus = false
189
190
    /**
191
     * Enable kill aura module
192
     */
193
    override fun onEnable() {
194
        mc.thePlayer ?: return
195
        mc.theWorld ?: return
196
197
        updateTarget()
198
    }
199
200
    /**
201
     * Disable kill aura module
202
     */
203
    override fun onDisable() {
204
        target = null
205
        currentTarget = null
206
        hitable = false
207
        prevTargetEntities.clear()
208
        attackTimer.reset()
209
        clicks = 0
210
211
        stopBlocking()
212
    }
213
214
    /**
215
     * Motion event
216
     */
217
    @EventTarget
218
    fun onMotion(event: MotionEvent) {
219
        if (event.eventState == EventState.POST) {
220
            target ?: return
221
            currentTarget ?: return
222
223
            // Update hitable
224
            updateHitable()
225
226
            // AutoBlock
227
            if (!AutoBlockValue.get().equals("Off", ignoreCase = true) && delayedBlockValue.get() && canBlock)
228
                startBlocking(currentTarget!!, hitable)
229
230
            return
231
        }
232
233
        if (rotationStrafeValue.get().equals("Off", true))
234
            update()
235
    }
236
237
    /**
238
     * Strafe event
239
     */
240
    @EventTarget
241
    fun onStrafe(event: StrafeEvent) {
242
        if (rotationStrafeValue.get().equals("Off", true))
243
            return
244
245
        update()
246
247
        if (!silentRotationValue.get())
248
            return
249
250
        when (rotationStrafeValue.get().toLowerCase()) {
251
            "newstrict" -> {
252
                currentTarget ?: return
253
254
                val (yaw) = RotationUtils.targetRotation ?: return
255
                var strafe = event.strafe
256
                var forward = event.forward
257
                val friction = event.friction
258
259
                var f = strafe * strafe + forward * forward
260
261
                if (f >= 1.0E-4F) {
262
                    f = MathHelper.sqrt_float(f)
263
264
                    if (f < 1.0F)
265
                        f = 1.0F
266
267
                    f = friction / f
268
                    strafe *= f
269
                    forward *= f
270
271
                    val yawSin = MathHelper.sin((yaw * Math.PI / 180F).toFloat())
272
                    val yawCos = MathHelper.cos((yaw * Math.PI / 180F).toFloat())
273
274
                    mc.thePlayer.motionX += strafe * yawCos - forward * yawSin
275
                    mc.thePlayer.motionZ += forward * yawCos + strafe * yawSin
276
                }
277
                event.cancelEvent()
278
            }
279
            "oldstrict" -> {
280
                currentTarget ?: return
281
282
                val (yaw) = RotationUtils.targetRotation ?: return
283
                var strafe = event.strafe
284
                var forward = event.forward
285
                val friction = event.friction
286
287
                var f = strafe * strafe + forward * forward
288
289
                if (f >= 1.0E-4F) {
290
                    f = MathHelper.sqrt_float(f)
291
292
                    if (f < 1.0F)
293
                        f = 1.0F
294
295
                    f = friction / f
296
                    strafe *= f
297
                    forward *= f
298
299
                    val yawSin = MathHelper.sin((yaw * Math.PI / 180F).toFloat())
300
                    val yawCos = MathHelper.cos((yaw * Math.PI / 180F).toFloat())
301
302
                    mc.thePlayer.motionX += strafe * yawCos - forward * yawSin
303
                    mc.thePlayer.motionZ += forward * yawCos + strafe * yawSin
304
                }
305
306
                event.cancelEvent()
307
            }
308
            "silent" -> {
309
                currentTarget ?: return
310
311
                update()
312
313
                RotationUtils.targetRotation.applyStrafeToPlayer(event)
314
                event.cancelEvent()
315
            }
316
        }
317
    }
318
319
    fun update() {
320
        if (cancelRun || (noInventoryAttackValue.get() && (mc.currentScreen is GuiContainer ||
321
                        System.currentTimeMillis() - containerOpen < noInventoryDelayValue.get())))
322
            return
323
324
        // Update target
325
        updateTarget()
326
327
        if (target == null) {
328
            stopBlocking()
329
            return
330
        }
331
332
        // Target
333
        currentTarget = target
334
335
        if (!targetModeValue.get().equals("Switch", ignoreCase = true) && isEnemy(currentTarget))
336
            target = currentTarget
337
    }
338
339
    /**
340
     * Update event
341
     */
342
    @EventTarget
343
    fun onUpdate(event: UpdateEvent) {
344
        if(AutoBlockValue.get().equals("AAC", ignoreCase = true) && mc.thePlayer.heldItem.item is ItemSword) return
345
        if (cancelRun) {
346
            target = null
347
            currentTarget = null
348
            hitable = false
349
            stopBlocking()
350
            return
351
        }
352
353
        if (noInventoryAttackValue.get() && (mc.currentScreen is GuiContainer ||
354
                        System.currentTimeMillis() - containerOpen < noInventoryDelayValue.get())) {
355
            target = null
356
            currentTarget = null
357
            hitable = false
358
            if (mc.currentScreen is GuiContainer) containerOpen = System.currentTimeMillis()
359
            return
360
        }
361
362
        if (target != null && currentTarget != null) {
363
            while (clicks > 0) {
364
                runAttack()
365
                clicks--
366
            }
367
        }
368
    }
369
370
    /**
371
     * Render event
372
     */
373
    @EventTarget
374
    fun onRender3D(event: Render3DEvent) {
375
        if (cancelRun) {
376
            target = null
377
            currentTarget = null
378
            hitable = false
379
            stopBlocking()
380
            return
381
        }
382
383
        if (noInventoryAttackValue.get() && (mc.currentScreen is GuiContainer ||
384
                        System.currentTimeMillis() - containerOpen < noInventoryDelayValue.get())) {
385
            target = null
386
            currentTarget = null
387
            hitable = false
388
            if (mc.currentScreen is GuiContainer) containerOpen = System.currentTimeMillis()
389
            return
390
        }
391
392
        target ?: return
393
394
        if (currentTarget != null && attackTimer.hasTimePassed(attackDelay) &&
395
                currentTarget!!.hurtTime <= hurtTimeValue.get()) {
396
            clicks++
397
            attackTimer.reset()
398
            attackDelay = TimeUtils.randomClickDelay(minCPS.get(), maxCPS.get())
399
        }
400
    }
401
402
    /**
403
     * Handle entity move
404
     */
405
    @EventTarget
406
    fun onEntityMove(event: EntityMovementEvent) {
407
        val movedEntity = event.movedEntity
408
409
        if (target == null || movedEntity != currentTarget)
410
            return
411
412
        updateHitable()
413
    }
414
415
    /**
416
     * Attack enemy
417
     */
418
    private fun runAttack() {
419
        target ?: return
420
        currentTarget ?: return
421
422
        // Settings
423
        val failRate = failRateValue.get()
424
        val swing = swingValue.get()
425
        val multi = targetModeValue.get().equals("Multi", ignoreCase = true)
426
        val switchmode = targetModeValue.get().equals("Switch", ignoreCase = true)
427
        val openInventory = aacValue.get() && mc.currentScreen is GuiInventory
428
        val failHit = failRate > 0 && Random().nextInt(100) <= failRate
429
430
        // Close inventory when open
431
        if (openInventory)
432
            mc.netHandler.addToSendQueue(C0DPacketCloseWindow())
433
434
        // Check is not hitable or check failrate
435
        if (!hitable || failHit) {
436
            if (swing && (fakeSwingValue.get() || failHit)) mc.thePlayer.swingItem()
437
        } else {
438
            // Attack
439
            if (!multi) {
440
                attackEntity(currentTarget!!)
441
            } else {
442
                var targets = 0
443
444
                for (entity in mc.theWorld.loadedEntityList) {
445
                    val distance = mc.thePlayer.getDistanceToEntityBox(entity)
446
447
                    if (entity is EntityLivingBase && isEnemy(entity) && distance <= getRange(entity)) {
448
                        attackEntity(entity)
449
450
                        targets += 1
451
452
                        if (limitedMultiTargetsValue.get() != 0 && limitedMultiTargetsValue.get() <= targets)
453
                            break
454
                    }
455
                }
456
            }
457
            if (switchmode) {
458
                if(Timer.hasTimePassed((switchdelayValue.get() * 10).toLong()) && (this.switchdelayValue.get()) != 10){
459
                    prevTargetEntities.add(if (aacValue.get()) target!!.entityId else currentTarget!!.entityId)
460
                }
461
                /*if (target == currentTarget)
462
                    target = null*/
463
            } else {
464
                prevTargetEntities.add(if (aacValue.get()) target!!.entityId else currentTarget!!.entityId)
465
            }
466
            Timer.reset()
467
468
469
        }
470
471
        // Open inventory
472
        if (openInventory)
473
            mc.netHandler.addToSendQueue(C16PacketClientStatus(C16PacketClientStatus.EnumState.OPEN_INVENTORY_ACHIEVEMENT))
474
    }
475
476
    /**
477
     * Update current target
478
     */
479
    private fun updateTarget() {
480
        // Reset fixed target to null
481
        target = null
482
483
        // Settings
484
        val hurtTime = hurtTimeValue.get()
485
        val fov = fovValue.get()
486
        val switchMode = targetModeValue.get().equals("Switch", ignoreCase = true)
487
488
        // Find possible targets
489
        val targets = mutableListOf<EntityLivingBase>()
490
491
        for (entity in mc.theWorld.loadedEntityList) {
492
            if (entity !is EntityLivingBase || !isEnemy(entity) || (switchMode && prevTargetEntities.contains(entity.entityId)))
493
                continue
494
495
            val distance = mc.thePlayer.getDistanceToEntityBox(entity)
496
            val entityFov = RotationUtils.getRotationDifference(entity)
497
498
            if (distance <= maxRange && (fov == 180F || entityFov <= fov) && entity.hurtTime <= hurtTime)
499
                targets.add(entity)
500
        }
501
502
        // Sort targets by priority
503
        when (priorityValue.get().toLowerCase()) {
504
            "distance" -> targets.sortBy { mc.thePlayer.getDistanceToEntityBox(it) } // Sort by distance
505
            "health" -> targets.sortBy { it.health } // Sort by health
506
            "direction" -> targets.sortBy { RotationUtils.getRotationDifference(it) } // Sort by FOV
507
            "livingtime" -> targets.sortBy { -it.ticksExisted } // Sort by existence
508
        }
509
510
        // Find best target
511
        for (entity in targets) {
512
            // Update rotations to current target
513
            if (!updateRotations(entity)) // when failed then try another target
514
                continue
515
516
            // Set target to current entity
517
            target = entity
518
            return
519
        }
520
521
        // Cleanup last targets when no target found and try again
522
        if (prevTargetEntities.isNotEmpty()) {
523
            prevTargetEntities.clear()
524
            updateTarget()
525
        }
526
    }
527
528
    /**
529
     * Check if [entity] is selected as enemy with current target options and other modules
530
     */
531
    private fun isEnemy(entity: Entity?): Boolean {
532
        if (entity is EntityLivingBase && (EntityUtils.targetDead || isAlive(entity)) && entity != mc.thePlayer) {
533
            if (!EntityUtils.targetInvisible && entity.isInvisible())
534
                return false
535
536
            if (EntityUtils.targetPlayer && entity is EntityPlayer) {
537
                if (entity.isSpectator || AntiBot.isBot(entity) || NoHurt.isBot(entity))
538
                    return false
539
540
                if (EntityUtils.isFriend(entity) && !LiquidBounce.moduleManager[NoFriends::class.java]!!.state)
541
                    return false
542
543
                val teams = LiquidBounce.moduleManager[Teams::class.java] as Teams
544
545
                return !teams.state || !teams.isInYourTeam(entity)
546
            }
547
548
            return EntityUtils.targetMobs && EntityUtils.isMob(entity) || EntityUtils.targetAnimals &&
549
                    EntityUtils.isAnimal(entity)
550
        }
551
552
        return false
553
    }
554
555
    /**
556
     * Attack [entity]
557
     */
558
    private fun attackEntity(entity: EntityLivingBase) {
559
        if (rotations.get().equals("Other", ignoreCase = true)){
560
            // Stop blocking
561
562
            val distance = Minecraft.getMinecraft().thePlayer.getDistanceToEntity(entity)
563
            if (distance <= rangeValue.get() && Rotationhit && hitable) {
564
                //
565
                if (mc.thePlayer.isBlocking|| blockingStatus) {
566
                    if (AutoBlockValue.get().equals("Click", ignoreCase = true)) {
567
                        KeyBinding.setKeyBindState(mc.gameSettings.keyBindUseItem.getKeyCode(), false)
568
                    } else if (AutoBlockValue.get().equals("AAC", ignoreCase = true) && mc.thePlayer.heldItem.item is ItemSword) {
569
                        mc.gameSettings.keyBindUseItem.pressed = false
570
                    } else {
571
                        mc.netHandler.addToSendQueue(C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN))
572
                    }
573
                    blockingStatus = false
574
                }
575
                // Call attack event
576
                LiquidBounce.eventManager.callEvent(AttackEvent(entity))
577
                // Attack target
578
                if (swingValue.get())
579
                    mc.thePlayer.swingItem()
580
                mc.netHandler.addToSendQueue(C02PacketUseEntity(entity, C02PacketUseEntity.Action.ATTACK))
581
582
                // Extra critical effects
583
                if (EnchantmentHelper.getModifierForCreature(mc.thePlayer.heldItem, target!!.creatureAttribute) > 0.0f || fakeSharpValue.get())
584
                    mc.thePlayer.onEnchantmentCritical(target)
585
                if (mc.thePlayer.isBlocking || (!AutoBlockValue.get().equals("Off", ignoreCase = true) && canBlock)) {
586
                    if (!(blockRate.get() > 0 && Random().nextInt(100) <= blockRate.get()))
587
                        return
588
589
                    if (delayedBlockValue.get())
590
                        return
591
                    startBlocking(entity, interactAutoBlockValue.get())
592
                }
593
            }
594
        } else {
595
            // Stop blocking
596
            if (mc.thePlayer.isBlocking || blockingStatus) {
597
                if (AutoBlockValue.get().equals("Click", ignoreCase = true)) {
598
                    KeyBinding.setKeyBindState(mc.gameSettings.keyBindUseItem.getKeyCode(), false)
599
                } else if (AutoBlockValue.get().equals("AAC", ignoreCase = true) && mc.thePlayer.heldItem.item is ItemSword) {
600
                    mc.gameSettings.keyBindUseItem.pressed = false
601
                } else {
602
                    mc.netHandler.addToSendQueue(C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN))
603
                }
604
605
                blockingStatus = false
606
            }
607
            val distance = mc.thePlayer.getDistanceToEntityBox(entity)
608
609
            if (hitable && distance < rangeValue.get()) {
610
                // Call attack event
611
                LiquidBounce.eventManager.callEvent(AttackEvent(entity))
612
613
                // Attack target
614
                if (swingValue.get())
615
                    mc.thePlayer.swingItem()
616
                mc.netHandler.addToSendQueue(C02PacketUseEntity(entity, C02PacketUseEntity.Action.ATTACK))
617
618
                if (keepSprintValue.get()) {
619
                    // Critical Effect
620
                    if (mc.thePlayer.fallDistance > 0F && !mc.thePlayer.onGround && !mc.thePlayer.isOnLadder &&
621
                            !mc.thePlayer.isInWater && !mc.thePlayer.isPotionActive(Potion.blindness) && !mc.thePlayer.isRiding)
622
                        mc.thePlayer.onCriticalHit(entity)
623
624
                    // Enchant Effect
625
                    if (EnchantmentHelper.getModifierForCreature(mc.thePlayer.heldItem, entity.creatureAttribute) > 0F)
626
                        mc.thePlayer.onEnchantmentCritical(entity)
627
                } else {
628
                    if (mc.playerController.currentGameType != WorldSettings.GameType.SPECTATOR)
629
                        mc.thePlayer.attackTargetEntityWithCurrentItem(entity)
630
                }
631
632
                // Extra critical effects
633
                val criticals = LiquidBounce.moduleManager[Criticals::class.java] as Criticals
634
635
                for (i in 0..2) {
636
                    // Critical Effect
637
                    if (mc.thePlayer.fallDistance > 0F && !mc.thePlayer.onGround && !mc.thePlayer.isOnLadder && !mc.thePlayer.isInWater && !mc.thePlayer.isPotionActive(Potion.blindness) && mc.thePlayer.ridingEntity == null || criticals.state && criticals.msTimer.hasTimePassed(criticals.delayValue.get().toLong()) && !mc.thePlayer.isInWater && !mc.thePlayer.isInLava && !mc.thePlayer.isInWeb)
638
                        mc.thePlayer.onCriticalHit(target)
639
640
                    // Enchant Effect
641
                    if (EnchantmentHelper.getModifierForCreature(mc.thePlayer.heldItem, target!!.creatureAttribute) > 0.0f || fakeSharpValue.get())
642
                        mc.thePlayer.onEnchantmentCritical(target)
643
                }
644
            }
645
            // Start blocking after attack
646
            if (mc.thePlayer.isBlocking || (!AutoBlockValue.get().equals("Off", ignoreCase = true) && canBlock)) {
647
                if (!(blockRate.get() > 0 && Random().nextInt(100) <= blockRate.get()))
648
                    return
649
650
                if (delayedBlockValue.get())
651
                    return
652
653
                startBlocking(entity, interactAutoBlockValue.get())
654
            }
655
        }
656
    }
657
658
    /**
659
     * Update killaura rotations to enemy
660
     */
661
    private fun updateRotations(entity: Entity): Boolean {
662
        var boundingBox = entity.entityBoundingBox
663
664
        if (rotations.get().equals("Vanilla", ignoreCase = true)) {
665
            if (maxTurnSpeed.get() <= 0F)
666
                return true
667
668
            var boundingBox = entity.entityBoundingBox
669
670
            if (predictValue.get())
671
                boundingBox = boundingBox.offset(
672
                        (entity.posX - entity.prevPosX) * RandomUtils.nextFloat(minPredictSize.get(), maxPredictSize.get()),
673
                        (entity.posY - entity.prevPosY) * RandomUtils.nextFloat(minPredictSize.get(), maxPredictSize.get()),
674
                        (entity.posZ - entity.prevPosZ) * RandomUtils.nextFloat(minPredictSize.get(), maxPredictSize.get())
675
                )
676
677
            val (vec, rotation) = RotationUtils.searchCenter(
678
                    boundingBox,
679
                    outborderValue.get() && !attackTimer.hasTimePassed(attackDelay / 2),
680
                    randomCenterValue.get(),
681
                    predictValue.get(),
682
                    mc.thePlayer.getDistanceToEntityBox(entity) < throughwallValue.get(),
683
                    maxRange
684
            ) ?: return false
685
686
            val limitedRotation = RotationUtils.limitAngleChange(RotationUtils.serverRotation, rotation,
687
                    (Math.random() * (maxTurnSpeed.get() - minTurnSpeed.get()) + minTurnSpeed.get()).toFloat())
688
689
            val distance = mc.thePlayer.getDistanceToEntityBox(entity)
690
691
            if (distance < rangeValue.get()) {
692
                if (silentRotationValue.get())
693
                    RotationUtils.setTargetRotation(limitedRotation, if (aacValue.get()) 15 else 0)
694
                else
695
                    limitedRotation.toPlayer(mc.thePlayer)
696
            }
697
698
            return true
699
        }
700
701
        if (rotations.get().equals("BackTrack", ignoreCase = true)) {
702
            if (predictValue.get())
703
                boundingBox = boundingBox.offset(
704
                        (entity.posX - entity.prevPosX) * RandomUtils.nextFloat(minPredictSize.get(), maxPredictSize.get()),
705
                        (entity.posY - entity.prevPosY) * RandomUtils.nextFloat(minPredictSize.get(), maxPredictSize.get()),
706
                        (entity.posZ - entity.prevPosZ) * RandomUtils.nextFloat(minPredictSize.get(), maxPredictSize.get())
707
                )
708
709
            val limitedRotation = RotationUtils.limitAngleChange(RotationUtils.serverRotation,
710
                    RotationUtils.OtherRotation(boundingBox,RotationUtils.getCenter(entity.entityBoundingBox), predictValue.get(),
711
                            mc.thePlayer.getDistanceToEntityBox(entity) < throughwallValue.get(),maxRange), (Math.random() * (maxTurnSpeed.get() - minTurnSpeed.get()) + minTurnSpeed.get()).toFloat())
712
713
            if (silentRotationValue.get()) {
714
                RotationUtils.setTargetRotation(limitedRotation, if (aacValue.get()) 15 else 0)
715
            }else {
716
                limitedRotation.toPlayer(mc.thePlayer)
717
                return true
718
            }
719
        }
720
        if (rotations.get().equals("Other", ignoreCase = true)){
721
            val distance = mc.thePlayer.getDistanceToEntity(entity)
722
            val (vec, rotation) = OtherRotationUtils.searchCenter(
723
                    boundingBox,
724
                    outborderValue.get() && !attackTimer.hasTimePassed(attackDelay / 2),
725
                    randomCenterValue.get(),
726
                    predictValue.get(),
727
                    mc.thePlayer.getDistanceToEntityBox(entity) < throughwallValue.get(),
728
                    maxRange
729
            ) ?: return false
730
731
            val limitedRotation = RotationUtils.limitAngleChange(RotationUtils.serverRotation, rotation,
732
                    (Math.random() * (maxTurnSpeed.get() - minTurnSpeed.get()) + minTurnSpeed.get()).toFloat())
733
734
            if((limitedRotation.yaw  <= 5  || limitedRotation.pitch  <= 5)
735
                    || (limitedRotation.pitch  >= -5 || limitedRotation.pitch  >= -5))
736
                Rotationhit = true
737
            else
738
                Rotationhit = false
739
740
            if(distance <= rangeValue.get()) {
741
                if (silentRotationValue.get())
742
                    RotationUtils.setTargetRotation(limitedRotation, if (aacValue.get()) 15 else 0)
743
                else
744
                    limitedRotation.toPlayer(mc.thePlayer)
745
746
                return  true
747
            }
748
            return  Rotationhit
749
        }
750
751
        return true
752
753
    }
754
755
    /**
756
     * Check if enemy is hitable with current rotations
757
     */
758
    private fun updateHitable() {
759
        // Disable hitable check if turn speed is zero
760
        if (maxTurnSpeed.get() <= 0F) {
761
            hitable = true
762
            return
763
        }
764
765
        val reach = min(maxRange.toDouble(), mc.thePlayer.getDistanceToEntityBox(target!!)) + 1.4
766
767
        if (raycastValue.get()) {
768
            val raycastedEntity = RaycastUtils.raycastEntity(reach) {
769
                (!livingRaycastValue.get() || it is EntityLivingBase && it !is EntityArmorStand) &&
770
                        (isEnemy(it) || raycastIgnoredValue.get() || aacValue.get() && mc.theWorld.getEntitiesWithinAABBExcludingEntity(it, it.entityBoundingBox).isNotEmpty())
771
            }
772
773
            if (raycastValue.get() && raycastedEntity is EntityLivingBase
774
                    && (LiquidBounce.moduleManager[NoFriends::class.java]!!.state || !EntityUtils.isFriend(raycastedEntity)))
775
                currentTarget = raycastedEntity
776
777
            hitable = if (maxTurnSpeed.get() > 0F) currentTarget == raycastedEntity else true
778
        } else
779
            hitable = RotationUtils.isFaced(currentTarget, reach)
780
    }
781
782
    /**
783
     * Start blocking
784
     */
785
    private fun startBlocking(interactEntity: Entity, interact: Boolean) {
786
        if (interact) {
787
            mc.netHandler.addToSendQueue(C02PacketUseEntity(interactEntity, interactEntity.positionVector))
788
            mc.netHandler.addToSendQueue(C02PacketUseEntity(interactEntity, C02PacketUseEntity.Action.INTERACT))
789
        }
790
791
        if (AutoBlockValue.get().equals("AAC", ignoreCase = true) && mc.thePlayer.heldItem.item is ItemSword) {
792
            mc.gameSettings.keyBindUseItem.pressed = true
793
            blockingStatus = true
794
            return
795
        }
796
797
        if (AutoBlockValue.get().equals("Vanilla", ignoreCase = true)){
798
            mc.netHandler.addToSendQueue(C08PacketPlayerBlockPlacement(mc.thePlayer.inventory.getCurrentItem()))
799
            blockingStatus = true
800
        }
801
802
        if (AutoBlockValue.get().equals("Pos", ignoreCase = true)){
803
            mc.netHandler.addToSendQueue(C08PacketPlayerBlockPlacement(BlockPos(-1, -1, -1), 255, mc.thePlayer.inventory.getCurrentItem(), 0.0f, 0.0f, 0.0f))
804
            blockingStatus = true
805
        }
806
807
        if (AutoBlockValue.get().equals("Both", ignoreCase = true)){
808
            mc.netHandler.addToSendQueue(C08PacketPlayerBlockPlacement(mc.thePlayer.inventory.getCurrentItem()))
809
            mc.netHandler.addToSendQueue(C08PacketPlayerBlockPlacement(BlockPos.ORIGIN, 255, mc.thePlayer.getHeldItem(), 0.0F, 0.0F, 0.0F));
810
            blockingStatus = true
811
        }
812
        if (AutoBlockValue.get().equals("Click", ignoreCase = true)){
813
            KeyBinding.setKeyBindState(mc.gameSettings.keyBindUseItem.getKeyCode(), true)
814
            blockingStatus = true
815
        }
816
    }
817
818
    @EventTarget
819
    private fun onPacket(event: PacketEvent) {
820
        val packet = event.packet
821
822
        if (packet is C07PacketPlayerDigging && AutoBlockValue.get().equals("AAC", ignoreCase = true) && mc.thePlayer.heldItem.item is ItemSword) {
823
            flag = !flag
824
            if (flag) {
825
                event.cancelEvent()
826
                mc.netHandler.addToSendQueue(packet)
827
                if (cancelRun) {
828
                    target = null
829
                    currentTarget = null
830
                    hitable = false
831
                    stopBlocking()
832
                    return
833
                }
834
835
                if (noInventoryAttackValue.get() && (mc.currentScreen is GuiContainer ||
836
                                System.currentTimeMillis() - containerOpen < noInventoryDelayValue.get())) {
837
                    target = null
838
                    currentTarget = null
839
                    hitable = false
840
                    if (mc.currentScreen is GuiContainer) containerOpen = System.currentTimeMillis()
841
                    return
842
                }
843
844
                if (target != null && currentTarget != null) {
845
                    while (clicks > 0) {
846
                        runAttack()
847
                        clicks--
848
                    }
849
                }
850
            }
851
852
        }
853
    }
854
855
    /**
856
     * Stop blocking
857
     */
858
    private fun stopBlocking() {
859
        if (blockingStatus) {
860
            if (AutoBlockValue.get().equals("Click", ignoreCase = true)) {
861
                KeyBinding.setKeyBindState(mc.gameSettings.keyBindUseItem.getKeyCode(), false)
862
            } else if (AutoBlockValue.get().equals("AAC", ignoreCase = true) && mc.thePlayer.heldItem.item is ItemSword) {
863
                mc.gameSettings.keyBindUseItem.pressed = false
864
            } else {
865
                mc.netHandler.addToSendQueue(C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN))
866
            }
867
            blockingStatus = false
868
        }
869
    }
870
871
    /**
872
     * Check if run should be cancelled
873
     */
874
    private val cancelRun: Boolean
875
        get() = mc.thePlayer.isSpectator || !isAlive(mc.thePlayer)
876
                || LiquidBounce.moduleManager[Blink::class.java]!!.state || LiquidBounce.moduleManager[FreeCam::class.java]!!.state
877
878
    /**
879
     * Check if [entity] is alive
880
     */
881
    private fun isAlive(entity: EntityLivingBase) = entity.isEntityAlive && entity.health > 0 ||
882
            aacValue.get() && entity.hurtTime > 5
883
884
885
    /**
886
     * Check if player is able to block
887
     */
888
    private val canBlock: Boolean
889
        get() = mc.thePlayer.heldItem != null && mc.thePlayer.heldItem.item is ItemSword
890
891
    /**
892
     * Range
893
     */
894
    private val maxRange: Float
895
        get() = max(rangeValue.get(), BlockRangeValue.get())
896
897
    private fun getRange(entity: Entity) =
898
            (if (mc.thePlayer.getDistanceToEntityBox(entity) >= BlockRangeValue.get()) rangeValue.get() else rangeValue.get()) - if (mc.thePlayer.isSprinting) rangeSprintReducementValue.get() else 0F
899
900
    /**
901
     * HUD Tag
902
     */
903
    override val tag: String?
904
        get() = targetModeValue.get()
905
}

What this file does

The entire module lives in this one Kotlin file: the value declarations that define the CPS window, range, FOV, priority, target mode and rotation mode switches, the five event handlers that schedule and drain attacks, the target-selection and isEnemy filters, the three rotation backends, and every autoblock mode including the AAC inventory trick. updateTarget and updateRotations are the two methods that decide what gets attacked and from which angle, and runAttack is the single place where C02PacketUseEntity leaves the client. The onPacket handler is the only code path that touches outgoing C07 packets, and it exists purely to service the AAC autoblock mode's cancellation flip. Reading the file from the value block at the top gives the full configurable surface, while the event handlers at the bottom show the render-clock scheduling that ties attack rate to frame rate.

source RotationUtils.java (rotation math and silent application)

RotationUtils.java454 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
 */
6
package net.ccbluex.liquidbounce.utils;
7
8
import net.ccbluex.liquidbounce.LiquidBounce;
9
import net.ccbluex.liquidbounce.event.EventTarget;
10
import net.ccbluex.liquidbounce.event.Listenable;
11
import net.ccbluex.liquidbounce.event.PacketEvent;
12
import net.ccbluex.liquidbounce.event.TickEvent;
13
import net.ccbluex.liquidbounce.features.module.modules.combat.FastBow;
14
import net.minecraft.client.entity.EntityPlayerSP;
15
import net.minecraft.entity.Entity;
16
import net.minecraft.entity.EntityLivingBase;
17
import net.minecraft.network.Packet;
18
import net.minecraft.network.play.client.C03PacketPlayer;
19
import net.minecraft.util.*;
20
import net.minecraftforge.fml.relauncher.Side;
21
import net.minecraftforge.fml.relauncher.SideOnly;
22
import org.jetbrains.annotations.NotNull;
23
import net.minecraft.util.Vec3;
24
25
import java.util.Random;
26
27
@SideOnly(Side.CLIENT)
28
public final class RotationUtils extends MinecraftInstance implements Listenable {
29
30
    private static Random random = new Random();
31
32
    private static int keepLength;
33
34
    public static Rotation targetRotation;
35
    public static Rotation serverRotation;
36
37
    public static boolean keepCurrentRotation = false;
38
39
    private static double x = random.nextDouble();
40
    private static double y = random.nextDouble();
41
    private static double z = random.nextDouble();
42
43
    public static float getRotations(EntityLivingBase ent ,float otPos) {
44
        double x = ent.posX + Math.sin(otPos);
45
        double z = ent.posZ + Math.cos(otPos);
46
        return getRotationFromPosition(x, z);
47
    }
48
49
    public static float getRotationFromPosition(double x, double z) {
50
        double xDiff = x - mc.thePlayer.posX;
51
        double zDiff = z - mc.thePlayer.posZ;
52
53
        float yaw = (float) (Math.atan2(zDiff, xDiff) * 180.0D / 3.141592653589793D) - 90.0F;
54
        return yaw;
55
    }
56
57
58
    public static float[] getRotationFromPosition(double x, double z, double y) {
59
        double xDiff = x - mc.thePlayer.posX;
60
        double zDiff = z - mc.thePlayer.posZ;
61
        double yDiff = y - mc.thePlayer.posY - 1.2;
62
63
        double dist = MathHelper.sqrt_double(xDiff * xDiff + zDiff * zDiff);
64
        float yaw = (float) (Math.atan2(zDiff, xDiff) * 180.0D / 3.141592653589793D) - 90.0F;
65
        float pitch = (float) -(Math.atan2(yDiff, dist) * 180.0D / 3.141592653589793D);
66
        return new float[]{yaw, pitch};
67
    }
68
69
    public static VecRotation faceBlock(final BlockPos blockPos) {
70
        if (blockPos == null)
71
            return null;
72
73
        VecRotation vecRotation = null;
74
75
        for(double xSearch = 0.1D; xSearch < 0.9D; xSearch += 0.1D) {
76
            for(double ySearch = 0.1D; ySearch < 0.9D; ySearch += 0.1D) {
77
                for (double zSearch = 0.1D; zSearch < 0.9D; zSearch += 0.1D) {
78
                    final Vec3 eyesPos = new Vec3(mc.thePlayer.posX, mc.thePlayer.getEntityBoundingBox().minY + mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ);
79
                    final Vec3 posVec = new Vec3(blockPos).addVector(xSearch, ySearch, zSearch);
80
                    final double dist = eyesPos.distanceTo(posVec);
81
82
                    final double diffX = posVec.xCoord - eyesPos.xCoord;
83
                    final double diffY = posVec.yCoord - eyesPos.yCoord;
84
                    final double diffZ = posVec.zCoord - eyesPos.zCoord;
85
86
                    final double diffXZ = MathHelper.sqrt_double(diffX * diffX + diffZ * diffZ);
87
88
                    final Rotation rotation = new Rotation(
89
                            MathHelper.wrapAngleTo180_float((float) Math.toDegrees(Math.atan2(diffZ, diffX)) - 90F),
90
                            MathHelper.wrapAngleTo180_float((float) -Math.toDegrees(Math.atan2(diffY, diffXZ)))
91
                    );
92
93
                    final Vec3 rotationVector = getVectorForRotation(rotation);
94
                    final Vec3 vector = eyesPos.addVector(rotationVector.xCoord * dist, rotationVector.yCoord * dist,
95
                            rotationVector.zCoord * dist);
96
                    final MovingObjectPosition obj = mc.theWorld.rayTraceBlocks(eyesPos, vector, false,
97
                            false, true);
98
99
                    if (obj.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
100
                        final VecRotation currentVec = new VecRotation(posVec, rotation);
101
102
                        if (vecRotation == null || getRotationDifference(currentVec.getRotation()) < getRotationDifference(vecRotation.getRotation()))
103
                            vecRotation = currentVec;
104
                    }
105
                }
106
            }
107
        }
108
109
        return vecRotation;
110
    }
111
112
113
114
    /**
115
     * Face target with bow
116
     *
117
     * @param target your enemy
118
     * @param silent client side rotations
119
     * @param predict predict new enemy position
120
     * @param predictSize predict size of predict
121
     */
122
    public static void faceBow(final Entity target, final boolean silent, final boolean predict, final float predictSize) {
123
        final EntityPlayerSP player = mc.thePlayer;
124
125
        final double posX = target.posX + (predict ? (target.posX - target.prevPosX) * predictSize : 0) - (player.posX + (predict ? (player.posX - player.prevPosX) : 0));
126
        final double posY = target.getEntityBoundingBox().minY + (predict ? (target.getEntityBoundingBox().minY - target.prevPosY) * predictSize : 0) + target.getEyeHeight() - 0.15 - (player.getEntityBoundingBox().minY + (predict ? (player.posY - player.prevPosY) : 0)) - player.getEyeHeight();
127
        final double posZ = target.posZ + (predict ? (target.posZ - target.prevPosZ) * predictSize : 0) - (player.posZ + (predict ? (player.posZ - player.prevPosZ) : 0));
128
        final double posSqrt = Math.sqrt(posX * posX + posZ * posZ);
129
130
        float velocity = LiquidBounce.moduleManager.getModule(FastBow.class).getState() ? 1F : player.getItemInUseDuration() / 20F;
131
        velocity = (velocity * velocity + velocity * 2) / 3;
132
133
        if(velocity > 1) velocity = 1;
134
135
        final Rotation rotation = new Rotation(
136
                (float) (Math.atan2(posZ, posX) * 180 / Math.PI) - 90,
137
                (float) -Math.toDegrees(Math.atan((velocity * velocity - Math.sqrt(velocity * velocity * velocity * velocity - 0.006F * (0.006F * (posSqrt * posSqrt) + 2 * posY * (velocity * velocity)))) / (0.006F * posSqrt)))
138
        );
139
140
        if(silent)
141
            setTargetRotation(rotation);
142
        else
143
            limitAngleChange(new Rotation(player.rotationYaw, player.rotationPitch), rotation,10 +
144
                    new Random().nextInt(6)).toPlayer(mc.thePlayer);
145
    }
146
    /**
147
     * Search good center
148
     *
149
     * @param bb enemy box
150
     * @param outborder outborder option
151
     * @param random random option
152
     * @param predict predict option
153
     * @param throughWalls throughWalls option
154
     * @return center
155
     */
156
    public static VecRotation searchCenter(final AxisAlignedBB bb, final boolean outborder, final boolean random,
157
                                           final boolean predict, final boolean throughWalls, final float distance) {
158
        if(outborder) {
159
            final Vec3 vec3 = new Vec3(bb.minX + (bb.maxX - bb.minX) * (x * 0.3 + 1.0), bb.minY + (bb.maxY - bb.minY) * (y * 0.3 + 1.0), bb.minZ + (bb.maxZ - bb.minZ) * (z * 0.3 + 1.0));
160
            return new VecRotation(vec3, toRotation(vec3, predict));
161
        }
162
163
        final Vec3 randomVec = new Vec3(bb.minX + (bb.maxX - bb.minX) * x * 0.8, bb.minY + (bb.maxY - bb.minY) * y * 0.8, bb.minZ + (bb.maxZ - bb.minZ) * z * 0.8);
164
        final Rotation randomRotation = toRotation(randomVec, predict);
165
166
        final Vec3 eyes = mc.thePlayer.getPositionEyes(1F);
167
168
        VecRotation vecRotation = null;
169
170
        for(double xSearch = 0.15D; xSearch < 0.85D; xSearch += 0.1D) {
171
            for (double ySearch = 0.15D; ySearch < 1D; ySearch += 0.1D) {
172
                for (double zSearch = 0.15D; zSearch < 0.85D; zSearch += 0.1D) {
173
                    final Vec3 vec3 = new Vec3(bb.minX + (bb.maxX - bb.minX) * xSearch,
174
                            bb.minY + (bb.maxY - bb.minY) * ySearch, bb.minZ + (bb.maxZ - bb.minZ) * zSearch);
175
                    final Rotation rotation = toRotation(vec3, predict);
176
                    final double vecDist = eyes.distanceTo(vec3);
177
178
                    if (vecDist > distance)
179
                        continue;
180
181
                    if(throughWalls || isVisible(vec3)) {
182
                        final VecRotation currentVec = new VecRotation(vec3, rotation);
183
184
                        if (vecRotation == null || (random ? getRotationDifference(currentVec.getRotation(), randomRotation) < getRotationDifference(vecRotation.getRotation(), randomRotation) : getRotationDifference(currentVec.getRotation()) < getRotationDifference(vecRotation.getRotation())))
185
                            vecRotation = currentVec;
186
                    }
187
                }
188
            }
189
        }
190
191
        return vecRotation;
192
    }
193
194
    /**
195
     * Translate vec to rotation
196
     *
197
     * @param vec target vec
198
     * @param predict predict new location of your body
199
     * @return rotation
200
     */
201
202
203
    public static Rotation toRotation(final Vec3 vec, final boolean predict) {
204
        final Vec3 eyesPos = new Vec3(mc.thePlayer.posX, mc.thePlayer.getEntityBoundingBox().minY +
205
                mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ);
206
207
        if(predict) eyesPos.addVector(mc.thePlayer.motionX, mc.thePlayer.motionY, mc.thePlayer.motionZ);
208
209
        final double diffX = vec.xCoord - eyesPos.xCoord;
210
        final double diffY = vec.yCoord - eyesPos.yCoord;
211
        final double diffZ = vec.zCoord - eyesPos.zCoord;
212
213
        return new Rotation(MathHelper.wrapAngleTo180_float(
214
                (float) Math.toDegrees(Math.atan2(diffZ, diffX)) - 90F
215
        ), MathHelper.wrapAngleTo180_float(
216
                (float) (-Math.toDegrees(Math.atan2(diffY, Math.sqrt(diffX * diffX + diffZ * diffZ))))
217
        ));
218
    }
219
220
    /*
221
    sb
222
     */
223
224
225
    public static Rotation OtherRotation(final AxisAlignedBB bb,final Vec3 vec, final boolean predict,final boolean throughWalls, final float distance) {
226
        final Vec3 eyesPos = new Vec3(mc.thePlayer.posX, mc.thePlayer.getEntityBoundingBox().minY +
227
                mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ);
228
        final Vec3 eyes = mc.thePlayer.getPositionEyes(1F);
229
        VecRotation vecRotation = null;
230
        for(double xSearch = 0.15D; xSearch < 0.85D; xSearch += 0.1D) {
231
            for (double ySearch = 0.15D; ySearch < 1D; ySearch += 0.1D) {
232
                for (double zSearch = 0.15D; zSearch < 0.85D; zSearch += 0.1D) {
233
                    final Vec3 vec3 = new Vec3(bb.minX + (bb.maxX - bb.minX) * xSearch,
234
                            bb.minY + (bb.maxY - bb.minY) * ySearch, bb.minZ + (bb.maxZ - bb.minZ) * zSearch);
235
                    final Rotation rotation = toRotation(vec3, predict);
236
                    final double vecDist = eyes.distanceTo(vec3);
237
238
                    if (vecDist > distance)
239
                        continue;
240
241
                    if(throughWalls || isVisible(vec3)) {
242
                        final VecRotation currentVec = new VecRotation(vec3, rotation);
243
244
                        if (vecRotation == null)
245
                            vecRotation = currentVec;
246
                    }
247
                }
248
            }
249
        }
250
251
        if(predict) eyesPos.addVector(mc.thePlayer.motionX, mc.thePlayer.motionY, mc.thePlayer.motionZ);
252
253
        final double diffX = vec.xCoord - eyesPos.xCoord;
254
        final double diffY = vec.yCoord - eyesPos.yCoord;
255
        final double diffZ = vec.zCoord - eyesPos.zCoord;
256
257
        return new Rotation(MathHelper.wrapAngleTo180_float(
258
                (float) Math.toDegrees(Math.atan2(diffZ, diffX)) - 90F
259
        ), MathHelper.wrapAngleTo180_float(
260
                (float) (-Math.toDegrees(Math.atan2(diffY, Math.sqrt(diffX * diffX + diffZ * diffZ))))
261
        ));
262
263
264
    }
265
266
    /**
267
     * Get the center of a box
268
     *
269
     * @param bb your box
270
     * @return center of box
271
     */
272
    public static Vec3 getCenter(final AxisAlignedBB bb) {
273
        return new Vec3(bb.minX + (bb.maxX - bb.minX) * 0.5, bb.minY + (bb.maxY - bb.minY) * 0.5, bb.minZ + (bb.maxZ - bb.minZ) * 0.5);
274
    }
275
276
277
    /**
278
     * Calculate difference between the client rotation and your entity
279
     *
280
     * @param entity your entity
281
     * @return difference between rotation
282
     */
283
    public static double getRotationDifference(final Entity entity) {
284
        final Rotation rotation = toRotation(getCenter(entity.getEntityBoundingBox()), true);
285
286
        return getRotationDifference(rotation, new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch));
287
    }
288
289
    /**
290
     * Calculate difference between the server rotation and your rotation
291
     *
292
     * @param rotation your rotation
293
     * @return difference between rotation
294
     */
295
    public static double getRotationDifference(final Rotation rotation) {
296
        return serverRotation == null ? 0D : getRotationDifference(rotation, serverRotation);
297
    }
298
299
    /**
300
     * Calculate difference between two rotations
301
     *
302
     * @param a rotation
303
     * @param b rotation
304
     * @return difference between rotation
305
     */
306
    public static double getRotationDifference(final Rotation a, final Rotation b) {
307
        return Math.hypot(getAngleDifference(a.getYaw(), b.getYaw()), a.getPitch() - b.getPitch());
308
    }
309
310
    /**
311
     * Limit your rotation using a turn speed
312
     *
313
     * @param currentRotation your current rotation
314
     * @param targetRotation your goal rotation
315
     * @param turnSpeed your turn speed
316
     * @return limited rotation
317
     */
318
    @NotNull
319
    public static Rotation limitAngleChange(final Rotation currentRotation, final Rotation targetRotation, final float turnSpeed) {
320
        final float yawDifference = getAngleDifference(targetRotation.getYaw(), currentRotation.getYaw());
321
        final float pitchDifference = getAngleDifference(targetRotation.getPitch(), currentRotation.getPitch());
322
323
        return new Rotation(
324
                currentRotation.getYaw() + (yawDifference > turnSpeed ? turnSpeed : Math.max(yawDifference, -turnSpeed)),
325
                currentRotation.getPitch() + (pitchDifference > turnSpeed ? turnSpeed : Math.max(pitchDifference, -turnSpeed)
326
        ));
327
    }
328
329
    /**
330
     * Calculate difference between two angle points
331
     *
332
     * @param a angle point
333
     * @param b angle point
334
     * @return difference between angle points
335
     */
336
    private static float getAngleDifference(final float a, final float b) {
337
        return ((((a - b) % 360F) + 540F) % 360F) - 180F;
338
    }
339
340
    /**
341
     * Calculate rotation to vector
342
     *
343
     * @param rotation your rotation
344
     * @return target vector
345
     */
346
    public static Vec3 getVectorForRotation(final Rotation rotation) {
347
        float yawCos = MathHelper.cos(-rotation.getYaw() * 0.017453292F - (float) Math.PI);
348
        float yawSin = MathHelper.sin(-rotation.getYaw() * 0.017453292F - (float) Math.PI);
349
        float pitchCos = -MathHelper.cos(-rotation.getPitch() * 0.017453292F);
350
        float pitchSin = MathHelper.sin(-rotation.getPitch() * 0.017453292F);
351
        return new Vec3(yawSin * pitchCos, pitchSin, yawCos * pitchCos);
352
    }
353
354
    /**
355
     * Allows you to check if your crosshair is over your target entity
356
     *
357
     * @param targetEntity your target entity
358
     * @param blockReachDistance your reach
359
     * @return if crosshair is over target
360
     */
361
    public static boolean isFaced(final Entity targetEntity, double blockReachDistance) {
362
        return RaycastUtils.raycastEntity(blockReachDistance, entity -> entity == targetEntity) != null;
363
    }
364
365
    /**
366
     * Allows you to check if your enemy is behind a wall
367
     */
368
    public static boolean isVisible(final Vec3 vec3) {
369
        final Vec3 eyesPos = new Vec3(mc.thePlayer.posX, mc.thePlayer.getEntityBoundingBox().minY + mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ);
370
371
        return mc.theWorld.rayTraceBlocks(eyesPos, vec3) == null;
372
    }
373
374
    /**
375
     * Handle minecraft tick
376
     *
377
     * @param event Tick event
378
     */
379
    @EventTarget
380
    public void onTick(final TickEvent event) {
381
        if(targetRotation != null) {
382
            keepLength--;
383
384
            if (keepLength <= 0)
385
                reset();
386
        }
387
388
        if(random.nextGaussian() > 0.8D) x = Math.random();
389
        if(random.nextGaussian() > 0.8D) y = Math.random();
390
        if(random.nextGaussian() > 0.8D) z = Math.random();
391
    }
392
393
    /**
394
     * Handle packet
395
     *
396
     * @param event Packet Event
397
     */
398
    @EventTarget
399
    public void onPacket(final PacketEvent event) {
400
        final Packet<?> packet = event.getPacket();
401
402
        if(packet instanceof C03PacketPlayer) {
403
            final C03PacketPlayer packetPlayer = (C03PacketPlayer) packet;
404
405
            if(targetRotation != null && !keepCurrentRotation && (targetRotation.getYaw() != serverRotation.getYaw() || targetRotation.getPitch() != serverRotation.getPitch())) {
406
                packetPlayer.yaw = targetRotation.getYaw();
407
                packetPlayer.pitch = targetRotation.getPitch();
408
                packetPlayer.rotating = true;
409
            }
410
411
            if(packetPlayer.rotating) serverRotation = new Rotation(packetPlayer.yaw, packetPlayer.pitch);
412
        }
413
    }
414
415
    /**
416
     * Set your target rotation
417
     *
418
     * @param rotation your target rotation
419
     */
420
    public static void setTargetRotation(final Rotation rotation) {
421
        setTargetRotation(rotation, 0);
422
    }
423
424
    /**
425
     * Set your target rotation
426
     *
427
     * @param rotation your target rotation
428
     */
429
    public static void setTargetRotation(final Rotation rotation, final int keepLength) {
430
        if(Double.isNaN(rotation.getYaw()) || Double.isNaN(rotation.getPitch())
431
                || rotation.getPitch() > 90 || rotation.getPitch() < -90)
432
            return;
433
434
        rotation.fixedSensitivity(mc.gameSettings.mouseSensitivity);
435
        targetRotation = rotation;
436
        RotationUtils.keepLength = keepLength;
437
    }
438
439
    /**
440
     * Reset your target rotation
441
     */
442
    public static void reset() {
443
        keepLength = 0;
444
        targetRotation = null;
445
    }
446
447
    /**
448
     * @return YESSSS!!!
449
     */
450
    @Override
451
    public boolean handleEvents() {
452
        return true;
453
    }
454
}

What this file does

RotationUtils implements everything the Aura needs to aim: searchCenter picks a point inside the target bounding box (with outborder and random-center sampling), OtherRotation computes the alternative backtracking angle, limitAngleChange clamps a rotation to a maximum per-tick delta against the stored serverRotation, and setTargetRotation feeds the silent-rotation pipeline that rewrites the player's yaw and pitch in outgoing movement packets without moving the visual camera. getRotationDifference scores how far an entity sits from the current look direction and powers both the FOV filter and the Direction priority sort. isFaced is the fallback hitable test used when the RayCast switch is off. The class is shared with the client's other combat modules, but the Aura is the heaviest consumer: every attack cycle calls searchCenter or OtherRotation, limits the result, and applies it, which is exactly the rotation stream an aim-pattern check would analyze.

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 AimbotHeuristic (rotation pattern analysis)

AimbotHeuristic.java164 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.look;
20
21
import me.islandscout.hawk.HawkPlayer;
22
import me.islandscout.hawk.check.CustomCheck;
23
import me.islandscout.hawk.check.Cancelless;
24
import me.islandscout.hawk.event.*;
25
import me.islandscout.hawk.util.Debug;
26
import me.islandscout.hawk.util.MathPlus;
27
import org.bukkit.entity.Player;
28
import org.bukkit.util.Vector;
29
30
import java.util.*;
31
32
/**
33
 * AimbotHeuristic exploits flaws in aim-bot cheats by
34
 * analyzing mouse movement patterns during interaction. Although
35
 * easily bypassed, it catches a significant number of cheaters.
36
 * Caution is advised since this check may false flag during
37
 * certain circumstances. This check should only be used as a
38
 * hint that the player might be cheating.
39
 */
40
public class AimbotHeuristic extends CustomCheck implements Cancelless {
41
42
    private final Map<UUID, List<Vector>> mouseMoves;
43
    private final Map<UUID, List<Long>> clickTimes;
44
45
    private static final int MOVES_PER_SAMPLE = 4; //must be greater than 0
46
    private final int MOVES_AFTER_HIT;
47
    private final boolean DEBUG;
48
49
    public AimbotHeuristic() {
50
        super("aimbotheuristic", false, -1, 5, 0.99, 5000, "&7%player% failed aimbot (heuristic), VL %vl%", null);
51
        mouseMoves = new HashMap<>();
52
        clickTimes = new HashMap<>();
53
54
        MOVES_AFTER_HIT = MOVES_PER_SAMPLE - MOVES_PER_SAMPLE / 2;
55
56
        DEBUG = (boolean) customSetting("debug", "", false);
57
    }
58
59
    public void check(Event e) {
60
        if (e instanceof MoveEvent) {
61
            processMove((MoveEvent) e);
62
        } else if (e instanceof InteractEntityEvent || e instanceof InteractWorldEvent) {
63
            processClick(e);
64
        }
65
    }
66
67
    private void processMove(MoveEvent e) {
68
        Player p = e.getPlayer();
69
        HawkPlayer pp = e.getHawkPlayer();
70
        UUID uuid = p.getUniqueId();
71
72
        List<Vector> lastMoves = mouseMoves.getOrDefault(uuid, new ArrayList<>());
73
        Vector mouseMove = new Vector(e.getTo().getYaw() - e.getFrom().getYaw(), e.getTo().getPitch() - e.getFrom().getPitch(), 0);
74
75
        lastMoves.add(mouseMove);
76
        //make size 1 bigger so that we can get the move before
77
        //the first move that we check
78
        if(lastMoves.size() > MOVES_PER_SAMPLE + 1) {
79
            lastMoves.remove(0);
80
        }
81
        mouseMoves.put(uuid, lastMoves);
82
83
        if(clickedXMovesBefore(MOVES_AFTER_HIT, pp)) {
84
            double minSpeed = Double.MAX_VALUE;
85
            double maxSpeed = 0D;
86
            double maxAngle = 0D;
87
            for(int i = 1; i < lastMoves.size(); i++) {
88
                Vector lastMouseMove = lastMoves.get(i - 1);
89
                Vector currMouseMove = lastMoves.get(i);
90
                double speed = currMouseMove.length();
91
                double lastSpeed = lastMouseMove.length();
92
                double angle = (lastSpeed != 0 && lastSpeed != 0) ? MathPlus.angle(lastMouseMove, currMouseMove) : 0D;
93
                if(Double.isNaN(angle))
94
                    angle = 0D;
95
                maxSpeed = Math.max(speed, maxSpeed);
96
                minSpeed = Math.min(speed, minSpeed);
97
                maxAngle = Math.max(angle, maxAngle);
98
99
                //stutter
100
                if(maxSpeed - minSpeed > 4 && minSpeed < 0.01 && maxAngle < 0.1 && lastSpeed > 1) { //this lastSpeed check eliminates a false positive
101
                    if(DEBUG) {
102
                        p.sendMessage("AimbotHeuristic: A");
103
                    }
104
                    punishEm(pp, e);
105
                }
106
                //twitching or zig zags
107
                else if(speed > 20 && lastSpeed > 20 && angle > 2.86) {
108
                    if(DEBUG) {
109
                        p.sendMessage("AimbotHeuristic: B");
110
                    }
111
                    punishEm(pp, e);
112
                }
113
                //jump discontinuity
114
                else if(speed - lastSpeed < -30 && angle > 0.8) {
115
                    if(DEBUG) {
116
                        p.sendMessage("AimbotHeuristic: C");
117
                    }
118
                    punishEm(pp, e);
119
                }
120
                else {
121
                    reward(pp);
122
                }
123
            }
124
        }
125
    }
126
127
    private boolean clickedXMovesBefore(long x, HawkPlayer pp) {
128
        List<Long> clickTimess = clickTimes.getOrDefault(pp.getUuid(), new ArrayList<>());
129
        long time = pp.getCurrentTick() - x;
130
        for(int i = 0; i < clickTimess.size(); i++) {
131
            if(time == clickTimess.get(i)) {
132
                clickTimess.remove(i);
133
                return true;
134
            }
135
        }
136
        return false;
137
    }
138
139
    private void processClick(Event e) {
140
        UUID uuid = e.getPlayer().getUniqueId();
141
        List<Long> clickTimess = clickTimes.getOrDefault(uuid, new ArrayList<>());
142
        long currTick = e.getHawkPlayer().getCurrentTick();
143
        if(!clickTimess.contains(currTick))
144
            clickTimess.add(e.getHawkPlayer().getCurrentTick());
145
146
        //memory leak fail-safe, if necessary?
147
        for(int i = clickTimess.size() - 1; i >= 0; i--) {
148
            if(currTick - clickTimess.get(i) > MOVES_PER_SAMPLE + 1)
149
                clickTimess.remove(i);
150
        }
151
152
        clickTimes.put(uuid, clickTimess);
153
    }
154
155
    private void punishEm(HawkPlayer pp, MoveEvent e) {
156
        punish(pp, false, e);
157
    }
158
159
    @Override
160
    public void removeData(Player p) {
161
        mouseMoves.remove(p.getUniqueId());
162
        clickTimes.remove(p.getUniqueId());
163
    }
164
}

How it counteracts this module

Hawk's AimbotHeuristic records every look delta as a Vector(yawChange, pitchChange) in a per-player list and walks the recent history scoring speed and the angle between consecutive moves. It fires on three signatures: all recent moves sharing one speed and direction (maxSpeed - minSpeed > 4 with minSpeed below 0.01, maxAngle below 0.1 and a preceding move faster than 1), a pair of consecutive high-speed rotations with a sharp turn between them (speed and lastSpeed both over 20 with angle over 2.86), and a sudden deceleration of more than 30 with an angle over 0.8. These are the exact shapes a scripted snap leaves in the yaw/pitch stream, and because Hawk reads the rotations that actually reach the server, silent rotation does not hide them.

anticheat KillAura (direction, multi, reach, speed)

KillAura.java114 lines · Java
1
package me.vrekt.arc.check.combat;
2
3
import me.vrekt.arc.Arc;
4
import me.vrekt.arc.check.Check;
5
import me.vrekt.arc.check.CheckType;
6
import me.vrekt.arc.data.combat.FightData;
7
import me.vrekt.arc.utilties.LocationHelper;
8
import org.bukkit.ChatColor;
9
import org.bukkit.entity.Entity;
10
import org.bukkit.entity.Player;
11
import org.bukkit.util.Vector;
12
13
public class KillAura extends Check {
14
15
    private double maxAngle, maxReach;
16
    private int maxSwingTime, maxAttacks, maxAttackPackets;
17
18
    public KillAura() {
19
        super(CheckType.KILLAURA);
20
21
        maxAngle = Arc.getCheckManager().getValueDouble(CheckType.KILLAURA, "max-direction-angle");
22
        maxSwingTime = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-swing-time");
23
        maxReach = Arc.getCheckManager().getValueDouble(CheckType.KILLAURA, "max-reach");
24
        maxAttacks = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-attacks");
25
        maxAttackPackets = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-attack-packets");
26
27
    }
28
29
    public boolean check(FightData data, Player player) {
30
        result.reset();
31
32
        Entity last = data.getLastAttackedEntity();
33
        Entity entity = data.getAttackedEntity();
34
35
        // Calculate angle stuff.
36
        Vector playerLocation = player.getLocation().toVector();
37
        Vector entityLocation = entity.getLocation().toVector();
38
        double angle = entityLocation.subtract(playerLocation).angle(player.getLocation().getDirection());
39
40
        if (last != null && !entity.equals(last)) {
41
            // check the angle between the two entities
42
            Vector lastLocation = last.getLocation().toVector();
43
            double angleToLast = lastLocation.subtract(playerLocation).angle(player.getLocation().getDirection());
44
            double angleDifference = Math.abs(angleToLast - angle);
45
            double distanceDifference = LocationHelper.distance(last.getLocation(), entity.getLocation());
46
            if (angleDifference > maxAngle && distanceDifference <= maxReach) {
47
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Multi)");
48
                result.set(checkViolation(player, "Angle difference greater than allowed. a=" + angleDifference + " e=" + maxAngle));
49
            }
50
        }
51
52
        // check yaw difference.
53
        if (angle > maxAngle) {
54
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Direction)");
55
            result.set(checkViolation(player, "Angle distance greater than allowed. a=" + angle + " e=" + maxAngle));
56
        }
57
58
        // check swing time.
59
        long time = System.currentTimeMillis() - data.getLastArmSwing();
60
        if (time > maxSwingTime) {
61
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(NoSwing)");
62
            result.set(checkViolation(player, "Player did not swing their arm in time."));
63
        }
64
65
        // distance to entity excluding knockback.
66
        double distance = LocationHelper.distance(player.getLocation(), entity.getLocation().subtract(entity.getVelocity()));
67
        // check for reach
68
        if (distance > maxReach) {
69
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Reach)");
70
            result.set(checkViolation(player, "Entity is out of players range. d=" + distance + " e=" + maxReach));
71
        }
72
73
        // check max attacks
74
        if (data.getLastAttackCheck() == 0) {
75
            data.setLastAttackCheck(System.currentTimeMillis());
76
        }
77
        long lastAttack = System.currentTimeMillis() - data.getLastAttackCheck();
78
        if (lastAttack >= 1000) {
79
            // check if we exceeded the max attacks in the last second.
80
            int totalAttacks = data.getTotalAttacks();
81
            if (totalAttacks > maxAttacks) {
82
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Speed)");
83
                result.set(checkViolation(player, "Attacking too fast. a=" + totalAttacks + " e=" + maxAttacks));
84
            }
85
            // reset data for next check.
86
            data.setTotalAttacks(0);
87
            data.setLastAttackCheck(System.currentTimeMillis());
88
        }
89
90
        getCheck().setCheckName("KillAura");
91
        return result.failed();
92
    }
93
94
    public boolean checkFrequency(FightData data, Player player) {
95
        if (data.getLastAttackCheck() == 0) {
96
            data.setLastAttackCheck(System.currentTimeMillis());
97
            return false;
98
        }
99
100
        long time = System.currentTimeMillis() - data.getLastAttackCheck();
101
        if (time >= 1000) {
102
            data.setLastAttackCheck(System.currentTimeMillis());
103
            int totalPackets = data.getAttackPackets();
104
            if (totalPackets > maxAttackPackets) {
105
                data.setAttackPackets(0);
106
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Speed)");
107
                return checkViolation(player, "Attacking too fast a=" + totalPackets + " e=" + maxAttackPackets);
108
            }
109
        }
110
111
        return false;
112
    }
113
114
}

How it counteracts this module

Arc's KillAura check runs from the FightListener on every attack and combines four independent sub-checks. The direction check computes the angle between the player's look vector and the attacked entity and flags anything above max-direction-angle; the multi sub-check compares the angles to the last and current attacked entity and flags when they differ by more than maxAngle while both are in reach; the reach sub-check measures the distance from the player to the entity position minus its velocity, so knockback does not mask an out-of-range hit; and the speed sub-check counts attacks and attack packets per second against max-attacks and max-attack-packets, resetting on a one-second boundary. The no-swing sub-check is also present but fires only when an attack arrives without an arm swing inside max-swing-time.

anticheat Reach (distance limit with precision and dynamic reduction)

Reach.java372 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.fight;
16
17
18
import org.bukkit.GameMode;
19
import org.bukkit.Location;
20
import org.bukkit.entity.EnderDragon;
21
import org.bukkit.entity.Entity;
22
import org.bukkit.entity.Giant;
23
import org.bukkit.entity.LivingEntity;
24
import org.bukkit.entity.Player;
25
import org.bukkit.util.Vector;
26
27
import fr.neatmonster.nocheatplus.actions.ParameterName;
28
import fr.neatmonster.nocheatplus.checks.Check;
29
import fr.neatmonster.nocheatplus.checks.CheckType;
30
import fr.neatmonster.nocheatplus.checks.ViolationData;
31
import fr.neatmonster.nocheatplus.checks.combined.Improbable;
32
import fr.neatmonster.nocheatplus.checks.moving.location.tracking.LocationTrace.ITraceEntry;
33
import fr.neatmonster.nocheatplus.permissions.Permissions;
34
import fr.neatmonster.nocheatplus.players.IPlayerData;
35
import fr.neatmonster.nocheatplus.utilities.StringUtil;
36
import fr.neatmonster.nocheatplus.utilities.TickTask;
37
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
38
39
/**
40
 * The Reach check will find out if a player interacts with something that's too far away.
41
 */
42
public class Reach extends Check {
43
44
    /** The maximum distance allowed to interact with an entity in creative mode. */
45
    public static final double CREATIVE_DISTANCE = 6D;
46
47
48
    /** Additum for distance, based on entity. */
49
    private static double getDistMod(final Entity damaged) {
50
        // Handle the EnderDragon differently.
51
        if (damaged instanceof EnderDragon)
52
            return 6.5D;
53
        else if (damaged instanceof Giant){
54
            return 1.5D;
55
        }
56
        else return 0;
57
    }
58
59
60
    /**
61
     * Instantiates a new reach check.
62
     */
63
    public Reach() {
64
        super(CheckType.FIGHT_REACH);
65
    }
66
67
68
    /**
69
     * "Classic" check.
70
     * 
71
     * @param player
72
     *            the player
73
     * @param damaged
74
     *            the damaged
75
     * @return true, if successful
76
     */
77
    public boolean check(final Player player, final Location pLoc, 
78
                         final Entity damaged, final boolean damagedIsFake, final Location dRef, 
79
                         final FightData data, final FightConfig cc, final IPlayerData pData) {
80
81
        boolean cancel = false;
82
        // The maximum distance allowed to interact with an entity in survival mode.
83
        final double SURVIVAL_DISTANCE = cc.reachSurvivalDistance; 
84
        // Amount which can be reduced by reach adaption.
85
        final double DYNAMIC_RANGE = cc.reachReduceDistance; 
86
        // Adaption amount for dynamic range.
87
        final double DYNAMIC_STEP = cc.reachReduceStep / SURVIVAL_DISTANCE; 
88
        final double distanceLimit = player.getGameMode() == GameMode.CREATIVE ? CREATIVE_DISTANCE : SURVIVAL_DISTANCE + getDistMod(damaged);
89
        final double distanceMin = (distanceLimit - DYNAMIC_RANGE) / distanceLimit;
90
        final double height = damagedIsFake ? (damaged instanceof LivingEntity ? ((LivingEntity) damaged).getEyeHeight() : 1.75) : mcAccess.getHandle().getHeight(damaged);
91
        final double width = damagedIsFake ? 0.6 : mcAccess.getHandle().getWidth(damaged);
92
        double centertoedge = 0.0;
93
        
94
        if (cc.reachPrecision) {
95
            centertoedge = getinset(pLoc, dRef, width / 2, 0.0);
96
        }
97
98
        // Refine y position.
99
        final double pY = pLoc.getY() + player.getEyeHeight();
100
        final double dY = dRef.getY();
101
        if (pY <= dY) {
102
            // Keep the foot level y.
103
        } 
104
        // Highest ref y
105
        else if (pY >= dY + height) {
106
             dRef.setY(dY + height);
107
        }
108
        // Level with damaged.
109
        else dRef.setY(pY);
110
111
        final Vector pRel = dRef.toVector().subtract(pLoc.toVector().setY(pY)); // TODO: Run calculations on numbers only :p.
112
        // Distance is calculated from eye location to center of targeted. If the player is further away from their target
113
        // than allowed, the difference will be assigned to "distance".
114
        final double lenpRel = pRel.length() - centertoedge;
115
        double violation = lenpRel - distanceLimit;
116
        final double reachMod = data.reachMod; 
117
118
119
        if (violation > 0) {
120
            if (TickTask.getLag(1000, true) < 1.5f){ // Do not increase the vl in case of server lag (1.5 is a magic value)
121
                data.reachVL += violation;
122
                final ViolationData vd = new ViolationData(this, player, data.reachVL, violation, cc.reachActions);
123
                vd.setParameter(ParameterName.REACH_DISTANCE, StringUtil.fdec3.format(lenpRel));
124
                // Execute whatever actions are associated with this check and the violation level and find out if we should
125
                // cancel the event.
126
                cancel = executeActions(vd).willCancel();
127
            }
128
129
            if (Improbable.check(player, (float) violation / 2f, System.currentTimeMillis(), "fight.reach", pData)){
130
                cancel = true;
131
            }
132
133
            if (cancel && cc.reachPenalty > 0){
134
                // Apply an attack penalty time.
135
                data.attackPenalty.applyPenalty(cc.reachPenalty);
136
            }
137
        }
138
        else if (lenpRel - distanceLimit * reachMod > 0){
139
            // Silent cancel.
140
            if (cc.reachPenalty > 0) {
141
                data.attackPenalty.applyPenalty(cc.reachPenalty / 2);
142
            }
143
            cancel = true;
144
            Improbable.feed(player, (float) (lenpRel - distanceLimit * reachMod) / 4f, System.currentTimeMillis());
145
        }
146
        else data.reachVL *= 0.8D; // Player passed the check, reward them.
147
            
148
149
        if (!cc.reachReduce){
150
            data.reachMod = 1d;
151
        }
152
        else if (lenpRel > distanceLimit - DYNAMIC_RANGE){
153
            data.reachMod = Math.max(distanceMin, data.reachMod - DYNAMIC_STEP);
154
        }
155
        else data.reachMod = Math.min(1.0, data.reachMod + DYNAMIC_STEP);
156
157
        if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)){
158
            player.sendMessage("NC+: Attack/reach " + damaged.getType()+ " height="+ StringUtil.fdec3.format(height) + " dist=" + StringUtil.fdec3.format(lenpRel) +" @" + StringUtil.fdec3.format(reachMod));
159
        }
160
161
        return cancel;
162
    }
163
164
    /**
165
     * Data context for iterating over ITraceEntry instances.
166
     * @param player
167
     * @param pLoc
168
     * @param damaged
169
     * @param damagedLoc
170
     * @param data
171
     * @param cc
172
     * @return
173
     */
174
    public ReachContext getContext(final Player player, final Location pLoc, 
175
                                   final Entity damaged, final Location damagedLoc, 
176
                                   final FightData data, final FightConfig cc) {
177
178
        final ReachContext context = new ReachContext();
179
        context.distanceLimit = player.getGameMode() == GameMode.CREATIVE ? CREATIVE_DISTANCE : cc.reachSurvivalDistance + getDistMod(damaged);
180
        context.distanceMin = (context.distanceLimit - cc.reachReduceDistance) / context.distanceLimit;
181
        //context.eyeHeight = player.getEyeHeight();
182
        context.pY = pLoc.getY() + player.getEyeHeight();
183
        return context;
184
    }
185
186
    /**
187
     * Check if the player fails the reach check, no change of FightData.
188
     * @param player
189
     * @param pLoc
190
     * @param damaged
191
     * @param dRef
192
     * @param context
193
     * @param data
194
     * @param cc
195
     * @return
196
     */
197
    public boolean loopCheck(final Player player, final Location pLoc, final Entity damaged, 
198
                             final ITraceEntry dRef, final ReachContext context, 
199
                             final FightData data, final FightConfig cc) {
200
201
        boolean cancel = false;
202
203
        // Refine y position.
204
        final double dY = dRef.getY();
205
        double y = dRef.getY();
206
207
        if (context.pY <= dY) {
208
            // Keep the foot level y.
209
        }
210
        else if (context.pY >= dY + dRef.getBoxMarginVertical()) {
211
            y = dY + dRef.getBoxMarginVertical(); // Highest ref y.
212
        }
213
        else {
214
            y = context.pY; // Level with damaged.
215
        }
216
217
        double centertoedge = 0.0;
218
        if (cc.reachPrecision) centertoedge = getinset(pLoc, new Location(null, dRef.getX(), dRef.getY(), dRef.getZ()), dRef.getBoxMarginHorizontal(), y - context.pY);
219
        
220
        // Distance is calculated from eye location to center of targeted. If the player is further away from their target
221
        // than allowed, the difference will be assigned to "distance".
222
        // TODO: Run check on squared distances (quite easy to change to stored boundary-sq values).
223
        final double lenpRel = TrigUtil.distance(dRef.getX(), y, dRef.getZ(), pLoc.getX(), context.pY, pLoc.getZ()) - centertoedge;
224
        double violation = lenpRel - context.distanceLimit;
225
226
        if (violation > 0 || lenpRel - context.distanceLimit * data.reachMod > 0){
227
            // TODO: The silent cancel parts should be sen as "no violation" ?
228
            // Set minimum violation in context
229
            context.minViolation = Math.min(context.minViolation, lenpRel);
230
            cancel = true;
231
        }
232
        context.minResult = Math.min(context.minResult, lenpRel);
233
234
        return cancel;
235
236
    }
237
238
    /**
239
     * Apply changes to FightData according to check results (context), trigger violations.
240
     * @param player
241
     * @param pLoc
242
     * @param damaged
243
     * @param context
244
     * @param forceViolation
245
     * @param data
246
     * @param cc
247
     * @return
248
     */
249
    public boolean loopFinish(final Player player, final Location pLoc, final Entity damaged, 
250
                              final ReachContext context, final ITraceEntry traceEntry, final boolean forceViolation, 
251
                              final FightData data, final FightConfig cc, final IPlayerData pData) {
252
253
        final double lenpRel = forceViolation && context.minViolation != Double.MAX_VALUE ? context.minViolation : context.minResult;
254
255
        if (lenpRel == Double.MAX_VALUE) {
256
            return false;
257
        }
258
259
        double violation = lenpRel - context.distanceLimit;
260
        boolean cancel = false;
261
262
        if (violation > 0) {    
263
            if (TickTask.getLag(1000, true) < 1.5f){
264
                data.reachVL += violation;
265
                final ViolationData vd = new ViolationData(this, player, data.reachVL, violation, cc.reachActions);
266
                vd.setParameter(ParameterName.REACH_DISTANCE, StringUtil.fdec3.format(lenpRel));
267
                // Execute whatever actions are associated with this check and the violation level and find out if we should
268
                // cancel the event.
269
                cancel = executeActions(vd).willCancel();
270
            }
271
            
272
            //if (Improbable.check(player, (float) violation / 2f, System.currentTimeMillis(), 
273
            //        "fight.reach", pData)){
274
            //    cancel = true;
275
            //}
276
            // TODO: New improbable weight calculations so that weight is not inverse to config weight
277
            if (cc.reachImprobableWeight > 0.0f) {
278
                if (!cc.reachImprobableFeedOnly && Improbable.check(player, (float) violation / cc.reachImprobableWeight, System.currentTimeMillis(), "fight.reach", pData)) {
279
                    cancel = true;
280
                }
281
            }
282
283
            if (cancel && cc.reachPenalty > 0){
284
                // Apply an attack penalty time.
285
                data.attackPenalty.applyPenalty(cc.reachPenalty);
286
            }
287
        }
288
        else if (lenpRel - context.distanceLimit * data.reachMod > 0){
289
            // Silent cancel.
290
            if (cc.reachPenalty > 0) {
291
                data.attackPenalty.applyPenalty(cc.reachPenalty / 2);
292
            }
293
294
            cancel = true;
295
296
            if (cc.reachImprobableWeight > 0.0f) {
297
                Improbable.feed(player, (float) (lenpRel - context.distanceLimit * data.reachMod) / cc.reachImprobableWeight, System.currentTimeMillis());
298
            }
299
            // Improbable.feed(player, (float) (lenpRel - context.distanceLimit * data.reachMod) / 4f, System.currentTimeMillis());
300
        }
301
        else {
302
            // Player passed the check, reward them.
303
            data.reachVL *= 0.8D;
304
305
        }
306
307
        // Adaption amount for dynamic range.
308
        final double DYNAMIC_STEP = cc.reachReduceStep / cc.reachSurvivalDistance;
309
310
        if (!cc.reachReduce){
311
            data.reachMod = 1d;
312
        }
313
        else if (lenpRel > context.distanceLimit - cc.reachReduceDistance){
314
            data.reachMod = Math.max(context.distanceMin, data.reachMod - DYNAMIC_STEP);
315
        }
316
        else {
317
            data.reachMod = Math.min(1.0, data.reachMod + DYNAMIC_STEP);
318
        }
319
320
        if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)){
321
            // TODO: Height: remember successful ITraceEntry
322
            player.sendMessage("NC+: Attack/reach " + damaged.getType()+ (traceEntry == null ? "" : (" height=" + traceEntry.getBoxMarginVertical())) + " dist=" + StringUtil.fdec3.format(lenpRel) +" @" + StringUtil.fdec3.format(data.reachMod));
323
        }
324
325
        return cancel;
326
    }
327
328
329
    private boolean isSameXZ(final Location loc1, final Location loc2) {
330
        return loc1.getX() == loc2.getX() && loc1.getZ() == loc2.getZ();
331
    }
332
333
334
    /**
335
     *
336
     * @param pLoc
337
     *            the player location
338
     * @param dRef
339
     *            the target location
340
     * @param damagedBoxMarginHorizontal
341
     *            the target Width / 2
342
     * @param diffY the Y different
343
     * @return the double represent for the distance from target location to the edge of target hitbox
344
     */
345
    private double getinset(final Location pLoc, final Location dRef, final double damagedBoxMarginHorizontal, final double diffY) {
346
347
        if (!isSameXZ(pLoc, dRef)) {
348
            final Location dRefc = dRef.clone();
349
            final Vector vec1 = new Vector(pLoc.getX() - dRef.getX(), diffY , pLoc.getZ() - dRef.getZ());
350
            if (vec1.length() < damagedBoxMarginHorizontal * Math.sqrt(2)) return 0.0;
351
            if (vec1.getZ() > 0.0) {
352
                dRefc.setZ(dRefc.getZ() + damagedBoxMarginHorizontal);
353
            } 
354
            else if (vec1.getZ() < 0.0) {
355
                dRefc.setZ(dRefc.getZ() - damagedBoxMarginHorizontal);
356
            } 
357
            else if (vec1.getX() > 0.0) {
358
                dRefc.setX(dRefc.getX() + damagedBoxMarginHorizontal);
359
            } 
360
            else dRefc.setX(dRefc.getX() - damagedBoxMarginHorizontal);
361
362
            final Vector vec2 = new Vector(dRefc.getX() - dRef.getX(), 0.0 , dRefc.getZ() - dRef.getZ());
363
            double angle = TrigUtil.angle(vec1, vec2);
364
            // Require < 45deg, if not 90deg-angel
365
            if (angle > Math.PI / 4) angle = Math.PI / 2 - angle;
366
            if (angle >= 0.0 && angle <= Math.PI / 4) { // TODO: Dose this one necessary?
367
                return damagedBoxMarginHorizontal / Math.cos(angle);
368
            }
369
        }
370
        return 0.0;
371
    }
372
}

How it counteracts this module

NCP's fight.Reach validates every attack against a server-side distance limit. check() computes the player-to-entity distance lenpRel, picks distanceLimit from reachSurvivalDistance (with a separate 6.5 limit in creative), and flags when lenpRel exceeds the limit, optionally tightened by reachPrecision which compares the actual separation instead of the relaxed box margin. Repeated violations accumulate reachVL and drive a dynamic reduction: reachReduceDistance shrinks the effective limit step by step, and when the module cancels, reachPenalty applies an attack penalty that further suppresses the player's combat ability. The comparison runs on the server's own positions, so nothing the client claims about range or facing changes the measured distance.

← Back to Analysis Hub