PacketMine module

PacketMine: Minecraft 26.3 cheat module, full source for every implementation (2 clients: OfflineClient, LiquidBounce (Kotlin)).

2 implementationsWORLD

Full module source: 2 implementations

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

OfflineClientWORLDsrc/main/java/com/jellypudding/offlineclient/modules/world/PacketMine.javaJava · 312 lines · 11.9 KB

Keeps breaking the blocks you clicked whilst you do other things.

SettingsDelayAuto toolNot on useRotateObscure progressRenderRebreakInstant rebreakRebreak delayOnly pickaxe
PacketMine.javaJava · Minecraft 26.2 · 312 lines · 11.9 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.world;
2
3
import com.jellypudding.offlineclient.event.Subscribe;
4
import com.jellypudding.offlineclient.event.events.BlockBreakEvent;
5
import com.jellypudding.offlineclient.event.events.ClientTickEvent;
6
import com.jellypudding.offlineclient.event.events.Render3DEvent;
7
import com.jellypudding.offlineclient.event.events.TickEvent;
8
import com.jellypudding.offlineclient.module.Category;
9
import com.jellypudding.offlineclient.module.ExclusivityGroup;
10
import com.jellypudding.offlineclient.module.Module;
11
import com.jellypudding.offlineclient.util.InputUtil;
12
import com.jellypudding.offlineclient.render.DrawBatch;
13
import com.jellypudding.offlineclient.render.BoxStyle;
14
import com.jellypudding.offlineclient.setting.BoolSetting;
15
import com.jellypudding.offlineclient.setting.NumberSetting;
16
import com.jellypudding.offlineclient.util.BlockMiner;
17
import com.jellypudding.offlineclient.util.BlockUtil;
18
import com.jellypudding.offlineclient.util.InventoryUtil.SlotSwap;
19
import com.jellypudding.offlineclient.util.ItemUtil;
20
import com.jellypudding.offlineclient.util.RotationManager;
21
import com.jellypudding.offlineclient.util.RotationPriority;
22
import net.minecraft.core.BlockPos;
23
import net.minecraft.core.Direction;
24
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
25
import net.minecraft.network.protocol.game.ServerboundSwingPacket;
26
import net.minecraft.tags.ItemTags;
27
import net.minecraft.world.InteractionHand;
28
import net.minecraft.world.level.block.Block;
29
import net.minecraft.world.level.block.state.BlockState;
30
import net.minecraft.world.phys.AABB;
31
32
import java.util.ArrayList;
33
import java.util.List;
34
35
// Breaks the blocks you click with a start and stop pair instead of a held click.
36
// The server finishes each one on its own and the queue moves to the next.
37
public final class PacketMine extends Module {
38
39
    // Ticks of grace before a block that will not break is given up on.
40
    private static final int PATIENCE_TICKS = 50;
41
42
    private static final int MAX_QUEUE = 16;
43
44
    private final NumberSetting delay = new NumberSetting("Delay",
45
        "Ticks to wait after a click before the packets go out.", 1, 0, 20, 1, " ticks").min(0);
46
    private final BoolSetting autoTool = new BoolSetting("Auto tool",
47
        "Holds your fastest tool whilst the block breaks.", true);
48
    private final BoolSetting notOnUse = new BoolSetting("Not on use",
49
        "Holds off the tool swap whilst you are using an item.", true).under(autoTool);
50
    private final BoolSetting rotate = new BoolSetting("Rotate",
51
        "Turn towards the block on the server side.", true);
52
    private final BoolSetting obscure = new BoolSetting("Obscure progress",
53
        "Sends an abort every tick so others do not see the cracks.", false);
54
    private final BoolSetting render = new BoolSetting("Render",
55
        "Draws a box on each block in the queue.", true);
56
    private final BoxStyle miningBox = new BoxStyle("Mining", BoxStyle.Shape.BOTH, 0)
57
        .under(render);
58
    private final BoxStyle readyBox = new BoxStyle("Ready", BoxStyle.Shape.BOTH, 120)
59
        .under(render);
60
    private final BoolSetting rebreak = new BoolSetting("Rebreak",
61
        "Stays on the spot and starts again on whatever is put back.", false);
62
    private final BoolSetting instantRebreak = new BoolSetting("Instant rebreak",
63
        "Fires at the spot to catch a replacement the moment it lands.", true)
64
        .under(rebreak);
65
    private final NumberSetting rebreakDelay = new NumberSetting("Rebreak delay",
66
        "Ticks between the shots at the spot.", 0, 0, 20, 1, " ticks").min(0)
67
        .under(instantRebreak);
68
    private final BoolSetting onlyPickaxe = new BoolSetting("Only pickaxe",
69
        "Only fires whilst a pickaxe is in your main hand.", true).under(instantRebreak);
70
    private final BoxStyle rebreakBox = new BoxStyle("Rebreak", BoxStyle.Shape.BOTH, 0)
71
        .under(instantRebreak);
72
73
    // One block waiting its turn or being broken.
74
    private static final class Target {
75
76
        private final BlockPos pos;
77
        private final Direction side;
78
        private Block block;
79
        private int wait;
80
        private boolean mining;
81
        private int startTick;
82
        private int sincePoke;
83
84
        private Target(BlockPos pos, Direction side, int wait) {
85
            this.pos = pos;
86
            this.side = side;
87
            this.wait = wait;
88
        }
89
    }
90
91
    private final List<Target> queue = new ArrayList<>();
92
93
    private final SlotSwap slots = new SlotSwap();
94
95
    // Only a fresh press picks a target.
96
    private boolean attackHeld;
97
98
    public PacketMine() {
99
        super("PacketMine", "Keeps breaking the blocks you clicked whilst you do other things.", Category.WORLD);
100
        addSettings(delay, autoTool, notOnUse, rotate, obscure, render);
101
        addSettings(miningBox.settings());
102
        addSettings(readyBox.settings());
103
        addSettings(rebreak, instantRebreak, rebreakDelay, onlyPickaxe);
104
        addSettings(rebreakBox.settings());
105
        searchTags("obsidian", "packet mine", "instant mine", "queue");
106
    }
107
108
    @Override
109
    public String getSuffix() {
110
        if (queue.isEmpty()) {
111
            return "no target";
112
        }
113
        Target head = queue.getFirst();
114
        if (!head.mining) {
115
            return "waiting";
116
        }
117
        String amount = queue.size() > 1 ? " x" + queue.size() : "";
118
        return Math.min(100, (int) (progress(head) * 100)) + "%" + amount;
119
    }
120
121
    @Override
122
    public ExclusivityGroup getExclusivityGroup() {
123
        return ExclusivityGroup.MINING;
124
    }
125
126
    @Override
127
    protected void onEnable() {
128
        queue.clear();
129
        attackHeld = InputUtil.physicallyHeld(mc.options.keyAttack);
130
    }
131
132
    @Override
133
    protected void onDisable() {
134
        if (inGame()) {
135
            for (Target target : queue) {
136
                if (target.mining) {
137
                    mc.player.connection.send(new ServerboundPlayerActionPacket(
138
                        ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, target.pos, target.side));
139
                }
140
            }
141
        }
142
        BlockMiner.release();
143
        slots.restoreIfMine();
144
        queue.clear();
145
    }
146
147
    // Samples the attack key after the game has handled this tick's clicks.
148
    @Subscribe
149
    private void onClientTick(ClientTickEvent event) {
150
        attackHeld = InputUtil.physicallyHeld(mc.options.keyAttack);
151
    }
152
153
    // A fresh left click on a block puts it at the back of the queue.
154
    @Subscribe
155
    private void onBlockBreak(BlockBreakEvent event) {
156
        if (attackHeld || BlockMiner.isSelfCall() || !inGame() || mc.player.isSpectator()) {
157
            return;
158
        }
159
        BlockPos pos = event.getPos().immutable();
160
        if (queued(pos) || !BlockUtil.isBreakable(pos) || queue.size() >= MAX_QUEUE) {
161
            return;
162
        }
163
        queue.add(new Target(pos, BlockUtil.facingSide(pos), delay.getInt()));
164
    }
165
166
    private boolean queued(BlockPos pos) {
167
        for (Target target : queue) {
168
            if (target.pos.equals(pos)) {
169
                return true;
170
            }
171
        }
172
        return false;
173
    }
174
175
    @Subscribe
176
    private void onTick(TickEvent event) {
177
        if (!inGame() || mc.player.isSpectator()) {
178
            queue.clear();
179
            return;
180
        }
181
        queue.removeIf(this::finished);
182
        if (queue.isEmpty()) {
183
            slots.restoreIfMine();
184
            return;
185
        }
186
        Target head = queue.getFirst();
187
        BlockState state = BlockUtil.state(head.pos);
188
        if (head.mining) {
189
            holdTool(state);
190
            if (obscure.isOn()) {
191
                mc.player.connection.send(new ServerboundPlayerActionPacket(
192
                    ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, head.pos, head.side));
193
            }
194
            return;
195
        }
196
        // A broken block under Rebreak waits here for its replacement.
197
        if (state.isAir() || !BlockUtil.isBreakable(head.pos)) {
198
            if (canPoke(head)) {
199
                poke(head);
200
            }
201
            return;
202
        }
203
        if (head.wait > 0) {
204
            head.wait--;
205
            return;
206
        }
207
        start(head, state);
208
    }
209
210
    // True once the entry is done with or can never finish.
211
    private boolean finished(Target target) {
212
        if (BlockUtil.distanceTo(target.pos) > mc.player.blockInteractionRange()) {
213
            return true;
214
        }
215
        BlockState state = BlockUtil.state(target.pos);
216
        if (target.mining && (state.isAir() || state.getBlock() != target.block)) {
217
            if (!rebreak.isOn()) {
218
                return true;
219
            }
220
            target.mining = false;
221
            target.block = null;
222
            return false;
223
        }
224
        return target.mining && progress(target) > 2
225
            && mc.player.tickCount - target.startTick > PATIENCE_TICKS;
226
    }
227
228
    private void start(Target target, BlockState state) {
229
        // The pair goes out once the server has an angle on the block.
230
        if (rotate.isOn() && !RotationManager.look(BlockUtil.hitPoint(target.pos, target.side),
231
            RotationPriority.MINE, RotationManager.BLOCK_TOLERANCE)) {
232
            return;
233
        }
234
        holdTool(state);
235
        BlockMiner.breakInstantly(target.pos);
236
        mc.player.swing(InteractionHand.MAIN_HAND);
237
        target.block = state.getBlock();
238
        target.startTick = mc.player.tickCount;
239
        target.mining = true;
240
    }
241
242
    // True on the ticks a shot at the empty spot is due.
243
    private boolean canPoke(Target target) {
244
        if (!rebreak.isOn() || !instantRebreak.isOn()
245
            || (onlyPickaxe.isOn() && !mc.player.getMainHandItem().is(ItemTags.PICKAXES))) {
246
            return false;
247
        }
248
        if (target.sincePoke < rebreakDelay.getInt()) {
249
            target.sincePoke++;
250
            return false;
251
        }
252
        target.sincePoke = 0;
253
        return true;
254
    }
255
256
    // Breaks the replacement on the tick it lands. Ignored whilst the spot is empty.
257
    private void poke(Target target) {
258
        mc.player.connection.send(new ServerboundPlayerActionPacket(
259
            ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, target.pos, Direction.UP));
260
        mc.player.connection.send(new ServerboundSwingPacket(InteractionHand.MAIN_HAND));
261
    }
262
263
    // A client side estimate of how far along the server is.
264
    private double progress(Target target) {
265
        if (!target.mining || !inGame()) {
266
            return 0;
267
        }
268
        BlockState state = BlockUtil.state(target.pos);
269
        if (state.isAir()) {
270
            return 1;
271
        }
272
        return state.getDestroyProgress(mc.player, mc.level, target.pos)
273
            * (mc.player.tickCount - target.startTick + 1);
274
    }
275
276
    private void holdTool(BlockState state) {
277
        if (!autoTool.isOn() || (notOnUse.isOn() && mc.player.isUsingItem())) {
278
            return;
279
        }
280
        // A slot the player picked themselves is left alone.
281
        if (slots.isHolding() && !slots.stillMine()) {
282
            slots.forget();
283
            return;
284
        }
285
        ItemUtil.selectBestTool(state, slots);
286
    }
287
288
    @Subscribe
289
    private void onRender3D(Render3DEvent event) {
290
        if (!render.isOn() || !inGame()) {
291
            return;
292
        }
293
        for (Target target : queue) {
294
            if (!target.mining && rebreak.isOn() && instantRebreak.isOn()) {
295
                rebreakBox.draw(event.getBatch(), target.pos, true);
296
                continue;
297
            }
298
            double done = Math.clamp(progress(target), 0, 1);
299
            BoxStyle style = done >= 1 ? readyBox : miningBox;
300
            AABB box = DrawBatch.blockBox(target.pos);
301
            if (style.drawsLines()) {
302
                event.getBatch().outlineBox(box, style.lineColor(), true);
303
            }
304
            if (style.drawsSides() && done > 0) {
305
                AABB filled = new AABB(box.minX, box.minY, box.minZ,
306
                    box.maxX, box.minY + (box.maxY - box.minY) * done, box.maxZ);
307
                event.getBatch().solidBox(filled, style.fillColor(), true);
308
            }
309
        }
310
    }
311
}
312
LiquidBounce (Kotlin)WORLDsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/world/packetmine/ModulePacketMine.ktKotlin · 448 lines · 15.6 KB

Allows you to mine blocks by clicking them once.

SettingsRangeWallsRangeKeepRangeSwingRotateIgnoreOpenInventoryBreakDamagePostBreakDelayAbortAlwaysDownSelectDelay
ModulePacketMine.ktKotlin · Minecraft 26.2 · 448 lines · 15.6 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.packetmine
20
21
import net.ccbluex.liquidbounce.event.events.BlockAttackEvent
22
import net.ccbluex.liquidbounce.event.events.GameTickEvent
23
import net.ccbluex.liquidbounce.event.events.MouseButtonEvent
24
import net.ccbluex.liquidbounce.event.events.PacketEvent
25
import net.ccbluex.liquidbounce.event.events.RotationUpdateEvent
26
import net.ccbluex.liquidbounce.event.events.WorldChangeEvent
27
import net.ccbluex.liquidbounce.event.handler
28
import net.ccbluex.liquidbounce.features.module.ClientModule
29
import net.ccbluex.liquidbounce.features.module.ModuleCategories
30
import net.ccbluex.liquidbounce.features.module.modules.world.packetmine.mode.CivMineMode
31
import net.ccbluex.liquidbounce.features.module.modules.world.packetmine.mode.ImmediateMineMode
32
import net.ccbluex.liquidbounce.features.module.modules.world.packetmine.mode.NormalMineMode
33
import net.ccbluex.liquidbounce.features.module.modules.world.packetmine.tool.AlwaysToolMode
34
import net.ccbluex.liquidbounce.features.module.modules.world.packetmine.tool.NeverToolMode
35
import net.ccbluex.liquidbounce.features.module.modules.world.packetmine.tool.OnStopToolMode
36
import net.ccbluex.liquidbounce.features.module.modules.world.packetmine.tool.PostStartToolMode
37
import net.ccbluex.liquidbounce.render.engine.type.Color4b
38
import net.ccbluex.liquidbounce.utils.aiming.RotationManager
39
import net.ccbluex.liquidbounce.utils.aiming.RotationsValueGroup
40
import net.ccbluex.liquidbounce.utils.aiming.data.Rotation
41
import net.ccbluex.liquidbounce.utils.aiming.utils.raytraceBlockRotation
42
import net.ccbluex.liquidbounce.utils.block.SwingMode
43
import net.ccbluex.liquidbounce.utils.block.immutable
44
import net.ccbluex.liquidbounce.utils.block.outlineBox
45
import net.ccbluex.liquidbounce.utils.block.state
46
import net.ccbluex.liquidbounce.utils.block.stateOrEmpty
47
import net.ccbluex.liquidbounce.utils.client.Chronometer
48
import net.ccbluex.liquidbounce.utils.inventory.HotbarItemSlot
49
import net.ccbluex.liquidbounce.utils.kotlin.Priority
50
import net.ccbluex.liquidbounce.utils.raytracing.raytraceBlock
51
import net.ccbluex.liquidbounce.utils.render.BreakingProgress
52
import net.ccbluex.liquidbounce.utils.render.BreakingProgressRenderer
53
import net.ccbluex.liquidbounce.utils.render.placement.PlacementRenderer
54
import net.minecraft.core.BlockPos
55
import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket
56
import net.minecraft.network.protocol.game.ClientboundSectionBlocksUpdatePacket
57
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket
58
import net.minecraft.world.InteractionHand
59
import net.minecraft.world.level.block.state.BlockState
60
import net.minecraft.world.phys.BlockHitResult
61
import net.minecraft.world.phys.HitResult
62
import kotlin.math.max
63
64
/**
65
 * PacketMine module
66
 *
67
 * Automatically mines blocks you click once. Using AutoTool is recommended.
68
 *
69
 * @author ccetl
70
 */
71
@Suppress("TooManyFunctions")
72
object ModulePacketMine : ClientModule("PacketMine", ModuleCategories.WORLD), BreakingProgress.Provider {
73
74
    val mode = modes(
75
        this,
76
        "Mode",
77
        NormalMineMode,
78
        arrayOf(NormalMineMode, ImmediateMineMode, CivMineMode)
79
    ).apply {
80
        tagBy(this)
81
    }
82
83
    private val range by float("Range", 4.5f, 1f..6f)
84
    private val wallsRange by float("WallsRange", 4.5f, 0f..6f).onChange {
85
        minOf(range, it)
86
    }
87
88
    val keepRange by float("KeepRange", 25f, 0f..200f).onChange {
89
        maxOf(range, it)
90
    }
91
92
    val swingMode by enumChoice("Swing", SwingMode.HIDE_CLIENT)
93
    val switchMode = choices(
94
        "Switch",
95
        OnStopToolMode,
96
        arrayOf(AlwaysToolMode, PostStartToolMode, OnStopToolMode, NeverToolMode)
97
    )
98
99
    private val rotationMode by enumChoice("Rotate", MineRotationMode.NEVER)
100
    private val rotations = tree(RotationsValueGroup(this))
101
    private val ignoreOpenInventory by boolean("IgnoreOpenInventory", true)
102
    val breakDamage by float("BreakDamage", 1f, 0f..2f)
103
    /**
104
     * Extra delay before starting the next target after sending `STOP_DESTROY_BLOCK`.
105
     *
106
     * Vanilla applies a chained-break cooldown in
107
     * [net.minecraft.client.multiplayer.MultiPlayerGameMode.continueDestroyBlock]
108
     * by setting `destroyDelay = 5` after a successful break.
109
     * The default `6` is to prevent possible flags by different network environment and anticheat.
110
     *
111
     * @see net.minecraft.client.multiplayer.MultiPlayerGameMode.destroyDelay
112
     */
113
    private val postBreakDelay by int("PostBreakDelay", 6, 0..10, "ticks")
114
    val abortAlwaysDown by boolean("AbortAlwaysDown", false)
115
    private val selectDelay by int("SelectDelay", 200, 0..400, "ms")
116
117
    val targetRenderer = tree(
118
        PlacementRenderer(
119
            "TargetRendering", true, this,
120
            defaultColor = Color4b(255, 255, 0, 90),
121
            clump = false
122
        )
123
    )
124
    private val progressRenderer = targetRenderer.tree(BreakingProgressRenderer(targetRenderer, this))
125
126
    private val chronometer = Chronometer()
127
    private var rotation: Rotation? = null
128
    private var tickCounter = 0L
129
    private var nextAllowedStartTick = 0L
130
131
    /**
132
     * The current target of the module.
133
     *
134
     * Should never be accessed directly by other modules!
135
     */
136
    @Suppress("ObjectPropertyName", "ObjectPropertyNaming")
137
    var _target: MineTarget? = null // yes "_" because kotlin lacks package private
138
        set(value) { // and I don't want to offer this to modules using this to mine something
139
            if (value == field) {
140
                return
141
            }
142
143
            field?.cleanUp()
144
            value?.init()
145
            field = value
146
        }
147
148
    private fun shouldBlockTargetChange(mineTarget: MineTarget): Boolean {
149
        return mode.activeMode.shouldPreventTargetChange(mineTarget)
150
    }
151
152
    init {
153
        mode.onChanged {
154
            if (mc.level != null && mc.player != null) {
155
                onDisabled()
156
                onEnabled()
157
            }
158
        }
159
    }
160
161
    override fun onEnabled() {
162
        nextAllowedStartTick = 0L
163
        interaction.stopDestroyBlock()
164
    }
165
166
    override fun onDisabled() {
167
        targetRenderer.clearSilently()
168
        nextAllowedStartTick = 0L
169
        _target = null
170
    }
171
172
    @Suppress("unused")
173
    private val rotationUpdateHandler = handler<RotationUpdateEvent> {
174
        val mineTarget = _target ?: return@handler
175
        mineTarget.updateBlockState()
176
        rotate(mineTarget)
177
    }
178
179
    @Suppress("unused")
180
    private val repeatable = handler<GameTickEvent> {
181
        tickCounter++
182
        val mineTarget = _target ?: return@handler
183
        if (mineTarget.isInvalidOrOutOfRange()) {
184
            _target = null
185
            return@handler
186
        }
187
188
        mineTarget.updateBlockState()
189
        handleBreaking(mineTarget)
190
    }
191
192
    private fun rotate(mineTarget: MineTarget) {
193
        val rotate = rotationMode.shouldRotate(mineTarget)
194
195
        val raytrace = raytraceBlockRotation(
196
            player.eyePosition,
197
            mineTarget.targetPos,
198
            mineTarget.blockState,
199
            range = range.toDouble(),
200
            wallsRange = wallsRange.toDouble()
201
        ) ?: run {
202
            // don't do actions when the block is out of range
203
            mineTarget.abort()
204
            return
205
        }
206
207
        if (rotate) {
208
            RotationManager.setRotationTarget(
209
                raytrace.rotation,
210
                considerInventory = !ignoreOpenInventory,
211
                valueGroup = rotations,
212
                Priority.IMPORTANT_FOR_USAGE_2,
213
                ModulePacketMine
214
            )
215
        }
216
217
        rotation = raytrace.rotation
218
    }
219
220
    @Suppress("ReturnCount")
221
    private fun handleBreaking(mineTarget: MineTarget) {
222
        // are we looking at the target?
223
        val hit = raytraceBlock(
224
            max(range, wallsRange).toDouble(),
225
            RotationManager.serverRotation,
226
            mineTarget.targetPos,
227
            mineTarget.blockState
228
        )
229
230
        val invalidHit = hit == null || hit.type != HitResult.Type.BLOCK || hit.blockPos != mineTarget.targetPos
231
        if (invalidHit && rotationMode.getFailProcedure(mineTarget).execute(mineTarget)) {
232
            return
233
        }
234
235
        mineTarget.direction = raytraceBlock(
236
            max(range, wallsRange).toDouble() + 1.0,
237
            rotation = rotation ?: return,
238
            pos = mineTarget.targetPos,
239
            state = mineTarget.blockState
240
        )?.direction ?: run {
241
            // wrong rotations?? this should not happen!
242
            FailProcedure.ABORT.execute(mineTarget)
243
            return
244
        }
245
246
        if (player.isCreative) {
247
            interaction.startPrediction(world) { sequence: Int ->
248
                interaction.destroyBlock(mineTarget.targetPos)
249
                ServerboundPlayerActionPacket(
250
                    ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK,
251
                    mineTarget.targetPos,
252
                    mineTarget.direction!!,
253
                    sequence
254
                )
255
            }
256
257
            swingMode.swing(InteractionHand.MAIN_HAND)
258
            return
259
        }
260
261
        val switchMode = switchMode.activeMode
262
        val slot = switchMode.getSlot(mineTarget.blockState)
263
        if (!mineTarget.started) {
264
            if (tickCounter < nextAllowedStartTick) {
265
                return
266
            }
267
            startBreaking(slot, mineTarget)
268
        } else if (mode.activeMode.shouldUpdate(mineTarget, slot)) {
269
            updateBreakingProgress(mineTarget, slot)
270
            if (mineTarget.progress >= breakDamage && !mineTarget.finished) {
271
                val finishReadyTick = mineTarget.finishReadyTick
272
                if (finishReadyTick == null) {
273
                    mineTarget.finishReadyTick = tickCounter
274
                } else if (tickCounter > finishReadyTick) {
275
                    nextAllowedStartTick = tickCounter + postBreakDelay
276
                    mode.activeMode.finish(mineTarget)
277
                    switchMode.getSwitchingMethod().switchBack()
278
                }
279
            }
280
        }
281
282
        switchMode.getSwitchingMethod().reset()
283
    }
284
285
    private fun startBreaking(slot: HotbarItemSlot?, mineTarget: MineTarget) {
286
        switch(slot, mineTarget)
287
        if (switchMode.activeMode.syncOnStart) {
288
            interaction.ensureHasSentCarriedItem()
289
        }
290
291
        mode.activeMode.start(mineTarget)
292
        mineTarget.started = true
293
        mineTarget.finishReadyTick = null
294
    }
295
296
    private fun updateBreakingProgress(mineTarget: MineTarget, slot: HotbarItemSlot?) {
297
        val switchMode = switchMode.activeMode
298
        mineTarget.progress += switchMode.getBlockBreakingDelta(
299
            mineTarget.targetPos,
300
            mineTarget.blockState,
301
            slot?.itemStack
302
        )
303
304
        switch(slot, mineTarget)
305
        if (switchMode.getSwitchingMethod().shouldSync) {
306
            interaction.ensureHasSentCarriedItem()
307
        }
308
309
        val f = if (breakDamage > 0f) {
310
            mineTarget.progress.coerceIn(0f, breakDamage) / breakDamage * 0.5f
311
        } else {
312
            0.5f
313
        }
314
315
        val box = mineTarget.targetPos.outlineBox
316
        val lengthX = box.xsize
317
        val lengthY = box.ysize
318
        val lengthZ = box.zsize
319
        targetRenderer.updateBox(
320
            mineTarget.targetPos,
321
            box.inflate(
322
                lengthX * (f - 0.5f),
323
                lengthY * (f - 0.5f),
324
                lengthZ * (f - 0.5f),
325
            )
326
        )
327
    }
328
329
    override fun breakingProgress(): BreakingProgress? {
330
        val target = _target?.takeIf { it.started } ?: return null
331
        val damage = breakDamage
332
        val progress = if (damage > 0f) {
333
            target.progress / damage
334
        } else {
335
            1f
336
        }
337
338
        return BreakingProgress(target.targetPos, progress.coerceIn(0f, 1f))
339
    }
340
341
    fun switch(slot: HotbarItemSlot?, mineTarget: MineTarget) {
342
        if (slot == null) {
343
            return
344
        }
345
346
        val switchMode = switchMode.activeMode
347
        if (switchMode.shouldSwitch(mineTarget)) {
348
            switchMode.getSwitchingMethod().switch(slot, mineTarget)
349
        }
350
    }
351
352
    @Suppress("unused")
353
    private val mouseButtonHandler = handler<MouseButtonEvent> { event ->
354
        val openScreen = mc.gui.screen() != null
355
        val unchangeableActive = !mode.activeMode.canManuallyChange && _target != null
356
        if (openScreen || unchangeableActive || !player.abilities.mayBuild) {
357
            return@handler
358
        }
359
360
        // without adding a little delay before being able to unselect / select again, selecting would be impossible
361
        val hasTimePassed = chronometer.hasElapsed(selectDelay.toLong())
362
        val hitResult = mc.hitResult
363
        if (!event.isLeftButton || !hasTimePassed || hitResult == null || hitResult !is BlockHitResult) {
364
            return@handler
365
        }
366
367
        val blockPos = hitResult.blockPos
368
        val state = blockPos.stateOrEmpty
369
        val activeTarget = _target
370
371
        val shouldTargetBlock = mode.activeMode.shouldTarget(blockPos, state)
372
        // stop when the block is clicked again
373
        val isCancelledByUser = blockPos == activeTarget?.targetPos
374
375
        if (activeTarget != null && shouldBlockTargetChange(activeTarget)) {
376
            chronometer.reset()
377
            return@handler
378
        }
379
380
        _target = if (shouldTargetBlock && world.worldBorder.isWithinBounds(blockPos) && !isCancelledByUser) {
381
            MineTarget(blockPos.immutable)
382
        } else {
383
            null
384
        }
385
386
        chronometer.reset()
387
    }
388
389
    @Suppress("unused")
390
    private val blockAttackHandler = handler<BlockAttackEvent> {
391
        it.cancelEvent()
392
    }
393
394
    @Suppress("unused")
395
    private val worldChangeHandler = handler<WorldChangeEvent> {
396
        _target = null
397
    }
398
399
    @Suppress("unused")
400
    private val blockUpdateHandler = handler<PacketEvent> {
401
        when (val packet = it.packet) {
402
            is ClientboundBlockUpdatePacket -> {
403
                mc.execute { updatePosOnChange(packet.pos, packet.blockState) }
404
            }
405
406
            is ClientboundSectionBlocksUpdatePacket -> {
407
                mc.execute {
408
                    packet.runUpdates(::updatePosOnChange)
409
                }
410
            }
411
        }
412
    }
413
414
    private fun updatePosOnChange(pos: BlockPos, state: BlockState) {
415
        val target = _target ?: return
416
        if (pos != target.targetPos) {
417
            return
418
        }
419
420
        if (state.isAir && mode.activeMode.stopOnStateChange) {
421
            _target = null
422
        }
423
    }
424
425
    fun setTarget(blockPos: BlockPos) {
426
        val state = blockPos.state
427
        val shouldTargetBlock = state != null && mode.activeMode.shouldTarget(blockPos, state)
428
        if (!shouldTargetBlock || !world.worldBorder.isWithinBounds(blockPos)) {
429
            return
430
        }
431
432
        val activeTarget = _target
433
        if (activeTarget != null && shouldBlockTargetChange(activeTarget)) {
434
            return
435
        }
436
437
        if (activeTarget?.finished != false && mode.activeMode.canManuallyChange || activeTarget == null) {
438
            _target = MineTarget(blockPos.immutable)
439
        }
440
    }
441
442
    @Suppress("FunctionNaming", "FunctionName")
443
    fun _resetTarget() {
444
        _target = null
445
    }
446
447
}
448