highway-builder module

highway-builder: Minecraft 26.3 cheat module, full source for every implementation (1 client: Meteor Client).

1 implementationWorld

Clients with this module

Full module source: 1 implementation

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

Meteor ClientWorldsrc/main/java/meteordevelopment/meteorclient/systems/modules/world/HighwayBuilder.javaJava · 2,939 lines · 114.0 KB

Automatically builds highways.

Settingswidthheightfloorrailingscorner-support-blockmine-above-railingsrotationdisconnect-on-togglepause-on-lagdestroy-crystal-trapsdouble-minefast-breakdont-break-toolsdurability-percentagesave-pickaxesbreak-delayblocks-per-tickblocks-to-placeplace-rangeplace-delayplacements-per-ticktrash-itemsinventory-delayeject-useless-shulkerssearch-ender-chestsearch-shulkersminimum-empty-slotsmine-ender-chestsechest-blockade-typesave-ender-chestsinstantly-rebreak-echestsrebreak-delayrender-blocks-to-mineblocks-to-mine-shape-modeblocks-to-mine-side-colorblocks-to-mine-line-colorrender-blocks-to-placeblocks-to-place-shape-modeblocks-to-place-side-colorblocks-to-place-line-color
HighwayBuilder.javaJava · Minecraft 26.2 · 2,939 lines · 114.0 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Meteor Client distribution (https://github.com/MeteorDevelopment/meteor-client).
3
 * Copyright (c) Meteor Development.
4
 */
5
6
package meteordevelopment.meteorclient.systems.modules.world;
7
8
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
9
import meteordevelopment.meteorclient.events.game.GameLeftEvent;
10
import meteordevelopment.meteorclient.events.packets.PacketEvent;
11
import meteordevelopment.meteorclient.events.render.Render2DEvent;
12
import meteordevelopment.meteorclient.events.render.Render3DEvent;
13
import meteordevelopment.meteorclient.events.world.TickEvent;
14
import meteordevelopment.meteorclient.mixin.MinecraftMixin;
15
import meteordevelopment.meteorclient.mixin.ShulkerBoxMenuAccessor;
16
import meteordevelopment.meteorclient.mixininterface.IVec3;
17
import meteordevelopment.meteorclient.renderer.ShapeMode;
18
import meteordevelopment.meteorclient.renderer.text.TextRenderer;
19
import meteordevelopment.meteorclient.settings.*;
20
import meteordevelopment.meteorclient.systems.modules.Categories;
21
import meteordevelopment.meteorclient.systems.modules.Module;
22
import meteordevelopment.meteorclient.systems.modules.Modules;
23
import meteordevelopment.meteorclient.systems.modules.combat.KillAura;
24
import meteordevelopment.meteorclient.systems.modules.movement.Velocity;
25
import meteordevelopment.meteorclient.systems.modules.movement.speed.Speed;
26
import meteordevelopment.meteorclient.systems.modules.player.*;
27
import meteordevelopment.meteorclient.utils.Utils;
28
import meteordevelopment.meteorclient.utils.entity.SortPriority;
29
import meteordevelopment.meteorclient.utils.entity.TargetUtils;
30
import meteordevelopment.meteorclient.utils.misc.HorizontalDirection;
31
import meteordevelopment.meteorclient.utils.misc.MBlockPos;
32
import meteordevelopment.meteorclient.utils.player.*;
33
import meteordevelopment.meteorclient.utils.render.NametagUtils;
34
import meteordevelopment.meteorclient.utils.render.RenderUtils;
35
import meteordevelopment.meteorclient.utils.render.color.Color;
36
import meteordevelopment.meteorclient.utils.render.color.SettingColor;
37
import meteordevelopment.meteorclient.utils.world.BlockUtils;
38
import meteordevelopment.meteorclient.utils.world.Dir;
39
import meteordevelopment.meteorclient.utils.world.TickRate;
40
import meteordevelopment.orbit.EventHandler;
41
import net.minecraft.ChatFormatting;
42
import net.minecraft.client.gui.GuiGraphicsExtractor;
43
import net.minecraft.client.gui.screens.inventory.ContainerScreen;
44
import net.minecraft.client.gui.screens.inventory.ShulkerBoxScreen;
45
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
46
import net.minecraft.client.player.ClientInput;
47
import net.minecraft.core.BlockPos;
48
import net.minecraft.core.Direction;
49
import net.minecraft.network.chat.Component;
50
import net.minecraft.network.chat.MutableComponent;
51
import net.minecraft.network.protocol.game.ClientboundContainerSetContentPacket;
52
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
53
import net.minecraft.tags.ItemTags;
54
import net.minecraft.world.Container;
55
import net.minecraft.world.InteractionHand;
56
import net.minecraft.world.entity.Entity;
57
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
58
import net.minecraft.world.entity.item.ItemEntity;
59
import net.minecraft.world.entity.player.Player;
60
import net.minecraft.world.item.*;
61
import net.minecraft.world.item.enchantment.Enchantments;
62
import net.minecraft.world.level.ClipContext;
63
import net.minecraft.world.level.EmptyBlockGetter;
64
import net.minecraft.world.level.block.*;
65
import net.minecraft.world.level.block.state.BlockState;
66
import net.minecraft.world.phys.AABB;
67
import net.minecraft.world.phys.BlockHitResult;
68
import net.minecraft.world.phys.HitResult;
69
import net.minecraft.world.phys.Vec3;
70
import org.jetbrains.annotations.Range;
71
import org.joml.Vector3d;
72
import org.jspecify.annotations.NonNull;
73
74
import java.util.ArrayDeque;
75
import java.util.Iterator;
76
import java.util.List;
77
import java.util.Set;
78
import java.util.function.Predicate;
79
80
@SuppressWarnings("ConstantConditions")
81
public class HighwayBuilder extends Module {
82
    public enum Floor {
83
        Replace,
84
        PlaceMissing
85
    }
86
87
    public enum Rotation {
88
        None(false, false),
89
        Mine(true, false),
90
        Place(false, true),
91
        Both(true, true);
92
93
        public final boolean mine, place;
94
95
        Rotation(boolean mine, boolean place) {
96
            this.mine = mine;
97
            this.place = place;
98
        }
99
    }
100
101
    public enum BlockadeType {
102
        Full(6),
103
        Partial(4),
104
        Shulker(3);
105
106
        public final int columns;
107
108
        BlockadeType(int columns) {
109
            this.columns = columns;
110
        }
111
    }
112
113
    private final SettingGroup sgGeneral = settings.getDefaultGroup();
114
    private final SettingGroup sgDigging = settings.createGroup("Digging");
115
    private final SettingGroup sgPaving = settings.createGroup("Paving");
116
    private final SettingGroup sgInventory = settings.createGroup("Inventory");
117
    private final SettingGroup sgRenderDigging = settings.createGroup("Render Digging");
118
    private final SettingGroup sgRenderPaving = settings.createGroup("Render Paving");
119
120
    // General
121
122
    private final Setting<Integer> width = sgGeneral.add(new IntSetting.Builder()
123
        .name("width")
124
        .description("Width of the highway.")
125
        .defaultValue(4)
126
        .range(1, 5)
127
        .sliderRange(1, 5)
128
        .build()
129
    );
130
131
    private final Setting<Integer> height = sgGeneral.add(new IntSetting.Builder()
132
        .name("height")
133
        .description("Height of the highway.")
134
        .defaultValue(3)
135
        .range(2, 5)
136
        .sliderRange(2, 5)
137
        .build()
138
    );
139
140
    private final Setting<Floor> floor = sgGeneral.add(new EnumSetting.Builder<Floor>()
141
        .name("floor")
142
        .description("What floor placement mode to use.")
143
        .defaultValue(Floor.Replace)
144
        .build()
145
    );
146
147
    private final Setting<Boolean> railings = sgGeneral.add(new BoolSetting.Builder()
148
        .name("railings")
149
        .description("Builds railings next to the highway.")
150
        .defaultValue(true)
151
        .build()
152
    );
153
154
    private final Setting<Boolean> cornerBlock = sgGeneral.add(new BoolSetting.Builder()
155
        .name("corner-support-block")
156
        .description("Places a support block underneath the railings, to prevent air placing.")
157
        .defaultValue(true)
158
        .visible(railings::get)
159
        .build()
160
    );
161
162
    private final Setting<Boolean> mineAboveRailings = sgGeneral.add(new BoolSetting.Builder()
163
        .name("mine-above-railings")
164
        .description("Mines blocks above railings.")
165
        .defaultValue(true)
166
        .build()
167
    );
168
169
    private final Setting<Rotation> rotation = sgGeneral.add(new EnumSetting.Builder<Rotation>()
170
        .name("rotation")
171
        .description("Mode of rotation.")
172
        .defaultValue(Rotation.Both)
173
        .build()
174
    );
175
176
    private final Setting<Boolean> disconnectOnToggle = sgGeneral.add(new BoolSetting.Builder()
177
        .name("disconnect-on-toggle")
178
        .description("Automatically disconnects when the module is turned off, for example for not having enough blocks.")
179
        .defaultValue(false)
180
        .build()
181
    );
182
183
    private final Setting<Boolean> pauseOnLag = sgGeneral.add(new BoolSetting.Builder()
184
        .name("pause-on-lag")
185
        .description("Pauses the current process while the server stops responding.")
186
        .defaultValue(true)
187
        .build()
188
    );
189
190
    private final Setting<Boolean> destroyCrystalTraps = sgGeneral.add(new BoolSetting.Builder()
191
        .name("destroy-crystal-traps")
192
        .description("Use a bow to defuse crystal traps safely from a distance. An infinity bow is recommended.")
193
        .defaultValue(true)
194
        .build()
195
    );
196
197
    // Digging
198
199
    private final Setting<Boolean> doubleMine = sgDigging.add(new BoolSetting.Builder()
200
        .name("double-mine")
201
        .description("Whether to double mine blocks when applicable (normal mine and packet mine simultaneously).")
202
        .defaultValue(true)
203
        .build()
204
    );
205
206
    private final Setting<Boolean> fastBreak = sgDigging.add(new BoolSetting.Builder()
207
        .name("fast-break")
208
        .description("Whether to finish breaking blocks faster than normal while double mining.")
209
        .defaultValue(true)
210
        .visible(doubleMine::get)
211
        .build()
212
    );
213
214
    private final Setting<Boolean> dontBreakTools = sgDigging.add(new BoolSetting.Builder()
215
        .name("dont-break-tools")
216
        .description("Don't break tools.")
217
        .defaultValue(false)
218
        .build()
219
    );
220
221
    private final Setting<Integer> breakDurability = sgDigging.add(new IntSetting.Builder()
222
        .name("durability-percentage")
223
        .description("The durability percentage at which to stop using a tool.")
224
        .defaultValue(2)
225
        .range(1, 100)
226
        .sliderRange(1, 100)
227
        .visible(dontBreakTools::get)
228
        .build()
229
    );
230
231
    private final Setting<Integer> savePickaxes = sgDigging.add(new IntSetting.Builder()
232
        .name("save-pickaxes")
233
        .description("How many pickaxes to ensure are saved. Hitting this number in your inventory will trigger a restock or the module toggling off.")
234
        .defaultValue(1)
235
        .range(0, 36)
236
        .sliderRange(0, 36)
237
        .visible(() -> !dontBreakTools.get())
238
        .build()
239
    );
240
241
    private final Setting<Integer> breakDelay = sgDigging.add(new IntSetting.Builder()
242
        .name("break-delay")
243
        .description("The delay between breaking blocks.")
244
        .defaultValue(0)
245
        .min(0)
246
        .build()
247
    );
248
249
    private final Setting<Integer> blocksPerTick = sgDigging.add(new IntSetting.Builder()
250
        .name("blocks-per-tick")
251
        .description("The maximum amount of blocks that can be mined in a tick. Only applies to blocks instantly breakable.")
252
        .defaultValue(1)
253
        .range(1, 100)
254
        .sliderRange(1, 25)
255
        .build()
256
    );
257
258
    // Paving
259
260
    public final Setting<List<Block>> blocksToPlace = sgPaving.add(new BlockListSetting.Builder()
261
        .name("blocks-to-place")
262
        .description("Blocks it is allowed to place.")
263
        .defaultValue(Blocks.OBSIDIAN)
264
        .filter(block -> Block.isShapeFullBlock(block.defaultBlockState().getCollisionShape(EmptyBlockGetter.INSTANCE, BlockPos.ZERO)))
265
        .build()
266
    );
267
268
    private final Setting<Double> placeRange = sgPaving.add(new DoubleSetting.Builder()
269
        .name("place-range")
270
        .description("The maximum distance at which you can place blocks.")
271
        .defaultValue(4.5)
272
        .sliderMax(5.5)
273
        .build()
274
    );
275
276
    private final Setting<Integer> placeDelay = sgPaving.add(new IntSetting.Builder()
277
        .name("place-delay")
278
        .description("The delay between placing blocks.")
279
        .defaultValue(0)
280
        .min(0)
281
        .build()
282
    );
283
284
    private final Setting<Integer> placementsPerTick = sgPaving.add(new IntSetting.Builder()
285
        .name("placements-per-tick")
286
        .description("The maximum amount of blocks that can be placed in a tick.")
287
        .defaultValue(1)
288
        .min(1)
289
        .build()
290
    );
291
292
    // Inventory
293
294
    private final Setting<List<Item>> trashItems = sgInventory.add(new ItemListSetting.Builder()
295
        .name("trash-items")
296
        .description("Items that are considered trash and can be thrown out.")
297
        .defaultValue(
298
            Items.NETHERRACK, Items.QUARTZ, Items.GOLD_NUGGET, Items.GOLDEN_SWORD, Items.GLOWSTONE_DUST,
299
            Items.GLOWSTONE, Items.BLACKSTONE, Items.BASALT, Items.GHAST_TEAR, Items.SOUL_SAND, Items.SOUL_SOIL,
300
            Items.ROTTEN_FLESH, Items.MAGMA_BLOCK
301
        )
302
        .build()
303
    );
304
305
    private final Setting<Integer> inventoryDelay = sgInventory.add(new IntSetting.Builder()
306
        .name("inventory-delay")
307
        .description("Delay in ticks on inventory interactions.")
308
        .defaultValue(3)
309
        .min(0)
310
        .build()
311
    );
312
313
    private final Setting<Boolean> ejectUselessShulkers = sgInventory.add(new BoolSetting.Builder()
314
        .name("eject-useless-shulkers")
315
        .description("Whether you should eject useless shulkers. Warning - will throw out any shulkers that don't contain blocks to place, pickaxes, or food. Be careful with your kits.")
316
        .defaultValue(true)
317
        .build()
318
    );
319
320
    private final Setting<Boolean> searchEnderChest = sgInventory.add(new BoolSetting.Builder()
321
        .name("search-ender-chest")
322
        .description("Searches your ender chest to find items to use. Be careful with this one, especially if you let it search through shulkers.")
323
        .defaultValue(false)
324
        .build()
325
    );
326
327
    private final Setting<Boolean> searchShulkers = sgInventory.add(new BoolSetting.Builder()
328
        .name("search-shulkers")
329
        .description("Searches through shulkers to find items to use.")
330
        .defaultValue(true)
331
        .build()
332
    );
333
334
    private final Setting<Integer> minEmpty = sgInventory.add(new IntSetting.Builder()
335
        .name("minimum-empty-slots")
336
        .description("The minimum amount of empty slots you want left after mining obsidian.")
337
        .defaultValue(3)
338
        .sliderRange(0, 9)
339
        .min(0)
340
        .build()
341
    );
342
343
    private final Setting<Boolean> mineEnderChests = sgInventory.add(new BoolSetting.Builder()
344
        .name("mine-ender-chests")
345
        .description("Mines ender chests for obsidian.")
346
        .defaultValue(true)
347
        .build()
348
    );
349
350
    private final Setting<BlockadeType> blockadeType = sgInventory.add(new EnumSetting.Builder<BlockadeType>()
351
        .name("echest-blockade-type")
352
        .description("What blockade type to use (the structure placed when mining echests).")
353
        .defaultValue(BlockadeType.Full)
354
        .visible(mineEnderChests::get)
355
        .build()
356
    );
357
358
    public final Setting<Integer> saveEchests = sgInventory.add(new IntSetting.Builder()
359
        .name("save-ender-chests")
360
        .description("How many ender chests to ensure are saved. Hitting this number in your inventory will trigger a restock or the module toggling off.")
361
        .defaultValue(2)
362
        .range(0, 64)
363
        .sliderRange(0, 64)
364
        .visible(mineEnderChests::get)
365
        .build()
366
    );
367
368
    private final Setting<Boolean> rebreakEchests = sgInventory.add(new BoolSetting.Builder()
369
        .name("instantly-rebreak-echests")
370
        .description("Whether or not to use the instant rebreak exploit to break echests.")
371
        .defaultValue(false)
372
        .visible(mineEnderChests::get)
373
        .build()
374
    );
375
376
    private final Setting<Integer> rebreakTimer = sgInventory.add(new IntSetting.Builder()
377
        .name("rebreak-delay")
378
        .description("Delay between rebreak attempts.")
379
        .defaultValue(0)
380
        .sliderMax(20)
381
        .visible(() -> mineEnderChests.get() && rebreakEchests.get())
382
        .build()
383
    );
384
385
    // Render Digging
386
387
    private final Setting<Boolean> renderMine = sgRenderDigging.add(new BoolSetting.Builder()
388
        .name("render-blocks-to-mine")
389
        .description("Render blocks to be mined.")
390
        .defaultValue(true)
391
        .build()
392
    );
393
394
    private final Setting<ShapeMode> renderMineShape = sgRenderDigging.add(new EnumSetting.Builder<ShapeMode>()
395
        .name("blocks-to-mine-shape-mode")
396
        .description("How the blocks to be mined are rendered.")
397
        .defaultValue(ShapeMode.Both)
398
        .build()
399
    );
400
401
    private final Setting<SettingColor> renderMineSideColor = sgRenderDigging.add(new ColorSetting.Builder()
402
        .name("blocks-to-mine-side-color")
403
        .description("Color of blocks to be mined.")
404
        .defaultValue(new SettingColor(225, 25, 25, 25))
405
        .build()
406
    );
407
408
    private final Setting<SettingColor> renderMineLineColor = sgRenderDigging.add(new ColorSetting.Builder()
409
        .name("blocks-to-mine-line-color")
410
        .description("Color of blocks to be mined.")
411
        .defaultValue(new SettingColor(225, 25, 25))
412
        .build()
413
    );
414
415
    // Render Paving
416
417
    private final Setting<Boolean> renderPlace = sgRenderPaving.add(new BoolSetting.Builder()
418
        .name("render-blocks-to-place")
419
        .description("Render blocks to be placed.")
420
        .defaultValue(true)
421
        .build()
422
    );
423
424
    private final Setting<ShapeMode> renderPlaceShape = sgRenderPaving.add(new EnumSetting.Builder<ShapeMode>()
425
        .name("blocks-to-place-shape-mode")
426
        .description("How the blocks to be placed are rendered.")
427
        .defaultValue(ShapeMode.Both)
428
        .build()
429
    );
430
431
    private final Setting<SettingColor> renderPlaceSideColor = sgRenderPaving.add(new ColorSetting.Builder()
432
        .name("blocks-to-place-side-color")
433
        .description("Color of blocks to be placed.")
434
        .defaultValue(new SettingColor(25, 25, 225, 25))
435
        .build()
436
    );
437
438
    private final Setting<SettingColor> renderPlaceLineColor = sgRenderPaving.add(new ColorSetting.Builder()
439
        .name("blocks-to-place-line-color")
440
        .description("Color of blocks to be placed.")
441
        .defaultValue(new SettingColor(25, 25, 225))
442
        .build()
443
    );
444
445
    private HorizontalDirection dir, leftDir, rightDir;
446
447
    private ClientInput prevInput;
448
    private CustomPlayerInput input;
449
450
    private State state, lastState;
451
    private IBlockPosProvider blockPosProvider;
452
453
    public Vec3 start;
454
    public int blocksBroken, blocksPlaced;
455
    private final MBlockPos lastBreakingPos = new MBlockPos();
456
    private boolean displayInfo, warned;
457
    private boolean suspended = true, inventory = true;
458
    private int placeTimer, breakTimer, count, containerId;
459
    private final RestockTask restockTask = new RestockTask(this);
460
    private final Set<EndCrystal> ignoreCrystals = new ReferenceOpenHashSet<>();
461
    public boolean drawingBow;
462
    public DoubleMineBlock normalMining, packetMining;
463
464
    private final MBlockPos posRender2 = new MBlockPos();
465
    private final MBlockPos posRender3 = new MBlockPos();
466
467
    public HighwayBuilder() {
468
        super(Categories.World, "highway-builder", "Automatically builds highways.");
469
        runInMainMenu = true;
470
    }
471
472
    /* todo
473
        - separate digging and paving more effectively
474
        - separate walking forwards from the current state to speed up actions
475
        - scan one block behind you to ensure the highway is still valid
476
        - do something about god damn lava flowing in
477
     */
478
479
    @Override
480
    public void onActivate() {
481
        if (!Utils.canUpdate()) return;
482
483
        updateVariables();
484
485
        dir = HorizontalDirection.get(mc.player.getYRot());
486
        leftDir = dir.rotateLeftSkipOne();
487
        rightDir = leftDir.opposite();
488
489
        blockPosProvider = dir.diagonal ? new DiagonalBlockPosProvider() : new StraightBlockPosProvider();
490
        state = State.Forward;
491
        setState(State.Center);
492
        lastBreakingPos.set(0, 0, 0);
493
494
        start = mc.player.position();
495
        blocksBroken = blocksPlaced = 0;
496
        displayInfo = true;
497
        suspended = false;
498
499
        restockTask.complete();
500
501
        if (blocksPerTick.get() > 1 && rotation.get().mine)
502
            warning("With rotations enabled, you can break at most 1 block per tick.");
503
        if (placementsPerTick.get() > 1 && rotation.get().place)
504
            warning("With rotations enabled, you can place at most 1 block per tick.");
505
506
        if (Modules.get().get(InstantRebreak.class).isActive())
507
            warning("It's recommended to disable the Instant Rebreak module and instead use the 'instantly-rebreak-echests' setting to avoid errors.");
508
        if (Modules.get().get(Speed.class).isActive() && dir.diagonal)
509
            warning("It's recommended to disable the Speed module to avoid misalignment on diagonals.");
510
        if (!Modules.get().get(Velocity.class).isActive())
511
            warning("It's recommended to enable the Velocity module to avoid misalignment (entity pushing, liquid movement).");
512
        if (!warned && Modules.get().get(NoGhostBlocks.class).isActive()) {
513
            info("The No Ghost Blocks module is useful to prevent desyncs on laggy servers. However, it will also slow Highway Builder down, and comes with the risks of incorrect statistics and packet kicks.");
514
            warned = true;
515
        }
516
    }
517
518
    @Override
519
    public void onDeactivate() {
520
        if (!Utils.canUpdate()) return;
521
522
        mc.player.input = prevInput;
523
        mc.player.setYRot(dir.yaw);
524
        mc.options.keyUse.setDown(false);
525
526
        if (displayInfo) {
527
            info("Distance: (highlight)%.0f", PlayerUtils.distanceTo(start));
528
            info("Blocks broken: (highlight)%d", blocksBroken);
529
            info("Blocks placed: (highlight)%d", blocksPlaced);
530
        }
531
    }
532
533
    @Override
534
    public void error(String message, Object... args) {
535
        super.error(message, args);
536
        toggle();
537
538
        if (disconnectOnToggle.get()) {
539
            disconnect(message, args);
540
        }
541
    }
542
543
    private void errorEarly(String message, Object... args) {
544
        super.error(message, args);
545
546
        displayInfo = false;
547
        toggle();
548
    }
549
550
    @EventHandler
551
    private void onTick(TickEvent.Pre event) {
552
        if (dir == null) {
553
            onActivate();
554
            return;
555
        }
556
557
        if (suspended) {
558
            if (inventory && Utils.canUpdate()) {
559
                updateVariables();
560
                suspended = false;
561
            } else return;
562
        }
563
564
        if (width.get() < 3 && dir.diagonal) {
565
            errorEarly("Diagonal highways with width less than 3 are not supported.");
566
            return;
567
        }
568
569
        if (Modules.get().get(AutoEat.class).eating || Modules.get().get(AutoGap.class).isEating() || Modules.get().get(KillAura.class).attacking) {
570
            input.stop();
571
            return;
572
        }
573
574
        if (pauseOnLag.get() && TickRate.INSTANCE.getTimeSinceLastTick() >= 1.5f) {
575
            input.stop();
576
            return;
577
        }
578
579
        count = 0;
580
581
        if (mc.player.getY() < start.y - 0.5)
582
            setState(State.ReLevel); // don't let the current state keep ticking, switch to re-levelling straight away
583
        tickDoubleMine();
584
        state.tick(this);
585
586
        if (breakTimer > 0) breakTimer--;
587
        if (placeTimer > 0) placeTimer--;
588
    }
589
590
    @EventHandler
591
    private void onPacket(PacketEvent.Receive event) {
592
        if (event.packet instanceof ClientboundContainerSetContentPacket p) {
593
            if (p.containerId() == 0 && suspended)
594
                inventory = true;
595
            else
596
                this.containerId = p.containerId();
597
        }
598
    }
599
600
    @EventHandler
601
    private void onGameLeave(GameLeftEvent event) {
602
        suspended = true;
603
        inventory = false;
604
    }
605
606
    @EventHandler
607
    private void onRender2d(Render2DEvent event) {
608
        if (suspended || !renderMine.get()) return;
609
610
        if (normalMining != null) normalMining.renderLetter(event.graphics);
611
        if (packetMining != null) packetMining.renderLetter(event.graphics);
612
    }
613
614
    @EventHandler
615
    private void onRender3D(Render3DEvent event) {
616
        if (suspended || blockPosProvider == null) return; // prevents a fascinating crash
617
618
        if (renderMine.get()) {
619
            render(event, blockPosProvider.getFront(), mBlockPos -> canMine(mBlockPos, true), true);
620
            if (floor.get() == Floor.Replace)
621
                render(event, blockPosProvider.getFloor(), mBlockPos -> canMine(mBlockPos, false), true);
622
            if (railings.get())
623
                render(event, blockPosProvider.getRailings(0), mBlockPos -> canMine(mBlockPos, false), true);
624
            if (mineAboveRailings.get())
625
                render(event, blockPosProvider.getRailings(1), mBlockPos -> canMine(mBlockPos, true), true);
626
            if (state == State.MineEChestBlockade)
627
                render(event, blockPosProvider.getBlockade(true, blockadeType.get()), mBlockPos -> canMine(mBlockPos, true), true);
628
        }
629
630
        if (renderPlace.get()) {
631
            render(event, blockPosProvider.getLiquids(), mBlockPos -> canPlace(mBlockPos, true), false);
632
633
            if (railings.get()) {
634
                render(event, blockPosProvider.getRailings(0), mBlockPos -> canPlace(mBlockPos, false), false);
635
636
                if (cornerBlock.get()) {
637
                    // make sure we only render corner support blocks if we are actually planning to place a block there
638
                    render(event, blockPosProvider.getRailings(-1), mBlockPos -> {
639
                        boolean valid = false;
640
                        for (MBlockPos pos : blockPosProvider.getRailings(0)) {
641
                            if (!blocksToPlace.get().contains(pos.getState().getBlock()) && pos.add(0, -1, 0).equals(mBlockPos)) {
642
                                valid = true;
643
                                break;
644
                            }
645
                        }
646
647
                        return valid && canPlace(mBlockPos, false);
648
                    }, false);
649
                }
650
            }
651
652
            render(event, blockPosProvider.getFloor(), mBlockPos -> canPlace(mBlockPos, false), false);
653
            if (state == State.PlaceEChestBlockade)
654
                render(event, blockPosProvider.getBlockade(false, blockadeType.get()), mBlockPos -> canPlace(mBlockPos, false), false);
655
        }
656
    }
657
658
    private void render(Render3DEvent event, MBPIterator it, Predicate<MBlockPos> predicate, boolean mine) {
659
        Color sideColor = mine ? renderMineSideColor.get() : renderPlaceSideColor.get();
660
        Color lineColor = mine ? renderMineLineColor.get() : renderPlaceLineColor.get();
661
        ShapeMode shapeMode = mine ? renderMineShape.get() : renderPlaceShape.get();
662
663
        for (MBlockPos pos : it) {
664
            posRender2.set(pos);
665
666
            if (predicate.test(posRender2)) {
667
                int excludeDir = 0;
668
669
                for (Direction side : Direction.values()) {
670
                    posRender3.set(posRender2).add(side.getStepX(), side.getStepY(), side.getStepZ());
671
672
                    it.save();
673
                    for (MBlockPos p : it) {
674
                        if (p.equals(posRender3) && predicate.test(p)) excludeDir |= Dir.get(side);
675
                    }
676
                    it.restore();
677
                }
678
679
                event.renderer.box(posRender2.getBlockPos(), sideColor, lineColor, shapeMode, excludeDir);
680
            }
681
        }
682
    }
683
684
    private void updateVariables() {
685
        prevInput = mc.player.input;
686
        mc.player.input = input = new CustomPlayerInput();
687
688
        placeTimer = breakTimer = count = containerId = 0;
689
        ignoreCrystals.clear();
690
691
        normalMining = null;
692
        packetMining = null;
693
    }
694
695
    private void setState(State state) {
696
        setState(state, this.state);
697
    }
698
699
    private void setState(State state, State lastState) {
700
        this.lastState = lastState;
701
        this.state = state;
702
703
        input.stop();
704
        state.start(this);
705
    }
706
707
    private int getWidthLeft() {
708
        return switch (width.get()) {
709
            case 5, 4 -> 2;
710
            case 3, 2 -> 1;
711
            default -> 0;
712
        };
713
    }
714
715
    private int getWidthRight() {
716
        return switch (width.get()) {
717
            case 5 -> 2;
718
            case 4, 3 -> 1;
719
            default -> 0;
720
        };
721
    }
722
723
    private boolean canMine(MBlockPos pos, boolean mineBlocksToPlace) {
724
        BlockState state = pos.getState();
725
        return BlockUtils.canBreak(pos.getBlockPos(), state) && (mineBlocksToPlace || !blocksToPlace.get().contains(state.getBlock()));
726
    }
727
728
    private boolean canPlace(MBlockPos pos, boolean liquids) {
729
        if (pos.getBlockPos().distToCenterSqr(mc.player.getEyePosition()) > placeRange.get() * placeRange.get())
730
            return false;
731
        return liquids ? !pos.getState().getFluidState().isEmpty() : BlockUtils.canPlace(pos.getBlockPos());
732
    }
733
734
    private void disconnect(String message, Object... args) {
735
        MutableComponent text = Component.literal(String.format("%s[%s%s%s] %s", ChatFormatting.GRAY, ChatFormatting.BLUE, title, ChatFormatting.GRAY, ChatFormatting.RED) + String.format(message, args)).append("\n");
736
        text.append(getStatsText());
737
738
        mc.getConnection().getConnection().disconnect(text);
739
    }
740
741
    public MutableComponent getStatsText() {
742
        MutableComponent text = Component.literal(String.format("%sDistance: %s%.0f\n", ChatFormatting.GRAY, ChatFormatting.WHITE, mc.player == null ? 0.0f : PlayerUtils.distanceTo(start)));
743
        text.append(String.format("%sBlocks broken: %s%d\n", ChatFormatting.GRAY, ChatFormatting.WHITE, blocksBroken));
744
        text.append(String.format("%sBlocks placed: %s%d", ChatFormatting.GRAY, ChatFormatting.WHITE, blocksPlaced));
745
746
        return text;
747
    }
748
749
    private void tickDoubleMine() {
750
        // could add clientside block breaking to speed the system up, but it would probably make it too vulnerable to desyncs
751
        if (normalMining != null) {
752
            if (normalMining.shouldRemove()) {
753
                mc.getConnection().send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, normalMining.blockPos, normalMining.direction));
754
                normalMining = null;
755
                DoubleMineBlock.rateLimited = true;
756
            } else if (mc.level.getBlockState(normalMining.blockPos).getBlock() != normalMining.block) {
757
                normalMining = null;
758
                blocksBroken++;
759
                count++;
760
                DoubleMineBlock.rateLimited = false;
761
            } else if (normalMining.isReady()) {
762
                normalMining.stopDestroying();
763
            }
764
765
            mc.player.swing(InteractionHand.MAIN_HAND);
766
        }
767
768
        if (packetMining != null) {
769
            if (packetMining.shouldRemove()) {
770
                // should we add rate limiting for packet mined blocks? More testing required to see if appropriate
771
                packetMining = null;
772
            } else if (mc.level.getBlockState(packetMining.blockPos).getBlock() != packetMining.block) {
773
                packetMining = null;
774
                blocksBroken++;
775
                count++;
776
            }
777
        }
778
    }
779
780
    private enum State {
781
        Center {
782
            @Override
783
            protected void start(HighwayBuilder b) {
784
                if (b.mc.player.position().closerThan(Vec3.atBottomCenterOf(b.mc.player.blockPosition()), 0.1)) {
785
                    stop(b);
786
                }
787
            }
788
789
            @Override
790
            protected void tick(HighwayBuilder b) {
791
                // There is probably a much better way to do this
792
                double x = Math.abs(b.mc.player.getX() - (int) b.mc.player.getX()) - 0.5;
793
                double z = Math.abs(b.mc.player.getZ() - (int) b.mc.player.getZ()) - 0.5;
794
795
                boolean isX = Math.abs(x) <= 0.1;
796
                boolean isZ = Math.abs(z) <= 0.1;
797
798
                if (isX && isZ) {
799
                    stop(b);
800
                } else {
801
                    b.mc.player.setYRot(0);
802
803
                    if (!isZ) {
804
                        b.input.forward(z < 0);
805
                        b.input.backward(z > 0);
806
807
                        if (b.mc.player.getZ() < 0) {
808
                            boolean forward = b.input.keyPresses.forward();
809
                            b.input.forward(b.input.keyPresses.backward());
810
                            b.input.backward(forward);
811
                        }
812
                    }
813
814
                    if (!isX) {
815
                        b.input.right(x > 0);
816
                        b.input.left(x < 0);
817
818
                        if (b.mc.player.getX() < 0) {
819
                            boolean right = b.input.keyPresses.right();
820
                            b.input.right(b.input.keyPresses.left());
821
                            b.input.left(right);
822
                        }
823
                    }
824
825
                    b.input.sneak(true);
826
                }
827
            }
828
829
            private void stop(HighwayBuilder b) {
830
                b.input.stop();
831
                b.mc.player.setDeltaMovement(0, 0, 0);
832
                b.mc.player.setPos((int) b.mc.player.getX() + (b.mc.player.getX() < 0 ? -0.5 : 0.5), b.mc.player.getY(), (int) b.mc.player.getZ() + (b.mc.player.getZ() < 0 ? -0.5 : 0.5));
833
                b.setState(b.lastState);
834
            }
835
        },
836
837
        Forward {
838
            @Override
839
            protected void start(HighwayBuilder b) {
840
                checkTasks(b);
841
842
                if (b.state == Forward) b.mc.player.setYRot(b.dir.yaw);
843
            }
844
845
            @Override
846
            protected void tick(HighwayBuilder b) {
847
                checkTasks(b);
848
849
                if (b.state == Forward) b.input.forward(true); // Move
850
            }
851
852
            private void checkTasks(HighwayBuilder b) {
853
                if (b.destroyCrystalTraps.get() && isCrystalTrap(b))
854
                    b.setState(DefuseCrystalTraps); // Destroy crystal traps
855
                else if (needsToPlace(b, b.blockPosProvider.getLiquids(), true))
856
                    b.setState(FillLiquids); // Fill Liquids
857
                else if (needsToMine(b, b.blockPosProvider.getFront(), true)) b.setState(MineFront); // Mine Front
858
                else if (b.floor.get() == Floor.Replace && needsToMine(b, b.blockPosProvider.getFloor(), false))
859
                    b.setState(MineFloor); // Mine Floor
860
                else if (b.railings.get() && needsToMine(b, b.blockPosProvider.getRailings(0), false))
861
                    b.setState(MineRailings); // Mine Railings
862
                else if (b.mineAboveRailings.get() && needsToMine(b, b.blockPosProvider.getRailings(1), true))
863
                    b.setState(MineAboveRailings); // Mine above railings
864
                else if (b.railings.get() && needsToPlace(b, b.blockPosProvider.getRailings(0), false)) {
865
                    if (b.cornerBlock.get() && needsToPlace(b, b.blockPosProvider.getRailings(-1), false))
866
                        b.setState(PlaceCornerBlock); // Place corner support block
867
                    else b.setState(PlaceRailings); // Place Railings
868
                } else if (needsToPlace(b, b.blockPosProvider.getFloor(), false)) b.setState(PlaceFloor); // Place Floor
869
            }
870
871
            private boolean needsToMine(HighwayBuilder b, MBPIterator it, boolean mineBlocksToPlace) {
872
                for (MBlockPos pos : it) {
873
                    if (b.canMine(pos, mineBlocksToPlace)) return true;
874
                }
875
876
                return false;
877
            }
878
879
            private boolean needsToPlace(HighwayBuilder b, MBPIterator it, boolean liquids) {
880
                for (MBlockPos pos : it) {
881
                    if (b.canPlace(pos, liquids)) return true;
882
                }
883
884
                return false;
885
            }
886
887
            private boolean isCrystalTrap(HighwayBuilder b) {
888
                for (Entity entity : b.mc.level.entitiesForRendering()) {
889
                    if (!(entity instanceof EndCrystal endCrystal)) continue;
890
                    if (PlayerUtils.isWithin(endCrystal, 12) || !PlayerUtils.isWithin(endCrystal, 24)) continue;
891
                    if (b.ignoreCrystals.contains(endCrystal)) continue;
892
893
                    Vec3 vec1 = new Vec3(0, 0, 0);
894
                    Vec3 vec2 = new Vec3(0, 0, 0);
895
896
                    // todo add a better raytrace check
897
                    ((IVec3) vec1).meteor$set(b.mc.player.getX(), b.mc.player.getY() + b.mc.player.getEyeHeight(), b.mc.player.getZ());
898
                    ((IVec3) vec2).meteor$set(entity.getX(), entity.getY() + 0.5, entity.getZ());
899
                    return b.mc.level.clip(new ClipContext(vec1, vec2, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, b.mc.player)).getType() == HitResult.Type.MISS;
900
                }
901
902
                return false;
903
            }
904
        },
905
906
        ReLevel {
907
            private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
908
            private BlockPos startPos;
909
            private int timer = 30;
910
911
            @Override
912
            protected void start(HighwayBuilder b) {
913
                startPos = BlockPos.containing(b.start);
914
            }
915
916
            @Override
917
            protected void tick(HighwayBuilder b) {
918
                Vec3 vec = b.mc.player.position().add(b.mc.player.getDeltaMovement()).add(0, -0.75, 0);
919
                pos.set(b.mc.player.getBlockX(), vec.y, b.mc.player.getBlockZ());
920
921
                if (pos.getY() >= b.mc.player.blockPosition().getY()) {
922
                    pos.setY(b.mc.player.blockPosition().getY() - 1);
923
                }
924
925
                if (pos.getY() >= startPos.getY()) pos.setY(startPos.getY() - 1);
926
927
                if (b.mc.player.getY() > b.start.y - 0.5 && !b.mc.level.getBlockState(pos).canBeReplaced()) {
928
                    b.input.jump(false);
929
930
                    if (timer > 0) timer--;
931
                    else {
932
                        b.setState(Forward);
933
                        timer = 30;
934
                    }
935
936
                    return;
937
                }
938
939
                if (b.placeTimer > 0) return;
940
941
                if (timer < 30) timer = 30;
942
                b.input.jump(true);
943
944
                int slot = -1;
945
                if (pos.getY() == startPos.below().getY()) {
946
                    // we would prefer the block flush with the highway to be an appropriate placement block, not trash
947
                    slot = findAndMoveToHotbar(b, itemStack -> itemStack.getItem() instanceof BlockItem blockItem && b.blocksToPlace.get().contains(blockItem.getBlock()));
948
                }
949
950
                if (slot == -1) {
951
                    slot = findAcceptablePlacementBlock(b);
952
                    if (slot == -1) return;
953
                }
954
955
                if (BlockUtils.place(pos.immutable(), InteractionHand.MAIN_HAND, slot, b.rotation.get().place, 100, true, true, false)) {
956
                    if (b.renderPlace.get())
957
                        RenderUtils.renderTickingBlock(pos.immutable(), b.renderPlaceSideColor.get(), b.renderPlaceLineColor.get(), b.renderPlaceShape.get(), 0, 5, true, false);
958
                    b.placeTimer = b.placeDelay.get();
959
                }
960
            }
961
962
            private int findAcceptablePlacementBlock(HighwayBuilder b) {
963
                // still should prioritise trash
964
                int slot = findAndMoveToHotbar(b, itemStack -> {
965
                    if (!(itemStack.getItem() instanceof BlockItem)) return false;
966
                    return b.trashItems.get().contains(itemStack.getItem());
967
                });
968
969
                // next we prioritise placement blocks
970
                if (slot == -1) slot = findAndMoveToHotbar(b, itemStack -> {
971
                    if (!(itemStack.getItem() instanceof BlockItem bi)) return false;
972
                    return b.blocksToPlace.get().contains(bi.getBlock());
973
                });
974
975
                // falling is an emergency; in this case only, we allow access to any whole block in your inventory
976
                return slot != -1 ? slot : findAndMoveToHotbar(b, itemStack -> {
977
                    if (!(itemStack.getItem() instanceof BlockItem bi)) return false;
978
                    if (Utils.isShulker(bi)) return false;
979
                    Block block = bi.getBlock();
980
981
                    if (!Block.isShapeFullBlock(block.defaultBlockState().getCollisionShape(b.mc.level, pos)))
982
                        return false;
983
                    return !(block instanceof FallingBlock) || !FallingBlock.isFree(b.mc.level.getBlockState(pos));
984
                });
985
            }
986
        },
987
988
        FillLiquids {
989
            @Override
990
            protected void tick(HighwayBuilder b) {
991
                int slot = findBlocksToPlacePrioritizeTrash(b);
992
                if (slot == -1) return;
993
994
                place(b, new MBPIteratorFilter(b.blockPosProvider.getLiquids(), pos -> !pos.getState().getFluidState().isEmpty()), slot, Forward);
995
            }
996
        },
997
998
        MineFront {
999
            @Override
1000
            protected void start(HighwayBuilder b) {
1001
                mine(b, b.blockPosProvider.getFront(), true, Forward, this);
1002
            }
1003
1004
            @Override
1005
            protected void tick(HighwayBuilder b) {
1006
                mine(b, b.blockPosProvider.getFront(), true, Forward, this);
1007
            }
1008
        },
1009
1010
        MineFloor {
1011
            @Override
1012
            protected void start(HighwayBuilder b) {
1013
                mine(b, b.blockPosProvider.getFloor(), false, Forward, this);
1014
            }
1015
1016
            @Override
1017
            protected void tick(HighwayBuilder b) {
1018
                mine(b, b.blockPosProvider.getFloor(), false, Forward, this);
1019
            }
1020
        },
1021
1022
        MineRailings {
1023
            @Override
1024
            protected void start(HighwayBuilder b) {
1025
                mine(b, b.blockPosProvider.getRailings(0), false, Forward, this);
1026
            }
1027
1028
            @Override
1029
            protected void tick(HighwayBuilder b) {
1030
                mine(b, b.blockPosProvider.getRailings(0), false, Forward, this);
1031
            }
1032
        },
1033
1034
        MineAboveRailings {
1035
            @Override
1036
            protected void start(HighwayBuilder b) {
1037
                mine(b, b.blockPosProvider.getRailings(1), true, Forward, this);
1038
            }
1039
1040
            @Override
1041
            protected void tick(HighwayBuilder b) {
1042
                mine(b, b.blockPosProvider.getRailings(1), true, Forward, this);
1043
            }
1044
        },
1045
1046
        PlaceCornerBlock {
1047
            @Override
1048
            protected void start(HighwayBuilder b) {
1049
                int slot = findBlocksToPlacePrioritizeTrash(b);
1050
                if (slot == -1) return;
1051
1052
                place(b, b.blockPosProvider.getRailings(-1), slot, Forward);
1053
            }
1054
1055
            @Override
1056
            protected void tick(HighwayBuilder b) {
1057
                int slot = findBlocksToPlacePrioritizeTrash(b);
1058
                if (slot == -1) return;
1059
1060
                place(b, b.blockPosProvider.getRailings(-1), slot, Forward);
1061
            }
1062
        },
1063
1064
        PlaceRailings {
1065
            @Override
1066
            protected void start(HighwayBuilder b) {
1067
                int slot = findBlocksToPlace(b);
1068
                if (slot == -1) return;
1069
1070
                place(b, b.blockPosProvider.getRailings(0), slot, Forward);
1071
            }
1072
1073
            @Override
1074
            protected void tick(HighwayBuilder b) {
1075
                int slot = findBlocksToPlace(b);
1076
                if (slot == -1) return;
1077
1078
                place(b, b.blockPosProvider.getRailings(0), slot, Forward);
1079
            }
1080
        },
1081
1082
        PlaceFloor {
1083
            @Override
1084
            protected void start(HighwayBuilder b) {
1085
                int slot = findBlocksToPlace(b);
1086
                if (slot == -1) return;
1087
1088
                place(b, b.blockPosProvider.getFloor(), slot, Forward);
1089
            }
1090
1091
            @Override
1092
            protected void tick(HighwayBuilder b) {
1093
                int slot = findBlocksToPlace(b);
1094
                if (slot == -1) return;
1095
1096
                place(b, b.blockPosProvider.getFloor(), slot, Forward);
1097
            }
1098
        },
1099
1100
        ThrowOutTrash {
1101
            private int skipSlot;
1102
            private boolean timerEnabled,firstTick,threwItems;
1103
            private int timer;
1104
            private static final ItemStack[] ITEMS = new ItemStack[27];
1105
1106
            @Override
1107
            protected void start(HighwayBuilder b) {
1108
                int biggestCount = 0;
1109
1110
                for (int i = 0; i < b.mc.player.getInventory().getNonEquipmentItems().size(); i++) {
1111
                    ItemStack itemStack = b.mc.player.getInventory().getItem(i);
1112
1113
                    if (itemStack.getItem() instanceof BlockItem && b.trashItems.get().contains(itemStack.getItem()) && itemStack.getCount() > biggestCount) {
1114
                        biggestCount = itemStack.getCount();
1115
                        skipSlot = i;
1116
1117
                        if (biggestCount >= 64) break;
1118
                    }
1119
                }
1120
1121
                if (biggestCount == 0) skipSlot = -1;
1122
                timerEnabled = false;
1123
                firstTick = true;
1124
                threwItems = false;
1125
            }
1126
1127
            @Override
1128
            protected void tick(HighwayBuilder b) {
1129
                if (timerEnabled) {
1130
                    if (timer > 0) timer--;
1131
                    else b.setState(b.lastState);
1132
1133
                    return;
1134
                }
1135
1136
                b.mc.player.setYRot(b.dir.opposite().yaw);
1137
                b.mc.player.setXRot(-25);
1138
1139
                if (firstTick) {
1140
                    firstTick = false;
1141
                    return;
1142
                }
1143
1144
                if (!b.mc.player.containerMenu.getCarried().isEmpty()) {
1145
                    InvUtils.dropHand();
1146
                    return;
1147
                }
1148
1149
                for (int i = 0; i < b.mc.player.getInventory().getNonEquipmentItems().size(); i++) {
1150
                    if (i == skipSlot) continue;
1151
1152
                    ItemStack itemStack = b.mc.player.getInventory().getItem(i);
1153
1154
                    if (b.trashItems.get().contains(itemStack.getItem())) {
1155
                        InvUtils.drop().slot(i);
1156
                        threwItems = true;
1157
                        return;
1158
                    }
1159
1160
                    if (b.ejectUselessShulkers.get() && Utils.isShulker(itemStack.getItem())) {
1161
                        Utils.getItemsInContainerItem(itemStack, ITEMS);
1162
                        boolean eject = true;
1163
                        for (ItemStack stack : ITEMS) {
1164
                            if (stack.getItem() instanceof BlockItem bi && (b.blocksToPlace.get().contains(bi.getBlock()) || (b.blocksToPlace.get().contains(Blocks.OBSIDIAN) && bi == Items.ENDER_CHEST))) {
1165
                                eject = false;
1166
                                break;
1167
                            }
1168
                            if (stack.is(ItemTags.PICKAXES)) {
1169
                                eject = false;
1170
                                break;
1171
                            }
1172
                            if (Utils.isFood(stack) && !Modules.get().get(AutoEat.class).blacklist.get().contains(stack.getItem())) {
1173
                                eject = false;
1174
                                break;
1175
                            }
1176
                        }
1177
1178
                        if (eject) {
1179
                            InvUtils.drop().slot(i);
1180
                            threwItems = true;
1181
                            return;
1182
                        }
1183
                    }
1184
                }
1185
1186
                timerEnabled = true;
1187
                timer = threwItems ? 10 : 1;
1188
            }
1189
        },
1190
1191
        PlaceEChestBlockade {
1192
            @Override
1193
            protected void tick(HighwayBuilder b) {
1194
                int slot = findBlocksToPlacePrioritizeTrash(b);
1195
                if (slot == -1) return;
1196
1197
                place(b, b.blockPosProvider.getBlockade(false, b.blockadeType.get()), slot, MineEnderChests);
1198
            }
1199
        },
1200
1201
        MineEChestBlockade {
1202
            @Override
1203
            protected void tick(HighwayBuilder b) {
1204
                mine(b, b.blockPosProvider.getBlockade(true, b.blockadeType.get()), true, Center, Forward);
1205
            }
1206
        },
1207
1208
        MineEnderChests {
1209
            private static final MBlockPos pos = new MBlockPos();
1210
            private int minimumObsidian;
1211
            private boolean first,primed;
1212
            private boolean stopTimerEnabled;
1213
            private int stopTimer,moveTimer,rebreakTimer,timeout;
1214
1215
            @Override
1216
            protected void start(HighwayBuilder b) {
1217
                if (b.lastState != Center && b.lastState != ThrowOutTrash && b.lastState != PlaceEChestBlockade) {
1218
                    b.setState(Center);
1219
                    return;
1220
                } else if (b.lastState == Center) {
1221
                    b.setState(ThrowOutTrash);
1222
                    return;
1223
                } else if (b.lastState == ThrowOutTrash) {
1224
                    b.setState(PlaceEChestBlockade);
1225
                    return;
1226
                }
1227
1228
                int emptySlots = 0;
1229
                for (int i = 0; i < b.mc.player.getInventory().getNonEquipmentItems().size(); i++) {
1230
                    if (b.mc.player.getInventory().getItem(i).isEmpty()) emptySlots++;
1231
                }
1232
1233
                if (emptySlots == 0) {
1234
                    b.error("No empty slots.");
1235
                    return;
1236
                }
1237
1238
                int minimumSlots = Math.max(emptySlots - b.minEmpty.get(), 1);
1239
                minimumObsidian = minimumSlots * 64;
1240
                first = true;
1241
                moveTimer = timeout = 0;
1242
1243
                stopTimerEnabled = false;
1244
                primed = false;
1245
            }
1246
1247
            @Override
1248
            protected void tick(HighwayBuilder b) {
1249
                if (stopTimerEnabled) {
1250
                    if (stopTimer > 0) stopTimer--;
1251
                    else b.setState(MineEChestBlockade);
1252
1253
                    return;
1254
                }
1255
1256
                HorizontalDirection dir = b.dir.diagonal ? b.dir.rotateLeft().rotateLeftSkipOne() : b.dir.opposite();
1257
                pos.set(b.mc.player).offset(dir);
1258
1259
                // Move
1260
                if (moveTimer > 0) {
1261
                    b.mc.player.setYRot(dir.yaw);
1262
                    b.input.forward(moveTimer > 2);
1263
1264
                    moveTimer--;
1265
                    return;
1266
                }
1267
1268
                // Check for obsidian count
1269
                int obsidianCount = 0;
1270
1271
                for (Entity entity : b.mc.level.getEntities(b.mc.player, new AABB(pos.x, pos.y, pos.z, pos.x + 1, pos.y + 2, pos.z + 1))) {
1272
                    if (entity instanceof ItemEntity itemEntity && itemEntity.getItem().getItem() == Items.OBSIDIAN) {
1273
                        obsidianCount += itemEntity.getItem().getCount();
1274
                    }
1275
                }
1276
1277
                for (int i = 0; i < b.mc.player.getInventory().getNonEquipmentItems().size(); i++) {
1278
                    ItemStack itemStack = b.mc.player.getInventory().getItem(i);
1279
                    if (itemStack.getItem() == Items.OBSIDIAN) obsidianCount += itemStack.getCount();
1280
                }
1281
1282
                if (obsidianCount >= minimumObsidian) {
1283
                    stopTimerEnabled = true;
1284
                    stopTimer = 12;
1285
                    return;
1286
                }
1287
1288
                BlockPos bp = pos.getBlockPos();
1289
1290
                // Check block state
1291
                BlockState blockState = b.mc.level.getBlockState(bp);
1292
1293
                if (blockState.getBlock() == Blocks.ENDER_CHEST) {
1294
                    if (b.mc.gui.screen() instanceof ContainerScreen screen) {
1295
                        // wait for the screen to be properly loaded
1296
                        if (screen.getMenu().containerId != b.containerId) return;
1297
1298
                        b.mc.gui.screen().onClose();
1299
                    }
1300
1301
                    // if we don't know what's in your echest, open it quickly while we have one available to check
1302
                    if (!EChestMemory.isKnown()) {
1303
                        if (b.rotation.get().place) Rotations.rotate(Rotations.getYaw(bp), Rotations.getPitch(bp), () ->
1304
                            b.mc.gameMode.useItemOn(b.mc.player, InteractionHand.MAIN_HAND, new BlockHitResult(Vec3.atCenterOf(bp), Direction.UP, bp, false)));
1305
                        else
1306
                            b.mc.gameMode.useItemOn(b.mc.player, InteractionHand.MAIN_HAND, new BlockHitResult(Vec3.atCenterOf(bp), Direction.UP, bp, false));
1307
1308
                        return;
1309
                    }
1310
1311
                    if (first) {
1312
                        moveTimer = 8;
1313
                        first = false;
1314
                        return;
1315
                    }
1316
1317
                    // Mine ender chest
1318
                    int slot = findAndMoveBestToolToHotbar(b, blockState, true);
1319
                    if (slot == -1) {
1320
                        b.error("Cannot find pickaxe without silk touch to mine ender chests.");
1321
                        return;
1322
                    }
1323
1324
                    InvUtils.swap(slot, false);
1325
1326
                    if (b.rebreakEchests.get() && primed) {
1327
                        timeout++;
1328
                        if (timeout > 60) {
1329
                            primed = false;
1330
                            timeout = 0;
1331
                            return;
1332
                        }
1333
1334
                        if (rebreakTimer > 0) {
1335
                            rebreakTimer--;
1336
                            return;
1337
                        }
1338
1339
                        rebreakTimer = b.rebreakTimer.get();
1340
1341
                        if (b.rotation.get().mine) {
1342
                            Rotations.rotate(Rotations.getYaw(bp), Rotations.getPitch(bp), () ->
1343
                                b.mc.gameMode.startPrediction(b.mc.level, sequence ->
1344
                                    new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, bp, BlockUtils.getDirection(bp), sequence)
1345
                                )
1346
                            );
1347
                        } else b.mc.gameMode.startPrediction(b.mc.level, sequence ->
1348
                            new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, bp, BlockUtils.getDirection(bp), sequence)
1349
                        );
1350
                    } else {
1351
                        if (b.rotation.get().mine)
1352
                            Rotations.rotate(Rotations.getYaw(bp), Rotations.getPitch(bp), () -> BlockUtils.breakBlock(bp, true));
1353
                        else BlockUtils.breakBlock(bp, true);
1354
                    }
1355
                } else {
1356
                    // Place ender chest
1357
                    int slot = findAndMoveToHotbar(b, itemStack -> itemStack.getItem() == Items.ENDER_CHEST);
1358
                    if (slot == -1 || countItem(b, stack -> stack.getItem().equals(Items.ENDER_CHEST)) <= b.saveEchests.get()) {
1359
                        stopTimerEnabled = true;
1360
                        stopTimer = 12;
1361
                        return;
1362
                    }
1363
1364
                    if (countItem(b, stack -> stack.is(ItemTags.PICKAXES)) <= b.savePickaxes.get()) {
1365
                        if (b.searchEnderChest.get() || b.searchShulkers.get()) {
1366
                            b.restockTask.setPickaxes();
1367
                        }
1368
                    }
1369
1370
                    if (!first) primed = true;
1371
1372
                    BlockUtils.place(bp, InteractionHand.MAIN_HAND, slot, b.rotation.get().place, 0, true, true, false);
1373
                    timeout = 0;
1374
                }
1375
            }
1376
        },
1377
1378
        // this one was rough to do
1379
        Restock {
1380
            private static final MBlockPos pos = new MBlockPos();
1381
            private static final ItemStack[] ITEMS = new ItemStack[27];
1382
            private int minimumSlots,stopTimer,delayTimer;
1383
            private boolean breakContainer,indicateStopping;
1384
            private Predicate<ItemStack> shulkerPredicate;
1385
1386
            // if this is ever not -1 when we expect it to be, things break a lot
1387
            private int slot = -1;
1388
1389
            @Override
1390
            protected void start(HighwayBuilder b) {
1391
                slot = -1; // :ptsd:
1392
1393
                // set the predicate to test for shulker boxes
1394
                if (shulkerPredicate == null) setShulkerPredicate(b);
1395
1396
                if (b.restockTask.tasksInactive()) {
1397
                    b.setState(Forward);
1398
                    return;
1399
                }
1400
1401
                if (b.lastState != Center && b.lastState != ThrowOutTrash && b.lastState != PlaceShulkerBlockade && b.lastState != this) {
1402
                    b.setState(Center);
1403
                    return;
1404
                } else if (b.lastState == Center) {
1405
                    b.setState(ThrowOutTrash);
1406
                    return;
1407
                }
1408
1409
                // firstly search your inventory for shulkers that have the items you need
1410
                if (slot == -1 && b.searchShulkers.get()) {
1411
                    slot = findAndMoveToHotbar(b, shulkerPredicate);
1412
1413
                    if (slot != -1 && b.lastState != PlaceShulkerBlockade) {
1414
                        b.setState(PlaceShulkerBlockade);
1415
                    }
1416
                }
1417
1418
                // next search your ender chest for raw items and shulkers containing items
1419
                if (slot == -1 && b.searchEnderChest.get() && countItem(b, stack -> stack.getItem().equals(Items.ENDER_CHEST)) > 0) {
1420
                    // todo handle pulling ecs from shulker boxes so we can search through them
1421
1422
                    boolean stop = EChestMemory.isKnown();
1423
                    if (EChestMemory.isKnown()) {
1424
                        for (ItemStack stack : EChestMemory.ITEMS) {
1425
                            if (b.restockTask.materials && stack.getItem() instanceof BlockItem bi) {
1426
                                if (b.blocksToPlace.get().contains(bi.getBlock()) || (b.blocksToPlace.get().contains(Blocks.OBSIDIAN) && bi == Items.ENDER_CHEST)) {
1427
                                    stop = false;
1428
                                    break;
1429
                                }
1430
                            }
1431
                            if (b.restockTask.pickaxes && stack.is(ItemTags.PICKAXES)) {
1432
                                stop = false;
1433
                                break;
1434
                            }
1435
                            if (b.restockTask.food && Utils.isFood(stack) && !Modules.get().get(AutoEat.class).blacklist.get().contains(stack.getItem())) {
1436
                                stop = false;
1437
                                break;
1438
                            }
1439
1440
                            if (b.searchShulkers.get() && shulkerPredicate.test(stack)) {
1441
                                stop = false;
1442
                                break;
1443
                            }
1444
                        }
1445
                    }
1446
1447
                    if (!stop) slot = findAndMoveToHotbar(b, itemStack -> itemStack.getItem() == Items.ENDER_CHEST);
1448
                }
1449
1450
                // by this point we have searched shulkers and your ender chest, and no more items could be found to pull from
1451
                if (slot == -1) {
1452
                    boolean restockOccurred = (
1453
                        (b.restockTask.materials && (hasItem(b, stack -> stack.getItem() instanceof BlockItem bi && b.blocksToPlace.get().contains(bi.getBlock())) || b.blocksToPlace.get().contains(Blocks.OBSIDIAN) && countItem(b, itemStack -> itemStack.getItem() == Items.ENDER_CHEST) > b.saveEchests.get())) ||
1454
                            (b.restockTask.pickaxes && countItem(b, itemStack -> itemStack.is(ItemTags.PICKAXES)) > b.savePickaxes.get()) ||
1455
                            (b.restockTask.food && hasItem(b, itemStack -> Utils.isFood(itemStack) && !Modules.get().get(AutoEat.class).blacklist.get().contains(itemStack.getItem())))
1456
                    );
1457
1458
                    if (restockOccurred) {
1459
                        b.setState(ThrowOutTrash, Forward);
1460
                    } else b.error("Unable to perform restock for '" + b.restockTask.item() + "'.");
1461
1462
                    return;
1463
                }
1464
1465
                int restockSlots = -b.minEmpty.get();
1466
                for (int i = 0; i < b.mc.player.getInventory().getNonEquipmentItems().size(); i++) {
1467
                    if (b.mc.player.getInventory().getItem(i).isEmpty()) restockSlots++;
1468
                }
1469
1470
                if (restockSlots <= 0) {
1471
                    b.error("No empty slots for restocking items.");
1472
                    return;
1473
                }
1474
1475
                // todo when we add a digging only mode, make pickaxes fill all empty slots
1476
                minimumSlots = b.restockTask.materials ? restockSlots : 1;
1477
1478
                HorizontalDirection dir = b.dir.diagonal ? b.dir.rotateLeft().rotateLeftSkipOne() : b.dir.opposite();
1479
                pos.set(b.mc.player).offset(dir);
1480
1481
                // Quick fix for a specific issue - if your pickaxe breaks while mining echests, it will start a new
1482
                // task to restock pickaxes. However, there will be an echest placed down in the same position specified
1483
                // above, and if you have the search echest setting enabled it will assume it needs to pull items from
1484
                // your echest, even if you have a shulker full of pickaxes in your inventory.
1485
                breakContainer = b.mc.level.getBlockState(pos.getBlockPos()).getBlock() == Blocks.ENDER_CHEST;
1486
1487
                indicateStopping = false;
1488
                delayTimer = b.inventoryDelay.get();
1489
            }
1490
1491
            @Override
1492
            protected void tick(HighwayBuilder b) {
1493
                // this should only tick if there's a valid slot we can restock from
1494
                if (slot == -1) {
1495
                    b.error("Invalid restocking action.");
1496
                    return;
1497
                }
1498
1499
                if (indicateStopping && !breakContainer) {
1500
                    if (stopTimer > 0) stopTimer--;
1501
                    else {
1502
                        if (b.lastState == PlaceShulkerBlockade) {// && !(b.blocksToPlace.get().contains(Blocks.OBSIDIAN) && countItem(b, stack -> stack.getItem() == Items.ENDER_CHEST) > b.saveEchests.get() && !hasItem(b, stack -> stack.getItem() == Items.OBSIDIAN))) {
1503
                            b.setState(MineShulkerBlockade);
1504
                        } else {
1505
                            b.setState(ThrowOutTrash, Forward);
1506
                        }
1507
                    }
1508
1509
                    return;
1510
                }
1511
1512
                // prevent tasks executing when they shouldn't
1513
                if (b.restockTask.tasksInactive()) {
1514
                    b.setState(Forward);
1515
                    return;
1516
                }
1517
1518
                if (delayTimer > 0) {
1519
                    delayTimer--;
1520
                    return;
1521
                }
1522
1523
                // calculate the amount of materials we have already pulled
1524
                int slotsPulled = 0;
1525
                if (b.restockTask.materials) {
1526
                    slotsPulled += countSlots(b, itemStack -> itemStack.getItem() instanceof BlockItem bi && b.blocksToPlace.get().contains(bi.getBlock()));
1527
                    if (b.blocksToPlace.get().contains(Blocks.OBSIDIAN))
1528
                        slotsPulled += ((countItem(b, itemStack -> itemStack.getItem() == Items.ENDER_CHEST) - b.saveEchests.get()) * 8) / 64;
1529
                }
1530
                if (b.restockTask.pickaxes)
1531
                    slotsPulled += countSlots(b, itemStack -> itemStack.is(ItemTags.PICKAXES)) - b.savePickaxes.get();
1532
                if (b.restockTask.food)
1533
                    slotsPulled += countSlots(b, itemStack -> Utils.isFood(itemStack) && !Modules.get().get(AutoEat.class).blacklist.get().contains(itemStack.getItem()));
1534
1535
1536
                // whether we have pulled the minimum amount of items we want
1537
                if (slotsPulled >= minimumSlots && !indicateStopping) {
1538
                    indicateStopping = true;
1539
                    breakContainer = true;
1540
                    stopTimer = 12;
1541
                    if (b.mc.gui.screen() != null) b.mc.gui.screen().onClose();
1542
                    return;
1543
                }
1544
1545
                // Check block state
1546
                BlockPos blockPos = pos.getBlockPos();
1547
                BlockState blockState = b.mc.level.getBlockState(blockPos);
1548
1549
                switch (blockState.getBlock()) {
1550
                    // if we have placed a shulker box there should be items inside we want
1551
                    case ShulkerBoxBlock _ -> {
1552
                        if (b.mc.gui.screen() instanceof ShulkerBoxScreen screen) {
1553
                            // wait for the screen to be properly loaded
1554
                            if (screen.getMenu().containerId != b.containerId) return;
1555
1556
                            Container inv = ((ShulkerBoxMenuAccessor) screen.getMenu()).meteor$getContainer();
1557
1558
                            if (restockItems(b, inv)) {
1559
                                delayTimer = b.inventoryDelay.get();
1560
                                return;
1561
                            }
1562
1563
                            // we have taken everything we can from the shulker box, and since slotsPulled >= minimumSlots is false, we should keep going
1564
                            // close the screen, break the shulker box, look for more containers to loot from
1565
                            b.mc.gui.screen().onClose();
1566
                            breakContainer = true;
1567
                        } else {
1568
                            if (!b.searchShulkers.get()) breakContainer = true;
1569
                            handleContainerBlock(b, blockPos);
1570
                        }
1571
                    }
1572
1573
                    // we are either pulling items themselves, or shulkers containing items from your ec
1574
                    case EnderChestBlock _ -> {
1575
                        if (b.mc.gui.screen() instanceof ContainerScreen screen) {
1576
                            // wait for the screen to be properly loaded
1577
                            if (screen.getMenu().containerId != b.containerId) return;
1578
1579
                            Container inv = screen.getMenu().getContainer();
1580
1581
                            if (restockItems(b, inv)) {
1582
                                delayTimer = b.inventoryDelay.get();
1583
                                return;
1584
                            }
1585
1586
                            // we may have taken items themselves from the ec, but still need more. Now we try to find a shulker containing the items
1587
                            if (b.searchShulkers.get()) {
1588
                                int moveTo = InvUtils.findEmpty().slot();
1589
1590
                                if (moveTo != -1) {
1591
                                    for (int i = 0; i < inv.getContainerSize(); i++) {
1592
                                        if (shulkerPredicate.test(inv.getItem(i))) {
1593
                                            InvUtils.move().fromId(i).to(moveTo);
1594
                                            delayTimer = b.inventoryDelay.get();
1595
                                            break;
1596
                                        }
1597
                                    }
1598
                                }
1599
                            }
1600
1601
                            // if it reaches here, we have taken everything we can from your ender chest, and may have also grabbed a shulker
1602
                            // we should be finished in your ender chest, so we can break it and either continue on our way or start checking shulkers
1603
                            b.mc.gui.screen().onClose();
1604
                            breakContainer = true;
1605
                        } else {
1606
                            if (!b.searchEnderChest.get()) breakContainer = true;
1607
                            handleContainerBlock(b, blockPos);
1608
                        }
1609
                    }
1610
1611
                    // handling when there is no container there
1612
                    case AirBlock _ -> {
1613
                        // indicates we have just broken a container
1614
                        if (breakContainer) {
1615
                            breakContainer = false;
1616
1617
                            // if we don't signal intent to stop, we loop back to the start and continue restocking
1618
                            if (indicateStopping) b.restockTask.complete();
1619
                            else start(b);
1620
1621
                            return;
1622
                        }
1623
1624
                        BlockUtils.place(blockPos, InteractionHand.MAIN_HAND, slot, b.rotation.get().place, 0, true, true, false);
1625
                    }
1626
1627
                    // the only valid blocks should be air, a shulker box, or an ender chest
1628
                    // if there is another type of block, assume something has gone wrong and error out (e.g. lava flowed in)
1629
                    default -> b.error("Invalid block at container restocking position?");
1630
                }
1631
            }
1632
1633
            private boolean restockItems(HighwayBuilder b, Container inv) {
1634
                if (b.restockTask.materials) {
1635
                    // take raw material
1636
                    if (grabFromInventory(inv, itemStack -> itemStack.getItem() instanceof BlockItem bi && b.blocksToPlace.get().contains(bi.getBlock())))
1637
                        return true;
1638
1639
                    // prefer taking raw material before echests
1640
                    if (b.blocksToPlace.get().contains(Blocks.OBSIDIAN)) {
1641
                        if (grabFromInventory(inv, itemStack -> itemStack.getItem() == Items.ENDER_CHEST)) return true;
1642
                    }
1643
                }
1644
                if (b.restockTask.pickaxes) {
1645
                    if (grabFromInventory(inv, itemStack -> itemStack.is(ItemTags.PICKAXES))) return true;
1646
                }
1647
                if (b.restockTask.food) {
1648
                    return grabFromInventory(inv, itemStack -> Utils.isFood(itemStack) && !Modules.get().get(AutoEat.class).blacklist.get().contains(itemStack.getItem()));
1649
                }
1650
1651
                return false;
1652
            }
1653
1654
            // scans the inventory, takes out the first item that matches the predicate and returns
1655
            private boolean grabFromInventory(Container inv, Predicate<ItemStack> filterItem) {
1656
                for (int i = 0; i < inv.getContainerSize(); i++) {
1657
                    if (filterItem.test(inv.getItem(i))) {
1658
                        InvUtils.shiftClick().slotId(i);
1659
                        return true;
1660
                    }
1661
                }
1662
1663
                return false;
1664
            }
1665
1666
            private void setShulkerPredicate(HighwayBuilder b) {
1667
                shulkerPredicate = itemStack -> {
1668
                    if (!Utils.isShulker(itemStack.getItem())) return false;
1669
                    Utils.getItemsInContainerItem(itemStack, ITEMS);
1670
1671
                    for (ItemStack stack : ITEMS) {
1672
                        if (b.restockTask.materials && stack.getItem() instanceof BlockItem bi) {
1673
                            if (b.blocksToPlace.get().contains(bi.getBlock()) || (b.blocksToPlace.get().contains(Blocks.OBSIDIAN) && bi == Items.ENDER_CHEST))
1674
                                return true;
1675
                        }
1676
                        if (b.restockTask.pickaxes && stack.is(ItemTags.PICKAXES)) return true;
1677
                        if (b.restockTask.food && Utils.isFood(stack) && !Modules.get().get(AutoEat.class).blacklist.get().contains(stack.getItem()))
1678
                            return true;
1679
                    }
1680
1681
                    return false;
1682
                };
1683
            }
1684
1685
            private void handleContainerBlock(HighwayBuilder b, BlockPos bp) {
1686
                if (breakContainer) {
1687
                    BlockState state = b.mc.level.getBlockState(bp);
1688
1689
                    int toolSlot = findAndMoveBestToolToHotbar(b, state, false);
1690
                    InvUtils.swap(toolSlot, false);
1691
1692
                    if (b.rotation.get().mine)
1693
                        Rotations.rotate(Rotations.getYaw(bp), Rotations.getPitch(bp), () -> BlockUtils.breakBlock(bp, true));
1694
                    else BlockUtils.breakBlock(bp, true);
1695
                } else {
1696
                    if (b.rotation.get().place) {
1697
                        Rotations.rotate(Rotations.getYaw(bp), Rotations.getPitch(bp), () ->
1698
                            b.mc.gameMode.useItemOn(b.mc.player, InteractionHand.MAIN_HAND, new BlockHitResult(Vec3.atCenterOf(bp), Direction.UP, bp, false))
1699
                        );
1700
                    } else
1701
                        b.mc.gameMode.useItemOn(b.mc.player, InteractionHand.MAIN_HAND, new BlockHitResult(Vec3.atCenterOf(bp), Direction.UP, bp, false));
1702
1703
                    delayTimer = b.inventoryDelay.get();
1704
                }
1705
            }
1706
1707
            private int countSlots(HighwayBuilder b, Predicate<ItemStack> predicate) {
1708
                int count = 0;
1709
                for (int i = 0; i < b.mc.player.getInventory().getNonEquipmentItems().size(); i++) {
1710
                    ItemStack stack = b.mc.player.getInventory().getItem(i);
1711
                    if (predicate.test(stack)) count++;
1712
                }
1713
1714
                return count;
1715
            }
1716
        },
1717
1718
        PlaceShulkerBlockade {
1719
            @Override
1720
            protected void tick(HighwayBuilder b) {
1721
                int slot = findBlocksToPlacePrioritizeTrash(b);
1722
                if (slot == -1) return;
1723
1724
                place(b, b.blockPosProvider.getBlockade(false, BlockadeType.Shulker), slot, Restock);
1725
            }
1726
        },
1727
1728
        MineShulkerBlockade {
1729
            private boolean stopTimerEnabled;
1730
            private int stopTimer;
1731
1732
            @Override
1733
            protected void start(HighwayBuilder b) {
1734
                stopTimerEnabled = false;
1735
                if (b.lastState == this) {
1736
                    stopTimerEnabled = true;
1737
                    stopTimer = 12;
1738
                }
1739
            }
1740
1741
            @Override
1742
            protected void tick(HighwayBuilder b) {
1743
                if (!stopTimerEnabled) {
1744
                    // mining b.blockadeType instead of BlockadeType.Shulker is the fastest fix to the module leaving
1745
                    // some blocks behind if you start a pickaxe restock task while mining echests
1746
                    mine(b, b.blockPosProvider.getBlockade(true, b.blockadeType.get()), true, this, this);
1747
                } else {
1748
                    stopTimer--;
1749
                    if (stopTimer <= 0) {
1750
                        b.setState(ThrowOutTrash, Forward);
1751
                    }
1752
                }
1753
            }
1754
        },
1755
1756
        DefuseCrystalTraps {
1757
            private int cooldown,shots;
1758
            private EndCrystal target;
1759
1760
            @Override
1761
            protected void start(HighwayBuilder b) {
1762
                if (!InvUtils.find(Items.BOW).found() || (!InvUtils.find(itemStack -> itemStack.getItem() instanceof ArrowItem).found() && !b.mc.player.getAbilities().instabuild)) {
1763
                    b.destroyCrystalTraps.set(false);
1764
                    b.warning("No bow found to destroy crystal traps with. Toggling the setting off.");
1765
                    b.setState(Forward);
1766
                }
1767
1768
                shots = cooldown = 0;
1769
                target = null;
1770
            }
1771
1772
            /**
1773
             * Need to perform the linked injection to ensure that vanilla code does not interfere with us drawing our
1774
             * bow. The {@link net.minecraft.client.Minecraft#handleKeybinds} method is only called when you are not in a screen,
1775
             * meaning we cannot draw our bow using {@link net.minecraft.client.Options#keyUse} since it would not work if you are in a
1776
             * screen. Similarly, drawing our bow by {@link net.minecraft.client.multiplayer.MultiPlayerGameMode#useItem} would get
1777
             * cancelled by default within the handleKeybinds method if you do not have the use key held down,
1778
             * essentially meaning without the following injection it would not work if you don't have a screen open.
1779
             *
1780
             * @see MinecraftMixin#wrapStopUsing(MultiPlayerGameMode, Player)
1781
             */
1782
            @Override
1783
            protected void tick(HighwayBuilder b) {
1784
                if (cooldown > 0) {
1785
                    cooldown--;
1786
                    return;
1787
                }
1788
1789
                if (!InvUtils.testInMainHand(Items.BOW)) {
1790
                    int slot = findAndMoveToHotbar(b, itemStack -> itemStack.getItem() instanceof BowItem);
1791
                    if (slot == -1) {
1792
                        b.destroyCrystalTraps.set(false);
1793
                        b.warning("No bow found to destroy crystal traps with. Toggling the setting off.");
1794
                        b.setState(Forward);
1795
                        b.mc.gameMode.releaseUsingItem(b.mc.player);
1796
                        b.drawingBow = false;
1797
                        return;
1798
                    }
1799
1800
                    InvUtils.swap(slot, false);
1801
                }
1802
1803
                EndCrystal potentialTarget = (EndCrystal) TargetUtils.get(entity -> {
1804
                    if (!(entity instanceof EndCrystal endCrystal)) return false;
1805
                    if (PlayerUtils.isWithin(endCrystal, 12) || !PlayerUtils.isWithin(endCrystal, 24)) return false;
1806
                    if (b.ignoreCrystals.contains(endCrystal)) return false;
1807
1808
                    Vec3 vec1 = new Vec3(0, 0, 0);
1809
                    Vec3 vec2 = new Vec3(0, 0, 0);
1810
1811
                    ((IVec3) vec1).meteor$set(b.mc.player.getX(), b.mc.player.getY() + b.mc.player.getEyeHeight(), b.mc.player.getZ());
1812
                    ((IVec3) vec2).meteor$set(entity.getX(), entity.getY() + 0.5, entity.getZ());
1813
                    return b.mc.level.clip(new ClipContext(vec1, vec2, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, b.mc.player)).getType() == HitResult.Type.MISS;
1814
                }, SortPriority.LowestDistance);
1815
1816
                if (target == null || target.isRemoved()) {
1817
                    if (potentialTarget == null) {
1818
                        b.setState(Forward);
1819
                        b.mc.gameMode.releaseUsingItem(b.mc.player);
1820
                        b.drawingBow = false;
1821
                        return;
1822
                    } else {
1823
                        target = potentialTarget;
1824
                        shots = 0;
1825
                    }
1826
                }
1827
1828
                if (shots >= 3) {
1829
                    b.ignoreCrystals.add(target);
1830
                    b.warning("Detected potential hangup on a crystal. Adding it to ignore list and continuing forward.");
1831
                    b.setState(Forward);
1832
                    b.mc.gameMode.releaseUsingItem(b.mc.player);
1833
                    b.drawingBow = false;
1834
                    return;
1835
                }
1836
1837
                b.mc.player.setYRot((float) Rotations.getYaw(target));
1838
1839
                float pitch = aim(b, target);
1840
                if (Float.isNaN(pitch)) b.mc.player.setXRot((float) Rotations.getPitch(target));
1841
                else b.mc.player.setXRot(pitch);
1842
1843
                if (BowItem.getPowerForTime(b.mc.player.getTicksUsingItem() - 3) >= 1.0f) {
1844
                    b.mc.gameMode.releaseUsingItem(b.mc.player);
1845
                    b.drawingBow = false;
1846
                    cooldown = 20;
1847
                    shots++;
1848
                } else {
1849
                    b.drawingBow = true;
1850
                    b.mc.gameMode.useItem(b.mc.player, InteractionHand.MAIN_HAND);
1851
                }
1852
            }
1853
1854
            private float aim(HighwayBuilder b, Entity target) {
1855
                // Velocity based on bow charge.
1856
                float velocity = BowItem.getPowerForTime(b.mc.player.getTicksUsingItem());
1857
1858
                // Positions
1859
                Vec3 pos = target.position();
1860
1861
                double relativeX = pos.x - b.mc.player.getX();
1862
                double relativeY = pos.y + 0.5 - b.mc.player.getEyeY(); // aiming a little bit above the bottom of the crystal, hopefully prevents shooting the floor or failing the raytrace check
1863
                double relativeZ = pos.z - b.mc.player.getZ();
1864
1865
                // Calculate the pitch
1866
                double hDistance = Math.sqrt(relativeX * relativeX + relativeZ * relativeZ);
1867
                double hDistanceSq = hDistance * hDistance;
1868
                float g = 0.006f;
1869
                float velocitySq = velocity * velocity;
1870
1871
                return (float) -Math.toDegrees(Math.atan((velocitySq - Math.sqrt(velocitySq * velocitySq - g * (g * hDistanceSq + 2 * relativeY * velocitySq))) / (g * hDistance)));
1872
            }
1873
        };
1874
1875
        protected void start(HighwayBuilder b) {
1876
        }
1877
1878
        protected abstract void tick(HighwayBuilder b);
1879
1880
        protected void mine(HighwayBuilder b, MBPIterator it, boolean mineBlocksToPlace, State nextState, State lastState) {
1881
            boolean breaking = false;
1882
            boolean finishedBreaking = false; // if you can multi break this lets you mine blocks between tasks in a single tick
1883
1884
            // extract all candidates for double mining and enqueue them to be mined. After those we can break the remaining
1885
            // blocks normally
1886
            if (b.doubleMine.get()) {
1887
                // todo hold the best mining tool before performing the double mining checks so we dont double mine blocks unnecessarily
1888
                ArrayDeque<BlockPos> toDoubleMine = new ArrayDeque<>();
1889
1890
                it.save();
1891
                it.forEach(pos -> {
1892
                    // only want to double mine blocks that we can mine, that are not instamined, and we are not already mining
1893
                    if (
1894
                        BlockUtils.canBreak(pos.getBlockPos(), pos.getState())
1895
                            && (mineBlocksToPlace || !b.blocksToPlace.get().contains(pos.getState().getBlock()))
1896
                            && !BlockUtils.canInstaBreak(pos.getBlockPos()) && (!Modules.get().get(SpeedMine.class).instamine() || pos.getState().getDestroyProgress(b.mc.player, b.mc.level, pos.getBlockPos()) <= 0.5)
1897
                            && (b.normalMining == null || !pos.getBlockPos().equals(b.normalMining.blockPos))
1898
                            && (b.packetMining == null || !pos.getBlockPos().equals(b.packetMining.blockPos))
1899
                    ) {
1900
                        toDoubleMine.add(pos.getBlockPos().mutable());
1901
                    }
1902
                });
1903
1904
                // have to save and restore the iterator from the beginning to make sure the subsequent loop can use it properly
1905
                it.restore();
1906
1907
                // repeating the code for swapping to a tool, since we don't want to start mining a block if we don't
1908
                // have a tool to mine it with, but also we want to lock the slot to the tool while we are mining even
1909
                // the ArrayDequeue is empty
1910
                if (!toDoubleMine.isEmpty()) {
1911
                    int slot = findAndMoveBestToolToHotbar(b, b.mc.level.getBlockState(toDoubleMine.peek()), false);
1912
                    if (slot == -1) return;
1913
1914
                    InvUtils.swap(slot, false);
1915
                    doubleMine(b, toDoubleMine);
1916
                }
1917
1918
                if (b.normalMining != null || b.packetMining != null) {
1919
                    int slot = findAndMoveBestToolToHotbar(b, b.normalMining != null ? b.normalMining.blockState : b.packetMining.blockState, false);
1920
                    if (slot == -1) return;
1921
1922
                    InvUtils.swap(slot, false);
1923
                    return;
1924
                }
1925
            }
1926
1927
            for (MBlockPos pos : it) {
1928
                if (b.count >= b.blocksPerTick.get()) return;
1929
                if (b.breakTimer > 0) return;
1930
1931
                BlockState state = pos.getState();
1932
                if (state.isAir() || (!mineBlocksToPlace && b.blocksToPlace.get().contains(state.getBlock()))) continue;
1933
1934
                int slot = findAndMoveBestToolToHotbar(b, state, false);
1935
                if (slot == -1) return;
1936
1937
                InvUtils.swap(slot, false);
1938
1939
                BlockPos mcPos = pos.getBlockPos();
1940
                boolean multiBreak = b.blocksPerTick.get() > 1 && BlockUtils.canInstaBreak(mcPos) && !b.rotation.get().mine;
1941
                if (BlockUtils.canBreak(mcPos)) {
1942
                    if (b.rotation.get().mine)
1943
                        Rotations.rotate(Rotations.getYaw(mcPos), Rotations.getPitch(mcPos), () -> BlockUtils.breakBlock(mcPos, true));
1944
                    else BlockUtils.breakBlock(mcPos, true);
1945
                    breaking = true;
1946
1947
                    b.breakTimer = b.breakDelay.get();
1948
1949
                    if (!b.lastBreakingPos.equals(pos)) {
1950
                        b.lastBreakingPos.set(pos);
1951
                        b.blocksBroken++;
1952
                    }
1953
1954
                    b.count++;
1955
1956
                    // can only multi break if we aren't rotating and the block can be insta-mined
1957
                    if (!multiBreak) break;
1958
                }
1959
1960
                if (!it.hasNext() && BlockUtils.canInstaBreak(mcPos)) finishedBreaking = true;
1961
            }
1962
1963
            // we quickly jump to the next state, to remove micro delays in the process and allow us to break blocks
1964
            // between tasks if we can multi break
1965
            if (finishedBreaking || !breaking) {
1966
                b.setState(nextState, lastState);
1967
            }
1968
        }
1969
1970
        private void doubleMine(HighwayBuilder b, ArrayDeque<BlockPos> blocks) {
1971
            if (b.breakTimer > 0) return;
1972
1973
            if (b.normalMining == null) {
1974
                DoubleMineBlock block = new DoubleMineBlock(b, blocks.pop());
1975
                b.normalMining = block.startDestroying();
1976
1977
                b.breakTimer = b.breakDelay.get();
1978
                if (b.breakTimer > 0) return;
1979
            }
1980
1981
            if (DoubleMineBlock.rateLimited) return;
1982
1983
            if (b.packetMining == null && !blocks.isEmpty()) {
1984
                DoubleMineBlock block = new DoubleMineBlock(b, blocks.pop());
1985
1986
                if (block != null) {
1987
                    b.packetMining = b.normalMining.packetMine();
1988
                    b.normalMining = block.startDestroying();
1989
1990
                    b.breakTimer = b.breakDelay.get();
1991
                }
1992
            }
1993
        }
1994
1995
        protected void place(HighwayBuilder b, MBPIterator it, int slot, State nextState) {
1996
            boolean placed = false;
1997
            boolean finishedPlacing = false;
1998
1999
            for (MBlockPos pos : it) {
2000
                if (b.count >= it.placementsPerTick(b)) return;
2001
                if (b.placeTimer > 0) return;
2002
2003
                if (pos.getBlockPos().distToCenterSqr(b.mc.player.getEyePosition()) > b.placeRange.get() * b.placeRange.get())
2004
                    continue;
2005
2006
                if (BlockUtils.place(pos.getBlockPos(), InteractionHand.MAIN_HAND, slot, b.rotation.get().place, 0, true, true, true)) {
2007
                    placed = true;
2008
                    b.blocksPlaced++;
2009
                    b.placeTimer = b.placeDelay.get();
2010
2011
                    b.count++;
2012
                    if (b.placementsPerTick.get() == 1) break;
2013
                }
2014
2015
                if (!it.hasNext()) finishedPlacing = true;
2016
            }
2017
2018
            if (finishedPlacing || !placed) b.setState(nextState);
2019
        }
2020
2021
        private int findSlot(HighwayBuilder b, Predicate<ItemStack> predicate, boolean hotbar) {
2022
            for (int i = hotbar ? 0 : 9; i < (hotbar ? 9 : b.mc.player.getInventory().getNonEquipmentItems().size()); i++) {
2023
                if (predicate.test(b.mc.player.getInventory().getItem(i))) return i;
2024
            }
2025
2026
            return -1;
2027
        }
2028
2029
        protected int findHotbarSlot(HighwayBuilder b, boolean replaceTools) {
2030
            int thrashSlot = -1;
2031
            int slotsWithBlocks = 0;
2032
            int slotWithLeastBlocks = -1;
2033
            int slotWithLeastBlocksCount = Integer.MAX_VALUE;
2034
2035
            // Loop hotbar
2036
            for (int i = 0; i < 9; i++) {
2037
                ItemStack itemStack = b.mc.player.getInventory().getItem(i);
2038
2039
                // Return if the slot is empty
2040
                if (itemStack.isEmpty()) return i;
2041
2042
                // Return if the slot contains a tool and replacing tools is enabled
2043
                if (replaceTools && AutoTool.isTool(itemStack)) return i;
2044
2045
                // Store the slot if it contains thrash
2046
                if (b.trashItems.get().contains(itemStack.getItem())) thrashSlot = i;
2047
2048
                // Update tracked stats about slots that contain building blocks
2049
                if (itemStack.getItem() instanceof BlockItem blockItem && (b.blocksToPlace.get().contains(blockItem.getBlock()) || b.blocksToPlace.get().contains(Blocks.OBSIDIAN) && blockItem == Items.ENDER_CHEST)) {
2050
                    slotsWithBlocks++;
2051
2052
                    if (itemStack.getCount() < slotWithLeastBlocksCount) {
2053
                        slotWithLeastBlocksCount = itemStack.getCount();
2054
                        slotWithLeastBlocks = i;
2055
                    }
2056
                }
2057
            }
2058
2059
            // Return thrash slot if found
2060
            if (thrashSlot != -1) return thrashSlot;
2061
2062
            // If there are more than 1 slots with building blocks return the slot with the lowest amount of blocks
2063
            if (slotsWithBlocks > 0) return slotWithLeastBlocks;
2064
2065
            // No space found in hotbar
2066
            b.error("No empty space in hotbar.");
2067
            return -1;
2068
        }
2069
2070
        protected boolean hasItem(HighwayBuilder b, Predicate<ItemStack> predicate) {
2071
            for (int i = 0; i < b.mc.player.getInventory().getNonEquipmentItems().size(); i++) {
2072
                if (predicate.test(b.mc.player.getInventory().getItem(i))) return true;
2073
            }
2074
2075
            return false;
2076
        }
2077
2078
        protected int countItem(HighwayBuilder b, Predicate<ItemStack> predicate) {
2079
            int count = 0;
2080
            for (int i = 0; i < b.mc.player.getInventory().getNonEquipmentItems().size(); i++) {
2081
                ItemStack stack = b.mc.player.getInventory().getItem(i);
2082
                if (predicate.test(stack)) count += stack.getCount();
2083
            }
2084
2085
            return count;
2086
        }
2087
2088
        protected int findAndMoveToHotbar(HighwayBuilder b, Predicate<ItemStack> predicate) {
2089
            // Check hotbar
2090
            int slot = findSlot(b, predicate, true);
2091
            if (slot != -1) return slot;
2092
2093
            // Find hotbar slot to move to
2094
            int hotbarSlot = findHotbarSlot(b, false);
2095
            if (hotbarSlot == -1) return -1;
2096
2097
            // Check inventory
2098
            slot = findSlot(b, predicate, false);
2099
2100
            // Return if no items were found
2101
            if (slot == -1) return -1;
2102
2103
            // Move items from inventory to hotbar
2104
            InvUtils.move().from(slot).toHotbar(hotbarSlot);
2105
            InvUtils.dropHand();
2106
2107
            return hotbarSlot;
2108
        }
2109
2110
        protected int findAndMoveBestToolToHotbar(HighwayBuilder b, BlockState blockState, boolean noSilkTouch) {
2111
            // Check for creative
2112
            if (b.mc.player.isCreative()) return b.mc.player.getInventory().getSelectedSlot();
2113
2114
            // Find best tool
2115
            double bestScore = -1;
2116
            int bestSlot = -1;
2117
2118
            for (int i = 0; i < b.mc.player.getInventory().getNonEquipmentItems().size(); i++) {
2119
                double score = AutoTool.getScore(b.mc.player.getInventory().getItem(i), blockState, false, false, AutoTool.EnchantPreference.None, itemStack -> {
2120
                    if (noSilkTouch && Utils.hasEnchantment(itemStack, Enchantments.SILK_TOUCH)) return false;
2121
                    return !b.dontBreakTools.get() || itemStack.getMaxDamage() - itemStack.getDamageValue() > (itemStack.getMaxDamage() * (b.breakDurability.get() / 100));
2122
                });
2123
2124
                if (score > bestScore) {
2125
                    bestScore = score;
2126
                    bestSlot = i;
2127
                }
2128
            }
2129
2130
            if (bestSlot == -1) return b.mc.player.getInventory().getSelectedSlot();
2131
2132
            ItemStack bestStack = b.mc.player.getInventory().getItem(bestSlot);
2133
            if (bestStack.is(ItemTags.PICKAXES)) {
2134
                int count = countItem(b, stack -> stack.is(ItemTags.PICKAXES));
2135
2136
                // If we are in the process of restocking pickaxes and happen to need one, we should allow using it
2137
                // as long as it has enough durability, since we will obtain more shortly thereafter
2138
                if (count <= b.savePickaxes.get() && !(b.restockTask.pickaxes && bestStack.getMaxDamage() - bestStack.getDamageValue() > (bestStack.getMaxDamage() * (b.breakDurability.get() / 100)))) {
2139
                    if (!b.restockTask.pickaxes && (b.searchEnderChest.get() || b.searchShulkers.get())) {
2140
                        b.restockTask.setPickaxes();
2141
                    } else {
2142
                        b.error("Found less than the minimum amount of pickaxes required: " + count + "/" + (b.savePickaxes.get() + 1));
2143
                    }
2144
2145
                    return -1;
2146
                }
2147
            }
2148
2149
            // Check if the tool is already in hotbar
2150
            if (bestSlot < 9) return bestSlot;
2151
2152
            // Find hotbar slot to move to
2153
            int hotbarSlot = findHotbarSlot(b, true);
2154
            if (hotbarSlot == -1) return -1;
2155
2156
            // Move tool from inventory to hotbar
2157
            InvUtils.move().from(bestSlot).toHotbar(hotbarSlot);
2158
            InvUtils.dropHand();
2159
2160
            return hotbarSlot;
2161
        }
2162
2163
        protected int findBlocksToPlace(HighwayBuilder b) {
2164
            // find a block and move it to your hotbar
2165
            int slot = findAndMoveToHotbar(b, itemStack -> itemStack.getItem() instanceof BlockItem blockItem && b.blocksToPlace.get().contains(blockItem.getBlock()));
2166
2167
            if (slot == -1) {
2168
                if (b.mineEnderChests.get() && b.blocksToPlace.get().contains(Blocks.OBSIDIAN) && countItem(b, stack -> stack.getItem().equals(Items.ENDER_CHEST)) > b.saveEchests.get()) {
2169
                    // can grind echests for obsidian
2170
                    b.setState(MineEnderChests);
2171
                } else if (b.searchEnderChest.get() || b.searchShulkers.get()) {
2172
                    // start restocking if we're allowed
2173
                    b.restockTask.setMaterials();
2174
                } else {
2175
                    b.error("Out of blocks to place.");
2176
                }
2177
2178
                return -1;
2179
            }
2180
2181
            return slot;
2182
        }
2183
2184
        protected int findBlocksToPlacePrioritizeTrash(HighwayBuilder b) {
2185
            int slot = findAndMoveToHotbar(b, itemStack -> {
2186
                if (!(itemStack.getItem() instanceof BlockItem)) return false;
2187
                return b.trashItems.get().contains(itemStack.getItem());
2188
            });
2189
2190
            return slot != -1 ? slot : findBlocksToPlace(b);
2191
        }
2192
    }
2193
2194
    private interface MBPIterator extends Iterator<MBlockPos>, Iterable<MBlockPos> {
2195
        void save();
2196
2197
        void restore();
2198
2199
        @NonNull
2200
        @Override
2201
        default Iterator<MBlockPos> iterator() {
2202
            return this;
2203
        }
2204
2205
        default int placementsPerTick(HighwayBuilder b) {
2206
            return b.placementsPerTick.get();
2207
        }
2208
    }
2209
2210
    private static class MBPIteratorFilter implements MBPIterator {
2211
        private final MBPIterator it;
2212
        private final Predicate<MBlockPos> predicate;
2213
2214
        private MBlockPos pos;
2215
        private boolean isOld = true;
2216
2217
        private boolean pisOld = true;
2218
2219
        public MBPIteratorFilter(MBPIterator it, Predicate<MBlockPos> predicate) {
2220
            this.it = it;
2221
            this.predicate = predicate;
2222
        }
2223
2224
        @Override
2225
        public void save() {
2226
            it.save();
2227
            pisOld = isOld;
2228
            isOld = true;
2229
        }
2230
2231
        @Override
2232
        public void restore() {
2233
            it.restore();
2234
            isOld = pisOld;
2235
        }
2236
2237
        @Override
2238
        public boolean hasNext() {
2239
            if (isOld) {
2240
                isOld = false;
2241
                pos = null;
2242
2243
                while (it.hasNext()) {
2244
                    pos = it.next();
2245
2246
                    if (predicate.test(pos)) return true;
2247
                    else pos = null;
2248
                }
2249
            }
2250
2251
            return pos != null && predicate.test(pos);
2252
        }
2253
2254
        @Override
2255
        public MBlockPos next() {
2256
            isOld = true;
2257
            return pos;
2258
        }
2259
    }
2260
2261
    private interface IBlockPosProvider {
2262
        MBPIterator getFront();
2263
2264
        MBPIterator getFloor();
2265
2266
        /**
2267
         * state:
2268
         * 1 for above the railings,
2269
         * 0 for the railings themselves,
2270
         * -1 for the block under the railings
2271
         */
2272
        MBPIterator getRailings(int state);
2273
2274
        MBPIterator getLiquids();
2275
2276
        MBPIterator getBlockade(boolean mine, BlockadeType type);
2277
    }
2278
2279
    private class StraightBlockPosProvider implements IBlockPosProvider {
2280
        private final MBlockPos pos = new MBlockPos();
2281
        private final MBlockPos pos2 = new MBlockPos();
2282
2283
        @Override
2284
        public MBPIterator getFront() {
2285
            pos.coerceBlockLevel(mc.player).offset(dir).offset(leftDir, getWidthLeft());
2286
2287
            return new MBPIterator() {
2288
                private int w, y;
2289
                private int pw, py;
2290
2291
                @Override
2292
                public boolean hasNext() {
2293
                    return w < width.get() && y < height.get();
2294
                }
2295
2296
                @Override
2297
                public MBlockPos next() {
2298
                    pos2.set(pos).offset(rightDir, w).add(0, y, 0);
2299
2300
                    w++;
2301
                    if (w >= width.get()) {
2302
                        w = 0;
2303
                        y++;
2304
                    }
2305
2306
                    return pos2;
2307
                }
2308
2309
                @Override
2310
                public void save() {
2311
                    pw = w;
2312
                    py = y;
2313
                    w = y = 0;
2314
                }
2315
2316
                @Override
2317
                public void restore() {
2318
                    w = pw;
2319
                    y = py;
2320
                }
2321
            };
2322
        }
2323
2324
        @Override
2325
        public MBPIterator getFloor() {
2326
            pos.coerceBlockLevel(mc.player).offset(dir).offset(leftDir, getWidthLeft()).add(0, -1, 0);
2327
2328
            return new MBPIterator() {
2329
                private int w;
2330
                private int pw;
2331
2332
                @Override
2333
                public boolean hasNext() {
2334
                    return w < width.get();
2335
                }
2336
2337
                @Override
2338
                public MBlockPos next() {
2339
                    return pos2.set(pos).offset(rightDir, w++);
2340
                }
2341
2342
                @Override
2343
                public void save() {
2344
                    pw = w;
2345
                    w = 0;
2346
                }
2347
2348
                @Override
2349
                public void restore() {
2350
                    w = pw;
2351
                }
2352
            };
2353
        }
2354
2355
        @Override
2356
        public MBPIterator getRailings(int state) {
2357
            pos.coerceBlockLevel(mc.player).offset(dir);
2358
2359
            return new MBPIterator() {
2360
                private int i, y = state;
2361
                private int pi, py;
2362
2363
                @Override
2364
                public boolean hasNext() {
2365
                    // state == 1 : height
2366
                    // state == 0 : 1
2367
                    // state == -1 : 0
2368
                    return i < 2 && y < (state == 1 ? height.get() : state + 1);
2369
                }
2370
2371
                @Override
2372
                public MBlockPos next() {
2373
                    if (i == 0) pos2.set(pos).offset(leftDir, getWidthLeft() + 1).add(0, y, 0);
2374
                    else pos2.set(pos).offset(rightDir, getWidthRight() + 1).add(0, y, 0);
2375
2376
                    y++;
2377
                    if (y >= (state == 1 ? height.get() : state + 1)) {
2378
                        y = state;
2379
                        i++;
2380
                    }
2381
2382
                    return pos2;
2383
                }
2384
2385
                @Override
2386
                public void save() {
2387
                    pi = i;
2388
                    py = y;
2389
                    i = 0;
2390
                    y = state;
2391
                }
2392
2393
                @Override
2394
                public void restore() {
2395
                    i = pi;
2396
                    y = py;
2397
                }
2398
            };
2399
        }
2400
2401
        @Override
2402
        public MBPIterator getLiquids() {
2403
            pos.coerceBlockLevel(mc.player).offset(dir, 2).offset(leftDir, getWidthLeft() + (mineAboveRailings.get() ? 2 : 1));
2404
2405
            return new MBPIterator() {
2406
                private int w, y;
2407
                private int pw, py;
2408
2409
                private int getWidth() {
2410
                    return width.get() + (mineAboveRailings.get() ? 2 : 0);
2411
                }
2412
2413
                @Override
2414
                public boolean hasNext() {
2415
                    return w < getWidth() + 2 && y < height.get() + 1;
2416
                }
2417
2418
                @Override
2419
                public MBlockPos next() {
2420
                    pos2.set(pos).offset(rightDir, w).add(0, y, 0);
2421
2422
                    w++;
2423
                    if (w >= getWidth() + 2) {
2424
                        w = 0;
2425
                        y++;
2426
                    }
2427
2428
                    return pos2;
2429
                }
2430
2431
                @Override
2432
                public void save() {
2433
                    pw = w;
2434
                    py = y;
2435
                    w = y = 0;
2436
                }
2437
2438
                @Override
2439
                public void restore() {
2440
                    w = pw;
2441
                    y = py;
2442
                }
2443
            };
2444
        }
2445
2446
        @Override
2447
        public MBPIterator getBlockade(boolean mine, BlockadeType blockadeType) {
2448
            return new MBPIterator() {
2449
                private int i = mine ? -1 : 0, y;
2450
                private int pi, py;
2451
2452
                private MBlockPos get(int i) {
2453
                    pos.coerceBlockLevel(mc.player).offset(dir.opposite());
2454
2455
                    return switch (i) {
2456
                        case -1 -> pos;
2457
                        case 0 -> pos.offset(dir.opposite());
2458
                        case 1 -> pos.offset(leftDir);
2459
                        case 2 -> pos.offset(rightDir);
2460
                        case 3 -> pos.offset(dir, 2);
2461
                        case 4 -> pos.offset(dir).offset(leftDir);
2462
                        case 5 -> pos.offset(dir).offset(rightDir);
2463
                        default -> throw new IllegalStateException("Unexpected value: " + i);
2464
                    };
2465
                }
2466
2467
                @Override
2468
                public boolean hasNext() {
2469
                    return i < blockadeType.columns && y < 2;
2470
                }
2471
2472
                @Override
2473
                public MBlockPos next() {
2474
                    if (width.get() == 1 && railings.get() && i > 0 && y == 0) y++;
2475
2476
                    MBlockPos pos = get(i).add(0, y, 0);
2477
2478
                    y++;
2479
                    if (y > 1) {
2480
                        y = 0;
2481
                        i++;
2482
                    }
2483
2484
                    return pos;
2485
                }
2486
2487
                @Override
2488
                public void save() {
2489
                    pi = i;
2490
                    py = y;
2491
                    i = y = 0;
2492
                }
2493
2494
                @Override
2495
                public void restore() {
2496
                    i = pi;
2497
                    y = py;
2498
                }
2499
2500
                @Override
2501
                public int placementsPerTick(HighwayBuilder b) {
2502
                    return 1;
2503
                }
2504
            };
2505
        }
2506
    }
2507
2508
    private class DiagonalBlockPosProvider implements IBlockPosProvider {
2509
        private final MBlockPos pos = new MBlockPos();
2510
        private final MBlockPos pos2 = new MBlockPos();
2511
2512
        @Override
2513
        public MBPIterator getFront() {
2514
            pos.coerceBlockLevel(mc.player).offset(dir.rotateLeft()).offset(leftDir, getWidthLeft() - 1);
2515
2516
            return new MBPIterator() {
2517
                private int i, w, y;
2518
                private int pi, pw, py;
2519
2520
                @Override
2521
                public boolean hasNext() {
2522
                    return i < 2 && w < width.get() && y < height.get();
2523
                }
2524
2525
                @Override
2526
                public MBlockPos next() {
2527
                    pos2.set(pos).offset(rightDir, w).add(0, y++, 0);
2528
2529
                    if (y >= height.get()) {
2530
                        y = 0;
2531
                        w++;
2532
2533
                        if (w >= (i == 0 ? width.get() - 1 : width.get())) {
2534
                            w = 0;
2535
                            i++;
2536
2537
                            pos.coerceBlockLevel(mc.player).offset(dir).offset(leftDir, getWidthLeft());
2538
                        }
2539
                    }
2540
2541
                    return pos2;
2542
                }
2543
2544
                private void initPos() {
2545
                    if (i == 0)
2546
                        pos.coerceBlockLevel(mc.player).offset(dir.rotateLeft()).offset(leftDir, getWidthLeft() - 1);
2547
                    else pos.coerceBlockLevel(mc.player).offset(dir).offset(leftDir, getWidthLeft());
2548
                }
2549
2550
                @Override
2551
                public void save() {
2552
                    pi = i;
2553
                    pw = w;
2554
                    py = y;
2555
                    i = w = y = 0;
2556
2557
                    initPos();
2558
                }
2559
2560
                @Override
2561
                public void restore() {
2562
                    i = pi;
2563
                    w = pw;
2564
                    y = py;
2565
2566
                    initPos();
2567
                }
2568
            };
2569
        }
2570
2571
        @Override
2572
        public MBPIterator getFloor() {
2573
            pos.coerceBlockLevel(mc.player).add(0, -1, 0).offset(dir.rotateLeft()).offset(leftDir, getWidthLeft() - 1);
2574
2575
            return new MBPIterator() {
2576
                private int i, w;
2577
                private int pi, pw;
2578
2579
                @Override
2580
                public boolean hasNext() {
2581
                    return i < 2 && w < width.get();
2582
                }
2583
2584
                @Override
2585
                public MBlockPos next() {
2586
                    pos2.set(pos).offset(rightDir, w++);
2587
2588
                    if (w >= (i == 0 ? width.get() - 1 : width.get())) {
2589
                        w = 0;
2590
                        i++;
2591
2592
                        pos.coerceBlockLevel(mc.player).add(0, -1, 0).offset(dir).offset(leftDir, getWidthLeft());
2593
                    }
2594
2595
                    return pos2;
2596
                }
2597
2598
                private void initPos() {
2599
                    if (i == 0)
2600
                        pos.coerceBlockLevel(mc.player).add(0, -1, 0).offset(dir.rotateLeft()).offset(leftDir, getWidthLeft() - 1);
2601
                    else pos.coerceBlockLevel(mc.player).add(0, -1, 0).offset(dir).offset(leftDir, getWidthLeft());
2602
                }
2603
2604
                @Override
2605
                public void save() {
2606
                    pi = i;
2607
                    pw = w;
2608
                    i = w = 0;
2609
2610
                    initPos();
2611
                }
2612
2613
                @Override
2614
                public void restore() {
2615
                    i = pi;
2616
                    w = pw;
2617
2618
                    initPos();
2619
                }
2620
            };
2621
        }
2622
2623
        @Override
2624
        public MBPIterator getRailings(int state) {
2625
            pos.coerceBlockLevel(mc.player).offset(dir.rotateLeft()).offset(leftDir, getWidthLeft());
2626
2627
            return new MBPIterator() {
2628
                private int i, y = state;
2629
                private int pi, py;
2630
2631
                @Override
2632
                public boolean hasNext() {
2633
                    return i < 2 && y < (state == 1 ? height.get() : state + 1);
2634
                }
2635
2636
                @Override
2637
                public MBlockPos next() {
2638
                    pos2.set(pos).add(0, y++, 0);
2639
2640
                    if (y >= (state == 1 ? height.get() : state + 1)) {
2641
                        y = state;
2642
                        i++;
2643
2644
                        pos.coerceBlockLevel(mc.player).offset(dir.rotateRight()).offset(rightDir, getWidthRight());
2645
                    }
2646
2647
                    return pos2;
2648
                }
2649
2650
                private void initPos() {
2651
                    if (i == 0)
2652
                        pos.coerceBlockLevel(mc.player).offset(dir.rotateLeft()).offset(leftDir, getWidthLeft());
2653
                    else pos.coerceBlockLevel(mc.player).offset(dir.rotateRight()).offset(rightDir, getWidthRight());
2654
                }
2655
2656
                @Override
2657
                public void save() {
2658
                    pi = i;
2659
                    py = y;
2660
                    i = 0;
2661
                    y = state;
2662
2663
                    initPos();
2664
                }
2665
2666
                @Override
2667
                public void restore() {
2668
                    i = pi;
2669
                    y = py;
2670
2671
                    initPos();
2672
                }
2673
            };
2674
        }
2675
2676
        @Override
2677
        public MBPIterator getLiquids() {
2678
            boolean m = mineAboveRailings.get();
2679
            pos.coerceBlockLevel(mc.player).offset(dir).offset(dir.rotateLeft()).offset(leftDir, getWidthLeft());
2680
2681
            return new MBPIterator() {
2682
                private int i, w, y;
2683
                private int pi, pw, py;
2684
2685
                private int getWidth() {
2686
                    return width.get() + (i == 0 ? 1 : 0) + (m && i == 1 ? 2 : 0);
2687
                }
2688
2689
                @Override
2690
                public boolean hasNext() {
2691
                    if (m && i == 1 && y == height.get() && w == getWidth() - 1) return false;
2692
                    return i < 2 && w < getWidth() && y < height.get() + 1;
2693
                }
2694
2695
                private void updateW() {
2696
                    w++;
2697
2698
                    if (w >= getWidth()) {
2699
                        w = 0;
2700
                        i++;
2701
2702
                        pos.coerceBlockLevel(mc.player).offset(dir, 2).offset(leftDir, getWidthLeft() + (m ? 1 : 0));
2703
                    }
2704
                }
2705
2706
                @Override
2707
                public MBlockPos next() {
2708
                    if (i == (m ? 1 : 0) && y == height.get() && (w == 0 || w == getWidth() - 1)) {
2709
                        y = 0;
2710
                        updateW();
2711
                    }
2712
2713
                    pos2.set(pos).offset(rightDir, w).add(0, y++, 0);
2714
2715
                    if (y >= height.get() + 1) {
2716
                        y = 0;
2717
                        updateW();
2718
                    }
2719
2720
                    return pos2;
2721
                }
2722
2723
                private void initPos() {
2724
                    if (i == 0)
2725
                        pos.coerceBlockLevel(mc.player).offset(dir).offset(dir.rotateLeft()).offset(leftDir, getWidthLeft());
2726
                    else pos.coerceBlockLevel(mc.player).offset(dir, 2).offset(leftDir, getWidthLeft() + (m ? 1 : 0));
2727
                }
2728
2729
                @Override
2730
                public void save() {
2731
                    pi = i;
2732
                    pw = w;
2733
                    py = y;
2734
                    i = w = y = 0;
2735
2736
                    initPos();
2737
                }
2738
2739
                @Override
2740
                public void restore() {
2741
                    i = pi;
2742
                    w = pw;
2743
                    y = py;
2744
2745
                    initPos();
2746
                }
2747
            };
2748
        }
2749
2750
        @Override
2751
        public MBPIterator getBlockade(boolean mine, BlockadeType blockadeType) {
2752
            return new MBPIterator() {
2753
                private int i = mine ? -1 : 0, y;
2754
                private int pi, py;
2755
2756
                private MBlockPos get(int i) {
2757
                    HorizontalDirection dir2 = dir.rotateLeft().rotateLeftSkipOne();
2758
2759
                    pos.coerceBlockLevel(mc.player).offset(dir2);
2760
2761
                    return switch (i) {
2762
                        case -1 -> pos;
2763
                        case 0 -> pos.offset(dir2);
2764
                        case 1 -> pos.offset(dir2.rotateLeftSkipOne());
2765
                        case 2 -> pos.offset(dir2.rotateLeftSkipOne().opposite());
2766
                        case 3 -> pos.offset(dir2.opposite(), 2);
2767
                        case 4 -> pos.offset(dir2.opposite()).offset(dir2.rotateLeftSkipOne());
2768
                        case 5 -> pos.offset(dir2.opposite()).offset(dir2.rotateLeftSkipOne().opposite());
2769
                        default -> throw new IllegalStateException("Unexpected value: " + i);
2770
                    };
2771
                }
2772
2773
                @Override
2774
                public boolean hasNext() {
2775
                    return i < blockadeType.columns && y < 2;
2776
                }
2777
2778
                @Override
2779
                public MBlockPos next() {
2780
                    MBlockPos pos = get(i).add(0, y, 0);
2781
2782
                    y++;
2783
                    if (y > 1) {
2784
                        y = 0;
2785
                        i++;
2786
                    }
2787
2788
                    return pos;
2789
                }
2790
2791
                @Override
2792
                public void save() {
2793
                    pi = i;
2794
                    py = y;
2795
                    i = y = 0;
2796
                }
2797
2798
                @Override
2799
                public void restore() {
2800
                    i = pi;
2801
                    y = py;
2802
                }
2803
2804
                @Override
2805
                public int placementsPerTick(HighwayBuilder b) {
2806
                    return 1;
2807
                }
2808
            };
2809
        }
2810
    }
2811
2812
    public static class DoubleMineBlock {
2813
        public static boolean rateLimited = false;
2814
        public final BlockPos blockPos;
2815
        public final BlockState blockState;
2816
2817
        private final Block block;
2818
        private final Direction direction;
2819
        private final HighwayBuilder b;
2820
        private final Vector3d vec3 = new Vector3d(0);
2821
2822
        private int normalStartTime, packetStartTime;
2823
        private boolean packet;
2824
2825
        public DoubleMineBlock(HighwayBuilder b, BlockPos pos) {
2826
            this.b = b;
2827
            this.blockPos = pos;
2828
            this.blockState = b.mc.level.getBlockState(this.blockPos);
2829
            this.block = this.blockState.getBlock();
2830
            this.direction = BlockUtils.getDirection(pos);
2831
            this.packet = false;
2832
        }
2833
2834
        public DoubleMineBlock startDestroying() {
2835
            b.mc.gameMode.startPrediction(b.mc.level, sequence -> new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, this.blockPos, this.direction, sequence));
2836
            normalStartTime = b.mc.player.tickCount;
2837
            return this;
2838
        }
2839
2840
        public DoubleMineBlock stopDestroying() {
2841
            b.mc.gameMode.startPrediction(b.mc.level, sequence -> new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, this.blockPos, this.direction, sequence));
2842
            return this;
2843
        }
2844
2845
        public DoubleMineBlock packetMine() {
2846
            packetStartTime = b.mc.player.tickCount;
2847
            packet = true;
2848
            return stopDestroying();
2849
        }
2850
2851
        public boolean isReady() {
2852
            return progress() >= (b.fastBreak.get() ? 0.7 : 1.0);
2853
        }
2854
2855
        public boolean shouldRemove() {
2856
            boolean distance = !packet && Utils.distance(b.mc.player.getEyePosition().x, b.mc.player.getEyePosition().y, b.mc.player.getEyePosition().z, blockPos.getX() + direction.getStepX(), blockPos.getY() + direction.getStepY(), blockPos.getZ() + direction.getStepZ()) > b.mc.player.blockInteractionRange();
2857
2858
            // a minimum amount of time needs to have elapsed for the timeout check to occur, otherwise it may trigger
2859
            // when it isn't supposed to due to latency
2860
            boolean timeout = progress() > 2 && (b.mc.player.tickCount - (packet ? packetStartTime : normalStartTime) > 60);
2861
2862
            return distance || timeout;
2863
        }
2864
2865
        public double progress() {
2866
            int slot = b.mc.player.getInventory().getSelectedSlot();
2867
            return BlockUtils.getBreakDelta(slot, blockState) * ((b.mc.player.tickCount - (packet ? packetStartTime : normalStartTime)) + 1);
2868
        }
2869
2870
        public void renderLetter(GuiGraphicsExtractor graphics) {
2871
            vec3.set(blockPos.getX() + 0.5, blockPos.getY() + 0.5, blockPos.getZ() + 0.5);
2872
            if (!NametagUtils.to2D(vec3, 2)) return;
2873
2874
            NametagUtils.begin(vec3, graphics);
2875
            TextRenderer.get().begin(graphics, 1.0, false, true);
2876
2877
            String letter = packet ? "P" : "N";
2878
            double w = TextRenderer.get().getWidth(letter) / 2.0;
2879
            TextRenderer.get().render(letter, -w, 0.0, Color.WHITE, true);
2880
2881
            TextRenderer.get().end();
2882
            NametagUtils.end(graphics);
2883
        }
2884
    }
2885
2886
    private class RestockTask {
2887
        public boolean materials;
2888
        public boolean pickaxes;
2889
        public boolean food;
2890
        private final HighwayBuilder b;
2891
2892
        public RestockTask(HighwayBuilder b) {
2893
            this.b = b;
2894
        }
2895
2896
        public void setMaterials() {
2897
            setTask(0);
2898
        }
2899
2900
        public void setPickaxes() {
2901
            setTask(1);
2902
        }
2903
2904
        public void setFood() {
2905
            setTask(2);
2906
        }
2907
2908
        private void setTask(@Range(from = 0, to = 2) int value) {
2909
            complete();
2910
2911
            switch (value) {
2912
                case 0 -> materials = true;
2913
                case 1 -> pickaxes = true;
2914
                case 2 -> food = true;
2915
            }
2916
2917
            setState(State.Restock);
2918
            b.info("Starting new restock task for " + item());
2919
        }
2920
2921
        public void complete() {
2922
            materials = false;
2923
            pickaxes = false;
2924
            food = false;
2925
        }
2926
2927
        public boolean tasksInactive() {
2928
            return !materials && !pickaxes && !food;
2929
        }
2930
2931
        public String item() {
2932
            if (materials) return "building materials";
2933
            if (pickaxes) return "pickaxes";
2934
            if (food) return "food";
2935
            return "unknown";
2936
        }
2937
    }
2938
}
2939