StrongholdFinder module

StrongholdFinder: Minecraft 26.3 cheat module, full source for every implementation (1 client: LiquidBounce (Kotlin)).

1 implementationWORLD

Clients with this module

Full module source: 1 implementation

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

LiquidBounce (Kotlin)WORLDsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/world/ModuleStrongholdFinder.ktKotlin · 489 lines · 17.5 KB

Tracks Eye of Ender throws and predicts the strongest stronghold chunk candidate.

SettingsSigmaHypothesisCountRequireSameStrongholdAcrossThrowsSampleDelayTicksMinEyeHorizontalSpeedMaxSampleAgeTicksMaxEyeSpawnDistanceShowTopCandidatesRenderRaysRenderBestChunkRenderTopChunksAnnouncePredictionResetOnWorldChange
ModuleStrongholdFinder.ktKotlin · Minecraft 26.2 · 489 lines · 17.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
package net.ccbluex.liquidbounce.features.module.modules.world
20
21
import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap
22
import net.ccbluex.liquidbounce.event.events.GameTickEvent
23
import net.ccbluex.liquidbounce.event.events.NotificationEvent
24
import net.ccbluex.liquidbounce.event.events.OverlayRenderEvent
25
import net.ccbluex.liquidbounce.event.events.PacketEvent
26
import net.ccbluex.liquidbounce.event.events.PlayerInteractedItemEvent
27
import net.ccbluex.liquidbounce.event.events.WorldChangeEvent
28
import net.ccbluex.liquidbounce.event.events.WorldRenderEvent
29
import net.ccbluex.liquidbounce.event.handler
30
import net.ccbluex.liquidbounce.features.module.ClientModule
31
import net.ccbluex.liquidbounce.features.module.ModuleCategories
32
import net.ccbluex.liquidbounce.render.WorldRenderEnvironment
33
import net.ccbluex.liquidbounce.render.drawLine
34
import net.ccbluex.liquidbounce.render.drawPlane
35
import net.ccbluex.liquidbounce.render.engine.type.Color4b
36
import net.ccbluex.liquidbounce.render.renderEnvironment
37
import net.ccbluex.liquidbounce.render.withPositionRelativeToCamera
38
import net.ccbluex.liquidbounce.utils.block.immutable
39
import net.ccbluex.liquidbounce.utils.client.notification
40
import net.ccbluex.liquidbounce.utils.math.yaw
41
import net.ccbluex.liquidbounce.utils.entity.interpolateCurrentPosition
42
import net.ccbluex.liquidbounce.utils.math.center
43
import net.ccbluex.liquidbounce.utils.math.horizontalDistanceToSqr
44
import net.ccbluex.liquidbounce.utils.math.toFixed
45
import net.ccbluex.liquidbounce.utils.math.toVec3d
46
import net.ccbluex.liquidbounce.utils.world.forEachSectionBlock
47
import net.ccbluex.liquidbounce.utils.world.stronghold.EyeMeasurement
48
import net.ccbluex.liquidbounce.utils.world.stronghold.PosteriorSnapshot
49
import net.ccbluex.liquidbounce.utils.world.stronghold.StrongholdBayesianEstimator
50
import net.ccbluex.liquidbounce.utils.world.stronghold.StrongholdHypothesis
51
import net.ccbluex.liquidbounce.utils.world.stronghold.StrongholdHypothesisGenerator
52
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket
53
import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket
54
import net.minecraft.network.protocol.game.ClientboundForgetLevelChunkPacket
55
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket
56
import net.minecraft.network.protocol.game.ClientboundSectionBlocksUpdatePacket
57
import net.minecraft.world.level.block.Blocks
58
import net.minecraft.resources.ResourceKey
59
import net.minecraft.core.BlockPos
60
import net.minecraft.world.entity.EntityTypes
61
import net.minecraft.world.entity.projectile.EyeOfEnder
62
import net.minecraft.world.item.Items
63
import net.minecraft.world.level.ChunkPos
64
import net.minecraft.world.level.Level
65
import net.minecraft.world.level.block.Block
66
import net.minecraft.world.phys.Vec3
67
import kotlin.math.hypot
68
69
private const val RAY_RENDER_LENGTH = 2048.0
70
71
/**
72
 * Stronghold finder module.
73
 *
74
 * Automatically tracks Eye of Ender throws and estimates the strongest stronghold chunk candidate
75
 * using a Bayesian posterior.
76
 *
77
 * [Article](https://github.com/Ninjabrain1/Ninjabrain-Bot/blob/main/triangulation.pdf)
78
 */
79
@Suppress("TooManyFunctions")
80
object ModuleStrongholdFinder : ClientModule(
81
    "StrongholdFinder",
82
    ModuleCategories.WORLD,
83
    aliases = listOf("Triangulation")
84
) {
85
86
    private val sigma by float("Sigma", 0.03f, 0.005f..0.20f, "°").onChanged {
87
        onEstimatorSettingsChanged()
88
    }
89
90
    private val hypothesisCount by int("HypothesisCount", 20000, 2000..100000).onChanged {
91
        cachedHypothesisCount = -1
92
        onEstimatorSettingsChanged()
93
    }
94
95
    private val requireSameStrongholdAcrossThrows by boolean("RequireSameStrongholdAcrossThrows", true).onChanged {
96
        onEstimatorSettingsChanged()
97
    }
98
99
    private val sampleDelayTicks by int("SampleDelayTicks", 2, 0..10)
100
    private val minEyeHorizontalSpeed by float("MinEyeHorizontalSpeed", 0.02f, 0.001f..0.2f)
101
    private val maxSampleAgeTicks by int("MaxSampleAgeTicks", 20, 5..100)
102
    private val maxEyeSpawnDistance by float("MaxEyeSpawnDistance", 8f, 1f..32f)
103
104
    private val showTopCandidates by int("ShowTopCandidates", 3, 1..10).onChanged {
105
        onEstimatorSettingsChanged()
106
    }
107
108
    private val renderRays by boolean("RenderRays", true)
109
    private val renderBestChunk by boolean("RenderBestChunk", true)
110
    private val renderTopChunks by boolean("RenderTopChunks", true)
111
    private val announcePrediction by boolean("AnnouncePrediction", true)
112
    private val resetOnWorldChange by boolean("ResetOnWorldChange", true)
113
114
    private val pendingThrows = ArrayDeque<PendingThrow>()
115
    private val trackedEyes = Int2ObjectLinkedOpenHashMap<TrackedEye>()
116
    private val measurements = mutableListOf<EyeMeasurement>()
117
    private var posterior: PosteriorSnapshot? = null
118
    private var lastAnnouncedCandidate: ChunkPos? = null
119
    private val detectedPortalBlocks = hashMapOf<BlockPos, PortalBlockType>()
120
121
    private var hypothesisCache: List<StrongholdHypothesis> = emptyList()
122
    private var cachedHypothesisCount = -1
123
124
    override fun onDisabled() {
125
        resetState()
126
    }
127
128
    @Suppress("unused")
129
    private val worldChangeHandler = handler<WorldChangeEvent> {
130
        if (resetOnWorldChange) {
131
            resetState()
132
        }
133
    }
134
135
    @Suppress("unused")
136
    private val interactedItemHandler = handler<PlayerInteractedItemEvent> { event ->
137
        if (!isOverworld()) {
138
            return@handler
139
        }
140
141
        if (!event.actionResult.consumesAction()) {
142
            return@handler
143
        }
144
145
        if (event.player.getItemInHand(event.hand).item != Items.ENDER_EYE) {
146
            return@handler
147
        }
148
149
        val nowTick = player.tickCount
150
        trimPendingThrows(nowTick)
151
        pendingThrows.addLast(
152
            PendingThrow(
153
                throwPosition = player.position(),
154
                tick = nowTick,
155
                dimension = world.dimension()
156
            )
157
        )
158
    }
159
160
    @Suppress("unused")
161
    private val packetHandler = handler<PacketEvent> { event ->
162
        if (!isOverworld()) {
163
            return@handler
164
        }
165
166
        when (val packet = event.packet) {
167
            is ClientboundAddEntityPacket -> mc.execute {
168
                handleEyeSpawnPacket(packet)
169
            }
170
171
            is ClientboundBlockUpdatePacket -> mc.execute {
172
                trackPortalBlock(packet.pos, packet.blockState.block)
173
            }
174
175
            is ClientboundSectionBlocksUpdatePacket -> mc.execute {
176
                packet.runUpdates { pos, state ->
177
                    trackPortalBlock(pos, state.block)
178
                }
179
            }
180
181
            is ClientboundLevelChunkWithLightPacket -> mc.execute {
182
                scanChunkForPortalBlocks(packet.x, packet.z)
183
            }
184
185
            is ClientboundForgetLevelChunkPacket -> mc.execute {
186
                removePortalBlocksInChunk(packet.pos)
187
            }
188
        }
189
    }
190
191
    @Suppress("unused")
192
    private val tickHandler = handler<GameTickEvent> {
193
        if (!isOverworld()) {
194
            return@handler
195
        }
196
197
        val nowTick = player.tickCount
198
        trimPendingThrows(nowTick)
199
200
        val trackedIterator = trackedEyes.int2ObjectEntrySet().iterator()
201
        while (trackedIterator.hasNext()) {
202
            val entry = trackedIterator.next()
203
            val entityId = entry.intKey
204
            val trackedEye = entry.value
205
206
            if (nowTick - trackedEye.spawnTick < sampleDelayTicks) {
207
                continue
208
            }
209
210
            val eye = world.getEntity(entityId) as? EyeOfEnder ?: run {
211
                trackedIterator.remove()
212
                continue
213
            }
214
215
            if (eye.deltaMovement.horizontalDistance().toFloat() < minEyeHorizontalSpeed) {
216
                continue
217
            }
218
219
            val throwPos = trackedEye.throwPosition
220
            val eyePos = eye.position()
221
            val yaw = eyePos.subtract(throwPos).yaw
222
223
            measurements += EyeMeasurement(
224
                throwPos,
225
                angleDeg = yaw,
226
                tick = nowTick
227
            )
228
229
            trackedIterator.remove()
230
231
            notification(
232
                name,
233
                message("sampleCaptured", measurements.size),
234
                NotificationEvent.Severity.INFO
235
            )
236
237
            recomputePosterior(announce = true)
238
        }
239
    }
240
241
    @Suppress("unused")
242
    private val render3DHandler = handler<WorldRenderEvent> { event ->
243
        if (!isOverworld()) {
244
            return@handler
245
        }
246
247
        event.renderEnvironment {
248
            if (detectedPortalBlocks.isNotEmpty()) {
249
                renderDetectedPortalBlocks(event)
250
                return@renderEnvironment
251
            }
252
253
            if (renderRays) {
254
                val color = Color4b.WHITE.alpha(170).argb
255
                withPositionRelativeToCamera {
256
                    for ((start, angleDeg) in measurements) {
257
                        val direction = Vec3.directionFromRotation(0f, angleDeg)
258
                        val end = start.add(direction.scale(RAY_RENDER_LENGTH))
259
260
                        drawLine(
261
                            start,
262
                            end,
263
                            color,
264
                        )
265
                    }
266
                }
267
            }
268
269
            val snapshot = posterior ?: return@renderEnvironment
270
            val drawY = player.interpolateCurrentPosition(event.partialTicks).y
271
            val candidates = snapshot.candidates.take(showTopCandidates)
272
            candidates.forEachIndexed { index, candidate ->
273
                val chunkPos = candidate.chunkPos
274
                val minX = chunkPos.minBlockX
275
                val minZ = chunkPos.minBlockZ
276
                val alpha = (45 + candidate.probability * 170).toInt().coerceIn(30, 200)
277
278
                val color = if (index == 0) {
279
                    Color4b(0, 170, 255, alpha)
280
                } else {
281
                    Color4b(255, 170, 0, alpha)
282
                }
283
284
                if ((index == 0 && renderBestChunk) || (index > 0 && renderTopChunks)) {
285
                    withPositionRelativeToCamera(minX.toDouble(), drawY, minZ.toDouble()) {
286
                        drawPlane(16f, 16f, color, color.darker())
287
                    }
288
                }
289
            }
290
        }
291
    }
292
293
    @Suppress("unused")
294
    private val renderOverlayHandler = handler<OverlayRenderEvent> { event ->
295
        if (!isOverworld()) {
296
            return@handler
297
        }
298
299
        if (detectedPortalBlocks.isNotEmpty()) {
300
            return@handler
301
        }
302
303
        val snapshot = posterior ?: return@handler
304
        val best = snapshot.candidates.firstOrNull() ?: return@handler
305
        val bestChunk = best.chunkPos
306
307
        val lines = arrayOf(
308
            this.name,
309
            "Samples: ${snapshot.sampleCount} | Sigma: ${sigma.toFixed(3)}°",
310
            "Best chunk: ${bestChunk.x}, ${bestChunk.z} (${(best.probability * 100.0).toFixed(1)}%)",
311
            "/tp ${bestChunk.middleBlockX} ~ ${bestChunk.middleBlockZ}",
312
        )
313
314
        val centerX = mc.window.guiScaledWidth / 2
315
        val startY = mc.window.guiScaledHeight / 2 + 10
316
317
        lines.forEachIndexed { index, line ->
318
            val lineX = centerX - mc.font.width(line) / 2
319
            event.context.text(
320
                mc.font,
321
                line,
322
                lineX,
323
                startY + index * (mc.font.lineHeight + 1),
324
                Color4b.WHITE.argb,
325
            )
326
        }
327
    }
328
329
    private fun getOrCreateHypotheses(): List<StrongholdHypothesis> {
330
        if (cachedHypothesisCount != hypothesisCount || hypothesisCache.isEmpty()) {
331
            hypothesisCache = StrongholdHypothesisGenerator.generate(hypothesisCount)
332
            cachedHypothesisCount = hypothesisCount
333
        }
334
        return hypothesisCache
335
    }
336
337
    private fun recomputePosterior(announce: Boolean) {
338
        posterior = StrongholdBayesianEstimator.estimate(
339
            measurements = measurements,
340
            hypotheses = getOrCreateHypotheses(),
341
            sigmaDeg = sigma.toDouble(),
342
            requireSameStrongholdAcrossThrows = requireSameStrongholdAcrossThrows,
343
            topCandidates = showTopCandidates,
344
        )
345
346
        val best = posterior?.candidates?.firstOrNull() ?: return
347
        val bestChunk = best.chunkPos
348
349
        if (announcePrediction && announce && bestChunk != lastAnnouncedCandidate) {
350
            notification(
351
                name,
352
                message("bestChunk", bestChunk.x, bestChunk.z, (best.probability * 100.0).toFixed(1)),
353
                NotificationEvent.Severity.INFO
354
            )
355
            lastAnnouncedCandidate = bestChunk
356
        }
357
    }
358
359
    private fun onEstimatorSettingsChanged() {
360
        if (measurements.isNotEmpty()) {
361
            recomputePosterior(announce = false)
362
        }
363
    }
364
365
    private fun trimPendingThrows(nowTick: Int) {
366
        while (pendingThrows.firstOrNull()?.let { nowTick - it.tick > maxSampleAgeTicks } == true) {
367
            pendingThrows.removeFirst()
368
        }
369
    }
370
371
    private fun handleEyeSpawnPacket(packet: ClientboundAddEntityPacket) {
372
        if (packet.type != EntityTypes.EYE_OF_ENDER) {
373
            return
374
        }
375
376
        val nowTick = player.tickCount
377
        trimPendingThrows(nowTick)
378
379
        val maxSpawnDistanceSqr = maxEyeSpawnDistance * maxEyeSpawnDistance
380
        val pending = pendingThrows
381
            .filter {
382
                it.dimension == world.dimension()
383
                    && nowTick - it.tick in 0..maxSampleAgeTicks
384
                    && it.throwPosition.horizontalDistanceToSqr(packet.x, packet.z) <= maxSpawnDistanceSqr
385
            }
386
            .minWithOrNull(
387
                compareBy<PendingThrow> { it.throwPosition.horizontalDistanceToSqr(packet.x, packet.z) }
388
                    .thenComparingInt { nowTick - it.tick }
389
            ) ?: return
390
391
        pendingThrows.remove(pending)
392
        val trackedEye = TrackedEye(
393
            entityId = packet.id,
394
            throwPosition = pending.throwPosition,
395
            spawnTick = nowTick
396
        )
397
        trackedEyes.put(packet.id, trackedEye)
398
    }
399
400
    private fun trackPortalBlock(pos: BlockPos, block: Block) {
401
        when (block) {
402
            Blocks.END_PORTAL -> detectedPortalBlocks[pos.immutable] = PortalBlockType.Portal
403
            Blocks.END_PORTAL_FRAME -> detectedPortalBlocks[pos.immutable] = PortalBlockType.Frame
404
            else -> detectedPortalBlocks.remove(pos)
405
        }
406
    }
407
408
    private fun scanChunkForPortalBlocks(chunkX: Int, chunkZ: Int) {
409
        val chunk = world.getChunk(chunkX, chunkZ)
410
        removePortalBlocksInChunk(chunk.pos)
411
412
        for (sectionIndex in 0..chunk.highestFilledSectionIndex) {
413
            chunk.forEachSectionBlock(sectionIndex) { pos, state ->
414
                when (state.block) {
415
                    Blocks.END_PORTAL -> detectedPortalBlocks[pos.immutable] = PortalBlockType.Portal
416
                    Blocks.END_PORTAL_FRAME -> detectedPortalBlocks[pos.immutable] = PortalBlockType.Frame
417
                }
418
            }
419
        }
420
    }
421
422
    private fun removePortalBlocksInChunk(chunkPos: ChunkPos) {
423
        detectedPortalBlocks.keys.removeIf(chunkPos::contains)
424
    }
425
426
    private fun WorldRenderEnvironment.renderDetectedPortalBlocks(event: WorldRenderEvent) {
427
        detectedPortalBlocks.forEach { (pos, type) ->
428
            withPositionRelativeToCamera(pos.toVec3d(yOffset = 0.01)) {
429
                drawPlane(1f, 1f, type.color, type.color.darker())
430
            }
431
        }
432
433
        val playerPos = player.interpolateCurrentPosition(event.partialTicks)
434
        val closestPortalPos = detectedPortalBlocks.keys.minByOrNull { pos ->
435
            pos.distToCenterSqr(playerPos)
436
        } ?: return
437
438
        val start = playerPos.add(0.0, 0.05, 0.0)
439
        val target = closestPortalPos.center
440
441
        val lineColor = Color4b(255, 80, 80, 220).argb
442
        withPositionRelativeToCamera {
443
            drawLine(start, target, lineColor)
444
445
            val deltaX = target.x - start.x
446
            val deltaZ = target.z - start.z
447
            val horizontalLength = hypot(deltaX, deltaZ)
448
            if (horizontalLength > 1e-6) {
449
                val markerEnd = Vec3(
450
                    start.x + deltaX / horizontalLength * 2.0,
451
                    start.y,
452
                    start.z + deltaZ / horizontalLength * 2.0
453
                )
454
                drawLine(start, markerEnd, lineColor)
455
            }
456
        }
457
    }
458
459
    private fun resetState() {
460
        pendingThrows.clear()
461
        trackedEyes.clear()
462
        measurements.clear()
463
        posterior = null
464
        lastAnnouncedCandidate = null
465
        detectedPortalBlocks.clear()
466
    }
467
468
    private fun isOverworld(): Boolean {
469
        return world.dimension() == Level.OVERWORLD
470
    }
471
472
    private data class PendingThrow(
473
        val throwPosition: Vec3,
474
        val tick: Int,
475
        val dimension: ResourceKey<Level>,
476
    )
477
478
    private data class TrackedEye(
479
        val entityId: Int,
480
        val throwPosition: Vec3,
481
        val spawnTick: Int,
482
    )
483
484
    private enum class PortalBlockType(val color: Color4b) {
485
        Portal(Color4b(0, 220, 255, 170)),
486
        Frame(Color4b(255, 215, 0, 170)),
487
    }
488
}
489