KillAura module

KillAura: Minecraft 26.3 cheat module, full source for every implementation (4 clients: OfflineClient, Combatant, Nicotine, …).

4 implementationsCOMBATCombat

Full module source: 4 implementations

Every implementation below is the complete module file, verbatim. Expand a client to read its code.

OfflineClientCOMBATsrc/main/java/com/jellypudding/offlineclient/modules/combat/KillAura.javaJava · 540 lines · 24.1 KB

Automatically swings at nearby mobs and players.

SettingsRangeWalls rangeThrough wallsFOVOnly on lookPlayersIgnore creativeIgnore sleepingIgnore flyingHostile mobsHostile agesSlimesShulkersZombie villagersPassive mobsPassive agesWater mobsBatsVillagersGolemsAllaysNeutral mobsAlso hitNever hitIgnore namedIgnore petsIgnore invisibleMax targetsRotateRotate speedAuto weaponSwap backShieldsAttack when holdingWeaponsOnly on clickIgnore cooldownSwitch delayPause on usePause in containers
KillAura.javaJava · Minecraft 26.2 · 540 lines · 24.1 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.combat;
2
3
import com.jellypudding.offlineclient.event.Subscribe;
4
import com.jellypudding.offlineclient.event.events.PacketSendEvent;
5
import com.jellypudding.offlineclient.event.events.PreMotionEvent;
6
import com.jellypudding.offlineclient.event.events.Render3DEvent;
7
import com.jellypudding.offlineclient.module.Category;
8
import com.jellypudding.offlineclient.module.Module;
9
import com.jellypudding.offlineclient.setting.BoolSetting;
10
import com.jellypudding.offlineclient.setting.EnumSetting;
11
import com.jellypudding.offlineclient.setting.NumberSetting;
12
import com.jellypudding.offlineclient.setting.RegistryListSetting;
13
import com.jellypudding.offlineclient.util.AttackTimer;
14
import com.jellypudding.offlineclient.util.ColorUtil;
15
import com.jellypudding.offlineclient.util.EntityUtil;
16
import com.jellypudding.offlineclient.util.InventoryUtil.SlotSwap;
17
import com.jellypudding.offlineclient.util.Modules;
18
import com.jellypudding.offlineclient.util.RotationManager;
19
import com.jellypudding.offlineclient.util.RotationPriority;
20
import com.jellypudding.offlineclient.util.SwingMode;
21
import com.jellypudding.offlineclient.util.TargetPriority;
22
import com.jellypudding.offlineclient.util.TickRate;
23
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
24
import net.minecraft.client.gui.screens.inventory.CreativeModeInventoryScreen;
25
import net.minecraft.client.gui.screens.inventory.InventoryScreen;
26
import net.minecraft.core.registries.BuiltInRegistries;
27
import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket;
28
import net.minecraft.util.Mth;
29
import net.minecraft.world.InteractionHand;
30
import net.minecraft.world.entity.Entity;
31
import net.minecraft.world.entity.EntityType;
32
import net.minecraft.world.entity.LivingEntity;
33
import net.minecraft.world.entity.Mob;
34
import net.minecraft.world.entity.player.Player;
35
import net.minecraft.world.item.Item;
36
import net.minecraft.world.item.Items;
37
import net.minecraft.world.level.ClipContext;
38
import net.minecraft.world.phys.AABB;
39
import net.minecraft.world.phys.HitResult;
40
import net.minecraft.world.phys.Vec3;
41
42
import java.util.ArrayList;
43
import java.util.List;
44
45
public final class KillAura extends Module {
46
47
    public enum Rotate { NONE, ON_HIT, ALWAYS, CAMERA }
48
49
    public enum Shields { NONE, BREAK, IGNORE }
50
51
    public enum Ages { ADULTS, BABIES, BOTH }
52
53
    public enum Neutral { ALWAYS, WHEN_ANGRY, NEVER }
54
55
    public enum Holding { ANYTHING, WEAPONS }
56
57
    // How long the server may go quiet before hits are held back.
58
    private static final long LAG_MILLIS = 1000;
59
60
    private static final List<Item> WEAPONS = List.of(Items.WOODEN_SWORD, Items.STONE_SWORD,
61
        Items.COPPER_SWORD, Items.IRON_SWORD, Items.GOLDEN_SWORD, Items.DIAMOND_SWORD,
62
        Items.NETHERITE_SWORD, Items.WOODEN_AXE, Items.STONE_AXE, Items.COPPER_AXE, Items.IRON_AXE,
63
        Items.GOLDEN_AXE, Items.DIAMOND_AXE, Items.NETHERITE_AXE, Items.MACE, Items.TRIDENT,
64
        Items.WOODEN_SPEAR, Items.STONE_SPEAR, Items.COPPER_SPEAR, Items.IRON_SPEAR,
65
        Items.GOLDEN_SPEAR, Items.DIAMOND_SPEAR, Items.NETHERITE_SPEAR);
66
67
    private final NumberSetting range = new NumberSetting("Range",
68
        "Maximum reach in blocks.", 4.2, 1, 6, 0.05);
69
    private final NumberSetting wallsRange = new NumberSetting("Walls range",
70
        "Shorter reach for targets you cannot see.", 3.5, 0, 6, 0.05);
71
    private final BoolSetting walls = new BoolSetting("Through walls",
72
        "Also swing at targets you cannot see.", true);
73
    private final NumberSetting fov = new NumberSetting("FOV",
74
        "Only hit targets within this angle of your view.", 360, 30, 360, 5, " degrees")
75
        .max(360);
76
    private final BoolSetting onlyOnLook = new BoolSetting("Only on look",
77
        "Only hits whatever your crosshair is already on.", false);
78
79
    private final BoolSetting players = new BoolSetting("Players",
80
        "Swing at other players.", true);
81
    private final BoolSetting ignoreCreative = new BoolSetting("Ignore creative",
82
        "Skip players in creative mode.", true)
83
        .under(players);
84
    private final BoolSetting ignoreSleeping = new BoolSetting("Ignore sleeping",
85
        "Skip players lying in a bed.", false)
86
        .under(players);
87
    private final NumberSetting ignoreFlying = new NumberSetting("Ignore flying",
88
        "Skip players with nothing under them for this many blocks. Zero hits them anyway.",
89
        0, 0, 2, 0.05, " blocks")
90
        .under(players);
91
    private final BoolSetting hostile = new BoolSetting("Hostile mobs",
92
        "Swing at anything that hunts you.", false);
93
    private final EnumSetting<Ages> hostileAges = new EnumSetting<>("Hostile ages",
94
        "Which hostile mobs by age.", Ages.BOTH)
95
        .describe(Ages.ADULTS, "Grown mobs only.")
96
        .describe(Ages.BABIES, "Baby zombies and piglins only.")
97
        .describe(Ages.BOTH, "Any age.")
98
        .under(hostile);
99
    private final BoolSetting slimes = new BoolSetting("Slimes",
100
        "Swing at slimes and magma cubes.", true)
101
        .under(hostile);
102
    private final BoolSetting shulkers = new BoolSetting("Shulkers",
103
        "Swing at shulkers.", true)
104
        .under(hostile);
105
    private final BoolSetting zombieVillagers = new BoolSetting("Zombie villagers",
106
        "Swing at zombie villagers so a cure is still possible.", true)
107
        .under(hostile);
108
    private final BoolSetting passive = new BoolSetting("Passive mobs",
109
        "Swing at animals and villagers and other harmless mobs.", false);
110
    private final EnumSetting<Ages> passiveAges = new EnumSetting<>("Passive ages",
111
        "Which passive mobs by age.", Ages.ADULTS)
112
        .describe(Ages.ADULTS, "Grown animals only.")
113
        .describe(Ages.BABIES, "Baby animals only.")
114
        .describe(Ages.BOTH, "Any age.")
115
        .under(passive);
116
    private final BoolSetting waterMobs = new BoolSetting("Water mobs",
117
        "Swing at fish and squid and dolphins.", true)
118
        .under(passive);
119
    private final BoolSetting bats = new BoolSetting("Bats",
120
        "Swing at bats.", true)
121
        .under(passive);
122
    private final BoolSetting villagers = new BoolSetting("Villagers",
123
        "Swing at villagers and wandering traders.", true)
124
        .under(passive);
125
    private final BoolSetting golems = new BoolSetting("Golems",
126
        "Swing at iron golems and snow golems and copper golems.", true)
127
        .under(passive);
128
    private final BoolSetting allays = new BoolSetting("Allays",
129
        "Swing at allays.", true)
130
        .under(passive);
131
    private final EnumSetting<Neutral> neutral = new EnumSetting<>("Neutral mobs",
132
        "Endermen and piglins and wolves and the like.", Neutral.WHEN_ANGRY)
133
        .describe(Neutral.ALWAYS, "Hit them like any other mob.")
134
        .describe(Neutral.WHEN_ANGRY, "Only hit them once they are angry.")
135
        .describe(Neutral.NEVER, "Leave them alone.")
136
        .under(hostile, () -> hostile.isOn() || passive.isOn());
137
    private final RegistryListSetting<EntityType<?>> extraMobs = new RegistryListSetting<>("Also hit",
138
        "Kinds of entity to hit whatever the switches above say.", BuiltInRegistries.ENTITY_TYPE, List.of());
139
    private final RegistryListSetting<EntityType<?>> ignoredMobs = new RegistryListSetting<>("Never hit",
140
        "Kinds of entity to leave alone whatever the switches above say.", BuiltInRegistries.ENTITY_TYPE, List.of());
141
    private final BoolSetting ignoreNamed = new BoolSetting("Ignore named",
142
        "Skip mobs wearing a name tag.", true)
143
        .under(hostile, () -> hostile.isOn() || passive.isOn());
144
    private final BoolSetting ignorePets = new BoolSetting("Ignore pets",
145
        "Skip tamed and saddled and trusting animals.", true)
146
        .under(hostile, () -> hostile.isOn() || passive.isOn());
147
    private final BoolSetting ignoreInvisible = new BoolSetting("Ignore invisible",
148
        "Skip anything you cannot see because it is invisible.", false);
149
    private final EnumSetting<TargetPriority> priority = TargetPriority.setting("Attacks", TargetPriority.NEAREST);
150
    private final NumberSetting maxTargets = new NumberSetting("Max targets",
151
        "How many entities to swing at in one go.", 1, 1, 8, 1);
152
153
    private final EnumSetting<Rotate> rotate = new EnumSetting<>("Rotate",
154
        "How you turn towards the target.", Rotate.ALWAYS)
155
        .describe(Rotate.NONE, "Never turns.")
156
        .describe(Rotate.ON_HIT, "A look packet only on the tick a hit goes out.")
157
        .describe(Rotate.ALWAYS, "Look packets follow the target the whole time. Your view stays put.")
158
        .describe(Rotate.CAMERA, "Turns your real view and only hits once the crosshair rests on the target.");
159
    private final NumberSetting rotateSpeed = new NumberSetting("Rotate speed",
160
        "How many degrees the turn may cover in one tick.", 45, 5, 180, 5, " degrees")
161
        .min(1).max(180)
162
        .under(rotate, Rotate.ON_HIT, Rotate.ALWAYS, Rotate.CAMERA);
163
164
    private final BoolSetting autoWeapon = new BoolSetting("Auto weapon",
165
        "Switches to your best weapon before each hit.", false);
166
    private final BoolSetting weaponSwapBack = new BoolSetting("Swap back",
167
        "Returns to the slot you had once the hit has gone out.", false)
168
        .under(autoWeapon);
169
    private final EnumSetting<Shields> shields = new EnumSetting<>("Shields",
170
        "What to do about a raised shield.", Shields.BREAK)
171
        .describe(Shields.NONE, "Hits the shield like anything else.")
172
        .describe(Shields.BREAK, "Reaches for an axe to knock the shield down.")
173
        .describe(Shields.IGNORE, "Leaves anyone blocking alone.");
174
    private final EnumSetting<Holding> holding = new EnumSetting<>("Attack when holding",
175
        "What has to be in your hand for a swing.", Holding.ANYTHING)
176
        .describe(Holding.ANYTHING, "Swings with whatever you hold.")
177
        .describe(Holding.WEAPONS, "Only swings whilst you hold one of the weapons below.");
178
    private final RegistryListSetting<Item> weapons = new RegistryListSetting<>("Weapons",
179
        "The items that count as a weapon.", BuiltInRegistries.ITEM, WEAPONS)
180
        .under(holding, Holding.WEAPONS);
181
    private final BoolSetting onlyOnClick = new BoolSetting("Only on click",
182
        "Only swing whilst you hold the attack key down.", false);
183
    private final BoolSetting ignoreCooldown = new BoolSetting("Ignore cooldown",
184
        "Swings before the attack cooldown ends. Hits land weaker but far more often.", false);
185
    private final NumberSetting switchDelay = new NumberSetting("Switch delay",
186
        "Ticks to wait after a hotbar swap before hitting.", 0, 0, 10, 1, " ticks");
187
    private final EnumSetting<SwingMode> swing = SwingMode.setting(SwingMode.BOTH);
188
189
    private final BoolSetting pauseOnUse = new BoolSetting("Pause on use",
190
        "Hold off whilst eating or blocking or drawing a bow or mining.", true);
191
    private final BoolSetting pauseOnContainers = new BoolSetting("Pause in containers",
192
        "No swinging whilst a chest or furnace is open. Your own inventory and the menus carry on.", true);
193
    private final BoolSetting pauseOnCrystals = new BoolSetting("Pause on crystals",
194
        "Stands aside whilst CrystalAura places or breaks.", true);
195
    private final BoolSetting pauseOnLag = new BoolSetting("Pause on lag",
196
        "Holds off whilst the server has stopped ticking.", true);
197
    private final BoolSetting showTarget = new BoolSetting("Show target",
198
        "Draws a box inside each target that shrinks and reddens as it loses health.", true);
199
200
    private final AttackTimer timer = new AttackTimer();
201
    private final SlotSwap slots = new SlotSwap();
202
    private final List<LivingEntity> targets = new ArrayList<>();
203
    private int switchTimer;
204
205
    public KillAura() {
206
        super("KillAura", "Automatically swings at nearby mobs and players.", Category.COMBAT);
207
        addSettings(range, wallsRange, walls, fov, onlyOnLook,
208
            players, ignoreCreative, ignoreSleeping, ignoreFlying, hostile, hostileAges,
209
            slimes, shulkers, zombieVillagers, passive, passiveAges, waterMobs, bats,
210
            villagers, golems, allays, neutral, extraMobs, ignoredMobs, ignoreNamed, ignorePets,
211
            ignoreInvisible, priority, maxTargets, rotate, rotateSpeed);
212
        addSettings(timer.settings());
213
        addSettings(autoWeapon, weaponSwapBack, shields, holding, weapons, onlyOnClick,
214
            ignoreCooldown, switchDelay, swing, pauseOnUse, pauseOnContainers, pauseOnCrystals,
215
            pauseOnLag, showTarget);
216
        searchTags("aura", "multi aura", "aimbot", "legit aura");
217
    }
218
219
    @Override
220
    public String getSuffix() {
221
        return targets.isEmpty() ? range.getValueString() : targets.getFirst().getName().getString();
222
    }
223
224
    // The entity being hit right now. Null between fights.
225
    public LivingEntity getTarget() {
226
        return targets.isEmpty() ? null : targets.getFirst();
227
    }
228
229
    @Override
230
    protected void onEnable() {
231
        timer.clear();
232
        slots.forget();
233
        switchTimer = 0;
234
        targets.clear();
235
    }
236
237
    @Override
238
    protected void onDisable() {
239
        targets.clear();
240
    }
241
242
    @Subscribe
243
    private void onPreMotion(PreMotionEvent event) {
244
        targets.clear();
245
        if (switchTimer > 0) {
246
            switchTimer--;
247
        }
248
        if (!inGame() || mc.player.isSpectator() || holdingFire()) {
249
            return;
250
        }
251
        targets.addAll(pickTargets());
252
        if (targets.isEmpty()) {
253
            return;
254
        }
255
        LivingEntity primary = targets.getFirst();
256
        if (rotate.is(Rotate.CAMERA)) {
257
            turnCamera(primary);
258
        } else if (rotate.is(Rotate.ALWAYS)) {
259
            RotationManager.look(aimPoint(primary), RotationPriority.ATTACK,
260
                RotationManager.ENTITY_TOLERANCE, rotateSpeed.getFloat());
261
        }
262
        if (timer.ready() && switchTimer == 0) {
263
            strike();
264
        }
265
    }
266
267
    // Every reason the aura sits this tick out.
268
    private boolean holdingFire() {
269
        if (pauseOnUse.isOn() && (mc.player.isUsingItem() || mc.gameMode.isDestroying())) {
270
            return true;
271
        }
272
        if (pauseOnContainers.isOn() && mc.gui.screen() instanceof AbstractContainerScreen
273
            && !(mc.gui.screen() instanceof InventoryScreen)
274
            && !(mc.gui.screen() instanceof CreativeModeInventoryScreen)) {
275
            return true;
276
        }
277
        if (onlyOnClick.isOn() && !mc.options.keyAttack.isDown()) {
278
            return true;
279
        }
280
        if (holding.is(Holding.WEAPONS) && !weapons.contains(mc.player.getMainHandItem().getItem())) {
281
            return true;
282
        }
283
        // Hits before the attack cooldown ends deal reduced damage.
284
        if (!ignoreCooldown.isOn() && mc.player.getAttackStrengthScale(0.5f) < 1) {
285
            return true;
286
        }
287
        if (pauseOnLag.isOn() && TickRate.INSTANCE.lagging(LAG_MILLIS)) {
288
            return true;
289
        }
290
        return Modules.eating() || (pauseOnCrystals.isOn() && crystalsBusy());
291
    }
292
293
    // Crystals hurt far more than a sword. Only the ticks around a real
294
    // place or break are given up.
295
    private boolean crystalsBusy() {
296
        CrystalAura crystals = Modules.active(CrystalAura.class);
297
        return crystals != null && crystals.isActing();
298
    }
299
300
    // Hits everything in reach on one swing then sets the next wait.
301
    private void strike() {
302
        LivingEntity primary = targets.getFirst();
303
        if (rotate.is(Rotate.CAMERA) && !crosshairOn(primary)) {
304
            return;
305
        }
306
        // The swing waits for the turn to land on the server.
307
        if (rotate.is(Rotate.ALWAYS) && !RotationManager.look(aimPoint(primary),
308
            RotationPriority.ATTACK, RotationManager.ENTITY_TOLERANCE, rotateSpeed.getFloat())) {
309
            return;
310
        }
311
        if (rotate.is(Rotate.ON_HIT)) {
312
            RotationManager.look(aimPoint(primary), RotationPriority.ATTACK,
313
                RotationManager.ENTITY_TOLERANCE, RotationManager.NO_STEP);
314
        }
315
        if (!selectWeapon(primary)) {
316
            return;
317
        }
318
        // One swing animation covers every entity hit on the tick.
319
        for (LivingEntity target : targets) {
320
            mc.gameMode.attack(mc.player, target);
321
        }
322
        swing.getValue().swing(InteractionHand.MAIN_HAND);
323
        if (weaponSwapBack.isOn()) {
324
            slots.restore();
325
        } else {
326
            slots.forget();
327
        }
328
        timer.spent();
329
    }
330
331
    private static Vec3 aimPoint(LivingEntity target) {
332
        return target.getBoundingBox().getCenter();
333
    }
334
335
    // Moves the real view towards the target by at most the turn speed.
336
    private void turnCamera(LivingEntity target) {
337
        Vec3 eye = mc.player.getEyePosition();
338
        Vec3 to = aimPoint(target).subtract(eye);
339
        double flat = Math.sqrt(to.x * to.x + to.z * to.z);
340
        float wantYaw = (float) Math.toDegrees(Math.atan2(to.z, to.x)) - 90f;
341
        float wantPitch = (float) -Math.toDegrees(Math.atan2(to.y, flat));
342
        float step = rotateSpeed.getFloat();
343
        float yaw = mc.player.getYRot() + Mth.clamp(Mth.wrapDegrees(wantYaw - mc.player.getYRot()), -step, step);
344
        float pitch = mc.player.getXRot() + Mth.clamp(wantPitch - mc.player.getXRot(), -step, step);
345
        mc.player.setYRot(yaw);
346
        mc.player.setXRot(Mth.clamp(pitch, -90f, 90f));
347
    }
348
349
    // True once the real crosshair rests on the target's box within reach.
350
    private boolean crosshairOn(LivingEntity target) {
351
        Vec3 eye = mc.player.getEyePosition();
352
        Vec3 look = mc.player.getViewVector(1f);
353
        Vec3 end = eye.add(look.scale(range.getValue()));
354
        return target.getBoundingBox().clip(eye, end).isPresent();
355
    }
356
357
    // Holds the best weapon for the target until the hit has landed.
358
    // False when a shield is up and the settings say to leave it be.
359
    private boolean selectWeapon(LivingEntity target) {
360
        boolean blocking = target.isBlocking();
361
        if (blocking && shields.is(Shields.IGNORE)) {
362
            return false;
363
        }
364
        if (!autoWeapon.isOn()) {
365
            return true;
366
        }
367
        // AutoWeapon and AttributeSwap keep the slot themselves.
368
        if (Modules.enabled(AutoWeapon.class) || Modules.enabled(AttributeSwap.class)) {
369
            return true;
370
        }
371
        // An axe staggers a raised shield whilst a sword bounces off it.
372
        int best = -1;
373
        if (blocking && shields.is(Shields.BREAK)) {
374
            best = AutoWeapon.bestAxeSlot(target, true);
375
        }
376
        if (best == -1) {
377
            best = AutoWeapon.bestWeaponSlot(target);
378
        }
379
        if (best != -1) {
380
            slots.select(best);
381
        }
382
        return true;
383
    }
384
385
    private List<LivingEntity> pickTargets() {
386
        List<LivingEntity> found = new ArrayList<>();
387
        if (onlyOnLook.isOn()) {
388
            if (mc.crosshairPickEntity instanceof LivingEntity living && wanted(living)) {
389
                found.add(living);
390
            }
391
            return found;
392
        }
393
        for (Entity entity : mc.level.entitiesForRendering()) {
394
            if (entity instanceof LivingEntity living && wanted(living)) {
395
                found.add(living);
396
            }
397
        }
398
        TargetPriority order = priority.getValue();
399
        found.sort((a, b) -> Double.compare(order.score(a), order.score(b)));
400
        int limit = maxTargets.getInt();
401
        return found.size() <= limit ? found : found.subList(0, limit);
402
    }
403
404
    private boolean wanted(LivingEntity living) {
405
        if (living == mc.player || !living.isAlive() || living.isSpectator()) {
406
            return false;
407
        }
408
        if (ignoredMobs.contains(living.getType()) || (ignoreInvisible.isOn() && living.isInvisible())) {
409
            return false;
410
        }
411
        double furthest = walls.isOn() ? Math.max(range.getValue(), wallsRange.getValue()) : range.getValue();
412
        double distance = EntityUtil.reachDistance(mc.player, living);
413
        if (distance > furthest || !inFov(living)) {
414
            return false;
415
        }
416
        boolean chosen = extraMobs.contains(living.getType());
417
        if (living instanceof Player player) {
418
            if (!chosen && !wantedPlayer(player)) {
419
                return false;
420
            }
421
        } else if (living instanceof Mob mob) {
422
            if (!chosen && !wantedMob(mob)) {
423
                return false;
424
            }
425
        } else if (!chosen) {
426
            return false;
427
        }
428
        // The line of sight raycast costs the most.
429
        boolean visible = canSee(living);
430
        if (!visible && !walls.isOn()) {
431
            return false;
432
        }
433
        return distance <= (visible ? range.getValue() : wallsRange.getValue());
434
    }
435
436
    private boolean wantedPlayer(Player player) {
437
        if (!players.isOn() || EntityUtil.isFriend(player)) {
438
            return false;
439
        }
440
        if (ignoreCreative.isOn() && player.isCreative()) {
441
            return false;
442
        }
443
        if (ignoreSleeping.isOn() && player.isSleeping()) {
444
            return false;
445
        }
446
        return ignoreFlying.getValue() <= 0 || !floating(player);
447
    }
448
449
    private boolean floating(Player player) {
450
        AABB box = player.getBoundingBox();
451
        return mc.level.noCollision(player, box.expandTowards(0, -ignoreFlying.getValue(), 0));
452
    }
453
454
    private boolean wantedMob(Mob mob) {
455
        if (ignoreNamed.isOn() && mob.hasCustomName()) {
456
            return false;
457
        }
458
        if (ignorePets.isOn() && EntityUtil.isPet(mob)) {
459
            return false;
460
        }
461
        if (!speciesAllowed(mob)) {
462
            return false;
463
        }
464
        if (EntityUtil.isNeutral(mob)) {
465
            if (neutral.is(Neutral.NEVER) || (neutral.is(Neutral.WHEN_ANGRY) && EntityUtil.isCalm(mob))) {
466
                return false;
467
            }
468
        }
469
        boolean hostileKind = EntityUtil.kindOf(mob) == EntityUtil.Kind.HOSTILE;
470
        if (hostileKind) {
471
            return hostile.isOn() && allowedAge(mob, hostileAges.getValue());
472
        }
473
        return passive.isOn() && allowedAge(mob, passiveAges.getValue());
474
    }
475
476
    // The switches that pick out one family from the wider hostile or passive group.
477
    private boolean speciesAllowed(Mob mob) {
478
        return switch (EntityUtil.speciesOf(mob)) {
479
            case WATER -> waterMobs.isOn();
480
            case BAT -> bats.isOn();
481
            case SLIME -> slimes.isOn();
482
            case SHULKER -> shulkers.isOn();
483
            case VILLAGER -> villagers.isOn();
484
            case ZOMBIE_VILLAGER -> zombieVillagers.isOn();
485
            case GOLEM -> golems.isOn();
486
            case ALLAY -> allays.isOn();
487
            case OTHER -> true;
488
        };
489
    }
490
491
    private static boolean allowedAge(Mob mob, Ages ages) {
492
        return switch (ages) {
493
            case ADULTS -> !mob.isBaby();
494
            case BABIES -> mob.isBaby();
495
            case BOTH -> true;
496
        };
497
    }
498
499
    // Either the head or the feet being visible is enough to land a hit.
500
    private boolean canSee(LivingEntity target) {
501
        if (mc.player.hasLineOfSight(target)) {
502
            return true;
503
        }
504
        Vec3 eye = mc.player.getEyePosition();
505
        Vec3 feet = target.position().add(0, 0.1, 0);
506
        return mc.level.clip(new ClipContext(eye, feet, ClipContext.Block.COLLIDER,
507
            ClipContext.Fluid.NONE, mc.player)).getType() == HitResult.Type.MISS;
508
    }
509
510
    private boolean inFov(LivingEntity target) {
511
        double limit = fov.getValue();
512
        return limit >= 360 || EntityUtil.lookAngleTo(target) <= limit / 2;
513
    }
514
515
    // A hotbar swap the server has to hear about before a hit is believed.
516
    @Subscribe
517
    private void onPacketSend(PacketSendEvent event) {
518
        if (event.getPacket() instanceof ServerboundSetCarriedItemPacket) {
519
            switchTimer = switchDelay.getInt();
520
        }
521
    }
522
523
    @Subscribe
524
    private void onRender3D(Render3DEvent event) {
525
        if (!showTarget.isOn() || targets.isEmpty()) {
526
            return;
527
        }
528
        for (LivingEntity target : targets) {
529
            float share = Math.clamp(EntityUtil.totalHealth(target) / EntityUtil.totalMaxHealth(target), 0f, 1f);
530
            AABB box = EntityUtil.lerpedBox(target, event.getPartialTicks());
531
            Vec3 centre = box.getCenter();
532
            AABB inner = new AABB(centre, centre).inflate(box.getXsize() / 2 * share,
533
                box.getYsize() / 2 * share, box.getZsize() / 2 * share);
534
            int color = ColorUtil.hsv(share * 120, 0.85f, 1f);
535
            event.getBatch().outlineBox(inner, color, true);
536
            event.getBatch().solidBox(inner, ColorUtil.withAlpha(color, 60), true);
537
        }
538
    }
539
}
540
CombatantCOMBATsrc/main/java/combatant/client/features/module/modules/combat/KillAura.javaJava · 1,242 lines · 47.0 KB
SettingskillauraRangekillauraReachModekillauraFovkillauraPrioritykillauraRaycastkillauraAttackModekillauraAcquireRangeIncrementkillauraWallRangekillauraCpsMinkillauraCpsMaxkillauraBreakShieldskillauraRotationTimingkillauraCorrectionTypekillauraProtocolModekillauraProtocolHeuristicskillauraSprintResetModekillauraCriticalskillauraRotationModelinearHorizontalMinlinearHorizontalMaxlinearVerticalMinlinearVerticalMaxsigmoidHorizontalMinsigmoidHorizontalMaxsigmoidVerticalMinsigmoidVerticalMaxsigmoidSteepnesssigmoidMidpointsmartYawMinsmartYawMaxsmartPitchMinsmartPitchMaxsmartSnapThresholdsmartJitterYawsmartJitterPitchsmartDecelerateEnabledsmartDecelerateAnglesmartDecelerateMinFactorkillauraRotationResetTickskillauraRotationResetThreshold
KillAura.javaJava · Minecraft 26.2 · 1,242 lines · 47.0 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Combatant Client distribution.
3
 * Copyright (c) 2026 pivosos2007.
4
 *
5
 * Licensed under the GNU General Public License v3.0.
6
 */
7
8
package combatant.client.features.module.modules.combat;
9
10
import combatant.client.config.values.*;
11
import combatant.client.util.combat.*;
12
import lombok.Getter;
13
import lombok.RequiredArgsConstructor;
14
import net.minecraft.client.Minecraft;
15
import net.minecraft.world.entity.Entity;
16
import net.minecraft.world.entity.LivingEntity;
17
import net.minecraft.world.entity.player.Player;
18
import net.minecraft.world.phys.AABB;
19
import net.minecraft.world.phys.Vec3;
20
import combatant.client.config.common.CommonSettingSchemas;
21
import combatant.client.config.common.impl.TargetFilters;
22
import combatant.client.events.EventHandler;
23
import combatant.client.events.impl.RotationUpdateEvent;
24
import combatant.client.events.impl.SprintControlEvent;
25
import combatant.client.features.module.Module;
26
import combatant.client.features.module.ModuleCategory;
27
import combatant.client.features.module.ModuleInfo;
28
import combatant.client.features.module.Modules;
29
import combatant.client.features.module.modules.movement.TargetStrafe;
30
import combatant.client.util.aiming.RotationManager;
31
import combatant.client.util.aiming.RotationTarget;
32
import combatant.client.util.aiming.data.Rotation;
33
import combatant.client.util.aiming.data.RotationWithVector;
34
import combatant.client.util.aiming.features.MovementCorrection;
35
import combatant.client.util.aiming.features.processors.LazyAimProcessor;
36
import combatant.client.util.aiming.features.processors.RotationProcessor;
37
import combatant.client.util.aiming.features.processors.ShakeAimProcessor;
38
import combatant.client.util.aiming.features.processors.anglesmooth.AngleSmooth;
39
import combatant.client.util.aiming.features.processors.anglesmooth.impl.LinearAngleSmooth;
40
import combatant.client.util.aiming.features.processors.anglesmooth.impl.SigmoidAngleSmooth;
41
import combatant.client.util.aiming.features.processors.anglesmooth.impl.SmartAngleSmooth;
42
import combatant.client.util.aiming.features.processors.anglesmooth.impl.SpookyAngleSmooth;
43
import combatant.client.util.aiming.point.PointInsideBox;
44
import combatant.client.util.aiming.point.PointTracker;
45
import combatant.client.util.aiming.preference.LeastDifferencePreference;
46
import combatant.client.util.aiming.preference.RotationPreference;
47
import combatant.client.util.aiming.raytrace.RotationRaytrace;
48
import combatant.client.util.click.AttackPressing;
49
import combatant.client.util.click.ClickScheduler;
50
import combatant.client.util.combat.protocol.CombatProtocolHeuristics;
51
import combatant.client.util.combat.protocol.ProtocolUtil;
52
import combatant.client.util.raycast.RaycastUtil;
53
import combatant.client.util.target.TargetManager;
54
import combatant.client.util.target.TargetingUtil;
55
import combatant.client.util.target.TargetingUtil.TargetingSettings;
56
57
import java.util.ArrayList;
58
import java.util.LinkedHashMap;
59
import java.util.List;
60
61
//todo Description
62
@ModuleInfo(
63
        id = "killaura",
64
        displayName = "KillAura",
65
        category = ModuleCategory.COMBAT
66
)
67
public class KillAura extends Module {
68
69
    private static final int MAX_CPS = 100;
70
    private static final String IGNORE_BOTS = "ignore_bots";
71
    private final Minecraft mc = Minecraft.getInstance();
72
    private final NumberValue<Double> range =
73
            numCommon(
74
                    "killauraRange",
75
                    "range",
76
                    CommonSettingSchemas.COMBAT_RANGE,
77
                    3.2,
78
                    1.0,
79
                    6.0
80
            );
81
    private final EnumValue<Reach.Mode> reachMode =
82
            enumCommon(
83
                    "killauraReachMode",
84
                    "reach_mode",
85
                    CommonSettingSchemas.COMBAT_REACH_MODE,
86
                    Reach.Mode.NORMAL,
87
                    Reach.Mode.values()
88
            );
89
    private final NumberValue<Float> fov =
90
            numCommon(
91
                    "killauraFov",
92
                    "fov",
93
                    CommonSettingSchemas.COMBAT_FOV,
94
                    180f,
95
                    30f,
96
                    180f
97
            );
98
    private final EnumValue<TargetingUtil.TargetPriority> priority =
99
            enumCommon(
100
                    "killauraPriority",
101
                    "priority",
102
                    CommonSettingSchemas.COMBAT_PRIORITY,
103
                    TargetingUtil.TargetPriority.DISTANCE,
104
                    TargetingUtil.TargetPriority.values()
105
            );
106
    private final EnumValue<RaycastMode> raycast =
107
            enumCommon(
108
                    "killauraRaycast",
109
                    "raycast",
110
                    CommonSettingSchemas.COMBAT_RAYCAST,
111
                    RaycastMode.STRICT,
112
                    RaycastMode.values()
113
            );
114
    private final ModeValue attackMode = modeCommon(
115
            "killauraAttackMode",
116
            "attack_mode",
117
            CommonSettingSchemas.COMBAT_ATTACK_MODE,
118
            CombatRotationModeUtil.MODE_ROTATIONS,
119
            CombatRotationModeUtil.MODE_ROTATIONS,
120
            CombatRotationModeUtil.MODE_NO_ROTATIONS
121
    );
122
    private final NumberValue<Double> acquireRangeIncrement =
123
            visibleWhen(numCommon(
124
                    "killauraAcquireRangeIncrement",
125
                    "range_increment",
126
                    CommonSettingSchemas.COMBAT_RANGE_INCREMENT,
127
                    1.5,
128
                    0.0,
129
                    3.0
130
            ), this::usesRotationSettings);
131
    private final NumberValue<Double> wallRange =
132
            visibleWhen(numCommon(
133
                    "killauraWallRange",
134
                    "wall_range",
135
                    CommonSettingSchemas.COMBAT_WALL_RANGE,
136
                    2.5,
137
                    0.0,
138
                    6.0
139
            ), this::usesRotationSettings);
140
    private final NumberValue<Integer> cpsMin =
141
            numCommon(
142
                    "killauraCpsMin",
143
                    "cps_min",
144
                    CommonSettingSchemas.COMBAT_CPS_MIN,
145
                    8,
146
                    1,
147
                    MAX_CPS
148
            );
149
    private final NumberValue<Integer> cpsMax =
150
            numCommon(
151
                    "killauraCpsMax",
152
                    "cps_max",
153
                    CommonSettingSchemas.COMBAT_CPS_MAX,
154
                    12,
155
                    1,
156
                    MAX_CPS
157
            );
158
    private final BooleanValue breakShields =
159
            boolCommon(
160
                    "killauraBreakShields",
161
                    "break_shields",
162
                    CommonSettingSchemas.COMBAT_BREAK_SHIELDS,
163
                    true
164
            );
165
    private final EnumValue<RotationTiming> rotationTiming =
166
            visibleWhen(enumCommon(
167
                    "killauraRotationTiming",
168
                    "rotation_timing",
169
                    CommonSettingSchemas.ROTATION_TIMING,
170
                    RotationTiming.NORMAL,
171
                    RotationTiming.values()
172
            ), this::usesRotationSettings);
173
    private final EnumValue<CorrectionType> correctionType =
174
            visibleWhen(enumCommon(
175
                    "killauraCorrectionType",
176
                    "correction_type",
177
                    CommonSettingSchemas.COMBAT_CORRECTION_TYPE,
178
                    CorrectionType.FOCUSED,
179
                    CorrectionType.values()
180
            ), this::usesRotationSettings);
181
    private final EnumValue<ProtocolMode> protocolMode =
182
            enumCommon(
183
                    "killauraProtocolMode",
184
                    "protocol_mode",
185
                    CommonSettingSchemas.COMBAT_PROTOCOL,
186
                    ProtocolMode.AUTO,
187
                    ProtocolMode.values()
188
            );
189
    private final BooleanMapValue protocolHeuristicSources =
190
            visibleWhen(protocolHeuristics(
191
                    "killauraProtocolHeuristics",
192
                    "protocol_heuristics",
193
                    CommonSettingSchemas.COMBAT_PROTOCOL_HEURISTICS
194
            ), () -> protocolMode.get() == ProtocolMode.AUTO);
195
    private final EnumValue<SprintResetMode> sprintResetMode =
196
            enumCommon(
197
                    "killauraSprintResetMode",
198
                    "sprint_reset_mode",
199
                    CommonSettingSchemas.COMBAT_SPRINT_RESET,
200
                    SprintResetMode.DEFAULT,
201
                    SprintResetMode.values()
202
            );
203
    private final EnumValue<Criticals.SelectionMode> criticalsSelection =
204
            visibleWhen(enumCommon(
205
                    "killauraCriticals",
206
                    "criticals",
207
                    CommonSettingSchemas.COMBAT_CRITICALS,
208
                    Criticals.SelectionMode.SMART,
209
                    Criticals.SelectionMode.values()
210
            ), () -> !isLegacyAttackProtocol());
211
    private final EnumValue<AngleSmoothMode> rotationMode =
212
            visibleWhen(enumCommon(
213
                    "killauraRotationMode",
214
                    "rotation_mode",
215
                    CommonSettingSchemas.ROTATION_MODE,
216
                    AngleSmoothMode.SMART,
217
                    AngleSmoothMode.values()
218
            ), this::usesRotationSettings);
219
    // Linear smoothing
220
    private final NumberValue<Float> linearHorMin =
221
            visibleWhen(numCommon(
222
                    "linearHorizontalMin",
223
                    "linear_horizontal_min",
224
                    CommonSettingSchemas.ANGLESMOOTH_HORIZONTAL_MIN,
225
                    180f,
226
                    0f,
227
                    180f
228
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.LINEAR);
229
    private final NumberValue<Float> linearHorMax =
230
            visibleWhen(numCommon(
231
                    "linearHorizontalMax",
232
                    "linear_horizontal_max",
233
                    CommonSettingSchemas.ANGLESMOOTH_HORIZONTAL_MAX,
234
                    180f,
235
                    0f,
236
                    180f
237
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.LINEAR);
238
    private final NumberValue<Float> linearVertMin =
239
            visibleWhen(numCommon(
240
                    "linearVerticalMin",
241
                    "linear_vertical_min",
242
                    CommonSettingSchemas.ANGLESMOOTH_VERTICAL_MIN,
243
                    180f,
244
                    0f,
245
                    180f
246
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.LINEAR);
247
    private final NumberValue<Float> linearVertMax =
248
            visibleWhen(numCommon(
249
                    "linearVerticalMax",
250
                    "linear_vertical_max",
251
                    CommonSettingSchemas.ANGLESMOOTH_VERTICAL_MAX,
252
                    180f,
253
                    0f,
254
                    180f
255
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.LINEAR);
256
    private final LinearAngleSmooth linearSmooth = new LinearAngleSmooth(
257
            linearHorMin, linearHorMax, linearVertMin, linearVertMax
258
    );
259
    // Sigmoid smoothing
260
    private final NumberValue<Float> sigmoidHorMin =
261
            visibleWhen(numCommon(
262
                    "sigmoidHorizontalMin",
263
                    "sigmoid_horizontal_min",
264
                    CommonSettingSchemas.ANGLESMOOTH_HORIZONTAL_MIN,
265
                    180f,
266
                    0f,
267
                    180f
268
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SIGMOID);
269
    private final NumberValue<Float> sigmoidHorMax =
270
            visibleWhen(numCommon(
271
                    "sigmoidHorizontalMax",
272
                    "sigmoid_horizontal_max",
273
                    CommonSettingSchemas.ANGLESMOOTH_HORIZONTAL_MAX,
274
                    180f,
275
                    0f,
276
                    180f
277
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SIGMOID);
278
    private final NumberValue<Float> sigmoidVertMin =
279
            visibleWhen(numCommon(
280
                    "sigmoidVerticalMin",
281
                    "sigmoid_vertical_min",
282
                    CommonSettingSchemas.ANGLESMOOTH_VERTICAL_MIN,
283
                    180f,
284
                    0f,
285
                    180f
286
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SIGMOID);
287
    private final NumberValue<Float> sigmoidVertMax =
288
            visibleWhen(numCommon(
289
                    "sigmoidVerticalMax",
290
                    "sigmoid_vertical_max",
291
                    CommonSettingSchemas.ANGLESMOOTH_VERTICAL_MAX,
292
                    180f,
293
                    0f,
294
                    180f
295
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SIGMOID);
296
    private final NumberValue<Float> sigmoidSteepness =
297
            visibleWhen(numCommon(
298
                    "sigmoidSteepness",
299
                    "sigmoid_steepness",
300
                    CommonSettingSchemas.ANGLESMOOTH_STEEPNESS,
301
                    10f,
302
                    0f,
303
                    20f
304
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SIGMOID);
305
    private final NumberValue<Float> sigmoidMidpoint =
306
            visibleWhen(numCommon(
307
                    "sigmoidMidpoint",
308
                    "sigmoid_midpoint",
309
                    CommonSettingSchemas.ANGLESMOOTH_MIDPOINT,
310
                    0.3f,
311
                    0f,
312
                    1f
313
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SIGMOID);
314
    private final SigmoidAngleSmooth sigmoidSmooth = new SigmoidAngleSmooth(
315
            sigmoidHorMin, sigmoidHorMax, sigmoidVertMin, sigmoidVertMax,
316
            sigmoidSteepness, sigmoidMidpoint
317
    );
318
    // Smart smoothing
319
    private final NumberValue<Float> smartYawMin =
320
            visibleWhen(numCommon(
321
                    "smartYawMin",
322
                    "smart_yaw_min",
323
                    CommonSettingSchemas.ANGLESMOOTH_YAW_MIN,
324
                    70f,
325
                    1f,
326
                    180f
327
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SMART);
328
    private final NumberValue<Float> smartYawMax =
329
            visibleWhen(numCommon(
330
                    "smartYawMax",
331
                    "smart_yaw_max",
332
                    CommonSettingSchemas.ANGLESMOOTH_YAW_MAX,
333
                    95f,
334
                    1f,
335
                    180f
336
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SMART);
337
    private final NumberValue<Float> smartPitchMin =
338
            visibleWhen(numCommon(
339
                    "smartPitchMin",
340
                    "smart_pitch_min",
341
                    CommonSettingSchemas.ANGLESMOOTH_PITCH_MIN,
342
                    45f,
343
                    1f,
344
                    180f
345
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SMART);
346
    private final NumberValue<Float> smartPitchMax =
347
            visibleWhen(numCommon(
348
                    "smartPitchMax",
349
                    "smart_pitch_max",
350
                    CommonSettingSchemas.ANGLESMOOTH_PITCH_MAX,
351
                    70f,
352
                    1f,
353
                    180f
354
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SMART);
355
    private final NumberValue<Float> smartSnapThreshold =
356
            visibleWhen(numCommon(
357
                    "smartSnapThreshold",
358
                    "smart_snap_threshold",
359
                    CommonSettingSchemas.ANGLESMOOTH_SNAP_THRESHOLD,
360
                    1.2f,
361
                    0.05f,
362
                    10.0f
363
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SMART);
364
    private final NumberValue<Float> smartJitterYaw =
365
            visibleWhen(numCommon(
366
                    "smartJitterYaw",
367
                    "smart_jitter_yaw",
368
                    CommonSettingSchemas.ANGLESMOOTH_JITTER_YAW,
369
                    0.8f,
370
                    0.0f,
371
                    6.0f
372
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SMART);
373
    private final NumberValue<Float> smartJitterPitch =
374
            visibleWhen(numCommon(
375
                    "smartJitterPitch",
376
                    "smart_jitter_pitch",
377
                    CommonSettingSchemas.ANGLESMOOTH_JITTER_PITCH,
378
                    0.4f,
379
                    0.0f,
380
                    4.0f
381
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SMART);
382
    private final BooleanValue smartDecelerateEnabled =
383
            visibleWhen(boolCommon(
384
                    "smartDecelerateEnabled",
385
                    "smart_decelerate_enabled",
386
                    CommonSettingSchemas.ANGLESMOOTH_DECELERATE_ENABLED,
387
                    true
388
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SMART);
389
    private final NumberValue<Float> smartDecelerateAngle =
390
            visibleWhen(numCommon(
391
                    "smartDecelerateAngle",
392
                    "smart_decelerate_angle",
393
                    CommonSettingSchemas.ANGLESMOOTH_DECELERATE_ANGLE,
394
                    35.0f,
395
                    1.0f,
396
                    120.0f
397
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SMART && smartDecelerateEnabled.get());
398
    private final NumberValue<Float> smartDecelerateMinFactor =
399
            visibleWhen(numCommon(
400
                    "smartDecelerateMinFactor",
401
                    "smart_decelerate_min_factor",
402
                    CommonSettingSchemas.ANGLESMOOTH_DECELERATE_MIN_FACTOR,
403
                    0.22f,
404
                    0.05f,
405
                    1.0f
406
            ), () -> usesRotationSettings() && rotationMode.get() == AngleSmoothMode.SMART && smartDecelerateEnabled.get());
407
    private final SmartAngleSmooth smartSmooth = new SmartAngleSmooth(
408
            smartYawMin, smartYawMax, smartPitchMin, smartPitchMax,
409
            smartSnapThreshold, smartJitterYaw, smartJitterPitch,
410
            smartDecelerateEnabled, smartDecelerateAngle, smartDecelerateMinFactor
411
    );
412
    private final NumberValue<Integer> rotationResetTicks =
413
            visibleWhen(numCommon(
414
                    "killauraRotationResetTicks",
415
                    "rotation_reset_ticks",
416
                    CommonSettingSchemas.ROTATION_RESET_TICKS,
417
                    2,
418
                    1,
419
                    20
420
            ), this::usesRotationSettings);
421
    private final NumberValue<Float> rotationResetThreshold =
422
            visibleWhen(numCommon(
423
                    "killauraRotationResetThreshold",
424
                    "rotation_reset_threshold",
425
                    CommonSettingSchemas.ROTATION_RESET_THRESHOLD,
426
                    2.0f,
427
                    0.1f,
428
                    15.0f
429
            ), this::usesRotationSettings);
430
    private final BooleanValue rotationThroughWalls =
431
            visibleWhen(boolCommon(
432
                    "killauraRotationThroughWalls",
433
                    "rotation_through_walls",
434
                    CommonSettingSchemas.ROTATION_THROUGH_WALLS,
435
                    false
436
            ), this::usesRotationSettings);
437
    private final ClickScheduler clicker = new ClickScheduler(cpsMin.get(), cpsMax.get());
438
    private final PointTracker pointTracker = new PointTracker();
439
    // Optional aim processors
440
    private final BooleanValue lazyAimEnabled =
441
            visibleWhen(boolCommon(
442
                    "lazyAimEnabled",
443
                    "lazy_aim_enabled",
444
                    CommonSettingSchemas.LAZY_AIM_ENABLED,
445
                    false
446
            ), this::usesRotationSettings);
447
    private final NumberValue<Float> lazyAimThreshold =
448
            visibleWhen(numCommon(
449
                    "lazyAimThreshold",
450
                    "lazy_aim_threshold",
451
                    CommonSettingSchemas.LAZY_AIM_THRESHOLD,
452
                    1.8f,
453
                    0.1f,
454
                    10.0f
455
            ), () -> usesRotationSettings() && lazyAimEnabled.get());
456
    private final NumberValue<Float> lazyAimFollowFactor =
457
            visibleWhen(numCommon(
458
                    "lazyAimFollowFactor",
459
                    "lazy_aim_follow_factor",
460
                    CommonSettingSchemas.LAZY_AIM_FOLLOW_FACTOR,
461
                    0.65f,
462
                    0.1f,
463
                    2.0f
464
            ), () -> usesRotationSettings() && lazyAimEnabled.get());
465
    private final LazyAimProcessor lazyAimProcessor = new LazyAimProcessor(lazyAimThreshold, lazyAimFollowFactor);
466
    private final BooleanValue shakeAimEnabled =
467
            visibleWhen(boolCommon(
468
                    "shakeAimEnabled",
469
                    "shake_aim_enabled",
470
                    CommonSettingSchemas.SHAKE_AIM_ENABLED,
471
                    false
472
            ), this::usesRotationSettings);
473
    private final NumberValue<Float> shakeAimYawAmplitude =
474
            visibleWhen(numCommon(
475
                    "shakeAimYawAmplitude",
476
                    "shake_aim_yaw_amplitude",
477
                    CommonSettingSchemas.SHAKE_AIM_YAW_AMPLITUDE,
478
                    0.6f,
479
                    0.0f,
480
                    5.0f
481
            ), () -> usesRotationSettings() && shakeAimEnabled.get());
482
    private final NumberValue<Float> shakeAimPitchAmplitude =
483
            visibleWhen(numCommon(
484
                    "shakeAimPitchAmplitude",
485
                    "shake_aim_pitch_amplitude",
486
                    CommonSettingSchemas.SHAKE_AIM_PITCH_AMPLITUDE,
487
                    0.3f,
488
                    0.0f,
489
                    3.0f
490
            ), () -> usesRotationSettings() && shakeAimEnabled.get());
491
    private final NumberValue<Float> shakeAimSpeed =
492
            visibleWhen(numCommon(
493
                    "shakeAimSpeed",
494
                    "shake_aim_speed",
495
                    CommonSettingSchemas.SHAKE_AIM_SPEED,
496
                    0.25f,
497
                    0.01f,
498
                    2.0f
499
            ), () -> usesRotationSettings() && shakeAimEnabled.get());
500
    private final ShakeAimProcessor shakeAimProcessor = new ShakeAimProcessor(
501
            shakeAimYawAmplitude, shakeAimPitchAmplitude, shakeAimSpeed
502
    );
503
    private final BooleanMapValue toggles = common(
504
            group("killaura_toggles", "toggles", targetFilterDefaults()),
505
            CommonSettingSchemas.TARGET_FILTERS.commonI18nKey()
506
    );
507
    private final SpookyAngleSmooth spookySmooth = new SpookyAngleSmooth();
508
    private LivingEntity currentTarget;
509
    private Vec3 lastAimPoint;
510
    private int lastAimEntityId = -1;
511
    private Rotation lastRotation;
512
    private int lastRotationTick = -1;
513
    private int lastAttackExecutionAge = -1;
514
515
    private static LinkedHashMap<String, Boolean> targetFilterDefaults() {
516
        LinkedHashMap<String, Boolean> defaults = new LinkedHashMap<>();
517
        defaults.put(TargetFilters.PLAYERS_ONLY, false);
518
        defaults.put(TargetFilters.IGNORE_FRIENDS, true);
519
        defaults.put(TargetFilters.IGNORE_STAFF, true);
520
        defaults.put(IGNORE_BOTS, true);
521
        defaults.put(TargetFilters.IGNORE_ENEMIES, false);
522
        defaults.put(TargetFilters.IGNORE_NAKED, false);
523
        defaults.put(TargetFilters.IGNORE_ENTITIES, true);
524
        return defaults;
525
    }
526
527
    private boolean usesRotationSettings() {
528
        return CombatRotationModeUtil.usesRotations(attackMode);
529
    }
530
531
    @Override
532
    public void onEnable() {
533
        clicker.reset();
534
        currentTarget = null;
535
        lastRotation = null;
536
        lastRotationTick = -1;
537
        SprintController.INSTANCE.clearSprintBlock();
538
    }
539
540
    @Override
541
    public void onDisable() {
542
        currentTarget = null;
543
        TargetManager.setPredictionTarget(null);
544
        TargetManager.setModuleTarget(null);
545
        AttributeSwap.clearAuraControlIfActive();
546
        clearRotationState(false);
547
        lastAttackExecutionAge = -1;
548
        SprintController.INSTANCE.clearSprintBlock();
549
    }
550
551
    @EventHandler(priority = 10)
552
    public void onRotationUpdate(RotationUpdateEvent event) {
553
        if (!isEnabled()) return;
554
        if (mc.player == null || mc.level == null) {
555
            clearTargetImmediate();
556
            return;
557
        }
558
559
        switch (event.getType()) {
560
            case PRE -> {
561
                if (isLegacyAttackProtocol()) {
562
                    clicker.setCps(cpsMin.get(), cpsMax.get());
563
                    clicker.tick();
564
                }
565
566
                TargetingSettings settings = new TargetingSettings(
567
                        getAcquireRange(),
568
                        fov.get(),
569
                        toggles.get(TargetFilters.PLAYERS_ONLY),
570
                        toggles.get(TargetFilters.IGNORE_FRIENDS),
571
                        toggles.get(TargetFilters.IGNORE_STAFF),
572
                        toggles.get(TargetFilters.IGNORE_ENEMIES),
573
                        toggles.get(TargetFilters.IGNORE_NAKED),
574
                        toggles.get(TargetFilters.IGNORE_ENTITIES),
575
                        false,
576
                        priority.get()
577
                );
578
579
                List<LivingEntity> targets = filterDynamicReachTargets(filterAntiBotTargets(TargetingUtil.findTargets(mc, settings)));
580
                syncPredictionTarget(targets);
581
                boolean currentTargetCandidate = isCurrentTargetCandidate(targets);
582
                if (CombatRotationModeUtil.isNoRotations(attackMode)) {
583
                    clearRotationState(true);
584
                    if (currentTargetCandidate && processLockedTargetNoRotations()) {
585
                        return;
586
                    }
587
                    for (LivingEntity target : targets) {
588
                        if (processTargetNoRotations(target)) {
589
                            setActiveTarget(target);
590
                            return;
591
                        }
592
                    }
593
594
                    clearTargetRuntime();
595
                    return;
596
                }
597
598
                if (currentTargetCandidate && processLockedTarget()) {
599
                    return;
600
                }
601
                for (LivingEntity target : targets) {
602
                    if (processTarget(target)) {
603
                        setActiveTarget(target);
604
                        return;
605
                    }
606
                }
607
608
                clearTargetRuntime();
609
            }
610
            case POST -> tryAttackPost();
611
        }
612
    }
613
614
    @Override
615
    public void onTick() {
616
        if (!isEnabled()) return;
617
        if (mc.player == null || mc.level == null) {
618
            clearTargetImmediate();
619
            return;
620
        }
621
622
        syncModuleTargetState();
623
    }
624
625
    private void tryAttackPost() {
626
        if (mc.player == null || mc.level == null) return;
627
        if (mc.player.tickCount == lastAttackExecutionAge) return;
628
629
        LivingEntity target = currentTarget;
630
        if (target == null) return;
631
632
        syncModuleTargetState();
633
634
        if (!isInRange(target)) return;
635
        boolean legacyProtocol = isLegacyAttackProtocol();
636
637
        if (CombatRotationModeUtil.usesRotations(attackMode)) {
638
            Rotation rotation = resolveAttackRotation(target);
639
            if (rotation == null) return;
640
            if (!passesRaycast(target, rotation.yaw(), rotation.pitch())) return;
641
        }
642
643
        int clickCount = CombatStrikeController.INSTANCE.resolveClickCount(clicker, legacyProtocol);
644
        if (clickCount <= 0) return;
645
646
        CombatStrikeController.SprintResetMode resetMode = resolveStrikeResetMode();
647
648
        boolean attacked = CombatStrikeController.INSTANCE.tryAttack(
649
                mc,
650
                target,
651
                legacyProtocol,
652
                clickCount,
653
                resetMode,
654
                true,
655
                () -> criticalHitAllowed(target)
656
        );
657
658
        if (!attacked) {
659
            return;
660
        }
661
662
        lastAttackExecutionAge = mc.player.tickCount;
663
664
        AttributeSwap.tryBreakShieldPostAttack(
665
                target,
666
                true,
667
                breakShields.get()
668
        );
669
    }
670
671
    public boolean willAttackInTicks(int ticks) {
672
        if (!isEnabled()) {
673
            return false;
674
        }
675
676
        int safeTicks = Math.max(0, ticks);
677
        if (isLegacyAttackProtocol()) {
678
            return clicker.willClickAt(safeTicks);
679
        }
680
681
        return AttackPressing.INSTANCE.willCooldownComplete(mc.player, currentTarget, false, safeTicks);
682
    }
683
684
    public ClickScheduler getClickScheduler() {
685
        return clicker;
686
    }
687
688
    public LivingEntity getCurrentTarget() {
689
        return currentTarget;
690
    }
691
692
    public boolean isNoRotationMode() {
693
        return isEnabled() && CombatRotationModeUtil.isNoRotations(attackMode);
694
    }
695
696
    public List<LivingEntity> findElytraTargetCandidates(double range, float fov) {
697
        if (!isEnabled() || mc.player == null || mc.level == null) {
698
            return List.of();
699
        }
700
701
        double safeRange = Math.max(1.0, range);
702
        float safeFov = Math.max(1.0f, Math.min(180.0f, fov));
703
        TargetingSettings settings = new TargetingSettings(
704
                safeRange,
705
                safeFov,
706
                toggles.get(TargetFilters.PLAYERS_ONLY),
707
                toggles.get(TargetFilters.IGNORE_FRIENDS),
708
                toggles.get(TargetFilters.IGNORE_STAFF),
709
                toggles.get(TargetFilters.IGNORE_ENEMIES),
710
                toggles.get(TargetFilters.IGNORE_NAKED),
711
                toggles.get(TargetFilters.IGNORE_ENTITIES),
712
                false,
713
                priority.get()
714
        );
715
716
        return filterAntiBotTargets(TargetingUtil.findTargets(mc, settings));
717
    }
718
719
    @EventHandler
720
    private void onSprintControl(SprintControlEvent event) {
721
        if (!isEnabled()) return;
722
        if (event.getSource() != SprintControlEvent.Source.MOVEMENT_TICK
723
                && event.getSource() != SprintControlEvent.Source.INPUT) {
724
            return;
725
        }
726
727
        if (shouldBlockSprinting(currentTarget)) {
728
            event.setSprint(false);
729
        }
730
    }
731
732
    private void clearTargetImmediate() {
733
        currentTarget = null;
734
        TargetManager.setPredictionTarget(null);
735
        TargetManager.setModuleTarget(null);
736
        AttributeSwap.clearAuraControlIfActive();
737
        SprintController.INSTANCE.clearSprintBlock();
738
        clearRotationState(false);
739
        lastAttackExecutionAge = -1;
740
    }
741
742
    private void clearTargetRuntime() {
743
        currentTarget = null;
744
        TargetManager.setPredictionTarget(null);
745
        TargetManager.setModuleTarget(null);
746
        AttributeSwap.handleAuraTarget(null, false);
747
        SprintController.INSTANCE.clearSprintBlock();
748
        lastAttackExecutionAge = -1;
749
        clearRotationState(true);
750
    }
751
752
    private boolean isCurrentTargetCandidate(List<LivingEntity> targets) {
753
        LivingEntity target = currentTarget;
754
        if (target == null || targets == null || targets.isEmpty()) {
755
            return false;
756
        }
757
        int targetId = target.getId();
758
        for (LivingEntity candidate : targets) {
759
            if (candidate != null && candidate.getId() == targetId) {
760
                return true;
761
            }
762
        }
763
        return false;
764
    }
765
766
    private void syncModuleTargetState() {
767
        LivingEntity target = currentTarget;
768
        if (target == null || !target.isAlive() || target.isRemoved()) {
769
            if (target != null) {
770
                clearTargetRuntime();
771
            } else {
772
                TargetManager.setModuleTarget(null);
773
            }
774
            return;
775
        }
776
777
        TargetManager.setModuleTarget(target);
778
    }
779
780
    private void syncPredictionTarget(List<LivingEntity> targets) {
781
        if (targets == null || targets.isEmpty()) {
782
            TargetManager.setPredictionTarget(null);
783
            return;
784
        }
785
786
        TargetManager.setPredictionTarget(targets.getFirst());
787
    }
788
789
    private List<LivingEntity> filterDynamicReachTargets(List<LivingEntity> targets) {
790
        if (!usesDynamicReach() || targets == null || targets.isEmpty() || mc.player == null) {
791
            return targets;
792
        }
793
794
        Vec3 eyePos = mc.player.getEyePosition();
795
        List<LivingEntity> filtered = new ArrayList<>(targets.size());
796
        for (LivingEntity target : targets) {
797
            double targetRange = getEffectiveAcquireRange(target);
798
            double distSq = TargetingUtil.distanceToEntityBoxSq(eyePos, target);
799
            if (distSq <= targetRange * targetRange) {
800
                filtered.add(target);
801
            }
802
        }
803
        return filtered;
804
    }
805
806
    private List<LivingEntity> filterAntiBotTargets(List<LivingEntity> targets) {
807
        if (!toggles.get(IGNORE_BOTS) || targets == null || targets.isEmpty()) {
808
            return targets;
809
        }
810
811
        List<LivingEntity> filtered = new ArrayList<>(targets.size());
812
        for (LivingEntity target : targets) {
813
            if (target instanceof Player player && AntiBotTracker.INSTANCE.isBot(player)) {
814
                continue;
815
            }
816
            filtered.add(target);
817
        }
818
        return filtered;
819
    }
820
821
    private void clearRotationState(boolean smoothReturn) {
822
        RotationManager.INSTANCE.release(this, smoothReturn);
823
        pointTracker.reset();
824
        lastAimPoint = null;
825
        lastAimEntityId = -1;
826
        lastRotation = null;
827
        lastRotationTick = -1;
828
    }
829
830
    private void setActiveTarget(LivingEntity target) {
831
        currentTarget = target;
832
        TargetManager.setPredictionTarget(null);
833
        TargetManager.setModuleTarget(target);
834
        AttributeSwap.handleAuraTarget(target, breakShields.get());
835
    }
836
837
    private boolean processLockedTargetNoRotations() {
838
        LivingEntity target = currentTarget;
839
        if (mc.player == null || target == null) return false;
840
        if (!target.isAlive() || target.isRemoved()) return false;
841
        double lockRange = getEffectiveAcquireRange(target);
842
        double distSq = TargetingUtil.distanceToEntityBoxSq(mc.player.getEyePosition(), target);
843
        if (distSq > lockRange * lockRange) return false;
844
        if (!processTargetNoRotations(target)) return false;
845
846
        setActiveTarget(target);
847
        return true;
848
    }
849
850
    private boolean processLockedTarget() {
851
        LivingEntity target = currentTarget;
852
        if (mc.player == null || target == null) return false;
853
        if (!target.isAlive() || target.isRemoved()) return false;
854
        double lockRange = getEffectiveAcquireRange(target);
855
        double distSq = TargetingUtil.distanceToEntityBoxSq(mc.player.getEyePosition(), target);
856
        if (distSq > lockRange * lockRange) return false;
857
        if (processTarget(target)) {
858
            setActiveTarget(target);
859
            return true;
860
        }
861
        return false;
862
    }
863
864
    private Rotation resolveAttackRotation(LivingEntity target) {
865
        if (mc.player == null) return null;
866
867
        Rotation rotation;
868
        RotationTiming timing = rotationTiming.get();
869
        if (timing == RotationTiming.ON_TICK) {
870
            rotation = lastRotationTick == mc.player.tickCount ? lastRotation : null;
871
            if (rotation == null) {
872
                RotationWithVector rot = findAttackRotation(target);
873
                if (rot == null) {
874
                    ElytraTarget elytraTarget = Modules.get(ElytraTarget.class);
875
                    if (elytraTarget != null && elytraTarget.canIgnoreKillAuraRotations()) {
876
                        Rotation current = RotationManager.INSTANCE.getCurrentRotation();
877
                        rotation = current != null ? current : new Rotation(mc.player.getYRot(), mc.player.getXRot(), true);
878
                    } else {
879
                        return null;
880
                    }
881
                } else {
882
                    rotation = rot.rotation();
883
                }
884
            }
885
        } else {
886
            Rotation current = RotationManager.INSTANCE.getCurrentRotation();
887
            if (current != null) {
888
                rotation = current;
889
            } else if (lastRotation != null && lastAimEntityId == target.getId()) {
890
                rotation = lastRotation;
891
            } else {
892
                RotationWithVector rot = findAttackRotation(target);
893
                if (rot == null) {
894
                    ElytraTarget elytraTarget = Modules.get(ElytraTarget.class);
895
                    if (elytraTarget != null && elytraTarget.canIgnoreKillAuraRotations()) {
896
                        Rotation server = RotationManager.INSTANCE.getServerRotation();
897
                        rotation = server;
898
                    } else {
899
                        return null;
900
                    }
901
                } else {
902
                    lastRotation = rot.rotation();
903
                    lastRotationTick = mc.player.tickCount;
904
                    rotation = rot.rotation();
905
                }
906
            }
907
        }
908
909
        return rotation != null ? rotation.normalize() : null;
910
    }
911
912
    private boolean processTarget(LivingEntity target) {
913
        double targetRange = getEffectiveAcquireRange(target);
914
        double targetWallRange = getEffectiveWallRange(target, targetRange);
915
        RotationWithVector rotation = findRotation(target, (float) targetRange, (float) targetWallRange);
916
        if (rotation == null) return false;
917
918
        lastRotation = rotation.rotation();
919
        lastRotationTick = mc.player != null ? mc.player.tickCount : -1;
920
921
        RotationTarget plan = buildRotationTarget(rotation.rotation(), target);
922
        RotationManager.INSTANCE.setRotationTarget(plan, 10, this);
923
        return true;
924
    }
925
926
    private RotationWithVector findAttackRotation(LivingEntity target) {
927
        double targetRange = getEffectiveAttackRange(target);
928
        double targetWallRange = getEffectiveWallRange(target, targetRange);
929
        return findRotation(target, (float) targetRange, (float) targetWallRange);
930
    }
931
932
    private boolean processTargetNoRotations(LivingEntity target) {
933
        double attackRange = getEffectiveAttackRange(target);
934
        boolean requireLineOfSight = raycast.get() == RaycastMode.STRICT;
935
        return CombatRotationModeUtil.canAttackWithoutRotations(mc, target, attackRange, requireLineOfSight);
936
    }
937
938
    private boolean isLegacyAttackProtocol() {
939
        return switch (protocolMode.get()) {
940
            case AUTO -> ProtocolUtil.isLegacyAttackProtocol(protocolHeuristicSources.getAll());
941
            case FORCE_1_8 -> true;
942
            case FORCE_1_9 -> false;
943
        };
944
    }
945
946
    private boolean isInRange(Entity target) {
947
        double distSq = TargetingUtil.distanceToEntityBoxSq(mc.player.getEyePosition(), target);
948
        double targetRange = getEffectiveAttackRange(target);
949
        return distSq <= targetRange * targetRange;
950
    }
951
952
    private boolean passesRaycast(Entity target, float yaw, float pitch) {
953
        ElytraTarget elytraTarget = Modules.get(ElytraTarget.class);
954
        if (elytraTarget != null && elytraTarget.canIgnoreKillAuraRotations()) {
955
            return true;
956
        }
957
958
        RaycastMode mode = raycast.get();
959
        if (mode == RaycastMode.NONE) return true;
960
961
        if (mc.player == null || target == null) {
962
            return false;
963
        }
964
965
        double attackRange = Math.max(0.0, getEffectiveAttackRange(target));
966
        double throughWallsRange = mode == RaycastMode.THROUGH_WALLS
967
                ? getEffectiveWallRange(target, attackRange)
968
                : 0.0;
969
970
        return RaycastUtil.isLookingAtEntity(
971
                mc.player,
972
                target,
973
                yaw,
974
                pitch,
975
                attackRange,
976
                throughWallsRange
977
        ) != null;
978
    }
979
980
    private boolean isLookingAtTargetBox(LivingEntity target, Rotation rotation) {
981
        if (mc.player == null || target == null || rotation == null) {
982
            return false;
983
        }
984
985
        Vec3 eyePos = mc.player.getEyePosition();
986
        Vec3 lookVec = rotation.directionVector();
987
        AABB targetBox = target.getBoundingBox();
988
        Vec3 endVec = eyePos.add(lookVec.scale(getEffectiveAttackRange(target)));
989
        return targetBox.contains(eyePos) || targetBox.clip(eyePos, endVec).isPresent();
990
    }
991
992
    private RotationWithVector findRotation(Entity target, float range, float wallsRange) {
993
        if (mc.player == null) return null;
994
        Vec3 eyes = mc.player.getEyePosition();
995
        pointTracker.setOptions(
996
                false,
997
                0,
998
                0,
999
                false,
1000
                0.0,
1001
                0.0,
1002
                false,
1003
                0.0,
1004
                0.0,
1005
                0,
1006
                0.15
1007
        );
1008
        Rotation initialRotation = RotationManager.INSTANCE.getCurrentRotation();
1009
        if (initialRotation == null) {
1010
            initialRotation = new Rotation(mc.player.getYRot(), mc.player.getXRot(), true);
1011
        }
1012
1013
        RaycastMode pointMode = raycast.get();
1014
        boolean ignoreWallsForPoint = pointMode == RaycastMode.NONE || pointMode == RaycastMode.THROUGH_WALLS;
1015
        PointInsideBox point = pointTracker.findPoint(
1016
                eyes,
1017
                target,
1018
                0,
1019
                initialRotation,
1020
                range,
1021
                ignoreWallsForPoint
1022
        );
1023
        AABB targetBox = point.box();
1024
1025
        RotationPreference preference = LeastDifferencePreference.leastDifferenceToLastPoint(eyes, point.pos());
1026
1027
        RotationWithVector rot = RotationRaytrace.raytraceBox(
1028
                eyes,
1029
                targetBox,
1030
                range,
1031
                wallsRange,
1032
                RotationRaytrace.OUTLINE_VISIBILITY,
1033
                preference,
1034
                true
1035
        );
1036
1037
        if (rot == null && rotationThroughWalls.get()) {
1038
            rot = RotationRaytrace.raytraceBox(
1039
                    eyes,
1040
                    targetBox,
1041
                    range,
1042
                    range,
1043
                    RotationRaytrace.OUTLINE_VISIBILITY,
1044
                    preference,
1045
                    true
1046
            );
1047
        }
1048
1049
        if (rot == null) {
1050
            Rotation fallback = Rotation.lookingAt(point.pos(), eyes).normalize();
1051
            rot = new RotationWithVector(fallback, point.pos());
1052
        }
1053
1054
        if (rot != null) {
1055
            lastAimPoint = rot.vec();
1056
            lastAimEntityId = target.getId();
1057
        }
1058
        return rot;
1059
    }
1060
1061
    private RotationTarget buildRotationTarget(Rotation rotation, Entity target) {
1062
        List<RotationProcessor> processors = new ArrayList<>();
1063
        AngleSmooth smooth = selectAngleSmooth();
1064
        if (smooth != null) {
1065
            processors.add(smooth);
1066
        }
1067
        boolean spookyMode = rotationMode.get() == AngleSmoothMode.SPOOKY;
1068
        if (!spookyMode && lazyAimEnabled.get()) {
1069
            processors.add(lazyAimProcessor);
1070
        }
1071
        if (!spookyMode && shakeAimEnabled.get()) {
1072
            processors.add(shakeAimProcessor);
1073
        }
1074
        boolean freeCorrection = correctionType.get() == CorrectionType.FREE;
1075
        MovementCorrection movementCorrection;
1076
        if (correctionType.get() == CorrectionType.NOT_VISIBLE) {
1077
            movementCorrection = MovementCorrection.OFF;
1078
        } else {
1079
            movementCorrection = MovementCorrection.SILENT;
1080
        }
1081
1082
        TargetStrafe targetStrafe = Modules.get(TargetStrafe.class);
1083
        if (freeCorrection && targetStrafe != null && targetStrafe.shouldDisableAuraFreeCorrection()) {
1084
            freeCorrection = false;
1085
        }
1086
1087
        return new RotationTarget(
1088
                rotation,
1089
                target,
1090
                processors,
1091
                rotationResetTicks.get(),
1092
                rotationResetThreshold.get(),
1093
                true,
1094
                movementCorrection,
1095
                freeCorrection,
1096
                null
1097
        );
1098
    }
1099
1100
    private boolean shouldBlockSprinting(LivingEntity target) {
1101
        ElytraTarget elytraTarget = Modules.get(ElytraTarget.class);
1102
        if (elytraTarget != null && elytraTarget.isRunning()) {
1103
            return false;
1104
        }
1105
        return false;
1106
    }
1107
1108
    public double getRange() {
1109
        return range.get();
1110
    }
1111
1112
    public double getAcquireRange() {
1113
        return range.get() + Math.max(0.0, acquireRangeIncrement.get());
1114
    }
1115
1116
    public boolean usesDynamicReach() {
1117
        return reachMode.get() == Reach.Mode.VULCAN_297;
1118
    }
1119
1120
    public double getEffectiveRange(Entity target) {
1121
        return getEffectiveAttackRange(target);
1122
    }
1123
1124
    private double getEffectiveAttackRange(Entity target) {
1125
        return resolveDynamicReach(target, range.get());
1126
    }
1127
1128
    private double getEffectiveAcquireRange(Entity target) {
1129
        return Math.max(0.0, getAcquireRange());
1130
    }
1131
1132
    private double getEffectiveWallRange(Entity target, double effectiveRange) {
1133
        double requestedWallRange = Math.max(0.0, wallRange.get());
1134
        return usesDynamicReach() && target instanceof Player
1135
                ? Math.min(requestedWallRange, Math.max(0.0, effectiveRange))
1136
                : requestedWallRange;
1137
    }
1138
1139
    private double resolveDynamicReach(Entity target, double requestedReach) {
1140
        double safeReach = Math.max(0.0, requestedReach);
1141
        if (usesDynamicReach() && target instanceof Player) {
1142
            return VulcanReachController.INSTANCE.clampReach(target, safeReach);
1143
        }
1144
        return safeReach;
1145
    }
1146
1147
    private boolean criticalHitAllowed(LivingEntity target) {
1148
        if (target == null || mc.player == null) return true;
1149
        if (isLegacyAttackProtocol()) return true;
1150
        if (mc.player.isFallFlying()) return true;
1151
1152
        Criticals criticals = Modules.get(Criticals.class);
1153
        if (criticals == null) return true;
1154
        ClickScheduler gateClicker = isLegacyAttackProtocol() ? clicker : null;
1155
        CombatStrikeController.SprintResetMode resolvedSprintReset =
1156
                CombatStrikeController.INSTANCE.resolveSprintResetMode(resolveStrikeResetMode());
1157
        boolean ignoreLocalSprintAfterReset = resolvedSprintReset != CombatStrikeController.SprintResetMode.NONE;
1158
        return criticals.shouldAttackForKillAura(
1159
                gateClicker,
1160
                target,
1161
                criticalsSelection.get(),
1162
                ignoreLocalSprintAfterReset
1163
        );
1164
    }
1165
1166
    private int calculateTicks(Rotation rotation) {
1167
        AngleSmooth smooth = selectAngleSmooth();
1168
        if (smooth == null) return 0;
1169
        Rotation base = RotationManager.INSTANCE.getServerRotation();
1170
        if (base == null) return 0;
1171
        return smooth.calculateTicks(base, rotation);
1172
    }
1173
1174
    private CombatStrikeController.SprintResetMode resolveStrikeResetMode() {
1175
        return switch (sprintResetMode.get()) {
1176
            case DEFAULT -> CombatStrikeController.SprintResetMode.DEFAULT;
1177
            case LEGIT -> CombatStrikeController.SprintResetMode.LEGIT;
1178
            case PACKET -> CombatStrikeController.SprintResetMode.PACKET;
1179
            case NONE -> CombatStrikeController.SprintResetMode.NONE;
1180
        };
1181
    }
1182
1183
    private AngleSmooth selectAngleSmooth() {
1184
        return switch (rotationMode.get()) {
1185
            case LINEAR -> linearSmooth;
1186
            case SIGMOID -> sigmoidSmooth;
1187
            case SMART -> smartSmooth;
1188
            case SPOOKY -> spookySmooth;
1189
            case NONE -> null;
1190
        };
1191
    }
1192
1193
    public enum RaycastMode {
1194
        NONE,
1195
        STRICT,
1196
        THROUGH_WALLS
1197
    }
1198
1199
    public enum RotationTiming {
1200
        NORMAL,
1201
        SNAP,
1202
        ON_TICK
1203
    }
1204
1205
    @Getter
1206
    @RequiredArgsConstructor
1207
    public enum AngleSmoothMode implements EnumValue.IdProvider {
1208
        LINEAR("Linear"),
1209
        SIGMOID("Sigmoid"),
1210
        SMART("Smart"),
1211
        SPOOKY("Spooky"),
1212
        NONE("None");
1213
1214
        private final String id;
1215
    }
1216
1217
    @Getter
1218
    @RequiredArgsConstructor
1219
    public enum ProtocolMode implements EnumValue.IdProvider {
1220
        AUTO("auto"),
1221
        FORCE_1_8("1.8"),
1222
        FORCE_1_9("1.9");
1223
1224
        private final String id;
1225
    }
1226
1227
    public enum SprintResetMode {
1228
        DEFAULT,
1229
        LEGIT,
1230
        PACKET,
1231
        NONE
1232
    }
1233
1234
    public enum CorrectionType {
1235
        FREE,
1236
        FOCUSED,
1237
        NOT_VISIBLE
1238
    }
1239
1240
    // attack handled by AttackUtil
1241
}
1242
NicotineCombatsrc/client/java/nicotine/mod/mods/combat/KillAura.javaJava · 121 lines · 5.1 KB
SettingsCombatUpdateSelectWeaponInAirOnlyPlayersHostileNeutralPassivePlusDelayLook
KillAura.javaJava · Minecraft 26.3 · 121 lines · 5.1 KB · complete file, verbatimOriginal ↗
1
package nicotine.mod.mods.combat;
2
3
import com.mojang.blaze3d.platform.InputConstants;
4
import net.minecraft.client.player.AbstractClientPlayer;
5
import net.minecraft.network.protocol.game.ServerboundPunchPacket;
6
import net.minecraft.tags.ItemTags;
7
import net.minecraft.world.entity.AgeableMob;
8
import net.minecraft.world.entity.Entity;
9
import net.minecraft.world.entity.NeutralMob;
10
import net.minecraft.world.entity.monster.Monster;
11
import net.minecraft.world.item.ItemStack;
12
import net.minecraft.world.item.MaceItem;
13
import net.minecraft.world.item.TridentItem;
14
import nicotine.events.ClientTickEvent;
15
import nicotine.mod.Mod;
16
import nicotine.mod.ModCategory;
17
import nicotine.mod.option.SliderOption;
18
import nicotine.mod.option.DropDownOption;
19
import nicotine.mod.option.ToggleOption;
20
import nicotine.util.EventBus;
21
import nicotine.util.Inventory;
22
import nicotine.util.Player;
23
24
import java.util.Arrays;
25
26
import static nicotine.util.Common.friendList;
27
import static nicotine.util.Common.mc;
28
29
public class KillAura extends Mod {
30
31
    private float delayLeft = 0.0f;
32
33
    private final ToggleOption combatUpdate = new ToggleOption("CombatUpdate");
34
    private final ToggleOption selectWeapon = new ToggleOption("SelectWeapon");
35
    private final ToggleOption inAirOnly = new ToggleOption("InAirOnly");
36
    private final ToggleOption players = new ToggleOption("Players");
37
    private final ToggleOption hostile = new ToggleOption("Hostile");
38
    private final ToggleOption angerable = new ToggleOption("Neutral");
39
    private final ToggleOption passive = new ToggleOption("Passive");
40
    private final SliderOption delay = new SliderOption(
41
            "PlusDelay",
42
            0,
43
            0,
44
            20
45
    );
46
    private final DropDownOption rotation = new DropDownOption("Look", new String[]{"Revert", "Stay", "Target", "None"});
47
48
    private static boolean isWeapon(ItemStack itemStack) {
49
        return itemStack.is(ItemTags.SWORDS) || itemStack.is(ItemTags.AXES) || itemStack.is(ItemTags.SPEARS) || itemStack.getItem() instanceof MaceItem || itemStack.getItem() instanceof TridentItem;
50
    }
51
52
    public KillAura() {
53
        super(ModCategory.Combat, "KillAura");
54
        this.keybind.keyCode = InputConstants.KEY_K;
55
        this.addOptions(Arrays.asList(combatUpdate, selectWeapon, inAirOnly, players, hostile, angerable, passive, rotation, delay));
56
    }
57
58
    @Override
59
    protected void init() {
60
        EventBus.register(ClientTickEvent.class, event -> {
61
            if (!this.enabled || mc.level == null)
62
                return true;
63
64
            for (Entity entity : mc.level.entitiesForRendering()) {
65
                if (
66
                        (entity instanceof AbstractClientPlayer && players.enabled && mc.player != entity) ||
67
                        (entity instanceof Monster && hostile.enabled && !(entity instanceof NeutralMob)) ||
68
                        (entity instanceof AgeableMob && passive.enabled) ||
69
                        (entity instanceof NeutralMob && angerable.enabled)
70
                ) {
71
                    if (mc.player.isWithinEntityInteractionRange(entity, 0) && entity.isAlive() && delayLeft <= 0 && !Player.isBusy() && !entity.isInvulnerable() && !friendList.contains(entity.getUUID())) {
72
73
                        if (mc.player.onGround() && inAirOnly.enabled)
74
                            return true;
75
76
                        if (selectWeapon.enabled && !isWeapon(mc.player.getInventory().getSelectedItem())) {
77
                            for (int i = 0; i < 9; i++) {
78
                                 if (isWeapon(mc.player.getInventory().getItem(i))) {
79
                                     Inventory.selectSlot(i);
80
                                     return true;
81
                                 }
82
                            }
83
                        }
84
85
                        switch (rotation.value) {
86
                            case "Revert":
87
                                Player.lookAndAttack(entity);
88
                                break;
89
                            case "Stay":
90
                                Player.lookAndAttack(entity, false);
91
                                break;
92
                            case "Target":
93
                                if (mc.crosshairPickEntity == entity) {
94
                                    Player.attack(entity);
95
                                    Player.swingHand();
96
                                    mc.player.connection.send(ServerboundPunchPacket.INSTANCE);
97
                                }
98
                                break;
99
                            case "None":
100
                                Player.attack(entity);
101
                                Player.swingHand();
102
                                mc.player.connection.send(ServerboundPunchPacket.INSTANCE);
103
                                break;
104
                        }
105
106
                        if (combatUpdate.enabled)
107
                            delayLeft = mc.player.getCurrentItemAttackStrengthDelay() + delay.value;
108
                        else
109
                            delayLeft = delay.value;
110
111
                    }
112
                }
113
            }
114
115
            delayLeft--;
116
117
            return true;
118
        });
119
    }
120
}
121
LiquidBounce (Kotlin)COMBATsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/combat/killaura/ModuleKillAura.ktKotlin · 476 lines · 18.8 KB

Automatically attacks enemies around you.

SettingsRaycastCriticalsKeepSprintIgnoreOpenInventorySimulateInventoryClosing
ModuleKillAura.ktKotlin · Minecraft 26.2 · 476 lines · 18.8 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
3
 *
4
 * Copyright (c) 2015 - 2026 CCBlueX
5
 *
6
 * LiquidBounce is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * LiquidBounce is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
package net.ccbluex.liquidbounce.features.module.modules.combat.killaura
20
21
import com.google.gson.JsonObject
22
import net.ccbluex.liquidbounce.config.types.list.Tagged
23
import net.ccbluex.liquidbounce.event.events.RotationUpdateEvent
24
import net.ccbluex.liquidbounce.event.events.SprintEvent
25
import net.ccbluex.liquidbounce.event.events.WorldRenderEvent
26
import net.ccbluex.liquidbounce.event.handler
27
import net.ccbluex.liquidbounce.event.tickHandler
28
import net.ccbluex.liquidbounce.features.module.ClientModule
29
import net.ccbluex.liquidbounce.features.module.ModuleCategories
30
import net.ccbluex.liquidbounce.features.module.modules.combat.ModuleAutoWeapon
31
import net.ccbluex.liquidbounce.features.module.modules.combat.criticals.ModuleCriticals.CriticalsSelectionMode
32
import net.ccbluex.liquidbounce.features.module.modules.combat.elytratarget.ModuleElytraTarget
33
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.KillAuraRotationsValueGroup.KillAuraRotationTiming.ON_TICK
34
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.KillAuraRotationsValueGroup.KillAuraRotationTiming.SNAP
35
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.ModuleKillAura.RaycastMode.TRACE_ALL
36
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.ModuleKillAura.RaycastMode.TRACE_NONE
37
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.ModuleKillAura.RaycastMode.TRACE_ONLYENEMY
38
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.features.KillAuraAutoBlock
39
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.features.KillAuraFailSwing
40
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.features.KillAuraFailSwing.dealWithFakeSwing
41
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.features.KillAuraFightBot
42
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.features.KillAuraNotifyWhenFail
43
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.features.KillAuraNotifyWhenFail.failedHits
44
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.features.KillAuraNotifyWhenFail.renderFailedHits
45
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.features.KillAuraRange
46
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.features.KillAuraRangeIndicator
47
import net.ccbluex.liquidbounce.features.module.modules.misc.debugrecorder.modes.GenericDebugRecorder
48
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug
49
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug.debugGeometry
50
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug.debugParameter
51
import net.ccbluex.liquidbounce.render.engine.type.Color4b
52
import net.ccbluex.liquidbounce.render.renderEnvironment
53
import net.ccbluex.liquidbounce.utils.aiming.RotationManager
54
import net.ccbluex.liquidbounce.utils.aiming.data.Rotation
55
import net.ccbluex.liquidbounce.utils.aiming.data.RotationWithVector
56
import net.ccbluex.liquidbounce.utils.aiming.point.PointTracker
57
import net.ccbluex.liquidbounce.utils.aiming.preference.LeastDifferencePreference
58
import net.ccbluex.liquidbounce.utils.aiming.utils.raytraceBox
59
import net.ccbluex.liquidbounce.utils.block.SwingMode
60
import net.ccbluex.liquidbounce.utils.combat.CombatManager
61
import net.ccbluex.liquidbounce.utils.combat.attackEntity
62
import net.ccbluex.liquidbounce.utils.combat.shouldBeAttacked
63
import net.ccbluex.liquidbounce.utils.entity.rotation
64
import net.ccbluex.liquidbounce.utils.entity.squaredBoxedDistanceTo
65
import net.ccbluex.liquidbounce.utils.inventory.InventoryManager.isInventoryOpen
66
import net.ccbluex.liquidbounce.utils.inventory.isInContainerScreen
67
import net.ccbluex.liquidbounce.utils.kotlin.Priority
68
import net.ccbluex.liquidbounce.utils.math.sq
69
import net.ccbluex.liquidbounce.utils.raytracing.findEntityInCrosshair
70
import net.ccbluex.liquidbounce.utils.raytracing.isLookingAtEntity
71
import net.ccbluex.liquidbounce.utils.render.TargetRenderer
72
import net.minecraft.client.gui.screens.inventory.ContainerScreen
73
import net.minecraft.world.entity.Entity
74
import net.minecraft.world.entity.LivingEntity
75
import net.minecraft.world.item.ItemStack
76
77
/**
78
 * KillAura module
79
 *
80
 * Automatically attacks enemies.
81
 */
82
@Suppress("MagicNumber")
83
object ModuleKillAura : ClientModule("KillAura", ModuleCategories.COMBAT) {
84
85
    // Attack speed
86
    val clicker = tree(KillAuraClicker)
87
    val range = tree(KillAuraRange)
88
    val targetTracker = tree(KillAuraTargetTracker)
89
90
    // Rotation
91
    private val rotations = tree(KillAuraRotationsValueGroup)
92
    private val pointTracker = tree(PointTracker(this))
93
94
    private val requires by multiEnumChoice<KillAuraRequirements>("Requires")
95
96
    private val requirementsMet
97
        get() = requires.all { it.asBoolean }
98
99
    // Bypass techniques
100
    internal val raycast by enumChoice("Raycast", TRACE_ALL)
101
    private val criticalsSelectionMode by enumChoice("Criticals", CriticalsSelectionMode.SMART)
102
    private val keepSprint by boolean("KeepSprint", true)
103
104
    // Inventory Handling
105
    internal val ignoreOpenInventory by boolean("IgnoreOpenInventory", true)
106
    internal val simulateInventoryClosing by boolean("SimulateInventoryClosing", true)
107
108
    /**
109
     * The use of suspend [waitTicks] is a bit too
110
     * risky for a large and complex module
111
     * such as KillAura. So back to the basics.
112
     */
113
    internal var waitTicks = 0
114
115
    init {
116
        tree(KillAuraAutoBlock)
117
        tree(TargetRenderer(this) {
118
            targetTracker.target?.takeUnless { ModuleElytraTarget.isSameTargetRendering(it) }
119
        })
120
        tree(KillAuraFailSwing)
121
        tree(KillAuraFightBot)
122
        tree(KillAuraRangeIndicator)
123
    }
124
125
    override fun onDisabled() {
126
        targetTracker.reset()
127
        failedHits.clear()
128
        KillAuraNotifyWhenFail.failedHitsIncrement = 0
129
    }
130
131
    @Suppress("unused")
132
    private val renderHandler = handler<WorldRenderEvent> { event ->
133
        event.renderEnvironment {
134
            renderFailedHits()
135
            KillAuraRangeIndicator.render(this, event.partialTicks)
136
        }
137
    }
138
139
    @Suppress("unused")
140
    private val rotationUpdateHandler = handler<RotationUpdateEvent> {
141
        if (waitTicks > 0) {
142
            waitTicks--
143
        }
144
145
        // Make sure killaura-logic is not running while inventory is open
146
        val isInInventoryScreen = isInventoryOpen || mc.gui.screen() is ContainerScreen
147
        val shouldResetTarget = player.isSpectator || player.isDeadOrDying || !requirementsMet
148
149
        if (isInInventoryScreen && !ignoreOpenInventory || shouldResetTarget) {
150
            // Reset current target
151
            targetTracker.reset()
152
            return@handler
153
        }
154
155
        // Update the current target tracker to make sure you attack the best enemy
156
        updateTarget()
157
158
        // Update Auto Weapon
159
        ModuleAutoWeapon.onTarget(targetTracker.target)
160
    }
161
162
    @Suppress("unused")
163
    private val gameHandler = tickHandler {
164
        if (player.isDeadOrDying || player.isSpectator) {
165
            return@tickHandler
166
        }
167
168
        // Check if there is target to attack
169
        val target = targetTracker.target
170
171
        if (CombatManager.shouldPauseCombat) {
172
            KillAuraAutoBlock.stopBlocking()
173
            return@tickHandler
174
        }
175
176
        if (target == null) {
177
            val hasUnblocked = KillAuraAutoBlock.stopBlocking()
178
179
            // Deal with fake swing when there is no target
180
            if (KillAuraFailSwing.enabled && requirementsMet) {
181
                if (hasUnblocked && KillAuraAutoBlock.pauseOnUnblockTicks > 0) {
182
                    waitTicks = KillAuraAutoBlock.pauseOnUnblockTicks
183
                } else {
184
                    dealWithFakeSwing(null)
185
                }
186
            }
187
            return@tickHandler
188
        }
189
190
        // Check if the module should (not) continue after the blocking state is updated
191
        if (!requirementsMet) {
192
            return@tickHandler
193
        }
194
195
        val rotation = (if (rotations.rotationTiming == ON_TICK) {
196
            findRotation(target, range.interactionRange, range.interactionThroughWallsRange)?.rotation
197
        } else {
198
            null
199
        } ?: RotationManager.currentRotation ?: player.rotation).normalize()
200
201
        val crosshairTarget = when {
202
            raycast != TRACE_NONE -> {
203
                findEntityInCrosshair(range.interactionRange.toDouble(), rotation, predicate = {
204
                    when (raycast) {
205
                        TRACE_ONLYENEMY -> it.shouldBeAttacked()
206
                        TRACE_ALL -> true
207
                        else -> false
208
                    }
209
                })?.entity ?: target
210
            }
211
            else -> target
212
        }
213
214
        if (crosshairTarget is LivingEntity && crosshairTarget.shouldBeAttacked() && crosshairTarget != target) {
215
            targetTracker.target = crosshairTarget
216
        }
217
218
        attackTarget(crosshairTarget, rotation)
219
    }
220
221
    val shouldBlockSprinting
222
        get() = !ModuleElytraTarget.running
223
            && criticalsSelectionMode.shouldStopSprinting(clicker, targetTracker.target)
224
225
    @Suppress("unused")
226
    private val sprintHandler = handler<SprintEvent> { event ->
227
        if (shouldBlockSprinting && (event.source == SprintEvent.Source.MOVEMENT_TICK ||
228
                event.source == SprintEvent.Source.INPUT)) {
229
            event.sprint = false
230
        }
231
    }
232
233
    @Suppress("CognitiveComplexMethod", "CyclomaticComplexMethod")
234
    private fun attackTarget(target: Entity, rotation: Rotation) {
235
        // Make it seem like we are blocking
236
        KillAuraAutoBlock.makeSeemBlock()
237
238
        debugParameter("Rotation") { rotation }
239
        debugParameter("Target") { target.scoreboardName }
240
241
        val attackHitResult = isLookingAtEntity(
242
            toEntity = target,
243
            rotation = rotation,
244
            range = range.interactionRange.toDouble(),
245
            throughWallsRange = range.interactionThroughWallsRange.toDouble()
246
        )
247
248
        debugParameter("Target Hit Result") { attackHitResult?.location }
249
250
        val isInRange = ModuleElytraTarget.canIgnoreKillAuraRotations ||
251
            attackHitResult != null && range.isInRange(pos = attackHitResult.location)
252
        debugParameter("Is In Range") { isInRange }
253
254
        // Check if our target is in range, otherwise deal with auto block
255
        if (!isInRange) {
256
            if (KillAuraAutoBlock.enabled && KillAuraAutoBlock.onScanRange &&
257
                player.squaredBoxedDistanceTo(target) <= range.scanRange.sq()) {
258
                if (KillAuraClicker.ticksSinceLastClick >= KillAuraAutoBlock.reblockTicks) {
259
                    KillAuraAutoBlock.startBlocking()
260
                }
261
262
                return
263
            }
264
265
            // Make sure we are not blocking
266
            val hasUnblocked = KillAuraAutoBlock.stopBlocking()
267
            if (hasUnblocked && KillAuraAutoBlock.pauseOnUnblockTicks > 0) {
268
                waitTicks = KillAuraAutoBlock.pauseOnUnblockTicks
269
            }else if (KillAuraFailSwing.enabled) {
270
                dealWithFakeSwing(target)
271
            }
272
            return
273
        }
274
275
        debugParameter("Valid Rotation") { rotation }
276
277
        val mainHandStack = player.mainHandItem
278
279
        // Attack enemy, according to the attack scheduler
280
        if (clicker.isClickTick && canAttackNow(target, mainHandStack) &&
281
            !KillAuraAutoBlock.isPrioritizingBlocking) {
282
            clicker.prepareForAttack(rotation) {
283
                // On each click, we check if we are still ready to attack
284
                if (!canAttackNow(target, mainHandStack)) {
285
                    return@prepareForAttack false
286
                }
287
288
                // Attack enemy
289
                attackEntity(target, SwingMode.DO_NOT_HIDE, keepSprint && !shouldBlockSprinting)
290
                range.update()
291
                KillAuraNotifyWhenFail.failedHitsIncrement = 0
292
                KillAuraAutoBlock.hasBlockedSinceAttack = false
293
294
                GenericDebugRecorder.recordDebugInfo(ModuleKillAura, "attackEntity", JsonObject().apply {
295
                    add("player", GenericDebugRecorder.debugObject(player))
296
                    add("targetPos", GenericDebugRecorder.debugObject(target))
297
                })
298
299
                true
300
            }
301
        } else if (KillAuraClicker.ticksSinceLastClick >= KillAuraAutoBlock.reblockTicks) {
302
            KillAuraAutoBlock.startBlocking()
303
        }
304
    }
305
306
    private fun updateTarget() {
307
        // Calculate maximum range based on enemy distance
308
        val maximumRange = if (targetTracker.closestSquaredEnemyDistance > range.interactionRange.sq()) {
309
            range.scanRange
310
        } else {
311
            range.interactionRange
312
        }
313
314
        debugParameter("Maximum Range") { maximumRange }
315
        debugParameter("Range") { range }
316
        val squaredMaxRange = maximumRange.sq()
317
        val squaredNormalRange = range.interactionRange.sq()
318
319
        // Find a suitable target
320
        val target = targetTracker.targets()
321
            .filter { entity -> entity.squaredBoxedDistanceTo(player) <= squaredMaxRange }
322
            .sortedBy { entity -> if (entity.squaredBoxedDistanceTo(player) <= squaredNormalRange) 0 else 1 }
323
            .firstOrNull { entity -> processTarget(entity, maximumRange, range.interactionThroughWallsRange) }
324
325
        if (target != null) {
326
            targetTracker.target = target
327
        } else if (KillAuraFightBot.enabled) {
328
            KillAuraFightBot.updateTarget()
329
330
            RotationManager.setRotationTarget(
331
                rotations.toRotationTarget(
332
                    KillAuraFightBot.getMovementRotation(),
333
                    considerInventory = !ignoreOpenInventory
334
                ),
335
                priority = Priority.IMPORTANT_FOR_USAGE_2,
336
                provider = ModuleKillAura
337
            )
338
        } else {
339
            targetTracker.reset()
340
        }
341
    }
342
343
    @Suppress("ReturnCount")
344
    private fun processTarget(
345
        entity: LivingEntity,
346
        range: Float,
347
        wallsRange: Float
348
    ): Boolean {
349
        val (rotation, _) = findRotation(entity, range, wallsRange) ?: return false
350
        val ticks = rotations.calculateTicks(rotation)
351
        debugParameter("Rotation Ticks") { ticks }
352
353
        when (rotations.rotationTiming) {
354
355
            // If our click scheduler is not going to click the moment we reach the target,
356
            // we should not start aiming towards the target just yet.
357
            SNAP -> if (!clicker.willClickAt(ticks.coerceAtLeast(1))) {
358
                return true
359
            }
360
361
            // [ON_TICK] will always instantly aim onto the target on attack, however, if
362
            // our rotation is unable to be ready in time, we can at least start aiming towards
363
            // the target.
364
            ON_TICK -> if (ticks <= 1) {
365
                return true
366
            }
367
368
            else -> {
369
                // Continue with regular aiming
370
            }
371
        }
372
373
        RotationManager.setRotationTarget(
374
            rotations.toRotationTarget(
375
                rotation,
376
                entity,
377
                considerInventory = !ignoreOpenInventory
378
            ),
379
            priority = Priority.IMPORTANT_FOR_USAGE_2,
380
            provider = this@ModuleKillAura
381
        )
382
        return true
383
    }
384
385
    /**
386
     * Get the best spot to attack the entity
387
     *
388
     * @param entity The entity to attack
389
     * @param range The range to attack the entity (NOT SQUARED)
390
     *
391
     *  @return The best spot to attack the entity
392
     */
393
    private fun findRotation(entity: Entity, range: Float, wallsRange: Float): RotationWithVector? {
394
        if (rotations.lazyRotation) {
395
            val currentRotation = RotationManager.currentRotation ?: player.rotation
396
            val currentHit = isLookingAtEntity(
397
                fromEntity = player,
398
                toEntity = entity,
399
                rotation = currentRotation,
400
                range = range.toDouble(),
401
                throughWallsRange = wallsRange.toDouble(),
402
            )
403
404
            if (currentHit != null) {
405
                debugParameter("Lazy Rotation") { true }
406
                return RotationWithVector(currentRotation, currentHit.location)
407
            }
408
        }
409
410
        debugParameter("Lazy Rotation") { false }
411
        val eyes = player.eyePosition
412
        val point = pointTracker.findPoint(eyes, entity)
413
414
        debugGeometry("Box") { ModuleDebug.DebuggedBox(point.box, Color4b.ORANGE.with(a = 90)) }
415
        debugGeometry("Point") { ModuleDebug.DebuggedPoint(point.pos, Color4b.WHITE, size = 0.1) }
416
417
        val rotationPreference = LeastDifferencePreference.leastDifferenceToLastPoint(eyes, point.pos)
418
419
        // raytrace to the point
420
        val rotation = raytraceBox(
421
            eyes = eyes,
422
            box = point.box,
423
            range = range.toDouble(),
424
            wallsRange = wallsRange.toDouble(),
425
            rotationPreference = rotationPreference
426
        )
427
428
        return if (rotation == null && rotations.aimThroughWalls) {
429
            val rotationThroughWalls = raytraceBox(
430
                eyes = eyes,
431
                box = point.box,
432
                // Since [range] is squared, we need to square root
433
                range = range.toDouble(),
434
                wallsRange = range.toDouble(),
435
                rotationPreference = rotationPreference
436
            )
437
438
            rotationThroughWalls
439
        } else {
440
            rotation
441
        }
442
    }
443
444
    /**
445
     * Check if we can attack the target at the current moment
446
     */
447
    internal fun canAttackNow(
448
        target: Entity? = null,
449
        itemStack: ItemStack = player.mainHandItem,
450
    ): Boolean {
451
        if (!itemStack.isItemEnabled(world.enabledFeatures())) {
452
            return false
453
        }
454
455
        if (player.cannotAttackWithItem(itemStack, 0)) {
456
            return false
457
        }
458
459
        val criticalHitAllowed = target == null || player.isFallFlying || criticalsSelectionMode.isCriticalHit(target)
460
        if (!criticalHitAllowed) {
461
            return false
462
        }
463
464
        val isInventoryBlockingAttack = (isInventoryOpen || isInContainerScreen) &&
465
            !ignoreOpenInventory && !simulateInventoryClosing
466
        return !isInventoryBlockingAttack
467
    }
468
469
    enum class RaycastMode(override val tag: String) : Tagged {
470
        TRACE_NONE("None"),
471
        TRACE_ONLYENEMY("Enemy"),
472
        TRACE_ALL("All")
473
    }
474
475
}
476