AutoTool module

AutoTool: Minecraft 26.3 cheat module, full source for every implementation (5 clients: MelaHack (ThunderHack fork), OfflineClient, Combatant, …).

5 implementationsPLAYERPlayerWORLD

Full module source: 5 implementations

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

MelaHack (ThunderHack fork)PLAYERsrc/main/java/thunder/hack/features/modules/player/AutoTool.javaJava · 88 lines · 3.9 KB

Automatically switches to the best tool.

SettingsSwapBackSaveItemSilentEchestSilk
AutoTool.javaJava · Minecraft 26.2 · 88 lines · 3.9 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.player;
2
3
import thunder.hack.features.modules.Module;
4
import thunder.hack.setting.Setting;
5
6
import java.util.ArrayList;
7
import java.util.List;
8
import net.minecraft.core.BlockPos;
9
import net.minecraft.core.registries.Registries;
10
import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket;
11
import net.minecraft.world.item.ItemStack;
12
import net.minecraft.world.item.enchantment.EnchantmentHelper;
13
import net.minecraft.world.item.enchantment.Enchantments;
14
import net.minecraft.world.level.block.AirBlock;
15
import net.minecraft.world.level.block.EnderChestBlock;
16
import net.minecraft.world.phys.BlockHitResult;
17
18
public class AutoTool extends Module {
19
    public static Setting<Boolean> swapBack = new Setting<>("SwapBack", true);
20
    public static Setting<Boolean> saveItem = new Setting<>("SaveItem", true);
21
    public static Setting<Boolean> silent = new Setting<>("Silent", false);
22
    public static Setting<Boolean> echestSilk = new Setting<>("EchestSilk", true);
23
    public static int itemIndex;
24
    private boolean swap;
25
    private long swapDelay;
26
    private final List<Integer> lastItem = new ArrayList<>();
27
28
    public AutoTool() {
29
        super("AutoTool", Category.PLAYER);
30
    }
31
32
    @Override
33
    public void onUpdate() {
34
        if (!(mc.hitResult instanceof BlockHitResult)) return;
35
        BlockHitResult result = (BlockHitResult) mc.hitResult;
36
        BlockPos pos = result.getBlockPos();
37
        if (mc.level.getBlockState(pos).isAir())
38
            return;
39
40
        if (getTool(pos) != -1 && mc.options.keyAttack.isDown()) {
41
            lastItem.add(mc.player.getInventory().getSelectedSlot());
42
43
            if (silent.getValue()) mc.player.connection.send(new ServerboundSetCarriedItemPacket(getTool(pos)));
44
            else mc.player.getInventory().setSelectedSlot(getTool(pos));
45
46
            itemIndex = getTool(pos);
47
            swap = true;
48
49
            swapDelay = System.currentTimeMillis();
50
        } else if (swap && !lastItem.isEmpty() && System.currentTimeMillis() >= swapDelay + 300 && swapBack.getValue()) {
51
            if (silent.getValue())
52
                mc.player.connection.send(new ServerboundSetCarriedItemPacket(lastItem.get(0)));
53
            else mc.player.getInventory().setSelectedSlot(lastItem.get(0));
54
55
            itemIndex = lastItem.get(0);
56
            lastItem.clear();
57
            swap = false;
58
        }
59
    }
60
61
    public static int getTool(final BlockPos pos) {
62
        int index = -1;
63
        float CurrentFastest = 1.0f;
64
        for (int i = 0; i < 9; ++i) {
65
            final ItemStack stack = mc.player.getInventory().getItem(i);
66
            if (stack != ItemStack.EMPTY) {
67
                if (!(mc.player.getInventory().getItem(i).getMaxDamage() - mc.player.getInventory().getItem(i).getDamageValue() > 10) && saveItem.getValue())
68
                    continue;
69
70
                final float digSpeed = EnchantmentHelper.getItemEnchantmentLevel(mc.level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT).getOrThrow(Enchantments.EFFICIENCY), stack);
71
                final float destroySpeed = stack.getDestroySpeed(mc.level.getBlockState(pos));
72
73
                if (mc.level.getBlockState(pos).getBlock() instanceof AirBlock) return -1;
74
                if (mc.level.getBlockState(pos).getBlock() instanceof EnderChestBlock && echestSilk.getValue()) {
75
                    if (EnchantmentHelper.getItemEnchantmentLevel(mc.level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT).getOrThrow(Enchantments.SILK_TOUCH), stack) > 0 && digSpeed + destroySpeed > CurrentFastest) {
76
                        CurrentFastest = digSpeed + destroySpeed;
77
                        index = i;
78
                    }
79
                } else if (digSpeed + destroySpeed > CurrentFastest) {
80
                    CurrentFastest = digSpeed + destroySpeed;
81
                    index = i;
82
                }
83
            }
84
        }
85
        return index;
86
    }
87
}
88
OfflineClientPLAYERsrc/main/java/com/jellypudding/offlineclient/modules/player/AutoTool.javaJava · 270 lines · 11.1 KB

Switches to your best tool when you mine something.

SettingsSearch inventoryPreferFortune on oresSilk touch on ender chestsSwitch backSwitch delayAnti breakRetire atUse swordsUse handsTool filterTools
AutoTool.javaJava · Minecraft 26.2 · 270 lines · 11.1 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.player;
2
3
import com.jellypudding.offlineclient.event.Subscribe;
4
import com.jellypudding.offlineclient.event.events.BlockBreakEvent;
5
import com.jellypudding.offlineclient.event.events.TickEvent;
6
import com.jellypudding.offlineclient.module.Category;
7
import com.jellypudding.offlineclient.module.Module;
8
import com.jellypudding.offlineclient.modules.combat.AutoWeapon;
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.BlockUtil;
14
import com.jellypudding.offlineclient.util.InventoryUtil;
15
import com.jellypudding.offlineclient.util.ItemUtil;
16
import com.jellypudding.offlineclient.util.Modules;
17
import net.minecraft.core.BlockPos;
18
import net.minecraft.core.registries.BuiltInRegistries;
19
import net.minecraft.resources.ResourceKey;
20
import net.minecraft.tags.ItemTags;
21
import net.minecraft.world.item.Item;
22
import net.minecraft.world.item.ItemStack;
23
import net.minecraft.world.item.enchantment.Enchantment;
24
import net.minecraft.world.item.enchantment.Enchantments;
25
import net.minecraft.world.level.block.Blocks;
26
import net.minecraft.world.level.block.CropBlock;
27
import net.minecraft.world.level.block.state.BlockState;
28
29
import java.util.List;
30
31
public final class AutoTool extends Module {
32
33
    // Speed outranks every enchantment. The bonuses only break a tie.
34
    private static final double SPEED_WEIGHT = 1000;
35
    private static final double PREFERRED_WEIGHT = 10;
36
37
    // What a bare hand scores against any block.
38
    private static final double HAND_SCORE = SPEED_WEIGHT;
39
40
    public enum Prefer { NONE, FORTUNE, SILK_TOUCH }
41
42
    public enum Filter { OFF, ALLOW, BLOCK }
43
44
    private final BoolSetting fromInventory = new BoolSetting("Search inventory",
45
        "Also borrows a better tool from the rest of your inventory and puts it back afterwards.",
46
        false);
47
    private final EnumSetting<Prefer> prefer = new EnumSetting<>("Prefer",
48
        "Which enchantment wins between tools of the same speed on any block.", Prefer.FORTUNE)
49
        .describe(Prefer.NONE, "Speed alone decides.")
50
        .describe(Prefer.FORTUNE, "A Fortune tool wins a tie on any block.")
51
        .describe(Prefer.SILK_TOUCH, "A Silk Touch tool wins a tie on any block such as glass or ice.");
52
    private final BoolSetting fortune = new BoolSetting("Fortune on ores",
53
        "Takes a Fortune tool for ores and crops even when a plain one is faster.", true);
54
    private final BoolSetting silkTouch = new BoolSetting("Silk touch on ender chests",
55
        "Takes a Silk Touch pickaxe for an ender chest. It then drops whole.", true);
56
    private final BoolSetting switchBack = new BoolSetting("Switch back",
57
        "Returns to the slot you had once you stop mining.", true);
58
    private final NumberSetting switchDelay = new NumberSetting("Switch delay",
59
        "Ticks to keep mining with what you hold before the tool is switched.", 0, 0, 20, 1, " ticks")
60
        .min(0);
61
    private final BoolSetting antiBreak = new BoolSetting("Anti break",
62
        "Never picks a nearly broken tool and drops one that wears out mid swing.", true);
63
    private final NumberSetting breakMargin = new NumberSetting("Retire at",
64
        "A tool with this much durability or less counts as nearly broken.", 10, 1, 100, 1, "%")
65
        .min(1).max(100)
66
        .under(antiBreak);
67
    private final BoolSetting swords = new BoolSetting("Use swords",
68
        "A sword counts as a tool. Cobwebs and bamboo cut far faster with one.", false);
69
    private final BoolSetting hands = new BoolSetting("Use hands",
70
        "Switches to an empty slot when nothing beats a bare hand.", false);
71
    private final EnumSetting<Filter> filter = new EnumSetting<>("Tool filter",
72
        "Which tools may be picked.", Filter.OFF)
73
        .describe(Filter.OFF, "Every tool may be picked.")
74
        .describe(Filter.ALLOW, "Only the listed tools may be picked.")
75
        .describe(Filter.BLOCK, "The listed tools are never picked.");
76
    private final RegistryListSetting<Item> tools = new RegistryListSetting<>("Tools",
77
        "The tools the filter applies to. Click to pick them.", BuiltInRegistries.ITEM, List.of())
78
        .under(filter, Filter.ALLOW, Filter.BLOCK);
79
80
    private final InventoryUtil.HotbarLoan loan = new InventoryUtil.HotbarLoan();
81
82
    private boolean wasDestroying;
83
84
    // The block being mined and how many ticks it has taken up to now.
85
    private BlockPos breaking;
86
    private int breakTicks;
87
88
    public AutoTool() {
89
        super("AutoTool", "Switches to your best tool when you mine something.", Category.PLAYER);
90
        addSettings(fromInventory, prefer, fortune, silkTouch, switchBack, switchDelay, antiBreak,
91
            breakMargin, swords, hands, filter, tools);
92
        searchTags("tool", "pickaxe", "best tool", "fortune", "silk touch");
93
    }
94
95
    @Override
96
    protected void onDisable() {
97
        restore();
98
        wasDestroying = false;
99
        breaking = null;
100
    }
101
102
    @Subscribe
103
    private void onTick(TickEvent event) {
104
        if (!inGame() || mc.gameMode == null || mc.player.isDeadOrDying()) {
105
            // Respawn hands out a fresh inventory.
106
            loan.forget();
107
            wasDestroying = false;
108
            return;
109
        }
110
        boolean destroying = mc.gameMode.isDestroying();
111
        // A loan that could not go home earlier gets another go every tick.
112
        if (!destroying && (wasDestroying || loan.isLent())) {
113
            restore();
114
        }
115
        if (!destroying) {
116
            breaking = null;
117
        }
118
        wasDestroying = destroying;
119
    }
120
121
    @Subscribe
122
    private void onBlockBreak(BlockBreakEvent event) {
123
        if (!inGame() || mc.player.isSpectator()) {
124
            return;
125
        }
126
        // AutoWeapon drives the same hand.
127
        if (weaponBusy()) {
128
            return;
129
        }
130
        if (!countBreakTicks(event.getPos())) {
131
            return;
132
        }
133
        BlockState state = mc.level.getBlockState(event.getPos());
134
        int selected = InventoryUtil.selectedSlot();
135
        ItemStack held = mc.player.getInventory().getItem(selected);
136
        int slots = fromInventory.isOn() ? InventoryUtil.WHOLE_INVENTORY : InventoryUtil.HOTBAR_SIZE;
137
138
        int best = enchantedPick(state, slots);
139
        if (best == -1) {
140
            boolean heldWornOut = antiBreak.isOn() && isNearlyBroken(held);
141
            double floor = heldWornOut ? HAND_SCORE : score(held, state);
142
            best = bestSlot(state, floor, slots);
143
            // A tool about to snap is worth leaving even for a bare hand.
144
            if (best == -1 && heldWornOut) {
145
                best = InventoryUtil.freeHotbarSlot();
146
            }
147
        }
148
        // Nothing better than a hand and the hand itself is better than what is held.
149
        if (best == -1 && hands.isOn() && ItemUtil.miningSpeed(held, state) <= 1
150
            && !held.isEmpty()) {
151
            best = InventoryUtil.freeHotbarSlot();
152
        }
153
        if (best == -1 || best == selected) {
154
            return;
155
        }
156
        loan.select(best);
157
    }
158
159
    // True once the block has been mined for the switch delay.
160
    private boolean countBreakTicks(BlockPos pos) {
161
        if (!pos.equals(breaking)) {
162
            breaking = pos.immutable();
163
            breakTicks = 0;
164
        } else {
165
            breakTicks++;
166
        }
167
        return breakTicks >= switchDelay.getInt();
168
    }
169
170
    // The enchantment a block deserves outranks raw speed. Ores and crops want
171
    // Fortune and an ender chest wants Silk Touch. Minus one when nothing carries it.
172
    private int enchantedPick(BlockState state, int slots) {
173
        ResourceKey<Enchantment> wanted = null;
174
        if (silkTouch.isOn() && state.is(Blocks.ENDER_CHEST)) {
175
            wanted = Enchantments.SILK_TOUCH;
176
        } else if (fortune.isOn() && (BlockUtil.isOre(state) || state.getBlock() instanceof CropBlock)) {
177
            wanted = Enchantments.FORTUNE;
178
        }
179
        if (wanted == null) {
180
            return -1;
181
        }
182
        int best = -1;
183
        int bestLevel = 0;
184
        double bestScore = HAND_SCORE;
185
        for (int i = 0; i < slots; i++) {
186
            ItemStack stack = mc.player.getInventory().getItem(i);
187
            if (!allowed(stack)) {
188
                continue;
189
            }
190
            int level = ItemUtil.enchantLevel(wanted, stack);
191
            double score = score(stack, state);
192
            // Real tools for the block only. Level wins first and score breaks a tie.
193
            if (level == 0 || score <= HAND_SCORE) {
194
                continue;
195
            }
196
            if (level > bestLevel || (level == bestLevel && score > bestScore)) {
197
                bestLevel = level;
198
                bestScore = score;
199
                best = i;
200
            }
201
        }
202
        return best;
203
    }
204
205
    // The real tool that scores above the floor. Minus one when none does.
206
    private int bestSlot(BlockState state, double floor, int slots) {
207
        int best = -1;
208
        double bestScore = Math.max(floor, HAND_SCORE);
209
        for (int i = 0; i < slots; i++) {
210
            ItemStack stack = mc.player.getInventory().getItem(i);
211
            if (!allowed(stack)) {
212
                continue;
213
            }
214
            double score = score(stack, state);
215
            if (score > bestScore) {
216
                bestScore = score;
217
                best = i;
218
            }
219
        }
220
        return best;
221
    }
222
223
    // Speed first. The preferred enchantment and then the durability
224
    // enchantments only separate tools that mine at the same speed.
225
    private double score(ItemStack stack, BlockState state) {
226
        double score = ItemUtil.miningSpeed(stack, state) * SPEED_WEIGHT;
227
        if (score <= HAND_SCORE) {
228
            return HAND_SCORE;
229
        }
230
        ResourceKey<Enchantment> preferred = switch (prefer.getValue()) {
231
            case NONE -> null;
232
            case FORTUNE -> Enchantments.FORTUNE;
233
            case SILK_TOUCH -> Enchantments.SILK_TOUCH;
234
        };
235
        if (preferred != null) {
236
            score += ItemUtil.enchantLevel(preferred, stack) * PREFERRED_WEIGHT;
237
        }
238
        return score + ItemUtil.enchantLevel(Enchantments.UNBREAKING, stack)
239
            + ItemUtil.enchantLevel(Enchantments.MENDING, stack);
240
    }
241
242
    private boolean allowed(ItemStack stack) {
243
        if (antiBreak.isOn() && isNearlyBroken(stack)) {
244
            return false;
245
        }
246
        if (!swords.isOn() && stack.is(ItemTags.SWORDS)) {
247
            return false;
248
        }
249
        return switch (filter.getValue()) {
250
            case OFF -> true;
251
            case ALLOW -> tools.contains(stack.getItem());
252
            case BLOCK -> !tools.contains(stack.getItem());
253
        };
254
    }
255
256
    private boolean weaponBusy() {
257
        AutoWeapon weapon = Modules.get(AutoWeapon.class);
258
        return weapon != null && weapon.isHoldingWeapon();
259
    }
260
261
    // The old slot only comes back if the player has not picked another since.
262
    private void restore() {
263
        loan.giveBack(switchBack.isOn() && loan.stillMine());
264
    }
265
266
    private boolean isNearlyBroken(ItemStack stack) {
267
        return ItemUtil.wornBelow(stack, breakMargin.getValue() / 100);
268
    }
269
}
270
CombatantPLAYERsrc/main/java/combatant/client/features/module/modules/player/AutoTool.javaJava · 107 lines · 3.7 KB
SettingsautoToolRestoreDelayMs
AutoTool.javaJava · Minecraft 26.2 · 107 lines · 3.7 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.player;
9
10
import net.minecraft.client.Minecraft;
11
import net.minecraft.core.BlockPos;
12
import net.minecraft.world.item.ItemStack;
13
import net.minecraft.world.level.block.state.BlockState;
14
import combatant.client.config.values.NumberValue;
15
import combatant.client.events.EventHandler;
16
import combatant.client.events.impl.GameTickEvent;
17
import combatant.client.features.module.Module;
18
import combatant.client.features.module.ModuleCategory;
19
import combatant.client.features.module.ModuleInfo;
20
import combatant.client.mixins.accessors.MultiPlayerGameModeAccessor;
21
import combatant.client.mixins.accessors.PlayerInventoryAccessor;
22
import combatant.client.util.player.inventory.InventorySwap;
23
24
//todo Description
25
@ModuleInfo(
26
        id = "autotool",
27
        displayName = "AutoTool",
28
        category = ModuleCategory.PLAYER
29
)
30
public class AutoTool extends Module {
31
32
    private static final String SETTING_RESTORE_DELAY = "restore_delay_ms";
33
    private final NumberValue<Integer> restoreDelayMs =
34
            num("autoToolRestoreDelayMs", SETTING_RESTORE_DELAY, 300, 0, 1000);
35
36
    private final Minecraft mc = Minecraft.getInstance();
37
38
    private int originalSlot = -1;
39
    private long lastBreakMs = 0L;
40
41
    @Override
42
    public void onDisable() {
43
        if (mc != null && mc.player != null && originalSlot >= 0) {
44
            InventorySwap.INSTANCE.selectHotbar(originalSlot);
45
        }
46
        originalSlot = -1;
47
        lastBreakMs = 0L;
48
    }
49
50
    @EventHandler
51
    private void onGameTick(GameTickEvent event) {
52
        if (!isEnabled() || mc.player == null || mc.level == null || mc.options == null || mc.gameMode == null) {
53
            resetState();
54
            return;
55
        }
56
57
        boolean breakingNow = mc.options.keyAttack.isDown() && mc.gameMode.isDestroying();
58
        if (breakingNow && mc.gameMode instanceof MultiPlayerGameModeAccessor accessor) {
59
            BlockPos pos = accessor.combatant$getCurrentBreakingPos();
60
            if (pos != null) {
61
                int bestSlot = findBestHotbarTool(pos);
62
                int selected = ((PlayerInventoryAccessor) mc.player.getInventory()).combatant$getSelectedSlot();
63
                if (bestSlot >= 0 && bestSlot != selected) {
64
                    if (originalSlot < 0) {
65
                        originalSlot = selected;
66
                    }
67
                    InventorySwap.INSTANCE.selectHotbar(bestSlot);
68
                }
69
                lastBreakMs = System.currentTimeMillis();
70
                return;
71
            }
72
        }
73
74
        if (originalSlot >= 0) {
75
            long now = System.currentTimeMillis();
76
            if (now - lastBreakMs >= restoreDelayMs.get()) {
77
                InventorySwap.INSTANCE.selectHotbar(originalSlot);
78
                originalSlot = -1;
79
            }
80
        }
81
    }
82
83
    private int findBestHotbarTool(BlockPos pos) {
84
        if (mc.player == null || mc.level == null) return -1;
85
        BlockState state = mc.level.getBlockState(pos);
86
        if (state.isAir()) return -1;
87
88
        int bestSlot = -1;
89
        float bestSpeed = 1.0f;
90
        for (int slot = 0; slot < 9; slot++) {
91
            ItemStack stack = mc.player.getInventory().getItem(slot);
92
            if (stack == null || stack.isEmpty()) continue;
93
            float speed = stack.getDestroySpeed(state);
94
            if (speed > bestSpeed) {
95
                bestSpeed = speed;
96
                bestSlot = slot;
97
            }
98
        }
99
        return bestSlot;
100
    }
101
102
    private void resetState() {
103
        originalSlot = -1;
104
        lastBreakMs = 0L;
105
    }
106
}
107
NicotinePlayersrc/client/java/nicotine/mod/mods/player/AutoTool.javaJava · 53 lines · 1.6 KB

Selects the right tool when breaking a block

AutoTool.javaJava · Minecraft 26.3 · 53 lines · 1.6 KB · complete file, verbatimOriginal ↗
1
package nicotine.mod.mods.player;
2
3
import net.minecraft.world.item.ItemStack;
4
import net.minecraft.world.phys.BlockHitResult;
5
import net.minecraft.world.phys.HitResult;
6
import nicotine.events.ClientLevelTickEvent;
7
import nicotine.mod.Mod;
8
import nicotine.mod.ModCategory;
9
import nicotine.util.EventBus;
10
import nicotine.util.Inventory;
11
12
import static nicotine.util.Common.mc;
13
14
public class AutoTool extends Mod {
15
16
    public AutoTool() {
17
        super(ModCategory.Player, "AutoTool", "Selects the right tool when breaking a block");
18
    }
19
20
    @Override
21
    protected void init() {
22
        EventBus.register(ClientLevelTickEvent.class, event -> {
23
            if (!this.enabled)
24
                return true;
25
26
            if (mc.hitResult.getType() != HitResult.Type.BLOCK || !mc.gameMode.isDestroying())
27
                return true;
28
29
            BlockHitResult blockHitResult = (BlockHitResult) mc.hitResult;
30
31
            float bestSpeed = mc.player.getInventory().getSelectedItem().getDestroySpeed(mc.level.getBlockState(blockHitResult.getBlockPos()));
32
            int slot = mc.player.getInventory().getSelectedSlot();
33
34
            for (int i = 0; i < 9; i++) {
35
               ItemStack itemStack = mc.player.getInventory().getItem(i);
36
37
               float speed = itemStack.getDestroySpeed(mc.level.getBlockState(blockHitResult.getBlockPos()));
38
39
               if (speed > bestSpeed) {
40
                   bestSpeed = speed;
41
                   slot = i;
42
               }
43
            }
44
45
            if (mc.player.getInventory().getSelectedSlot() != slot) {
46
                Inventory.selectSlot(slot);
47
            }
48
49
            return true;
50
        });
51
    }
52
}
53
LiquidBounce (Kotlin)WORLDsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/world/ModuleAutoTool.ktKotlin · 253 lines · 9.3 KB

Automatically chooses the best tool in your inventory to mine a block.

SettingsIgnoreDurabilitySlotFilterBlocksSwapBackDelaySwitchDelayRequireSneakingNotDuringCombatDistance
ModuleAutoTool.ktKotlin · Minecraft 26.2 · 253 lines · 9.3 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.world
20
21
import net.ccbluex.liquidbounce.config.types.group.Mode
22
import net.ccbluex.liquidbounce.config.types.group.ModeValueGroup
23
import net.ccbluex.liquidbounce.config.types.group.ToggleableValueGroup
24
import net.ccbluex.liquidbounce.event.events.BlockBreakingProgressEvent
25
import net.ccbluex.liquidbounce.event.events.CancelBlockBreakingEvent
26
import net.ccbluex.liquidbounce.event.handler
27
import net.ccbluex.liquidbounce.features.module.ClientModule
28
import net.ccbluex.liquidbounce.features.module.ModuleCategories
29
import net.ccbluex.liquidbounce.utils.block.bed.BedBlockTracker
30
import net.ccbluex.liquidbounce.utils.block.getCenterDistanceSquaredEyes
31
import net.ccbluex.liquidbounce.utils.block.stateOrEmpty
32
import net.ccbluex.liquidbounce.utils.client.SilentHotbar
33
import net.ccbluex.liquidbounce.utils.collection.Filter
34
import net.ccbluex.liquidbounce.utils.collection.blockSortedSetOf
35
import net.ccbluex.liquidbounce.utils.combat.CombatManager
36
import net.ccbluex.liquidbounce.utils.inventory.AnchoredHotbarSwapController
37
import net.ccbluex.liquidbounce.utils.inventory.HotbarItemSlot
38
import net.ccbluex.liquidbounce.utils.inventory.InventoryConstraints
39
import net.ccbluex.liquidbounce.utils.inventory.ItemSlot
40
import net.ccbluex.liquidbounce.utils.inventory.Slots
41
import net.ccbluex.liquidbounce.utils.inventory.findBestToolToMineBlock
42
import net.ccbluex.liquidbounce.utils.item.getEnchantment
43
import net.ccbluex.liquidbounce.utils.math.sq
44
import net.minecraft.core.BlockPos
45
import net.minecraft.world.item.ItemStack
46
import net.minecraft.world.item.enchantment.Enchantments
47
import net.minecraft.world.level.block.Blocks
48
import net.minecraft.world.level.block.state.BlockState
49
import java.util.function.BiPredicate
50
51
/**
52
 * AutoTool module
53
 *
54
 * Automatically chooses the best tool in your inventory to mine a block.
55
 */
56
object ModuleAutoTool : ClientModule("AutoTool", ModuleCategories.WORLD) {
57
    val toolSelector =
58
        choices(
59
            "ToolSelector",
60
            DynamicSelectMode,
61
            arrayOf(DynamicSelectMode, StaticSelectMode)
62
        )
63
64
    sealed class ToolSelectorMode(name: String) : Mode(name) {
65
        final override val parent: ModeValueGroup<*>
66
            get() = toolSelector
67
68
        fun getTool(blockState: BlockState): HotbarItemSlot? =
69
            if (filter(blockState.block, blocks)) {
70
                getToolSlot(blockState)
71
            } else {
72
                null
73
            }
74
75
        protected abstract fun getToolSlot(blockState: BlockState): HotbarItemSlot?
76
    }
77
78
    private object DynamicSelectMode : ToolSelectorMode("Dynamic") {
79
        private val ignoreDurability by boolean("IgnoreDurability", false)
80
81
        object ConsiderInventory : ToggleableValueGroup(this, "ConsiderInventory", enabled = false) {
82
            private val inventoryConstraints = tree(InventoryConstraints())
83
            private val swapController = AnchoredHotbarSwapController(
84
                owner = this,
85
                inventoryConstraints = inventoryConstraints,
86
                swapDelayProvider = { swapBackDelay },
87
            )
88
89
            override fun onDisabled() {
90
                swapController.reset()
91
                super.onDisabled()
92
            }
93
94
            fun onToolInHotbar() {
95
                swapController.clearRequestedSwap()
96
                swapController.touchActiveSwitching()
97
            }
98
99
            fun onToolInInventory(slot: ItemSlot) {
100
                swapController.requestSwapFromInventory(slot)
101
            }
102
103
            fun onNoTool() {
104
                swapController.clearRequestedSwap()
105
            }
106
        }
107
108
        init {
109
            tree(ConsiderInventory)
110
        }
111
112
        override fun getToolSlot(blockState: BlockState): HotbarItemSlot? {
113
            if (!ConsiderInventory.running) {
114
                return Slots.Hotbar.findBestToolToMineBlock(blockState, ignoreDurability, SilkTouchHandler)
115
            } else {
116
                val slot = Slots.HotbarAndInventory
117
                    .findBestToolToMineBlock(blockState, ignoreDurability, SilkTouchHandler)
118
119
                return when (slot) {
120
                    is HotbarItemSlot -> {
121
                        // We found the best tool in hotbar, don't need inventory action
122
                        ConsiderInventory.onToolInHotbar()
123
                        slot
124
                    }
125
                    is ItemSlot -> {
126
                        // Request inventory action and keep restore delay alive while actively switching.
127
                        ConsiderInventory.onToolInInventory(slot)
128
                        null
129
                    }
130
                    null -> {
131
                        ConsiderInventory.onNoTool()
132
                        null
133
                    }
134
                }
135
            }
136
        }
137
    }
138
139
    private object StaticSelectMode : ToolSelectorMode("Static") {
140
        private val slot by int("Slot", 0, 0..8)
141
142
        override fun getToolSlot(blockState: BlockState) = Slots.Hotbar[slot]
143
    }
144
145
    private val filter by enumChoice("Filter", Filter.BLACKLIST)
146
    private val blocks by blocks("Blocks", blockSortedSetOf())
147
148
    private object SilkTouchHandler : ToggleableValueGroup(
149
        this, "SilkTouchHandler", enabled = false
150
    ), BiPredicate<ItemStack, BlockState> {
151
        private val filter by enumChoice("Filter", Filter.WHITELIST)
152
        private val blocks by blocks(
153
            "Blocks",
154
            blockSortedSetOf(Blocks.ENDER_CHEST, Blocks.GLOWSTONE, Blocks.SEA_LANTERN, Blocks.TURTLE_EGG),
155
        )
156
157
        override fun test(itemStack: ItemStack, blockState: BlockState): Boolean =
158
            !running // If module AutoTool is disabled, this function returns true
159
                || blockState.block !in blocks
160
                || (filter == Filter.BLACKLIST) == (itemStack.getEnchantment(Enchantments.SILK_TOUCH) == 0)
161
    }
162
163
    init {
164
        tree(SilkTouchHandler)
165
    }
166
167
    private val swapBackDelay by int("SwapBackDelay", 20, 1..100, "ticks", aliases = listOf("SwapPreviousDelay"))
168
169
    private val switchDelay by int("SwitchDelay", 0, 0..100, "ticks")
170
171
    // Tracks the current block breaking session so the switch is delayed only once per block
172
    private var breakingPos: BlockPos? = null
173
    private var breakingStartedTick = 0
174
175
    private val requireSneaking by boolean("RequireSneaking", false)
176
    private val notDuringCombat by boolean("NotDuringCombat", false)
177
178
    private object RequireNearBed : ToggleableValueGroup(
179
        this, "RequireNearBed", enabled = false
180
    ), BedBlockTracker.Subscriber {
181
        override val maxLayers: Int get() = 1
182
183
        override fun onEnabled() {
184
            BedBlockTracker.subscribe(this)
185
        }
186
187
        override fun onDisabled() {
188
            BedBlockTracker.unsubscribe(this)
189
        }
190
191
        private val distance by float("Distance", 10.0f, 3.0f..50.0f)
192
193
        fun matches(): Boolean {
194
            return BedBlockTracker.allPositions().any { it.getCenterDistanceSquaredEyes() <= distance.sq() }
195
        }
196
    }
197
198
    init {
199
        tree(RequireNearBed)
200
    }
201
202
    val isInventoryConsidered: Boolean
203
        get() = DynamicSelectMode.ConsiderInventory.running
204
205
    @Suppress("unused")
206
    private val handleBlockBreakingProgress = handler<BlockBreakingProgressEvent> { event ->
207
        switchToBreakBlock(event.pos)
208
    }
209
210
    @Suppress("unused")
211
    private val handleCancelBlockBreaking = handler<CancelBlockBreakingEvent> {
212
        if (isInventoryConsidered) {
213
            DynamicSelectMode.ConsiderInventory.onNoTool()
214
        }
215
    }
216
217
    fun switchToBreakBlock(pos: BlockPos) {
218
        if (switchDelay > 0) {
219
            // A new block starts a new breaking session and re-arms the delay
220
            if (breakingPos != pos) {
221
                breakingPos = pos
222
                breakingStartedTick = player.tickCount
223
            }
224
            if (player.tickCount - breakingStartedTick < switchDelay) {
225
                return
226
            }
227
        }
228
229
        val cancelDueToCombat = notDuringCombat && CombatManager.isInCombat
230
        val cancelDueToNotSneaking = requireSneaking && !player.isShiftKeyDown
231
        if (cancelDueToCombat
232
            || cancelDueToNotSneaking
233
            || RequireNearBed.enabled && !RequireNearBed.matches()
234
        ) {
235
            if (isInventoryConsidered) {
236
                DynamicSelectMode.ConsiderInventory.onNoTool()
237
            }
238
            return
239
        }
240
241
        val blockState = pos.stateOrEmpty
242
        val slot = toolSelector.activeMode.getTool(blockState) ?: return
243
        SilentHotbar.selectSlotSilently(this, slot, swapBackDelay)
244
    }
245
246
    override fun onDisabled() {
247
        SilentHotbar.resetSlot(this)
248
        breakingPos = null
249
    }
250
251
252
}
253