| 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 |
|
| 20 | @file:Suppress("TooManyFunctions")
|
| 21 |
|
| 22 | package net.ccbluex.liquidbounce.utils.entity
|
| 23 |
|
| 24 | import net.ccbluex.liquidbounce.common.ShapeFlag
|
| 25 | import net.ccbluex.liquidbounce.features.addon.AddonApi
|
| 26 | import net.ccbluex.liquidbounce.interfaces.ClientInputAddition
|
| 27 | import net.ccbluex.liquidbounce.interfaces.LocalPlayerAddition
|
| 28 | import net.ccbluex.liquidbounce.utils.aiming.data.Rotation
|
| 29 | import net.ccbluex.liquidbounce.utils.block.DIRECTIONS_EXCLUDING_UP
|
| 30 | import net.ccbluex.liquidbounce.utils.block.collisionShape
|
| 31 | import net.ccbluex.liquidbounce.utils.block.getBlock
|
| 32 | import net.ccbluex.liquidbounce.utils.block.isBlastResistant
|
| 33 | import net.ccbluex.liquidbounce.utils.block.raycast
|
| 34 | import net.ccbluex.liquidbounce.utils.client.isBlocksAttacksExisting
|
| 35 | import net.ccbluex.liquidbounce.utils.client.isOlderThanOrEqual1_8
|
| 36 | import net.ccbluex.liquidbounce.utils.client.mc
|
| 37 | import net.ccbluex.liquidbounce.utils.client.player
|
| 38 | import net.ccbluex.liquidbounce.utils.item.getEnchantment
|
| 39 | import net.ccbluex.liquidbounce.utils.item.isSword
|
| 40 | import net.ccbluex.liquidbounce.utils.math.allEmpty
|
| 41 | import net.ccbluex.liquidbounce.utils.math.anyNotEmpty
|
| 42 | import net.ccbluex.liquidbounce.utils.math.copy
|
| 43 | import net.ccbluex.liquidbounce.utils.math.fma
|
| 44 | import net.ccbluex.liquidbounce.utils.math.iterateBottomLayerBlockPos
|
| 45 | import net.ccbluex.liquidbounce.utils.math.minus
|
| 46 | import net.ccbluex.liquidbounce.utils.movement.DirectionalInput
|
| 47 | import net.ccbluex.liquidbounce.utils.movement.findEdgeCollision
|
| 48 | import net.minecraft.client.player.ClientInput
|
| 49 | import net.minecraft.client.player.LocalPlayer
|
| 50 | import net.minecraft.core.BlockPos
|
| 51 | import net.minecraft.core.Position
|
| 52 | import net.minecraft.core.Vec3i
|
| 53 | import net.minecraft.core.component.DataComponents
|
| 54 | import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket
|
| 55 | import net.minecraft.network.protocol.game.ServerboundMoveVehiclePacket
|
| 56 | import net.minecraft.server.level.ServerLevel
|
| 57 | import net.minecraft.tags.DamageTypeTags
|
| 58 | import net.minecraft.util.Mth
|
| 59 | import net.minecraft.world.Difficulty
|
| 60 | import net.minecraft.world.InteractionHand
|
| 61 | import net.minecraft.world.damagesource.DamageSource
|
| 62 | import net.minecraft.world.effect.MobEffects
|
| 63 | import net.minecraft.world.entity.Entity
|
| 64 | import net.minecraft.world.entity.EquipmentSlot
|
| 65 | import net.minecraft.world.entity.LivingEntity
|
| 66 | import net.minecraft.world.entity.ai.attributes.Attributes
|
| 67 | import net.minecraft.world.entity.boss.enderdragon.EndCrystal
|
| 68 | import net.minecraft.world.entity.item.PrimedTnt
|
| 69 | import net.minecraft.world.entity.monster.Creeper
|
| 70 | import net.minecraft.world.entity.player.Input
|
| 71 | import net.minecraft.world.entity.player.Player
|
| 72 | import net.minecraft.world.entity.projectile.arrow.AbstractArrow
|
| 73 | import net.minecraft.world.entity.vehicle.minecart.MinecartTNT
|
| 74 | import net.minecraft.world.item.ItemStack
|
| 75 | import net.minecraft.world.item.ItemUseAnimation
|
| 76 | import net.minecraft.world.item.ShieldItem
|
| 77 | import net.minecraft.world.item.component.UseEffects
|
| 78 | import net.minecraft.world.item.enchantment.Enchantments
|
| 79 | import net.minecraft.world.level.ClipContext
|
| 80 | import net.minecraft.world.level.Explosion
|
| 81 | import net.minecraft.world.level.GameType
|
| 82 | import net.minecraft.world.level.Level
|
| 83 | import net.minecraft.world.level.ServerExplosion
|
| 84 | import net.minecraft.world.level.block.Blocks
|
| 85 | import net.minecraft.world.level.block.MagmaBlock
|
| 86 | import net.minecraft.world.phys.AABB
|
| 87 | import net.minecraft.world.phys.HitResult
|
| 88 | import net.minecraft.world.phys.Vec2
|
| 89 | import net.minecraft.world.phys.Vec3
|
| 90 | import net.minecraft.world.phys.shapes.EntityCollisionContext
|
| 91 | import net.minecraft.world.scores.DisplaySlot
|
| 92 | import java.lang.Math.fma
|
| 93 | import kotlin.math.acos
|
| 94 | import kotlin.math.cos
|
| 95 | import kotlin.math.floor
|
| 96 | import kotlin.math.max
|
| 97 | import kotlin.math.sin
|
| 98 | import kotlin.math.sqrt
|
| 99 |
|
| 100 | // Copied from 1.21.4
|
| 101 | val Entity.isInsideWaterOrBubbleColumn: Boolean
|
| 102 | get() = this.isInWater || this.inBlockState.`is`(Blocks.BUBBLE_COLUMN)
|
| 103 |
|
| 104 | inline var ClientInput.movementForward: Float
|
| 105 | get() = moveVector.y
|
| 106 | set(value) {
|
| 107 | (this as ClientInputAddition).`liquid_bounce$setMovementInput`(moveVector.copy(y = value))
|
| 108 | }
|
| 109 |
|
| 110 | inline var ClientInput.movementSideways: Float
|
| 111 | get() = moveVector.x
|
| 112 | set(value) {
|
| 113 | (this as ClientInputAddition).`liquid_bounce$setMovementInput`(moveVector.copy(x = value))
|
| 114 | }
|
| 115 |
|
| 116 | val LivingEntity.handItems: Array<ItemStack>
|
| 117 | get() = arrayOf(mainHandItem, offhandItem)
|
| 118 |
|
| 119 | val LivingEntity.armorItems: Array<ItemStack>
|
| 120 | get() = arrayOf(
|
| 121 | getItemBySlot(EquipmentSlot.FEET),
|
| 122 | getItemBySlot(EquipmentSlot.LEGS),
|
| 123 | getItemBySlot(EquipmentSlot.CHEST),
|
| 124 | getItemBySlot(EquipmentSlot.HEAD),
|
| 125 | )
|
| 126 |
|
| 127 | // Copied from 1.21.4 END
|
| 128 |
|
| 129 | /**
|
| 130 | * Mirrors the blocking-angle and bypass checks from
|
| 131 | * `net.minecraft.world.entity.LivingEntity#applyItemBlocking`.
|
| 132 | *
|
| 133 | * @see net.minecraft.world.entity.LivingEntity#applyItemBlocking
|
| 134 | */
|
| 135 | @JvmOverloads
|
| 136 | fun LivingEntity.blockedByShield(source: DamageSource, damageAmount: Float = 1.0F): Boolean =
|
| 137 | getBlockedDamage(source, damageAmount) > 0.0F
|
| 138 |
|
| 139 | /**
|
| 140 | * Mirrors the client-computable part of `net.minecraft.world.entity.LivingEntity#applyItemBlocking`.
|
| 141 | *
|
| 142 | * @see net.minecraft.world.entity.LivingEntity#applyItemBlocking
|
| 143 | */
|
| 144 | private fun LivingEntity.getBlockedDamage(source: DamageSource, damageAmount: Float): Float {
|
| 145 | if (damageAmount <= 0.0F) {
|
| 146 | return 0.0F
|
| 147 | }
|
| 148 |
|
| 149 | val itemStack = itemBlockingWith ?: return 0.0F
|
| 150 | val blocksAttacks = itemStack[DataComponents.BLOCKS_ATTACKS] ?: return 0.0F
|
| 151 |
|
| 152 | if (blocksAttacks.bypassedBy().orElse(null)?.contains(source.typeHolder()) ?: false) {
|
| 153 | return 0.0F
|
| 154 | }
|
| 155 |
|
| 156 | val entity = source.directEntity
|
| 157 | if (entity is AbstractArrow && entity.pierceLevel > 0.toByte()) {
|
| 158 | return 0.0F
|
| 159 | }
|
| 160 |
|
| 161 | val horizontalAngle = source.sourcePosition?.let { sourcePosition ->
|
| 162 | val viewVector = calculateViewVector(0.0F, yHeadRot)
|
| 163 | val sourceDirection = sourcePosition
|
| 164 | .subtract(position())
|
| 165 | .copy(y = 0.0)
|
| 166 | .normalize()
|
| 167 | acos(sourceDirection.dot(viewVector))
|
| 168 | } ?: Math.PI
|
| 169 |
|
| 170 | return blocksAttacks.resolveBlockedDamage(source, damageAmount, horizontalAngle)
|
| 171 | }
|
| 172 |
|
| 173 | val Entity.netherPosition: Vec3
|
| 174 | get() = if (this.level().dimension() == Level.NETHER) {
|
| 175 | Vec3(x, y, z)
|
| 176 | } else {
|
| 177 | Vec3(x / 8.0, y, z / 8.0)
|
| 178 | }
|
| 179 |
|
| 180 | @AddonApi
|
| 181 | val LocalPlayer.moving
|
| 182 | get() = input.moveVector != Vec2.ZERO
|
| 183 |
|
| 184 | val ClientInput.untransformed: Input
|
| 185 | get() = (this as ClientInputAddition).`liquid_bounce$getUntransformed`()
|
| 186 |
|
| 187 | val ClientInput.initial: Input
|
| 188 | get() = (this as ClientInputAddition).`liquid_bounce$getInitial`()
|
| 189 |
|
| 190 | val Player.ping: Int
|
| 191 | get() = mc.connection?.getPlayerInfo(uuid)?.latency ?: 0
|
| 192 |
|
| 193 | val InteractionHand.opposite: InteractionHand
|
| 194 | get() = if (this === InteractionHand.MAIN_HAND) InteractionHand.OFF_HAND else InteractionHand.MAIN_HAND
|
| 195 |
|
| 196 | fun GameType.shortName(): String = when (this) {
|
| 197 | GameType.SURVIVAL -> "S"
|
| 198 | GameType.CREATIVE -> "C"
|
| 199 | GameType.ADVENTURE -> "A"
|
| 200 | GameType.SPECTATOR -> "S"
|
| 201 | }
|
| 202 |
|
| 203 | val LocalPlayer.airTicks: Int
|
| 204 | get() = (this as LocalPlayerAddition).`liquid_bounce$getAirTicks`()
|
| 205 |
|
| 206 | val LocalPlayer.onGroundTicks: Int
|
| 207 | get() = (this as LocalPlayerAddition).`liquid_bounce$getOnGroundTicks`()
|
| 208 |
|
| 209 | /**
|
| 210 | * Check if the attack speed is below 1 tick. If so, we have a cooldown.
|
| 211 | */
|
| 212 | val LocalPlayer.hasCooldown: Boolean
|
| 213 | get() = !isOlderThanOrEqual1_8 && this.getAttributeValue(Attributes.ATTACK_SPEED) < 20.0
|
| 214 |
|
| 215 | @JvmOverloads
|
| 216 | fun LocalPlayer.getMovementDirectionOfInput(input: DirectionalInput = DirectionalInput(this.input)): Float {
|
| 217 | return getMovementDirectionOfInput(this.yRot, input)
|
| 218 | }
|
| 219 |
|
| 220 | val LivingEntity.usingItemOrNull: ItemStack?
|
| 221 | get() = if (isUsingItem) useItem else null
|
| 222 |
|
| 223 | fun LivingEntity.isInHand(itemStack: ItemStack?, hand: InteractionHand) =
|
| 224 | this.getItemInHand(hand) === itemStack
|
| 225 |
|
| 226 | val LivingEntity.isBlockAction: Boolean
|
| 227 | get() = usingItemOrNull?.useAnimation === ItemUseAnimation.BLOCK
|
| 228 |
|
| 229 | val LivingEntity.isBlockingServerside: Boolean
|
| 230 | get() {
|
| 231 | if (this.isBlocking) return true
|
| 232 |
|
| 233 | // 1.8 server + 1.9~1.21.4 protocol
|
| 234 | if (this.isUsingItem && !isBlocksAttacksExisting) {
|
| 235 | val usingItem = this.useItem
|
| 236 |
|
| 237 | // I don't know why but if you join 1.8 server with 1.21.11 client + 1.20.x protocol [useItem] will be same as [mainHandItem]
|
| 238 | if (isInHand(usingItem, InteractionHand.MAIN_HAND) && usingItem.isSword ||
|
| 239 | isInHand(usingItem, InteractionHand.OFF_HAND) && usingItem.item is ShieldItem
|
| 240 | ) {
|
| 241 | return true
|
| 242 | }
|
| 243 | }
|
| 244 |
|
| 245 | return false
|
| 246 | }
|
| 247 |
|
| 248 | /**
|
| 249 | * @see LocalPlayer.isSlowDueToUsingItem
|
| 250 | */
|
| 251 | val Player.isSlowDueToUsingItem: Boolean
|
| 252 | get() = isUsingItem && !(useItem[DataComponents.USE_EFFECTS] ?: UseEffects.DEFAULT).canSprint
|
| 253 |
|
| 254 | fun Entity.lastRenderPos() = Vec3(this.xOld, this.yOld, this.zOld)
|
| 255 |
|
| 256 | fun Player.wouldBeCloseToFallOff(position: Vec3): Boolean {
|
| 257 | val hitbox =
|
| 258 | this.dimensions
|
| 259 | .makeBoundingBox(position)
|
| 260 | .inflate(-0.05, 0.0, -0.05)
|
| 261 | .move(0.0, this.fallDistance - this.maxUpStep(), 0.0)
|
| 262 |
|
| 263 | return this.level().noCollision(this, hitbox)
|
| 264 | }
|
| 265 |
|
| 266 | fun LocalPlayer.isCloseToEdge(
|
| 267 | directionalInput: DirectionalInput = DirectionalInput(this.input),
|
| 268 | distance: Double = 0.1,
|
| 269 | pos: Vec3 = this.position(),
|
| 270 | ): Boolean {
|
| 271 | val simulatedInput = SimulatedPlayer.SimulatedPlayerInput.fromClientPlayer(directionalInput)
|
| 272 | simulatedInput.set(
|
| 273 | jump = false,
|
| 274 | sneak = false
|
| 275 | )
|
| 276 |
|
| 277 | val simulatedPlayer = SimulatedPlayer.fromClientPlayer(
|
| 278 | simulatedInput
|
| 279 | )
|
| 280 |
|
| 281 | simulatedPlayer.pos = pos
|
| 282 | simulatedPlayer.tick()
|
| 283 |
|
| 284 | val nextVelocity = simulatedPlayer.deltaMovement
|
| 285 | val direction = if (nextVelocity.horizontalDistanceSqr() > 0.003 * 0.003) {
|
| 286 | nextVelocity.copy(y = 0.0).normalize()
|
| 287 | } else {
|
| 288 | val movementYaw = getMovementDirectionOfInput(directionalInput)
|
| 289 | Vec3.directionFromRotation(0.0F, movementYaw)
|
| 290 | }
|
| 291 |
|
| 292 | val from = pos.add(0.0, -0.1, 0.0)
|
| 293 | val to = from.fma(distance, direction)
|
| 294 |
|
| 295 | if (findEdgeCollision(from, to) != null) {
|
| 296 | return true
|
| 297 | }
|
| 298 |
|
| 299 | val playerPosInTwoTicks = simulatedPlayer.pos.add(nextVelocity.copy(y = 0.0))
|
| 300 |
|
| 301 | return wouldBeCloseToFallOff(pos) || wouldBeCloseToFallOff(playerPosInTwoTicks)
|
| 302 | }
|
| 303 |
|
| 304 | /**
|
| 305 | * Check if the player can step up by [height] blocks.
|
| 306 | *
|
| 307 | * TODO: Use Minecraft Step logic instead of this basic collision check.
|
| 308 | */
|
| 309 | fun LocalPlayer.canStep(height: Double = 1.0): Boolean {
|
| 310 | if (!horizontalCollision || isDescending || !onGround()) {
|
| 311 | // If we are not colliding with anything, we are not meant to step
|
| 312 | return false
|
| 313 | }
|
| 314 |
|
| 315 | val box = this.boundingBox
|
| 316 |
|
| 317 | val angle = Math.toRadians(this.yRot.toDouble())
|
| 318 | val xOffset = -sin(angle) * 0.1
|
| 319 | val zOffset = cos(angle) * 0.1
|
| 320 |
|
| 321 | val offsetBox = box.move(xOffset, 0.0, zOffset)
|
| 322 | val stepBox = offsetBox.move(0.0, height, 0.0)
|
| 323 |
|
| 324 | return this.level().getBlockCollisions(this, stepBox).allEmpty()
|
| 325 | && this.level().getBlockCollisions(this, offsetBox).anyNotEmpty()
|
| 326 | }
|
| 327 |
|
| 328 | fun getMovementDirectionOfInput(facingYaw: Float, input: DirectionalInput = DirectionalInput(player.input)): Float {
|
| 329 | var actualYaw = facingYaw
|
| 330 | val forwardMultiplier = when {
|
| 331 | input.backwards && !input.forwards -> {
|
| 332 | actualYaw += 180f
|
| 333 | -0.5f
|
| 334 | }
|
| 335 |
|
| 336 | input.forwards && !input.backwards -> 0.5f
|
| 337 | else -> 1f
|
| 338 | }
|
| 339 |
|
| 340 | if (input.left && !input.right) {
|
| 341 | actualYaw -= 90f * forwardMultiplier
|
| 342 | }
|
| 343 | if (input.right && !input.left) {
|
| 344 | actualYaw += 90f * forwardMultiplier
|
| 345 | }
|
| 346 |
|
| 347 | return actualYaw
|
| 348 | }
|
| 349 |
|
| 350 | @AddonApi
|
| 351 | inline val Entity.horizontalSpeed: Double
|
| 352 | get() = deltaMovement.horizontalDistance()
|
| 353 |
|
| 354 | @AddonApi
|
| 355 | @JvmOverloads
|
| 356 | fun Vec3.withStrafe(
|
| 357 | speed: Double = horizontalDistance(),
|
| 358 | strength: Double = 1.0,
|
| 359 | input: DirectionalInput? = DirectionalInput(player.input),
|
| 360 | yaw: Float = player.getMovementDirectionOfInput(input ?: DirectionalInput(player.input)),
|
| 361 | ): Vec3 {
|
| 362 | if (input?.isMoving == false) {
|
| 363 | return Vec3(0.0, y, 0.0)
|
| 364 | }
|
| 365 |
|
| 366 | val oneMinusStrength = 1.0 - strength
|
| 367 | val prevX = x * oneMinusStrength
|
| 368 | val prevZ = z * oneMinusStrength
|
| 369 | val usedSpeed = speed * strength
|
| 370 |
|
| 371 | val angle = Math.toRadians(yaw.toDouble())
|
| 372 | val newX = prevX - sin(angle) * usedSpeed
|
| 373 | val newZ = prevZ + cos(angle) * usedSpeed
|
| 374 |
|
| 375 | return Vec3(newX, y, newZ)
|
| 376 | }
|
| 377 |
|
| 378 | val Entity.lastPos: Vec3
|
| 379 | get() = Vec3(xo, yo, zo)
|
| 380 |
|
| 381 | val Entity.rotation: Rotation
|
| 382 | get() = Rotation(this.yRot, this.xRot, true)
|
| 383 |
|
| 384 | val LocalPlayer.lastRotation: Rotation
|
| 385 | get() = Rotation(this.yRotLast, this.xRotLast, true)
|
| 386 |
|
| 387 | /**
|
| 388 | * Check if the entity is inside the world border.
|
| 389 | *
|
| 390 | * Mirrors the server-side attack/interact border check.
|
| 391 | *
|
| 392 | * @see net.minecraft.server.network.ServerGamePacketListenerImpl.handleAttack
|
| 393 | */
|
| 394 | val Entity.isWithinWorldBorder: Boolean
|
| 395 | get() = level().worldBorder.isWithinBounds(blockPosition())
|
| 396 |
|
| 397 | val Entity.box: AABB
|
| 398 | get() = boundingBox.inflate(pickRadius.toDouble())
|
| 399 |
|
| 400 | private val cameraPos: Vec3 get() = mc.gameRenderer.mainCamera().position()
|
| 401 |
|
| 402 | fun Position.cameraDistanceSq() = cameraPos.distanceToSqr(x(), y(), z())
|
| 403 |
|
| 404 | fun Position.cameraDistance() = sqrt(cameraDistanceSq())
|
| 405 |
|
| 406 | fun Vec3i.cameraDistanceSq() = cameraPos.distanceToSqr(x.toDouble(), y.toDouble(), z.toDouble())
|
| 407 |
|
| 408 | /**
|
| 409 | * Allows to calculate the distance between the current entity and [entity] from the nearest corner of the bounding box
|
| 410 | */
|
| 411 | fun Entity.boxedDistanceTo(entity: Entity): Double {
|
| 412 | return sqrt(squaredBoxedDistanceTo(entity))
|
| 413 | }
|
| 414 |
|
| 415 | fun Entity.squaredBoxedDistanceTo(entity: Entity): Double {
|
| 416 | return this.squaredBoxedDistanceTo(entity.eyePosition)
|
| 417 | }
|
| 418 |
|
| 419 | fun Entity.squaredBoxedDistanceTo(otherPos: Vec3): Double {
|
| 420 | return box.distanceToSqr(otherPos)
|
| 421 | }
|
| 422 |
|
| 423 | fun Entity.squareBoxedDistanceTo(entity: Entity, offsetPos: Vec3): Double {
|
| 424 | return box.move(offsetPos - position()).distanceToSqr(entity.eyePosition)
|
| 425 | }
|
| 426 |
|
| 427 | fun Entity.interpolateCurrentPosition(tickDelta: Float): Vec3 {
|
| 428 | if (this.tickCount == 0) {
|
| 429 | return this.position()
|
| 430 | }
|
| 431 |
|
| 432 | val tickDelta = tickDelta.toDouble()
|
| 433 |
|
| 434 | return Vec3(
|
| 435 | fma(tickDelta, this.x - this.xOld, this.xOld),
|
| 436 | fma(tickDelta, this.y - this.yOld, this.yOld),
|
| 437 | fma(tickDelta, this.z - this.zOld, this.zOld),
|
| 438 | )
|
| 439 | }
|
| 440 |
|
| 441 | fun Entity.interpolateCurrentRotation(tickDelta: Float): Rotation {
|
| 442 | if (this.tickCount == 0) {
|
| 443 | return this.rotation
|
| 444 | }
|
| 445 |
|
| 446 | return Rotation(
|
| 447 | fma(tickDelta, this.yRot - this.yRotO, this.yRotO),
|
| 448 | fma(tickDelta, this.xRot - this.xRotO, this.xRotO),
|
| 449 | )
|
| 450 | }
|
| 451 |
|
| 452 | /**
|
| 453 | * Mirrors the vanilla damage-reduction pipeline after the base amount is known.
|
| 454 | *
|
| 455 | * By default, this returns the remaining damage before absorption so callers can compare it
|
| 456 | * against `health + absorptionAmount`. Pass [includeAbsorption] to mirror the final health
|
| 457 | * loss applied by vanilla.
|
| 458 | *
|
| 459 | * @see net.minecraft.world.entity.player.Player#hurtServer
|
| 460 | * @see net.minecraft.world.entity.LivingEntity#hurtServer
|
| 461 | * @see net.minecraft.world.entity.LivingEntity#getDamageAfterArmorAbsorb
|
| 462 | * @see net.minecraft.world.entity.LivingEntity#getDamageAfterMagicAbsorb
|
| 463 | * @see net.minecraft.world.entity.LivingEntity#actuallyHurt
|
| 464 | */
|
| 465 | @Suppress("detekt:all")
|
| 466 | @JvmOverloads
|
| 467 | fun LivingEntity.getEffectiveDamage(
|
| 468 | source: DamageSource,
|
| 469 | damage: Float,
|
| 470 | ignoreShield: Boolean = false,
|
| 471 | includeAbsorption: Boolean = false
|
| 472 | ): Float {
|
| 473 | val level = this.level()
|
| 474 | val serverLevel = level as? ServerLevel
|
| 475 |
|
| 476 | if ((serverLevel != null && this.isInvulnerableTo(serverLevel, source)) ||
|
| 477 | (serverLevel == null && this.isInvulnerableToBase(source))
|
| 478 | ) {
|
| 479 | return 0.0F
|
| 480 | }
|
| 481 |
|
| 482 | if (this.isDeadOrDying) {
|
| 483 | return 0.0F
|
| 484 | }
|
| 485 |
|
| 486 | var amount = damage
|
| 487 |
|
| 488 | if (this is Player) {
|
| 489 | if (this.abilities.invulnerable && !source.`is`(DamageTypeTags.BYPASSES_INVULNERABILITY))
|
| 490 | return 0.0F
|
| 491 |
|
| 492 | if (source.scalesWithDifficulty()) {
|
| 493 | when (level.difficulty) {
|
| 494 | Difficulty.PEACEFUL -> {
|
| 495 | amount = 0.0f
|
| 496 | }
|
| 497 |
|
| 498 | Difficulty.EASY -> {
|
| 499 | amount = (amount / 2.0f + 1.0f).coerceAtMost(amount)
|
| 500 | }
|
| 501 |
|
| 502 | Difficulty.HARD -> {
|
| 503 | amount = amount * 3.0f / 2.0f
|
| 504 | }
|
| 505 |
|
| 506 | else -> {}
|
| 507 | }
|
| 508 | }
|
| 509 | }
|
| 510 |
|
| 511 | if (amount == 0.0F)
|
| 512 | return 0.0F
|
| 513 |
|
| 514 | if (source.`is`(DamageTypeTags.IS_FIRE) && this.hasEffect(MobEffects.FIRE_RESISTANCE))
|
| 515 | return 0.0F
|
| 516 |
|
| 517 | if (!ignoreShield) {
|
| 518 | amount -= getBlockedDamage(source, amount)
|
| 519 | if (amount == 0.0F) {
|
| 520 | return 0.0F
|
| 521 | }
|
| 522 | }
|
| 523 |
|
| 524 | // Do we need to take the timeUntilRegen mechanic into account?
|
| 525 |
|
| 526 | amount = this.getDamageAfterArmorAbsorb(source, amount)
|
| 527 | amount = this.getDamageAfterMagicAbsorb(source, amount)
|
| 528 |
|
| 529 | if (includeAbsorption) {
|
| 530 | amount = (amount - this.absorptionAmount).coerceAtLeast(0.0F)
|
| 531 | }
|
| 532 |
|
| 533 | return amount
|
| 534 | }
|
| 535 |
|
| 536 | /**
|
| 537 | * Mirrors the vanilla blast-power setup of explosive entities.
|
| 538 | *
|
| 539 | * TNT minecarts use the current speed to reproduce vanilla's upper-bound radius because
|
| 540 | * `net.minecraft.world.entity.vehicle.minecart.MinecartTNT#explode` multiplies the speed
|
| 541 | * term by server-side randomness.
|
| 542 | *
|
| 543 | * @see net.minecraft.world.entity.boss.enderdragon.EndCrystal.hurtServer
|
| 544 | * @see net.minecraft.world.entity.item.PrimedTnt
|
| 545 | * @see net.minecraft.world.entity.vehicle.minecart.MinecartTNT.explode
|
| 546 | * @see net.minecraft.world.entity.monster.Creeper
|
| 547 | */
|
| 548 | fun LivingEntity.getExplosionDamageFromEntity(entity: Entity): Float {
|
| 549 | return when (entity) {
|
| 550 | is EndCrystal -> getDamageFromExplosion(
|
| 551 | pos = entity.position(),
|
| 552 | power = 6f,
|
| 553 | explosionRange = 12f,
|
| 554 | damageDistance = 144f,
|
| 555 | damageSource = Explosion.getDefaultDamageSource(this.level(), entity)
|
| 556 | )
|
| 557 |
|
| 558 | is PrimedTnt -> getDamageFromExplosion(
|
| 559 | pos = entity.position().add(0.0, 0.0625, 0.0),
|
| 560 | power = 4f,
|
| 561 | explosionRange = 8f,
|
| 562 | damageDistance = 64f,
|
| 563 | damageSource = Explosion.getDefaultDamageSource(this.level(), entity)
|
| 564 | )
|
| 565 |
|
| 566 | is MinecartTNT -> getDamageFromExplosion(
|
| 567 | pos = entity.position(),
|
| 568 | power = entity.getMaximumPotentialExplosionPower(),
|
| 569 | damageSource = Explosion.getDefaultDamageSource(this.level(), entity)
|
| 570 | )
|
| 571 |
|
| 572 | is Creeper -> {
|
| 573 | val f = if (entity.isPowered) 2f else 1f
|
| 574 | getDamageFromExplosion(
|
| 575 | pos = entity.position(),
|
| 576 | power = entity.explosionRadius * f,
|
| 577 | damageSource = Explosion.getDefaultDamageSource(this.level(), entity)
|
| 578 | )
|
| 579 | }
|
| 580 |
|
| 581 | else -> 0f
|
| 582 | }
|
| 583 | }
|
| 584 |
|
| 585 | /**
|
| 586 | * Mirrors the vanilla entity damage formula for explosions.
|
| 587 | *
|
| 588 | * Pass [damageSource] when the original explosion type is known so shield checks and
|
| 589 | * source-sensitive tags stay aligned with vanilla.
|
| 590 | *
|
| 591 | * @see net.minecraft.world.level.ExplosionDamageCalculator#getEntityDamageAmount
|
| 592 | * @see net.minecraft.world.level.ServerExplosion#getSeenPercent
|
| 593 | */
|
| 594 | @Suppress("LongParameterList")
|
| 595 | fun LivingEntity.getDamageFromExplosion(
|
| 596 | pos: Vec3,
|
| 597 | power: Float = 6f,
|
| 598 | explosionRange: Float = power * 2f, // allows setting precomputed values
|
| 599 | damageDistance: Float = explosionRange * explosionRange,
|
| 600 | exclude: Collection<BlockPos>? = null,
|
| 601 | include: BlockPos? = null,
|
| 602 | maxBlastResistance: Float? = null,
|
| 603 | entityBoundingBox: AABB? = null,
|
| 604 | damageSource: DamageSource? = null,
|
| 605 | ): Float {
|
| 606 | if (this.distanceToSqr(pos) > damageDistance) {
|
| 607 | return 0f
|
| 608 | }
|
| 609 |
|
| 610 | try {
|
| 611 | ShapeFlag.noShapeChange = true
|
| 612 |
|
| 613 | val useTweakedMethod = exclude != null ||
|
| 614 | maxBlastResistance != null ||
|
| 615 | include != null ||
|
| 616 | entityBoundingBox != null
|
| 617 |
|
| 618 | val exposure = if (useTweakedMethod) {
|
| 619 | getExposureToExplosion(pos, exclude, include, maxBlastResistance, entityBoundingBox)
|
| 620 | } else {
|
| 621 | ServerExplosion.getSeenPercent(pos, this)
|
| 622 | }
|
| 623 |
|
| 624 | val distanceDecay = 1.0 - (sqrt(this.distanceToSqr(pos)) / explosionRange.toDouble())
|
| 625 | val pre1 = exposure.toDouble() * distanceDecay
|
| 626 |
|
| 627 | val preprocessedDamage = (pre1 * pre1 + pre1) / 2.0 * 7.0 * explosionRange.toDouble() + 1.0
|
| 628 | if (preprocessedDamage == 0.0) {
|
| 629 | return 0f
|
| 630 | }
|
| 631 |
|
| 632 | val actualDamageSource = damageSource
|
| 633 | ?: DamageSource(this.level().damageSources().explosion(null).typeHolder(), pos)
|
| 634 | return getEffectiveDamage(actualDamageSource, preprocessedDamage.toFloat())
|
| 635 | } finally {
|
| 636 | ShapeFlag.noShapeChange = false
|
| 637 | }
|
| 638 | }
|
| 639 |
|
| 640 | /**
|
| 641 | * Basically [ServerExplosion.getSeenPercent] but this method allows us to exclude blocks using [exclude].
|
| 642 | *
|
| 643 | * @see net.minecraft.world.level.ServerExplosion.getSeenPercent
|
| 644 | */
|
| 645 | @Suppress("NestedBlockDepth")
|
| 646 | fun LivingEntity.getExposureToExplosion(
|
| 647 | source: Vec3,
|
| 648 | exclude: Collection<BlockPos>?,
|
| 649 | include: BlockPos?,
|
| 650 | maxBlastResistance: Float?,
|
| 651 | entityBoundingBox: AABB?
|
| 652 | ): Float {
|
| 653 | val entityBoundingBox1 = entityBoundingBox ?: boundingBox
|
| 654 | val shapeContext = EntityCollisionContext(
|
| 655 | isDescending,
|
| 656 | false,
|
| 657 | entityBoundingBox1.minY,
|
| 658 | mainHandItem,
|
| 659 | false,
|
| 660 | this
|
| 661 | )
|
| 662 |
|
| 663 | val stepX = 1.0 / ((entityBoundingBox1.maxX - entityBoundingBox1.minX) * 2.0 + 1.0)
|
| 664 | val stepY = 1.0 / ((entityBoundingBox1.maxY - entityBoundingBox1.minY) * 2.0 + 1.0)
|
| 665 | val stepZ = 1.0 / ((entityBoundingBox1.maxZ - entityBoundingBox1.minZ) * 2.0 + 1.0)
|
| 666 |
|
| 667 | val offsetX = (1.0 - floor(1.0 / stepX) * stepX) / 2.0
|
| 668 | val offsetZ = (1.0 - floor(1.0 / stepZ) * stepZ) / 2.0
|
| 669 |
|
| 670 | if (stepX < 0.0 || stepY < 0.0 || stepZ < 0.0) {
|
| 671 | return 0f
|
| 672 | }
|
| 673 |
|
| 674 | var hits = 0
|
| 675 | var totalRays = 0
|
| 676 |
|
| 677 | var currentXStep = 0.0
|
| 678 | while (currentXStep <= 1.0) {
|
| 679 | var currentYStep = 0.0
|
| 680 | while (currentYStep <= 1.0) {
|
| 681 | var currentZStep = 0.0
|
| 682 | while (currentZStep <= 1.0) {
|
| 683 | val sampleX = Mth.lerp(currentXStep, entityBoundingBox1.minX, entityBoundingBox1.maxX)
|
| 684 | val sampleY = Mth.lerp(currentYStep, entityBoundingBox1.minY, entityBoundingBox1.maxY)
|
| 685 | val sampleZ = Mth.lerp(currentZStep, entityBoundingBox1.minZ, entityBoundingBox1.maxZ)
|
| 686 |
|
| 687 | val samplePoint = Vec3(sampleX + offsetX, sampleY, sampleZ + offsetZ)
|
| 688 | val hitResult = this.level().raycast(
|
| 689 | ClipContext(
|
| 690 | samplePoint,
|
| 691 | source,
|
| 692 | ClipContext.Block.COLLIDER,
|
| 693 | ClipContext.Fluid.NONE,
|
| 694 | shapeContext
|
| 695 | ),
|
| 696 | exclude,
|
| 697 | include,
|
| 698 | maxBlastResistance
|
| 699 | )
|
| 700 |
|
| 701 | if (hitResult.type == HitResult.Type.MISS) {
|
| 702 | hits++
|
| 703 | }
|
| 704 |
|
| 705 | totalRays++
|
| 706 | currentZStep += stepZ
|
| 707 | }
|
| 708 | currentYStep += stepY
|
| 709 | }
|
| 710 | currentXStep += stepX
|
| 711 | }
|
| 712 |
|
| 713 | return hits.toFloat() / totalRays.toFloat()
|
| 714 | }
|
| 715 |
|
| 716 | /**
|
| 717 | * Uses the current horizontal speed to reproduce the vanilla TNT minecart blast upper bound.
|
| 718 | *
|
| 719 | * @see net.minecraft.world.entity.vehicle.minecart.MinecartTNT.explode
|
| 720 | */
|
| 721 | private fun MinecartTNT.getMaximumPotentialExplosionPower(): Float {
|
| 722 | val currentHorizontalSpeed = sqrt(this.deltaMovement.horizontalDistanceSqr()).coerceAtMost(5.0).toFloat()
|
| 723 | return 4f + currentHorizontalSpeed * 1.5f
|
| 724 | }
|
| 725 |
|
| 726 | /**
|
| 727 | * Sometimes the server does not publish the actual entity health with its metadata.
|
| 728 | * This function incorporates other sources to get the actual value.
|
| 729 | *
|
| 730 | * Currently, uses the following sources:
|
| 731 | * 1. Scoreboard
|
| 732 | */
|
| 733 | fun LivingEntity.getActualHealth(fromScoreboard: Boolean = true): Float {
|
| 734 | if (fromScoreboard) {
|
| 735 | val health = getHealthFromScoreboard()
|
| 736 |
|
| 737 | if (health != null) {
|
| 738 | return health
|
| 739 | }
|
| 740 | }
|
| 741 |
|
| 742 |
|
| 743 | return health
|
| 744 | }
|
| 745 |
|
| 746 | private val HEALTH_KEYWORDS = listOf("❤", "HP", "Health", "Здоровья", "Здоровье")
|
| 747 |
|
| 748 | fun LivingEntity.hasHealthScoreboard(): Boolean {
|
| 749 | if (this == player) return false
|
| 750 |
|
| 751 | val objective = this.level().scoreboard.getDisplayObjective(DisplaySlot.BELOW_NAME) ?: return false
|
| 752 | val displayName = objective.displayName.string
|
| 753 |
|
| 754 | return HEALTH_KEYWORDS.any { displayName.contains(it) }
|
| 755 | }
|
| 756 |
|
| 757 | private fun LivingEntity.getHealthFromScoreboard(): Float? {
|
| 758 | if (!this.hasHealthScoreboard()) return null
|
| 759 | val objective = this.level().scoreboard.getDisplayObjective(DisplaySlot.BELOW_NAME)
|
| 760 | val score = objective?.scoreboard?.getPlayerScoreInfo(this, objective) ?: return null
|
| 761 |
|
| 762 | return score.value().toFloat()
|
| 763 | }
|
| 764 |
|
| 765 | fun Entity.getBoundingBoxAt(pos: Vec3): AABB {
|
| 766 | return boundingBox.move(pos - this.position())
|
| 767 | }
|
| 768 |
|
| 769 | /**
|
| 770 | * Check if the entity collides with anything below his bounding box.
|
| 771 | */
|
| 772 | fun Entity.doesNotCollideBelow(until: Double = -64.0): Boolean {
|
| 773 | if (this.y < until || boundingBox.minY < until) {
|
| 774 | return true
|
| 775 | }
|
| 776 |
|
| 777 | val offsetBb = boundingBox.setMinY(until)
|
| 778 | return this.level().getBlockCollisions(this, offsetBb).allEmpty()
|
| 779 | }
|
| 780 |
|
| 781 | /**
|
| 782 | * Check if the entity box collides with any block in the world at the given [pos].
|
| 783 | */
|
| 784 | fun Entity.doesCollideAt(pos: Vec3 = this.position()): Boolean {
|
| 785 | return !this.level().getBlockCollisions(this, getBoundingBoxAt(pos)).allEmpty()
|
| 786 | }
|
| 787 |
|
| 788 | /**
|
| 789 | * Check if the entity is likely falling to the void based on the given position and bounding box.
|
| 790 | */
|
| 791 | fun Entity.wouldFallIntoVoid(pos: Vec3, voidLevel: Double = -64.0, safetyExpand: Double = 0.0): Boolean {
|
| 792 | val offsetBb = getBoundingBoxAt(pos)
|
| 793 |
|
| 794 | if (pos.y < voidLevel || offsetBb.minY < voidLevel) {
|
| 795 | return true
|
| 796 | }
|
| 797 |
|
| 798 | // If there is no collision to void threshold, we don't want to teleport down.
|
| 799 | val boundingBox = offsetBb
|
| 800 | // Set the minimum Y to the void threshold to check for collisions below the player
|
| 801 | .setMinY(voidLevel)
|
| 802 | // Expand the bounding box to check if there might be blocks to safely land on
|
| 803 | .inflate(safetyExpand, 0.0, safetyExpand)
|
| 804 | return this.level().getBlockCollisions(this, boundingBox).allEmpty()
|
| 805 | }
|
| 806 |
|
| 807 |
|
| 808 | fun LocalPlayer.warp(pos: Vec3? = null, onGround: Boolean = false) {
|
| 809 | val vehicle = this.vehicle
|
| 810 |
|
| 811 | if (vehicle != null) {
|
| 812 | pos?.let(vehicle::setPos)
|
| 813 | connection.send(ServerboundMoveVehiclePacket.fromEntity(vehicle))
|
| 814 | return
|
| 815 | }
|
| 816 |
|
| 817 | if (pos != null) {
|
| 818 | connection.send(ServerboundMovePlayerPacket.Pos(pos.x, pos.y, pos.z, onGround, horizontalCollision))
|
| 819 | } else {
|
| 820 | connection.send(ServerboundMovePlayerPacket.StatusOnly(onGround, horizontalCollision))
|
| 821 | }
|
| 822 | }
|
| 823 |
|
| 824 | fun LocalPlayer.isInHole(feetBlockPos: BlockPos = getFeetBlockPos()): Boolean {
|
| 825 | return DIRECTIONS_EXCLUDING_UP.all {
|
| 826 | feetBlockPos.relative(it).isBlastResistant()
|
| 827 | }
|
| 828 | }
|
| 829 |
|
| 830 | fun LocalPlayer.isBurrowed(): Boolean {
|
| 831 | return getFeetBlockPos().isBlastResistant()
|
| 832 | }
|
| 833 |
|
| 834 | fun LocalPlayer.getFeetBlockPos(): BlockPos {
|
| 835 | val bb = boundingBox
|
| 836 | return BlockPos(
|
| 837 | Mth.floor(Mth.lerp(0.5, bb.minX, bb.maxX)),
|
| 838 | Mth.ceil(bb.minY),
|
| 839 | Mth.floor(Mth.lerp(0.5, bb.minZ, bb.maxZ))
|
| 840 | )
|
| 841 | }
|
| 842 |
|
| 843 | val LivingEntity.wouldBlockHit
|
| 844 | get() = !isOlderThanOrEqual1_8 &&
|
| 845 | this.blockedByShield(this.level().damageSources().playerAttack(player))
|
| 846 |
|
| 847 | /**
|
| 848 | * @see <a href="https://minecraft.fandom.com/wiki/Magma_Block#Damage">Magma Block — Damage</a>
|
| 849 | */
|
| 850 | val LocalPlayer.immuneToMagmaBlocks
|
| 851 | get() = this.hasEffect(MobEffects.FIRE_RESISTANCE)
|
| 852 | || (this.getEffect(MobEffects.RESISTANCE)?.amplifier ?: -1) >= 4
|
| 853 | || this.isCreative
|
| 854 | || this.isSpectator
|
| 855 | || this.getItemBySlot(EquipmentSlot.FEET).getEnchantment(Enchantments.FROST_WALKER) > 0
|
| 856 |
|
| 857 | /**
|
| 858 | * @receiver the specific bounding box of a player, mob or even another block.
|
| 859 | */
|
| 860 | fun AABB.isOnMagmaBlock(): Boolean {
|
| 861 | // Blocks that are the height of a trapdoor or lower
|
| 862 | // (such as snow layers, carpets, repeaters, or comparators)
|
| 863 | // do not prevent a magma block from damaging mobs and players above it.
|
| 864 | // Therefore, we expand the box downward by 0.2 blocks.
|
| 865 | val expandedBox = inflate(0.0, 0.1, 0.0)
|
| 866 | .move(0.0, -0.1, 0.0)
|
| 867 |
|
| 868 | return expandedBox.iterateBottomLayerBlockPos().any {
|
| 869 | it.getBlock() is MagmaBlock &&
|
| 870 | expandedBox.intersects(it.collisionShape.bounds().move(it))
|
| 871 | }
|
| 872 | }
|
| 873 |
|
| 874 | val Entity?.cameraDistance: Float
|
| 875 | get() {
|
| 876 | var scale: Float
|
| 877 | var distance: Float
|
| 878 | if (this is LivingEntity) {
|
| 879 | scale = this.scale
|
| 880 | distance = this.getAttributeValue(Attributes.CAMERA_DISTANCE).toFloat()
|
| 881 | } else {
|
| 882 | scale = 1f
|
| 883 | distance = 4f
|
| 884 | }
|
| 885 |
|
| 886 | (this?.vehicle as? LivingEntity)
|
| 887 | ?.takeIf { this.isPassenger }
|
| 888 | ?.also { mount ->
|
| 889 | scale = max(scale, mount.scale)
|
| 890 | distance = max(distance, mount.getAttributeValue(Attributes.CAMERA_DISTANCE).toFloat())
|
| 891 | }
|
| 892 |
|
| 893 | return scale * distance
|
| 894 | }
|
| 895 |
|