LivingEntity .java

net.minecraft.world.entity.LivingEntity (class, 4134 lines): extends Entity, implements Attackable, WaypointTransmitter. members: xxa, yya, zza, dead.

net.minecraft.world.entityclass4,134 linescommonextends Entity137.4 KB

Implements

API Surface (200)

EntityEquipment createEquipment()
Brain<? extends LivingEntity> getBrain()
Brain<? extends LivingEntity> makeBrain(final Brain.Packed packedBrain)
void kill(final ServerLevel level)
void defineSynchedData(final SynchedEntityData.Builder entityData)
AttributeSupplier.Builder createLivingAttributes()
void checkFallDamage(final double ya, final boolean onGround, final BlockState onState, final BlockPos pos)
boolean canBreatheUnderwater()
float getSwimAmount(final float a)
boolean hasLandedInLiquid()
void baseTick()
boolean shouldTakeDrowningDamage()
float getBlockSpeedFactor()
float getLuck()
void removeFrost()
void tryAddFrost()
void onChangedBlock(final ServerLevel level, final BlockPos pos)
boolean isBaby()
float getAgeScale()
float getScale()
float sanitizeScale(final float scale)
boolean isAffectedByFluids()
void tickDeath()
boolean shouldDropExperience()
boolean shouldDropLoot(final ServerLevel level)
int decreaseAirSupply(final int currentSupply)
int increaseAirSupply(final int currentSupply)
int getExperienceReward(final ServerLevel level, final @Nullable Entity killer)
int getBaseExperienceReward(final ServerLevel level)
boolean isAlwaysExperienceDropper()
LivingEntity getLastAttacker()
int getLastHurtByMobTimestamp()
void setLastHurtByPlayer(final Player player, final int timeToRemember)
void setLastHurtByPlayer(final UUID player, final int timeToRemember)
void setLastHurtByMob(final @Nullable LivingEntity hurtBy)
int getLastHurtMobTimestamp()
void setLastHurtMob(final Entity target)
int getNoActionTime()
void setNoActionTime(final int noActionTime)
boolean shouldDiscardFriction()
void setDiscardFriction(final boolean discardFriction)
boolean doesEmitEquipEvent(final EquipmentSlot slot)
void onEquipItem(final EquipmentSlot slot, final ItemStack oldStack, final ItemStack stack)
Holder<SoundEvent> getEquipSound(final EquipmentSlot slot, final ItemStack stack, final Equippable equippable)
void remove(final Entity.RemovalReason reason)
void onRemoval(final Entity.RemovalReason reason)
void triggerOnDeathMobEffects(final ServerLevel level, final Entity.RemovalReason reason)
void addAdditionalSaveData(final ValueOutput output)
void readAdditionalSaveData(final ValueInput input)
void updateDataBeforeSync()
void tickEffects()
void updateInvisibilityStatus()
double getVisibilityPercent(final ServerLevel serverLevel, final @Nullable Entity targetingEntity)
boolean canAttack(final LivingEntity target)
boolean canBeSeenAsEnemy()
boolean canBeSeenByAnyone()
boolean areAllEffectsAmbient(final Collection<MobEffectInstance> effects)
void removeEffectParticles()
boolean removeAllEffects()
Collection<MobEffectInstance> getActiveEffects()
Map<Holder<MobEffect>, MobEffectInstance> getActiveEffectsMap()
boolean hasEffect(final Holder<MobEffect> effect)
float getEffectBlendFactor(final Holder<MobEffect> effect, final float partialTicks)
boolean addEffect(final MobEffectInstance newEffect)
boolean addEffect(final MobEffectInstance newEffect, final @Nullable Entity source)
boolean canBeAffected(final MobEffectInstance newEffect)
void forceAddEffect(final MobEffectInstance newEffect, final @Nullable Entity source)
boolean isInvertedHealAndHarm()
boolean removeEffect(final Holder<MobEffect> effect)
void onEffectAdded(final MobEffectInstance effect, final @Nullable Entity source)
void sendEffectToPassengers(final MobEffectInstance effect)
void onEffectUpdated(final MobEffectInstance effect, final boolean doRefreshAttributes, final @Nullable Entity source)
void onEffectsRemoved(final Collection<MobEffectInstance> effects)
void onAttributeUpdated(final Holder<Attribute> attribute)
void heal(final float heal)
float getHealth()
void setHealth(final float health)
boolean isDeadOrDying()
boolean wasHurtRecently()
boolean hurtServer(final ServerLevel level, final DamageSource source, float damage)
void dealDefaultKnockback(final DamageSource source, final float damage, final boolean blocked)
float applyItemBlocking(final ServerLevel level, final DamageSource source, final float damage)
void resolveMobResponsibleForDamage(final DamageSource source)
void blockUsingItem(final ServerLevel level, final LivingEntity attacker, final DamageSource source, final float damage, final boolean fullyBlocked)
void blockedByItem(final LivingEntity defender, final DamageSource source, final float damage, final boolean fullyBlocked)
void playHurtSound(final DamageSource source)
void makeSound(final @Nullable SoundEvent sound)
void die(final DamageSource source)
void handleKillingBlow()
void createWitherRose(final @Nullable LivingEntity killer)
void dropAllDeathLoot(final ServerLevel level, final DamageSource source)
void dropEquipment(final ServerLevel level)
void dropExperience(final ServerLevel level, final @Nullable Entity killer)
void dropCustomDeathLoot(final ServerLevel level, final DamageSource source, final boolean killedByPlayer)
long getLootTableSeed()
float getKnockback(final Entity target, final DamageSource damageSource)
void dropFromLootTable(final ServerLevel level, final DamageSource source, final boolean playerKilled)
void dropFromLootTable(final ServerLevel level, final DamageSource source, final boolean playerKilled, final ResourceKey<LootTable> lootTable)
void dropFromLootTable(final ServerLevel level, final DamageSource source, final boolean playerKilled, final ResourceKey<LootTable> lootTable, final Consumer<ItemStack> itemStackConsumer)
boolean dropFromEntityInteractLootTable(final ServerLevel level, final ResourceKey<LootTable> key, final @Nullable Entity interactingEntity, final ItemInstance tool, final BiConsumer<ServerLevel, ItemStack> consumer)
boolean dropFromGiftLootTable(final ServerLevel level, final ResourceKey<LootTable> key, final BiConsumer<ServerLevel, ItemStack> consumer)
void dropFromShearingLootTable(final ServerLevel level, final ResourceKey<LootTable> key, final ItemInstance tool, final BiConsumer<ServerLevel, ItemStack> consumer)
boolean dropFromLootTable(final ServerLevel level, final ResourceKey<LootTable> key, final Function<LootParams.Builder, LootParams> paramsBuilder, final BiConsumer<ServerLevel, ItemStack> consumer)
void knockback(double power, double xd, double zd, final DamageSource source, final float damage, final boolean comesFromEffect)
void knockback(final double power, final double xd, final double zd, final DamageSource source, final float damage)
void indicateDamage(final double xd, final double zd)
void skipDropExperience()
boolean wasExperienceConsumed()
float getHurtDir()
AABB getHitbox()
Map<Enchantment, Set<EnchantmentLocationBasedEffect>> activeLocationDependentEnchantments(final EquipmentSlot slot)
void postPiercingAttack()
LivingEntity.Fallsounds getFallSounds()
Optional<BlockPos> getLastClimbablePos()
boolean onClimbable()
boolean isAlive()
boolean isLookingAtMe(final LivingEntity target, final double coneSize, final boolean adjustForDistance, final boolean seeThroughTransparentBlocks, final double... gazeHeights)
int getMaxFallDistance()
int getComfortableFallDistance(final float allowedDamage)
boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource)

…and 80 more (see full source).

Fields & Constants (142)

LOGGER
TAG_ACTIVE_EFFECTS
TAG_ATTRIBUTES
TAG_SLEEPING_POS
TAG_EQUIPMENT
TAG_BRAIN
TAG_FALL_FLYING
TAG_HURT_TIME
TAG_DEATH_TIME
TAG_HEALTH
SPEED_MODIFIER_POWDER_SNOW_ID
SPRINTING_MODIFIER_ID
SPEED_MODIFIER_SPRINTING
EQUIPMENT_SLOT_OFFSET
ARMOR_SLOT_OFFSET
BODY_ARMOR_OFFSET
SADDLE_OFFSET
PLAYER_HURT_EXPERIENCE_TIME
DAMAGE_SOURCE_TIMEOUT
MIN_MOVEMENT_DISTANCE
DEFAULT_BASE_GRAVITY
DEATH_DURATION
INPUT_FRICTION
TICKS_PER_ELYTRA_FREE_FALL_EVENT
FREE_FALL_EVENTS_PER_ELYTRA_BREAK
BASE_JUMP_POWER
DEFAULT_KNOCKBACK
DAMAGE_COOLDOWN_DURATION
HURT_DURATION_TICKS
CLIMBING_VERTICAL_SPEED
SWIM_AMOUNT_PER_TICK
MAX_LINE_OF_SIGHT_TEST_RANGE
LIVING_ENTITY_FLAG_IS_USING
LIVING_ENTITY_FLAG_OFF_HAND
LIVING_ENTITY_FLAG_SPIN_ATTACK
DATA_LIVING_ENTITY_FLAGS
DATA_HEALTH_ID
DATA_EFFECT_PARTICLES
DATA_EFFECT_AMBIENCE_ID
DATA_ARROW_COUNT_ID
DATA_STINGER_COUNT_ID
SLEEPING_POS_ID
PARTICLE_FREQUENCY_WHEN_INVISIBLE
SLEEPING_DIMENSIONS
EXTRA_RENDER_CULLING_SIZE_WITH_BIG_HAT
DEFAULT_BABY_SCALE
SWIMMING_VERTICAL_SPEED
CURRENT_IMPULSE_CONTEXT_RESET_GRACE_TIME_TICKS
DEFAULT_CURRENT_IMPULSE_CONTEXT_RESET_GRACE_TIME
BASE_HORIZONTAL_AIR_DRAG
BASE_VERTICAL_AIR_DRAG
WATER_DRAG
SPRINTING_WATER_DRAG
LAVA_DRAG
LAVA_SHALLOW_VERTICAL_DRAG
DOLPHINS_GRACE_WATER_DRAG
FLYING_AIR_DRAG
FLYING_VERTICAL_AIR_DRAG
FLYING_LAVA_DRAG
FLYING_WATER_DRAG
ELYTRA_HORIZONTAL_AIR_DRAG
ELYTRA_VERTICAL_AIR_DRAG
BASE_SWIM_SPEED
PLAYER_NOT_WEARING_DISGUISE_ITEM
currentImpulseContextResetGraceTime
attributes
combatTracker
activeEffects
lastEquipmentItems
swingState
discardFriction
removeArrowTime
removeStingerTime
hurtTime
hurtDuration
deathTime
damageCooldownTime
attackStrengthTicker
itemSwapTicker
walkAnimation
yBodyRot
yBodyRotO
yHeadRot
yHeadRotO
elytraAnimationState
lastHurtByPlayer
lastHurtByPlayerMemoryTime
dead

…and 54 more (see full source).

String literals (28)

"active_effects"
"attributes"
"sleeping_pos"
"equipment"
"Brain"
"FallFlying"
"HurtTime"
"DeathTime"
"Health"
"powder_snow"
"sprinting"
"livingEntityBaseTick"
"AbsorptionAmount"
"current_impulse_context_reset_grace_time"
"current_explosion_impact_pos"
"last_hurt_by_player"
"last_hurt_by_player_memory_time"
"last_hurt_by_mob"
"ticks_since_last_hurt_by_mob"
"locator_bar_icon"
"Invalid hand "
"headTurn"
"rangeChecks"
"newAi"

Code Graph: Dependencies (80)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

LivingEntity.java4134 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.entity;
2
3
import com.google.common.annotations.VisibleForTesting;
4
import com.google.common.base.Objects;
5
import com.google.common.collect.ImmutableList;
6
import com.google.common.collect.Lists;
7
import com.google.common.collect.Maps;
8
import com.mojang.datafixers.util.Pair;
9
import com.mojang.logging.LogUtils;
10
import it.unimi.dsi.fastutil.doubles.DoubleDoubleImmutablePair;
11
import it.unimi.dsi.fastutil.objects.Object2LongMap;
12
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;
13
import it.unimi.dsi.fastutil.objects.Reference2ObjectArrayMap;
14
import it.unimi.dsi.fastutil.objects.Reference2ObjectMap;
15
import java.util.Collection;
16
import java.util.ConcurrentModificationException;
17
import java.util.EnumMap;
18
import java.util.Iterator;
19
import java.util.List;
20
import java.util.Map;
21
import java.util.Optional;
22
import java.util.OptionalDouble;
23
import java.util.Set;
24
import java.util.UUID;
25
import java.util.Map.Entry;
26
import java.util.function.BiConsumer;
27
import java.util.function.Consumer;
28
import java.util.function.Function;
29
import java.util.function.Predicate;
30
import net.minecraft.advancements.triggers.CriteriaTriggers;
31
import net.minecraft.commands.arguments.EntityAnchorArgument;
32
import net.minecraft.core.BlockPos;
33
import net.minecraft.core.Direction;
34
import net.minecraft.core.Holder;
35
import net.minecraft.core.component.DataComponents;
36
import net.minecraft.core.particles.BlockParticleOption;
37
import net.minecraft.core.particles.ItemParticleOption;
38
import net.minecraft.core.particles.ParticleOptions;
39
import net.minecraft.core.particles.ParticleTypes;
40
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
41
import net.minecraft.network.protocol.game.ClientboundEntityEventPacket;
42
import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket;
43
import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket;
44
import net.minecraft.network.protocol.game.ClientboundSwingAnimationPacket;
45
import net.minecraft.network.protocol.game.ClientboundTakeItemEntityPacket;
46
import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket;
47
import net.minecraft.network.syncher.EntityDataAccessor;
48
import net.minecraft.network.syncher.EntityDataSerializers;
49
import net.minecraft.network.syncher.SynchedEntityData;
50
import net.minecraft.resources.Identifier;
51
import net.minecraft.resources.ResourceKey;
52
import net.minecraft.server.level.ServerChunkCache;
53
import net.minecraft.server.level.ServerLevel;
54
import net.minecraft.server.level.ServerPlayer;
55
import net.minecraft.server.waypoints.ServerWaypointManager;
56
import net.minecraft.sounds.SoundEvent;
57
import net.minecraft.sounds.SoundEvents;
58
import net.minecraft.sounds.SoundSource;
59
import net.minecraft.stats.Stats;
60
import net.minecraft.tags.BlockTags;
61
import net.minecraft.tags.DamageTypeTags;
62
import net.minecraft.tags.EntityTypeTags;
63
import net.minecraft.tags.FluidTags;
64
import net.minecraft.tags.ItemTags;
65
import net.minecraft.tags.TagKey;
66
import net.minecraft.util.BlockUtil;
67
import net.minecraft.util.Mth;
68
import net.minecraft.util.Prediction;
69
import net.minecraft.util.Util;
70
import net.minecraft.util.profiling.Profiler;
71
import net.minecraft.util.profiling.ProfilerFiller;
72
import net.minecraft.world.Difficulty;
73
import net.minecraft.world.InteractionHand;
74
import net.minecraft.world.damagesource.CombatRules;
75
import net.minecraft.world.damagesource.CombatTracker;
76
import net.minecraft.world.damagesource.DamageSource;
77
import net.minecraft.world.damagesource.DamageTypes;
78
import net.minecraft.world.effect.MobEffect;
79
import net.minecraft.world.effect.MobEffectInstance;
80
import net.minecraft.world.effect.MobEffectUtil;
81
import net.minecraft.world.effect.MobEffects;
82
import net.minecraft.world.entity.ai.Brain;
83
import net.minecraft.world.entity.ai.attributes.Attribute;
84
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
85
import net.minecraft.world.entity.ai.attributes.AttributeMap;
86
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
87
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
88
import net.minecraft.world.entity.ai.attributes.Attributes;
89
import net.minecraft.world.entity.ai.attributes.DefaultAttributes;
90
import net.minecraft.world.entity.animal.wolf.Wolf;
91
import net.minecraft.world.entity.boss.wither.WitherBoss;
92
import net.minecraft.world.entity.item.ItemEntity;
93
import net.minecraft.world.entity.player.Player;
94
import net.minecraft.world.entity.projectile.Projectile;
95
import net.minecraft.world.entity.projectile.arrow.AbstractArrow;
96
import net.minecraft.world.item.Item;
97
import net.minecraft.world.item.ItemInstance;
98
import net.minecraft.world.item.ItemStack;
99
import net.minecraft.world.item.ItemStackTemplate;
100
import net.minecraft.world.item.Items;
101
import net.minecraft.world.item.component.AttackRange;
102
import net.minecraft.world.item.component.BlocksAttacks;
103
import net.minecraft.world.item.component.DeathProtection;
104
import net.minecraft.world.item.component.KineticWeapon;
105
import net.minecraft.world.item.component.MobVisibility;
106
import net.minecraft.world.item.component.SwingAnimation;
107
import net.minecraft.world.item.component.Weapon;
108
import net.minecraft.world.item.enchantment.Enchantment;
109
import net.minecraft.world.item.enchantment.EnchantmentHelper;
110
import net.minecraft.world.item.enchantment.effects.EnchantmentLocationBasedEffect;
111
import net.minecraft.world.item.equipment.Equippable;
112
import net.minecraft.world.level.ClipContext;
113
import net.minecraft.world.level.Level;
114
import net.minecraft.world.level.block.AbstractBedBlock;
115
import net.minecraft.world.level.block.BedBlock;
116
import net.minecraft.world.level.block.Block;
117
import net.minecraft.world.level.block.Blocks;
118
import net.minecraft.world.level.block.HoneyBlock;
119
import net.minecraft.world.level.block.LadderBlock;
120
import net.minecraft.world.level.block.PowderSnowBlock;
121
import net.minecraft.world.level.block.SoundType;
122
import net.minecraft.world.level.block.TrapDoorBlock;
123
import net.minecraft.world.level.block.state.BlockState;
124
import net.minecraft.world.level.border.WorldBorder;
125
import net.minecraft.world.level.gameevent.GameEvent;
126
import net.minecraft.world.level.gamerules.GameRules;
127
import net.minecraft.world.level.material.Fluid;
128
import net.minecraft.world.level.material.FluidState;
129
import net.minecraft.world.level.storage.ValueInput;
130
import net.minecraft.world.level.storage.ValueOutput;
131
import net.minecraft.world.level.storage.loot.LootParams;
132
import net.minecraft.world.level.storage.loot.LootTable;
133
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
134
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
135
import net.minecraft.world.phys.AABB;
136
import net.minecraft.world.phys.HitResult;
137
import net.minecraft.world.phys.Vec3;
138
import net.minecraft.world.phys.shapes.Shapes;
139
import net.minecraft.world.phys.shapes.VoxelShape;
140
import net.minecraft.world.waypoints.Waypoint;
141
import net.minecraft.world.waypoints.WaypointTransmitter;
142
import org.jetbrains.annotations.Contract;
143
import org.jspecify.annotations.Nullable;
144
import org.slf4j.Logger;
145
146
/**
147
 * Access widened by fabric-transitive-access-wideners-v1 to accessible
148
 */
149
public abstract class LivingEntity extends Entity implements Attackable, WaypointTransmitter {
150
	private static final Logger LOGGER = LogUtils.getLogger();
151
	private static final String TAG_ACTIVE_EFFECTS = "active_effects";
152
	public static final String TAG_ATTRIBUTES = "attributes";
153
	public static final String TAG_SLEEPING_POS = "sleeping_pos";
154
	public static final String TAG_EQUIPMENT = "equipment";
155
	public static final String TAG_BRAIN = "Brain";
156
	public static final String TAG_FALL_FLYING = "FallFlying";
157
	public static final String TAG_HURT_TIME = "HurtTime";
158
	public static final String TAG_DEATH_TIME = "DeathTime";
159
	public static final String TAG_HEALTH = "Health";
160
	private static final Identifier SPEED_MODIFIER_POWDER_SNOW_ID = Identifier.withDefaultNamespace("powder_snow");
161
	private static final Identifier SPRINTING_MODIFIER_ID = Identifier.withDefaultNamespace("sprinting");
162
	private static final AttributeModifier SPEED_MODIFIER_SPRINTING = new AttributeModifier(
163
		SPRINTING_MODIFIER_ID, 0.3F, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL
164
	);
165
	public static final int EQUIPMENT_SLOT_OFFSET = 98;
166
	public static final int ARMOR_SLOT_OFFSET = 100;
167
	public static final int BODY_ARMOR_OFFSET = 105;
168
	public static final int SADDLE_OFFSET = 106;
169
	public static final int PLAYER_HURT_EXPERIENCE_TIME = 100;
170
	private static final int DAMAGE_SOURCE_TIMEOUT = 40;
171
	public static final double MIN_MOVEMENT_DISTANCE = 0.003;
172
	public static final double DEFAULT_BASE_GRAVITY = 0.08;
173
	public static final int DEATH_DURATION = 20;
174
	protected static final float INPUT_FRICTION = 0.98F;
175
	private static final int TICKS_PER_ELYTRA_FREE_FALL_EVENT = 10;
176
	private static final int FREE_FALL_EVENTS_PER_ELYTRA_BREAK = 2;
177
	public static final float BASE_JUMP_POWER = 0.42F;
178
	protected static final float DEFAULT_KNOCKBACK = 0.4F;
179
	protected static final int DAMAGE_COOLDOWN_DURATION = 20;
180
	protected static final int HURT_DURATION_TICKS = 10;
181
	private static final double CLIMBING_VERTICAL_SPEED = 0.2;
182
	private static final float SWIM_AMOUNT_PER_TICK = 0.09F;
183
	private static final double MAX_LINE_OF_SIGHT_TEST_RANGE = 128.0;
184
	protected static final int LIVING_ENTITY_FLAG_IS_USING = 1;
185
	protected static final int LIVING_ENTITY_FLAG_OFF_HAND = 2;
186
	protected static final int LIVING_ENTITY_FLAG_SPIN_ATTACK = 4;
187
	protected static final EntityDataAccessor<Byte> DATA_LIVING_ENTITY_FLAGS = SynchedEntityData.defineId(LivingEntity.class, EntityDataSerializers.BYTE);
188
	private static final EntityDataAccessor<Float> DATA_HEALTH_ID = SynchedEntityData.defineId(LivingEntity.class, EntityDataSerializers.FLOAT);
189
	private static final EntityDataAccessor<List<ParticleOptions>> DATA_EFFECT_PARTICLES = SynchedEntityData.defineId(
190
		LivingEntity.class, EntityDataSerializers.PARTICLES
191
	);
192
	private static final EntityDataAccessor<Boolean> DATA_EFFECT_AMBIENCE_ID = SynchedEntityData.defineId(LivingEntity.class, EntityDataSerializers.BOOLEAN);
193
	private static final EntityDataAccessor<Integer> DATA_ARROW_COUNT_ID = SynchedEntityData.defineId(LivingEntity.class, EntityDataSerializers.INT);
194
	private static final EntityDataAccessor<Integer> DATA_STINGER_COUNT_ID = SynchedEntityData.defineId(LivingEntity.class, EntityDataSerializers.INT);
195
	private static final EntityDataAccessor<Optional<BlockPos>> SLEEPING_POS_ID = SynchedEntityData.defineId(
196
		LivingEntity.class, EntityDataSerializers.OPTIONAL_BLOCK_POS
197
	);
198
	private static final int PARTICLE_FREQUENCY_WHEN_INVISIBLE = 15;
199
	protected static final EntityDimensions SLEEPING_DIMENSIONS = EntityDimensions.fixed(0.2F, 0.2F).withEyeHeight(0.2F);
200
	public static final float EXTRA_RENDER_CULLING_SIZE_WITH_BIG_HAT = 0.5F;
201
	public static final float DEFAULT_BABY_SCALE = 0.5F;
202
	protected static final float SWIMMING_VERTICAL_SPEED = 0.04F;
203
	private static final int CURRENT_IMPULSE_CONTEXT_RESET_GRACE_TIME_TICKS = 40;
204
	private static final int DEFAULT_CURRENT_IMPULSE_CONTEXT_RESET_GRACE_TIME = 0;
205
	public static final float BASE_HORIZONTAL_AIR_DRAG = 0.91F;
206
	public static final float BASE_VERTICAL_AIR_DRAG = 0.98F;
207
	public static final float WATER_DRAG = 0.8F;
208
	public static final float SPRINTING_WATER_DRAG = 0.9F;
209
	public static final float LAVA_DRAG = 0.5F;
210
	public static final float LAVA_SHALLOW_VERTICAL_DRAG = 0.8F;
211
	public static final float DOLPHINS_GRACE_WATER_DRAG = 0.96F;
212
	public static final float FLYING_AIR_DRAG = 0.91F;
213
	public static final float FLYING_VERTICAL_AIR_DRAG = 0.91F;
214
	public static final float FLYING_LAVA_DRAG = 0.5F;
215
	public static final float FLYING_WATER_DRAG = 0.8F;
216
	public static final float ELYTRA_HORIZONTAL_AIR_DRAG = 0.99F;
217
	public static final float ELYTRA_VERTICAL_AIR_DRAG = 0.98F;
218
	public static final float BASE_SWIM_SPEED = 0.02F;
219
	private int currentImpulseContextResetGraceTime = 0;
220
	public static final Predicate<LivingEntity> PLAYER_NOT_WEARING_DISGUISE_ITEM = livingEntity -> {
221
		if (livingEntity instanceof Player player) {
222
			ItemStack helmet = player.getItemBySlot(EquipmentSlot.HEAD);
223
			return !helmet.is(ItemTags.GAZE_DISGUISE_EQUIPMENT);
224
		} else {
225
			return true;
226
		}
227
	};
228
	private final AttributeMap attributes;
229
	private final CombatTracker combatTracker = new CombatTracker(this);
230
	private final Map<Holder<MobEffect>, MobEffectInstance> activeEffects = Maps.newHashMap();
231
	private final Map<EquipmentSlot, ItemStack> lastEquipmentItems = Util.makeEnumMap(EquipmentSlot.class, slot -> ItemStack.EMPTY);
232
	private final LivingEntity.SwingState swingState = new LivingEntity.SwingState();
233
	private boolean discardFriction = false;
234
	public int removeArrowTime;
235
	public int removeStingerTime;
236
	public int hurtTime;
237
	public int hurtDuration;
238
	public int deathTime;
239
	public int damageCooldownTime;
240
	protected int attackStrengthTicker;
241
	protected int itemSwapTicker;
242
	public final WalkAnimationState walkAnimation = new WalkAnimationState();
243
	public float yBodyRot;
244
	public float yBodyRotO;
245
	public float yHeadRot;
246
	public float yHeadRotO;
247
	public final ElytraAnimationState elytraAnimationState = new ElytraAnimationState(this);
248
	protected @Nullable EntityReference<Player> lastHurtByPlayer;
249
	protected int lastHurtByPlayerMemoryTime;
250
	protected boolean dead;
251
	protected int noActionTime;
252
	protected float lastHurt;
253
	protected boolean jumping;
254
	public float xxa;
255
	public float yya;
256
	public float zza;
257
	protected double lerpYHeadRot;
258
	protected int lerpHeadSteps;
259
	private boolean effectsDirty = true;
260
	private @Nullable EntityReference<LivingEntity> lastHurtByMob;
261
	private int lastHurtByMobTimestamp;
262
	private @Nullable LivingEntity lastHurtMob;
263
	private int lastHurtMobTimestamp;
264
	private float speed;
265
	private int noJumpDelay;
266
	private float absorptionAmount;
267
	protected ItemStack useItem = ItemStack.EMPTY;
268
	protected int useItemRemaining;
269
	protected int fallFlyTicks;
270
	private long lastKineticHitFeedbackTime = -2147483648L;
271
	private BlockPos lastPos;
272
	private Optional<BlockPos> lastClimbablePos = Optional.empty();
273
	private @Nullable DamageSource lastDamageSource;
274
	private long lastDamageStamp;
275
	protected int autoSpinAttackTicks;
276
	protected float autoSpinAttackDmg;
277
	protected @Nullable ItemStack autoSpinAttackItemStack;
278
	protected @Nullable Object2LongMap<Entity> recentKineticEnemies;
279
	private float swimAmount;
280
	private float swimAmountO;
281
	protected Brain<?> brain;
282
	private boolean skipDropExperience;
283
	private final EnumMap<EquipmentSlot, Reference2ObjectMap<Enchantment, Set<EnchantmentLocationBasedEffect>>> activeLocationDependentEnchantments = new EnumMap<>(
284
		EquipmentSlot.class
285
	);
286
	protected final EntityEquipment equipment;
287
	private Waypoint.Icon locatorBarIcon = new Waypoint.Icon();
288
	public @Nullable Vec3 currentImpulseImpactPos;
289
290
	protected LivingEntity(final EntityType<? extends LivingEntity> type, final Level level) {
291
		super(type, level);
292
		this.attributes = new AttributeMap(DefaultAttributes.getSupplier(type));
293
		this.setHealth(this.getMaxHealth());
294
		this.equipment = this.createEquipment();
295
		this.blocksBuilding = true;
296
		this.reapplyPosition();
297
		this.setYRot(this.random.nextFloat() * (float) (Math.PI * 2));
298
		this.yHeadRot = this.getYRot();
299
		this.brain = this.makeBrain(Brain.Packed.EMPTY);
300
	}
301
302
	@Override
303
	public @Nullable LivingEntity asLivingEntity() {
304
		return this;
305
	}
306
307
	@Contract(pure = true)
308
	protected EntityEquipment createEquipment() {
309
		return new EntityEquipment();
310
	}
311
312
	public Brain<? extends LivingEntity> getBrain() {
313
		return (Brain<? extends LivingEntity>)this.brain;
314
	}
315
316
	protected Brain<? extends LivingEntity> makeBrain(final Brain.Packed packedBrain) {
317
		return new Brain<>();
318
	}
319
320
	@Override
321
	public void kill(final ServerLevel level) {
322
		this.hurtServer(level, this.damageSources().genericKill(), Float.MAX_VALUE);
323
	}
324
325
	@Override
326
	protected void defineSynchedData(final SynchedEntityData.Builder entityData) {
327
		entityData.define(DATA_LIVING_ENTITY_FLAGS, (byte)0);
328
		entityData.define(DATA_EFFECT_PARTICLES, List.of());
329
		entityData.define(DATA_EFFECT_AMBIENCE_ID, false);
330
		entityData.define(DATA_ARROW_COUNT_ID, 0);
331
		entityData.define(DATA_STINGER_COUNT_ID, 0);
332
		entityData.define(DATA_HEALTH_ID, 1.0F);
333
		entityData.define(SLEEPING_POS_ID, Optional.empty());
334
	}
335
336
	public static AttributeSupplier.Builder createLivingAttributes() {
337
		return AttributeSupplier.builder()
338
			.add(Attributes.MAX_HEALTH)
339
			.add(Attributes.KNOCKBACK_RESISTANCE)
340
			.add(Attributes.MOVEMENT_SPEED)
341
			.add(Attributes.ARMOR)
342
			.add(Attributes.ARMOR_TOUGHNESS)
343
			.add(Attributes.MAX_ABSORPTION)
344
			.add(Attributes.STEP_HEIGHT)
345
			.add(Attributes.SCALE)
346
			.add(Attributes.GRAVITY)
347
			.add(Attributes.SAFE_FALL_DISTANCE)
348
			.add(Attributes.FALL_DAMAGE_MULTIPLIER)
349
			.add(Attributes.JUMP_STRENGTH)
350
			.add(Attributes.ENTITY_INTERACTION_RANGE)
351
			.add(Attributes.OXYGEN_BONUS)
352
			.add(Attributes.BURNING_TIME)
353
			.add(Attributes.EXPLOSION_KNOCKBACK_RESISTANCE)
354
			.add(Attributes.WATER_MOVEMENT_EFFICIENCY)
355
			.add(Attributes.MOVEMENT_EFFICIENCY)
356
			.add(Attributes.ATTACK_KNOCKBACK)
357
			.add(Attributes.CAMERA_DISTANCE)
358
			.add(Attributes.WAYPOINT_TRANSMIT_RANGE)
359
			.add(Attributes.BOUNCINESS)
360
			.add(Attributes.AIR_DRAG_MODIFIER)
361
			.add(Attributes.FRICTION_MODIFIER)
362
			.add(Attributes.NAME_TAG_DISTANCE)
363
			.add(Attributes.BELOW_NAME_DISTANCE);
364
	}
365
366
	@Override
367
	protected void checkFallDamage(final double ya, final boolean onGround, final BlockState onState, final BlockPos pos) {
368
		if (!this.isInWater()) {
369
			this.updateFluidInteraction();
370
		}
371
372
		if (this.level() instanceof ServerLevel level && onGround && this.fallDistance > 0.0) {
373
			this.onChangedBlock(level, pos);
374
			double power = Math.max(0, Mth.floor(this.calculateFallPower(this.fallDistance)));
375
			if (power > 0.0 && !onState.isAir()) {
376
				double x = this.getX();
377
				double y = this.getY();
378
				double z = this.getZ();
379
				BlockPos entityPos = this.blockPosition();
380
				if (pos.getX() != entityPos.getX() || pos.getZ() != entityPos.getZ()) {
381
					double xDiff = x - pos.getX() - 0.5;
382
					double zDiff = z - pos.getZ() - 0.5;
383
					double maxDiff = Math.max(Math.abs(xDiff), Math.abs(zDiff));
384
					x = pos.getX() + 0.5 + xDiff / maxDiff * 0.5;
385
					z = pos.getZ() + 0.5 + zDiff / maxDiff * 0.5;
386
				}
387
388
				double scale = Math.min(0.2F + power / 15.0, 2.5);
389
				int particles = (int)(150.0 * scale);
390
				level.sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, onState), x, y, z, particles, 0.0, 0.0, 0.0, 0.15F);
391
			}
392
		}
393
394
		super.checkFallDamage(ya, onGround, onState, pos);
395
		if (onGround) {
396
			this.lastClimbablePos = Optional.empty();
397
		}
398
	}
399
400
	public boolean canBreatheUnderwater() {
401
		return this.is(EntityTypeTags.CAN_BREATHE_UNDER_WATER);
402
	}
403
404
	public float getSwimAmount(final float a) {
405
		return Mth.lerp(a, this.swimAmountO, this.swimAmount);
406
	}
407
408
	public boolean hasLandedInLiquid() {
409
		return this.getDeltaMovement().y() < 1.0E-5F && this.isInLiquid();
410
	}
411
412
	@Override
413
	public void baseTick() {
414
		this.swingState.tick();
415
		if (this.firstTick) {
416
			this.getSleepingPos().ifPresent(bedPosition -> {
417
				if (!this.setPosToBed(bedPosition)) {
418
					this.stopSleeping();
419
				}
420
			});
421
		}
422
423
		if (this.level() instanceof ServerLevel serverLevel) {
424
			EnchantmentHelper.tickEffects(serverLevel, this);
425
		}
426
427
		super.baseTick();
428
		ProfilerFiller profiler = Profiler.get();
429
		profiler.push("livingEntityBaseTick");
430
		if (this.isAlive() && this.level() instanceof ServerLevel level) {
431
			boolean isPlayer = this instanceof Player;
432
			if (this.isInWall()) {
433
				this.hurtServer(level, this.damageSources().inWall(), 1.0F);
434
			} else if (isPlayer && !level.getWorldBorder().isWithinBounds(this.getBoundingBox())) {
435
				double dist = level.getWorldBorder().getDistanceToBorder(this) + level.getWorldBorder().getSafeZone();
436
				if (dist < 0.0) {
437
					double damagePerBlock = level.getWorldBorder().getDamagePerBlock();
438
					if (damagePerBlock > 0.0) {
439
						this.hurtServer(level, this.damageSources().outOfBorder(), Math.max(1, Mth.floor(-dist * damagePerBlock)));
440
					}
441
				}
442
			}
443
444
			if (this.isEyeInFluid(FluidTags.WATER) && !level.getBlockState(BlockPos.containing(this.getX(), this.getEyeY(), this.getZ())).is(Blocks.BUBBLE_COLUMN)) {
445
				boolean canDrownInWater = !this.canBreatheUnderwater()
446
					&& !MobEffectUtil.hasWaterBreathing(this)
447
					&& (!isPlayer || !((Player)this).getAbilities().invulnerable);
448
				if (canDrownInWater) {
449
					this.setAirSupply(this.decreaseAirSupply(this.getAirSupply()));
450
					if (this.shouldTakeDrowningDamage()) {
451
						this.setAirSupply(0);
452
						level.broadcastEntityEvent(this, (byte)67);
453
						this.hurtServer(level, this.damageSources().drown(), 2.0F);
454
					}
455
				} else if (this.getAirSupply() < this.getMaxAirSupply() && MobEffectUtil.shouldEffectsRefillAirsupply(this)) {
456
					this.setAirSupply(this.increaseAirSupply(this.getAirSupply()));
457
				}
458
459
				if (this.isPassenger() && this.getVehicle() != null && this.getVehicle().dismountsUnderwater()) {
460
					this.stopRiding();
461
				}
462
			} else if (this.getAirSupply() < this.getMaxAirSupply()) {
463
				this.setAirSupply(this.increaseAirSupply(this.getAirSupply()));
464
			}
465
466
			BlockPos pos = this.blockPosition();
467
			if (!Objects.equal(this.lastPos, pos)) {
468
				this.lastPos = pos;
469
				this.onChangedBlock(level, pos);
470
			}
471
		}
472
473
		if (this.hurtTime > 0) {
474
			this.hurtTime--;
475
		}
476
477
		if (this.damageCooldownTime > 0 && !(this instanceof ServerPlayer)) {
478
			this.damageCooldownTime--;
479
		}
480
481
		if (this.isDeadOrDying() && this.level().shouldTickDeath(this)) {
482
			this.tickDeath();
483
		}
484
485
		if (this.lastHurtByPlayerMemoryTime > 0) {
486
			this.lastHurtByPlayerMemoryTime--;
487
		} else {
488
			this.lastHurtByPlayer = null;
489
		}
490
491
		if (this.lastHurtMob != null && !this.lastHurtMob.isAlive()) {
492
			this.lastHurtMob = null;
493
		}
494
495
		LivingEntity hurtByMob = this.getLastHurtByMob();
496
		if (hurtByMob != null) {
497
			if (!hurtByMob.isAlive()) {
498
				this.setLastHurtByMob(null);
499
			} else if (this.tickCount - this.lastHurtByMobTimestamp > 100) {
500
				this.setLastHurtByMob(null);
501
			}
502
		}
503
504
		this.tickEffects();
505
		this.yHeadRotO = this.yHeadRot;
506
		this.yBodyRotO = this.yBodyRot;
507
		profiler.pop();
508
	}
509
510
	protected boolean shouldTakeDrowningDamage() {
511
		return this.getAirSupply() <= -20;
512
	}
513
514
	@Override
515
	protected float getBlockSpeedFactor() {
516
		return Mth.lerp((float)this.getAttributeValue(Attributes.MOVEMENT_EFFICIENCY), super.getBlockSpeedFactor(), 1.0F);
517
	}
518
519
	private static float computeModifiedFriction(final float friction, final float modifier) {
520
		return Mth.clamp(1.0F - (1.0F - friction) * modifier, 0.0F, 1.0F);
521
	}
522
523
	public float getLuck() {
524
		return 0.0F;
525
	}
526
527
	protected void removeFrost() {
528
		AttributeInstance speed = this.getAttribute(Attributes.MOVEMENT_SPEED);
529
		if (speed != null) {
530
			if (speed.getModifier(SPEED_MODIFIER_POWDER_SNOW_ID) != null) {
531
				speed.removeModifier(SPEED_MODIFIER_POWDER_SNOW_ID);
532
			}
533
		}
534
	}
535
536
	protected void tryAddFrost() {
537
		if (!this.getBlockStateOnLegacy().isAir()) {
538
			int ticksFrozen = this.getTicksFrozen();
539
			if (ticksFrozen > 0) {
540
				AttributeInstance speed = this.getAttribute(Attributes.MOVEMENT_SPEED);
541
				if (speed == null) {
542
					return;
543
				}
544
545
				float slowAmount = -0.05F * this.getPercentFrozen();
546
				speed.addTransientModifier(new AttributeModifier(SPEED_MODIFIER_POWDER_SNOW_ID, slowAmount, AttributeModifier.Operation.ADD_VALUE));
547
			}
548
		}
549
	}
550
551
	protected void onChangedBlock(final ServerLevel level, final BlockPos pos) {
552
		EnchantmentHelper.runLocationChangedEffects(level, this);
553
	}
554
555
	public boolean isBaby() {
556
		return false;
557
	}
558
559
	public float getAgeScale() {
560
		return this.isBaby() ? 0.5F : 1.0F;
561
	}
562
563
	public final float getScale() {
564
		AttributeMap attributes = this.getAttributes();
565
		return attributes == null ? 1.0F : this.sanitizeScale((float)attributes.getValue(Attributes.SCALE));
566
	}
567
568
	protected float sanitizeScale(final float scale) {
569
		return scale;
570
	}
571
572
	public boolean isAffectedByFluids() {
573
		return true;
574
	}
575
576
	protected void tickDeath() {
577
		this.deathTime++;
578
		if (this.deathTime >= 20 && !this.level().isClientSide() && !this.isRemoved()) {
579
			this.level().broadcastEntityEvent(this, (byte)60);
580
			this.remove(Entity.RemovalReason.KILLED);
581
		}
582
	}
583
584
	public boolean shouldDropExperience() {
585
		return !this.isBaby();
586
	}
587
588
	protected boolean shouldDropLoot(final ServerLevel level) {
589
		return !this.isBaby() && level.getGameRules().get(GameRules.MOB_DROPS);
590
	}
591
592
	protected int decreaseAirSupply(final int currentSupply) {
593
		AttributeInstance respiration = this.getAttribute(Attributes.OXYGEN_BONUS);
594
		double oxygenBonus;
595
		if (respiration != null) {
596
			oxygenBonus = respiration.getValue();
597
		} else {
598
			oxygenBonus = 0.0;
599
		}
600
601
		return oxygenBonus > 0.0 && this.random.nextDouble() >= 1.0 / (oxygenBonus + 1.0) ? currentSupply : currentSupply - 1;
602
	}
603
604
	protected int increaseAirSupply(final int currentSupply) {
605
		return Math.min(currentSupply + 4, this.getMaxAirSupply());
606
	}
607
608
	public final int getExperienceReward(final ServerLevel level, final @Nullable Entity killer) {
609
		return EnchantmentHelper.processMobExperience(level, killer, this, this.getBaseExperienceReward(level));
610
	}
611
612
	protected int getBaseExperienceReward(final ServerLevel level) {
613
		return 0;
614
	}
615
616
	protected boolean isAlwaysExperienceDropper() {
617
		return false;
618
	}
619
620
	public @Nullable LivingEntity getLastHurtByMob() {
621
		return EntityReference.getLivingEntity(this.lastHurtByMob, this.level());
622
	}
623
624
	public @Nullable Player getLastHurtByPlayer() {
625
		return EntityReference.getPlayer(this.lastHurtByPlayer, this.level());
626
	}
627
628
	@Override
629
	public LivingEntity getLastAttacker() {
630
		return this.getLastHurtByMob();
631
	}
632
633
	public int getLastHurtByMobTimestamp() {
634
		return this.lastHurtByMobTimestamp;
635
	}
636
637
	public void setLastHurtByPlayer(final Player player, final int timeToRemember) {
638
		this.setLastHurtByPlayer(EntityReference.of(player), timeToRemember);
639
	}
640
641
	public void setLastHurtByPlayer(final UUID player, final int timeToRemember) {
642
		this.setLastHurtByPlayer(EntityReference.of(player), timeToRemember);
643
	}
644
645
	private void setLastHurtByPlayer(final EntityReference<Player> player, final int timeToRemember) {
646
		this.lastHurtByPlayer = player;
647
		this.lastHurtByPlayerMemoryTime = timeToRemember;
648
	}
649
650
	public void setLastHurtByMob(final @Nullable LivingEntity hurtBy) {
651
		this.lastHurtByMob = EntityReference.of(hurtBy);
652
		this.lastHurtByMobTimestamp = this.tickCount;
653
	}
654
655
	public @Nullable LivingEntity getLastHurtMob() {
656
		return this.lastHurtMob;
657
	}
658
659
	public int getLastHurtMobTimestamp() {
660
		return this.lastHurtMobTimestamp;
661
	}
662
663
	public void setLastHurtMob(final Entity target) {
664
		if (target instanceof LivingEntity livingEntity) {
665
			this.lastHurtMob = livingEntity;
666
		} else {
667
			this.lastHurtMob = null;
668
		}
669
670
		this.lastHurtMobTimestamp = this.tickCount;
671
	}
672
673
	public int getNoActionTime() {
674
		return this.noActionTime;
675
	}
676
677
	public void setNoActionTime(final int noActionTime) {
678
		this.noActionTime = noActionTime;
679
	}
680
681
	public boolean shouldDiscardFriction() {
682
		return this.discardFriction;
683
	}
684
685
	public void setDiscardFriction(final boolean discardFriction) {
686
		this.discardFriction = discardFriction;
687
	}
688
689
	protected boolean doesEmitEquipEvent(final EquipmentSlot slot) {
690
		return true;
691
	}
692
693
	public void onEquipItem(final EquipmentSlot slot, final ItemStack oldStack, final ItemStack stack) {
694
		if (!this.level().isClientSide() && !this.isSpectator()) {
695
			if (!ItemStack.isSameItemSameComponents(oldStack, stack) && !this.firstTick) {
696
				Equippable equippable = stack.get(DataComponents.EQUIPPABLE);
697
				if (!this.isSilent() && equippable != null && slot == equippable.slot()) {
698
					this.level()
699
						.playSeededSound(
700
							null, this.getX(), this.getY(), this.getZ(), this.getEquipSound(slot, stack, equippable), this.getSoundSource(), 1.0F, 1.0F, this.random.nextLong()
701
						);
702
				}
703
704
				if (this.doesEmitEquipEvent(slot)) {
705
					this.gameEvent(equippable != null ? GameEvent.EQUIP : GameEvent.UNEQUIP);
706
				}
707
			}
708
		}
709
	}
710
711
	protected Holder<SoundEvent> getEquipSound(final EquipmentSlot slot, final ItemStack stack, final Equippable equippable) {
712
		return equippable.equipSound();
713
	}
714
715
	@Override
716
	public void remove(final Entity.RemovalReason reason) {
717
		if ((reason == Entity.RemovalReason.KILLED || reason == Entity.RemovalReason.DISCARDED) && this.level() instanceof ServerLevel level) {
718
			this.triggerOnDeathMobEffects(level, reason);
719
		}
720
721
		super.remove(reason);
722
		this.brain.clearMemories();
723
		this.getCombatTracker().recheckStatus();
724
	}
725
726
	@Override
727
	public void onRemoval(final Entity.RemovalReason reason) {
728
		super.onRemoval(reason);
729
		if (this.level() instanceof ServerLevel serverLevel) {
730
			serverLevel.getWaypointManager().untrackWaypoint(this);
731
		}
732
	}
733
734
	protected void triggerOnDeathMobEffects(final ServerLevel level, final Entity.RemovalReason reason) {
735
		for (MobEffectInstance effect : this.getActiveEffects()) {
736
			effect.onMobRemoved(level, this, reason);
737
		}
738
739
		this.activeEffects.clear();
740
	}
741
742
	@Override
743
	protected void addAdditionalSaveData(final ValueOutput output) {
744
		output.putFloat("Health", this.getHealth());
745
		output.putShort("HurtTime", (short)this.hurtTime);
746
		output.putShort("DeathTime", (short)this.deathTime);
747
		output.putFloat("AbsorptionAmount", this.getAbsorptionAmount());
748
		output.putInt("current_impulse_context_reset_grace_time", this.currentImpulseContextResetGraceTime);
749
		output.storeNullable("current_explosion_impact_pos", Vec3.CODEC, this.currentImpulseImpactPos);
750
		output.store("attributes", AttributeInstance.Packed.LIST_CODEC, this.getAttributes().pack());
751
		if (!this.activeEffects.isEmpty()) {
752
			output.store("active_effects", MobEffectInstance.CODEC.listOf(), List.copyOf(this.activeEffects.values()));
753
		}
754
755
		output.putBoolean("FallFlying", this.isFallFlying());
756
		this.getSleepingPos().ifPresent(sleepingPos -> output.store("sleeping_pos", BlockPos.CODEC, sleepingPos));
757
		output.store("Brain", Brain.Packed.CODEC, this.brain.pack());
758
		if (this.lastHurtByPlayer != null) {
759
			this.lastHurtByPlayer.store(output, "last_hurt_by_player");
760
			output.putInt("last_hurt_by_player_memory_time", this.lastHurtByPlayerMemoryTime);
761
		}
762
763
		if (this.lastHurtByMob != null) {
764
			this.lastHurtByMob.store(output, "last_hurt_by_mob");
765
			output.putInt("ticks_since_last_hurt_by_mob", this.tickCount - this.lastHurtByMobTimestamp);
766
		}
767
768
		if (!this.equipment.isEmpty()) {
769
			output.store("equipment", EntityEquipment.CODEC, this.equipment);
770
		}
771
772
		if (this.locatorBarIcon.hasData()) {
773
			output.store("locator_bar_icon", Waypoint.Icon.CODEC, this.locatorBarIcon);
774
		}
775
	}
776
777
	public @Nullable ItemEntity drop(final ItemStack itemStack, final boolean thrownFromHand, final Prediction prediction) {
778
		if (itemStack.isEmpty()) {
779
			return null;
780
		}
781
782
		this.swing(InteractionHand.MAIN_HAND, SwingAnimation.DEFAULT, prediction != Prediction.PREDICTED);
783
		if (this.level().isClientSide()) {
784
			return null;
785
		}
786
787
		ItemEntity entity = this.createItemStackToDrop(itemStack, false, thrownFromHand);
788
		if (entity != null) {
789
			this.level().addFreshEntity(entity);
790
		}
791
792
		return entity;
793
	}
794
795
	@Override
796
	protected void readAdditionalSaveData(final ValueInput input) {
797
		this.internalSetAbsorptionAmount(input.getFloatOr("AbsorptionAmount", 0.0F));
798
		if (this.level() != null && !this.level().isClientSide()) {
799
			input.read("attributes", AttributeInstance.Packed.LIST_CODEC).ifPresent(this.getAttributes()::apply);
800
		}
801
802
		List<MobEffectInstance> effects = input.read("active_effects", MobEffectInstance.CODEC.listOf()).orElse(List.of());
803
		this.activeEffects.clear();
804
805
		for (MobEffectInstance effect : effects) {
806
			this.activeEffects.put(effect.getEffect(), effect);
807
			this.effectsDirty = true;
808
		}
809
810
		this.setHealth(input.getFloatOr("Health", this.getMaxHealth()));
811
		this.hurtTime = input.getShortOr("HurtTime", (short)0);
812
		this.deathTime = input.getShortOr("DeathTime", (short)0);
813
		this.setSharedFlag(7, input.getBooleanOr("FallFlying", false));
814
		input.read("sleeping_pos", BlockPos.CODEC).ifPresentOrElse(sleepingPos -> {
815
			this.setSleepingPos(sleepingPos);
816
			this.entityData.set(DATA_POSE, Pose.SLEEPING);
817
			if (!this.firstTick && !this.setPosToBed(sleepingPos)) {
818
				this.stopSleeping();
819
			}
820
		}, this::clearSleepingPos);
821
		input.read("Brain", Brain.Packed.CODEC).ifPresent(packedBrain -> this.brain = this.makeBrain(packedBrain));
822
		this.lastHurtByPlayer = EntityReference.read(input, "last_hurt_by_player");
823
		this.lastHurtByPlayerMemoryTime = input.getIntOr("last_hurt_by_player_memory_time", 0);
824
		this.lastHurtByMob = EntityReference.read(input, "last_hurt_by_mob");
825
		this.lastHurtByMobTimestamp = this.tickCount - input.getIntOr("ticks_since_last_hurt_by_mob", 0);
826
		this.equipment.setAll(input.read("equipment", EntityEquipment.CODEC).orElseGet(EntityEquipment::new));
827
		this.locatorBarIcon = input.read("locator_bar_icon", Waypoint.Icon.CODEC).orElseGet(Waypoint.Icon::new);
828
		this.currentImpulseContextResetGraceTime = input.getIntOr("current_impulse_context_reset_grace_time", 0);
829
		this.currentImpulseImpactPos = input.read("current_explosion_impact_pos", Vec3.CODEC).orElse(null);
830
	}
831
832
	@Override
833
	public void updateDataBeforeSync() {
834
		super.updateDataBeforeSync();
835
		this.updateDirtyEffects();
836
	}
837
838
	protected void tickEffects() {
839
		if (this.level() instanceof ServerLevel serverLevel) {
840
			Iterator<Holder<MobEffect>> iterator = this.activeEffects.keySet().iterator();
841
842
			try {
843
				while (iterator.hasNext()) {
844
					Holder<MobEffect> mobEffect = iterator.next();
845
					MobEffectInstance effect = this.activeEffects.get(mobEffect);
846
					if (!effect.tickServer(serverLevel, this, () -> this.onEffectUpdated(effect, true, null))) {
847
						iterator.remove();
848
						this.onEffectsRemoved(List.of(effect));
849
					} else if (effect.getDuration() % 600 == 0) {
850
						this.onEffectUpdated(effect, false, null);
851
					}
852
				}
853
			} catch (ConcurrentModificationException var6) {
854
			}
855
		} else {
856
			for (MobEffectInstance effect : this.activeEffects.values()) {
857
				effect.tickClient();
858
			}
859
860
			List<ParticleOptions> particles = this.entityData.get(DATA_EFFECT_PARTICLES);
861
			if (!particles.isEmpty()) {
862
				boolean isAmbient = this.entityData.get(DATA_EFFECT_AMBIENCE_ID);
863
				int bound = this.isInvisible() ? 15 : 4;
864
				int ambientFactor = isAmbient ? 5 : 1;
865
				if (this.random.nextInt(bound * ambientFactor) == 0) {
866
					this.level().addParticle(Util.getRandom(particles, this.random), this.getRandomX(0.5), this.getRandomY(), this.getRandomZ(0.5), 1.0, 1.0, 1.0);
867
				}
868
			}
869
		}
870
	}
871
872
	private void updateDirtyEffects() {
873
		if (this.effectsDirty) {
874
			this.updateInvisibilityStatus();
875
			this.updateGlowingStatus();
876
			this.effectsDirty = false;
877
		}
878
	}
879
880
	protected void updateInvisibilityStatus() {
881
		if (this.activeEffects.isEmpty()) {
882
			this.removeEffectParticles();
883
			this.setInvisible(false);
884
		} else {
885
			this.setInvisible(this.hasEffect(MobEffects.INVISIBILITY));
886
			this.updateSynchronizedMobEffectParticles();
887
		}
888
	}
889
890
	private void updateSynchronizedMobEffectParticles() {
891
		List<ParticleOptions> visibleEffectParticles = this.activeEffects
892
			.values()
893
			.stream()
894
			.filter(MobEffectInstance::isVisible)
895
			.map(MobEffectInstance::getParticleOptions)
896
			.toList();
897
		this.entityData.set(DATA_EFFECT_PARTICLES, visibleEffectParticles);
898
		this.entityData.set(DATA_EFFECT_AMBIENCE_ID, areAllEffectsAmbient(this.activeEffects.values()));
899
	}
900
901
	private void updateGlowingStatus() {
902
		boolean glowingState = this.isCurrentlyGlowing();
903
		if (this.getSharedFlag(6) != glowingState) {
904
			this.setSharedFlag(6, glowingState);
905
		}
906
	}
907
908
	public double getVisibilityPercent(final ServerLevel serverLevel, final @Nullable Entity targetingEntity) {
909
		double visibilityPercent = 1.0;
910
		if (this.isDiscrete()) {
911
			visibilityPercent *= 0.8;
912
		}
913
914
		if (this.isInvisible()) {
915
			float coverPercentage = this.getArmorCoverPercentage();
916
			if (coverPercentage < 0.1F) {
917
				coverPercentage = 0.1F;
918
			}
919
920
			visibilityPercent *= 0.7 * coverPercentage;
921
		}
922
923
		if (targetingEntity != null) {
924
			for (EquipmentSlot slot : EquipmentSlot.VALUES) {
925
				ItemStack item = this.getItemBySlot(slot);
926
				MobVisibility mobVisibility = item.get(DataComponents.MOB_VISIBILITY);
927
				if (mobVisibility != null) {
928
					Equippable equippable = item.get(DataComponents.EQUIPPABLE);
929
					if (equippable != null && slot == equippable.slot() && mobVisibility.targetingEntityTypes().contains(targetingEntity.typeHolder())) {
930
						visibilityPercent *= mobVisibility.visibility();
931
					}
932
				}
933
			}
934
		}
935
936
		return Mth.clamp(visibilityPercent, 0.0, 10.0);
937
	}
938
939
	public boolean canAttack(final LivingEntity target) {
940
		return target instanceof Player && this.level().getDifficulty() == Difficulty.PEACEFUL ? false : target.canBeSeenAsEnemy();
941
	}
942
943
	public boolean canBeSeenAsEnemy() {
944
		return !this.isInvulnerable() && this.canBeSeenByAnyone();
945
	}
946
947
	public boolean canBeSeenByAnyone() {
948
		return !this.isSpectator() && this.isAlive();
949
	}
950
951
	public static boolean areAllEffectsAmbient(final Collection<MobEffectInstance> effects) {
952
		for (MobEffectInstance effect : effects) {
953
			if (effect.isVisible() && !effect.isAmbient()) {
954
				return false;
955
			}
956
		}
957
958
		return true;
959
	}
960
961
	protected void removeEffectParticles() {
962
		this.entityData.set(DATA_EFFECT_PARTICLES, List.of());
963
	}
964
965
	public boolean removeAllEffects() {
966
		if (this.level().isClientSide()) {
967
			return false;
968
		}
969
970
		if (this.activeEffects.isEmpty()) {
971
			return false;
972
		}
973
974
		Map<Holder<MobEffect>, MobEffectInstance> copy = Maps.newHashMap(this.activeEffects);
975
		this.activeEffects.clear();
976
		this.onEffectsRemoved(copy.values());
977
		return true;
978
	}
979
980
	public Collection<MobEffectInstance> getActiveEffects() {
981
		return this.activeEffects.values();
982
	}
983
984
	public Map<Holder<MobEffect>, MobEffectInstance> getActiveEffectsMap() {
985
		return this.activeEffects;
986
	}
987
988
	public boolean hasEffect(final Holder<MobEffect> effect) {
989
		return this.activeEffects.containsKey(effect);
990
	}
991
992
	public @Nullable MobEffectInstance getEffect(final Holder<MobEffect> effect) {
993
		return this.activeEffects.get(effect);
994
	}
995
996
	public float getEffectBlendFactor(final Holder<MobEffect> effect, final float partialTicks) {
997
		MobEffectInstance instance = this.getEffect(effect);
998
		return instance != null ? instance.getBlendFactor(this, partialTicks) : 0.0F;
999
	}
1000
1001
	public final boolean addEffect(final MobEffectInstance newEffect) {
1002
		return this.addEffect(newEffect, null);
1003
	}
1004
1005
	public boolean addEffect(final MobEffectInstance newEffect, final @Nullable Entity source) {
1006
		if (!this.canBeAffected(newEffect)) {
1007
			return false;
1008
		}
1009
1010
		MobEffectInstance effect = this.activeEffects.get(newEffect.getEffect());
1011
		boolean changed = false;
1012
		if (effect == null) {
1013
			this.activeEffects.put(newEffect.getEffect(), newEffect);
1014
			this.onEffectAdded(newEffect, source);
1015
			changed = true;
1016
			newEffect.onEffectAdded(this);
1017
		} else if (effect.update(newEffect)) {
1018
			this.onEffectUpdated(effect, true, source);
1019
			changed = true;
1020
		}
1021
1022
		newEffect.onEffectStarted(this);
1023
		return changed;
1024
	}
1025
1026
	public boolean canBeAffected(final MobEffectInstance newEffect) {
1027
		if (this.is(EntityTypeTags.IMMUNE_TO_INFESTED)) {
1028
			return !newEffect.is(MobEffects.INFESTED);
1029
		} else if (this.is(EntityTypeTags.IMMUNE_TO_OOZING)) {
1030
			return !newEffect.is(MobEffects.OOZING);
1031
		} else {
1032
			return !this.is(EntityTypeTags.IGNORES_POISON_AND_REGEN) ? true : !newEffect.is(MobEffects.REGENERATION) && !newEffect.is(MobEffects.POISON);
1033
		}
1034
	}
1035
1036
	public void forceAddEffect(final MobEffectInstance newEffect, final @Nullable Entity source) {
1037
		if (this.canBeAffected(newEffect)) {
1038
			MobEffectInstance previousEffect = this.activeEffects.put(newEffect.getEffect(), newEffect);
1039
			if (previousEffect == null) {
1040
				this.onEffectAdded(newEffect, source);
1041
			} else {
1042
				newEffect.copyBlendState(previousEffect);
1043
				this.onEffectUpdated(newEffect, true, source);
1044
			}
1045
		}
1046
	}
1047
1048
	public boolean isInvertedHealAndHarm() {
1049
		return this.is(EntityTypeTags.INVERTED_HEALING_AND_HARM);
1050
	}
1051
1052
	public final @Nullable MobEffectInstance removeEffectNoUpdate(final Holder<MobEffect> effect) {
1053
		return this.activeEffects.remove(effect);
1054
	}
1055
1056
	public boolean removeEffect(final Holder<MobEffect> effect) {
1057
		MobEffectInstance effectInstance = this.removeEffectNoUpdate(effect);
1058
		if (effectInstance != null) {
1059
			this.onEffectsRemoved(List.of(effectInstance));
1060
			return true;
1061
		} else {
1062
			return false;
1063
		}
1064
	}
1065
1066
	protected void onEffectAdded(final MobEffectInstance effect, final @Nullable Entity source) {
1067
		if (!this.level().isClientSide()) {
1068
			this.effectsDirty = true;
1069
			effect.getEffect().value().addAttributeModifiers(this.getAttributes(), effect.getAmplifier());
1070
			this.sendEffectToPassengers(effect);
1071
		}
1072
	}
1073
1074
	public void sendEffectToPassengers(final MobEffectInstance effect) {
1075
		for (Entity passenger : this.getPassengers()) {
1076
			if (passenger instanceof ServerPlayer serverPlayer) {
1077
				serverPlayer.connection.send(new ClientboundUpdateMobEffectPacket(this.getId(), effect, false));
1078
			}
1079
		}
1080
	}
1081
1082
	protected void onEffectUpdated(final MobEffectInstance effect, final boolean doRefreshAttributes, final @Nullable Entity source) {
1083
		if (!this.level().isClientSide()) {
1084
			this.effectsDirty = true;
1085
			if (doRefreshAttributes) {
1086
				MobEffect mobEffect = effect.getEffect().value();
1087
				mobEffect.removeAttributeModifiers(this.getAttributes());
1088
				mobEffect.addAttributeModifiers(this.getAttributes(), effect.getAmplifier());
1089
				this.refreshDirtyAttributes();
1090
			}
1091
1092
			this.sendEffectToPassengers(effect);
1093
		}
1094
	}
1095
1096
	protected void onEffectsRemoved(final Collection<MobEffectInstance> effects) {
1097
		if (!this.level().isClientSide()) {
1098
			this.effectsDirty = true;
1099
1100
			for (MobEffectInstance effect : effects) {
1101
				effect.getEffect().value().removeAttributeModifiers(this.getAttributes());
1102
1103
				for (Entity passenger : this.getPassengers()) {
1104
					if (passenger instanceof ServerPlayer serverPlayer) {
1105
						serverPlayer.connection.send(new ClientboundRemoveMobEffectPacket(this.getId(), effect.getEffect()));
1106
					}
1107
				}
1108
			}
1109
1110
			this.refreshDirtyAttributes();
1111
		}
1112
	}
1113
1114
	private void refreshDirtyAttributes() {
1115
		Set<AttributeInstance> attributesToUpdate = this.getAttributes().getAttributesToUpdate();
1116
1117
		for (AttributeInstance changedAttributeInstance : attributesToUpdate) {
1118
			this.onAttributeUpdated(changedAttributeInstance.getAttribute());
1119
		}
1120
1121
		attributesToUpdate.clear();
1122
	}
1123
1124
	protected void onAttributeUpdated(final Holder<Attribute> attribute) {
1125
		if (attribute.is(Attributes.MAX_HEALTH)) {
1126
			float currentMaxHealth = this.getMaxHealth();
1127
			if (this.getHealth() > currentMaxHealth) {
1128
				this.setHealth(currentMaxHealth);
1129
			}
1130
		} else if (attribute.is(Attributes.MAX_ABSORPTION)) {
1131
			float currentMaxAbsorption = this.getMaxAbsorption();
1132
			if (this.getAbsorptionAmount() > currentMaxAbsorption) {
1133
				this.setAbsorptionAmount(currentMaxAbsorption);
1134
			}
1135
		} else if (attribute.is(Attributes.SCALE)) {
1136
			this.refreshDimensions();
1137
		} else if (attribute.is(Attributes.WAYPOINT_TRANSMIT_RANGE) && this.level() instanceof ServerLevel serverLevel) {
1138
			ServerWaypointManager waypointManager = serverLevel.getWaypointManager();
1139
			if (this.attributes.getValue(attribute) > 0.0) {
1140
				waypointManager.trackWaypoint(this);
1141
			} else {
1142
				waypointManager.untrackWaypoint(this);
1143
			}
1144
		}
1145
	}
1146
1147
	public void heal(final float heal) {
1148
		float health = this.getHealth();
1149
		if (health > 0.0F) {
1150
			this.setHealth(health + heal);
1151
		}
1152
	}
1153
1154
	public float getHealth() {
1155
		return this.entityData.get(DATA_HEALTH_ID);
1156
	}
1157
1158
	public void setHealth(final float health) {
1159
		this.entityData.set(DATA_HEALTH_ID, Mth.clamp(health, 0.0F, this.getMaxHealth()));
1160
	}
1161
1162
	public boolean isDeadOrDying() {
1163
		return this.getHealth() <= 0.0F || this.dead;
1164
	}
1165
1166
	public boolean wasHurtRecently() {
1167
		return this.hurtTime > 0;
1168
	}
1169
1170
	@Override
1171
	public boolean hurtServer(final ServerLevel level, final DamageSource source, float damage) {
1172
		if (this.isInvulnerableTo(level, source)) {
1173
			return false;
1174
		}
1175
1176
		if (this.isDeadOrDying()) {
1177
			return false;
1178
		}
1179
1180
		if (source.is(DamageTypeTags.IS_FIRE) && this.hasEffect(MobEffects.FIRE_RESISTANCE)) {
1181
			return false;
1182
		}
1183
1184
		if (this.isSleeping()) {
1185
			this.stopSleeping();
1186
		}
1187
1188
		this.noActionTime = 0;
1189
		if (damage < 0.0F) {
1190
			damage = 0.0F;
1191
		}
1192
1193
		float originalDamage = damage;
1194
		ItemStack itemInUse = this.getUseItem();
1195
		float damageBlocked = this.applyItemBlocking(level, source, damage);
1196
		damage -= damageBlocked;
1197
		boolean blocked = damageBlocked > 0.0F;
1198
		if (source.is(DamageTypeTags.IS_FREEZING) && this.is(EntityTypeTags.FREEZE_HURTS_EXTRA_TYPES)) {
1199
			damage *= 5.0F;
1200
		}
1201
1202
		if (source.is(DamageTypeTags.DAMAGES_HELMET) && !this.getItemBySlot(EquipmentSlot.HEAD).isEmpty()) {
1203
			this.hurtHelmet(source, damage);
1204
			damage *= 0.75F;
1205
		}
1206
1207
		if (Float.isNaN(damage) || Float.isInfinite(damage)) {
1208
			damage = Float.MAX_VALUE;
1209
		}
1210
1211
		boolean tookFullDamage = true;
1212
		if (this.damageCooldownTime > 10.0F && !source.is(DamageTypeTags.BYPASSES_COOLDOWN)) {
1213
			if (damage <= this.lastHurt) {
1214
				return false;
1215
			}
1216
1217
			this.actuallyHurt(level, source, damage - this.lastHurt);
1218
			this.lastHurt = damage;
1219
			tookFullDamage = false;
1220
		} else {
1221
			this.lastHurt = damage;
1222
			this.damageCooldownTime = 20;
1223
			this.actuallyHurt(level, source, damage);
1224
			this.hurtDuration = 10;
1225
			this.hurtTime = this.hurtDuration;
1226
		}
1227
1228
		this.resolveMobResponsibleForDamage(source);
1229
		this.resolvePlayerResponsibleForDamage(source);
1230
		if (tookFullDamage) {
1231
			BlocksAttacks blocksAttacks = itemInUse.get(DataComponents.BLOCKS_ATTACKS);
1232
			if (blocked && blocksAttacks != null) {
1233
				blocksAttacks.onBlocked(level, this);
1234
			} else {
1235
				level.broadcastDamageEvent(this, source);
1236
			}
1237
1238
			if (!source.is(DamageTypeTags.NO_IMPACT) && (!blocked || damage > 0.0F)) {
1239
				this.markHurt();
1240
			}
1241
1242
			boolean fullyBlocked = blocked && damage <= 0.0F;
1243
			if (!source.is(DamageTypeTags.NO_KNOCKBACK) && !fullyBlocked) {
1244
				this.dealDefaultKnockback(source, damage, blocked);
1245
			}
1246
		}
1247
1248
		if (this.isDeadOrDying()) {
1249
			if (!this.checkTotemDeathProtection(source)) {
1250
				if (tookFullDamage) {
1251
					this.makeSound(this.getDeathSound());
1252
					this.playSecondaryHurtSound(source);
1253
				}
1254
1255
				this.die(source);
1256
			}
1257
		} else if (tookFullDamage) {
1258
			this.playHurtSound(source);
1259
			this.playSecondaryHurtSound(source);
1260
		}
1261
1262
		boolean success = !blocked || damage > 0.0F;
1263
		if (success) {
1264
			this.lastDamageSource = source;
1265
			this.lastDamageStamp = this.level().getGameTime();
1266
1267
			for (MobEffectInstance effect : this.getActiveEffects()) {
1268
				effect.onMobHurt(level, this, source, damage);
1269
			}
1270
		}
1271
1272
		if (this instanceof ServerPlayer serverPlayer) {
1273
			CriteriaTriggers.ENTITY_HURT_PLAYER.trigger(serverPlayer, source, originalDamage, damage, blocked);
1274
			if (damageBlocked > 0.0F && damageBlocked < 3.4028235E37F) {
1275
				serverPlayer.awardStat(Stats.DAMAGE_BLOCKED_BY_SHIELD, Math.round(damageBlocked * 10.0F));
1276
			}
1277
		}
1278
1279
		if (source.getEntity() instanceof ServerPlayer sourcePlayer) {
1280
			CriteriaTriggers.PLAYER_HURT_ENTITY.trigger(sourcePlayer, this, source, originalDamage, damage, blocked);
1281
		}
1282
1283
		return success;
1284
	}
1285
1286
	public void dealDefaultKnockback(final DamageSource source, final float damage, final boolean blocked) {
1287
		double xd = 0.0;
1288
		double zd = 0.0;
1289
		if (source.getDirectEntity() instanceof Projectile projectile) {
1290
			DoubleDoubleImmutablePair knockbackDirection = projectile.calculateHorizontalHurtKnockbackDirection(this, source);
1291
			xd = -knockbackDirection.leftDouble();
1292
			zd = -knockbackDirection.rightDouble();
1293
		} else if (source.getSourcePosition() != null) {
1294
			xd = source.getSourcePosition().x() - this.getX();
1295
			zd = source.getSourcePosition().z() - this.getZ();
1296
		}
1297
1298
		this.knockback(0.4F, xd, zd, source, damage);
1299
		if (!blocked) {
1300
			this.indicateDamage(xd, zd);
1301
		}
1302
	}
1303
1304
	public float applyItemBlocking(final ServerLevel level, final DamageSource source, final float damage) {
1305
		if (damage <= 0.0F) {
1306
			return 0.0F;
1307
		}
1308
1309
		ItemStack blockingWith = this.getItemBlockingWith();
1310
		if (blockingWith == null) {
1311
			return 0.0F;
1312
		}
1313
1314
		BlocksAttacks blocksAttacks = blockingWith.get(DataComponents.BLOCKS_ATTACKS);
1315
		if (blocksAttacks != null && !blocksAttacks.bypassedBy().map(t -> t.contains(source.typeHolder())).orElse(false)) {
1316
			if (source.getDirectEntity() instanceof AbstractArrow abstractArrow && abstractArrow.getPierceLevel() > 0) {
1317
				return 0.0F;
1318
			} else {
1319
				Vec3 sourcePosition = source.getSourcePosition();
1320
				double angle;
1321
				if (sourcePosition != null) {
1322
					Vec3 viewVector = calculateViewVector(0.0F, this.getYHeadRot());
1323
					Vec3 vectorTo = sourcePosition.subtract(this.position());
1324
					vectorTo = new Vec3(vectorTo.x, 0.0, vectorTo.z).normalize();
1325
					angle = Math.acos(vectorTo.dot(viewVector));
1326
				} else {
1327
					angle = (float) Math.PI;
1328
				}
1329
1330
				float damageBlocked = blocksAttacks.resolveBlockedDamage(source, damage, angle);
1331
				blocksAttacks.hurtBlockingItem(this.level(), blockingWith, this, this.getUsedItemHand(), damageBlocked);
1332
				if (damageBlocked > 0.0F && !source.is(DamageTypeTags.IS_PROJECTILE) && source.getDirectEntity() instanceof LivingEntity livingEntity) {
1333
					this.blockUsingItem(level, livingEntity, source, damage, damageBlocked >= damage);
1334
				}
1335
1336
				return damageBlocked;
1337
			}
1338
		} else {
1339
			return 0.0F;
1340
		}
1341
	}
1342
1343
	private void playSecondaryHurtSound(final DamageSource source) {
1344
		if (source.is(DamageTypes.THORNS)) {
1345
			SoundSource soundSource = this instanceof Player ? SoundSource.PLAYERS : SoundSource.HOSTILE;
1346
			this.level().playSound(null, this.position().x, this.position().y, this.position().z, SoundEvents.THORNS_HIT, soundSource);
1347
		}
1348
	}
1349
1350
	protected void resolveMobResponsibleForDamage(final DamageSource source) {
1351
		if (source.getEntity() instanceof LivingEntity livingSource
1352
			&& !source.is(DamageTypeTags.NO_ANGER)
1353
			&& (!source.is(DamageTypes.WIND_CHARGE) || !this.is(EntityTypeTags.NO_ANGER_FROM_WIND_CHARGE))) {
1354
			this.setLastHurtByMob(livingSource);
1355
		}
1356
	}
1357
1358
	protected @Nullable Player resolvePlayerResponsibleForDamage(final DamageSource source) {
1359
		Entity sourceEntity = source.getEntity();
1360
		if (sourceEntity instanceof Player playerSource) {
1361
			this.setLastHurtByPlayer(playerSource, 100);
1362
		} else if (sourceEntity instanceof Wolf wolf && wolf.isTame()) {
1363
			if (wolf.getOwnerReference() != null) {
1364
				this.setLastHurtByPlayer(wolf.getOwnerReference().getUUID(), 100);
1365
			} else {
1366
				this.lastHurtByPlayer = null;
1367
				this.lastHurtByPlayerMemoryTime = 0;
1368
			}
1369
		}
1370
1371
		return EntityReference.getPlayer(this.lastHurtByPlayer, this.level());
1372
	}
1373
1374
	protected void blockUsingItem(final ServerLevel level, final LivingEntity attacker, final DamageSource source, final float damage, final boolean fullyBlocked) {
1375
		attacker.blockedByItem(this, source, damage, fullyBlocked);
1376
	}
1377
1378
	protected void blockedByItem(final LivingEntity defender, final DamageSource source, final float damage, final boolean fullyBlocked) {
1379
		if (!fullyBlocked) {
1380
			defender.knockback(0.5, defender.getX() - this.getX(), defender.getZ() - this.getZ(), source, damage);
1381
		}
1382
	}
1383
1384
	private boolean checkTotemDeathProtection(final DamageSource killingDamage) {
1385
		if (killingDamage.is(DamageTypeTags.BYPASSES_INVULNERABILITY)) {
1386
			return false;
1387
		}
1388
1389
		ItemStack protectionItem = null;
1390
		DeathProtection protection = null;
1391
1392
		for (InteractionHand hand : InteractionHand.values()) {
1393
			ItemStack itemStack = this.getItemInHand(hand);
1394
			protection = itemStack.get(DataComponents.DEATH_PROTECTION);
1395
			if (protection != null) {
1396
				protectionItem = itemStack.copy();
1397
				itemStack.shrink(1);
1398
				break;
1399
			}
1400
		}
1401
1402
		if (protectionItem != null) {
1403
			if (this instanceof ServerPlayer player) {
1404
				player.awardStat(Stats.ITEM_USED.get(protectionItem.getItem()));
1405
				CriteriaTriggers.USED_TOTEM.trigger(player, protectionItem);
1406
				protectionItem.causeUseVibration(this, GameEvent.ITEM_INTERACT_FINISH);
1407
			}
1408
1409
			this.setHealth(1.0F);
1410
			protection.applyEffects(protectionItem, this);
1411
			this.level().broadcastEntityEvent(this, (byte)35);
1412
		}
1413
1414
		return protection != null;
1415
	}
1416
1417
	public @Nullable DamageSource getLastDamageSource() {
1418
		return this.getLastDamageSource(40);
1419
	}
1420
1421
	public @Nullable DamageSource getLastDamageSource(final int damageSourceTimeout) {
1422
		return this.level().getGameTime() - this.lastDamageStamp > damageSourceTimeout ? null : this.lastDamageSource;
1423
	}
1424
1425
	protected void playHurtSound(final DamageSource source) {
1426
		this.makeSound(this.getHurtSound(source));
1427
	}
1428
1429
	public void makeSound(final @Nullable SoundEvent sound) {
1430
		if (sound != null) {
1431
			this.playSound(sound, this.getSoundVolume(), this.getVoicePitch());
1432
		}
1433
	}
1434
1435
	private void breakItem(final ItemStack itemStack) {
1436
		if (!itemStack.isEmpty()) {
1437
			Holder<SoundEvent> breakSound = itemStack.get(DataComponents.BREAK_SOUND);
1438
			if (breakSound != null && !this.isSilent()) {
1439
				this.level()
1440
					.playLocalSound(this.getX(), this.getY(), this.getZ(), breakSound.value(), this.getSoundSource(), 0.8F, 0.8F + this.random.nextFloat() * 0.4F, false);
1441
			}
1442
1443
			this.spawnItemParticles(itemStack, 5);
1444
		}
1445
	}
1446
1447
	public void die(final DamageSource source) {
1448
		if (!this.isRemoved() && !this.dead) {
1449
			Entity sourceEntity = source.getEntity();
1450
			LivingEntity killer = this.getKillCredit();
1451
			if (killer != null) {
1452
				killer.awardKillScore(this, source);
1453
			}
1454
1455
			if (this.isSleeping()) {
1456
				this.stopSleeping();
1457
			}
1458
1459
			this.stopUsingItem();
1460
			if (!this.level().isClientSide() && this.hasCustomName()) {
1461
				LOGGER.info("Named entity {} died: {}", this, this.getCombatTracker().getDeathMessage().getString());
1462
			}
1463
1464
			this.handleKillingBlow();
1465
			if (this.level() instanceof ServerLevel serverLevel) {
1466
				if (sourceEntity == null || sourceEntity.killedEntity(serverLevel, this, source)) {
1467
					this.gameEvent(GameEvent.ENTITY_DIE);
1468
					this.dropAllDeathLoot(serverLevel, source);
1469
					this.createWitherRose(killer);
1470
				}
1471
1472
				this.level().broadcastEntityEvent(this, (byte)3);
1473
			}
1474
1475
			this.setPose(Pose.DYING);
1476
		}
1477
	}
1478
1479
	protected void handleKillingBlow() {
1480
		this.dead = true;
1481
	}
1482
1483
	protected void createWitherRose(final @Nullable LivingEntity killer) {
1484
		if (this.level() instanceof ServerLevel serverLevel) {
1485
			boolean var6 = false;
1486
			if (killer instanceof WitherBoss) {
1487
				if (serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) {
1488
					BlockPos pos = this.blockPosition();
1489
					BlockState state = Blocks.WITHER_ROSE.defaultBlockState();
1490
					if (this.level().getBlockState(pos).isAir() && state.canSurvive(this.level(), pos)) {
1491
						this.level().setBlockAndUpdate(pos, state);
1492
						var6 = true;
1493
					}
1494
				}
1495
1496
				if (!var6) {
1497
					ItemEntity itemEntity = new ItemEntity(this.level(), this.getX(), this.getY(), this.getZ(), new ItemStack(Items.WITHER_ROSE));
1498
					this.level().addFreshEntity(itemEntity);
1499
				}
1500
			}
1501
		}
1502
	}
1503
1504
	protected void dropAllDeathLoot(final ServerLevel level, final DamageSource source) {
1505
		boolean playerKilled = this.lastHurtByPlayerMemoryTime > 0;
1506
		if (this.shouldDropLoot(level)) {
1507
			this.dropFromLootTable(level, source, playerKilled);
1508
			this.dropCustomDeathLoot(level, source, playerKilled);
1509
		}
1510
1511
		this.dropEquipment(level);
1512
		this.dropExperience(level, source.getEntity());
1513
	}
1514
1515
	protected void dropEquipment(final ServerLevel level) {
1516
	}
1517
1518
	protected void dropExperience(final ServerLevel level, final @Nullable Entity killer) {
1519
		if (!this.wasExperienceConsumed()
1520
			&& (this.isAlwaysExperienceDropper() || this.lastHurtByPlayerMemoryTime > 0 && this.shouldDropExperience() && level.getGameRules().get(GameRules.MOB_DROPS))
1521
			)
1522
		 {
1523
			ExperienceOrb.award(level, this.position(), this.getExperienceReward(level, killer));
1524
		}
1525
	}
1526
1527
	protected void dropCustomDeathLoot(final ServerLevel level, final DamageSource source, final boolean killedByPlayer) {
1528
	}
1529
1530
	public long getLootTableSeed() {
1531
		return 0L;
1532
	}
1533
1534
	protected float getKnockback(final Entity target, final DamageSource damageSource) {
1535
		float knockback = (float)this.getAttributeValue(Attributes.ATTACK_KNOCKBACK);
1536
		return this.level() instanceof ServerLevel level
1537
			? EnchantmentHelper.modifyKnockback(level, this.getWeaponItem(), target, damageSource, knockback) / 2.0F
1538
			: knockback / 2.0F;
1539
	}
1540
1541
	protected void dropFromLootTable(final ServerLevel level, final DamageSource source, final boolean playerKilled) {
1542
		Optional<ResourceKey<LootTable>> lootTable = this.getLootTable();
1543
		if (!lootTable.isEmpty()) {
1544
			this.dropFromLootTable(level, source, playerKilled, lootTable.get());
1545
		}
1546
	}
1547
1548
	public void dropFromLootTable(final ServerLevel level, final DamageSource source, final boolean playerKilled, final ResourceKey<LootTable> lootTable) {
1549
		this.dropFromLootTable(level, source, playerKilled, lootTable, itemStack -> this.spawnAtLocation(level, itemStack));
1550
	}
1551
1552
	public void dropFromLootTable(
1553
		final ServerLevel level,
1554
		final DamageSource source,
1555
		final boolean playerKilled,
1556
		final ResourceKey<LootTable> lootTable,
1557
		final Consumer<ItemStack> itemStackConsumer
1558
	) {
1559
		LootTable table = level.getServer().reloadableRegistries().getLootTable(lootTable);
1560
		LootParams.Builder builder = new LootParams.Builder(level)
1561
			.withParameter(LootContextParams.THIS_ENTITY, this)
1562
			.withParameter(LootContextParams.ORIGIN, this.position())
1563
			.withParameter(LootContextParams.DAMAGE_SOURCE, source)
1564
			.withOptionalParameter(LootContextParams.ATTACKING_ENTITY, source.getEntity())
1565
			.withOptionalParameter(LootContextParams.DIRECT_ATTACKING_ENTITY, source.getDirectEntity());
1566
		Player killerPlayer = this.getLastHurtByPlayer();
1567
		if (playerKilled && killerPlayer != null) {
1568
			builder = builder.withParameter(LootContextParams.LAST_DAMAGE_PLAYER, killerPlayer).withLuck(killerPlayer.getLuck());
1569
		}
1570
1571
		LootParams params = builder.create(LootContextParamSets.ENTITY);
1572
		table.getRandomItems(params, this.getLootTableSeed(), itemStackConsumer);
1573
	}
1574
1575
	public boolean dropFromEntityInteractLootTable(
1576
		final ServerLevel level,
1577
		final ResourceKey<LootTable> key,
1578
		final @Nullable Entity interactingEntity,
1579
		final ItemInstance tool,
1580
		final BiConsumer<ServerLevel, ItemStack> consumer
1581
	) {
1582
		return this.dropFromLootTable(
1583
			level,
1584
			key,
1585
			params -> params.withParameter(LootContextParams.TARGET_ENTITY, this)
1586
				.withOptionalParameter(LootContextParams.INTERACTING_ENTITY, interactingEntity)
1587
				.withParameter(LootContextParams.TOOL, tool)
1588
				.create(LootContextParamSets.ENTITY_INTERACT),
1589
			consumer
1590
		);
1591
	}
1592
1593
	public boolean dropFromGiftLootTable(final ServerLevel level, final ResourceKey<LootTable> key, final BiConsumer<ServerLevel, ItemStack> consumer) {
1594
		return this.dropFromLootTable(
1595
			level,
1596
			key,
1597
			params -> params.withParameter(LootContextParams.ORIGIN, this.position())
1598
				.withParameter(LootContextParams.THIS_ENTITY, this)
1599
				.create(LootContextParamSets.GIFT),
1600
			consumer
1601
		);
1602
	}
1603
1604
	protected void dropFromShearingLootTable(
1605
		final ServerLevel level, final ResourceKey<LootTable> key, final ItemInstance tool, final BiConsumer<ServerLevel, ItemStack> consumer
1606
	) {
1607
		this.dropFromLootTable(
1608
			level,
1609
			key,
1610
			params -> params.withParameter(LootContextParams.ORIGIN, this.position())
1611
				.withParameter(LootContextParams.THIS_ENTITY, this)
1612
				.withParameter(LootContextParams.TOOL, tool)
1613
				.create(LootContextParamSets.SHEARING),
1614
			consumer
1615
		);
1616
	}
1617
1618
	protected boolean dropFromLootTable(
1619
		final ServerLevel level,
1620
		final ResourceKey<LootTable> key,
1621
		final Function<LootParams.Builder, LootParams> paramsBuilder,
1622
		final BiConsumer<ServerLevel, ItemStack> consumer
1623
	) {
1624
		LootTable lootTable = level.getServer().reloadableRegistries().getLootTable(key);
1625
		LootParams params = paramsBuilder.apply(new LootParams.Builder(level));
1626
		List<ItemStack> drops = lootTable.getRandomItems(params);
1627
		if (!drops.isEmpty()) {
1628
			drops.forEach(stack -> consumer.accept(level, stack));
1629
			return true;
1630
		} else {
1631
			return false;
1632
		}
1633
	}
1634
1635
	public void knockback(double power, double xd, double zd, final DamageSource source, final float damage, final boolean comesFromEffect) {
1636
		power *= 1.0 - this.getAttributeValue(Attributes.KNOCKBACK_RESISTANCE);
1637
		if (!(power <= 0.0)) {
1638
			this.needsSync = true;
1639
			Vec3 deltaMovement = this.getDeltaMovement();
1640
1641
			while (xd * xd + zd * zd < 1.0E-5F) {
1642
				xd = (this.random.nextDouble() - this.random.nextDouble()) * 0.01;
1643
				zd = (this.random.nextDouble() - this.random.nextDouble()) * 0.01;
1644
			}
1645
1646
			Vec3 deltaVector = new Vec3(xd, 0.0, zd).normalize().scale(power);
1647
			this.setDeltaMovement(
1648
				deltaMovement.x / 2.0 - deltaVector.x,
1649
				this.onGround() ? Math.min(0.4, deltaMovement.y / 2.0 + power) : deltaMovement.y,
1650
				deltaMovement.z / 2.0 - deltaVector.z
1651
			);
1652
		}
1653
	}
1654
1655
	public void knockback(final double power, final double xd, final double zd, final DamageSource source, final float damage) {
1656
		this.knockback(power, xd, zd, source, damage, false);
1657
	}
1658
1659
	public void indicateDamage(final double xd, final double zd) {
1660
	}
1661
1662
	protected @Nullable SoundEvent getHurtSound(final DamageSource source) {
1663
		return SoundEvents.GENERIC_HURT;
1664
	}
1665
1666
	protected @Nullable SoundEvent getDeathSound() {
1667
		return SoundEvents.GENERIC_DEATH;
1668
	}
1669
1670
	private SoundEvent getFallDamageSound(final int dmg) {
1671
		return dmg > 4 ? this.getFallSounds().big() : this.getFallSounds().small();
1672
	}
1673
1674
	public void skipDropExperience() {
1675
		this.skipDropExperience = true;
1676
	}
1677
1678
	public boolean wasExperienceConsumed() {
1679
		return this.skipDropExperience;
1680
	}
1681
1682
	public float getHurtDir() {
1683
		return 0.0F;
1684
	}
1685
1686
	protected AABB getHitbox() {
1687
		AABB aabb = this.getBoundingBox();
1688
		Entity vehicle = this.getVehicle();
1689
		if (vehicle != null) {
1690
			Vec3 pos = vehicle.getPassengerRidingPosition(this);
1691
			return aabb.setMinY(Math.max(pos.y, aabb.minY));
1692
		} else {
1693
			return aabb;
1694
		}
1695
	}
1696
1697
	public Map<Enchantment, Set<EnchantmentLocationBasedEffect>> activeLocationDependentEnchantments(final EquipmentSlot slot) {
1698
		return this.activeLocationDependentEnchantments.computeIfAbsent(slot, s -> new Reference2ObjectArrayMap<>());
1699
	}
1700
1701
	public void postPiercingAttack() {
1702
		if (this.level() instanceof ServerLevel serverLevel) {
1703
			EnchantmentHelper.doPostPiercingAttackEffects(serverLevel, this);
1704
		}
1705
	}
1706
1707
	public LivingEntity.Fallsounds getFallSounds() {
1708
		return new LivingEntity.Fallsounds(SoundEvents.GENERIC_SMALL_FALL, SoundEvents.GENERIC_BIG_FALL);
1709
	}
1710
1711
	public Optional<BlockPos> getLastClimbablePos() {
1712
		return this.lastClimbablePos;
1713
	}
1714
1715
	public boolean onClimbable() {
1716
		if (this.isSpectator()) {
1717
			return false;
1718
		} else {
1719
			BlockPos ladderCheckPos = this.blockPosition();
1720
			BlockState state = this.getInBlockState();
1721
			if (this.isFallFlying() && state.is(BlockTags.CAN_GLIDE_THROUGH)) {
1722
				return false;
1723
			} else if (state.is(BlockTags.CLIMBABLE)) {
1724
				this.lastClimbablePos = Optional.of(ladderCheckPos);
1725
				return true;
1726
			} else if (state.getBlock() instanceof TrapDoorBlock && this.trapdoorUsableAsLadder(ladderCheckPos, state)) {
1727
				this.lastClimbablePos = Optional.of(ladderCheckPos);
1728
				return true;
1729
			} else {
1730
				return false;
1731
			}
1732
		}
1733
	}
1734
1735
	private boolean trapdoorUsableAsLadder(final BlockPos pos, final BlockState state) {
1736
		if (!state.getValue(TrapDoorBlock.OPEN)) {
1737
			return false;
1738
		}
1739
1740
		BlockState belowState = this.level().getBlockState(pos.below());
1741
		return belowState.is(Blocks.LADDER) && belowState.getValue(LadderBlock.FACING) == state.getValue(TrapDoorBlock.FACING);
1742
	}
1743
1744
	@Override
1745
	public boolean isAlive() {
1746
		return !this.isRemoved() && this.getHealth() > 0.0F;
1747
	}
1748
1749
	public boolean isLookingAtMe(
1750
		final LivingEntity target, final double coneSize, final boolean adjustForDistance, final boolean seeThroughTransparentBlocks, final double... gazeHeights
1751
	) {
1752
		Vec3 look = target.getViewVector(1.0F).normalize();
1753
1754
		for (double gazeHeight : gazeHeights) {
1755
			Vec3 dir = new Vec3(this.getX() - target.getX(), gazeHeight - target.getEyeY(), this.getZ() - target.getZ());
1756
			double dist = dir.length();
1757
			dir = dir.normalize();
1758
			double dot = look.dot(dir);
1759
			if (dot > 1.0 - coneSize / (adjustForDistance ? dist : 1.0)
1760
				&& target.hasLineOfSight(this, seeThroughTransparentBlocks ? ClipContext.Block.VISUAL : ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, gazeHeight)) {
1761
				return true;
1762
			}
1763
		}
1764
1765
		return false;
1766
	}
1767
1768
	@Override
1769
	public int getMaxFallDistance() {
1770
		return this.getComfortableFallDistance(0.0F);
1771
	}
1772
1773
	protected final int getComfortableFallDistance(final float allowedDamage) {
1774
		return Mth.floor(allowedDamage + 3.0F);
1775
	}
1776
1777
	@Override
1778
	public boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource) {
1779
		double effectiveFallDistance;
1780
		if (this.isIgnoringFallDamageFromCurrentImpulse()) {
1781
			effectiveFallDistance = Math.min(fallDistance, this.currentImpulseImpactPos.y - this.getY());
1782
			boolean hasLandedAboveCurrentImpulseImpactPosY = effectiveFallDistance <= 0.0;
1783
			if (hasLandedAboveCurrentImpulseImpactPosY) {
1784
				this.resetCurrentImpulseContext();
1785
			} else {
1786
				this.tryResetCurrentImpulseContext();
1787
			}
1788
		} else {
1789
			effectiveFallDistance = fallDistance;
1790
		}
1791
1792
		boolean damaged = super.causeFallDamage(effectiveFallDistance, damageModifier, damageSource);
1793
		int dmg = this.calculateFallDamage(effectiveFallDistance, damageModifier);
1794
		if (dmg > 0) {
1795
			this.resetCurrentImpulseContext();
1796
			this.playSound(this.getFallDamageSound(dmg), 1.0F, 1.0F);
1797
			this.playBlockFallSound();
1798
			this.hurt(damageSource, dmg);
1799
			return true;
1800
		} else {
1801
			return damaged;
1802
		}
1803
	}
1804
1805
	public void setIgnoreFallDamageFromCurrentImpulse(final boolean ignoreFallDamage, final Vec3 newImpulseImpactPos) {
1806
		if (ignoreFallDamage) {
1807
			this.applyPostImpulseGraceTime(40);
1808
			this.currentImpulseImpactPos = newImpulseImpactPos;
1809
		} else {
1810
			this.currentImpulseContextResetGraceTime = 0;
1811
		}
1812
	}
1813
1814
	public void applyPostImpulseGraceTime(final int ticks) {
1815
		this.currentImpulseContextResetGraceTime = Math.max(this.currentImpulseContextResetGraceTime, ticks);
1816
	}
1817
1818
	public boolean isIgnoringFallDamageFromCurrentImpulse() {
1819
		return this.currentImpulseImpactPos != null;
1820
	}
1821
1822
	public void tryResetCurrentImpulseContext() {
1823
		if (this.currentImpulseContextResetGraceTime == 0) {
1824
			this.resetCurrentImpulseContext();
1825
		}
1826
	}
1827
1828
	public boolean isInPostImpulseGraceTime() {
1829
		return this.currentImpulseContextResetGraceTime > 0;
1830
	}
1831
1832
	public void resetCurrentImpulseContext() {
1833
		this.currentImpulseContextResetGraceTime = 0;
1834
		this.currentImpulseImpactPos = null;
1835
	}
1836
1837
	protected int calculateFallDamage(final double fallDistance, final float damageModifier) {
1838
		if (this.is(EntityTypeTags.FALL_DAMAGE_IMMUNE)) {
1839
			return 0;
1840
		}
1841
1842
		double baseDamage = this.calculateFallPower(fallDistance);
1843
		return Mth.floor(baseDamage * damageModifier * this.getAttributeValue(Attributes.FALL_DAMAGE_MULTIPLIER));
1844
	}
1845
1846
	private double calculateFallPower(final double fallDistance) {
1847
		return fallDistance + 1.0E-6 - this.getAttributeValue(Attributes.SAFE_FALL_DISTANCE);
1848
	}
1849
1850
	protected void playBlockFallSound() {
1851
		if (!this.isSilent()) {
1852
			int xx = Mth.floor(this.getX());
1853
			int yy = Mth.floor(this.getY() - 0.2F);
1854
			int zz = Mth.floor(this.getZ());
1855
			BlockState state = this.level().getBlockState(new BlockPos(xx, yy, zz));
1856
			if (!state.isAir()) {
1857
				SoundType soundType = state.getSoundType();
1858
				this.playSound(soundType.getFallSound(), soundType.getVolume() * 0.5F, soundType.getPitch() * 0.75F);
1859
			}
1860
		}
1861
	}
1862
1863
	@Override
1864
	public void animateHurt(final float yaw) {
1865
		this.hurtDuration = 10;
1866
		this.hurtTime = this.hurtDuration;
1867
	}
1868
1869
	public int getArmorValue() {
1870
		return Mth.floor(this.getAttributeValue(Attributes.ARMOR));
1871
	}
1872
1873
	/**
1874
	 * Access widened by fabric-transitive-access-wideners-v1 to accessible
1875
	 */
1876
	public void hurtArmor(final DamageSource damageSource, final float damage) {
1877
	}
1878
1879
	/**
1880
	 * Access widened by fabric-transitive-access-wideners-v1 to accessible
1881
	 */
1882
	public void hurtHelmet(final DamageSource damageSource, final float damage) {
1883
	}
1884
1885
	protected void doHurtEquipment(final DamageSource damageSource, final float damage, final EquipmentSlot... slots) {
1886
		if (!(damage <= 0.0F)) {
1887
			int durabilityDamage = (int)Math.max(1.0F, damage / 4.0F);
1888
1889
			for (EquipmentSlot slot : slots) {
1890
				ItemStack itemStack = this.getItemBySlot(slot);
1891
				Equippable equippable = itemStack.get(DataComponents.EQUIPPABLE);
1892
				if (equippable != null && equippable.damageOnHurt() && itemStack.isDamageableItem() && itemStack.canBeHurtBy(damageSource)) {
1893
					itemStack.hurtAndBreak(durabilityDamage, this, slot);
1894
				}
1895
			}
1896
		}
1897
	}
1898
1899
	protected float getDamageAfterArmorAbsorb(final DamageSource damageSource, float damage) {
1900
		if (!damageSource.is(DamageTypeTags.BYPASSES_ARMOR)) {
1901
			this.hurtArmor(damageSource, damage);
1902
			damage = CombatRules.getDamageAfterAbsorb(this, damage, damageSource, this.getArmorValue(), (float)this.getAttributeValue(Attributes.ARMOR_TOUGHNESS));
1903
		}
1904
1905
		return damage;
1906
	}
1907
1908
	protected float getDamageAfterMagicAbsorb(final DamageSource damageSource, float damage) {
1909
		if (damageSource.is(DamageTypeTags.BYPASSES_EFFECTS)) {
1910
			return damage;
1911
		}
1912
1913
		if (this.hasEffect(MobEffects.RESISTANCE) && !damageSource.is(DamageTypeTags.BYPASSES_RESISTANCE)) {
1914
			int absorbValue = (this.getEffect(MobEffects.RESISTANCE).getAmplifier() + 1) * 5;
1915
			int absorb = 25 - absorbValue;
1916
			float v = damage * absorb;
1917
			float oldDamage = damage;
1918
			damage = Math.max(v / 25.0F, 0.0F);
1919
			float damageResisted = oldDamage - damage;
1920
			if (damageResisted > 0.0F && damageResisted < 3.4028235E37F) {
1921
				if (this instanceof ServerPlayer serverPlayer) {
1922
					serverPlayer.awardStat(Stats.DAMAGE_RESISTED, Math.round(damageResisted * 10.0F));
1923
				} else if (damageSource.getEntity() instanceof ServerPlayer) {
1924
					((ServerPlayer)damageSource.getEntity()).awardStat(Stats.DAMAGE_DEALT_RESISTED, Math.round(damageResisted * 10.0F));
1925
				}
1926
			}
1927
		}
1928
1929
		if (damage <= 0.0F) {
1930
			return 0.0F;
1931
		}
1932
1933
		if (damageSource.is(DamageTypeTags.BYPASSES_ENCHANTMENTS)) {
1934
			return damage;
1935
		}
1936
1937
		float enchantmentArmor;
1938
		if (this.level() instanceof ServerLevel serverLevel) {
1939
			enchantmentArmor = EnchantmentHelper.getDamageProtection(serverLevel, this, damageSource);
1940
		} else {
1941
			enchantmentArmor = 0.0F;
1942
		}
1943
1944
		if (enchantmentArmor > 0.0F) {
1945
			damage = CombatRules.getDamageAfterMagicAbsorb(damage, enchantmentArmor);
1946
		}
1947
1948
		return damage;
1949
	}
1950
1951
	protected void actuallyHurt(final ServerLevel level, final DamageSource source, float dmg) {
1952
		if (!this.isInvulnerableTo(level, source)) {
1953
			dmg = this.getDamageAfterArmorAbsorb(source, dmg);
1954
			dmg = this.getDamageAfterMagicAbsorb(source, dmg);
1955
			float originalDamage = dmg;
1956
			dmg = Math.max(dmg - this.getAbsorptionAmount(), 0.0F);
1957
			this.setAbsorptionAmount(this.getAbsorptionAmount() - (originalDamage - dmg));
1958
			float absorbedDamage = originalDamage - dmg;
1959
			if (absorbedDamage > 0.0F && absorbedDamage < 3.4028235E37F && source.getEntity() instanceof ServerPlayer serverPlayer) {
1960
				serverPlayer.awardStat(Stats.DAMAGE_DEALT_ABSORBED, Math.round(absorbedDamage * 10.0F));
1961
			}
1962
1963
			if (dmg != 0.0F) {
1964
				this.getCombatTracker().recordDamage(source, dmg);
1965
				this.setHealth(this.getHealth() - dmg);
1966
				this.setAbsorptionAmount(this.getAbsorptionAmount() - dmg);
1967
				this.gameEvent(GameEvent.ENTITY_DAMAGE);
1968
			}
1969
		}
1970
	}
1971
1972
	public CombatTracker getCombatTracker() {
1973
		return this.combatTracker;
1974
	}
1975
1976
	public @Nullable LivingEntity getKillCredit() {
1977
		if (this.lastHurtByPlayer != null) {
1978
			return this.lastHurtByPlayer.getEntity(this.level(), Player.class);
1979
		} else {
1980
			return this.lastHurtByMob != null ? this.lastHurtByMob.getEntity(this.level(), LivingEntity.class) : null;
1981
		}
1982
	}
1983
1984
	public final float getMaxHealth() {
1985
		return (float)this.getAttributeValue(Attributes.MAX_HEALTH);
1986
	}
1987
1988
	public final float getMaxAbsorption() {
1989
		return (float)this.getAttributeValue(Attributes.MAX_ABSORPTION);
1990
	}
1991
1992
	public final int getArrowCount() {
1993
		return this.entityData.get(DATA_ARROW_COUNT_ID);
1994
	}
1995
1996
	public final void setArrowCount(final int count) {
1997
		this.entityData.set(DATA_ARROW_COUNT_ID, count);
1998
	}
1999
2000
	public final int getStingerCount() {
2001
		return this.entityData.get(DATA_STINGER_COUNT_ID);
2002
	}
2003
2004
	public final void setStingerCount(final int count) {
2005
		this.entityData.set(DATA_STINGER_COUNT_ID, count);
2006
	}
2007
2008
	private int getModifiedSwingDuration(final SwingAnimation animation) {
2009
		int swingDuration = animation.duration();
2010
		if (MobEffectUtil.hasDigSpeed(this)) {
2011
			return swingDuration - (1 + MobEffectUtil.getDigSpeedAmplification(this));
2012
		} else {
2013
			return this.hasEffect(MobEffects.MINING_FATIGUE) ? swingDuration + (1 + this.getEffect(MobEffects.MINING_FATIGUE).getAmplifier()) * 2 : swingDuration;
2014
		}
2015
	}
2016
2017
	@Deprecated
2018
	public void swingAndResetAttackStrength(final InteractionHand hand, final SwingAnimation animation, final boolean sendToSwingingEntity) {
2019
		this.swing(hand, animation, sendToSwingingEntity);
2020
	}
2021
2022
	public boolean swing(final InteractionHand hand, final SwingAnimation animation, final boolean sendToSwingingEntity) {
2023
		if (this.swingState.startIfAble(hand, animation, this.getModifiedSwingDuration(animation))) {
2024
			if (this.level() instanceof ServerLevel serverLevel) {
2025
				ClientboundSwingAnimationPacket packet = new ClientboundSwingAnimationPacket(this, hand, animation);
2026
				ServerChunkCache chunkSource = serverLevel.getChunkSource();
2027
				if (sendToSwingingEntity) {
2028
					chunkSource.sendToTrackingPlayersAndSelf(this, packet);
2029
				} else {
2030
					chunkSource.sendToTrackingPlayers(this, packet);
2031
				}
2032
			}
2033
2034
			return true;
2035
		} else {
2036
			return false;
2037
		}
2038
	}
2039
2040
	@Override
2041
	public void handleDamageEvent(final DamageSource source) {
2042
		this.walkAnimation.setSpeed(1.5F);
2043
		this.damageCooldownTime = 20;
2044
		this.hurtDuration = 10;
2045
		this.hurtTime = this.hurtDuration;
2046
		SoundEvent hurtSound = this.getHurtSound(source);
2047
		if (hurtSound != null) {
2048
			this.playSound(hurtSound, this.getSoundVolume(), (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F);
2049
		}
2050
2051
		this.lastDamageSource = source;
2052
		this.lastDamageStamp = this.level().getGameTime();
2053
	}
2054
2055
	@Override
2056
	public void handleEntityEvent(final @EntityEvent.Value byte id) {
2057
		switch (id) {
2058
			case 2:
2059
				this.onKineticHit();
2060
				break;
2061
			case 3:
2062
				SoundEvent deathSound = this.getDeathSound();
2063
				if (deathSound != null) {
2064
					this.playSound(deathSound, this.getSoundVolume(), (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F);
2065
				}
2066
2067
				if (!(this instanceof Player)) {
2068
					this.setHealth(0.0F);
2069
					this.die(this.damageSources().generic());
2070
				}
2071
				break;
2072
			case 46:
2073
				int count = 128;
2074
2075
				for (int i = 0; i < 128; i++) {
2076
					double d = i / 127.0;
2077
					float xa = (this.random.nextFloat() - 0.5F) * 0.2F;
2078
					float ya = (this.random.nextFloat() - 0.5F) * 0.2F;
2079
					float za = (this.random.nextFloat() - 0.5F) * 0.2F;
2080
					double x = Mth.lerp(d, this.xo, this.getX()) + (this.random.nextDouble() - 0.5) * this.getBbWidth() * 2.0;
2081
					double y = Mth.lerp(d, this.yo, this.getY()) + this.random.nextDouble() * this.getBbHeight();
2082
					double z = Mth.lerp(d, this.zo, this.getZ()) + (this.random.nextDouble() - 0.5) * this.getBbWidth() * 2.0;
2083
					this.level().addParticle(ParticleTypes.PORTAL, x, y, z, xa, ya, za);
2084
				}
2085
				break;
2086
			case 47:
2087
				this.breakItem(this.getItemBySlot(EquipmentSlot.MAINHAND));
2088
				break;
2089
			case 48:
2090
				this.breakItem(this.getItemBySlot(EquipmentSlot.OFFHAND));
2091
				break;
2092
			case 49:
2093
				this.breakItem(this.getItemBySlot(EquipmentSlot.HEAD));
2094
				break;
2095
			case 50:
2096
				this.breakItem(this.getItemBySlot(EquipmentSlot.CHEST));
2097
				break;
2098
			case 51:
2099
				this.breakItem(this.getItemBySlot(EquipmentSlot.LEGS));
2100
				break;
2101
			case 52:
2102
				this.breakItem(this.getItemBySlot(EquipmentSlot.FEET));
2103
				break;
2104
			case 54:
2105
				HoneyBlock.showJumpParticles(this);
2106
				break;
2107
			case 55:
2108
				this.swapHandItems();
2109
				break;
2110
			case 60:
2111
				this.makePoofParticles();
2112
				break;
2113
			case 65:
2114
				this.breakItem(this.getItemBySlot(EquipmentSlot.BODY));
2115
				break;
2116
			case 67:
2117
				this.makeDrownParticles();
2118
				break;
2119
			case 68:
2120
				this.breakItem(this.getItemBySlot(EquipmentSlot.SADDLE));
2121
				break;
2122
			default:
2123
				super.handleEntityEvent(id);
2124
		}
2125
	}
2126
2127
	public float getTicksSinceLastKineticHitFeedback(final float partial) {
2128
		return this.lastKineticHitFeedbackTime < 0L ? 0.0F : (float)(this.level().getGameTime() - this.lastKineticHitFeedbackTime) + partial;
2129
	}
2130
2131
	public void makePoofParticles() {
2132
		for (int i = 0; i < 20; i++) {
2133
			double xa = this.random.nextGaussian() * 0.02;
2134
			double ya = this.random.nextGaussian() * 0.02;
2135
			double za = this.random.nextGaussian() * 0.02;
2136
			double dd = 10.0;
2137
			this.level().addParticle(ParticleTypes.POOF, this.getRandomX(1.0) - xa * 10.0, this.getRandomY() - ya * 10.0, this.getRandomZ(1.0) - za * 10.0, xa, ya, za);
2138
		}
2139
	}
2140
2141
	private void makeDrownParticles() {
2142
		Vec3 movement = this.getDeltaMovement();
2143
2144
		for (int i = 0; i < 8; i++) {
2145
			double offsetX = this.random.triangle(0.0, 1.0);
2146
			double offsetY = this.random.triangle(0.0, 1.0);
2147
			double offsetZ = this.random.triangle(0.0, 1.0);
2148
			this.level().addParticle(ParticleTypes.BUBBLE, this.getX() + offsetX, this.getY() + offsetY, this.getZ() + offsetZ, movement.x, movement.y, movement.z);
2149
		}
2150
	}
2151
2152
	private void onKineticHit() {
2153
		if (this.level().getGameTime() - this.lastKineticHitFeedbackTime > 10L) {
2154
			this.lastKineticHitFeedbackTime = this.level().getGameTime();
2155
			KineticWeapon kineticWeapon = this.useItem.get(DataComponents.KINETIC_WEAPON);
2156
			if (kineticWeapon != null) {
2157
				kineticWeapon.makeLocalHitSound(this);
2158
			}
2159
		}
2160
	}
2161
2162
	private void swapHandItems() {
2163
		ItemStack tmp = this.getItemBySlot(EquipmentSlot.OFFHAND);
2164
		this.setItemSlot(EquipmentSlot.OFFHAND, this.getItemBySlot(EquipmentSlot.MAINHAND));
2165
		this.setItemSlot(EquipmentSlot.MAINHAND, tmp);
2166
	}
2167
2168
	@Override
2169
	protected void onBelowWorld() {
2170
		this.hurt(this.damageSources().fellOutOfWorld(), 4.0F);
2171
	}
2172
2173
	@Override
2174
	protected double getEntityBounciness() {
2175
		return this.getAttributeValue(Attributes.BOUNCINESS);
2176
	}
2177
2178
	public @Nullable AttributeInstance getAttribute(final Holder<Attribute> attribute) {
2179
		return this.getAttributes().getInstance(attribute);
2180
	}
2181
2182
	public double getAttributeValue(final Holder<Attribute> attribute) {
2183
		return this.getAttributes().getValue(attribute);
2184
	}
2185
2186
	public double getAttributeBaseValue(final Holder<Attribute> attribute) {
2187
		return this.getAttributes().getBaseValue(attribute);
2188
	}
2189
2190
	public AttributeMap getAttributes() {
2191
		return this.attributes;
2192
	}
2193
2194
	public ItemStack getMainHandItem() {
2195
		return this.getItemBySlot(EquipmentSlot.MAINHAND);
2196
	}
2197
2198
	public ItemStack getOffhandItem() {
2199
		return this.getItemBySlot(EquipmentSlot.OFFHAND);
2200
	}
2201
2202
	public ItemStack getItemHeldByArm(final HumanoidArm arm) {
2203
		return this.getMainArm() == arm ? this.getMainHandItem() : this.getOffhandItem();
2204
	}
2205
2206
	@Override
2207
	public ItemStack getWeaponItem() {
2208
		return this.getMainHandItem();
2209
	}
2210
2211
	public AttackRange getAttackRangeWith(final ItemStack weaponItem) {
2212
		AttackRange attackRange = weaponItem.get(DataComponents.ATTACK_RANGE);
2213
		return attackRange != null ? attackRange : AttackRange.defaultFor(this);
2214
	}
2215
2216
	public ItemStack getActiveItem() {
2217
		if (this.isSpectator()) {
2218
			return ItemStack.EMPTY;
2219
		} else {
2220
			return this.isUsingItem() ? this.getUseItem() : this.getMainHandItem();
2221
		}
2222
	}
2223
2224
	public boolean isHolding(final Item item) {
2225
		return this.isHolding(heldItem -> heldItem.is(item));
2226
	}
2227
2228
	public boolean isHolding(final Predicate<ItemStack> itemPredicate) {
2229
		return itemPredicate.test(this.getMainHandItem()) || itemPredicate.test(this.getOffhandItem());
2230
	}
2231
2232
	public ItemStack getItemInHand(final InteractionHand hand) {
2233
		if (hand == InteractionHand.MAIN_HAND) {
2234
			return this.getItemBySlot(EquipmentSlot.MAINHAND);
2235
		} else if (hand == InteractionHand.OFF_HAND) {
2236
			return this.getItemBySlot(EquipmentSlot.OFFHAND);
2237
		} else {
2238
			throw new IllegalArgumentException("Invalid hand " + hand);
2239
		}
2240
	}
2241
2242
	public void setItemInHand(final InteractionHand hand, final ItemStack itemStack) {
2243
		if (hand == InteractionHand.MAIN_HAND) {
2244
			this.setItemSlot(EquipmentSlot.MAINHAND, itemStack);
2245
		} else {
2246
			if (hand != InteractionHand.OFF_HAND) {
2247
				throw new IllegalArgumentException("Invalid hand " + hand);
2248
			}
2249
2250
			this.setItemSlot(EquipmentSlot.OFFHAND, itemStack);
2251
		}
2252
	}
2253
2254
	public boolean hasItemInSlot(final EquipmentSlot slot) {
2255
		return !this.getItemBySlot(slot).isEmpty();
2256
	}
2257
2258
	public boolean canUseSlot(final EquipmentSlot slot) {
2259
		return true;
2260
	}
2261
2262
	public ItemStack getItemBySlot(final EquipmentSlot slot) {
2263
		return this.equipment.get(slot);
2264
	}
2265
2266
	public void setItemSlot(final EquipmentSlot slot, final ItemStack itemStack) {
2267
		this.onEquipItem(slot, this.equipment.set(slot, itemStack), itemStack);
2268
	}
2269
2270
	public float getArmorCoverPercentage() {
2271
		int total = 0;
2272
		int count = 0;
2273
2274
		for (EquipmentSlot slot : EquipmentSlotGroup.ARMOR) {
2275
			if (slot.getType() == EquipmentSlot.Type.HUMANOID_ARMOR) {
2276
				ItemStack itemStack = this.getItemBySlot(slot);
2277
				if (!itemStack.isEmpty()) {
2278
					count++;
2279
				}
2280
2281
				total++;
2282
			}
2283
		}
2284
2285
		return total > 0 ? (float)count / total : 0.0F;
2286
	}
2287
2288
	@Override
2289
	public void setSprinting(final boolean isSprinting) {
2290
		super.setSprinting(isSprinting);
2291
		AttributeInstance speed = this.getAttribute(Attributes.MOVEMENT_SPEED);
2292
		speed.removeModifier(SPEED_MODIFIER_SPRINTING.id());
2293
		if (isSprinting) {
2294
			speed.addTransientModifier(SPEED_MODIFIER_SPRINTING);
2295
		}
2296
	}
2297
2298
	protected float getSoundVolume() {
2299
		return 1.0F;
2300
	}
2301
2302
	public float getVoicePitch() {
2303
		return this.isBaby() ? (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.5F : (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F;
2304
	}
2305
2306
	protected boolean isImmobile() {
2307
		return this.isDeadOrDying();
2308
	}
2309
2310
	@Override
2311
	public void push(final Entity entity) {
2312
		if (!this.isSleeping()) {
2313
			super.push(entity);
2314
		}
2315
	}
2316
2317
	private void dismountVehicle(final Entity vehicle) {
2318
		Vec3 teleportTarget;
2319
		if (this.isRemoved()) {
2320
			teleportTarget = this.position();
2321
		} else if (!vehicle.isRemoved() && !this.level().getBlockState(vehicle.blockPosition()).is(BlockTags.PORTALS)) {
2322
			teleportTarget = vehicle.getDismountLocationForPassenger(this);
2323
		} else {
2324
			double maxY = Math.max(this.getY(), vehicle.getY());
2325
			teleportTarget = new Vec3(this.getX(), maxY, this.getZ());
2326
			boolean isSmall = this.getBbWidth() <= 4.0F && this.getBbHeight() <= 4.0F;
2327
			if (isSmall) {
2328
				double halfHeight = this.getBbHeight() / 2.0;
2329
				Vec3 center = teleportTarget.add(0.0, halfHeight, 0.0);
2330
				VoxelShape allowedCenters = Shapes.create(AABB.ofSize(center, this.getBbWidth(), this.getBbHeight(), this.getBbWidth()));
2331
				teleportTarget = this.level()
2332
					.findFreePosition(this, allowedCenters, center, this.getBbWidth(), this.getBbHeight(), this.getBbWidth())
2333
					.map(pos -> pos.add(0.0, -halfHeight, 0.0))
2334
					.orElse(teleportTarget);
2335
			}
2336
		}
2337
2338
		this.dismountTo(teleportTarget.x, teleportTarget.y, teleportTarget.z);
2339
	}
2340
2341
	@Override
2342
	public boolean shouldShowName() {
2343
		return this.isCustomNameVisible();
2344
	}
2345
2346
	protected float getJumpPower() {
2347
		return this.getJumpPower(1.0F);
2348
	}
2349
2350
	protected float getJumpPower(final float multiplier) {
2351
		return (float)this.getAttributeValue(Attributes.JUMP_STRENGTH) * multiplier * this.getBlockJumpFactor() + this.getJumpBoostPower();
2352
	}
2353
2354
	public float getJumpBoostPower() {
2355
		return this.hasEffect(MobEffects.JUMP_BOOST) ? 0.1F * (this.getEffect(MobEffects.JUMP_BOOST).getAmplifier() + 1.0F) : 0.0F;
2356
	}
2357
2358
	@VisibleForTesting
2359
	public void jumpFromGround() {
2360
		float jumpPower = this.getJumpPower();
2361
		if (!(jumpPower <= 1.0E-5F)) {
2362
			Vec3 movement = this.getDeltaMovement();
2363
			this.setDeltaMovement(movement.x, Math.max(jumpPower, movement.y), movement.z);
2364
			if (this.isSprinting()) {
2365
				float angle = this.getYRot() * (float) (Math.PI / 180.0);
2366
				this.addDeltaMovement(new Vec3(-Mth.sin(angle) * 0.2, 0.0, Mth.cos(angle) * 0.2));
2367
			}
2368
2369
			this.needsSync = true;
2370
		}
2371
	}
2372
2373
	protected void goDownInWater() {
2374
		this.setDeltaMovement(this.getDeltaMovement().add(0.0, -0.04F, 0.0));
2375
	}
2376
2377
	protected void jumpInLiquid(final TagKey<Fluid> type) {
2378
		this.setDeltaMovement(this.getDeltaMovement().add(0.0, 0.04F, 0.0));
2379
	}
2380
2381
	protected float getWaterSlowDown() {
2382
		return 0.8F;
2383
	}
2384
2385
	public boolean canStandOnFluid(final FluidState fluid) {
2386
		return false;
2387
	}
2388
2389
	@Override
2390
	protected double getDefaultGravity() {
2391
		return this.getAttributeValue(Attributes.GRAVITY);
2392
	}
2393
2394
	@Override
2395
	protected double getEffectiveGravity() {
2396
		boolean isFalling = this.getDeltaMovement().y <= 0.0;
2397
		return isFalling && this.hasEffect(MobEffects.SLOW_FALLING) ? Math.min(this.getGravity(), 0.01) : this.getGravity();
2398
	}
2399
2400
	public void travel(final Vec3 input) {
2401
		if (this.shouldTravelInFluid(this.level().getFluidState(this.blockPosition()))) {
2402
			this.travelInFluid(input);
2403
		} else if (this.isFallFlying()) {
2404
			this.travelFallFlying(input);
2405
		} else {
2406
			this.travelInAir(input);
2407
		}
2408
	}
2409
2410
	public VoxelShape getLiquidCollisionShape() {
2411
		return Shapes.empty();
2412
	}
2413
2414
	protected boolean shouldTravelInFluid(final FluidState fluidState) {
2415
		return this.isInLiquid() && this.isAffectedByFluids() && !this.canStandOnFluid(fluidState);
2416
	}
2417
2418
	protected void travelFlying(final Vec3 input, final float speed) {
2419
		this.travelFlying(input, 0.02F, 0.02F, speed);
2420
	}
2421
2422
	protected void travelFlying(final Vec3 input, final float waterSpeed, final float lavaSpeed, final float airSpeed) {
2423
		if (this.isInWater()) {
2424
			this.moveRelative(waterSpeed, input);
2425
			this.move(MoverType.SELF, this.getDeltaMovement());
2426
			this.setDeltaMovement(this.getDeltaMovement().scale(0.8F));
2427
		} else if (this.isInLava()) {
2428
			this.moveRelative(lavaSpeed, input);
2429
			this.move(MoverType.SELF, this.getDeltaMovement());
2430
			this.setDeltaMovement(this.getDeltaMovement().scale(0.5));
2431
		} else {
2432
			this.moveRelative(airSpeed, input);
2433
			this.move(MoverType.SELF, this.getDeltaMovement());
2434
			this.setDeltaMovement(this.getDeltaMovement().scale(0.91F));
2435
		}
2436
	}
2437
2438
	private void travelInAir(final Vec3 input) {
2439
		BlockPos posBelow = this.getBlockPosBelowThatAffectsMyMovement();
2440
		float blockFriction = this.onGround()
2441
			? computeModifiedFriction(this.level().getBlockState(posBelow).getBlock().getFriction(), (float)this.getAttributeValue(Attributes.FRICTION_MODIFIER))
2442
			: 1.0F;
2443
		Vec3 movement = this.handleRelativeFrictionAndCalculateMovement(input, blockFriction);
2444
		double movementY = movement.y;
2445
		MobEffectInstance levitationEffect = this.getEffect(MobEffects.LEVITATION);
2446
		if (levitationEffect != null) {
2447
			movementY += (0.05 * (levitationEffect.getAmplifier() + 1) - movement.y) * 0.2;
2448
		} else if (!this.level().isClientSide() || this.level().hasChunkAt(posBelow)) {
2449
			movementY -= this.getEffectiveGravity();
2450
		} else if (this.getY() > this.level().getMinY()) {
2451
			movementY = -0.1;
2452
		} else {
2453
			movementY = 0.0;
2454
		}
2455
2456
		if (this.shouldDiscardFriction()) {
2457
			this.setDeltaMovement(movement.x, movementY, movement.z);
2458
		} else {
2459
			float entityAirDragModifier = (float)this.getAttributeValue(Attributes.AIR_DRAG_MODIFIER);
2460
			float airDrag = computeModifiedFriction(0.91F, entityAirDragModifier);
2461
			float friction = blockFriction * airDrag;
2462
			float verticalFriction = this.omnidirectionalAirMover() ? airDrag : computeModifiedFriction(0.98F, entityAirDragModifier);
2463
			this.setDeltaMovement(movement.x * friction, movementY * verticalFriction, movement.z * friction);
2464
		}
2465
	}
2466
2467
	@Override
2468
	protected float getAirDrag() {
2469
		return computeModifiedFriction(this.omnidirectionalAirMover() ? 0.91F : 0.98F, (float)this.getAttributeValue(Attributes.AIR_DRAG_MODIFIER));
2470
	}
2471
2472
	protected void travelInFluid(final Vec3 input) {
2473
		boolean isFalling = this.getDeltaMovement().y <= 0.0;
2474
		double oldY = this.getY();
2475
		double baseGravity = this.getEffectiveGravity();
2476
		if (this.isInWater()) {
2477
			this.travelInWater(input, baseGravity, isFalling, oldY);
2478
		} else {
2479
			this.travelInLava(input, baseGravity, isFalling, oldY);
2480
		}
2481
2482
		this.floatInLiquidWhileRidden(FluidTags.ENTITY_FLOATABLE);
2483
	}
2484
2485
	protected void travelInWater(final Vec3 input, final double baseGravity, final boolean isFalling, final double oldY) {
2486
		float slowDown = this.isSprinting() ? 0.9F : this.getWaterSlowDown();
2487
		float speed = 0.02F;
2488
		float waterWalker = (float)this.getAttributeValue(Attributes.WATER_MOVEMENT_EFFICIENCY);
2489
		if (!this.onGround()) {
2490
			waterWalker *= 0.5F;
2491
		}
2492
2493
		if (waterWalker > 0.0F) {
2494
			slowDown += (0.54600006F - slowDown) * waterWalker;
2495
			speed += (this.getSpeed() - speed) * waterWalker;
2496
		}
2497
2498
		if (this.hasEffect(MobEffects.DOLPHINS_GRACE)) {
2499
			slowDown = 0.96F;
2500
		}
2501
2502
		this.moveRelative(speed, input);
2503
		this.move(MoverType.SELF, this.getDeltaMovement());
2504
		Vec3 movement = this.getDeltaMovement();
2505
		if (this.horizontalCollision && this.onClimbable()) {
2506
			movement = new Vec3(movement.x, 0.2, movement.z);
2507
		}
2508
2509
		movement = movement.multiply(slowDown, 0.8F, slowDown);
2510
		this.setDeltaMovement(this.getFluidFallingAdjustedMovement(baseGravity, isFalling, movement));
2511
		this.jumpOutOfFluid(oldY);
2512
	}
2513
2514
	protected boolean isInShallowFluid(final TagKey<Fluid> fluidTag) {
2515
		return this.getFluidHeight(fluidTag) <= this.getFluidJumpThreshold();
2516
	}
2517
2518
	private void travelInLava(final Vec3 input, final double baseGravity, final boolean isFalling, final double oldY) {
2519
		this.moveRelative(0.02F, input);
2520
		this.move(MoverType.SELF, this.getDeltaMovement());
2521
		if (this.isInShallowFluid(FluidTags.LAVA)) {
2522
			this.setDeltaMovement(this.getDeltaMovement().multiply(0.5, 0.8F, 0.5));
2523
			Vec3 movement = this.getFluidFallingAdjustedMovement(baseGravity, isFalling, this.getDeltaMovement());
2524
			this.setDeltaMovement(movement);
2525
		} else {
2526
			this.setDeltaMovement(this.getDeltaMovement().scale(0.5));
2527
		}
2528
2529
		if (baseGravity != 0.0) {
2530
			this.setDeltaMovement(this.getDeltaMovement().add(0.0, -baseGravity / 4.0, 0.0));
2531
		}
2532
2533
		this.jumpOutOfFluid(oldY);
2534
	}
2535
2536
	private void jumpOutOfFluid(final double oldY) {
2537
		Vec3 movement = this.getDeltaMovement();
2538
		if (this.horizontalCollision && this.isFree(movement.x, movement.y + 0.6F - this.getY() + oldY, movement.z)) {
2539
			this.setDeltaMovement(movement.x, 0.3F, movement.z);
2540
		}
2541
	}
2542
2543
	private void floatInLiquidWhileRidden(final TagKey<Fluid> fluidTag) {
2544
		if (this.isVehicle() && this.is(EntityTypeTags.CAN_FLOAT_WHILE_RIDDEN) && this.isInFluidDeeperThan(this.getFluidJumpThreshold(), fluidTag)) {
2545
			this.setDeltaMovement(this.getDeltaMovement().add(0.0, 0.04F, 0.0));
2546
		}
2547
	}
2548
2549
	public boolean isInFluidDeeperThan(final double depth, final TagKey<Fluid> fluidTag) {
2550
		return this.getFluidHeight(fluidTag) > depth;
2551
	}
2552
2553
	private void travelFallFlying(final Vec3 input) {
2554
		if (this.onClimbable()) {
2555
			this.travelInAir(input);
2556
			this.stopFallFlying();
2557
		} else {
2558
			Vec3 lastMovement = this.getDeltaMovement();
2559
			double lastSpeed = lastMovement.horizontalDistance();
2560
			this.setDeltaMovement(this.updateFallFlyingMovement(lastMovement));
2561
			this.move(MoverType.SELF, this.getDeltaMovement());
2562
			if (!this.level().isClientSide()) {
2563
				double newSpeed = this.getDeltaMovement().horizontalDistance();
2564
				this.handleFallFlyingCollisions(lastSpeed, newSpeed);
2565
			}
2566
		}
2567
	}
2568
2569
	public void stopFallFlying() {
2570
		this.setSharedFlag(7, true);
2571
		this.setSharedFlag(7, false);
2572
	}
2573
2574
	private Vec3 updateFallFlyingMovement(Vec3 movement) {
2575
		Vec3 lookAngle = this.getLookAngle();
2576
		float leanAngle = this.getXRot() * (float) (Math.PI / 180.0);
2577
		double lookHorLength = Math.sqrt(lookAngle.x * lookAngle.x + lookAngle.z * lookAngle.z);
2578
		double moveHorLength = movement.horizontalDistance();
2579
		double gravity = this.getEffectiveGravity();
2580
		double liftForce = Mth.square(Math.cos(leanAngle));
2581
		movement = movement.add(0.0, gravity * (-1.0 + liftForce * 0.75), 0.0);
2582
		if (movement.y < 0.0 && lookHorLength > 0.0) {
2583
			double convert = movement.y * -0.1 * liftForce;
2584
			movement = movement.add(lookAngle.x * convert / lookHorLength, convert, lookAngle.z * convert / lookHorLength);
2585
		}
2586
2587
		if (leanAngle < 0.0F && lookHorLength > 0.0) {
2588
			double convert = moveHorLength * -Mth.sin(leanAngle) * 0.04;
2589
			movement = movement.add(-lookAngle.x * convert / lookHorLength, convert * 3.2, -lookAngle.z * convert / lookHorLength);
2590
		}
2591
2592
		if (lookHorLength > 0.0) {
2593
			movement = movement.add(
2594
				(lookAngle.x / lookHorLength * moveHorLength - movement.x) * 0.1, 0.0, (lookAngle.z / lookHorLength * moveHorLength - movement.z) * 0.1
2595
			);
2596
		}
2597
2598
		return movement.multiply(0.99F, 0.98F, 0.99F);
2599
	}
2600
2601
	private void handleFallFlyingCollisions(final double moveHorLength, final double newMoveHorLength) {
2602
		if (this.horizontalCollision) {
2603
			double diff = moveHorLength - newMoveHorLength;
2604
			float dmg = (float)(diff * 10.0 - 3.0);
2605
			if (dmg > 0.0F) {
2606
				this.playSound(this.getFallDamageSound((int)dmg), 1.0F, 1.0F);
2607
				this.hurt(this.damageSources().flyIntoWall(), dmg);
2608
			}
2609
		}
2610
	}
2611
2612
	private void travelRidden(final Player controller, final Vec3 selfInput) {
2613
		Vec3 riddenInput = this.getRiddenInput(controller, selfInput);
2614
		this.tickRidden(controller, riddenInput);
2615
		if (this.canSimulateMovement()) {
2616
			this.setSpeed(this.getRiddenSpeed(controller));
2617
			this.travel(riddenInput);
2618
		} else {
2619
			this.setDeltaMovement(Vec3.ZERO);
2620
		}
2621
	}
2622
2623
	protected void tickRidden(final Player controller, final Vec3 riddenInput) {
2624
	}
2625
2626
	protected Vec3 getRiddenInput(final Player controller, final Vec3 selfInput) {
2627
		return selfInput;
2628
	}
2629
2630
	protected float getRiddenSpeed(final Player controller) {
2631
		return this.getSpeed();
2632
	}
2633
2634
	public void calculateEntityAnimation(final boolean useY) {
2635
		float distance = (float)Mth.length(this.getX() - this.xo, useY ? this.getY() - this.yo : 0.0, this.getZ() - this.zo);
2636
		if (!this.isPassenger() && this.isAlive()) {
2637
			this.updateWalkAnimation(distance);
2638
		} else {
2639
			this.walkAnimation.stop();
2640
		}
2641
	}
2642
2643
	protected void updateWalkAnimation(final float distance) {
2644
		float targetSpeed = Math.min(distance * 4.0F, 1.0F);
2645
		this.walkAnimation.update(targetSpeed, 0.4F, this.isBaby() ? 3.0F : 1.0F);
2646
	}
2647
2648
	private Vec3 handleRelativeFrictionAndCalculateMovement(final Vec3 input, final float friction) {
2649
		this.moveRelative(this.getFrictionInfluencedSpeed(friction), input);
2650
		this.setDeltaMovement(this.handleOnClimbable(this.getDeltaMovement()));
2651
		this.move(MoverType.SELF, this.getDeltaMovement());
2652
		Vec3 movement = this.getDeltaMovement();
2653
		if ((this.horizontalCollision || this.jumping) && (this.onClimbable() || this.wasInPowderSnow && PowderSnowBlock.canEntityWalkOnPowderSnow(this))) {
2654
			movement = new Vec3(movement.x, 0.2, movement.z);
2655
		}
2656
2657
		return movement;
2658
	}
2659
2660
	public Vec3 getFluidFallingAdjustedMovement(final double baseGravity, final boolean isFalling, final Vec3 movement) {
2661
		if (baseGravity != 0.0 && !this.isSprinting()) {
2662
			double yd;
2663
			if (isFalling && Math.abs(movement.y - 0.005) >= 0.003 && Math.abs(movement.y - baseGravity / 16.0) < 0.003) {
2664
				yd = -0.003;
2665
			} else {
2666
				yd = movement.y - baseGravity / 16.0;
2667
			}
2668
2669
			return new Vec3(movement.x, yd, movement.z);
2670
		} else {
2671
			return movement;
2672
		}
2673
	}
2674
2675
	private Vec3 handleOnClimbable(Vec3 delta) {
2676
		if (this.onClimbable()) {
2677
			this.resetFallDistance();
2678
			float max = 0.15F;
2679
			double xd = Mth.clamp(delta.x, -0.15F, 0.15F);
2680
			double zd = Mth.clamp(delta.z, -0.15F, 0.15F);
2681
			double yd = Math.max(delta.y, -0.15F);
2682
			if (yd < 0.0 && !this.getInBlockState().is(Blocks.SCAFFOLDING) && this.isSuppressingSlidingDownLadder() && this instanceof Player) {
2683
				yd = 0.0;
2684
			}
2685
2686
			delta = new Vec3(xd, yd, zd);
2687
		}
2688
2689
		return delta;
2690
	}
2691
2692
	private float getFrictionInfluencedSpeed(final float blockFriction) {
2693
		if (this.onGround()) {
2694
			return blockFriction > 0.6 ? this.getSpeed() * (0.21600002F / (blockFriction * blockFriction * blockFriction)) : this.getSpeed();
2695
		} else {
2696
			return this.getFlyingSpeed();
2697
		}
2698
	}
2699
2700
	protected float getFlyingSpeed() {
2701
		return this.getControllingPassenger() instanceof Player ? this.getSpeed() * 0.1F : 0.02F;
2702
	}
2703
2704
	public float getSpeed() {
2705
		return this.speed;
2706
	}
2707
2708
	public void setSpeed(final float speed) {
2709
		this.speed = speed;
2710
	}
2711
2712
	public boolean doHurtTarget(final ServerLevel level, final Entity target) {
2713
		this.setLastHurtMob(target);
2714
		return false;
2715
	}
2716
2717
	public void causeExtraKnockback(
2718
		final Entity target, final float knockback, final Vec3 oldMovement, final DamageSource damageSource, final float damage, final boolean comesFromEffect
2719
	) {
2720
		if (knockback > 0.0F && target instanceof LivingEntity livingTarget) {
2721
			livingTarget.knockback(
2722
				knockback, Mth.sin(this.getYRot() * (float) (Math.PI / 180.0)), -Mth.cos(this.getYRot() * (float) (Math.PI / 180.0)), damageSource, damage, comesFromEffect
2723
			);
2724
			this.setDeltaMovement(this.getDeltaMovement().multiply(0.6, 1.0, 0.6));
2725
		}
2726
	}
2727
2728
	protected void playAttackSound() {
2729
	}
2730
2731
	@Override
2732
	public void tick() {
2733
		super.tick();
2734
		this.updatingUsingItem();
2735
		this.updateSwimAmount();
2736
		if (!this.level().isClientSide()) {
2737
			int arrowCount = this.getArrowCount();
2738
			if (arrowCount > 0) {
2739
				if (this.removeArrowTime <= 0) {
2740
					this.removeArrowTime = 20 * (30 - arrowCount);
2741
				}
2742
2743
				this.removeArrowTime--;
2744
				if (this.removeArrowTime <= 0) {
2745
					this.setArrowCount(arrowCount - 1);
2746
				}
2747
			}
2748
2749
			int stingerCount = this.getStingerCount();
2750
			if (stingerCount > 0) {
2751
				if (this.removeStingerTime <= 0) {
2752
					this.removeStingerTime = 20 * (30 - stingerCount);
2753
				}
2754
2755
				this.removeStingerTime--;
2756
				if (this.removeStingerTime <= 0) {
2757
					this.setStingerCount(stingerCount - 1);
2758
				}
2759
			}
2760
2761
			this.detectEquipmentUpdates();
2762
			if (this.tickCount % 20 == 0) {
2763
				this.getCombatTracker().recheckStatus();
2764
			}
2765
2766
			if (this.isSleeping() && (!this.canInteractWithLevel() || !this.checkBedExists())) {
2767
				this.stopSleeping();
2768
			}
2769
		}
2770
2771
		if (!this.isRemoved()) {
2772
			this.aiStep();
2773
		}
2774
2775
		double xd = this.getX() - this.xo;
2776
		double zd = this.getZ() - this.zo;
2777
		float sideDist = (float)(xd * xd + zd * zd);
2778
		float yBodyRotT = this.yBodyRot;
2779
		if (sideDist > 0.0025000002F) {
2780
			float walkDirection = (float)Mth.atan2(zd, xd) * (180.0F / (float)Math.PI) - 90.0F;
2781
			float diffBetweenDirectionAndFacing = Mth.abs(Mth.wrapDegrees(this.getYRot()) - walkDirection);
2782
			if (95.0F < diffBetweenDirectionAndFacing && diffBetweenDirectionAndFacing < 265.0F) {
2783
				yBodyRotT = walkDirection - 180.0F;
2784
			} else {
2785
				yBodyRotT = walkDirection;
2786
			}
2787
		}
2788
2789
		if (this.swingState.animation > 0.0F) {
2790
			yBodyRotT = this.getYRot();
2791
		}
2792
2793
		ProfilerFiller profiler = Profiler.get();
2794
		profiler.push("headTurn");
2795
		this.tickHeadTurn(yBodyRotT);
2796
		profiler.pop();
2797
		profiler.push("rangeChecks");
2798
2799
		while (this.getYRot() - this.yRotO < -180.0F) {
2800
			this.yRotO -= 360.0F;
2801
		}
2802
2803
		while (this.getYRot() - this.yRotO >= 180.0F) {
2804
			this.yRotO += 360.0F;
2805
		}
2806
2807
		while (this.yBodyRot - this.yBodyRotO < -180.0F) {
2808
			this.yBodyRotO -= 360.0F;
2809
		}
2810
2811
		while (this.yBodyRot - this.yBodyRotO >= 180.0F) {
2812
			this.yBodyRotO += 360.0F;
2813
		}
2814
2815
		while (this.getXRot() - this.xRotO < -180.0F) {
2816
			this.xRotO -= 360.0F;
2817
		}
2818
2819
		while (this.getXRot() - this.xRotO >= 180.0F) {
2820
			this.xRotO += 360.0F;
2821
		}
2822
2823
		while (this.yHeadRot - this.yHeadRotO < -180.0F) {
2824
			this.yHeadRotO -= 360.0F;
2825
		}
2826
2827
		while (this.yHeadRot - this.yHeadRotO >= 180.0F) {
2828
			this.yHeadRotO += 360.0F;
2829
		}
2830
2831
		profiler.pop();
2832
		if (this.isFallFlying()) {
2833
			this.fallFlyTicks++;
2834
		} else {
2835
			this.fallFlyTicks = 0;
2836
		}
2837
2838
		if (this.isSleeping()) {
2839
			this.setXRot(0.0F);
2840
		}
2841
2842
		this.refreshDirtyAttributes();
2843
		this.elytraAnimationState.tick();
2844
		if (this.currentImpulseContextResetGraceTime > 0) {
2845
			this.currentImpulseContextResetGraceTime--;
2846
		}
2847
	}
2848
2849
	public boolean wasRecentlyStabbed(final Entity target, final int allowedTime) {
2850
		if (this.recentKineticEnemies == null) {
2851
			return false;
2852
		} else {
2853
			return this.recentKineticEnemies.containsKey(target) ? this.level().getGameTime() - this.recentKineticEnemies.getLong(target) < allowedTime : false;
2854
		}
2855
	}
2856
2857
	public void rememberStabbedEntity(final Entity target) {
2858
		if (this.recentKineticEnemies != null) {
2859
			this.recentKineticEnemies.put(target, this.level().getGameTime());
2860
		}
2861
	}
2862
2863
	public int stabbedEntities(final Predicate<Entity> filter) {
2864
		return this.recentKineticEnemies == null ? 0 : (int)this.recentKineticEnemies.keySet().stream().filter(filter).count();
2865
	}
2866
2867
	public boolean stabAttack(
2868
		final EquipmentSlot weaponSlot, final Entity target, final float baseDamage, final boolean dealsDamage, final boolean dealsKnockback, final boolean dismounts
2869
	) {
2870
		if (!(this.level() instanceof ServerLevel serverLevel)) {
2871
			return false;
2872
		} else {
2873
			ItemStack weaponItem = this.getItemBySlot(weaponSlot);
2874
			DamageSource damageSource = weaponItem.getDamageSource(this);
2875
			float postEnchantmentDamage = EnchantmentHelper.modifyDamage(serverLevel, weaponItem, target, damageSource, baseDamage);
2876
			Vec3 oldMovement = target.getDeltaMovement();
2877
			boolean affected = dealsKnockback;
2878
			boolean dealtDamage = dealsDamage && target.hurtServer(serverLevel, damageSource, postEnchantmentDamage);
2879
			affected |= dealtDamage;
2880
			if (dealsKnockback) {
2881
				this.causeExtraKnockback(target, 0.4F, oldMovement, damageSource, postEnchantmentDamage, false);
2882
				this.causeExtraKnockback(target, this.getKnockback(target, damageSource), oldMovement, damageSource, postEnchantmentDamage, true);
2883
			}
2884
2885
			if (dismounts && target.isPassenger() && !target.is(EntityTypeTags.CANNOT_BE_DISMOUNTED_BY_ITEM_USAGE)) {
2886
				affected = true;
2887
				target.stopRiding();
2888
			}
2889
2890
			if (target instanceof LivingEntity livingTarget) {
2891
				weaponItem.hurtEnemy(livingTarget, this);
2892
			}
2893
2894
			if (dealtDamage) {
2895
				EnchantmentHelper.doPostAttackEffects(serverLevel, target, damageSource);
2896
			}
2897
2898
			if (!affected) {
2899
				return false;
2900
			}
2901
2902
			this.setLastHurtMob(target);
2903
			this.playAttackSound();
2904
			return true;
2905
		}
2906
	}
2907
2908
	public void onAttack() {
2909
	}
2910
2911
	private void detectEquipmentUpdates() {
2912
		Map<EquipmentSlot, ItemStack> changedItems = this.collectEquipmentChanges(this.lastEquipmentItems);
2913
		if (changedItems != null) {
2914
			this.handleHandSwap(changedItems);
2915
			if (!changedItems.isEmpty()) {
2916
				this.handleEquipmentChanges(changedItems);
2917
			}
2918
		}
2919
	}
2920
2921
	protected @Nullable Map<EquipmentSlot, ItemStack> collectEquipmentChanges(final Map<EquipmentSlot, ItemStack> lastEquipmentItems) {
2922
		Map<EquipmentSlot, ItemStack> changedItems = null;
2923
2924
		for (EquipmentSlot slot : EquipmentSlot.VALUES) {
2925
			ItemStack previous = lastEquipmentItems.get(slot);
2926
			ItemStack current = this.getItemBySlot(slot);
2927
			if (this.equipmentHasChanged(previous, current)) {
2928
				if (changedItems == null) {
2929
					changedItems = Maps.newEnumMap(EquipmentSlot.class);
2930
				}
2931
2932
				changedItems.put(slot, current);
2933
				AttributeMap attributes = this.getAttributes();
2934
				if (!previous.isEmpty()) {
2935
					this.stopLocationBasedEffects(previous, slot, attributes);
2936
				}
2937
			}
2938
		}
2939
2940
		if (changedItems != null) {
2941
			for (Entry<EquipmentSlot, ItemStack> entry : changedItems.entrySet()) {
2942
				EquipmentSlot slot = entry.getKey();
2943
				ItemStack current = entry.getValue();
2944
				if (!current.isEmpty() && !current.isBroken()) {
2945
					current.forEachModifier(slot, (attribute, modifier) -> {
2946
						AttributeInstance instance = this.attributes.getInstance(attribute);
2947
						if (instance != null) {
2948
							instance.removeModifier(modifier.id());
2949
							instance.addTransientModifier(modifier);
2950
						}
2951
					});
2952
					if (this.level() instanceof ServerLevel serverLevel) {
2953
						EnchantmentHelper.runLocationChangedEffects(serverLevel, current, this, slot);
2954
					}
2955
				}
2956
			}
2957
		}
2958
2959
		return changedItems;
2960
	}
2961
2962
	public boolean equipmentHasChanged(final ItemStack previous, final ItemStack current) {
2963
		return !ItemStack.matches(current, previous);
2964
	}
2965
2966
	private void handleHandSwap(final Map<EquipmentSlot, ItemStack> changedItems) {
2967
		ItemStack currentMainHand = changedItems.get(EquipmentSlot.MAINHAND);
2968
		ItemStack currentOffHand = changedItems.get(EquipmentSlot.OFFHAND);
2969
		if (currentMainHand != null
2970
			&& currentOffHand != null
2971
			&& ItemStack.matches(currentMainHand, this.lastEquipmentItems.get(EquipmentSlot.OFFHAND))
2972
			&& ItemStack.matches(currentOffHand, this.lastEquipmentItems.get(EquipmentSlot.MAINHAND))) {
2973
			((ServerLevel)this.level()).getChunkSource().sendToTrackingPlayers(this, new ClientboundEntityEventPacket(this, (byte)55));
2974
			changedItems.remove(EquipmentSlot.MAINHAND);
2975
			changedItems.remove(EquipmentSlot.OFFHAND);
2976
			this.lastEquipmentItems.put(EquipmentSlot.MAINHAND, currentMainHand.copy());
2977
			this.lastEquipmentItems.put(EquipmentSlot.OFFHAND, currentOffHand.copy());
2978
		}
2979
	}
2980
2981
	private void handleEquipmentChanges(final Map<EquipmentSlot, ItemStack> changedItems) {
2982
		List<Pair<EquipmentSlot, ItemStack>> itemsToSend = Lists.newArrayListWithCapacity(changedItems.size());
2983
		changedItems.forEach((slot, newItem) -> {
2984
			ItemStack newItemToStore = newItem.copy();
2985
			itemsToSend.add(Pair.of(slot, newItemToStore));
2986
			this.lastEquipmentItems.put(slot, newItemToStore);
2987
		});
2988
		this.updatePlayersWithNewEquipment((ServerLevel)this.level(), itemsToSend);
2989
	}
2990
2991
	private void updatePlayersWithNewEquipment(final ServerLevel level, final List<Pair<EquipmentSlot, ItemStack>> itemsToSend) {
2992
		level.getChunkSource().sendToTrackingPlayers(this, new ClientboundSetEquipmentPacket(this.getId(), itemsToSend));
2993
	}
2994
2995
	protected void tickHeadTurn(final float yBodyRotT) {
2996
		float yBodyRotD = Mth.wrapDegrees(yBodyRotT - this.yBodyRot);
2997
		this.yBodyRot += yBodyRotD * 0.3F;
2998
		float headDiff = Mth.wrapDegrees(this.getYRot() - this.yBodyRot);
2999
		float maxHeadRotation = this.getMaxHeadRotationRelativeToBody();
3000
		if (Math.abs(headDiff) > maxHeadRotation) {
3001
			this.yBodyRot = this.yBodyRot + (headDiff - Mth.sign(headDiff) * maxHeadRotation);
3002
		}
3003
	}
3004
3005
	protected float getMaxHeadRotationRelativeToBody() {
3006
		return 50.0F;
3007
	}
3008
3009
	public void aiStep() {
3010
		if (this.noJumpDelay > 0) {
3011
			this.noJumpDelay--;
3012
		}
3013
3014
		if (!this.isInterpolating() && !this.canSimulateMovement()) {
3015
			this.setDeltaMovement(this.getDeltaMovement().scale(0.98));
3016
		}
3017
3018
		if (this.lerpHeadSteps > 0) {
3019
			this.lerpHeadRotationStep(this.lerpHeadSteps, this.lerpYHeadRot);
3020
			this.lerpHeadSteps--;
3021
		}
3022
3023
		this.equipment.tick(this);
3024
		Vec3 movement = this.getDeltaMovement();
3025
		double dx = movement.x;
3026
		double dy = movement.y;
3027
		double dz = movement.z;
3028
		if (this.is(EntityTypes.PLAYER)) {
3029
			if (movement.horizontalDistanceSqr() < 9.0E-6) {
3030
				dx = 0.0;
3031
				dz = 0.0;
3032
			}
3033
		} else {
3034
			if (Math.abs(movement.x) < 0.003) {
3035
				dx = 0.0;
3036
			}
3037
3038
			if (Math.abs(movement.z) < 0.003) {
3039
				dz = 0.0;
3040
			}
3041
		}
3042
3043
		if (Math.abs(movement.y) < 0.003) {
3044
			dy = 0.0;
3045
		}
3046
3047
		this.setDeltaMovement(dx, dy, dz);
3048
		ProfilerFiller profiler = Profiler.get();
3049
		profiler.push("ai");
3050
		this.applyInput();
3051
		if (this.isImmobile()) {
3052
			this.jumping = false;
3053
			this.xxa = 0.0F;
3054
			this.zza = 0.0F;
3055
		} else if (this.isEffectiveAi() && !this.level().isClientSide()) {
3056
			profiler.push("newAi");
3057
			this.serverAiStep();
3058
			profiler.pop();
3059
		}
3060
3061
		profiler.pop();
3062
		profiler.push("jump");
3063
		if (this.jumping && this.isAffectedByFluids()) {
3064
			double fluidHeight;
3065
			if (this.isInLava()) {
3066
				fluidHeight = this.getFluidHeight(FluidTags.LAVA);
3067
			} else {
3068
				fluidHeight = this.getFluidHeight(FluidTags.WATER);
3069
			}
3070
3071
			boolean inWaterAndHasFluidHeight = this.isInWater() && fluidHeight > 0.0;
3072
			double fluidJumpThreshold = this.getFluidJumpThreshold();
3073
			if (!inWaterAndHasFluidHeight || this.onGround() && !(fluidHeight > fluidJumpThreshold)) {
3074
				if (!this.isInLava() || this.onGround() && this.isInShallowFluid(FluidTags.LAVA)) {
3075
					if ((this.onGround() || inWaterAndHasFluidHeight && fluidHeight <= fluidJumpThreshold) && this.noJumpDelay == 0) {
3076
						this.jumpFromGround();
3077
						this.noJumpDelay = 10;
3078
					}
3079
				} else {
3080
					this.jumpInLiquid(FluidTags.LAVA);
3081
				}
3082
			} else {
3083
				this.jumpInLiquid(FluidTags.WATER);
3084
			}
3085
		} else {
3086
			this.noJumpDelay = 0;
3087
		}
3088
3089
		profiler.pop();
3090
		profiler.push("travel");
3091
		if (this.isFallFlying()) {
3092
			this.updateFallFlying();
3093
		}
3094
3095
		AABB beforeTravelBox = this.getBoundingBox();
3096
		Vec3 input = new Vec3(this.xxa, this.yya, this.zza);
3097
		if (this.hasEffect(MobEffects.SLOW_FALLING) || this.hasEffect(MobEffects.LEVITATION)) {
3098
			this.resetFallDistance();
3099
		}
3100
3101
		if (this.getControllingPassenger() instanceof Player controller && this.isAlive()) {
3102
			this.travelRidden(controller, input);
3103
		} else if (this.canSimulateMovement() && this.isEffectiveAi()) {
3104
			this.travel(input);
3105
		}
3106
3107
		if (!this.level().isClientSide() || this.isLocalInstanceAuthoritative()) {
3108
			this.applyEffectsFromBlocks();
3109
		}
3110
3111
		if (this.level().isClientSide()) {
3112
			this.calculateEntityAnimation(this.omnidirectionalAirMover());
3113
		}
3114
3115
		profiler.pop();
3116
		if (this.level() instanceof ServerLevel serverLevel) {
3117
			profiler.push("freezing");
3118
			if (!this.isInPowderSnow || !this.canFreeze()) {
3119
				this.setTicksFrozen(Math.max(0, this.getTicksFrozen() - 2));
3120
			}
3121
3122
			this.removeFrost();
3123
			this.tryAddFrost();
3124
			if (this.tickCount % 40 == 0 && this.isFullyFrozen() && this.canFreeze()) {
3125
				this.hurtServer(serverLevel, this.damageSources().freeze(), 1.0F);
3126
			}
3127
3128
			profiler.pop();
3129
		}
3130
3131
		profiler.push("push");
3132
		if (this.autoSpinAttackTicks > 0) {
3133
			this.autoSpinAttackTicks--;
3134
			this.checkAutoSpinAttack(beforeTravelBox, this.getBoundingBox());
3135
		}
3136
3137
		this.pushEntities();
3138
		profiler.pop();
3139
		if (this.level() instanceof ServerLevel serverLevel && this.isSensitiveToWater() && this.isInWaterOrRain()) {
3140
			this.hurtServer(serverLevel, this.damageSources().drown(), 1.0F);
3141
		}
3142
	}
3143
3144
	protected void applyInput() {
3145
		this.xxa *= 0.98F;
3146
		this.zza *= 0.98F;
3147
	}
3148
3149
	public boolean isSensitiveToWater() {
3150
		return false;
3151
	}
3152
3153
	public boolean isJumping() {
3154
		return this.jumping;
3155
	}
3156
3157
	protected void updateFallFlying() {
3158
		this.checkFallDistanceAccumulation();
3159
		if (!this.level().isClientSide()) {
3160
			if (!this.canGlide()) {
3161
				this.setSharedFlag(7, false);
3162
				return;
3163
			}
3164
3165
			int checkFallFlyTicks = this.fallFlyTicks + 1;
3166
			if (checkFallFlyTicks % 10 == 0) {
3167
				int freeFallInterval = checkFallFlyTicks / 10;
3168
				if (freeFallInterval % 2 == 0) {
3169
					List<EquipmentSlot> slotsWithGliders = EquipmentSlot.VALUES.stream().filter(slot -> canGlideUsing(this.getItemBySlot(slot), slot)).toList();
3170
					EquipmentSlot slotToDamage = Util.getRandom(slotsWithGliders, this.random);
3171
					this.getItemBySlot(slotToDamage).hurtAndBreak(1, this, slotToDamage);
3172
				}
3173
3174
				this.gameEvent(GameEvent.ELYTRA_GLIDE);
3175
			}
3176
		}
3177
	}
3178
3179
	protected boolean canGlide() {
3180
		if (!this.onGround() && !this.isPassenger() && !this.hasEffect(MobEffects.LEVITATION)) {
3181
			for (EquipmentSlot slot : EquipmentSlot.VALUES) {
3182
				if (canGlideUsing(this.getItemBySlot(slot), slot)) {
3183
					return true;
3184
				}
3185
			}
3186
3187
			return false;
3188
		} else {
3189
			return false;
3190
		}
3191
	}
3192
3193
	protected void serverAiStep() {
3194
	}
3195
3196
	protected void pushEntities() {
3197
		List<Entity> pushableEntities = this.level().getPushableEntities(this, this.getBoundingBox());
3198
		if (!pushableEntities.isEmpty()) {
3199
			if (this.level() instanceof ServerLevel serverLevel) {
3200
				int maxCramming = serverLevel.getGameRules().get(GameRules.MAX_ENTITY_CRAMMING);
3201
				if (maxCramming > 0 && pushableEntities.size() > maxCramming - 1 && this.random.nextInt(4) == 0) {
3202
					int count = 0;
3203
3204
					for (Entity entity : pushableEntities) {
3205
						if (!entity.isPassenger()) {
3206
							count++;
3207
						}
3208
					}
3209
3210
					if (count > maxCramming - 1) {
3211
						this.hurtServer(serverLevel, this.damageSources().cramming(), 6.0F);
3212
					}
3213
				}
3214
			}
3215
3216
			for (Entity entity : pushableEntities) {
3217
				this.doPush(entity);
3218
			}
3219
		}
3220
	}
3221
3222
	protected void checkAutoSpinAttack(final AABB old, final AABB current) {
3223
		AABB minmax = old.minmax(current);
3224
		List<Entity> entities = this.level().getEntities(this, minmax);
3225
		if (!entities.isEmpty()) {
3226
			for (Entity entity : entities) {
3227
				if (entity instanceof LivingEntity livingEntity) {
3228
					this.doAutoAttackOnTouch(livingEntity);
3229
					this.autoSpinAttackTicks = 0;
3230
					this.setDeltaMovement(this.getDeltaMovement().scale(-0.2));
3231
					break;
3232
				}
3233
			}
3234
		} else if (this.horizontalCollision) {
3235
			this.autoSpinAttackTicks = 0;
3236
		}
3237
3238
		if (!this.level().isClientSide() && this.autoSpinAttackTicks <= 0) {
3239
			this.setLivingEntityFlag(4, false);
3240
			this.autoSpinAttackDmg = 0.0F;
3241
			this.autoSpinAttackItemStack = null;
3242
		}
3243
	}
3244
3245
	protected void doPush(final Entity entity) {
3246
		entity.push(this);
3247
	}
3248
3249
	protected void doAutoAttackOnTouch(final LivingEntity entity) {
3250
	}
3251
3252
	public boolean isAutoSpinAttack() {
3253
		return (this.entityData.get(DATA_LIVING_ENTITY_FLAGS) & 4) != 0;
3254
	}
3255
3256
	@Override
3257
	public void stopRiding() {
3258
		Entity oldVehicle = this.getVehicle();
3259
		super.stopRiding();
3260
		if (oldVehicle != null && oldVehicle != this.getVehicle() && !this.level().isClientSide()) {
3261
			this.dismountVehicle(oldVehicle);
3262
		}
3263
	}
3264
3265
	@Override
3266
	public void rideTick() {
3267
		super.rideTick();
3268
		this.resetFallDistance();
3269
	}
3270
3271
	@Override
3272
	protected InterpolationHandler createInterpolationHandler() {
3273
		return SteppedInterpolationHandler.create(this);
3274
	}
3275
3276
	@Override
3277
	public void lerpHeadTo(final float yRot, final int steps) {
3278
		this.lerpYHeadRot = yRot;
3279
		this.lerpHeadSteps = steps;
3280
	}
3281
3282
	public void setJumping(final boolean jump) {
3283
		this.jumping = jump;
3284
	}
3285
3286
	public void onItemPickup(final ItemEntity entity) {
3287
		if (entity.getOwner() instanceof ServerPlayer serverPlayer) {
3288
			CriteriaTriggers.THROWN_ITEM_PICKED_UP_BY_ENTITY.trigger(serverPlayer, entity.getItem(), this);
3289
		}
3290
	}
3291
3292
	public void take(final Entity entity, final int orgCount) {
3293
		if (!entity.isRemoved()
3294
			&& !this.level().isClientSide()
3295
			&& (entity instanceof ItemEntity || entity instanceof AbstractArrow || entity instanceof ExperienceOrb)) {
3296
			((ServerLevel)this.level()).getChunkSource().sendToTrackingPlayers(entity, new ClientboundTakeItemEntityPacket(entity.getId(), this.getId(), orgCount));
3297
		}
3298
	}
3299
3300
	public boolean hasLineOfSight(final Entity target) {
3301
		return this.hasLineOfSight(target, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, target.getEyeY());
3302
	}
3303
3304
	public boolean hasLineOfSight(
3305
		final Entity target, final ClipContext.Block blockCollidingContext, final ClipContext.Fluid fluidCollidingContext, final double eyeHeight
3306
	) {
3307
		if (target.level() != this.level()) {
3308
			return false;
3309
		}
3310
3311
		Vec3 from = new Vec3(this.getX(), this.getEyeY(), this.getZ());
3312
		Vec3 to = new Vec3(target.getX(), eyeHeight, target.getZ());
3313
		return to.distanceTo(from) > 128.0
3314
			? false
3315
			: this.level().clip(new ClipContext(from, to, blockCollidingContext, fluidCollidingContext, this)).getType() == HitResult.Type.MISS;
3316
	}
3317
3318
	@Override
3319
	public float getViewYRot(final float a) {
3320
		return a == 1.0F ? this.yHeadRot : Mth.rotLerp(a, this.yHeadRotO, this.yHeadRot);
3321
	}
3322
3323
	public LivingEntity.@Nullable SwingDescription getCurrentSwing() {
3324
		return this.swingState.currentSwing;
3325
	}
3326
3327
	public float getSwingAnimation(final float partialTicks) {
3328
		return this.swingState.getAnimation(partialTicks);
3329
	}
3330
3331
	public boolean isSwinging() {
3332
		return this.swingState.isSwinging();
3333
	}
3334
3335
	@Override
3336
	public boolean isPickable() {
3337
		return !this.isRemoved();
3338
	}
3339
3340
	@Override
3341
	public boolean isPushable() {
3342
		return !this.isAlwaysTicking() && this.level() instanceof ServerLevel level && !level.isPositionEntityTicking(this.blockPosition())
3343
			? false
3344
			: this.isAlive() && !this.isSpectator() && !this.onClimbable();
3345
	}
3346
3347
	@Override
3348
	public float getYHeadRot() {
3349
		return this.yHeadRot;
3350
	}
3351
3352
	@Override
3353
	public void setYHeadRot(final float yHeadRot) {
3354
		this.yHeadRot = yHeadRot;
3355
	}
3356
3357
	@Override
3358
	public void setYBodyRot(final float yBodyRot) {
3359
		this.yBodyRot = yBodyRot;
3360
	}
3361
3362
	@Override
3363
	public Vec3 getRelativePortalPosition(final Direction.Axis axis, final BlockUtil.FoundRectangle portalArea) {
3364
		return resetForwardDirectionOfRelativePortalPosition(super.getRelativePortalPosition(axis, portalArea));
3365
	}
3366
3367
	public static Vec3 resetForwardDirectionOfRelativePortalPosition(final Vec3 offsets) {
3368
		return new Vec3(offsets.x, offsets.y, 0.0);
3369
	}
3370
3371
	public float getAbsorptionAmount() {
3372
		return this.absorptionAmount;
3373
	}
3374
3375
	public final void setAbsorptionAmount(final float absorptionAmount) {
3376
		this.internalSetAbsorptionAmount(Mth.clamp(absorptionAmount, 0.0F, this.getMaxAbsorption()));
3377
	}
3378
3379
	protected void internalSetAbsorptionAmount(final float absorptionAmount) {
3380
		this.absorptionAmount = absorptionAmount;
3381
	}
3382
3383
	public void onEnterCombat() {
3384
	}
3385
3386
	public void onLeaveCombat() {
3387
	}
3388
3389
	protected void updateEffectVisibility() {
3390
		this.effectsDirty = true;
3391
	}
3392
3393
	public abstract HumanoidArm getMainArm();
3394
3395
	public boolean isUsingItem() {
3396
		return (this.entityData.get(DATA_LIVING_ENTITY_FLAGS) & 1) > 0;
3397
	}
3398
3399
	public InteractionHand getUsedItemHand() {
3400
		return (this.entityData.get(DATA_LIVING_ENTITY_FLAGS) & 2) > 0 ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND;
3401
	}
3402
3403
	private void updatingUsingItem() {
3404
		if (this.isUsingItem()) {
3405
			if (ItemStack.isSameItem(this.getItemInHand(this.getUsedItemHand()), this.useItem)) {
3406
				this.useItem = this.getItemInHand(this.getUsedItemHand());
3407
				this.updateUsingItem(this.useItem);
3408
			} else {
3409
				this.stopUsingItem();
3410
			}
3411
		}
3412
	}
3413
3414
	public @Nullable ItemEntity createItemStackToDrop(final ItemStack itemStack, final boolean randomly, final boolean thrownFromHand) {
3415
		if (itemStack.isEmpty()) {
3416
			return null;
3417
		}
3418
3419
		double yHandPos = this.getEyeY() - 0.3F;
3420
		ItemEntity entity = new ItemEntity(this.level(), this.getX(), yHandPos, this.getZ(), itemStack);
3421
		entity.setPickUpDelay(40);
3422
		if (thrownFromHand) {
3423
			entity.setThrower(this);
3424
		}
3425
3426
		if (randomly) {
3427
			float pow = this.random.nextFloat() * 0.5F;
3428
			float dir = this.random.nextFloat() * (float) (Math.PI * 2);
3429
			entity.setDeltaMovement(-Mth.sin(dir) * pow, 0.2F, Mth.cos(dir) * pow);
3430
		} else {
3431
			float pow = 0.3F;
3432
			float sinX = Mth.sin(this.getXRot() * (float) (Math.PI / 180.0));
3433
			float cosX = Mth.cos(this.getXRot() * (float) (Math.PI / 180.0));
3434
			float sinY = Mth.sin(this.getYRot() * (float) (Math.PI / 180.0));
3435
			float cosY = Mth.cos(this.getYRot() * (float) (Math.PI / 180.0));
3436
			float dir = this.random.nextFloat() * (float) (Math.PI * 2);
3437
			float pow2 = 0.02F * this.random.nextFloat();
3438
			entity.setDeltaMovement(
3439
				-sinY * cosX * 0.3F + Math.cos(dir) * pow2,
3440
				-sinX * 0.3F + 0.1F + (this.random.nextFloat() - this.random.nextFloat()) * 0.1F,
3441
				cosY * cosX * 0.3F + Math.sin(dir) * pow2
3442
			);
3443
		}
3444
3445
		return entity;
3446
	}
3447
3448
	protected void updateUsingItem(final ItemStack useItem) {
3449
		useItem.onUseTick(this.level(), this, this.getUseItemRemainingTicks());
3450
		if (--this.useItemRemaining == 0 && !this.level().isClientSide() && !useItem.useOnRelease()) {
3451
			this.completeUsingItem();
3452
		}
3453
	}
3454
3455
	private void updateSwimAmount() {
3456
		this.swimAmountO = this.swimAmount;
3457
		if (this.isVisuallySwimming()) {
3458
			this.swimAmount = Math.min(1.0F, this.swimAmount + 0.09F);
3459
		} else {
3460
			this.swimAmount = Math.max(0.0F, this.swimAmount - 0.09F);
3461
		}
3462
	}
3463
3464
	protected void setLivingEntityFlag(final int flag, final boolean value) {
3465
		int currentFlags = this.entityData.get(DATA_LIVING_ENTITY_FLAGS);
3466
		if (value) {
3467
			currentFlags |= flag;
3468
		} else {
3469
			currentFlags &= ~flag;
3470
		}
3471
3472
		this.entityData.set(DATA_LIVING_ENTITY_FLAGS, (byte)currentFlags);
3473
	}
3474
3475
	public void startUsingItem(final InteractionHand hand) {
3476
		ItemStack itemStack = this.getItemInHand(hand);
3477
		if (!itemStack.isEmpty() && !this.isUsingItem()) {
3478
			this.useItem = itemStack;
3479
			this.useItemRemaining = itemStack.getUseDuration(this);
3480
			if (!this.level().isClientSide()) {
3481
				this.updatePlayersWithNewEquipment((ServerLevel)this.level(), List.of(Pair.of(hand.asEquipmentSlot(), this.useItem)));
3482
				this.setLivingEntityFlag(1, true);
3483
				this.setLivingEntityFlag(2, hand == InteractionHand.OFF_HAND);
3484
				this.useItem.causeUseVibration(this, GameEvent.ITEM_INTERACT_START);
3485
				if (this.useItem.has(DataComponents.KINETIC_WEAPON)) {
3486
					this.recentKineticEnemies = new Object2LongOpenHashMap<>();
3487
				}
3488
			}
3489
		}
3490
	}
3491
3492
	@Override
3493
	public void onSyncedDataUpdated(final EntityDataAccessor<?> accessor) {
3494
		super.onSyncedDataUpdated(accessor);
3495
		if (SLEEPING_POS_ID.equals(accessor)) {
3496
			if (this.level().isClientSide()) {
3497
				this.getSleepingPos().ifPresent(this::setPosToBed);
3498
			}
3499
		} else if (DATA_LIVING_ENTITY_FLAGS.equals(accessor) && this.level().isClientSide()) {
3500
			if (this.isUsingItem() && this.useItem.isEmpty()) {
3501
				this.useItem = this.getItemInHand(this.getUsedItemHand());
3502
				if (!this.useItem.isEmpty()) {
3503
					this.useItemRemaining = this.useItem.getUseDuration(this);
3504
				}
3505
			} else if (!this.isUsingItem() && !this.useItem.isEmpty()) {
3506
				this.useItem = ItemStack.EMPTY;
3507
				this.useItemRemaining = 0;
3508
			}
3509
		}
3510
	}
3511
3512
	@Override
3513
	public void lookAt(final EntityAnchorArgument.Anchor anchor, final Vec3 pos) {
3514
		super.lookAt(anchor, pos);
3515
		this.yHeadRotO = this.yHeadRot;
3516
		this.yBodyRot = this.yHeadRot;
3517
		this.yBodyRotO = this.yBodyRot;
3518
	}
3519
3520
	@Override
3521
	public float getPreciseBodyRotation(final float partial) {
3522
		return Mth.lerp(partial, this.yBodyRotO, this.yBodyRot);
3523
	}
3524
3525
	public void spawnItemParticles(final ItemStack itemStack, final int count) {
3526
		if (!itemStack.isEmpty()) {
3527
			ItemParticleOption breakParticle = new ItemParticleOption(ParticleTypes.ITEM, ItemStackTemplate.fromNonEmptyStack(itemStack));
3528
3529
			for (int i = 0; i < count; i++) {
3530
				Vec3 d = new Vec3((this.random.nextFloat() - 0.5) * 0.1, this.random.nextFloat() * 0.1 + 0.1, 0.0);
3531
				d = d.xRot(-this.getXRot() * (float) (Math.PI / 180.0));
3532
				d = d.yRot(-this.getYRot() * (float) (Math.PI / 180.0));
3533
				double y1 = -this.random.nextFloat() * 0.6 - 0.3;
3534
				Vec3 p = new Vec3((this.random.nextFloat() - 0.5) * 0.3, y1, 0.6);
3535
				p = p.xRot(-this.getXRot() * (float) (Math.PI / 180.0));
3536
				p = p.yRot(-this.getYRot() * (float) (Math.PI / 180.0));
3537
				p = p.add(this.getX(), this.getEyeY(), this.getZ());
3538
				this.level().addParticle(breakParticle, p.x, p.y, p.z, d.x, d.y + 0.05, d.z);
3539
			}
3540
		}
3541
	}
3542
3543
	protected void completeUsingItem() {
3544
		if (!this.level().isClientSide() || this.isUsingItem()) {
3545
			InteractionHand hand = this.getUsedItemHand();
3546
			if (!this.useItem.equals(this.getItemInHand(hand))) {
3547
				this.releaseUsingItem();
3548
			} else {
3549
				if (!this.useItem.isEmpty() && this.isUsingItem()) {
3550
					ItemStack result = this.useItem.finishUsingItem(this.level(), this);
3551
					if (result != this.useItem) {
3552
						this.setItemInHand(hand, result);
3553
					}
3554
3555
					this.stopUsingItem();
3556
				}
3557
			}
3558
		}
3559
	}
3560
3561
	public void handleExtraItemsCreatedOnUse(final ItemStack extraCreatedRemainder) {
3562
	}
3563
3564
	public ItemStack getUseItem() {
3565
		return this.useItem;
3566
	}
3567
3568
	public int getUseItemRemainingTicks() {
3569
		return this.useItemRemaining;
3570
	}
3571
3572
	public int getTicksUsingItem() {
3573
		return this.isUsingItem() ? this.useItem.getUseDuration(this) - this.getUseItemRemainingTicks() : 0;
3574
	}
3575
3576
	public float getTicksUsingItem(final float partialTicks) {
3577
		return !this.isUsingItem() ? 0.0F : this.getTicksUsingItem() + partialTicks;
3578
	}
3579
3580
	public void releaseUsingItem() {
3581
		ItemStack itemInUsedHand = this.getItemInHand(this.getUsedItemHand());
3582
		if (!this.useItem.isEmpty() && ItemStack.isSameItem(itemInUsedHand, this.useItem)) {
3583
			this.useItem = itemInUsedHand;
3584
			this.useItem.releaseUsing(this.level(), this, this.getUseItemRemainingTicks());
3585
			if (this.useItem.useOnRelease()) {
3586
				this.updatingUsingItem();
3587
			}
3588
		}
3589
3590
		this.stopUsingItem();
3591
	}
3592
3593
	public void stopUsingItem() {
3594
		if (!this.level().isClientSide()) {
3595
			boolean wasUsingItem = this.isUsingItem();
3596
			this.recentKineticEnemies = null;
3597
			this.setLivingEntityFlag(1, false);
3598
			if (wasUsingItem) {
3599
				this.useItem.causeUseVibration(this, GameEvent.ITEM_INTERACT_FINISH);
3600
			}
3601
		}
3602
3603
		this.useItem = ItemStack.EMPTY;
3604
		this.useItemRemaining = 0;
3605
	}
3606
3607
	public boolean isBlocking() {
3608
		return this.getItemBlockingWith() != null;
3609
	}
3610
3611
	public @Nullable ItemStack getItemBlockingWith() {
3612
		if (!this.isUsingItem()) {
3613
			return null;
3614
		}
3615
3616
		BlocksAttacks blocksAttacks = this.useItem.get(DataComponents.BLOCKS_ATTACKS);
3617
		if (blocksAttacks != null) {
3618
			int elapsedTicks = this.useItem.getItem().getUseDuration(this.useItem, this) - this.useItemRemaining;
3619
			if (elapsedTicks >= blocksAttacks.blockDelayTicks()) {
3620
				return this.useItem;
3621
			}
3622
		}
3623
3624
		return null;
3625
	}
3626
3627
	public boolean isSuppressingSlidingDownLadder() {
3628
		return this.isShiftKeyDown();
3629
	}
3630
3631
	public boolean isFallFlying() {
3632
		return this.getSharedFlag(7);
3633
	}
3634
3635
	@Override
3636
	public boolean isVisuallySwimming() {
3637
		return super.isVisuallySwimming() || !this.isFallFlying() && this.hasPose(Pose.FALL_FLYING);
3638
	}
3639
3640
	public int getFallFlyingTicks() {
3641
		return this.fallFlyTicks;
3642
	}
3643
3644
	public boolean randomTeleport(final double xx, final double yy, final double zz, final boolean showParticles, final TagKey<Block> avoidanceTag) {
3645
		return this.randomTeleport(xx, yy, zz, showParticles, state -> state.is(avoidanceTag));
3646
	}
3647
3648
	public boolean randomTeleport(final double xx, final double yy, final double zz, final boolean showParticles, final Predicate<BlockState> isInvalidPosition) {
3649
		double y = yy;
3650
		Level level = this.level();
3651
		WorldBorder worldBorder = level.getWorldBorder();
3652
		Vec3 clamped = worldBorder.clampVec3ToBound(xx, y, zz);
3653
		BlockPos.MutableBlockPos pos = BlockPos.containing(clamped).mutable();
3654
		if (level.hasChunkAt(pos)) {
3655
			while (pos.getY() > level.getMinY()) {
3656
				pos.move(Direction.DOWN);
3657
				BlockState state = level.getBlockState(pos);
3658
				if (state.is(BlockTags.ENTITIES_CAN_TELEPORT_TO)) {
3659
					return this.checkPositionAndTeleport(clamped.x, y, clamped.z, showParticles, isInvalidPosition, state, level);
3660
				}
3661
3662
				y--;
3663
			}
3664
		}
3665
3666
		return false;
3667
	}
3668
3669
	private boolean checkPositionAndTeleport(
3670
		final double xx,
3671
		final double y,
3672
		final double zz,
3673
		final boolean showParticles,
3674
		final Predicate<BlockState> isInvalidPosition,
3675
		final BlockState state,
3676
		final Level level
3677
	) {
3678
		if (isInvalidPosition.test(state)) {
3679
			return false;
3680
		}
3681
3682
		AABB aabb = this.makeBoundingBox(new Vec3(xx, y, zz));
3683
		if (level.noCollision(aabb) && !level.containsAnyLiquid(aabb)) {
3684
			boolean hasInvalidPosition = level.findBlocksIn(aabb).filterState(isInvalidPosition).anyMatched();
3685
			if (hasInvalidPosition) {
3686
				return false;
3687
			}
3688
3689
			if (this.canRandomlyTeleportTo(xx, y, zz)) {
3690
				this.teleportTo(xx, y, zz);
3691
				if (showParticles) {
3692
					level.broadcastEntityEvent(this, (byte)46);
3693
				}
3694
3695
				if (this instanceof PathfinderMob pathfinderMob) {
3696
					pathfinderMob.getNavigation().stop();
3697
				}
3698
3699
				return true;
3700
			} else {
3701
				return false;
3702
			}
3703
		} else {
3704
			return false;
3705
		}
3706
	}
3707
3708
	public boolean canRandomlyTeleportTo(final double x, final double y, final double z) {
3709
		return true;
3710
	}
3711
3712
	public boolean isAffectedByPotions() {
3713
		return !this.isDeadOrDying();
3714
	}
3715
3716
	public boolean attackable() {
3717
		return true;
3718
	}
3719
3720
	public void setRecordPlayingNearby(final BlockPos jukebox, final boolean isPlaying) {
3721
	}
3722
3723
	public boolean canPickUpLoot() {
3724
		return false;
3725
	}
3726
3727
	@Override
3728
	public final EntityDimensions getDimensions(final Pose pose) {
3729
		return pose == Pose.SLEEPING ? SLEEPING_DIMENSIONS : this.getDefaultDimensions(pose).scale(this.getScale());
3730
	}
3731
3732
	protected EntityDimensions getDefaultDimensions(final Pose pose) {
3733
		return this.getType().getDimensions().scale(this.getAgeScale());
3734
	}
3735
3736
	public ImmutableList<Pose> getDismountPoses() {
3737
		return ImmutableList.of(Pose.STANDING);
3738
	}
3739
3740
	public AABB getLocalBoundsForPose(final Pose pose) {
3741
		EntityDimensions dimensions = this.getDimensions(pose);
3742
		return new AABB(-dimensions.width() / 2.0F, 0.0, -dimensions.width() / 2.0F, dimensions.width() / 2.0F, dimensions.height(), dimensions.width() / 2.0F);
3743
	}
3744
3745
	protected boolean wouldNotSuffocateAtTargetPose(final Pose pose) {
3746
		AABB targetBB = this.getDimensions(pose).makeBoundingBox(this.position());
3747
		return this.level().noBlockCollision(this, targetBB);
3748
	}
3749
3750
	@Override
3751
	public boolean canUsePortal(final boolean ignorePassenger) {
3752
		return super.canUsePortal(ignorePassenger) && !this.isSleeping();
3753
	}
3754
3755
	public Optional<BlockPos> getSleepingPos() {
3756
		return this.entityData.get(SLEEPING_POS_ID);
3757
	}
3758
3759
	public void setSleepingPos(final BlockPos bedPosition) {
3760
		this.entityData.set(SLEEPING_POS_ID, Optional.of(bedPosition));
3761
	}
3762
3763
	public void clearSleepingPos() {
3764
		this.entityData.set(SLEEPING_POS_ID, Optional.empty());
3765
	}
3766
3767
	public boolean isSleeping() {
3768
		return this.getSleepingPos().isPresent();
3769
	}
3770
3771
	public boolean startSleeping(final BlockPos bedPosition) {
3772
		BlockState blockState = this.level().getBlockState(bedPosition);
3773
		if (blockState.getBlock() instanceof AbstractBedBlock bedBlock) {
3774
			OptionalDouble sleepHeight = bedBlock.getSleepHeight(blockState, this.level(), bedPosition);
3775
			if (sleepHeight.isEmpty()) {
3776
				return false;
3777
			}
3778
3779
			if (this.isPassenger()) {
3780
				this.stopRiding();
3781
			}
3782
3783
			this.setPosToBed(sleepHeight.getAsDouble(), bedPosition);
3784
			this.level().setBlockAndUpdate(bedPosition, blockState.setValue(BedBlock.OCCUPIED, true));
3785
			this.setPose(Pose.SLEEPING);
3786
			this.setSleepingPos(bedPosition);
3787
			this.setDeltaMovement(Vec3.ZERO);
3788
			this.needsSync = true;
3789
			return true;
3790
		} else {
3791
			return false;
3792
		}
3793
	}
3794
3795
	private boolean setPosToBed(final BlockPos bedPosition) {
3796
		BlockState state = this.level().getBlockState(bedPosition);
3797
		if (state.getBlock() instanceof AbstractBedBlock bedBlock) {
3798
			OptionalDouble sleepHeight = bedBlock.getSleepHeight(state, this.level(), bedPosition);
3799
			if (sleepHeight.isEmpty()) {
3800
				return false;
3801
			}
3802
3803
			this.setPosToBed(sleepHeight.getAsDouble(), bedPosition);
3804
			return true;
3805
		} else {
3806
			return false;
3807
		}
3808
	}
3809
3810
	private void setPosToBed(final double sleepHeight, final BlockPos bedPosition) {
3811
		double adjustHeight = 0.125;
3812
		this.setPos(bedPosition.getX() + 0.5, bedPosition.getY() + sleepHeight + 0.125, bedPosition.getZ() + 0.5);
3813
	}
3814
3815
	private boolean checkBedExists() {
3816
		return this.getSleepingPos().map(bedPosition -> {
3817
			BlockState state = this.level().getBlockState(bedPosition);
3818
			return state.getBlock() instanceof AbstractBedBlock bedBlock && bedBlock.getSleepHeight(state, this.level(), bedPosition).isPresent();
3819
		}).orElse(false);
3820
	}
3821
3822
	public void stopSleeping() {
3823
		this.getSleepingPos().filter(this.level()::hasChunkAt).ifPresent(bedPosition -> {
3824
			BlockState state = this.level().getBlockState(bedPosition);
3825
			if (state.getBlock() instanceof AbstractBedBlock bedBlock) {
3826
				Direction facing = state.getValue(BedBlock.FACING);
3827
				this.level().setBlockAndUpdate(bedPosition, state.setValue(BedBlock.OCCUPIED, false));
3828
				bedBlock.onStopSleeping(this.level(), bedPosition);
3829
				Vec3 standUp = AbstractBedBlock.findStandUpPosition(this.getType(), this.level(), bedPosition, facing, this.getYRot()).orElseGet(() -> {
3830
					BlockPos above = bedPosition.above();
3831
					return new Vec3(above.getX() + 0.5, above.getY() + 0.1, above.getZ() + 0.5);
3832
				});
3833
				Vec3 lookDirection = Vec3.atBottomCenterOf(bedPosition).subtract(standUp).normalize();
3834
				float yaw = (float)Mth.wrapDegrees(Mth.atan2(lookDirection.z, lookDirection.x) * 180.0F / (float)Math.PI - 90.0);
3835
				this.setPos(standUp.x, standUp.y, standUp.z);
3836
				this.setYRot(yaw);
3837
				this.setXRot(0.0F);
3838
			}
3839
		});
3840
		Vec3 pos = this.position();
3841
		this.setPose(Pose.STANDING);
3842
		this.setPos(pos.x, pos.y, pos.z);
3843
		this.clearSleepingPos();
3844
	}
3845
3846
	public @Nullable Direction getBedOrientation() {
3847
		BlockPos bedPos = this.getSleepingPos().orElse(null);
3848
		return bedPos != null ? BedBlock.getBedOrientation(this.level(), bedPos) : null;
3849
	}
3850
3851
	@Override
3852
	public boolean isInWall() {
3853
		return !this.isSleeping() && super.isInWall();
3854
	}
3855
3856
	public ItemStack getProjectile(final ItemStack heldWeapon) {
3857
		return ItemStack.EMPTY;
3858
	}
3859
3860
	private static @EntityEvent.Value byte entityEventForEquipmentBreak(final EquipmentSlot equipmentSlot) {
3861
		return switch (equipmentSlot) {
3862
			case MAINHAND -> 47;
3863
			case OFFHAND -> 48;
3864
			case HEAD -> 49;
3865
			case CHEST -> 50;
3866
			case FEET -> 52;
3867
			case LEGS -> 51;
3868
			case BODY -> 65;
3869
			case SADDLE -> 68;
3870
		};
3871
	}
3872
3873
	public void onEquippedItemBroken(final ItemStack brokenItem, final EquipmentSlot inSlot) {
3874
		this.level().broadcastEntityEvent(this, entityEventForEquipmentBreak(inSlot));
3875
		this.stopLocationBasedEffects(brokenItem, inSlot, this.attributes);
3876
	}
3877
3878
	private void stopLocationBasedEffects(final ItemStack previous, final EquipmentSlot inSlot, final AttributeMap attributes) {
3879
		previous.forEachModifier(inSlot, (attribute, modifier) -> {
3880
			AttributeInstance instance = attributes.getInstance(attribute);
3881
			if (instance != null) {
3882
				instance.removeModifier(modifier);
3883
			}
3884
		});
3885
		EnchantmentHelper.stopLocationBasedEffects(previous, this, inSlot);
3886
	}
3887
3888
	public final boolean canEquipWithDispenser(final ItemStack itemStack) {
3889
		if (this.isAlive() && !this.isSpectator()) {
3890
			Equippable equippable = itemStack.get(DataComponents.EQUIPPABLE);
3891
			if (equippable != null && equippable.dispensable()) {
3892
				EquipmentSlot slot = equippable.slot();
3893
				return this.canUseSlot(slot) && equippable.canBeEquippedBy(this.typeHolder())
3894
					? this.getItemBySlot(slot).isEmpty() && this.canDispenserEquipIntoSlot(slot)
3895
					: false;
3896
			} else {
3897
				return false;
3898
			}
3899
		} else {
3900
			return false;
3901
		}
3902
	}
3903
3904
	protected boolean canDispenserEquipIntoSlot(final EquipmentSlot slot) {
3905
		return true;
3906
	}
3907
3908
	public EquipmentSlot getEquipmentSlotForItem(final ItemStack itemStack) {
3909
		Equippable equippable = itemStack.get(DataComponents.EQUIPPABLE);
3910
		return equippable != null && this.canUseSlot(equippable.slot()) ? equippable.slot() : EquipmentSlot.MAINHAND;
3911
	}
3912
3913
	public boolean isEquippableInSlot(final ItemStack itemStack, final EquipmentSlot slot) {
3914
		Equippable equippable = itemStack.get(DataComponents.EQUIPPABLE);
3915
		return equippable == null
3916
			? slot == EquipmentSlot.MAINHAND && this.canUseSlot(EquipmentSlot.MAINHAND)
3917
			: slot == equippable.slot() && this.canUseSlot(equippable.slot()) && equippable.canBeEquippedBy(this.typeHolder());
3918
	}
3919
3920
	private static SlotAccess createEquipmentSlotAccess(final LivingEntity entity, final EquipmentSlot equipmentSlot) {
3921
		return equipmentSlot != EquipmentSlot.HEAD && equipmentSlot != EquipmentSlot.MAINHAND && equipmentSlot != EquipmentSlot.OFFHAND
3922
			? SlotAccess.forEquipmentSlot(entity, equipmentSlot, stack -> stack.isEmpty() || entity.getEquipmentSlotForItem(stack) == equipmentSlot)
3923
			: SlotAccess.forEquipmentSlot(entity, equipmentSlot);
3924
	}
3925
3926
	private static @Nullable EquipmentSlot getEquipmentSlot(final int slot) {
3927
		if (slot == 100 + EquipmentSlot.HEAD.getIndex()) {
3928
			return EquipmentSlot.HEAD;
3929
		} else if (slot == 100 + EquipmentSlot.CHEST.getIndex()) {
3930
			return EquipmentSlot.CHEST;
3931
		} else if (slot == 100 + EquipmentSlot.LEGS.getIndex()) {
3932
			return EquipmentSlot.LEGS;
3933
		} else if (slot == 100 + EquipmentSlot.FEET.getIndex()) {
3934
			return EquipmentSlot.FEET;
3935
		} else if (slot == 98) {
3936
			return EquipmentSlot.MAINHAND;
3937
		} else if (slot == 99) {
3938
			return EquipmentSlot.OFFHAND;
3939
		} else if (slot == 105) {
3940
			return EquipmentSlot.BODY;
3941
		} else {
3942
			return slot == 106 ? EquipmentSlot.SADDLE : null;
3943
		}
3944
	}
3945
3946
	@Override
3947
	public @Nullable SlotAccess getSlot(final int slot) {
3948
		EquipmentSlot equipmentSlot = getEquipmentSlot(slot);
3949
		return equipmentSlot != null ? createEquipmentSlotAccess(this, equipmentSlot) : super.getSlot(slot);
3950
	}
3951
3952
	@Override
3953
	public boolean canFreeze() {
3954
		if (this.isSpectator()) {
3955
			return false;
3956
		}
3957
3958
		for (EquipmentSlot slot : EquipmentSlotGroup.ARMOR) {
3959
			if (this.getItemBySlot(slot).is(ItemTags.FREEZE_IMMUNE_WEARABLES)) {
3960
				return false;
3961
			}
3962
		}
3963
3964
		return super.canFreeze();
3965
	}
3966
3967
	@Override
3968
	public boolean isCurrentlyGlowing() {
3969
		return !this.level().isClientSide() && this.hasEffect(MobEffects.GLOWING) || super.isCurrentlyGlowing();
3970
	}
3971
3972
	@Override
3973
	public float getVisualRotationYInDegrees() {
3974
		return this.yBodyRot;
3975
	}
3976
3977
	@Override
3978
	public void recreateFromPacket(final ClientboundAddEntityPacket packet) {
3979
		double x = packet.getX();
3980
		double y = packet.getY();
3981
		double z = packet.getZ();
3982
		float yRot = packet.getYRot();
3983
		float xRot = packet.getXRot();
3984
		this.syncPacketPositionCodec(x, y, z);
3985
		this.yBodyRot = packet.getYHeadRot();
3986
		this.yHeadRot = packet.getYHeadRot();
3987
		this.yBodyRotO = this.yBodyRot;
3988
		this.yHeadRotO = this.yHeadRot;
3989
		this.setId(packet.getId());
3990
		this.setUUID(packet.getUUID());
3991
		this.absSnapTo(x, y, z, yRot, xRot);
3992
		this.setDeltaMovement(packet.getMovement());
3993
	}
3994
3995
	public float getSecondsToDisableBlocking() {
3996
		ItemStack weaponItem = this.getWeaponItem();
3997
		Weapon weapon = weaponItem.get(DataComponents.WEAPON);
3998
		return weapon != null && weaponItem == this.getActiveItem() ? weapon.disableBlockingForSeconds() : 0.0F;
3999
	}
4000
4001
	@Override
4002
	public float maxUpStep() {
4003
		float maxUpStep = (float)this.getAttributeValue(Attributes.STEP_HEIGHT);
4004
		return this.getControllingPassenger() instanceof Player ? Math.max(maxUpStep, 1.0F) : maxUpStep;
4005
	}
4006
4007
	@Override
4008
	public Vec3 getPassengerRidingPosition(final Entity passenger) {
4009
		return this.position().add(this.getPassengerAttachmentPoint(passenger, this.getDimensions(this.getPose()), this.getScale() * this.getAgeScale()));
4010
	}
4011
4012
	protected void lerpHeadRotationStep(final int lerpHeadSteps, final double targetYHeadRot) {
4013
		this.yHeadRot = (float)Mth.rotLerp(1.0 / lerpHeadSteps, this.yHeadRot, targetYHeadRot);
4014
	}
4015
4016
	@Override
4017
	public void igniteForTicks(final int numberOfTicks) {
4018
		super.igniteForTicks(Mth.ceil(numberOfTicks * this.getAttributeValue(Attributes.BURNING_TIME)));
4019
	}
4020
4021
	public boolean hasInfiniteMaterials() {
4022
		return false;
4023
	}
4024
4025
	public boolean isInvulnerableTo(final ServerLevel level, final DamageSource source) {
4026
		return this.isInvulnerableToBase(source) || EnchantmentHelper.isImmuneToDamage(level, this, source);
4027
	}
4028
4029
	public static boolean canGlideUsing(final ItemStack itemStack, final EquipmentSlot slot) {
4030
		if (!itemStack.has(DataComponents.GLIDER)) {
4031
			return false;
4032
		}
4033
4034
		Equippable equippable = itemStack.get(DataComponents.EQUIPPABLE);
4035
		return equippable != null && slot == equippable.slot() && !itemStack.nextDamageWillBreak();
4036
	}
4037
4038
	@VisibleForTesting
4039
	public int getLastHurtByPlayerMemoryTime() {
4040
		return this.lastHurtByPlayerMemoryTime;
4041
	}
4042
4043
	@Override
4044
	public boolean isTransmittingWaypoint() {
4045
		return this.getAttributeValue(Attributes.WAYPOINT_TRANSMIT_RANGE) > 0.0;
4046
	}
4047
4048
	@Override
4049
	public Optional<WaypointTransmitter.Connection> makeWaypointConnectionWith(final ServerPlayer player) {
4050
		if (this.firstTick || player == this) {
4051
			return Optional.empty();
4052
		} else if (WaypointTransmitter.doesSourceIgnoreReceiver(this, player)) {
4053
			return Optional.empty();
4054
		} else {
4055
			Waypoint.Icon icon = this.locatorBarIcon.cloneAndAssignStyle(this);
4056
			if (WaypointTransmitter.isReallyFar(this, player)) {
4057
				return Optional.of(new WaypointTransmitter.EntityAzimuthConnection(this, icon, player));
4058
			} else {
4059
				return !WaypointTransmitter.isChunkVisible(this.chunkPosition(), player)
4060
					? Optional.of(new WaypointTransmitter.EntityChunkConnection(this, icon, player))
4061
					: Optional.of(new WaypointTransmitter.EntityBlockConnection(this, icon, player));
4062
			}
4063
		}
4064
	}
4065
4066
	@Override
4067
	public Waypoint.Icon waypointIcon() {
4068
		return this.locatorBarIcon;
4069
	}
4070
4071
	public DamageSource createDamageSource() {
4072
		return this.damageSources().mobAttack(this);
4073
	}
4074
4075
	public record Fallsounds(SoundEvent small, SoundEvent big) {
4076
	}
4077
4078
	public record SwingDescription(InteractionHand hand, SwingAnimation animation, int durationTicks) {
4079
	}
4080
4081
	public static class SwingState {
4082
		private LivingEntity.@Nullable SwingDescription currentSwing;
4083
		private int ticks;
4084
		private float oldAnimation;
4085
		private float animation;
4086
4087
		public boolean startIfAble(final InteractionHand hand, final SwingAnimation animation, final int durationTicks) {
4088
			if (this.currentSwing != null && this.ticks <= this.currentSwing.durationTicks / 2 && this.ticks > 0) {
4089
				return false;
4090
			}
4091
4092
			this.start(hand, animation, durationTicks);
4093
			return true;
4094
		}
4095
4096
		private void start(final InteractionHand hand, final SwingAnimation animation, final int durationTicks) {
4097
			LivingEntity.SwingDescription oldSwing = this.currentSwing;
4098
			this.currentSwing = new LivingEntity.SwingDescription(hand, animation, durationTicks);
4099
			if (!this.currentSwing.equals(oldSwing)) {
4100
				this.oldAnimation = 0.0F;
4101
				this.animation = 0.0F;
4102
			}
4103
4104
			this.ticks = 0;
4105
		}
4106
4107
		public void tick() {
4108
			this.oldAnimation = this.animation;
4109
			if (this.currentSwing != null) {
4110
				if (this.currentSwing.durationTicks > 0) {
4111
					this.animation = Math.min((float)this.ticks / this.currentSwing.durationTicks, 1.0F);
4112
				}
4113
4114
				if (this.ticks++ > this.currentSwing.durationTicks) {
4115
					this.currentSwing = null;
4116
					this.animation = 0.0F;
4117
				}
4118
			} else {
4119
				this.animation = 0.0F;
4120
			}
4121
		}
4122
4123
		public float getAnimation(final float partialTicks) {
4124
			return this.animation >= this.oldAnimation
4125
				? Mth.lerp(partialTicks, this.oldAnimation, this.animation)
4126
				: Mth.lerp(partialTicks, this.oldAnimation, this.animation + 1.0F);
4127
		}
4128
4129
		public boolean isSwinging() {
4130
			return this.currentSwing != null;
4131
		}
4132
	}
4133
}
4134

Decompiled Minecraft 26.3 source of LivingEntity (net/minecraft/world/entity/LivingEntity.java) with Mojang official mappings, stored verbatim on the site.