surround module

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

5 implementationsCombatCOMBATWORLD

Full module source: 5 implementations

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

Meteor ClientCombatsrc/main/java/meteordevelopment/meteorclient/systems/modules/combat/Surround.javaJava · 473 lines · 17.0 KB

Surrounds you in blocks to prevent massive crystal damage.

Settingsblocksdelayblocks-per-tickcenterdouble-heightonly-on-groundair-placetoggle-modulestoggle-back-onmodulesrotateprotecttoggle-on-y-changetoggle-on-completetoggle-on-deathswingrenderbelowshape-modesafe-side-colorsafe-line-colornormal-side-colornormal-line-colorunsafe-side-colorunsafe-line-color
Surround.javaJava · Minecraft 26.2 · 473 lines · 17.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.combat;
7
8
import meteordevelopment.meteorclient.events.packets.PacketEvent;
9
import meteordevelopment.meteorclient.events.render.Render3DEvent;
10
import meteordevelopment.meteorclient.events.world.TickEvent;
11
import meteordevelopment.meteorclient.mixin.DirectionAccessor;
12
import meteordevelopment.meteorclient.renderer.ShapeMode;
13
import meteordevelopment.meteorclient.settings.*;
14
import meteordevelopment.meteorclient.systems.modules.Categories;
15
import meteordevelopment.meteorclient.systems.modules.Module;
16
import meteordevelopment.meteorclient.utils.entity.DamageUtils;
17
import meteordevelopment.meteorclient.utils.player.FindItemResult;
18
import meteordevelopment.meteorclient.utils.player.InvUtils;
19
import meteordevelopment.meteorclient.utils.player.PlayerUtils;
20
import meteordevelopment.meteorclient.utils.player.Rotations;
21
import meteordevelopment.meteorclient.utils.render.color.Color;
22
import meteordevelopment.meteorclient.utils.render.color.SettingColor;
23
import meteordevelopment.meteorclient.utils.world.BlockUtils;
24
import meteordevelopment.meteorclient.utils.world.Dir;
25
import meteordevelopment.orbit.EventHandler;
26
import net.minecraft.core.BlockPos;
27
import net.minecraft.core.Direction;
28
import net.minecraft.network.protocol.game.ClientboundPlayerCombatKillPacket;
29
import net.minecraft.network.protocol.game.ServerboundAttackPacket;
30
import net.minecraft.network.protocol.game.ServerboundSwingPacket;
31
import net.minecraft.server.level.BlockDestructionProgress;
32
import net.minecraft.world.InteractionHand;
33
import net.minecraft.world.entity.Entity;
34
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
35
import net.minecraft.world.level.block.Block;
36
import net.minecraft.world.level.block.Blocks;
37
import net.minecraft.world.level.block.state.BlockState;
38
import net.minecraft.world.phys.AABB;
39
40
import java.util.ArrayList;
41
import java.util.List;
42
import java.util.function.Predicate;
43
import java.util.SortedSet;
44
45
public class Surround extends Module {
46
    private final SettingGroup sgGeneral = settings.getDefaultGroup();
47
    private final SettingGroup sgToggles = settings.createGroup("Toggles");
48
    private final SettingGroup sgRender = settings.createGroup("Render");
49
50
    // General
51
52
    private final Setting<List<Block>> blocks = sgGeneral.add(new BlockListSetting.Builder()
53
        .name("blocks")
54
        .description("What blocks to use for surround.")
55
        .defaultValue(Blocks.OBSIDIAN, Blocks.CRYING_OBSIDIAN, Blocks.NETHERITE_BLOCK)
56
        .filter(this::blockFilter)
57
        .build()
58
    );
59
60
    private final Setting<Integer> delay = sgGeneral.add(new IntSetting.Builder()
61
        .name("delay")
62
        .description("Delay, in ticks, between block placements.")
63
        .min(0)
64
        .defaultValue(0)
65
        .build()
66
    );
67
68
    private final Setting<Integer> blocksPerTick = sgGeneral.add(new IntSetting.Builder()
69
        .name("blocks-per-tick")
70
        .description("How many blocks to place in one tick.")
71
        .defaultValue(1)
72
        .min(1)
73
        .build()
74
    );
75
76
    private final Setting<Center> center = sgGeneral.add(new EnumSetting.Builder<Center>()
77
        .name("center")
78
        .description("Teleports you to the center of the block.")
79
        .defaultValue(Center.Incomplete)
80
        .build()
81
    );
82
83
    private final Setting<Boolean> doubleHeight = sgGeneral.add(new BoolSetting.Builder()
84
        .name("double-height")
85
        .description("Places obsidian on top of the original surround blocks to prevent people from face-placing you.")
86
        .defaultValue(false)
87
        .build()
88
    );
89
90
    private final Setting<Boolean> onlyOnGround = sgGeneral.add(new BoolSetting.Builder()
91
        .name("only-on-ground")
92
        .description("Works only when you are standing on blocks.")
93
        .defaultValue(true)
94
        .build()
95
    );
96
97
    private final Setting<Boolean> airPlace = sgGeneral.add(new BoolSetting.Builder()
98
        .name("air-place")
99
        .description("Allows Surround to place blocks in the air.")
100
        .defaultValue(true)
101
        .build()
102
    );
103
104
    private final Setting<Boolean> toggleModules = sgGeneral.add(new BoolSetting.Builder()
105
        .name("toggle-modules")
106
        .description("Turn off other modules when surround is activated.")
107
        .defaultValue(false)
108
        .build()
109
    );
110
111
    private final Setting<Boolean> toggleBack = sgGeneral.add(new BoolSetting.Builder()
112
        .name("toggle-back-on")
113
        .description("Turn the other modules back on when surround is deactivated.")
114
        .defaultValue(false)
115
        .visible(toggleModules::get)
116
        .build()
117
    );
118
119
    private final Setting<List<Module>> modules = sgGeneral.add(new ModuleListSetting.Builder()
120
        .name("modules")
121
        .description("Which modules to disable on activation.")
122
        .visible(toggleModules::get)
123
        .build()
124
    );
125
126
    private final Setting<Boolean> rotate = sgGeneral.add(new BoolSetting.Builder()
127
        .name("rotate")
128
        .description("Automatically faces towards the obsidian being placed.")
129
        .defaultValue(true)
130
        .build()
131
    );
132
133
    private final Setting<Boolean> protect = sgGeneral.add(new BoolSetting.Builder()
134
        .name("protect")
135
        .description("Attempts to break crystals around surround positions to prevent surround break.")
136
        .defaultValue(true)
137
        .build()
138
    );
139
140
    // Toggles
141
142
    private final Setting<Boolean> toggleOnYChange = sgToggles.add(new BoolSetting.Builder()
143
        .name("toggle-on-y-change")
144
        .description("Automatically disables when your y level changes (step, jumping, etc).")
145
        .defaultValue(true)
146
        .build()
147
    );
148
149
    private final Setting<Boolean> toggleOnComplete = sgToggles.add(new BoolSetting.Builder()
150
        .name("toggle-on-complete")
151
        .description("Toggles off when all blocks are placed.")
152
        .defaultValue(false)
153
        .build()
154
    );
155
156
    private final Setting<Boolean> toggleOnDeath = sgToggles.add(new BoolSetting.Builder()
157
        .name("toggle-on-death")
158
        .description("Toggles off when you die.")
159
        .defaultValue(true)
160
        .build()
161
    );
162
163
    // Render
164
165
    private final Setting<Boolean> swing = sgRender.add(new BoolSetting.Builder()
166
        .name("swing")
167
        .description("Render your hand swinging when placing surround blocks.")
168
        .defaultValue(true)
169
        .build()
170
    );
171
172
    private final Setting<Boolean> render = sgRender.add(new BoolSetting.Builder()
173
        .name("render")
174
        .description("Renders a block overlay where the obsidian will be placed.")
175
        .defaultValue(true)
176
        .build()
177
    );
178
179
    private final Setting<Boolean> renderBelow = sgRender.add(new BoolSetting.Builder()
180
        .name("below")
181
        .description("Renders the block below you.")
182
        .defaultValue(false)
183
        .build()
184
    );
185
186
    private final Setting<ShapeMode> shapeMode = sgRender.add(new EnumSetting.Builder<ShapeMode>()
187
        .name("shape-mode")
188
        .description("How the shapes are rendered.")
189
        .defaultValue(ShapeMode.Both)
190
        .build()
191
    );
192
193
    private final Setting<SettingColor> safeSideColor = sgRender.add(new ColorSetting.Builder()
194
        .name("safe-side-color")
195
        .description("The side color for safe blocks.")
196
        .defaultValue(new SettingColor(13, 255, 0, 0))
197
        .visible(() -> render.get() && shapeMode.get() != ShapeMode.Lines)
198
        .build()
199
    );
200
201
    private final Setting<SettingColor> safeLineColor = sgRender.add(new ColorSetting.Builder()
202
        .name("safe-line-color")
203
        .description("The line color for safe blocks.")
204
        .defaultValue(new SettingColor(13, 255, 0, 0))
205
        .visible(() -> render.get() && shapeMode.get() != ShapeMode.Sides)
206
        .build()
207
    );
208
209
    private final Setting<SettingColor> normalSideColor = sgRender.add(new ColorSetting.Builder()
210
        .name("normal-side-color")
211
        .description("The side color for normal blocks.")
212
        .defaultValue(new SettingColor(0, 255, 238, 12))
213
        .visible(() -> render.get() && shapeMode.get() != ShapeMode.Lines)
214
        .build()
215
    );
216
217
    private final Setting<SettingColor> normalLineColor = sgRender.add(new ColorSetting.Builder()
218
        .name("normal-line-color")
219
        .description("The line color for normal blocks.")
220
        .defaultValue(new SettingColor(0, 255, 238, 100))
221
        .visible(() -> render.get() && shapeMode.get() != ShapeMode.Sides)
222
        .build()
223
    );
224
225
    private final Setting<SettingColor> unsafeSideColor = sgRender.add(new ColorSetting.Builder()
226
        .name("unsafe-side-color")
227
        .description("The side color for unsafe blocks.")
228
        .defaultValue(new SettingColor(204, 0, 0, 12))
229
        .visible(() -> render.get() && shapeMode.get() != ShapeMode.Lines)
230
        .build()
231
    );
232
233
    private final Setting<SettingColor> unsafeLineColor = sgRender.add(new ColorSetting.Builder()
234
        .name("unsafe-line-color")
235
        .description("The line color for unsafe blocks.")
236
        .defaultValue(new SettingColor(204, 0, 0, 100))
237
        .visible(() -> render.get() && shapeMode.get() != ShapeMode.Sides)
238
        .build()
239
    );
240
241
    public ArrayList<Module> toActivate = new ArrayList<>();
242
    private int timer;
243
244
    public Surround() {
245
        super(Categories.Combat, "surround", "Surrounds you in blocks to prevent massive crystal damage.");
246
    }
247
248
    // Render
249
250
    @EventHandler
251
    private void onRender3D(Render3DEvent event) {
252
        if (!render.get()) return;
253
254
        BlockPos playerPos = mc.player.blockPosition();
255
256
        // Below
257
        if (renderBelow.get()) draw(playerPos.below(), event, 0);
258
259
        for (Direction direction : DirectionAccessor.meteor$getHorizontal()) {
260
            BlockPos renderPos = playerPos.relative(direction);
261
262
            // Regular surround positions
263
            draw(renderPos, event, doubleHeight.get() ? Dir.UP : 0);
264
265
            // Double height
266
            if (doubleHeight.get()) draw(renderPos.above(), event, Dir.DOWN);
267
        }
268
    }
269
270
    private void draw(BlockPos renderPos, Render3DEvent event, int exclude) {
271
        Color sideColor = getSideColor(renderPos);
272
        Color lineColor = getLineColor(renderPos);
273
        event.renderer.box(renderPos, sideColor, lineColor, shapeMode.get(), exclude);
274
    }
275
276
    // Function
277
278
    @Override
279
    public void onActivate() {
280
        // Center on activate
281
        if (center.get() == Center.OnActivate) PlayerUtils.centerPlayer();
282
283
        // Reset delay
284
        timer = delay.get();
285
286
        if (toggleModules.get() && !modules.get().isEmpty() && mc.level != null && mc.player != null) {
287
            for (Module module : modules.get()) {
288
                if (module.isActive()) {
289
                    module.toggle();
290
                    toActivate.add(module);
291
                }
292
            }
293
        }
294
    }
295
296
    @Override
297
    public void onDeactivate() {
298
        if (toggleBack.get() && !toActivate.isEmpty() && mc.level != null && mc.player != null) {
299
            for (Module module : toActivate) {
300
                module.enable();
301
            }
302
        }
303
    }
304
305
    @EventHandler
306
    private void onTick(TickEvent.Pre event) {
307
        // Delay
308
        if (timer++ < delay.get()) return;
309
310
        // Toggle if Y level changed
311
        if (toggleOnYChange.get() && mc.player.yo != mc.player.getY()) {
312
            toggle();
313
            return;
314
        }
315
316
        // Wait till player is on ground
317
        if (onlyOnGround.get() && !mc.player.onGround()) return;
318
319
        // Wait until the player has a block available to place
320
        FindItemResult block = InvUtils.findInHotbar(itemStack -> blocks.get().contains(Block.byItem(itemStack.getItem())));
321
        if (!block.found()) return;
322
323
        // Centering player
324
        if (center.get() == Center.Always) PlayerUtils.centerPlayer();
325
326
        int placedCount = 0;
327
        boolean complete = true;
328
329
        BlockPos playerPos = mc.player.blockPosition();
330
331
        // Placing feet blocks
332
        for (Direction direction : DirectionAccessor.meteor$getHorizontal()) {
333
            BlockPos placePos = playerPos.relative(direction);
334
335
            // Place support blocks if air place is disabled
336
            if (!airPlace.get() && isAirPlace(placePos) && mc.level.getBlockState(placePos).canBeReplaced()) {
337
                if (place(placePos.below(), block) && ++placedCount >= blocksPerTick.get()) break;
338
339
                if (mc.level.getBlockState(placePos.below()).canBeReplaced()) complete = false;
340
            }
341
342
            if (place(placePos, block) && ++placedCount >= blocksPerTick.get()) break;
343
344
            if (mc.level.getBlockState(placePos).canBeReplaced()) complete = false;
345
        }
346
347
        // Placing head blocks
348
        if (doubleHeight.get() && complete) {
349
            for (Direction direction : DirectionAccessor.meteor$getHorizontal()) {
350
                BlockPos placePos = playerPos.relative(direction).above();
351
                if (place(placePos, block) && ++placedCount >= blocksPerTick.get()) break;
352
353
                if (mc.level.getBlockState(placePos).canBeReplaced()) complete = false;
354
            }
355
        }
356
357
        timer = 0;
358
359
        // Disable if all the surround blocks are placed
360
        if (complete && toggleOnComplete.get()) {
361
            toggle();
362
            return;
363
        }
364
365
        // Keep the player centered until all the blocks are placed to avoid collision
366
        if (!complete && center.get() == Center.Incomplete) PlayerUtils.centerPlayer();
367
    }
368
369
    private boolean place(BlockPos placePos, FindItemResult block) {
370
        // Attempt to place
371
        boolean placed = BlockUtils.place(placePos, block, rotate.get(), 100, swing.get(), true);
372
373
        // Check if the block is being mined
374
        boolean beingMined = false;
375
        for (SortedSet<BlockDestructionProgress> progresses : mc.level.destructionProgress().values()) {
376
            if (progresses.isEmpty()) continue;
377
378
            if (progresses.last().getPos().equals(placePos)) {
379
                beingMined = true;
380
                break;
381
            }
382
        }
383
384
        boolean isThreat = mc.level.getBlockState(placePos).canBeReplaced() || beingMined;
385
386
        // If the block is air or is being mined, destroy nearby crystals to be safe
387
        if (protect.get() && !placed && isThreat) {
388
            AABB box = new AABB(
389
                placePos.getX() - 1, placePos.getY() - 1, placePos.getZ() - 1,
390
                placePos.getX() + 1, placePos.getY() + 1, placePos.getZ() + 1
391
            );
392
393
            Predicate<Entity> entityPredicate = entity -> entity instanceof EndCrystal && DamageUtils.crystalDamage(mc.player, entity.position()) < PlayerUtils.getTotalHealth();
394
395
            for (Entity crystal : mc.level.getEntities((Entity) null, box, entityPredicate)) {
396
                if (rotate.get()) {
397
                    Rotations.rotate(Rotations.getPitch(crystal), Rotations.getYaw(crystal), () -> {
398
                        mc.player.connection.send(new ServerboundAttackPacket(crystal.getId()));
399
                    });
400
                } else {
401
                    mc.player.connection.send(new ServerboundAttackPacket(crystal.getId()));
402
                }
403
404
                mc.getConnection().send(new ServerboundSwingPacket(InteractionHand.MAIN_HAND));
405
            }
406
        }
407
408
        return placed;
409
    }
410
411
    @EventHandler
412
    private void onPacketReceive(PacketEvent.Receive event) {
413
        if (event.packet instanceof ClientboundPlayerCombatKillPacket packet) {
414
            Entity entity = mc.level.getEntity(packet.playerId());
415
            if (entity == mc.player && toggleOnDeath.get()) {
416
                toggle();
417
                info("Toggled off because you died.");
418
            }
419
        }
420
    }
421
422
    private BlockType getBlockType(BlockPos pos) {
423
        BlockState blockState = mc.level.getBlockState(pos);
424
425
        // Unbreakable eg. bedrock
426
        if (blockState.getBlock().defaultDestroyTime() < 0) return BlockType.Safe;
427
            // Blast resistant eg. obsidian
428
        else if (blockState.getBlock().getExplosionResistance() >= 600) return BlockType.Normal;
429
            // Anything else
430
        else return BlockType.Unsafe;
431
    }
432
433
    private Color getSideColor(BlockPos pos) {
434
        return switch (getBlockType(pos)) {
435
            case Safe -> safeSideColor.get();
436
            case Normal -> normalSideColor.get();
437
            case Unsafe -> unsafeSideColor.get();
438
        };
439
    }
440
441
    private Color getLineColor(BlockPos pos) {
442
        return switch (getBlockType(pos)) {
443
            case Safe -> safeLineColor.get();
444
            case Normal -> normalLineColor.get();
445
            case Unsafe -> unsafeLineColor.get();
446
        };
447
    }
448
449
    private boolean isAirPlace(BlockPos blockPos) {
450
        for (Direction direction : Direction.values()) {
451
            if (!mc.level.getBlockState(blockPos.relative(direction)).canBeReplaced()) return false;
452
        }
453
        return true;
454
    }
455
456
    private boolean blockFilter(Block block) {
457
        return block.getExplosionResistance() >= 600 && block.defaultDestroyTime() >= 0 && block != Blocks.REINFORCED_DEEPSLATE;
458
    }
459
460
    public enum Center {
461
        Never,
462
        OnActivate,
463
        Incomplete,
464
        Always
465
    }
466
467
    public enum BlockType {
468
        Safe,
469
        Normal,
470
        Unsafe
471
    }
472
}
473
MelaHack (ThunderHack fork)COMBATsrc/main/java/thunder/hack/features/modules/combat/Surround.javaJava · 247 lines · 10.3 KB

Surrounds your legs using specified blocks.

SettingsBlocks/PlaceDelay/PlaceCenterAuto DisableOn Y ChangeOn TpOn Death
Surround.javaJava · Minecraft 26.2 · 247 lines · 10.3 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.combat;
2
3
import meteordevelopment.orbit.EventHandler;
4
import meteordevelopment.orbit.EventPriority;
5
import net.minecraft.core.*;
6
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
7
import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket;
8
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
9
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
10
import net.minecraft.util.Mth;
11
import net.minecraft.world.entity.EntityType;
12
import net.minecraft.world.entity.EntityTypes;
13
import net.minecraft.world.entity.MoverType;
14
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
15
import net.minecraft.world.phys.*;
16
import org.jetbrains.annotations.NotNull;
17
import org.jetbrains.annotations.Nullable;
18
import thunder.hack.ThunderHack;
19
import thunder.hack.events.impl.EventTick;
20
import thunder.hack.events.impl.PacketEvent;
21
import thunder.hack.features.modules.base.PlaceModule;
22
import thunder.hack.setting.Setting;
23
import thunder.hack.setting.impl.SettingGroup;
24
import thunder.hack.utility.player.InteractionUtility;
25
import thunder.hack.utility.world.HoleUtility;
26
27
import java.util.ArrayList;
28
import java.util.List;
29
import java.util.Objects;
30
31
import static thunder.hack.features.modules.client.ClientSettings.isRu;
32
33
public final class Surround extends PlaceModule {
34
    private final Setting<Integer> blocksPerTick = new Setting<>("Blocks/Place", 8, 1, 12);
35
    private final Setting<Integer> placeDelay = new Setting<>("Delay/Place", 3, 0, 10);
36
    private final Setting<CenterMode> center = new Setting<>("Center", CenterMode.Disabled);
37
    private final Setting<SettingGroup> autoDisable = new Setting<>("Auto Disable", new SettingGroup(false, 0));
38
    private final Setting<Boolean> onYChange = new Setting<>("On Y Change", true).addToGroup(autoDisable);
39
    private final Setting<OnTpAction> onTp = new Setting<>("On Tp", OnTpAction.None).addToGroup(autoDisable);
40
    private final Setting<Boolean> onDeath = new Setting<>("On Death", false).addToGroup(autoDisable);
41
42
    private int delay;
43
    private double prevY;
44
45
    public Surround() {
46
        super("Surround", Category.COMBAT);
47
    }
48
49
    @Override
50
    public void onEnable() {
51
        if (mc.player == null) return;
52
53
        delay = 0;
54
        prevY = mc.player.getY();
55
56
        // Centering
57
        if (center.getValue() == CenterMode.Teleport) {
58
            mc.player.absSnapTo(Mth.floor(mc.player.getX()) + 0.5, mc.player.getY(), Mth.floor(mc.player.getZ()) + 0.5);
59
            sendPacket(new ServerboundMovePlayerPacket.Pos(mc.player.getX(), mc.player.getY(), mc.player.getZ(), mc.player.onGround(), mc.player.horizontalCollision));
60
        }
61
    }
62
63
    @Override
64
    public void onUpdate() {
65
        if ((mc.player.isDeadOrDying() || !mc.player.isAlive() || mc.player.getHealth() + mc.player.getAbsorptionAmount() <= 0) && onDeath.getValue())
66
            disable(isRu() ? "Выключен из-за смерти." : "Disable because you died.");
67
    }
68
69
    @SuppressWarnings("unused")
70
    @EventHandler(priority = EventPriority.HIGHEST)
71
    private void onTick(EventTick event) {
72
        if (prevY != mc.player.getY() && onYChange.getValue() && ThunderHack.core.getSetBackTime() > 500) {
73
            disable(isRu() ? "Отключён из-за изменения Y!" : "Disabled due to Y change!");
74
            return;
75
        }
76
77
        prevY = mc.player.getY();
78
79
        Vec3 centerVec = new Vec3(Mth.floor(mc.player.getX()) + 0.5, mc.player.getY(), Mth.floor(mc.player.getZ()) + 0.5);
80
81
        AABB centerBox = new AABB(centerVec.x() - 0.2, centerVec.y() - 0.1, centerVec.z() - 0.2, centerVec.x() + 0.2, centerVec.y() + 0.1, centerVec.z() + 0.2);
82
83
        if (center.getValue() == CenterMode.Motion && !centerBox.contains(mc.player.position())) {
84
            mc.player.move(MoverType.SELF, new Vec3((centerVec.x() - mc.player.getX()) / 2, 0, (centerVec.z() - mc.player.getZ()) / 2));
85
            return;
86
        }
87
88
        List<BlockPos> blocks = getBlocks();
89
        if (blocks.isEmpty()) return;
90
91
        if (delay > 0) {
92
            delay--;
93
            return;
94
        }
95
96
        if (!getBlockResult().found()) disable(isRu() ? "Нет блоков!" : "No blocks!");
97
98
99
        int placed = 0;
100
        if (delay > 0) return;
101
        while (placed < blocksPerTick.getValue()) {
102
            if (!getBlockResult().found()) disable(isRu() ? "Нет блоков!" : "No blocks!");
103
104
            BlockPos targetBlock = getSequentialPos();
105
            if (targetBlock == null) break;
106
107
            if (placeBlock(targetBlock, true)) {
108
                placed++;
109
                delay = placeDelay.getValue();
110
                inactivityTimer.reset();
111
            } else break;
112
        }
113
    }
114
115
    @SuppressWarnings("unused")
116
    @EventHandler(priority = EventPriority.HIGHEST)
117
    private void onPacketReceive(PacketEvent.@NotNull Receive event) {
118
        if (!getBlockResult().found()) disable(isRu() ? "Нет блоков!" : "No blocks!");
119
120
        if (event.getPacket() instanceof ClientboundAddEntityPacket spawn && spawn.getType() == EntityTypes.END_CRYSTAL) {
121
122
            EndCrystal cr = new EndCrystal(mc.level, spawn.getX(), spawn.getY(), spawn.getZ());
123
            cr.setId(spawn.getId());
124
125
            if (crystalBreaker.getValue().isEnabled() && cr.distanceToSqr(mc.player) <= remove.getPow2Value())
126
                handlePacket();
127
        }
128
129
        if (event.getPacket() instanceof ClientboundBlockUpdatePacket pac && mc.player.distanceToSqr(net.minecraft.world.phys.Vec3.atBottomCenterOf(pac.getPos())) < range.getPow2Value() && pac.getBlockState().canBeReplaced())
130
            handlePacket();
131
132
        if (event.getPacket() instanceof ClientboundPlayerPositionPacket && onTp.getValue() == OnTpAction.Disable)
133
            disable(isRu() ? "Выключен из-за руббербенда!" : "Disabled due to a rubberband!");
134
    }
135
136
    private void handlePacket() {
137
        BlockPos bp = getSequentialPos();
138
        if (bp != null) {
139
            if (placeBlock(bp, InteractMode.Packet)) inactivityTimer.reset();
140
        }
141
    }
142
143
    private @Nullable BlockPos getSequentialPos() {
144
        for (BlockPos bp : getBlocks()) {
145
            if (new AABB(bp).intersects(mc.player.getBoundingBox())) continue;
146
            if (InteractionUtility.canPlaceBlock(bp, interact.getValue(), true) && mc.level.getBlockState(bp).canBeReplaced())
147
                return bp;
148
        }
149
        return null;
150
    }
151
152
153
    private @NotNull List<BlockPos> getBlocks() {
154
        final BlockPos playerPos = getPlayerPos();
155
        final List<BlockPos> offsets = new ArrayList<>();
156
157
        if (center.getValue() == CenterMode.Disabled && mc.player != null) {
158
            int z;
159
            int x;
160
            final double decimalX = Math.abs(mc.player.getX()) - Math.floor(Math.abs(mc.player.getX()));
161
            final double decimalZ = Math.abs(mc.player.getZ()) - Math.floor(Math.abs(mc.player.getZ()));
162
            final int lengthXPos = HoleUtility.calcLength(decimalX, false);
163
            final int lengthXNeg = HoleUtility.calcLength(decimalX, true);
164
            final int lengthZPos = HoleUtility.calcLength(decimalZ, false);
165
            final int lengthZNeg = HoleUtility.calcLength(decimalZ, true);
166
            final ArrayList<BlockPos> tempOffsets = new ArrayList<>();
167
            offsets.addAll(getOverlapPos());
168
169
            for (x = 1; x < lengthXPos + 1; ++x) {
170
                tempOffsets.add(HoleUtility.addToPlayer(playerPos, x, 0.0, 1 + lengthZPos));
171
                tempOffsets.add(HoleUtility.addToPlayer(playerPos, x, 0.0, -(1 + lengthZNeg)));
172
            }
173
            for (x = 0; x <= lengthXNeg; ++x) {
174
                tempOffsets.add(HoleUtility.addToPlayer(playerPos, -x, 0.0, 1 + lengthZPos));
175
                tempOffsets.add(HoleUtility.addToPlayer(playerPos, -x, 0.0, -(1 + lengthZNeg)));
176
            }
177
            for (z = 1; z < lengthZPos + 1; ++z) {
178
                tempOffsets.add(HoleUtility.addToPlayer(playerPos, 1 + lengthXPos, 0.0, z));
179
                tempOffsets.add(HoleUtility.addToPlayer(playerPos, -(1 + lengthXNeg), 0.0, z));
180
            }
181
            for (z = 0; z <= lengthZNeg; ++z) {
182
                tempOffsets.add(HoleUtility.addToPlayer(playerPos, 1 + lengthXPos, 0.0, -z));
183
                tempOffsets.add(HoleUtility.addToPlayer(playerPos, -(1 + lengthXNeg), 0.0, -z));
184
            }
185
186
            for (BlockPos pos : tempOffsets) {
187
                if (getDown(pos))
188
                    offsets.add(pos.offset(0, -1, 0));
189
                offsets.add(pos);
190
            }
191
        } else {
192
            offsets.add(playerPos.offset(0, -1, 0));
193
194
            for (Vec3i surround : HoleUtility.VECTOR_PATTERN) {
195
                if (getDown(playerPos.offset(surround)))
196
                    offsets.add(playerPos.offset(surround.getX(), -1, surround.getZ()));
197
198
                offsets.add(playerPos.offset(surround));
199
            }
200
        }
201
202
        return offsets;
203
    }
204
205
    private boolean getDown(BlockPos pos) {
206
        for (Direction dir : Direction.values())
207
            if (!mc.level.getBlockState(pos.offset(dir.getUnitVec3i())).canBeReplaced())
208
                return false;
209
210
        return mc.level.getBlockState(pos).canBeReplaced()
211
                && interact.getValue() != InteractionUtility.Interact.AirPlace;
212
    }
213
214
    private @NotNull List<BlockPos> getOverlapPos() {
215
        List<BlockPos> positions = new ArrayList<>();
216
217
        if (mc.player != null) {
218
            double decimalX = mc.player.getX() - Math.floor(mc.player.getX());
219
            double decimalZ = mc.player.getZ() - Math.floor(mc.player.getZ());
220
            int offX = HoleUtility.calcOffset(decimalX);
221
            int offZ = HoleUtility.calcOffset(decimalZ);
222
            positions.add(getPlayerPos());
223
            for (int x = 0; x <= Math.abs(offX); ++x) {
224
                for (int z = 0; z <= Math.abs(offZ); ++z) {
225
                    int properX = x * offX;
226
                    int properZ = z * offZ;
227
                    positions.add(Objects.requireNonNull(getPlayerPos()).offset(properX, -1, properZ));
228
                }
229
            }
230
        }
231
232
        return positions;
233
    }
234
235
    private @NotNull BlockPos getPlayerPos() {
236
        return BlockPos.containing(mc.player.getX(), mc.player.getY() - Math.floor(mc.player.getY()) > 0.8 ? Math.floor(mc.player.getY()) + 1.0 : Math.floor(mc.player.getY()), mc.player.getZ());
237
    }
238
239
    private enum CenterMode {
240
        Teleport, Motion, Disabled
241
    }
242
243
    private enum OnTpAction {
244
        Disable, Stay, None
245
    }
246
}
247
OfflineClientCOMBATsrc/main/java/com/jellypudding/offlineclient/modules/combat/Surround.javaJava · 399 lines · 15.8 KB

Places blast proof blocks around your feet to stop crystals.

SettingsBlocksCentreOnly on groundBlocks per tickDelayAir placeRotateDouble heightProtectDisable modulesRestore modulesToggle off on deathToggle off when doneToggle off on moveRenderShow belowUnbreakable colourSafe colourWeak colourOpen colour
Surround.javaJava · Minecraft 26.2 · 399 lines · 15.8 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.combat;
2
3
import com.jellypudding.offlineclient.OfflineClient;
4
import com.jellypudding.offlineclient.event.Subscribe;
5
import com.jellypudding.offlineclient.event.events.Render3DEvent;
6
import com.jellypudding.offlineclient.event.events.TickEvent;
7
import com.jellypudding.offlineclient.module.Category;
8
import com.jellypudding.offlineclient.module.Module;
9
import com.jellypudding.offlineclient.render.BoxStyle;
10
import com.jellypudding.offlineclient.render.DrawBatch;
11
import com.jellypudding.offlineclient.setting.BoolSetting;
12
import com.jellypudding.offlineclient.setting.ChoiceListSetting;
13
import com.jellypudding.offlineclient.setting.ColorSetting;
14
import com.jellypudding.offlineclient.setting.EnumSetting;
15
import com.jellypudding.offlineclient.setting.NumberSetting;
16
import com.jellypudding.offlineclient.setting.RegistryListSetting;
17
import com.jellypudding.offlineclient.util.BlockUtil;
18
import com.jellypudding.offlineclient.util.EntityUtil;
19
import com.jellypudding.offlineclient.util.ExplosionUtil;
20
import com.jellypudding.offlineclient.util.InventoryUtil.SlotSwap;
21
import com.jellypudding.offlineclient.util.RotationPriority;
22
import com.jellypudding.offlineclient.util.SwingMode;
23
import net.minecraft.core.BlockPos;
24
import net.minecraft.core.Direction;
25
import net.minecraft.core.registries.BuiltInRegistries;
26
import net.minecraft.network.protocol.game.ServerboundAttackPacket;
27
import net.minecraft.server.level.BlockDestructionProgress;
28
import net.minecraft.world.InteractionHand;
29
import net.minecraft.world.entity.Entity;
30
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
31
import net.minecraft.world.entity.player.Player;
32
import net.minecraft.world.level.block.Block;
33
import net.minecraft.world.level.block.Blocks;
34
import net.minecraft.world.level.block.state.BlockState;
35
import net.minecraft.world.phys.AABB;
36
import net.minecraft.world.phys.Vec3;
37
import net.minecraft.world.phys.shapes.CollisionContext;
38
39
import java.util.ArrayList;
40
import java.util.Comparator;
41
import java.util.HashMap;
42
import java.util.List;
43
import java.util.Map;
44
import java.util.Set;
45
import java.util.SortedSet;
46
47
// Missing support under a side is filled first.
48
public final class Surround extends Module {
49
50
    public enum Centre { NEVER, ON_ENABLE, INCOMPLETE, ALWAYS }
51
52
    // Blocks that are far too valuable to spend on a wall.
53
    private static final Set<Block> NEVER = Set.of(
54
        Blocks.ANCIENT_DEBRIS, Blocks.DIAMOND_BLOCK, Blocks.NETHERITE_BLOCK);
55
56
    // How far off an enemy still decides which side is walled first.
57
    private static final double THREAT_RANGE = 12;
58
59
    // Ticks a hit crystal is left alone before it is hit again.
60
    private static final int HIT_MEMORY = 10;
61
62
    private final RegistryListSetting<Block> blocks = new RegistryListSetting<>("Blocks",
63
        "Blocks to use in order of preference.",
64
        BuiltInRegistries.BLOCK,
65
        List.of(Blocks.OBSIDIAN, Blocks.CRYING_OBSIDIAN));
66
    private final EnumSetting<Centre> centre = new EnumSetting<>("Centre",
67
        "When to snap to the middle of your block so every side lines up.", Centre.INCOMPLETE)
68
        .describe(Centre.NEVER, "Never moves you.")
69
        .describe(Centre.ON_ENABLE, "Once when the module turns on.")
70
        .describe(Centre.INCOMPLETE, "Whilst any side is still open.")
71
        .describe(Centre.ALWAYS, "The whole time the module is on.");
72
    private final BoolSetting onlyOnGround = new BoolSetting("Only on ground",
73
        "Wait until you are standing on something.", true);
74
    private final NumberSetting perTick = new NumberSetting("Blocks per tick",
75
        "How many blocks to place in one tick.", 4, 1, 4, 1);
76
    private final NumberSetting delay = new NumberSetting("Delay",
77
        "Ticks to wait between placing rounds.", 0, 0, 5, 1, " ticks");
78
    private final BoolSetting airPlace = new BoolSetting("Air place",
79
        "Places on an open side with nothing to lean on. Off lays a support block under it first.", true);
80
    private final BoolSetting rotate = new BoolSetting("Rotate",
81
        "Send a look packet towards each block as it goes down.", true);
82
    private final EnumSetting<SwingMode> swing = SwingMode.setting(SwingMode.BOTH);
83
    private final BoolSetting doubleHeight = new BoolSetting("Double height",
84
        "Also wall the four sides at head height to stop a face place.", false);
85
    private final BoolSetting protect = new BoolSetting("Protect",
86
        "Hits any crystal sitting on an open side before it can be set off.", true);
87
    private final ChoiceListSetting disableModules = new ChoiceListSetting("Disable modules",
88
        "Modules switched off whilst this is on.", Surround::moduleNames);
89
    private final BoolSetting restoreModules = new BoolSetting("Restore modules",
90
        "Switches those modules back on when this turns off.", true)
91
        .under(disableModules, () -> disableModules.size() > 0);
92
    private final BoolSetting toggleOnDeath = new BoolSetting("Toggle off on death",
93
        "Turn off when you die instead of walling your respawn.", true);
94
    private final BoolSetting toggleOnDone = new BoolSetting("Toggle off when done",
95
        "Turn off once all four sides are filled.", false);
96
    private final BoolSetting toggleOnMove = new BoolSetting("Toggle off on move",
97
        "Turn off if you leave the block you started on.", false);
98
    private final BoolSetting render = new BoolSetting("Render",
99
        "Draws the side positions by how well they hold.", true);
100
    private final BoxStyle boxStyle = BoxStyle.shapeOnly(BoxStyle.Shape.BOTH).under(render);
101
    private final BoolSetting renderBelow = new BoolSetting("Show below",
102
        "Also draws the block under your feet.", false)
103
        .under(render);
104
    private final ColorSetting unbreakableColor = new ColorSetting("Unbreakable colour",
105
        "A side of bedrock.", 200, false).under(render);
106
    private final ColorSetting safeColor = new ColorSetting("Safe colour",
107
        "A side a crystal cannot open.", 120, false).under(render);
108
    private final ColorSetting weakColor = new ColorSetting("Weak colour",
109
        "A side a blast would clear.", 35, false).under(render);
110
    private final ColorSetting openColor = new ColorSetting("Open colour",
111
        "A side with nothing in it.", 0, false).under(render);
112
113
    private final Map<Integer, Integer> hitCrystals = new HashMap<>();
114
    private final List<Module> disabled = new ArrayList<>();
115
    private int timer;
116
    private BlockPos anchor;
117
    private final SlotSwap slots = new SlotSwap();
118
119
    public Surround() {
120
        super("Surround", "Places blast proof blocks around your feet to stop crystals.", Category.COMBAT);
121
        addSettings(blocks, centre, onlyOnGround, perTick, delay, airPlace, rotate, swing,
122
            doubleHeight, protect, disableModules, restoreModules, toggleOnDeath, toggleOnDone,
123
            toggleOnMove, render);
124
        addSettings(boxStyle.settings());
125
        addSettings(renderBelow, unbreakableColor, safeColor, weakColor, openColor);
126
        searchTags("obsidian", "crystal", "hole");
127
    }
128
129
    private static List<String> moduleNames() {
130
        List<String> names = new ArrayList<>();
131
        for (Module module : OfflineClient.INSTANCE.getModuleManager().getAll()) {
132
            if (module.isTogglable() && !(module instanceof Surround)) {
133
                names.add(module.getName());
134
            }
135
        }
136
        return names;
137
    }
138
139
    @Override
140
    protected void onEnable() {
141
        timer = 0;
142
        anchor = null;
143
        slots.forget();
144
        holdModules();
145
        if (inGame()) {
146
            anchor = mc.player.blockPosition();
147
            if (!centre.is(Centre.NEVER)) {
148
                BlockUtil.centerPlayer();
149
            }
150
        }
151
    }
152
153
    @Override
154
    protected void onDisable() {
155
        slots.restore();
156
        anchor = null;
157
        releaseModules();
158
    }
159
160
    private void holdModules() {
161
        disabled.clear();
162
        for (String name : disableModules.getValue()) {
163
            Module module = OfflineClient.INSTANCE.getModuleManager().get(name);
164
            if (module != null && module.isEnabled()) {
165
                module.setEnabled(false);
166
                disabled.add(module);
167
            }
168
        }
169
    }
170
171
    private void releaseModules() {
172
        if (restoreModules.isOn()) {
173
            for (Module module : disabled) {
174
                module.setEnabled(true);
175
            }
176
        }
177
        disabled.clear();
178
    }
179
180
    @Subscribe
181
    private void onTick(TickEvent event) {
182
        if (!inGame() || mc.player.isSpectator()) {
183
            return;
184
        }
185
        if (mc.player.isDeadOrDying()) {
186
            if (toggleOnDeath.isOn()) {
187
                setEnabled(false);
188
            }
189
            return;
190
        }
191
        BlockPos feet = mc.player.blockPosition();
192
        if (!keepAnchor(feet)) {
193
            return;
194
        }
195
        if (onlyOnGround.isOn() && !mc.player.onGround()) {
196
            return;
197
        }
198
        // A crystal on an open side goes before the wall does.
199
        // The delay never holds this up.
200
        if (protect.isOn()) {
201
            protectSides(feet);
202
        }
203
        if (centre.is(Centre.ALWAYS)) {
204
            BlockUtil.centerPlayer();
205
        }
206
        if (timer > 0) {
207
            timer--;
208
            return;
209
        }
210
211
        List<BlockPos> missing = missingSides(feet);
212
        // Off the ground the floor of the pocket comes first.
213
        if (!mc.player.onGround() && canFill(feet.below())) {
214
            missing.add(0, feet.below());
215
        }
216
        if (missing.isEmpty()) {
217
            slots.restore();
218
            if (toggleOnDone.isOn()) {
219
                setEnabled(false);
220
            }
221
            return;
222
        }
223
224
        int slot = findBlastBlock();
225
        if (slot == -1) {
226
            slots.restore();
227
            return;
228
        }
229
        if (centre.is(Centre.INCOMPLETE)) {
230
            BlockUtil.centerPlayer();
231
        }
232
        if (placeRound(missing, slot) > 0) {
233
            timer = delay.getInt();
234
        }
235
        slots.restore();
236
    }
237
238
    // Keeps the wall on the block the player stands in.
239
    // False once the module has switched off.
240
    private boolean keepAnchor(BlockPos feet) {
241
        // Null on the first tick after enabling from the GUI with no world loaded.
242
        if (anchor == null || feet.equals(anchor)) {
243
            anchor = feet;
244
            return true;
245
        }
246
        if (toggleOnMove.isOn()) {
247
            setEnabled(false);
248
            return false;
249
        }
250
        anchor = feet;
251
        return true;
252
    }
253
254
    private int placeRound(List<BlockPos> missing, int slot) {
255
        int placed = 0;
256
        for (BlockPos pos : missing) {
257
            if (placed >= perTick.getInt()) {
258
                break;
259
            }
260
            BlockPos target = pos;
261
            Direction support = BlockUtil.findPlaceSupport(pos);
262
            if (support == null) {
263
                BlockPos below = pos.below();
264
                Direction belowSupport = canFill(below) ? BlockUtil.findPlaceSupport(below) : null;
265
                if (belowSupport != null) {
266
                    target = below;
267
                    support = belowSupport;
268
                }
269
            }
270
            if (support == null && !airPlace.isOn()) {
271
                continue;
272
            }
273
            slots.select(slot);
274
            // Every side asks to turn and the rotation manager keeps the first one.
275
            boolean ok = support != null
276
                ? BlockUtil.place(target, support, rotate.isOn(), false)
277
                : BlockUtil.placeDirect(pos, rotate.isOn(), false);
278
            if (ok) {
279
                swing.getValue().swing(InteractionHand.MAIN_HAND);
280
                placed++;
281
            }
282
        }
283
        return placed;
284
    }
285
286
    private List<BlockPos> missingSides(BlockPos feet) {
287
        List<BlockPos> result = new ArrayList<>();
288
        for (Direction side : Direction.Plane.HORIZONTAL) {
289
            BlockPos pos = feet.relative(side);
290
            if (canFill(pos)) {
291
                result.add(pos);
292
            }
293
        }
294
        // The side facing the nearest enemy goes first.
295
        // That is where the crystal comes from.
296
        Player enemy = EntityUtil.nearestEnemy(THREAT_RANGE);
297
        if (enemy != null) {
298
            result.sort(Comparator.comparingDouble(pos -> enemy.distanceToSqr(Vec3.atCenterOf(pos))));
299
        }
300
        // The lower ring goes down first. The pocket is sealed before it is raised.
301
        if (doubleHeight.isOn()) {
302
            BlockPos head = feet.above();
303
            for (Direction side : Direction.Plane.HORIZONTAL) {
304
                BlockPos pos = head.relative(side);
305
                if (canFill(pos)) {
306
                    result.add(pos);
307
                }
308
            }
309
        }
310
        return result;
311
    }
312
313
    private boolean canFill(BlockPos pos) {
314
        if (!BlockUtil.isReplaceable(pos)) {
315
            return false;
316
        }
317
        BlockState obsidian = Blocks.OBSIDIAN.defaultBlockState();
318
        return mc.level.isUnobstructed(obsidian, pos, CollisionContext.empty());
319
    }
320
321
    private int findBlastBlock() {
322
        return BlockUtil.findRankedBlockSlot(blocks.getValue(), block -> !NEVER.contains(block));
323
    }
324
325
    // A side that is open or being mined is where a crystal would go.
326
    // Any crystal touching such a side is hit unless popping it would kill us.
327
    private void protectSides(BlockPos feet) {
328
        int now = mc.player.tickCount;
329
        hitCrystals.values().removeIf(tick -> now - tick > HIT_MEMORY);
330
        float health = EntityUtil.totalHealth(mc.player);
331
        for (Direction side : Direction.Plane.HORIZONTAL) {
332
            BlockPos pos = feet.relative(side);
333
            if (!BlockUtil.isReplaceable(pos) && !beingMined(pos)) {
334
                continue;
335
            }
336
            AABB reach = new AABB(pos).inflate(1);
337
            for (Entity crystal : mc.level.getEntities((Entity) null, reach, e -> e instanceof EndCrystal)) {
338
                if (ExplosionUtil.crystalDamage(mc.player, crystal.position()) >= health) {
339
                    continue;
340
                }
341
                // One hit a crystal. A second packet before it pops is wasted.
342
                if (hitCrystals.containsKey(crystal.getId())) {
343
                    continue;
344
                }
345
                hitCrystals.put(crystal.getId(), now);
346
                if (rotate.isOn()) {
347
                    BlockUtil.faceVector(crystal.position(), RotationPriority.ATTACK);
348
                }
349
                mc.player.connection.send(new ServerboundAttackPacket(crystal.getId()));
350
                swing.getValue().swing(InteractionHand.MAIN_HAND);
351
            }
352
        }
353
    }
354
355
    // True whilst somebody has a crack pattern on the block.
356
    private boolean beingMined(BlockPos pos) {
357
        for (SortedSet<BlockDestructionProgress> progress : mc.level.destructionProgress().values()) {
358
            if (!progress.isEmpty() && progress.last().getPos().equals(pos)) {
359
                return true;
360
            }
361
        }
362
        return false;
363
    }
364
365
    @Subscribe
366
    private void onRender3D(Render3DEvent event) {
367
        if (!render.isOn() || !inGame()) {
368
            return;
369
        }
370
        DrawBatch batch = event.getBatch();
371
        BlockPos feet = mc.player.blockPosition();
372
        for (Direction side : Direction.Plane.HORIZONTAL) {
373
            drawSide(batch, feet.relative(side));
374
            if (doubleHeight.isOn()) {
375
                drawSide(batch, feet.above().relative(side));
376
            }
377
        }
378
        if (renderBelow.isOn()) {
379
            drawSide(batch, feet.below());
380
        }
381
    }
382
383
    private void drawSide(DrawBatch batch, BlockPos pos) {
384
        boxStyle.draw(batch, pos, sideColor(pos), false);
385
    }
386
387
    private int sideColor(BlockPos pos) {
388
        if (BlockUtil.isReplaceable(pos)) {
389
            return openColor.getColor();
390
        }
391
        BlockState state = BlockUtil.state(pos);
392
        if (state.getBlock().defaultDestroyTime() < 0) {
393
            return unbreakableColor.getColor();
394
        }
395
        return state.getBlock().getExplosionResistance() >= BlockUtil.BLAST_PROOF
396
            ? safeColor.getColor() : weakColor.getColor();
397
    }
398
}
399
NicotineCombatsrc/client/java/nicotine/mod/mods/combat/Surround.javaJava · 141 lines · 5.1 KB

Surrounds you with obsidian

SettingsConstantDoubleSelfCenterInAir
Surround.javaJava · Minecraft 26.3 · 141 lines · 5.1 KB · complete file, verbatimOriginal ↗
1
package nicotine.mod.mods.combat;
2
3
import com.mojang.blaze3d.platform.InputConstants;
4
import net.minecraft.core.BlockPos;
5
import net.minecraft.core.Direction;
6
import net.minecraft.world.entity.Entity;
7
import net.minecraft.world.entity.item.ItemEntity;
8
import net.minecraft.world.item.Items;
9
import net.minecraft.world.phys.AABB;
10
import net.minecraft.world.phys.BlockHitResult;
11
import net.minecraft.world.phys.Vec3;
12
import nicotine.events.ClientLevelTickEvent;
13
import nicotine.mod.Mod;
14
import nicotine.mod.ModCategory;
15
import nicotine.mod.option.KeybindOption;
16
import nicotine.mod.option.ToggleOption;
17
import nicotine.util.*;
18
import nicotine.util.math.BoxUtil;
19
20
import java.util.ArrayList;
21
import java.util.Arrays;
22
import java.util.Comparator;
23
import java.util.List;
24
25
import static nicotine.util.Common.*;
26
27
public class Surround extends Mod {
28
29
    private final ToggleOption constant = new ToggleOption("Constant");
30
    private final ToggleOption doublePlace = new ToggleOption("Double");
31
    private final ToggleOption selfCenter = new ToggleOption("SelfCenter");
32
    private final ToggleOption inAir = new ToggleOption("InAir");
33
34
    public Surround() {
35
        super(ModCategory.Combat, "Surround", "Surrounds you with obsidian");
36
        this.keybind.keyCode = InputConstants.KEY_B;
37
        this.addOptions(Arrays.asList(constant, doublePlace, selfCenter, inAir));
38
    }
39
40
    @Override
41
    protected void init() {
42
        EventBus.register(ClientLevelTickEvent.class, event -> {
43
            if (!this.enabled || (!mc.player.onGround() && !inAir.enabled) || Player.isBusy())
44
                return true;
45
46
            List<BlockPos> surroundBlocks = Player.getSurroundBlocks(mc.player.blockPosition());
47
48
            if (selfCenter.enabled) {
49
                Comparator<BlockPos> byDistanceToPlayer = Comparator.comparingInt(blockPos -> (int)Vec3.atCenterOf(blockPos).distanceTo(mc.player.position()));
50
                surroundBlocks.sort(byDistanceToPlayer.reversed());
51
            }
52
53
            if (doublePlace.enabled) {
54
                surroundBlocks.addAll(Player.getSurroundBlocks(mc.player.blockPosition(), 0));
55
            }
56
57
            boolean alreadySurrounded = true;
58
59
            for (BlockPos surroundBlock : surroundBlocks) {
60
                if (mc.level.getBlockState(surroundBlock.offset(0, 1, 0)).getBlock().defaultBlockState().canBeReplaced())
61
                    alreadySurrounded = false;
62
            }
63
64
            if (alreadySurrounded) {
65
                if (!constant.enabled)
66
                    this.toggle();
67
                return true;
68
            }
69
70
            int targetSlot = -1;
71
72
            if (mc.player.getMainHandItem().getItem() != Items.OBSIDIAN) {
73
                for (int i = 0; i < 9; i++) {
74
                    if (mc.player.getInventory().getItem(i).getItem() == Items.OBSIDIAN) {
75
                        targetSlot = i;
76
                        break;
77
                    }
78
                }
79
80
                if (targetSlot == -1) {
81
                    Message.sendWarning("No obsidian in hotbar!");
82
                    this.toggle();
83
                    return true;
84
                }
85
            } else {
86
                targetSlot = mc.player.getInventory().getSelectedSlot();
87
            }
88
89
            List<AABB> takenPositions = new ArrayList<>();
90
91
            for (Entity entity : mc.level.entitiesForRendering()) {
92
                if (!(entity instanceof ItemEntity)) {
93
                    if (entity == mc.player && selfCenter.enabled)
94
                        continue;
95
96
                    takenPositions.add(entity.getBoundingBox());
97
                }
98
            }
99
100
            int size = surroundBlocks.size();
101
            for (int i = 0; i < size; i++) {
102
                BlockPos surroundBlock = surroundBlocks.get(i);
103
104
                if (mc.level.getBlockState(surroundBlock).getBlock().defaultBlockState().canBeReplaced() && !surroundBlocks.contains(surroundBlock.offset(0, -1, 0))) {
105
                    surroundBlocks.add(i, surroundBlock.offset(0, -1, 0));
106
                    surroundBlock = surroundBlocks.get(i);
107
                    size++;
108
                }
109
110
                if (!(mc.level.getBlockState(surroundBlock.offset(0, 1, 0)).getBlock().defaultBlockState().canBeReplaced())) {
111
                    continue;
112
                }
113
114
                boolean invalidPlacement = false;
115
116
                Vec3 interSectionPos = new Vec3(surroundBlock.getX(), surroundBlock.getY() + 1, surroundBlock.getZ());
117
118
                for (AABB takenPosition : takenPositions) {
119
                    if (BoxUtil.get1x1Box(interSectionPos).intersects(takenPosition)) {
120
                        invalidPlacement = true;
121
                        break;
122
                    }
123
                }
124
125
                if (invalidPlacement) {
126
                   continue;
127
                }
128
129
                BlockHitResult blockHitResult = new BlockHitResult(new Vec3(surroundBlock.getX(), surroundBlock.getY(), surroundBlock.getZ()), Direction.UP, surroundBlock, false);
130
                Player.lookAndPlace(blockHitResult, targetSlot, true, selfCenter.enabled);
131
            }
132
133
            if (!constant.enabled) {
134
                this.toggle();
135
            }
136
137
            return true;
138
        });
139
    }
140
}
141
LiquidBounce (Kotlin)WORLDsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/world/ModuleSurround.ktKotlin · 415 lines · 14.0 KB

Builds holes that protect you from explosion damage.

SettingsFeaturesDisableOnInstantMinDestroyProgressCornersAddExtraLayerFilterBlocks
ModuleSurround.ktKotlin · Minecraft 26.2 · 415 lines · 14.0 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
3
 *
4
 * Copyright (c) 2015 - 2026 CCBlueX
5
 *
6
 * LiquidBounce is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * LiquidBounce is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
package net.ccbluex.liquidbounce.features.module.modules.world
20
21
import it.unimi.dsi.fastutil.longs.LongOpenHashSet
22
import net.ccbluex.fastutil.fastIterator
23
import net.ccbluex.liquidbounce.config.types.group.ToggleableValueGroup
24
import net.ccbluex.liquidbounce.config.types.list.Tagged
25
import net.ccbluex.liquidbounce.event.EventState
26
import net.ccbluex.liquidbounce.event.events.GameTickEvent
27
import net.ccbluex.liquidbounce.event.events.KeyboardKeyEvent
28
import net.ccbluex.liquidbounce.event.events.PacketEvent
29
import net.ccbluex.liquidbounce.event.events.PlayerNetworkMovementTickEvent
30
import net.ccbluex.liquidbounce.event.events.RotationUpdateEvent
31
import net.ccbluex.liquidbounce.event.handler
32
import net.ccbluex.liquidbounce.features.command.commands.ingame.CommandCenter
33
import net.ccbluex.liquidbounce.features.command.commands.ingame.CommandCenter.CenterHandlerState
34
import net.ccbluex.liquidbounce.features.module.ClientModule
35
import net.ccbluex.liquidbounce.features.module.ModuleCategories
36
import net.ccbluex.liquidbounce.utils.block.DIRECTIONS_EXCLUDING_UP
37
import net.ccbluex.liquidbounce.utils.block.getBlockingEntities
38
import net.ccbluex.liquidbounce.utils.block.isBlockedByEntitiesReturnCrystal
39
import net.ccbluex.liquidbounce.utils.block.placer.BlockPlacer
40
import net.ccbluex.liquidbounce.utils.block.placer.CrystalDestroyFeature
41
import net.ccbluex.liquidbounce.utils.block.placer.placeInstantOnBlockUpdate
42
import net.ccbluex.liquidbounce.utils.collection.Filter
43
import net.ccbluex.liquidbounce.utils.collection.blockSortedSetOf
44
import net.ccbluex.liquidbounce.utils.collection.getSlot
45
import net.ccbluex.liquidbounce.utils.entity.getFeetBlockPos
46
import net.ccbluex.liquidbounce.utils.entity.isInHole
47
import net.ccbluex.liquidbounce.utils.kotlin.Priority
48
import net.ccbluex.liquidbounce.utils.math.center
49
import net.minecraft.core.BlockPos
50
import net.minecraft.core.Direction
51
import net.minecraft.world.entity.Entity
52
import net.minecraft.world.entity.boss.enderdragon.EndCrystal
53
import net.minecraft.world.level.block.Blocks
54
import net.minecraft.world.phys.AABB
55
import org.joml.Vector2d
56
import kotlin.math.abs
57
import kotlin.math.ceil
58
import kotlin.math.floor
59
60
/**
61
 * Surround module
62
 *
63
 * Builds safe holes.
64
 *
65
 * @author ccetl
66
 */
67
object ModuleSurround : ClientModule("Surround", ModuleCategories.WORLD, disableOnQuit = true) {
68
69
    /**
70
     * The blocks the surround normal utilizes.
71
     */
72
    private val DEFAULT_BLOCKS = arrayOf(Blocks.OBSIDIAN, Blocks.ENDER_CHEST, Blocks.CRYING_OBSIDIAN)
73
74
    private val features by multiEnumChoice("Features",
75
        Features.EXTEND,
76
        Features.DOWN,
77
    )
78
79
    /**
80
     * Disables the module when the y-coordinate changes.
81
     * Or when the player has moved at least 0.5 blocks away from the original center.
82
     * Or when the player has a speed that is faster than or equal to 5 m/s.
83
     */
84
    private val disableOn by multiEnumChoice("DisableOn", DisableOn.Y_CHANGE)
85
86
    /**
87
     * Replaces broken blocks instantly.
88
     *
89
     * Note: requires the rotation mode "None" in the block placer
90
     */
91
    private val instant by boolean("Instant", true)
92
93
    /**
94
     * Protects the surround against being blocked by crystals on destruction.
95
     *
96
     * Destroying requires the crystal destroyer in the placer to be active.
97
     */
98
    private object Protect : ToggleableValueGroup(this, "Protect", true) {
99
100
        /**
101
         * At what destroy stage, actions should be taken.
102
         */
103
        @Suppress("MagicNumber")
104
        private val minDestroyProgress by int("MinDestroyProgress", 4, 0..9, "stage")
105
106
        /**
107
         * Builds an extra layer around the surround blocks (slice):
108
         *     p
109
         *   x p x
110
         *     x
111
         * will become:
112
         *   x p x
113
         * x x p x x
114
         *     x
115
         *
116
         * X = obsidian
117
         * p = the players hitbox
118
         */
119
        object ExtraLayer : ToggleableValueGroup(this, "ExtraLayer", true) {
120
121
            /**
122
             * Will place even more blocks (top view):
123
             *   x
124
             * x p x
125
             *   x
126
             * will become:
127
             * x x x
128
             * x p x
129
             * x x x
130
             *
131
             * X = obsidian
132
             * p = the players hitbox
133
             */
134
            val corners by boolean("Corners", false)
135
136
        }
137
138
        init {
139
            tree(ExtraLayer)
140
        }
141
142
        val broken = LongOpenHashSet()
143
144
        /**
145
         * With a higher priority so that it runs before [CrystalDestroyFeature].
146
         */
147
        @Suppress("unused", "LoopWithTooManyJumpStatements")
148
        private val tickHandler = handler<GameTickEvent>(priority = 10) {
149
            // check if this feature isn't enabled and the extra layer forcefully applied or not enabled ->
150
            // checks are not needed
151
            if (!placer.crystalDestroyer.enabled && (addExtraLayerBlocks || !ExtraLayer.enabled)) {
152
                return@handler
153
            }
154
155
            // clear the map of previously considered blocks
156
            broken.clear()
157
158
            // iterate all surround blocks and check if they're being broken
159
            for (entry in placer.blocks.fastIterator()) {
160
                if (entry.booleanValue) continue  // exclude support blocks
161
                val posAsLong = entry.longKey
162
163
                // find the list of current breaking data, or else return
164
                val breakingProgressions = world.destructionProgress()[posAsLong] ?: continue
165
166
                // find the braking info that doesn't belong to us, if we mine our own surround, it should be ignored
167
                val breakingInfo = breakingProgressions.lastOrNull { it.id != player.id } ?: continue
168
                val stage = breakingInfo.progress
169
170
                // check if the stage is too low, if so return
171
                if (stage < minDestroyProgress) {
172
                    continue
173
                }
174
175
                val pos = BlockPos.of(posAsLong)
176
                // add the block to the map of blocks that are being broken
177
                if (ExtraLayer.enabled && stage > 0) {
178
                    broken.add(posAsLong)
179
                }
180
181
                // skip to the next entry if the crystal destroy feature is disabled
182
                if (!placer.crystalDestroyer.enabled) {
183
                    continue
184
                }
185
186
                // destroy crystals that would block replacements
187
                val blockedResult = pos.isBlockedByEntitiesReturnCrystal()
188
                val crystal = blockedResult.value() ?: continue
189
190
                // try to replace the current target
191
                placer.crystalDestroyer.currentTarget = crystal
192
193
                // we could target the blocking crystal, now we have to wait a tick before it has been destroyed
194
                // anyway, so we can return here
195
                if (placer.crystalDestroyer.currentTarget == crystal) {
196
                    return@handler
197
                }
198
            }
199
        }
200
201
    }
202
203
    /**
204
     * Manually triggers the protection mechanism [Protect.ExtraLayer].
205
     */
206
    private val addExtraLayer by bind("AddExtraLayer")
207
208
    init {
209
        tree(Protect)
210
    }
211
212
    private val filter by enumChoice("Filter", Filter.WHITELIST)
213
    private val blocks by blocks("Blocks", blockSortedSetOf(blocks = DEFAULT_BLOCKS))
214
    private val placer = tree(BlockPlacer(
215
        "Placing",
216
        this,
217
        Priority.IMPORTANT_FOR_PLAYER_LIFE,
218
        { filter.getSlot(blocks) }
219
    ))
220
221
    private var addExtraLayerBlocks = false
222
    private var startY = 0.0
223
    private val centerPos = Vector2d()
224
225
    init {
226
        // for this module, support should by default be able to use obsidian
227
        placer.support.blocks.addAll(DEFAULT_BLOCKS)
228
    }
229
230
    override fun onEnabled() {
231
        if (Features.CENTER in features) {
232
            CommandCenter.state = CenterHandlerState.APPLY_ON_NEXT_EVENT
233
        }
234
235
        startY = player.position().y
236
        val centerBlockPos = player.blockPosition().center
237
        centerPos.set(centerBlockPos.x, centerBlockPos.z)
238
    }
239
240
    override fun onDisabled() {
241
        placer.disable()
242
        addExtraLayerBlocks = false
243
        centerPos.set(0.0)
244
    }
245
246
    @Suppress("unused")
247
    val keyHandler = handler<KeyboardKeyEvent> {
248
        addExtraLayerBlocks = addExtraLayer.getNewState(it, addExtraLayerBlocks)
249
    }
250
251
    @Suppress("unused", "MagicNumber")
252
    private val tickMoveHandler = handler<PlayerNetworkMovementTickEvent> {
253
        if (it.state == EventState.PRE) {
254
            return@handler
255
        }
256
257
        val yChange = DisableOn.Y_CHANGE in disableOn && it.y != startY
258
        val dx = abs(player.x - centerPos.x)
259
        val dz = abs(player.z - centerPos.y)
260
        val xzChange = DisableOn.XZ_MOVE in disableOn && (dx > 0.5 || dz > 0.5)
261
        val speed = player.position().subtract(player.xo, player.yo, player.zo).lengthSqr() * 20.0
262
        val highSpeed = DisableOn.XZ_SPEED in disableOn && speed >= 5.0
263
        if (yChange || xzChange || highSpeed) {
264
            enabled = false
265
        }
266
    }
267
268
    @Suppress("unused")
269
    private val targetUpdater = handler<RotationUpdateEvent> {
270
        if (DisableOn.Y_CHANGE in disableOn && player.position().y != startY) {
271
            enabled = false
272
            return@handler
273
        }
274
275
        val bb = player.boundingBox
276
        val y = ceil(bb.minY)
277
278
        val feetBlockPos = player.getFeetBlockPos()
279
        val hole = if (Features.NO_WASTE in features && player.isInHole(feetBlockPos)) {
280
            listOf(feetBlockPos)
281
        } else {
282
            val maxX = getMax(bb, Direction.Axis.X)
283
            val maxZ = getMax(bb, Direction.Axis.Z)
284
            listOf(
285
                BlockPos.containing(bb.minX, y, bb.minZ),
286
                BlockPos.containing(bb.minX, y, maxZ),
287
                BlockPos.containing(maxX, y, bb.minZ),
288
                BlockPos.containing(maxX, y, maxZ),
289
            )
290
        }
291
292
        val holeBlocks = hashSetOf<BlockPos>()
293
        val blocked = hashSetOf<BlockPos>()
294
        blocked.addAll(hole)
295
296
        for (holePos in hole) {
297
            DIRECTIONS_EXCLUDING_UP.forEach { direction ->
298
                val pos = holePos.relative(direction)
299
                if (pos in hole || !holeBlocks.add(pos)) {
300
                    return@forEach
301
                }
302
303
                val isDown = direction == Direction.DOWN
304
                if (isDown && Features.DOWN in features) {
305
                    holeBlocks.add(holePos.relative(direction, 2))
306
                }
307
308
                if (!isDown && (addExtraLayerBlocks || Protect.broken.contains(pos.asLong()))) {
309
                    holeBlocks.add(pos.relative(direction))
310
                    holeBlocks.add(pos.above())
311
                    if (Protect.ExtraLayer.corners) {
312
                        holeBlocks.add(pos.relative(direction.clockWise))
313
                    }
314
                }
315
316
                if (!isDown && Features.EXTEND in features) {
317
                    pos.getBlockingEntities(except = player) { it !is EndCrystal }.forEach {
318
                        getEntitySurround(it, holeBlocks, blocked, y)
319
                    }
320
                }
321
            }
322
        }
323
324
        placer.update(holeBlocks)
325
    }
326
327
    @Suppress("unused")
328
    private val blockUpdateHandler = handler<PacketEvent> {
329
        if (!instant) {
330
            return@handler
331
        }
332
333
        placer.placeInstantOnBlockUpdate(it)
334
    }
335
336
    private fun getEntitySurround(
337
        entity: Entity,
338
        list: HashSet<BlockPos>,
339
        blocked: HashSet<BlockPos>,
340
        y: Double,
341
        down: Boolean = false
342
    ) {
343
        val bb = entity.boundingBox
344
345
        val maxX = getMax(bb, Direction.Axis.X)
346
        val maxZ = getMax(bb, Direction.Axis.Z)
347
        val hole = listOf(
348
            BlockPos.containing(bb.minX, y, bb.minZ),
349
            BlockPos.containing(bb.minX, y, maxZ),
350
            BlockPos.containing(maxX, y, bb.minZ),
351
            BlockPos.containing(maxX, y, maxZ),
352
        )
353
354
        blocked.addAll(hole)
355
356
        val directions = if (down) DIRECTIONS_EXCLUDING_UP else Direction.BY_2D_DATA
357
        hole.forEach {
358
            for (direction in directions) {
359
                val pos = it.relative(direction)
360
361
                if (it !in blocked) {
362
                    list += pos
363
                }
364
            }
365
        }
366
    }
367
368
    private fun getMax(boundingBox: AABB, axis: Direction.Axis): Double {
369
        val max = boundingBox.max(axis)
370
        val min = boundingBox.min(axis)
371
372
        return if (max == floor(min) + 1.0) {
373
            min
374
        } else {
375
            max
376
        }
377
    }
378
379
    private enum class DisableOn(
380
        override val tag: String
381
    ) : Tagged {
382
        Y_CHANGE("YChange"),
383
        XZ_MOVE("XZMove"),
384
        XZ_SPEED("XZSpeed");
385
    }
386
387
    private enum class Features(
388
        override val tag: String
389
    ) : Tagged {
390
        /**
391
         * Runs [CommandCenter] when the module is enabled.
392
         */
393
        CENTER("Center"),
394
395
        /**
396
         * Extends when entities block placement spots.
397
         */
398
        EXTEND("Extend"),
399
400
        /**
401
         * When enabled, the surround won't build 2x1 or 2x2 holes if we already are in a completed 1x1 hole, even if
402
         * we block replacements.
403
         *
404
         * This should only be enabled if no wall placements are possible, or we have a significantly lower ping
405
         * than our opponent.
406
         */
407
        NO_WASTE("NoWaste"),
408
409
        /**
410
         * Places blocks below the surround so that enemies can't mine the block bellow you making you fall down.
411
         */
412
        DOWN("Down");
413
    }
414
}
415