freecam module

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

7 implementationsRenderRENDERVISUALS

Full module source: 7 implementations

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

Meteor ClientRendersrc/main/java/meteordevelopment/meteorclient/systems/modules/render/Freecam.javaJava · 495 lines · 16.3 KB

Allows the camera to move away from the player.

Settingsspeedspeed-scroll-sensitivitystay-sneakingtoggle-on-damagetoggle-on-deathtoggle-on-logreload-chunksshow-handsrotatestaticclick-to-pathdouble-click
Freecam.javaJava · Minecraft 26.2 · 495 lines · 16.3 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.render;
7
8
9
import meteordevelopment.meteorclient.events.game.GameLeftEvent;
10
import meteordevelopment.meteorclient.events.game.OpenScreenEvent;
11
import meteordevelopment.meteorclient.events.meteor.KeyInputEvent;
12
import meteordevelopment.meteorclient.events.meteor.MouseClickEvent;
13
import meteordevelopment.meteorclient.events.meteor.MouseScrollEvent;
14
import meteordevelopment.meteorclient.events.packets.PacketEvent;
15
import meteordevelopment.meteorclient.events.world.ChunkOcclusionEvent;
16
import meteordevelopment.meteorclient.events.world.TickEvent;
17
import meteordevelopment.meteorclient.pathing.PathManagers;
18
import meteordevelopment.meteorclient.settings.BoolSetting;
19
import meteordevelopment.meteorclient.settings.DoubleSetting;
20
import meteordevelopment.meteorclient.settings.Setting;
21
import meteordevelopment.meteorclient.settings.SettingGroup;
22
import meteordevelopment.meteorclient.systems.modules.Categories;
23
import meteordevelopment.meteorclient.systems.modules.Module;
24
import meteordevelopment.meteorclient.systems.modules.Modules;
25
import meteordevelopment.meteorclient.systems.modules.movement.GUIMove;
26
import meteordevelopment.meteorclient.utils.Utils;
27
import meteordevelopment.meteorclient.utils.misc.input.Input;
28
import meteordevelopment.meteorclient.utils.misc.input.KeyAction;
29
import meteordevelopment.meteorclient.utils.player.Rotations;
30
import meteordevelopment.orbit.EventHandler;
31
import meteordevelopment.orbit.EventPriority;
32
import net.minecraft.client.Camera;
33
import net.minecraft.client.CameraType;
34
import net.minecraft.core.BlockPos;
35
import net.minecraft.network.protocol.game.ClientboundPlayerCombatKillPacket;
36
import net.minecraft.network.protocol.game.ClientboundRespawnPacket;
37
import net.minecraft.network.protocol.game.ClientboundSetHealthPacket;
38
import net.minecraft.util.Mth;
39
import net.minecraft.world.entity.Entity;
40
import net.minecraft.world.entity.projectile.ProjectileUtil;
41
import net.minecraft.world.level.ClipContext;
42
import net.minecraft.world.phys.*;
43
import net.minecraft.world.phys.shapes.CollisionContext;
44
import org.joml.Vector3d;
45
import org.jspecify.annotations.Nullable;
46
import com.mojang.blaze3d.platform.InputConstants;
47
48
public class Freecam extends Module {
49
    private final SettingGroup sgGeneral = settings.getDefaultGroup();
50
    private final SettingGroup sgPathing = settings.createGroup("Pathing");
51
52
    private final Setting<Double> speed = sgGeneral.add(new DoubleSetting.Builder()
53
        .name("speed")
54
        .description("Your speed while in freecam.")
55
        .onChanged(aDouble -> speedValue = aDouble)
56
        .defaultValue(1.0)
57
        .min(0.0)
58
        .build()
59
    );
60
61
    private final Setting<Double> speedScrollSensitivity = sgGeneral.add(new DoubleSetting.Builder()
62
        .name("speed-scroll-sensitivity")
63
        .description("Allows you to change speed value using scroll wheel. 0 to disable.")
64
        .defaultValue(0)
65
        .min(0)
66
        .sliderMax(2)
67
        .build()
68
    );
69
70
    private final Setting<Boolean> staySneaking = sgGeneral.add(new BoolSetting.Builder()
71
        .name("stay-sneaking")
72
        .description("If you are sneaking when you enter freecam, whether your player should remain sneaking.")
73
        .defaultValue(true)
74
        .build()
75
    );
76
77
    private final Setting<Boolean> toggleOnDamage = sgGeneral.add(new BoolSetting.Builder()
78
        .name("toggle-on-damage")
79
        .description("Disables freecam when you take damage.")
80
        .defaultValue(false)
81
        .build()
82
    );
83
84
    private final Setting<Boolean> toggleOnDeath = sgGeneral.add(new BoolSetting.Builder()
85
        .name("toggle-on-death")
86
        .description("Disables freecam when you die.")
87
        .defaultValue(false)
88
        .build()
89
    );
90
91
    private final Setting<Boolean> toggleOnLog = sgGeneral.add(new BoolSetting.Builder()
92
        .name("toggle-on-log")
93
        .description("Disables freecam when you disconnect from a server.")
94
        .defaultValue(true)
95
        .build()
96
    );
97
98
    private final Setting<Boolean> reloadChunks = sgGeneral.add(new BoolSetting.Builder()
99
        .name("reload-chunks")
100
        .description("Disables cave culling.")
101
        .defaultValue(true)
102
        .build()
103
    );
104
105
    private final Setting<Boolean> renderHands = sgGeneral.add(new BoolSetting.Builder()
106
        .name("show-hands")
107
        .description("Whether or not to render your hands in freecam.")
108
        .defaultValue(true)
109
        .build()
110
    );
111
112
    private final Setting<Boolean> rotate = sgGeneral.add(new BoolSetting.Builder()
113
        .name("rotate")
114
        .description("Rotates to the block or entity you are looking at.")
115
        .defaultValue(false)
116
        .build()
117
    );
118
119
    private final Setting<Boolean> staticView = sgGeneral.add(new BoolSetting.Builder()
120
        .name("static")
121
        .description("Disables settings that move the view.")
122
        .defaultValue(true)
123
        .build()
124
    );
125
126
    private final Setting<Boolean> baritoneClick = sgPathing.add(new BoolSetting.Builder()
127
        .name("click-to-path")
128
        .description("Sets a pathfinding goal to any block/entity you click at.")
129
        .defaultValue(false)
130
        .build()
131
    );
132
133
    private final Setting<Boolean> requireDoubleClick = sgPathing.add(new BoolSetting.Builder()
134
        .name("double-click")
135
        .description("Require two clicks to start pathing.")
136
        .defaultValue(false)
137
        .build()
138
    );
139
140
    public final Vector3d pos = new Vector3d();
141
    public final Vector3d prevPos = new Vector3d();
142
143
    private CameraType perspective;
144
    private double speedValue;
145
146
    public float yaw, pitch;
147
    public float lastYaw, lastPitch;
148
149
    private double fovScale;
150
    private boolean bobView;
151
152
    private boolean forward, backward, right, left, up, down, isSneaking;
153
154
    private long clickTs = 0;
155
156
    public Freecam() {
157
        super(Categories.Render, "freecam", "Allows the camera to move away from the player.");
158
    }
159
160
    @Override
161
    public void onActivate() {
162
        fovScale = mc.options.fovEffectScale().get();
163
        bobView = mc.options.bobView().get();
164
        if (staticView.get()) {
165
            mc.options.fovEffectScale().set((double) 0);
166
            mc.options.bobView().set(false);
167
        }
168
        yaw = mc.player.getYRot();
169
        pitch = mc.player.getXRot();
170
171
        perspective = mc.options.getCameraType();
172
        speedValue = speed.get();
173
174
        Utils.set(pos, mc.gameRenderer.mainCamera().position());
175
        Utils.set(prevPos, mc.gameRenderer.mainCamera().position());
176
177
        if (mc.options.getCameraType() == CameraType.THIRD_PERSON_FRONT) {
178
            yaw += 180;
179
            pitch *= -1;
180
        }
181
182
        lastYaw = yaw;
183
        lastPitch = pitch;
184
185
        isSneaking = mc.options.keyShift.isDown();
186
187
        forward = Input.isPressed(mc.options.keyUp);
188
        backward = Input.isPressed(mc.options.keyDown);
189
        right = Input.isPressed(mc.options.keyRight);
190
        left = Input.isPressed(mc.options.keyLeft);
191
        up = Input.isPressed(mc.options.keyJump);
192
        down = Input.isPressed(mc.options.keyShift);
193
194
        unpress();
195
        if (reloadChunks.get()) {
196
            mc.levelExtractor.allChanged();
197
        }
198
    }
199
200
    @Override
201
    public void onDeactivate() {
202
        if (reloadChunks.get()) {
203
            mc.execute(mc.levelExtractor::allChanged);
204
        }
205
206
        mc.options.setCameraType(perspective);
207
208
        if (staticView.get()) {
209
            mc.options.fovEffectScale().set(fovScale);
210
            mc.options.bobView().set(bobView);
211
        }
212
213
        isSneaking = false;
214
    }
215
216
    @EventHandler
217
    private void onOpenScreen(OpenScreenEvent event) {
218
        unpress();
219
220
        prevPos.set(pos);
221
        lastYaw = yaw;
222
        lastPitch = pitch;
223
    }
224
225
    private void unpress() {
226
        mc.options.keyUp.setDown(false);
227
        mc.options.keyDown.setDown(false);
228
        mc.options.keyRight.setDown(false);
229
        mc.options.keyLeft.setDown(false);
230
        mc.options.keyJump.setDown(false);
231
        mc.options.keyShift.setDown(false);
232
    }
233
234
    @EventHandler
235
    private void onTick(TickEvent.Post event) {
236
        if (mc.getCameraEntity().isInWall()) mc.getCameraEntity().noPhysics = true;
237
        if (!perspective.isFirstPerson()) mc.options.setCameraType(CameraType.FIRST_PERSON);
238
239
        Vec3 forward = Vec3.directionFromRotation(0, yaw);
240
        Vec3 right = Vec3.directionFromRotation(0, yaw + 90);
241
        double velX = 0;
242
        double velY = 0;
243
        double velZ = 0;
244
245
        if (rotate.get()) {
246
            BlockPos crossHairPos;
247
            Vec3 crossHairPosition;
248
249
            if (mc.hitResult instanceof EntityHitResult ehr) {
250
                crossHairPos = ehr.getEntity().blockPosition();
251
                Rotations.rotate(Rotations.getYaw(crossHairPos), Rotations.getPitch(crossHairPos), 0, null);
252
            } else {
253
                crossHairPosition = mc.hitResult.getLocation();
254
                crossHairPos = ((BlockHitResult) mc.hitResult).getBlockPos();
255
256
                if (!mc.level.getBlockState(crossHairPos).isAir()) {
257
                    Rotations.rotate(Rotations.getYaw(crossHairPosition), Rotations.getPitch(crossHairPosition), 0, null);
258
                }
259
            }
260
        }
261
262
        double s = 0.5;
263
        if (Input.isPressed(mc.options.keySprint)) s = 1;
264
265
        boolean a = false;
266
        if (this.forward) {
267
            velX += forward.x * s * speedValue;
268
            velZ += forward.z * s * speedValue;
269
            a = true;
270
        }
271
        if (this.backward) {
272
            velX -= forward.x * s * speedValue;
273
            velZ -= forward.z * s * speedValue;
274
            a = true;
275
        }
276
277
        boolean b = false;
278
        if (this.right) {
279
            velX += right.x * s * speedValue;
280
            velZ += right.z * s * speedValue;
281
            b = true;
282
        }
283
        if (this.left) {
284
            velX -= right.x * s * speedValue;
285
            velZ -= right.z * s * speedValue;
286
            b = true;
287
        }
288
289
        if (a && b) {
290
            double diagonal = 1 / Math.sqrt(2);
291
            velX *= diagonal;
292
            velZ *= diagonal;
293
        }
294
295
        if (this.up) {
296
            velY += s * speedValue;
297
        }
298
        if (this.down) {
299
            velY -= s * speedValue;
300
        }
301
302
        prevPos.set(pos);
303
        pos.set(pos.x + velX, pos.y + velY, pos.z + velZ);
304
    }
305
306
    @EventHandler(priority = EventPriority.HIGH)
307
    public void onKey(KeyInputEvent event) {
308
        if (Input.isKeyPressed(InputConstants.KEY_F3)) return;
309
        if (checkGuiMove()) return;
310
311
        if (onInput(event.key(), event.action)) event.cancel();
312
    }
313
314
    @Nullable
315
    private BlockPos rayCastEntity(Vec3 posVec, Vec3 max, short maxDist) {
316
        EntityHitResult res = ProjectileUtil.getEntityHitResult(
317
            mc.player,
318
            posVec,
319
            max,
320
            AABB.encapsulatingFullBlocks(BlockPos.containing(posVec.x, posVec.y, posVec.z), BlockPos.containing(max.x, max.y, max.z)),
321
            _ -> true,
322
            maxDist
323
        );
324
325
        if (res == null) return null;
326
327
        Vec3 vec = res.getLocation();
328
329
        return BlockPos.containing(vec.x, vec.y, vec.z);
330
    }
331
332
    @Nullable
333
    private BlockPos rayCastBlock(Vec3 posVec, Vec3 max) {
334
        ClipContext ctx = new ClipContext(
335
            posVec,
336
            max,
337
            ClipContext.Block.VISUAL,
338
            ClipContext.Fluid.SOURCE_ONLY,
339
            CollisionContext.empty()
340
        );
341
342
        BlockHitResult res = mc.level.clip(ctx);
343
        if (res.getType() == HitResult.Type.MISS) return null;
344
345
        // Don't move inside block
346
        return res.getBlockPos().offset(res.getDirection().getUnitVec3i());
347
    }
348
349
    private void setGoal() {
350
        long prevClick = clickTs;
351
        clickTs = System.currentTimeMillis();
352
353
        if (requireDoubleClick.get() && clickTs - prevClick > 500) return;
354
355
        Camera cam = mc.gameRenderer.mainCamera();
356
        Vec3 posVec = cam.position();
357
        Vec3 lookVec = Vec3.directionFromRotation(cam.xRot(), cam.yRot());
358
        short maxDist = 256;
359
        Vec3 max = posVec.add(lookVec.scale(maxDist));
360
361
        BlockPos pos = rayCastEntity(posVec, max, maxDist);
362
        if (pos == null) {
363
            pos = rayCastBlock(posVec, max);
364
        }
365
366
        if (pos == null) return;
367
368
        PathManagers.get().moveTo(pos);
369
    }
370
371
    @EventHandler(priority = EventPriority.HIGH)
372
    private void onMouseClick(MouseClickEvent event) {
373
        if (checkGuiMove()) return;
374
375
        if (baritoneClick.get() && event.action == KeyAction.Press && mc.options.keyAttack.matchesMouse(event.click)) {
376
            setGoal();
377
        }
378
379
        if (onInput(event.button(), event.action)) event.cancel();
380
    }
381
382
    private boolean onInput(int key, KeyAction action) {
383
        if (Input.getKey(mc.options.keyUp) == key) {
384
            forward = action != KeyAction.Release;
385
            mc.options.keyUp.setDown(false);
386
        } else if (Input.getKey(mc.options.keyDown) == key) {
387
            backward = action != KeyAction.Release;
388
            mc.options.keyDown.setDown(false);
389
        } else if (Input.getKey(mc.options.keyRight) == key) {
390
            right = action != KeyAction.Release;
391
            mc.options.keyRight.setDown(false);
392
        } else if (Input.getKey(mc.options.keyLeft) == key) {
393
            left = action != KeyAction.Release;
394
            mc.options.keyLeft.setDown(false);
395
        } else if (Input.getKey(mc.options.keyJump) == key) {
396
            up = action != KeyAction.Release;
397
            mc.options.keyJump.setDown(false);
398
        } else if (Input.getKey(mc.options.keyShift) == key) {
399
            down = action != KeyAction.Release;
400
            mc.options.keyShift.setDown(false);
401
        } else {
402
            return false;
403
        }
404
405
        return true;
406
    }
407
408
    @EventHandler(priority = EventPriority.LOW)
409
    private void onMouseScroll(MouseScrollEvent event) {
410
        if (speedScrollSensitivity.get() > 0 && mc.gui.screen() == null) {
411
            speedValue += event.value * 0.25 * (speedScrollSensitivity.get() * speedValue);
412
            if (speedValue < 0.1) speedValue = 0.1;
413
414
            event.cancel();
415
        }
416
    }
417
418
    @EventHandler
419
    private void onChunkOcclusion(ChunkOcclusionEvent event) {
420
        event.cancel();
421
    }
422
423
    @EventHandler
424
    private void onGameLeft(GameLeftEvent event) {
425
        if (!toggleOnLog.get()) return;
426
427
        toggle();
428
    }
429
430
    @EventHandler
431
    private void onPacketReceive(PacketEvent.Receive event) {
432
        if (event.packet instanceof ClientboundPlayerCombatKillPacket packet) {
433
            Entity entity = mc.level.getEntity(packet.playerId());
434
            if (entity == mc.player && toggleOnDeath.get()) {
435
                toggle();
436
                info("Toggled off because you died.");
437
            }
438
        } else if (event.packet instanceof ClientboundSetHealthPacket packet) {
439
            if (mc.player.getHealth() - packet.getHealth() > 0 && toggleOnDamage.get()) {
440
                toggle();
441
                info("Toggled off because you took damage.");
442
            }
443
        } else if (event.packet instanceof ClientboundRespawnPacket) {
444
            if (isActive()) {
445
                toggle();
446
                info("Toggled off because you changed dimensions.");
447
            }
448
        }
449
    }
450
451
    private boolean checkGuiMove() {
452
        GUIMove guiMove = Modules.get().get(GUIMove.class);
453
        if (mc.gui.screen() != null && !guiMove.isActive()) return true;
454
        return (mc.gui.screen() != null && guiMove.isActive() && guiMove.skip());
455
    }
456
457
    public void changeLookDirection(double deltaX, double deltaY) {
458
        lastYaw = yaw;
459
        lastPitch = pitch;
460
461
        yaw += (float) deltaX;
462
        pitch += (float) deltaY;
463
464
        pitch = Mth.clamp(pitch, -90, 90);
465
    }
466
467
    public boolean renderHands() {
468
        return !isActive() || renderHands.get();
469
    }
470
471
    public boolean staySneaking() {
472
        return isActive() && !mc.player.getAbilities().flying && staySneaking.get() && isSneaking;
473
    }
474
475
    public double getX(float tickDelta) {
476
        return Mth.lerp(tickDelta, prevPos.x, pos.x);
477
    }
478
479
    public double getY(float tickDelta) {
480
        return Mth.lerp(tickDelta, prevPos.y, pos.y);
481
    }
482
483
    public double getZ(float tickDelta) {
484
        return Mth.lerp(tickDelta, prevPos.z, pos.z);
485
    }
486
487
    public double getYaw(float tickDelta) {
488
        return Mth.lerp(tickDelta, lastYaw, yaw);
489
    }
490
491
    public double getPitch(float tickDelta) {
492
        return Mth.lerp(tickDelta, lastPitch, pitch);
493
    }
494
}
495
MelaHack (ThunderHack fork)RENDERsrc/main/java/thunder/hack/features/modules/render/FreeCam.javaJava · 158 lines · 4.8 KB

Unhooks the camera from the player.

SettingsHSpeedVSpeedFreezeTrack
FreeCam.javaJava · Minecraft 26.2 · 158 lines · 4.8 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.render;
2
3
import meteordevelopment.orbit.EventHandler;
4
import meteordevelopment.orbit.EventPriority;
5
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
6
import net.minecraft.world.entity.LivingEntity;
7
import org.lwjgl.glfw.GLFW;
8
import thunder.hack.events.impl.*;
9
import thunder.hack.features.modules.Module;
10
import thunder.hack.setting.Setting;
11
import thunder.hack.utility.player.MovementUtility;
12
import thunder.hack.utility.render.Render2DEngine;
13
import thunder.hack.utility.render.Render3DEngine;
14
15
public class FreeCam extends Module {
16
    public FreeCam() {
17
        super("FreeCam", Category.RENDER);
18
    }
19
20
    private final Setting<Float> speed = new Setting<>("HSpeed", 1f, 0.1f, 3f);
21
    private final Setting<Float> hspeed = new Setting<>("VSpeed", 0.42f, 0.1f, 3f);
22
    private final Setting<Boolean> freeze = new Setting<>("Freeze", false);
23
    public final Setting<Boolean> track = new Setting<>("Track", false);
24
25
    private float fakeYaw, fakePitch, prevFakeYaw, prevFakePitch, prevScroll;
26
    private double fakeX, fakeY, fakeZ, prevFakeX, prevFakeY, prevFakeZ;
27
    public LivingEntity trackEntity;
28
29
    @Override
30
    public void onEnable() {
31
        mc.smartCull = false;
32
        trackEntity = null;
33
34
        fakePitch = mc.player.getXRot();
35
        fakeYaw = mc.player.getYRot();
36
37
        prevFakePitch = fakePitch;
38
        prevFakeYaw = fakeYaw;
39
40
        fakeX = mc.player.getX();
41
        fakeY = mc.player.getY() + mc.player.getEyeHeight(mc.player.getPose());
42
        fakeZ = mc.player.getZ();
43
44
        prevFakeX = mc.player.getX();
45
        prevFakeY = mc.player.getY();
46
        prevFakeZ = mc.player.getZ();
47
    }
48
49
    @EventHandler
50
    public void onAttack(EventAttack e) {
51
        if (!e.isPre() && e.getEntity() instanceof LivingEntity entity && track.getValue())
52
            trackEntity = entity;
53
    }
54
55
    @Override
56
    public void onDisable() {
57
        if (fullNullCheck()) return;
58
        mc.smartCull = true;
59
    }
60
61
    @EventHandler(priority = EventPriority.HIGH)
62
    public void onSync(EventSync e) {
63
        prevFakeYaw = fakeYaw;
64
        prevFakePitch = fakePitch;
65
66
        if (isKeyPressed(GLFW.GLFW_KEY_ESCAPE) || isKeyPressed(GLFW.GLFW_KEY_LEFT_SHIFT) || isKeyPressed(GLFW.GLFW_KEY_RIGHT_SHIFT))
67
            trackEntity = null;
68
69
        if (trackEntity != null) {
70
            fakeYaw = trackEntity.getYRot();
71
            fakePitch = trackEntity.getXRot();
72
73
            prevFakeX = fakeX;
74
            prevFakeY = fakeY;
75
            prevFakeZ = fakeZ;
76
77
            fakeX = trackEntity.getX();
78
            fakeY = trackEntity.getY() + trackEntity.getEyeHeight(trackEntity.getPose());
79
            fakeZ = trackEntity.getZ();
80
        } else {
81
            fakeYaw = mc.player.getYRot();
82
            fakePitch = mc.player.getXRot();
83
        }
84
    }
85
86
87
    @EventHandler
88
    public void onKeyboardInput(EventKeyboardInput e) {
89
        if (mc.player == null) return;
90
91
        if (trackEntity == null) {
92
            double[] motion = MovementUtility.forward(speed.getValue());
93
94
            prevFakeX = fakeX;
95
            prevFakeY = fakeY;
96
            prevFakeZ = fakeZ;
97
98
            fakeX += motion[0];
99
            fakeZ += motion[1];
100
101
            if (mc.options.keyJump.isDown())
102
                fakeY += hspeed.getValue();
103
104
            if (mc.options.keyShift.isDown())
105
                fakeY -= hspeed.getValue();
106
        }
107
108
        MovementUtility.clearMovementInput();
109
        mc.options.keyJump.setDown(false);
110
        mc.options.keyShift.setDown(false);
111
    }
112
113
    @EventHandler(priority = EventPriority.LOW)
114
    public void onMove(EventMove e) {
115
        if (freeze.getValue()) {
116
            e.setX(0.);
117
            e.setY(0.);
118
            e.setZ(0.);
119
            e.cancel();
120
        }
121
    }
122
123
    @EventHandler
124
    public void onPacketSend(PacketEvent.Send e) {
125
        if (freeze.getValue() && e.getPacket() instanceof ServerboundMovePlayerPacket)
126
            e.cancel();
127
    }
128
129
    @EventHandler
130
    public void onScroll(EventMouse e) {
131
        if (e.getAction() == 2) {
132
            if (e.getButton() > 0) speed.setValue(speed.getValue() + 0.05f);
133
            else speed.setValue(speed.getValue() - 0.05f);
134
            prevScroll = e.getButton();
135
        }
136
    }
137
138
    public float getFakeYaw() {
139
        return (float) Render2DEngine.interpolate(prevFakeYaw, fakeYaw, Render3DEngine.getTickDelta());
140
    }
141
142
    public float getFakePitch() {
143
        return (float) Render2DEngine.interpolate(prevFakePitch, fakePitch, Render3DEngine.getTickDelta());
144
    }
145
146
    public double getFakeX() {
147
        return Render2DEngine.interpolate(prevFakeX, fakeX, Render3DEngine.getTickDelta());
148
    }
149
150
    public double getFakeY() {
151
        return Render2DEngine.interpolate(prevFakeY, fakeY, Render3DEngine.getTickDelta());
152
    }
153
154
    public double getFakeZ() {
155
        return Render2DEngine.interpolate(prevFakeZ, fakeZ, Render3DEngine.getTickDelta());
156
    }
157
}
158
OfflineClientRENDERsrc/main/java/com/jellypudding/offlineclient/modules/render/Freecam.javaJava · 481 lines · 18.8 KB

Fly the camera around whilst your character stays still.

SettingsHorizontal speedVertical speedApply input toInteract fromScroll sensitivityHide handBlock clicksRotateStay sneakingStill viewStart atTracerTracer colourDisable on damageDisable on deathDisable on leaveClick to walkDouble clickReload chunks
Freecam.javaJava · Minecraft 26.2 · 481 lines · 18.8 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.render;
2
3
import com.jellypudding.offlineclient.event.Subscribe;
4
import com.jellypudding.offlineclient.event.events.ClientTickEvent;
5
import com.jellypudding.offlineclient.event.events.LeftClickEvent;
6
import com.jellypudding.offlineclient.event.events.MouseScrollEvent;
7
import com.jellypudding.offlineclient.event.events.PacketReceiveEvent;
8
import com.jellypudding.offlineclient.event.events.Render3DEvent;
9
import com.jellypudding.offlineclient.event.events.RightClickEvent;
10
import com.jellypudding.offlineclient.event.events.TickEvent;
11
import com.jellypudding.offlineclient.module.Category;
12
import com.jellypudding.offlineclient.module.Module;
13
import com.jellypudding.offlineclient.path.PathWalker;
14
import com.jellypudding.offlineclient.path.Trip;
15
import com.jellypudding.offlineclient.setting.BoolSetting;
16
import com.jellypudding.offlineclient.setting.ColorSetting;
17
import com.jellypudding.offlineclient.setting.EnumSetting;
18
import com.jellypudding.offlineclient.setting.NumberSetting;
19
import com.jellypudding.offlineclient.util.ChatUtil;
20
import com.jellypudding.offlineclient.util.ChunkRebuild;
21
import com.jellypudding.offlineclient.util.EntityUtil;
22
import com.jellypudding.offlineclient.util.InputUtil;
23
import com.jellypudding.offlineclient.util.RotationManager;
24
import com.jellypudding.offlineclient.util.RotationPriority;
25
import net.minecraft.client.CameraType;
26
import net.minecraft.client.player.ClientInput;
27
import net.minecraft.client.player.LocalPlayer;
28
import net.minecraft.core.BlockPos;
29
import net.minecraft.network.protocol.game.ClientboundPlayerCombatKillPacket;
30
import net.minecraft.network.protocol.game.ClientboundRespawnPacket;
31
import net.minecraft.util.Mth;
32
import net.minecraft.world.entity.player.Input;
33
import net.minecraft.world.entity.projectile.ProjectileUtil;
34
import net.minecraft.world.level.ClipContext;
35
import net.minecraft.world.phys.AABB;
36
import net.minecraft.world.phys.BlockHitResult;
37
import net.minecraft.world.phys.EntityHitResult;
38
import net.minecraft.world.phys.HitResult;
39
import net.minecraft.world.phys.Vec3;
40
41
// CameraMixin positions the camera and MouseHandlerMixin routes the mouse here.
42
// PickMixin aims the crosshair and VisGraphMixin keeps chunk insides drawn.
43
public final class Freecam extends Module {
44
45
    public enum Start { INSIDE, IN_FRONT, ABOVE }
46
47
    // How far a start other than Inside sits from your eyes.
48
    private static final double START_STEP = 3;
49
50
    // Share of the speed one wheel notch changes at sensitivity one.
51
    private static final double NOTCH_SHARE = 0.25;
52
    private static final double MIN_SPEED = 0.1;
53
54
    // Two clicks this close together count as a double click.
55
    private static final long DOUBLE_CLICK_MS = 500;
56
57
    public enum InputTarget { CAMERA, PLAYER }
58
59
    public enum InteractFrom { PLAYER, CAMERA }
60
61
    private final NumberSetting speed = new NumberSetting("Horizontal speed",
62
        "How fast the camera moves along.", 1, 0.1, 5, 0.1);
63
    private final NumberSetting verticalSpeed = new NumberSetting("Vertical speed",
64
        "How fast the camera climbs and dives as a share of the speed.", 1, 0.1, 5, 0.1, "x");
65
    private final EnumSetting<InputTarget> inputTarget = new EnumSetting<>("Apply input to",
66
        "Who the keys and the mouse steer.", InputTarget.CAMERA)
67
        .describe(InputTarget.CAMERA, "The camera moves and your body stands still.")
68
        .describe(InputTarget.PLAYER, "Your body keeps moving whilst the camera hangs where you left it.");
69
    private final EnumSetting<InteractFrom> interactFrom = new EnumSetting<>("Interact from",
70
        "Where clicks are aimed from.", InteractFrom.PLAYER)
71
        .describe(InteractFrom.PLAYER, "Clicks go where your body looks.")
72
        .describe(InteractFrom.CAMERA, "Clicks go where the camera looks. The server still checks reach from your body.");
73
    private final NumberSetting scrollSensitivity = new NumberSetting("Scroll sensitivity",
74
        "How much of the speed one wheel notch adds or takes away. Nought leaves the wheel to the hotbar.",
75
        0.5, 0, 2, 0.1, "x").min(0).max(5);
76
    private final BoolSetting hideHand = new BoolSetting("Hide hand",
77
        "Hides the held item whilst the camera is away.", true);
78
    private final BoolSetting blockClicks = new BoolSetting("Block clicks",
79
        "Clicks do nothing whilst the camera is away.", true);
80
    private final BoolSetting rotate = new BoolSetting("Rotate",
81
        "Turns your body to face whatever the camera crosshair rests on.", false);
82
    private final BoolSetting staySneaking = new BoolSetting("Stay sneaking",
83
        "If you were sneaking when the camera left your body keeps sneaking.", true);
84
    private final BoolSetting stillView = new BoolSetting("Still view",
85
        "Turns off view bobbing and speed field of view changes whilst the camera is away.", true);
86
    private final EnumSetting<Start> start = new EnumSetting<>("Start at",
87
        "Where the camera begins when you switch it on.", Start.INSIDE)
88
        .describe(Start.INSIDE, "Right where your eyes are.")
89
        .describe(Start.IN_FRONT, "A few blocks in front of you.")
90
        .describe(Start.ABOVE, "A few blocks over your head.");
91
    private final BoolSetting tracer = new BoolSetting("Tracer",
92
        "Draws a line back to your body.", true);
93
    private final ColorSetting tracerColor = new ColorSetting("Tracer colour",
94
        "Colour of the line back to your body.", 193, 0.75f, 1f, false).under(tracer);
95
    private final BoolSetting disableOnDamage = new BoolSetting("Disable on damage",
96
        "Snaps back to your body when you take a hit.", true);
97
    private final BoolSetting disableOnDeath = new BoolSetting("Disable on death",
98
        "Snaps back to your body when you die.", false);
99
    private final BoolSetting disableOnLeave = new BoolSetting("Disable on leave",
100
        "Turns off when you leave the server.", true);
101
    private final BoolSetting clickToWalk = new BoolSetting("Click to walk",
102
        "A left click walks your body to the block the camera looks at. Any movement key stops it.",
103
        false);
104
    private final BoolSetting doubleClick = new BoolSetting("Double click",
105
        "Needs two clicks within half a second.", false).under(clickToWalk);
106
    private final BoolSetting reloadChunks = new BoolSetting("Reload chunks",
107
        "Redraws the world when the camera leaves and when it comes back so walls stop hiding rooms.", false);
108
109
    private Vec3 camPos = Vec3.ZERO;
110
    private Vec3 prevCamPos = Vec3.ZERO;
111
    private float camYaw;
112
    private float camPitch;
113
    private final Trip trip = new Trip();
114
    private long lastClick;
115
116
    private ClientInput dummyInput;
117
    private ClientInput realInput;
118
    // The player the camera was seeded from. A respawn or a portal hands out a new one.
119
    private LocalPlayer seededFor;
120
    private float lastHealth;
121
    private boolean sneakingAtStart;
122
    private CameraType savedView;
123
    private double savedFovScale;
124
    private boolean savedBobbing;
125
    private boolean viewChanged;
126
    // Set on the netty thread and acted on next tick.
127
    private volatile String stopReason;
128
129
    public Freecam() {
130
        super("Freecam", "Fly the camera around whilst your character stays still.", Category.RENDER);
131
        addSettings(start, speed, verticalSpeed, inputTarget, interactFrom, scrollSensitivity, hideHand,
132
            blockClicks, rotate, staySneaking, stillView, tracer, tracerColor, disableOnDamage, disableOnDeath,
133
            disableOnLeave, reloadChunks);
134
        searchTags("free camera", "spectator", "detach");
135
    }
136
137
    @Override
138
    public String getSuffix() {
139
        return speed.getValueString();
140
    }
141
142
    // Consulted by MinecraftMixin before the game handles an attack.
143
    public boolean blocksClicks() {
144
        return isEnabled() && blockClicks.isOn();
145
    }
146
147
    // True whilst the keys and the mouse drive the camera rather than the body.
148
    public boolean movesCamera() {
149
        return isEnabled() && inputTarget.is(InputTarget.CAMERA);
150
    }
151
152
    public boolean interactsFromCamera() {
153
        return isEnabled() && interactFrom.is(InteractFrom.CAMERA);
154
    }
155
156
    public boolean hidesHand() {
157
        return isEnabled() && hideHand.isOn();
158
    }
159
160
    @Subscribe
161
    private void onRightClick(RightClickEvent event) {
162
        if (blocksClicks()) {
163
            event.cancel();
164
        }
165
    }
166
167
    @Subscribe
168
    private void onScroll(MouseScrollEvent event) {
169
        if (!movesCamera() || scrollSensitivity.getValue() <= 0 || mc.gui.screen() != null) {
170
            return;
171
        }
172
        double now = speed.getValue();
173
        speed.setValue(Math.max(MIN_SPEED, now + event.getAmount() * NOTCH_SHARE * scrollSensitivity.getValue() * now));
174
        event.cancel();
175
    }
176
177
    // Death and dimension changes arrive on the netty thread.
178
    @Subscribe
179
    private void onPacketReceive(PacketReceiveEvent event) {
180
        if (event.getPacket() instanceof ClientboundPlayerCombatKillPacket packet) {
181
            if (disableOnDeath.isOn() && mc.player != null && packet.playerId() == mc.player.getId()) {
182
                stopReason = "you died";
183
            }
184
        } else if (event.getPacket() instanceof ClientboundRespawnPacket) {
185
            stopReason = "you changed dimension";
186
        }
187
    }
188
189
    @Override
190
    public boolean savesEnabledState() {
191
        return false;
192
    }
193
194
    @Override
195
    protected void onEnable() {
196
        seededFor = null;
197
        stopReason = null;
198
        viewChanged = false;
199
        if (mc.player != null) {
200
            init();
201
        }
202
        if (reloadChunks.isOn()) {
203
            ChunkRebuild.now();
204
        }
205
    }
206
207
    private void init() {
208
        camPos = startPos();
209
        prevCamPos = camPos;
210
        camYaw = mc.player.getYRot();
211
        camPitch = mc.player.getXRot();
212
        lastHealth = mc.player.getHealth();
213
        sneakingAtStart = mc.player.isShiftKeyDown();
214
        seededFor = mc.player;
215
        takeView();
216
    }
217
218
    // Where the camera is placed the moment it is switched on.
219
    private Vec3 startPos() {
220
        Vec3 eye = mc.player.getEyePosition();
221
        return switch (start.getValue()) {
222
            case INSIDE -> eye;
223
            case IN_FRONT -> eye.add(mc.player.getViewVector(1).scale(START_STEP));
224
            case ABOVE -> eye.add(0, START_STEP, 0);
225
        };
226
    }
227
228
    // The camera always looks out from first person and the view stays still.
229
    private void takeView() {
230
        if (viewChanged) {
231
            return;
232
        }
233
        viewChanged = true;
234
        savedView = mc.options.getCameraType();
235
        savedFovScale = mc.options.fovEffectScale().get();
236
        savedBobbing = mc.options.bobView().get();
237
        mc.options.setCameraType(CameraType.FIRST_PERSON);
238
        if (stillView.isOn()) {
239
            mc.options.fovEffectScale().set(0.0);
240
            mc.options.bobView().set(false);
241
        }
242
    }
243
244
    private void giveBackView() {
245
        if (!viewChanged) {
246
            return;
247
        }
248
        viewChanged = false;
249
        mc.options.setCameraType(savedView);
250
        if (stillView.isOn()) {
251
            mc.options.fovEffectScale().set(savedFovScale);
252
            mc.options.bobView().set(savedBobbing);
253
        }
254
    }
255
256
    // Hands the player an input object that reads no keys. Only the sneak
257
    // held when the camera left stays down.
258
    private void swapInput() {
259
        realInput = mc.player.input;
260
        dummyInput = new ClientInput();
261
        if (staySneaking.isOn() && sneakingAtStart) {
262
            dummyInput.keyPresses = new Input(false, false, false, false, false, true, false);
263
        }
264
        mc.player.input = dummyInput;
265
    }
266
267
    private void restoreInput() {
268
        if (mc.player != null && realInput != null && mc.player.input == dummyInput) {
269
            mc.player.input = realInput;
270
        }
271
        realInput = null;
272
        dummyInput = null;
273
    }
274
275
    // Fires even without a world. Leaving the server can be seen.
276
    @Subscribe
277
    private void onClientTick(ClientTickEvent event) {
278
        if (disableOnLeave.isOn() && mc.level == null && seededFor != null) {
279
            setEnabled(false);
280
        }
281
    }
282
283
    @Subscribe
284
    private void onTick(TickEvent event) {
285
        if (!inGame()) {
286
            return;
287
        }
288
        if (mc.player != seededFor) {
289
            init();
290
        }
291
        String reason = stopReason;
292
        if (reason != null) {
293
            stopReason = null;
294
            ChatUtil.message("Freecam turned off because " + reason + ".");
295
            setEnabled(false);
296
            return;
297
        }
298
        syncInput();
299
300
        float healthNow = mc.player.getHealth();
301
        if (disableOnDamage.isOn() && healthNow < lastHealth) {
302
            lastHealth = healthNow;
303
            setEnabled(false);
304
            return;
305
        }
306
        lastHealth = healthNow;
307
        if (rotate.isOn()) {
308
            faceCrosshair();
309
        }
310
311
        prevCamPos = camPos;
312
        if (walkTick() || mc.gui.screen() != null || !movesCamera()) {
313
            return;
314
        }
315
        moveCamera();
316
    }
317
318
    // True whilst the body is walking to a clicked spot and the camera must stay put.
319
    private boolean walkTick() {
320
        if (!trip.active()) {
321
            return false;
322
        }
323
        if (InputUtil.physicallyHeld(mc.options.keyUp) || InputUtil.physicallyHeld(mc.options.keyDown)
324
            || InputUtil.physicallyHeld(mc.options.keyLeft) || InputUtil.physicallyHeld(mc.options.keyRight)) {
325
            trip.stop();
326
            return false;
327
        }
328
        trip.tick();
329
        return true;
330
    }
331
332
    @Subscribe
333
    private void onLeftClick(LeftClickEvent event) {
334
        if (!clickToWalk.isOn() || !inGame() || mc.gui.screen() != null) {
335
            return;
336
        }
337
        event.cancel();
338
        long now = System.currentTimeMillis();
339
        boolean second = now - lastClick <= DOUBLE_CLICK_MS;
340
        lastClick = now;
341
        if (doubleClick.isOn() && !second) {
342
            return;
343
        }
344
        HitResult hit = pick(mc.player, 1);
345
        BlockPos target;
346
        if (hit instanceof BlockHitResult block && hit.getType() == HitResult.Type.BLOCK) {
347
            target = block.getBlockPos().relative(block.getDirection());
348
        } else if (hit instanceof EntityHitResult entity) {
349
            target = entity.getEntity().blockPosition();
350
        } else {
351
            return;
352
        }
353
        trip.walker().turn(PathWalker.Turn.NONE);
354
        if (!trip.start(target, 1)) {
355
            ChatUtil.error("Could not start walking there.");
356
        }
357
    }
358
359
    // The body only loses its keys whilst they drive the camera. A respawn or
360
    // dimension change builds a fresh player with real keys and gets a new dummy.
361
    // A walk hands the keys back to the body for as long as it lasts.
362
    private void syncInput() {
363
        if (!movesCamera() || trip.active()) {
364
            restoreInput();
365
            return;
366
        }
367
        if (mc.player.input != dummyInput) {
368
            swapInput();
369
        }
370
    }
371
372
    // Turns the body towards whatever the camera crosshair rests on.
373
    private void faceCrosshair() {
374
        HitResult hit = mc.hitResult;
375
        if (hit instanceof EntityHitResult entityHit) {
376
            RotationManager.look(entityHit.getEntity().getEyePosition(), RotationPriority.IDLE,
377
                RotationManager.ENTITY_TOLERANCE);
378
        } else if (hit instanceof BlockHitResult blockHit && hit.getType() != HitResult.Type.MISS
379
            && !mc.level.getBlockState(blockHit.getBlockPos()).isAir()) {
380
            RotationManager.look(hit.getLocation(), RotationPriority.IDLE, RotationManager.BLOCK_TOLERANCE);
381
        }
382
    }
383
384
    private void moveCamera() {
385
        // Holding sprint doubles the pace.
386
        double move = speed.getValue() * (mc.options.keySprint.isDown() ? 1 : 0.5);
387
        double yaw = Math.toRadians(camYaw);
388
        Vec3 forward = new Vec3(-Math.sin(yaw), 0, Math.cos(yaw));
389
        Vec3 right = new Vec3(-Math.cos(yaw), 0, -Math.sin(yaw));
390
391
        Vec3 delta = Vec3.ZERO;
392
        if (mc.options.keyUp.isDown()) {
393
            delta = delta.add(forward);
394
        }
395
        if (mc.options.keyDown.isDown()) {
396
            delta = delta.subtract(forward);
397
        }
398
        if (mc.options.keyRight.isDown()) {
399
            delta = delta.add(right);
400
        }
401
        if (mc.options.keyLeft.isDown()) {
402
            delta = delta.subtract(right);
403
        }
404
        if (delta.lengthSqr() > 0) {
405
            delta = delta.normalize().scale(move);
406
        }
407
        double climb = move * verticalSpeed.getValue();
408
        double vertical = 0;
409
        if (mc.options.keyJump.isDown()) {
410
            vertical += climb;
411
        }
412
        if (mc.options.keyShift.isDown()) {
413
            vertical -= climb;
414
        }
415
        camPos = camPos.add(delta.x, vertical, delta.z);
416
    }
417
418
    @Subscribe
419
    private void onRender3D(Render3DEvent event) {
420
        if (!tracer.isOn() || !inGame()) {
421
            return;
422
        }
423
        event.getBatch().tracer(
424
            EntityUtil.lerpedBox(mc.player, event.getPartialTicks()).getCenter(),
425
            tracerColor.getColor(), true);
426
    }
427
428
    @Override
429
    protected void onDisable() {
430
        trip.stop();
431
        restoreInput();
432
        giveBackView();
433
        seededFor = null;
434
        // The chunks around the body were meshed from the camera's side.
435
        if (reloadChunks.isOn()) {
436
            ChunkRebuild.now();
437
        }
438
    }
439
440
    // Mouse movement lands here instead of turning the player.
441
    public void turn(double deltaYaw, double deltaPitch) {
442
        camYaw += (float) (deltaYaw * InputUtil.MOUSE_TURN);
443
        camPitch = Mth.clamp(camPitch + (float) (deltaPitch * InputUtil.MOUSE_TURN), -90f, 90f);
444
    }
445
446
    public Vec3 getCamPos(float partialTicks) {
447
        return Mth.lerp(partialTicks, prevCamPos, camPos);
448
    }
449
450
    public float getCamYaw() {
451
        return camYaw;
452
    }
453
454
    public float getCamPitch() {
455
        return camPitch;
456
    }
457
458
    // The crosshair ray cast from the camera instead of the eyes. Blocks and
459
    // entities use their own reach and the nearer hit wins like vanilla.
460
    public HitResult pick(LocalPlayer player, float partialTicks) {
461
        Vec3 start = getCamPos(partialTicks);
462
        Vec3 direction = Vec3.directionFromRotation(camPitch, camYaw);
463
464
        double blockRange = player.blockInteractionRange();
465
        HitResult result = mc.level.clip(new ClipContext(start, start.add(direction.scale(blockRange)),
466
            ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, player));
467
468
        double entityRange = player.entityInteractionRange();
469
        Vec3 entityEnd = start.add(direction.scale(entityRange));
470
        AABB bounds = new AABB(start, entityEnd).inflate(1);
471
        EntityHitResult entityHit = ProjectileUtil.getEntityHitResult(player, start, entityEnd, bounds,
472
            entity -> !entity.isSpectator() && entity.isPickable(), entityRange * entityRange);
473
        if (entityHit == null) {
474
            return result;
475
        }
476
        boolean nearer = result.getType() == HitResult.Type.MISS
477
            || entityHit.getLocation().distanceToSqr(start) < result.getLocation().distanceToSqr(start);
478
        return nearer ? entityHit : result;
479
    }
480
}
481
CombatantVISUALSsrc/main/java/combatant/client/features/module/modules/visuals/Freecam.javaJava · 244 lines · 7.0 KB
SettingsfreecamToggleshorizontalSpeedverticalSpeed
Freecam.javaJava · Minecraft 26.2 · 244 lines · 7.0 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Combatant Client distribution.
3
 * Copyright (c) 2026 pivosos2007.
4
 *
5
 * Licensed under the GNU General Public License v3.0.
6
 */
7
8
package combatant.client.features.module.modules.visuals;
9
10
import net.minecraft.client.CameraType;
11
import net.minecraft.client.Minecraft;
12
import net.minecraft.util.Mth;
13
import net.minecraft.world.phys.Vec3;
14
import combatant.client.config.values.BindMode;
15
import combatant.client.config.values.BooleanMapValue;
16
import combatant.client.config.values.NumberValue;
17
import combatant.client.events.EventHandler;
18
import combatant.client.events.impl.GameTickEvent;
19
import combatant.client.events.impl.LightmapModifyEvent;
20
import combatant.client.features.module.Module;
21
import combatant.client.features.module.ModuleCategory;
22
import combatant.client.features.module.ModuleInfo;
23
import combatant.client.features.module.Notifier;
24
import combatant.client.util.entity.FreecamEntity;
25
26
import java.util.Map;
27
28
//todo Description
29
@ModuleInfo(id = "freecam", displayName = "Freecam", aliases = {"camera", "spectator"}, category = ModuleCategory.VISUALS)
30
public class Freecam extends Module {
31
32
    private static final String SETTING_TOGGLES = "toggles";
33
    private static final String SETTING_HORIZONTAL_SPEED = "horizontal_speed";
34
    private static final String SETTING_VERTICAL_SPEED = "vertical_speed";
35
    private static final String SETTING_TOGGLE_INPUT = "toggle_input";
36
    private final BooleanMapValue toggles = group(
37
            "freecamToggles",
38
            SETTING_TOGGLES,
39
            Map.of(
40
                    "Freeze player", true,
41
                    "Allow interact", false,
42
                    "Render hand", false,
43
                    "Disable on damage", true,
44
                    "Use FullBright", false
45
            )
46
    );
47
    private final NumberValue<Double> horizontalSpeed =
48
            num("horizontalSpeed", SETTING_HORIZONTAL_SPEED, 0.8, 0.1, 5.0);
49
    private final NumberValue<Double> verticalSpeed =
50
            num("verticalSpeed", SETTING_VERTICAL_SPEED, 0.8, 0.1, 5.0);
51
    public CameraType prevPerspective;
52
    public FreecamEntity camEntity;
53
54
    public float camYaw;
55
    public float camPitch;
56
57
    public Vec3 camPos = Vec3.ZERO;
58
    public Vec3 camPosPrev = Vec3.ZERO;
59
    private boolean cameraInput = true;
60
61
    {
62
        setDefaultBind("F4");
63
        action(SETTING_TOGGLE_INPUT, "H", BindMode.PRESS).hudToggle(() -> !cameraInput);
64
    }
65
66
    public boolean isCameraInput() {
67
        return cameraInput;
68
    }
69
70
71
    @Override
72
    public void onEnable() {
73
        Minecraft mc = Minecraft.getInstance();
74
        if (mc.player == null || mc.level == null) {
75
            toggle();
76
            return;
77
        }
78
79
        prevPerspective = mc.options.getCameraType();
80
        mc.options.setCameraType(CameraType.FIRST_PERSON);
81
82
        camYaw = mc.player.getYRot();
83
        camPitch = mc.player.getXRot();
84
85
        camPos = new Vec3(mc.player.getX(), mc.player.getEyeY(), mc.player.getZ());
86
        camPosPrev = camPos;
87
88
        camEntity = new FreecamEntity(mc.level);
89
        syncCameraEntity(camPos, camPos);
90
        mc.setCameraEntity(camEntity);
91
    }
92
93
    @Override
94
    public void onDisable() {
95
        Minecraft mc = Minecraft.getInstance();
96
        if (prevPerspective != null) {
97
            mc.options.setCameraType(prevPerspective);
98
        }
99
        if (mc.player != null && mc.getCameraEntity() == camEntity) {
100
            mc.setCameraEntity(mc.player);
101
        }
102
        camEntity = null;
103
    }
104
105
    @EventHandler
106
    private void onGameTick(GameTickEvent event) {
107
        if (isActionPressedOnce(SETTING_TOGGLE_INPUT)) {
108
            cameraInput = !cameraInput;
109
            notifyInputMode(cameraInput);
110
        }
111
        tickCameraMovement();
112
    }
113
114
    private void notifyInputMode(boolean cameraInput) {
115
        String msg = cameraInput
116
                ? "Freecam input: Camera"
117
                : "Freecam input: Player";
118
119
        Notifier.info(msg);
120
    }
121
122
    public boolean freezePlayer() {
123
        return isEnabled() && toggles.get("Freeze player");
124
    }
125
126
    public boolean allowInteract() {
127
        return isEnabled() && toggles.get("Allow interact");
128
    }
129
130
    public boolean renderHand() {
131
        return toggles.get("Render hand");
132
    }
133
134
    public boolean disableOnDamage() {
135
        return toggles.get("Disable on damage");
136
    }
137
138
    public boolean useFullBright() {
139
        return isEnabled() && toggles.get("Use FullBright");
140
    }
141
142
    @EventHandler
143
    private void onLightmapState(LightmapModifyEvent event) {
144
        if (useFullBright()) {
145
            event.raiseMinimumLight(1.0f);
146
        }
147
    }
148
149
    private void tickCameraMovement() {
150
        if (camEntity == null) return;
151
152
        Minecraft mc = Minecraft.getInstance();
153
        if (mc == null || mc.options == null) return;
154
155
        camPosPrev = camPos;
156
        if (!cameraInput) {
157
            syncCameraEntity(camPos, camPosPrev);
158
            return;
159
        }
160
161
        var o = mc.options;
162
163
        double forward = 0;
164
        double strafe = 0;
165
        double vertical = 0;
166
167
        if (o.keyUp.isDown()) forward += 1;
168
        if (o.keyDown.isDown()) forward -= 1;
169
170
        if (o.keyLeft.isDown()) strafe += 1;
171
        if (o.keyRight.isDown()) strafe -= 1;
172
173
        if (o.keyJump.isDown()) vertical += 1;
174
        if (o.keyShift.isDown()) vertical -= 1;
175
176
        if (forward == 0 && strafe == 0 && vertical == 0) {
177
            syncCameraEntity(camPos, camPosPrev);
178
            return;
179
        }
180
181
        double yawRad = Math.toRadians(camYaw);
182
183
        Vec3 forwardVec = new Vec3(
184
                -Math.sin(yawRad),
185
                0,
186
                Math.cos(yawRad)
187
        );
188
189
        Vec3 rightVec = new Vec3(
190
                Math.cos(yawRad),
191
                0,
192
                Math.sin(yawRad)
193
        );
194
195
        Vec3 move = Vec3.ZERO
196
                .add(forwardVec.scale(forward))
197
                .add(rightVec.scale(strafe));
198
199
        if (move.lengthSqr() != 0) {
200
            double speed = hSpeed();
201
            if (o.keySprint.isDown()) speed *= 2.0;
202
            move = move.normalize().scale(speed);
203
        }
204
205
        move = move.add(0, vertical * vSpeed(), 0);
206
207
        camPos = camPos.add(move);
208
        syncCameraEntity(camPos, camPosPrev);
209
    }
210
211
    public Vec3 getCameraPos(float tickDelta) {
212
        float t = Mth.clamp(tickDelta, 0.0f, 1.0f);
213
        return new Vec3(
214
                Mth.lerp(t, camPosPrev.x, camPos.x),
215
                Mth.lerp(t, camPosPrev.y, camPos.y),
216
                Mth.lerp(t, camPosPrev.z, camPos.z)
217
        );
218
    }
219
220
    public void syncCameraEntity(Vec3 current, Vec3 previous) {
221
        if (camEntity == null) return;
222
223
        camEntity.xo = previous.x;
224
        camEntity.yo = previous.y;
225
        camEntity.zo = previous.z;
226
        camEntity.xOld = previous.x;
227
        camEntity.yOld = previous.y;
228
        camEntity.zOld = previous.z;
229
        camEntity.absSnapTo(current.x, current.y, current.z);
230
        camEntity.setYRot(camYaw);
231
        camEntity.setXRot(camPitch);
232
        camEntity.setDeltaMovement(Vec3.ZERO);
233
    }
234
235
    public double hSpeed() {
236
        return horizontalSpeed.get();
237
    }
238
239
    public double vSpeed() {
240
        return verticalSpeed.get();
241
    }
242
243
}
244
NicotineRendersrc/client/java/nicotine/mod/mods/render/FreeCam.javaJava · 107 lines · 3.1 KB
SettingsSpeed
FreeCam.javaJava · Minecraft 26.3 · 107 lines · 3.1 KB · complete file, verbatimOriginal ↗
1
package nicotine.mod.mods.render;
2
3
import com.mojang.blaze3d.platform.InputConstants;
4
import net.minecraft.client.renderer.entity.state.AvatarRenderState;
5
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
6
import net.minecraft.network.protocol.game.ServerboundPlayerAbilitiesPacket;
7
import net.minecraft.world.phys.Vec3;
8
import nicotine.events.*;
9
import nicotine.mod.Mod;
10
import nicotine.mod.ModCategory;
11
import nicotine.mod.option.SliderOption;
12
import nicotine.util.EventBus;
13
14
import static nicotine.util.Common.mc;
15
16
public class FreeCam extends Mod {
17
18
    private Vec3 realPos;
19
    private float realPitch;
20
    private float realYaw;
21
    private AvatarRenderState avatarRenderState;
22
23
    private final SliderOption speed = new SliderOption(
24
            "Speed",
25
            0.5f,
26
            0.05f,
27
            1.0f,
28
            true
29
    );
30
31
    public FreeCam() {
32
        super(ModCategory.Render, "FreeCam");
33
34
        this.keybind.keyCode = InputConstants.KEY_M;
35
        this.addOptions(speed);
36
    }
37
38
    @Override
39
    public void toggle() {
40
        if (mc.player == null) {
41
            this.enabled = false;
42
            return;
43
        }
44
45
        mc.player.getAbilities().flying = !this.enabled;
46
        mc.smartCull = this.enabled;
47
        mc.gameRenderer.setRenderBlockOutline(this.enabled);
48
49
        if (!this.enabled) {
50
            realPos = mc.player.position();
51
            realPitch = mc.player.getXRot();
52
            realYaw = mc.player.getYRot();
53
54
            avatarRenderState = (AvatarRenderState) mc.getEntityRenderDispatcher().getRenderer(mc.player).createRenderState(mc.player, 0);
55
        } else {
56
            mc.player.setDeltaMovement(Vec3.ZERO);
57
            mc.player.snapTo(realPos, realYaw, realPitch);
58
        }
59
60
        this.enabled = !this.enabled;
61
    }
62
63
    @Override
64
    protected void init() {
65
        EventBus.register(PacketOutEvent.class, event -> {
66
            if (!this.enabled)
67
                return true;
68
69
            if (event.packet instanceof ServerboundMovePlayerPacket)
70
               return false;
71
            else if (event.packet instanceof ServerboundPlayerAbilitiesPacket)
72
               return false;
73
74
            return true;
75
        });
76
77
        EventBus.register(ClientLevelTickEvent.class, event -> {
78
            if (!this.enabled)
79
                return true;
80
81
            mc.player.getAbilities().setFlyingSpeed(speed.value);
82
83
            return true;
84
        });
85
86
        EventBus.register(GetCollisionShapeEvent.class, event -> {
87
            if (!this.enabled)
88
                return true;
89
90
            return false;
91
        });
92
93
        EventBus.register(RenderBeforeEvent.class, event -> {
94
            if (!this.enabled)
95
                return true;
96
97
            Vec3 view = event.camera.position();
98
            event.matrixStack.pushPose();
99
            event.matrixStack.translate(-view.x, -view.y, -view.z);
100
            mc.getEntityRenderDispatcher().submit(avatarRenderState, mc.gameRenderer.gameRenderState().levelRenderState.cameraRenderState, realPos.x, realPos.y, realPos.z, event.matrixStack, event.submitNodeStorage);
101
            event.matrixStack.popPose();
102
103
            return true;
104
        });
105
    }
106
}
107
KiwiClientRENDERsrc/main/java/com/tangykiwi/kiwiclient/module/render/Freecam.javaJava · 141 lines · 4.2 KB

Detaches your camera

SettingsSpeed
Freecam.javaJava · Minecraft 26.2 · 141 lines · 4.2 KB · complete file, verbatimOriginal ↗
1
package com.tangykiwi.kiwiclient.module.render;
2
3
import static com.tangykiwi.kiwiclient.KiwiClient.mc;
4
5
import com.google.common.eventbus.AllowConcurrentEvents;
6
import com.google.common.eventbus.Subscribe;
7
import com.tangykiwi.kiwiclient.event.ChunkOcclusionEvent;
8
import com.tangykiwi.kiwiclient.event.LevelRenderEvent;
9
import com.tangykiwi.kiwiclient.event.TickEvent;
10
import com.tangykiwi.kiwiclient.mixin.CameraAccessor;
11
import com.tangykiwi.kiwiclient.module.Module;
12
import com.tangykiwi.kiwiclient.module.Category;
13
import com.tangykiwi.kiwiclient.module.setting.SliderSetting;
14
15
import net.minecraft.client.Camera;
16
import net.minecraft.client.player.ClientInput;
17
import net.minecraft.client.player.KeyboardInput;
18
import net.minecraft.client.player.LocalPlayer;
19
import net.minecraft.util.Mth;
20
import net.minecraft.world.phys.Vec3;
21
22
public class Freecam extends Module {
23
24
    private ClientInput savedInput;
25
	private Vec3 prevPos;
26
	private Vec3 pos;
27
28
    public Freecam() {
29
        super("Freecam", "Detaches your camera", Category.RENDER,
30
            new SliderSetting("Speed", "Camera movement speed", 0.1, 10, 2, 1));
31
    }
32
33
    @Override
34
    public void onEnable() {
35
        Camera camera = mc.gameRenderer.mainCamera();
36
        CameraAccessor iCamera = (CameraAccessor) camera;
37
        LocalPlayer player = mc.player;
38
39
        Vec3 startPos;
40
        if (player != null) {
41
            startPos = player.position().add(0, player.getEyeHeight(), 0);
42
            savedInput = player.input;
43
            player.input = new ClientInput();
44
        } else {
45
            startPos = camera.position();
46
        }
47
48
        prevPos = startPos;
49
        pos = startPos;
50
        iCamera.setCameraPos(startPos);
51
52
        mc.levelRenderer.invalidateCompiledGeometry(mc.level, mc.options, camera, mc.getBlockColors());
53
54
        super.onEnable();
55
    }
56
57
    @Override
58
    public void onDisable() {
59
        LocalPlayer player = mc.player;
60
		if (player != null && savedInput != null) {
61
			player.input = savedInput;
62
		}
63
64
		savedInput = null;
65
66
        mc.levelRenderer.invalidateCompiledGeometry(mc.level, mc.options, mc.gameRenderer.mainCamera(), mc.getBlockColors());
67
68
        super.onDisable();
69
    }
70
71
    @Subscribe
72
    @AllowConcurrentEvents
73
    public void onLevelRender(LevelRenderEvent event) {
74
        if (mc.player == null || mc.level == null) return;
75
76
        Camera camera = mc.gameRenderer.mainCamera();
77
        CameraAccessor iCamera = (CameraAccessor) camera;
78
79
        float tickDelta = event.getPartialTicks();
80
81
        Vec3 interpolatedPos = new Vec3(Mth.lerp(tickDelta, prevPos.x, pos.x),
82
            Mth.lerp(tickDelta, prevPos.y, pos.y),
83
            Mth.lerp(tickDelta, prevPos.z, pos.z));
84
        iCamera.setCameraPos(interpolatedPos);
85
    }
86
87
    @Subscribe
88
    @AllowConcurrentEvents
89
    public void onPreTick(TickEvent.Pre event) {
90
        LocalPlayer player = mc.player;
91
        if (player == null) return;
92
93
        if (player.input instanceof KeyboardInput) {
94
            savedInput = player.input;
95
            player.input = new ClientInput();
96
        }
97
    }
98
99
    @Subscribe
100
    @AllowConcurrentEvents
101
    public void onPostTick(TickEvent.Post event) {
102
        if (mc.player == null) return;
103
104
        Camera camera = mc.gameRenderer.mainCamera();
105
        Vec3 cameraPos = camera.position();
106
        prevPos = cameraPos;
107
108
        Vec3 forward = Vec3.directionFromRotation(0, camera.yRot());
109
        Vec3 right = Vec3.directionFromRotation(0, camera.yRot() + 90);
110
111
        Vec3 velocity = new Vec3(0, 0, 0);
112
113
        double flySpeed = ((SliderSetting) getSetting("Speed")).getValue();
114
115
        if (mc.options.keyUp.isDown()) {
116
			velocity = velocity.add(forward.scale(flySpeed));
117
		} else if (mc.options.keyDown.isDown()) {
118
			velocity = velocity.subtract(forward.scale(flySpeed));
119
		}
120
121
		if (mc.options.keyRight.isDown()) {
122
			velocity = velocity.add(right.scale(flySpeed));
123
		} else if (mc.options.keyLeft.isDown()) {
124
			velocity = velocity.subtract(right.scale(flySpeed));
125
		}
126
127
		if (mc.options.keyJump.isDown()) {
128
			velocity = velocity.add(0, flySpeed, 0);
129
		} else if (mc.options.keyShift.isDown())
130
			velocity = velocity.add(0, -flySpeed, 0);
131
132
		pos = cameraPos.add(velocity);
133
    }
134
135
    @Subscribe
136
    @AllowConcurrentEvents
137
    public void onChunkOcclusion(ChunkOcclusionEvent e) {
138
        e.cancel();
139
    }
140
}
141
LiquidBounce (Kotlin)RENDERsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/render/ModuleFreeCam.ktKotlin · 326 lines · 11.5 KB

Allows you to move the camera out of your body.

SettingsSpeedLookAtCancelOnKeyMidClickCameraTeleportKeepSneaking
ModuleFreeCam.ktKotlin · Minecraft 26.2 · 326 lines · 11.5 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
@file:Suppress("detekt:TooManyFunctions")
20
21
package net.ccbluex.liquidbounce.features.module.modules.render
22
23
import com.mojang.blaze3d.platform.InputConstants
24
import net.ccbluex.fastutil.enumSetOf
25
import net.ccbluex.liquidbounce.config.types.group.ToggleableValueGroup
26
import net.ccbluex.liquidbounce.config.types.list.Tagged
27
import net.ccbluex.liquidbounce.event.Event
28
import net.ccbluex.liquidbounce.event.EventManager
29
import net.ccbluex.liquidbounce.event.events.GameTickEvent
30
import net.ccbluex.liquidbounce.event.events.HealthUpdateEvent
31
import net.ccbluex.liquidbounce.event.events.MouseButtonEvent
32
import net.ccbluex.liquidbounce.event.events.MovementInputEvent
33
import net.ccbluex.liquidbounce.event.events.PacketEvent
34
import net.ccbluex.liquidbounce.event.events.PerspectiveEvent
35
import net.ccbluex.liquidbounce.event.events.PlayerMoveEvent
36
import net.ccbluex.liquidbounce.event.events.PlayerTickEvent
37
import net.ccbluex.liquidbounce.event.events.RotationUpdateEvent
38
import net.ccbluex.liquidbounce.event.events.WorldChangeEvent
39
import net.ccbluex.liquidbounce.event.handler
40
import net.ccbluex.liquidbounce.event.newEventHook
41
import net.ccbluex.liquidbounce.features.module.ClientModule
42
import net.ccbluex.liquidbounce.features.module.ModuleCategories
43
import net.ccbluex.liquidbounce.utils.aiming.RotationManager
44
import net.ccbluex.liquidbounce.utils.aiming.RotationsValueGroup
45
import net.ccbluex.liquidbounce.utils.aiming.data.Rotation
46
import net.ccbluex.liquidbounce.utils.entity.getMovementDirectionOfInput
47
import net.ccbluex.liquidbounce.utils.entity.rotation
48
import net.ccbluex.liquidbounce.utils.entity.withStrafe
49
import net.ccbluex.liquidbounce.utils.input.isPressed
50
import net.ccbluex.liquidbounce.utils.kotlin.EventPriorityConvention.FIRST_PRIORITY
51
import net.ccbluex.liquidbounce.utils.kotlin.EventPriorityConvention.OBJECTION_AGAINST_EVERYTHING
52
import net.ccbluex.liquidbounce.utils.kotlin.Priority
53
import net.ccbluex.liquidbounce.utils.math.plus
54
import net.ccbluex.liquidbounce.utils.movement.DirectionalInput
55
import net.ccbluex.liquidbounce.utils.navigation.NavigationBaseValueGroup
56
import net.ccbluex.liquidbounce.utils.raytracing.traceFromPoint
57
import net.minecraft.client.CameraType
58
import net.minecraft.core.Direction
59
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket
60
import net.minecraft.world.entity.Entity
61
import net.minecraft.world.phys.Vec3
62
import java.util.function.Predicate
63
import kotlin.math.abs
64
65
/**
66
 * FreeCam module
67
 *
68
 * Allows you to move out of your body.
69
 */
70
object ModuleFreeCam : ClientModule("FreeCam", ModuleCategories.RENDER, disableOnQuit = true) {
71
72
    private val speed by float("Speed", 1f, 0.1f..2f)
73
74
    /**
75
     * Allows to interact from the camera perspective. This is very useful to interact with blocks that
76
     * are behind the player or walls. Similar functionality to the GhostBlock module.
77
     */
78
    private object CameraInteract : ToggleableValueGroup(ModuleFreeCam, "AllowCameraInteract", true) {
79
        val lookAt by boolean("LookAt", true)
80
    }
81
82
    private class CancelTrigger<E : Event>(val eventType: Class<E>, val predicate: Predicate<E>)
83
    private inline fun <reified E : Event> cancelTrigger(predicate: Predicate<E>) =
84
        CancelTrigger(E::class.java, predicate)
85
86
    /**
87
     * This is useful for cancelling FreeCam on certain events.
88
     * For example, when the player takes damage.
89
     */
90
    private enum class CancelOn(
91
        override val tag: String,
92
        private val trigger: CancelTrigger<out Event>,
93
    ) : Tagged {
94
        DAMAGE("Damage", cancelTrigger<HealthUpdateEvent> { event ->
95
            event.health < event.previousHealth
96
        }),
97
        TELEPORT("Teleport", cancelTrigger<PacketEvent> { event ->
98
            // ClientboundPlayerPositionPacket not trigger PlayerMoveEvent
99
            event.packet is ClientboundPlayerPositionPacket
100
        }),
101
        MOVE("Move", cancelTrigger<PlayerMoveEvent> { event ->
102
            // Don't check movement.y because it's gravity / falling motion
103
            abs(event.movement.x) > 0 || abs(event.movement.z) > 0
104
        }),
105
        LIQUID("Liquid", cancelTrigger<PlayerTickEvent> {
106
            player.isInLiquid
107
        });
108
109
        init {
110
            EventManager.registerEventHook(
111
                this.trigger.eventType,
112
                @Suppress("UNCHECKED_CAST")
113
                newEventHook { event ->
114
                    if (this in cancelOn && (this.trigger.predicate as Predicate<Event>).test(event)) {
115
                        ModuleFreeCam.enabled = false
116
                    }
117
                }
118
            )
119
        }
120
    }
121
122
    private val cancelOn by multiEnumChoice("CancelOn", enumSetOf<CancelOn>())
123
124
    /**
125
     * Navigation configuration for the FreeCam module
126
     */
127
    private object Navigation : NavigationBaseValueGroup<Unit>(ModuleFreeCam, "Navigation", false) {
128
129
        private val controlKey by key("Key", InputConstants.KEY_LCONTROL)
130
131
        val shouldBeGoing
132
            get() = running && controlKey != InputConstants.UNKNOWN && controlKey.isPressed
133
134
        /**
135
         * Creates context for navigation
136
         */
137
        override fun createNavigationContext() {
138
            // Nothing to do
139
        }
140
141
        /**
142
         * Calculates the desired position to move towards
143
         *
144
         * @return Target position as [Vec3]
145
         */
146
        override fun calculateGoalPosition(context: Unit): Vec3? {
147
            return if (shouldBeGoing) {
148
                getCameraLookingAt()
149
            } else {
150
                null
151
            }
152
        }
153
154
    }
155
156
    private val midClickCameraTeleport by boolean("MidClickCameraTeleport", false)
157
158
    private val keepSneaking by boolean("KeepSneaking", false)
159
160
    private val rotations = tree(RotationsValueGroup(this))
161
162
    init {
163
        tree(CameraInteract)
164
        tree(Navigation)
165
    }
166
167
    object PositionState {
168
        var available: Boolean = false
169
            set(value) {
170
                if (value) {
171
                    pos = player.eyePosition
172
                    lastPos = pos
173
174
                    rot = player.rotation
175
                    lastRot = rot
176
                } else {
177
                    pos = Vec3.ZERO
178
                    lastPos = Vec3.ZERO
179
180
                    rot = Rotation.ZERO
181
                    lastRot = rot
182
                }
183
                field = value
184
            }
185
186
        @JvmField var pos: Vec3 = Vec3.ZERO
187
        @JvmField var lastPos: Vec3 = Vec3.ZERO
188
        @JvmField var rot: Rotation = Rotation.ZERO
189
        @JvmField var lastRot: Rotation = Rotation.ZERO
190
191
        fun set(target: Vec3) {
192
            lastPos = pos
193
            pos = target
194
        }
195
        fun set(target: Rotation) {
196
            lastRot = rot
197
            rot = target
198
        }
199
200
        fun update(velocity: Vec3) = set(pos + velocity)
201
        fun rotation(xDelta: Double, yDelta: Double) = set(
202
            Rotation(
203
                rot.yRot + xDelta.toFloat(),
204
                (rot.xRot + yDelta.toFloat()).coerceIn(-90f..90f)
205
            )
206
        )
207
        fun interpolate(partialTicks: Float) = lastPos.lerp(pos, partialTicks.toDouble())
208
        fun interpolateRot(partialTicks: Float) = lastRot.interpolateTo(rot, partialTicks)
209
    }
210
211
    override fun onEnabled() {
212
        PositionState.available = true
213
        super.onEnabled()
214
    }
215
216
    override fun onDisabled() {
217
        PositionState.available = false
218
        super.onDisabled()
219
    }
220
221
    @Suppress("unused")
222
    private val mouseHandler = handler<MouseButtonEvent> { event ->
223
        if (midClickCameraTeleport && event.isMiddleClick) {
224
            val target = getCameraLookingAt() ?: return@handler
225
226
            // interpolate to prevent tp into block
227
            PositionState.set(PositionState.pos.lerp(target, 0.9))
228
        }
229
    }
230
231
    @Suppress("unused")
232
    private val inputHandler = handler<MovementInputEvent>(priority = FIRST_PRIORITY) { event ->
233
        event.directionalInput = DirectionalInput.NONE
234
        event.jump = false
235
        event.sneak = false
236
    }
237
238
    @Suppress("unused")
239
    private val tickHandler = handler<GameTickEvent> { event ->
240
        val directionalInput = DirectionalInput(mc.options)
241
        var yAxisMovement = 0.0
242
243
        if (mc.options.keyJump.isDown) yAxisMovement += 1.0f
244
        if (mc.options.keyShift.isDown) yAxisMovement -= 1.0f
245
246
        val speed = this.speed.toDouble()
247
248
        ModuleDebug.debugParameter(this, "DirectionalInput", directionalInput)
249
        val velocity = Vec3.ZERO
250
            .withStrafe(
251
                speed = speed,
252
                input = directionalInput,
253
                yaw = getMovementDirectionOfInput(PositionState.rot.yaw, directionalInput)
254
            )
255
            .with(Direction.Axis.Y, yAxisMovement * speed)
256
        ModuleDebug.debugParameter(this, "Velocity", velocity)
257
        PositionState.update(velocity)
258
259
        ModuleDebug.debugParameter(this, "Position", PositionState.pos)
260
        ModuleDebug.debugParameter(this, "Rotation", PositionState.rot)
261
    }
262
263
    @Suppress("unused")
264
    private val forceSneakHandler = handler<MovementInputEvent>(priority = OBJECTION_AGAINST_EVERYTHING) { event ->
265
        if (keepSneaking) {
266
            event.sneak = true
267
        }
268
    }
269
270
    @Suppress("unused")
271
    private val perspectiveHandler = handler<PerspectiveEvent> { event ->
272
        event.perspective = CameraType.FIRST_PERSON
273
    }
274
275
    @Suppress("unused")
276
    private val rotationHandler = handler<RotationUpdateEvent> {
277
        val lookAt = if (Navigation.shouldBeGoing) {
278
            // Look at target position
279
            Navigation.getMovementRotation()
280
        } else if (CameraInteract.running && CameraInteract.lookAt) {
281
            // Aim at crosshair target
282
            val crosshairTarget = mc.hitResult ?: return@handler
283
            Rotation.lookingAt(crosshairTarget.location, player.eyePosition)
284
        } else {
285
            return@handler
286
        }
287
288
        RotationManager.setRotationTarget(rotations.toRotationTarget(lookAt),
289
            Priority.NOT_IMPORTANT, ModuleFreeCam)
290
    }
291
292
    @Suppress("unused")
293
    private val alwaysCancelOnHandler = handler<WorldChangeEvent> {
294
        // If not, will get stuck when world change
295
        enabled = false
296
    }
297
298
    fun applyCameraPosition(entity: Entity?, partialTicks: Float) {
299
        if (!running || entity != player || !PositionState.available) {
300
            return
301
        }
302
303
        val camera = mc.gameRenderer.mainCamera()
304
305
        return camera.setPosition(PositionState.interpolate(partialTicks))
306
    }
307
308
    @JvmStatic
309
    fun shouldCameraInteractActive() = running && CameraInteract.running
310
    fun shouldDisableCameraInteract() = running && !CameraInteract.running
311
312
    private fun getCameraLookingAt(): Vec3? {
313
        if (!PositionState.available) return null
314
315
        val cameraPosition = PositionState.interpolate(1f)
316
        val target = traceFromPoint(
317
            range = 200.0,
318
            start = cameraPosition,
319
            direction = PositionState.rot.directionVector
320
        )
321
322
        return target.location
323
    }
324
325
}
326