Mob .java

net.minecraft.world.entity.Mob (class, 1474 lines): members: WEARING_ARMOR_UPGRADE_MATERIAL_ATTEMPTS, WEARING_ARMOR_UPGRADE_MATERIAL_CHANCE, setZza.

net.minecraft.world.entityclass1,474 linescommonextends LivingEntity48.7 KB

Implements

API Surface (132)

void registerGoals()
AttributeSupplier.Builder createMobAttributes()
PathNavigation createNavigation(final Level level)
boolean shouldPassengersInheritMalus()
float getPathfindingMalus(final PathType pathType)
void setPathfindingMalus(final PathType pathType, final float cost)
void onPathfindingStart()
void onPathfindingDone()
BodyRotationControl createBodyControl()
LookControl getLookControl()
MoveControl getMoveControl()
JumpControl getJumpControl()
PathNavigation getNavigation()
Sensing getSensing()
void setTarget(final @Nullable LivingEntity target)
boolean canAttack(final LivingEntity target)
boolean canUseNonMeleeWeapon(final ItemStack item)
void ate()
void defineSynchedData(final SynchedEntityData.Builder entityData)
int getAmbientSoundInterval()
void playAmbientSound()
void baseTick()
void playHurtSound(final DamageSource source)
int getBaseExperienceReward(final ServerLevel level)
void spawnAnim()
void handleEntityEvent(final @EntityEvent.Value byte id)
void tick()
void updateControlFlags()
void tickHeadTurn(final float yBodyRotT)
void addAdditionalSaveData(final ValueOutput output)
void readAdditionalSaveData(final ValueInput input)
void dropFromLootTable(final ServerLevel level, final DamageSource source, final boolean playerKilled)
Optional<ResourceKey<LootTable>> getLootTable()
long getLootTableSeed()
void setZza(final float zza)
void setYya(final float yya)
void setXxa(final float xxa)
void setSpeed(final float speed)
void stopInPlace()
void aiStep()
EquipmentSlot sunProtectionSlot()
Vec3i getPickupReach()
void pickUpItem(final ServerLevel level, final ItemEntity entity)
ItemStack equipItemIfPossible(final ServerLevel level, final ItemStack itemStack)
void setItemSlotAndDropWhenKilled(final EquipmentSlot slot, final ItemStack itemStack)
boolean canShearEquipment(final Player player)
boolean attemptToShearEquipment(final Player player, final InteractionHand hand, final ItemStack heldItem)
void shearItem(final Player player, final InteractionHand hand, final ItemStack heldItem, final EquipmentSlot slot, final ItemStack itemStackToShear)
void setGuaranteedDrop(final EquipmentSlot slot)
boolean canReplaceCurrentItem(final ItemStack newItemStack, final ItemStack currentItemStack, final EquipmentSlot slot)
boolean canReplaceEqualItem(final ItemStack newItemStack, final ItemStack currentItemStack)
boolean canHoldItem(final ItemStack itemStack)
boolean wantsToPickUp(final ServerLevel level, final ItemStack itemStack)
boolean removeWhenFarAway(final double distSqr)
boolean requiresCustomPersistence()
void checkDespawn()
void serverAiStep()
void customServerAiStep(final ServerLevel level)
int getMaxHeadXRot()
int getMaxHeadYRot()
void clampHeadRotationToBody()
int getHeadRotSpeed()
void lookAt(final Entity entity, final float yMax, final float xMax)
boolean checkMobSpawnRules(final EntityType<? extends Mob> type, final LevelAccessor level, final EntitySpawnReason spawnReason, final BlockPos pos, final RandomSource random)
boolean checkSpawnRules(final LevelAccessor level, final EntitySpawnReason spawnReason)
boolean checkSpawnObstruction(final LevelReader level)
int getMaxSpawnClusterSize()
boolean isMaxGroupSizeReached(final int groupSize)
int getMaxFallDistance()
ItemStack getBodyArmorItem()
boolean isSaddled()
boolean isWearingBodyArmor()
Container createEquipmentSlotContainer(final EquipmentSlot slot)
ItemStack getTheItem()
void setTheItem(final ItemStack itemStack)
void setChanged()
boolean stillValid(final Player player)
void dropCustomDeathLoot(final ServerLevel level, final DamageSource source, final boolean killedByPlayer)
DropChances getDropChances()
void dropPreservedEquipment(final ServerLevel level)
Set<EquipmentSlot> dropPreservedEquipment(final ServerLevel level, final Predicate<ItemStack> shouldDrop)
void equip(final EquipmentTable equipment)
void equip(final ResourceKey<LootTable> lootTable, final Map<EquipmentSlot, Float> dropChances)
void populateDefaultEquipmentSlots(final RandomSource random, final DifficultyInstance difficulty)
void populateDefaultEquipmentEnchantments(final ServerLevelAccessor level, final RandomSource random, final DifficultyInstance localDifficulty)
void enchantSpawnedWeapon(final ServerLevelAccessor level, final RandomSource random, final DifficultyInstance difficulty)
void enchantSpawnedArmor(final ServerLevelAccessor level, final RandomSource random, final EquipmentSlot slot, final DifficultyInstance difficulty)
void setPersistenceRequired()
void setDropChance(final EquipmentSlot slot, final float percent)
boolean canPickUpLoot()
void setCanPickUpLoot(final boolean canPickUpLoot)
boolean canDispenserEquipIntoSlot(final EquipmentSlot slot)
boolean isPersistenceRequired()
InteractionResult interact(final Player player, final InteractionHand hand, final Vec3 location)
void onOffspringSpawnedFromEgg(final Player spawner, final Mob offspring)
InteractionResult mobInteract(final Player player, final InteractionHand hand)
void usePlayerItem(final Player player, final InteractionHand hand, final ItemStack itemStack)
boolean isWithinHome()
boolean isWithinHome(final BlockPos pos)
boolean isWithinHome(final Vec3 pos)
void setHomeTo(final BlockPos newCenter, final int radius)
BlockPos getHomePosition()
int getHomeRadius()
void clearHome()
boolean hasHome()
void setLeashData(final Leashable.@Nullable LeashData leashData)
void onLeashRemoved()
void leashTooFarBehaviour()
boolean canBeLeashed()
boolean startRiding(final Entity entity, final boolean force, final boolean sendEventAndTriggers)
boolean isEffectiveAi()
void setNoAi(final boolean flag)
void setLeftHanded(final boolean flag)
void setAggressive(final boolean flag)
boolean isNoAi()
boolean isLeftHanded()
boolean isAggressive()
void setBaby(final boolean baby)
HumanoidArm getMainArm()
boolean isWithinMeleeAttackRange(final LivingEntity target)

…and 12 more (see full source).

Fields & Constants (49)

DATA_MOB_FLAGS_ID
MOB_FLAG_NO_AI
MOB_FLAG_LEFTHANDED
MOB_FLAG_AGGRESSIVE
PICKUP_REACH
ITEM_PICKUP_REACH
EQUIPMENT_POPULATION_ORDER
MAX_WEARING_ARMOR_CHANCE
WEARING_ARMOR_UPGRADE_MATERIAL_CHANCE
WEARING_ARMOR_UPGRADE_MATERIAL_ATTEMPTS
MAX_PICKUP_LOOT_CHANCE
MAX_ENCHANTED_ARMOR_CHANCE
MAX_ENCHANTED_WEAPON_CHANCE
UPDATE_GOAL_SELECTOR_EVERY_N_TICKS
DEFAULT_ATTACK_REACH
DEFAULT_CAN_PICK_UP_LOOT
DEFAULT_PERSISTENCE_REQUIRED
DEFAULT_LEFT_HANDED
DEFAULT_NO_AI
RANDOM_SPAWN_BONUS_ID
TAG_DROP_CHANCES
TAG_LEFT_HANDED
TAG_CAN_PICK_UP_LOOT
TAG_NO_AI
TAG_PERSISTENCE_REQUIRED
ambientSoundTime
xpReward
lookControl
moveControl
jumpControl
bodyRotationControl
navigation
goalSelector
targetSelector
target
sensing
dropChances
canPickUpLoot
persistenceRequired
pathfindingMalus
lootTable
lootTableSeed
leashData
homePosition
homeRadius
pos
chance
spawnReason
params

String literals (21)

"random_spawn_bonus"
"drop_chances"
"LeftHanded"
"CanPickUpLoot"
"NoAI"
"PersistenceRequired"
"mobBaseTick"
"home_radius"
"home_pos"
"DeathLootTable"
"DeathLootTableSeed"
"looting"
"sensing"
"targetSelector"
"goalSelector"
"navigation"
"mob tick"
"controls"
"move"
"look"
"jump"

Code Graph: Dependencies (80)

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

Full Source

Mob.java1474 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.entity;
2
3
import com.google.common.annotations.VisibleForTesting;
4
import com.google.common.collect.Maps;
5
import it.unimi.dsi.fastutil.objects.Object2IntMap.Entry;
6
import java.util.ArrayList;
7
import java.util.HashSet;
8
import java.util.List;
9
import java.util.Map;
10
import java.util.Objects;
11
import java.util.Optional;
12
import java.util.Set;
13
import java.util.function.Predicate;
14
import net.minecraft.advancements.triggers.CriteriaTriggers;
15
import net.minecraft.core.BlockPos;
16
import net.minecraft.core.Holder;
17
import net.minecraft.core.Vec3i;
18
import net.minecraft.core.component.DataComponents;
19
import net.minecraft.network.syncher.EntityDataAccessor;
20
import net.minecraft.network.syncher.EntityDataSerializers;
21
import net.minecraft.network.syncher.SynchedEntityData;
22
import net.minecraft.resources.Identifier;
23
import net.minecraft.resources.ResourceKey;
24
import net.minecraft.server.level.ServerLevel;
25
import net.minecraft.server.level.ServerPlayer;
26
import net.minecraft.sounds.SoundEvent;
27
import net.minecraft.tags.EntityTypeTags;
28
import net.minecraft.tags.TagKey;
29
import net.minecraft.util.Mth;
30
import net.minecraft.util.RandomSource;
31
import net.minecraft.util.VisibleForDebug;
32
import net.minecraft.util.debug.DebugBrainDump;
33
import net.minecraft.util.debug.DebugGoalInfo;
34
import net.minecraft.util.debug.DebugPathInfo;
35
import net.minecraft.util.debug.DebugSubscriptions;
36
import net.minecraft.util.debug.DebugValueSource;
37
import net.minecraft.util.profiling.Profiler;
38
import net.minecraft.util.profiling.ProfilerFiller;
39
import net.minecraft.world.Container;
40
import net.minecraft.world.Difficulty;
41
import net.minecraft.world.DifficultyInstance;
42
import net.minecraft.world.InteractionHand;
43
import net.minecraft.world.InteractionResult;
44
import net.minecraft.world.attribute.EnvironmentAttributes;
45
import net.minecraft.world.damagesource.DamageSource;
46
import net.minecraft.world.entity.ai.attributes.Attribute;
47
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
48
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
49
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
50
import net.minecraft.world.entity.ai.attributes.Attributes;
51
import net.minecraft.world.entity.ai.control.BodyRotationControl;
52
import net.minecraft.world.entity.ai.control.JumpControl;
53
import net.minecraft.world.entity.ai.control.LookControl;
54
import net.minecraft.world.entity.ai.control.MoveControl;
55
import net.minecraft.world.entity.ai.goal.Goal;
56
import net.minecraft.world.entity.ai.goal.GoalSelector;
57
import net.minecraft.world.entity.ai.goal.WrappedGoal;
58
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
59
import net.minecraft.world.entity.ai.navigation.GroundPathNavigation;
60
import net.minecraft.world.entity.ai.navigation.PathNavigation;
61
import net.minecraft.world.entity.ai.sensing.Sensing;
62
import net.minecraft.world.entity.item.ItemEntity;
63
import net.minecraft.world.entity.monster.Enemy;
64
import net.minecraft.world.entity.player.Player;
65
import net.minecraft.world.entity.vehicle.boat.AbstractBoat;
66
import net.minecraft.world.item.Item;
67
import net.minecraft.world.item.ItemStack;
68
import net.minecraft.world.item.Items;
69
import net.minecraft.world.item.SpawnEggItem;
70
import net.minecraft.world.item.component.AttackRange;
71
import net.minecraft.world.item.component.ItemAttributeModifiers;
72
import net.minecraft.world.item.component.SwingAnimation;
73
import net.minecraft.world.item.component.UseRemainder;
74
import net.minecraft.world.item.enchantment.Enchantment;
75
import net.minecraft.world.item.enchantment.EnchantmentEffectComponents;
76
import net.minecraft.world.item.enchantment.EnchantmentHelper;
77
import net.minecraft.world.item.enchantment.ItemEnchantments;
78
import net.minecraft.world.item.enchantment.providers.VanillaEnchantmentProviders;
79
import net.minecraft.world.item.equipment.Equippable;
80
import net.minecraft.world.level.Level;
81
import net.minecraft.world.level.LevelAccessor;
82
import net.minecraft.world.level.LevelReader;
83
import net.minecraft.world.level.ServerLevelAccessor;
84
import net.minecraft.world.level.gameevent.GameEvent;
85
import net.minecraft.world.level.gamerules.GameRules;
86
import net.minecraft.world.level.material.Fluid;
87
import net.minecraft.world.level.pathfinder.Path;
88
import net.minecraft.world.level.pathfinder.PathType;
89
import net.minecraft.world.level.storage.ValueInput;
90
import net.minecraft.world.level.storage.ValueOutput;
91
import net.minecraft.world.level.storage.loot.LootParams;
92
import net.minecraft.world.level.storage.loot.LootTable;
93
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
94
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
95
import net.minecraft.world.phys.AABB;
96
import net.minecraft.world.phys.Vec3;
97
import net.minecraft.world.ticks.ContainerSingleItem;
98
import org.jspecify.annotations.Nullable;
99
100
public abstract class Mob extends LivingEntity implements Targeting, EquipmentUser, Leashable {
101
	private static final EntityDataAccessor<Byte> DATA_MOB_FLAGS_ID = SynchedEntityData.defineId(Mob.class, EntityDataSerializers.BYTE);
102
	private static final int MOB_FLAG_NO_AI = 1;
103
	private static final int MOB_FLAG_LEFTHANDED = 2;
104
	private static final int MOB_FLAG_AGGRESSIVE = 4;
105
	protected static final int PICKUP_REACH = 1;
106
	private static final Vec3i ITEM_PICKUP_REACH = new Vec3i(1, 0, 1);
107
	private static final List<EquipmentSlot> EQUIPMENT_POPULATION_ORDER = List.of(EquipmentSlot.HEAD, EquipmentSlot.CHEST, EquipmentSlot.LEGS, EquipmentSlot.FEET);
108
	public static final float MAX_WEARING_ARMOR_CHANCE = 0.15F;
109
	public static final float WEARING_ARMOR_UPGRADE_MATERIAL_CHANCE = 0.1087F;
110
	public static final float WEARING_ARMOR_UPGRADE_MATERIAL_ATTEMPTS = 3.0F;
111
	public static final float MAX_PICKUP_LOOT_CHANCE = 0.55F;
112
	public static final float MAX_ENCHANTED_ARMOR_CHANCE = 0.5F;
113
	public static final float MAX_ENCHANTED_WEAPON_CHANCE = 0.25F;
114
	public static final int UPDATE_GOAL_SELECTOR_EVERY_N_TICKS = 2;
115
	private static final double DEFAULT_ATTACK_REACH = Math.sqrt(2.04F) - 0.6F;
116
	private static final boolean DEFAULT_CAN_PICK_UP_LOOT = false;
117
	private static final boolean DEFAULT_PERSISTENCE_REQUIRED = false;
118
	private static final boolean DEFAULT_LEFT_HANDED = false;
119
	private static final boolean DEFAULT_NO_AI = false;
120
	protected static final Identifier RANDOM_SPAWN_BONUS_ID = Identifier.withDefaultNamespace("random_spawn_bonus");
121
	public static final String TAG_DROP_CHANCES = "drop_chances";
122
	public static final String TAG_LEFT_HANDED = "LeftHanded";
123
	public static final String TAG_CAN_PICK_UP_LOOT = "CanPickUpLoot";
124
	public static final String TAG_NO_AI = "NoAI";
125
	public static final String TAG_PERSISTENCE_REQUIRED = "PersistenceRequired";
126
	public int ambientSoundTime;
127
	protected int xpReward;
128
	protected LookControl lookControl;
129
	protected MoveControl moveControl;
130
	protected JumpControl jumpControl;
131
	private final BodyRotationControl bodyRotationControl;
132
	protected PathNavigation navigation;
133
	protected final GoalSelector goalSelector;
134
	protected final GoalSelector targetSelector;
135
	private @Nullable LivingEntity target;
136
	private final Sensing sensing;
137
	private DropChances dropChances = DropChances.DEFAULT;
138
	private boolean canPickUpLoot = false;
139
	private boolean persistenceRequired = false;
140
	private final Map<PathType, Float> pathfindingMalus = Maps.newEnumMap(PathType.class);
141
	private Optional<ResourceKey<LootTable>> lootTable = Optional.empty();
142
	private long lootTableSeed;
143
	private Leashable.@Nullable LeashData leashData;
144
	private BlockPos homePosition = BlockPos.ZERO;
145
	private int homeRadius = -1;
146
147
	protected Mob(final EntityType<? extends Mob> type, final Level level) {
148
		super(type, level);
149
		this.goalSelector = new GoalSelector();
150
		this.targetSelector = new GoalSelector();
151
		this.lookControl = new LookControl(this);
152
		this.moveControl = new MoveControl<>(this);
153
		this.jumpControl = new JumpControl(this);
154
		this.bodyRotationControl = this.createBodyControl();
155
		this.navigation = this.createNavigation(level);
156
		this.sensing = new Sensing(this);
157
		if (level instanceof ServerLevel) {
158
			this.registerGoals();
159
		}
160
	}
161
162
	protected void registerGoals() {
163
	}
164
165
	public static AttributeSupplier.Builder createMobAttributes() {
166
		return LivingEntity.createLivingAttributes().add(Attributes.FOLLOW_RANGE, 16.0);
167
	}
168
169
	protected PathNavigation createNavigation(final Level level) {
170
		return new GroundPathNavigation(this, level);
171
	}
172
173
	protected boolean shouldPassengersInheritMalus() {
174
		return false;
175
	}
176
177
	public float getPathfindingMalus(final PathType pathType) {
178
		Mob inheritFrom;
179
		if (this.getControlledVehicle() instanceof Mob riding && riding.shouldPassengersInheritMalus()) {
180
			inheritFrom = riding;
181
		} else {
182
			inheritFrom = this;
183
		}
184
185
		Float malus = inheritFrom.pathfindingMalus.get(pathType);
186
		return malus == null ? pathType.getMalus() : malus;
187
	}
188
189
	public void setPathfindingMalus(final PathType pathType, final float cost) {
190
		this.pathfindingMalus.put(pathType, cost);
191
	}
192
193
	public void onPathfindingStart() {
194
	}
195
196
	public void onPathfindingDone() {
197
	}
198
199
	protected BodyRotationControl createBodyControl() {
200
		return new BodyRotationControl(this);
201
	}
202
203
	public LookControl getLookControl() {
204
		return this.lookControl;
205
	}
206
207
	public MoveControl getMoveControl() {
208
		return this.getControlledVehicle() instanceof Mob riding ? riding.getMoveControl() : this.moveControl;
209
	}
210
211
	public JumpControl getJumpControl() {
212
		return this.jumpControl;
213
	}
214
215
	public PathNavigation getNavigation() {
216
		return this.getControlledVehicle() instanceof Mob riding ? riding.getNavigation() : this.navigation;
217
	}
218
219
	@Override
220
	public @Nullable LivingEntity getControllingPassenger() {
221
		Entity firstPassenger = this.getFirstPassenger();
222
		return !this.isNoAi() && firstPassenger instanceof Mob passenger && firstPassenger.canControlVehicle() ? passenger : null;
223
	}
224
225
	public Sensing getSensing() {
226
		return this.sensing;
227
	}
228
229
	@Override
230
	public @Nullable LivingEntity getTarget() {
231
		return this.asValidTarget(this.target);
232
	}
233
234
	public @Nullable LivingEntity getTargetUnchecked() {
235
		return this.target;
236
	}
237
238
	protected @Nullable LivingEntity asValidTarget(final @Nullable LivingEntity target) {
239
		if (target instanceof Player player && (player.isCreative() || player.isSpectator())) {
240
			return null;
241
		} else {
242
			return target != null && !this.canAttack(target) ? null : target;
243
		}
244
	}
245
246
	protected final @Nullable LivingEntity getTargetFromBrain() {
247
		return this.asValidTarget(this.getBrain().getMemory(MemoryModuleType.ATTACK_TARGET).orElse(null));
248
	}
249
250
	public void setTarget(final @Nullable LivingEntity target) {
251
		this.target = this.asValidTarget(target);
252
	}
253
254
	@Override
255
	public boolean canAttack(final LivingEntity target) {
256
		return !target.is(EntityTypes.GHAST) && super.canAttack(target);
257
	}
258
259
	public boolean canUseNonMeleeWeapon(final ItemStack item) {
260
		return false;
261
	}
262
263
	public void ate() {
264
		this.gameEvent(GameEvent.EAT);
265
	}
266
267
	@Override
268
	protected void defineSynchedData(final SynchedEntityData.Builder entityData) {
269
		super.defineSynchedData(entityData);
270
		entityData.define(DATA_MOB_FLAGS_ID, (byte)0);
271
	}
272
273
	public int getAmbientSoundInterval() {
274
		return 80;
275
	}
276
277
	public void playAmbientSound() {
278
		this.makeSound(this.getAmbientSound());
279
	}
280
281
	@Override
282
	public void baseTick() {
283
		super.baseTick();
284
		ProfilerFiller profiler = Profiler.get();
285
		profiler.push("mobBaseTick");
286
		if (this.isAlive() && this.random.nextInt(1000) < this.ambientSoundTime++) {
287
			this.resetAmbientSoundTime();
288
			this.playAmbientSound();
289
		}
290
291
		profiler.pop();
292
	}
293
294
	@Override
295
	protected void playHurtSound(final DamageSource source) {
296
		this.resetAmbientSoundTime();
297
		super.playHurtSound(source);
298
	}
299
300
	private void resetAmbientSoundTime() {
301
		this.ambientSoundTime = -this.getAmbientSoundInterval();
302
	}
303
304
	@Override
305
	protected int getBaseExperienceReward(final ServerLevel level) {
306
		if (this.xpReward > 0) {
307
			int result = this.xpReward;
308
309
			for (EquipmentSlot slot : EquipmentSlot.VALUES) {
310
				if (slot.canIncreaseExperience()) {
311
					ItemStack item = this.getItemBySlot(slot);
312
					if (!item.isEmpty() && this.dropChances.byEquipment(slot) <= 1.0F) {
313
						result += 1 + this.random.nextInt(3);
314
					}
315
				}
316
			}
317
318
			return result;
319
		} else {
320
			return this.xpReward;
321
		}
322
	}
323
324
	public void spawnAnim() {
325
		if (this.level().isClientSide()) {
326
			this.makePoofParticles();
327
		} else {
328
			this.level().broadcastEntityEvent(this, (byte)20);
329
		}
330
	}
331
332
	@Override
333
	public void handleEntityEvent(final @EntityEvent.Value byte id) {
334
		if (id == 20) {
335
			this.spawnAnim();
336
		} else {
337
			super.handleEntityEvent(id);
338
		}
339
	}
340
341
	@Override
342
	public void tick() {
343
		super.tick();
344
		if (!this.level().isClientSide() && this.tickCount % 5 == 0) {
345
			this.updateControlFlags();
346
		}
347
	}
348
349
	protected void updateControlFlags() {
350
		boolean noController = !(this.getControllingPassenger() instanceof Mob);
351
		boolean notInBoat = !(this.getVehicle() instanceof AbstractBoat);
352
		this.goalSelector.setControlFlag(Goal.Flag.MOVE, noController);
353
		this.goalSelector.setControlFlag(Goal.Flag.JUMP, noController && notInBoat);
354
		this.goalSelector.setControlFlag(Goal.Flag.LOOK, noController);
355
	}
356
357
	@Override
358
	protected void tickHeadTurn(final float yBodyRotT) {
359
		this.bodyRotationControl.clientTick();
360
	}
361
362
	protected @Nullable SoundEvent getAmbientSound() {
363
		return null;
364
	}
365
366
	@Override
367
	protected void addAdditionalSaveData(final ValueOutput output) {
368
		super.addAdditionalSaveData(output);
369
		output.putBoolean("CanPickUpLoot", this.canPickUpLoot());
370
		output.putBoolean("PersistenceRequired", this.persistenceRequired);
371
		if (!this.dropChances.equals(DropChances.DEFAULT)) {
372
			output.store("drop_chances", DropChances.CODEC, this.dropChances);
373
		}
374
375
		this.writeLeashData(output, this.leashData);
376
		if (this.hasHome()) {
377
			output.putInt("home_radius", this.homeRadius);
378
			output.store("home_pos", BlockPos.CODEC, this.homePosition);
379
		}
380
381
		output.putBoolean("LeftHanded", this.isLeftHanded());
382
		this.lootTable.ifPresent(lootTable -> output.store("DeathLootTable", LootTable.KEY_CODEC, (ResourceKey<LootTable>)lootTable));
383
		if (this.lootTableSeed != 0L) {
384
			output.putLong("DeathLootTableSeed", this.lootTableSeed);
385
		}
386
387
		if (this.isNoAi()) {
388
			output.putBoolean("NoAI", this.isNoAi());
389
		}
390
	}
391
392
	@Override
393
	protected void readAdditionalSaveData(final ValueInput input) {
394
		super.readAdditionalSaveData(input);
395
		this.setCanPickUpLoot(input.getBooleanOr("CanPickUpLoot", false));
396
		this.persistenceRequired = input.getBooleanOr("PersistenceRequired", false);
397
		this.dropChances = input.read("drop_chances", DropChances.CODEC).orElse(DropChances.DEFAULT);
398
		this.readLeashData(input);
399
		this.homeRadius = input.getIntOr("home_radius", -1);
400
		if (this.homeRadius >= 0) {
401
			this.homePosition = input.read("home_pos", BlockPos.CODEC).orElse(BlockPos.ZERO);
402
		}
403
404
		this.setLeftHanded(input.getBooleanOr("LeftHanded", false));
405
		this.lootTable = input.read("DeathLootTable", LootTable.KEY_CODEC);
406
		this.lootTableSeed = input.getLongOr("DeathLootTableSeed", 0L);
407
		this.setNoAi(input.getBooleanOr("NoAI", false));
408
	}
409
410
	@Override
411
	protected void dropFromLootTable(final ServerLevel level, final DamageSource source, final boolean playerKilled) {
412
		super.dropFromLootTable(level, source, playerKilled);
413
		this.lootTable = Optional.empty();
414
	}
415
416
	@Override
417
	public final Optional<ResourceKey<LootTable>> getLootTable() {
418
		return this.lootTable.isPresent() ? this.lootTable : super.getLootTable();
419
	}
420
421
	@Override
422
	public long getLootTableSeed() {
423
		return this.lootTableSeed;
424
	}
425
426
	public void setZza(final float zza) {
427
		this.zza = zza;
428
	}
429
430
	public void setYya(final float yya) {
431
		this.yya = yya;
432
	}
433
434
	public void setXxa(final float xxa) {
435
		this.xxa = xxa;
436
	}
437
438
	@Override
439
	public void setSpeed(final float speed) {
440
		super.setSpeed(speed);
441
		this.setZza(speed);
442
	}
443
444
	public void stopInPlace() {
445
		this.getNavigation().stop();
446
		this.setXxa(0.0F);
447
		this.setYya(0.0F);
448
		this.setSpeed(0.0F);
449
		this.setDeltaMovement(0.0, 0.0, 0.0);
450
		this.resetAngularLeashMomentum();
451
	}
452
453
	@Override
454
	public void aiStep() {
455
		super.aiStep();
456
		if (this.is(EntityTypeTags.BURN_IN_DAYLIGHT)) {
457
			this.burnUndead();
458
		}
459
460
		ProfilerFiller profiler = Profiler.get();
461
		profiler.push("looting");
462
		if (this.level() instanceof ServerLevel serverLevel
463
			&& this.canPickUpLoot()
464
			&& this.isAlive()
465
			&& !this.dead
466
			&& serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) {
467
			Vec3i pickupReach = this.getPickupReach();
468
469
			for (ItemEntity entity : this.level()
470
				.getEntitiesOfClass(ItemEntity.class, this.getBoundingBox().inflate(pickupReach.getX(), pickupReach.getY(), pickupReach.getZ()))) {
471
				if (!entity.isRemoved() && !entity.getItem().isEmpty() && !entity.hasPickUpDelay() && this.wantsToPickUp(serverLevel, entity.getItem())) {
472
					this.pickUpItem(serverLevel, entity);
473
				}
474
			}
475
		}
476
477
		profiler.pop();
478
	}
479
480
	protected EquipmentSlot sunProtectionSlot() {
481
		return EquipmentSlot.HEAD;
482
	}
483
484
	private void burnUndead() {
485
		if (this.isAlive() && this.isSunBurnTick()) {
486
			EquipmentSlot slot = this.sunProtectionSlot();
487
			ItemStack sunBlocker = this.getItemBySlot(slot);
488
			if (!sunBlocker.isEmpty()) {
489
				if (sunBlocker.isDamageableItem()) {
490
					sunBlocker.hurtAndBreak(this.random.nextInt(2), this, slot);
491
				}
492
			} else {
493
				this.igniteForSeconds(8.0F);
494
			}
495
		}
496
	}
497
498
	private boolean isSunBurnTick() {
499
		if (!this.level().isClientSide() && this.level().environmentAttributes().getValue(EnvironmentAttributes.MONSTERS_BURN, this.position())) {
500
			float br = this.getLightLevelDependentMagicValue();
501
			BlockPos roundedPos = BlockPos.containing(this.getX(), this.getEyeY(), this.getZ());
502
			boolean isInNonBurnableBlock = this.isInWaterOrRain() || this.isInPowderSnow || this.wasInPowderSnow;
503
			if (br > 0.5F && this.random.nextFloat() * 30.0F < (br - 0.4F) * 2.0F && !isInNonBurnableBlock && this.level().canSeeSky(roundedPos)) {
504
				return true;
505
			}
506
		}
507
508
		return false;
509
	}
510
511
	protected Vec3i getPickupReach() {
512
		return ITEM_PICKUP_REACH;
513
	}
514
515
	protected void pickUpItem(final ServerLevel level, final ItemEntity entity) {
516
		ItemStack itemStack = entity.getItem();
517
		ItemStack equippedWithStack = this.equipItemIfPossible(level, itemStack.copy());
518
		if (!equippedWithStack.isEmpty()) {
519
			this.onItemPickup(entity);
520
			this.take(entity, equippedWithStack.getCount());
521
			itemStack.shrink(equippedWithStack.getCount());
522
			if (itemStack.isEmpty()) {
523
				entity.discard();
524
			}
525
		}
526
	}
527
528
	public ItemStack equipItemIfPossible(final ServerLevel level, final ItemStack itemStack) {
529
		EquipmentSlot slot = this.getEquipmentSlotForItem(itemStack);
530
		if (!this.isEquippableInSlot(itemStack, slot)) {
531
			return ItemStack.EMPTY;
532
		}
533
534
		ItemStack current = this.getItemBySlot(slot);
535
		boolean canReplace = this.canReplaceCurrentItem(itemStack, current, slot);
536
		if (slot.isArmor() && !canReplace) {
537
			slot = EquipmentSlot.MAINHAND;
538
			current = this.getItemBySlot(slot);
539
			canReplace = current.isEmpty();
540
		}
541
542
		if (canReplace && this.canHoldItem(itemStack)) {
543
			double dropChance = this.dropChances.byEquipment(slot);
544
			if (!current.isEmpty() && Math.max(this.random.nextFloat() - 0.1F, 0.0F) < dropChance) {
545
				this.spawnAtLocation(level, current);
546
			}
547
548
			ItemStack toEquip = slot.limit(itemStack);
549
			this.setItemSlotAndDropWhenKilled(slot, toEquip);
550
			this.persistenceRequired = true;
551
			return toEquip;
552
		} else {
553
			return ItemStack.EMPTY;
554
		}
555
	}
556
557
	protected void setItemSlotAndDropWhenKilled(final EquipmentSlot slot, final ItemStack itemStack) {
558
		this.setItemSlot(slot, itemStack);
559
		this.setGuaranteedDrop(slot);
560
	}
561
562
	protected boolean canShearEquipment(final Player player) {
563
		return !this.isVehicle();
564
	}
565
566
	protected boolean attemptToShearEquipment(final Player player, final InteractionHand hand, final ItemStack heldItem) {
567
		for (EquipmentSlot slot : EquipmentSlot.VALUES) {
568
			ItemStack itemStack = this.getItemBySlot(slot);
569
			Equippable equippable = itemStack.get(DataComponents.EQUIPPABLE);
570
			if (equippable != null
571
				&& equippable.canBeSheared()
572
				&& (!EnchantmentHelper.has(itemStack, EnchantmentEffectComponents.PREVENT_ARMOR_CHANGE) || player.isCreative())) {
573
				this.shearItem(player, hand, heldItem, slot, itemStack);
574
				this.playSound(equippable.shearingSound().value());
575
				return true;
576
			}
577
		}
578
579
		return false;
580
	}
581
582
	protected void shearItem(final Player player, final InteractionHand hand, final ItemStack heldItem, final EquipmentSlot slot, final ItemStack itemStackToShear) {
583
		heldItem.hurtAndBreak(1, player, hand.asEquipmentSlot());
584
		Vec3 equipmentSpawnOffset = this.getAttachments().getAverage(EntityAttachment.PASSENGER);
585
		this.setItemSlot(slot, ItemStack.EMPTY);
586
		this.gameEvent(GameEvent.SHEAR, player);
587
		if (this.level() instanceof ServerLevel serverLevel) {
588
			this.spawnAtLocation(serverLevel, itemStackToShear, equipmentSpawnOffset);
589
			CriteriaTriggers.PLAYER_SHEARED_EQUIPMENT.trigger((ServerPlayer)player, itemStackToShear, this);
590
		}
591
	}
592
593
	public void setGuaranteedDrop(final EquipmentSlot slot) {
594
		this.dropChances = this.dropChances.withGuaranteedDrop(slot);
595
	}
596
597
	protected boolean canReplaceCurrentItem(final ItemStack newItemStack, final ItemStack currentItemStack, final EquipmentSlot slot) {
598
		if (currentItemStack.isEmpty()) {
599
			return true;
600
		} else if (slot.isArmor()) {
601
			return this.compareArmor(newItemStack, currentItemStack, slot);
602
		} else {
603
			return slot == EquipmentSlot.MAINHAND ? this.compareWeapons(newItemStack, currentItemStack, slot) : false;
604
		}
605
	}
606
607
	private boolean compareArmor(final ItemStack newItemStack, final ItemStack currentItemStack, final EquipmentSlot slot) {
608
		if (EnchantmentHelper.has(currentItemStack, EnchantmentEffectComponents.PREVENT_ARMOR_CHANGE)) {
609
			return false;
610
		} else {
611
			double newDefense = this.getApproximateAttributeWith(newItemStack, Attributes.ARMOR, slot);
612
			double oldDefense = this.getApproximateAttributeWith(currentItemStack, Attributes.ARMOR, slot);
613
			double newToughness = this.getApproximateAttributeWith(newItemStack, Attributes.ARMOR_TOUGHNESS, slot);
614
			double oldToughness = this.getApproximateAttributeWith(currentItemStack, Attributes.ARMOR_TOUGHNESS, slot);
615
			if (newDefense != oldDefense) {
616
				return newDefense > oldDefense;
617
			} else {
618
				return newToughness != oldToughness ? newToughness > oldToughness : this.canReplaceEqualItem(newItemStack, currentItemStack);
619
			}
620
		}
621
	}
622
623
	private boolean compareWeapons(final ItemStack newItemStack, final ItemStack currentItemStack, final EquipmentSlot slot) {
624
		TagKey<Item> preferredWeaponType = this.getPreferredWeaponType();
625
		if (preferredWeaponType != null) {
626
			if (currentItemStack.is(preferredWeaponType) && !newItemStack.is(preferredWeaponType)) {
627
				return false;
628
			}
629
630
			if (!currentItemStack.is(preferredWeaponType) && newItemStack.is(preferredWeaponType)) {
631
				return true;
632
			}
633
		}
634
635
		double newAttackDamage = this.getApproximateAttributeWith(newItemStack, Attributes.ATTACK_DAMAGE, slot);
636
		double oldAttackDamage = this.getApproximateAttributeWith(currentItemStack, Attributes.ATTACK_DAMAGE, slot);
637
		return newAttackDamage != oldAttackDamage ? newAttackDamage > oldAttackDamage : this.canReplaceEqualItem(newItemStack, currentItemStack);
638
	}
639
640
	private double getApproximateAttributeWith(final ItemStack itemStack, final Holder<Attribute> attribute, final EquipmentSlot slot) {
641
		double baseValue = this.getAttributes().hasAttribute(attribute) ? this.getAttributeBaseValue(attribute) : 0.0;
642
		ItemAttributeModifiers attributeModifiers = itemStack.getOrDefault(DataComponents.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY);
643
		return attributeModifiers.compute(attribute, baseValue, slot);
644
	}
645
646
	public boolean canReplaceEqualItem(final ItemStack newItemStack, final ItemStack currentItemStack) {
647
		Set<Entry<Holder<Enchantment>>> currentEnchantments = currentItemStack.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY).entrySet();
648
		Set<Entry<Holder<Enchantment>>> newEnchantments = newItemStack.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY).entrySet();
649
		if (newEnchantments.size() != currentEnchantments.size()) {
650
			return newEnchantments.size() > currentEnchantments.size();
651
		}
652
653
		int newDamageValue = newItemStack.getDamageValue();
654
		int currentDamageValue = currentItemStack.getDamageValue();
655
		return newDamageValue != currentDamageValue
656
			? newDamageValue < currentDamageValue
657
			: newItemStack.has(DataComponents.CUSTOM_NAME) && !currentItemStack.has(DataComponents.CUSTOM_NAME);
658
	}
659
660
	public boolean canHoldItem(final ItemStack itemStack) {
661
		return true;
662
	}
663
664
	public boolean wantsToPickUp(final ServerLevel level, final ItemStack itemStack) {
665
		return this.canHoldItem(itemStack);
666
	}
667
668
	public @Nullable TagKey<Item> getPreferredWeaponType() {
669
		return null;
670
	}
671
672
	public boolean removeWhenFarAway(final double distSqr) {
673
		return true;
674
	}
675
676
	public boolean requiresCustomPersistence() {
677
		return this.isPassenger() || this.isLeashed();
678
	}
679
680
	@Override
681
	public void checkDespawn() {
682
		if (this.level().getDifficulty() == Difficulty.PEACEFUL && !this.getType().isAllowedInPeaceful()) {
683
			this.discard();
684
		} else {
685
			boolean isPersistent = this.isPersistenceRequired() || this.requiresCustomPersistence();
686
			Entity player = this.level().getNearestPlayer(this, -1.0);
687
			if (player != null) {
688
				double distSqr = player.distanceToSqr(this);
689
				int instantDespawnDistance = this.getType().getCategory().getDespawnDistance();
690
				int despawnDistanceSqr = instantDespawnDistance * instantDespawnDistance;
691
				if (!isPersistent && distSqr > despawnDistanceSqr && this.removeWhenFarAway(distSqr)) {
692
					this.discard();
693
				}
694
695
				int noDespawnDistance = this.getType().getCategory().getNoDespawnDistance();
696
				int noDespawnDistanceSqr = noDespawnDistance * noDespawnDistance;
697
				if (!isPersistent && this.noActionTime > 600 && this.random.nextInt(800) == 0 && distSqr > noDespawnDistanceSqr && this.removeWhenFarAway(distSqr)) {
698
					this.discard();
699
				} else if (distSqr < noDespawnDistanceSqr) {
700
					this.noActionTime = 0;
701
				}
702
			}
703
		}
704
	}
705
706
	@Override
707
	protected final void serverAiStep() {
708
		this.noActionTime++;
709
		ProfilerFiller profiler = Profiler.get();
710
		profiler.push("sensing");
711
		this.sensing.tick();
712
		profiler.pop();
713
		int idBasedTickCount = this.tickCount + this.getId();
714
		if (idBasedTickCount % 2 != 0 && this.tickCount > 1) {
715
			profiler.push("targetSelector");
716
			this.targetSelector.tickRunningGoals(false);
717
			profiler.pop();
718
			profiler.push("goalSelector");
719
			this.goalSelector.tickRunningGoals(false);
720
			profiler.pop();
721
		} else {
722
			profiler.push("targetSelector");
723
			this.targetSelector.tick();
724
			profiler.pop();
725
			profiler.push("goalSelector");
726
			this.goalSelector.tick();
727
			profiler.pop();
728
		}
729
730
		profiler.push("navigation");
731
		this.navigation.tick();
732
		profiler.pop();
733
		profiler.push("mob tick");
734
		this.customServerAiStep((ServerLevel)this.level());
735
		profiler.pop();
736
		profiler.push("controls");
737
		profiler.push("move");
738
		this.moveControl.tick();
739
		profiler.popPush("look");
740
		this.lookControl.tick();
741
		profiler.popPush("jump");
742
		this.jumpControl.tick();
743
		profiler.pop();
744
		profiler.pop();
745
	}
746
747
	protected void customServerAiStep(final ServerLevel level) {
748
	}
749
750
	public int getMaxHeadXRot() {
751
		return 40;
752
	}
753
754
	public int getMaxHeadYRot() {
755
		return 75;
756
	}
757
758
	public void clampHeadRotationToBody() {
759
		float limit = this.getMaxHeadYRot();
760
		float headYRot = this.getYHeadRot();
761
		float delta = Mth.wrapDegrees(this.yBodyRot - headYRot);
762
		float targetDelta = Mth.clamp(Mth.wrapDegrees(this.yBodyRot - headYRot), -limit, limit);
763
		float newHeadYRot = headYRot + delta - targetDelta;
764
		this.setYHeadRot(newHeadYRot);
765
	}
766
767
	public int getHeadRotSpeed() {
768
		return 10;
769
	}
770
771
	public void lookAt(final Entity entity, final float yMax, final float xMax) {
772
		double xd = entity.getX() - this.getX();
773
		double zd = entity.getZ() - this.getZ();
774
		double yd;
775
		if (entity instanceof LivingEntity mob) {
776
			yd = mob.getEyeY() - this.getEyeY();
777
		} else {
778
			yd = (entity.getBoundingBox().minY + entity.getBoundingBox().maxY) / 2.0 - this.getEyeY();
779
		}
780
781
		double sd = Math.sqrt(xd * xd + zd * zd);
782
		float yRotD = (float)(Mth.atan2(zd, xd) * 180.0F / (float)Math.PI) - 90.0F;
783
		float xRotD = (float)(-(Mth.atan2(yd, sd) * 180.0F / (float)Math.PI));
784
		this.setXRot(this.rotlerp(this.getXRot(), xRotD, xMax));
785
		this.setYRot(this.rotlerp(this.getYRot(), yRotD, yMax));
786
	}
787
788
	private float rotlerp(final float a, final float b, final float max) {
789
		float diff = Mth.wrapDegrees(b - a);
790
		if (diff > max) {
791
			diff = max;
792
		}
793
794
		if (diff < -max) {
795
			diff = -max;
796
		}
797
798
		return a + diff;
799
	}
800
801
	public static boolean checkMobSpawnRules(
802
		final EntityType<? extends Mob> type, final LevelAccessor level, final EntitySpawnReason spawnReason, final BlockPos pos, final RandomSource random
803
	) {
804
		BlockPos below = pos.below();
805
		return EntitySpawnReason.isSpawner(spawnReason) || level.getBlockState(below).isValidSpawn(level, below, type);
806
	}
807
808
	public boolean checkSpawnRules(final LevelAccessor level, final EntitySpawnReason spawnReason) {
809
		return true;
810
	}
811
812
	public boolean checkSpawnObstruction(final LevelReader level) {
813
		return !level.containsAnyLiquid(this.getBoundingBox()) && level.isUnobstructed(this);
814
	}
815
816
	public int getMaxSpawnClusterSize() {
817
		return 4;
818
	}
819
820
	public boolean isMaxGroupSizeReached(final int groupSize) {
821
		return false;
822
	}
823
824
	@Override
825
	public int getMaxFallDistance() {
826
		if (this.getTarget() == null) {
827
			return this.getComfortableFallDistance(0.0F);
828
		}
829
830
		int sacrifice = (int)(this.getHealth() - this.getMaxHealth() * 0.33F);
831
		sacrifice -= (3 - this.level().getDifficulty().getId()) * 4;
832
		if (sacrifice < 0) {
833
			sacrifice = 0;
834
		}
835
836
		return this.getComfortableFallDistance(sacrifice);
837
	}
838
839
	public ItemStack getBodyArmorItem() {
840
		return this.getItemBySlot(EquipmentSlot.BODY);
841
	}
842
843
	public boolean isSaddled() {
844
		return this.hasValidEquippableItemForSlot(EquipmentSlot.SADDLE);
845
	}
846
847
	public boolean isWearingBodyArmor() {
848
		return this.hasValidEquippableItemForSlot(EquipmentSlot.BODY);
849
	}
850
851
	private boolean hasValidEquippableItemForSlot(final EquipmentSlot slot) {
852
		return this.hasItemInSlot(slot) && this.isEquippableInSlot(this.getItemBySlot(slot), slot);
853
	}
854
855
	public Container createEquipmentSlotContainer(final EquipmentSlot slot) {
856
		return new ContainerSingleItem() {
857
			@Override
858
			public ItemStack getTheItem() {
859
				return Mob.this.getItemBySlot(slot);
860
			}
861
862
			@Override
863
			public void setTheItem(final ItemStack itemStack) {
864
				Mob.this.setItemSlot(slot, itemStack);
865
				if (!itemStack.isEmpty()) {
866
					Mob.this.setGuaranteedDrop(slot);
867
					Mob.this.setPersistenceRequired();
868
				}
869
			}
870
871
			@Override
872
			public void setChanged() {
873
			}
874
875
			@Override
876
			public boolean stillValid(final Player player) {
877
				return player.getVehicle() == Mob.this || player.isWithinEntityInteractionRange(Mob.this, 4.0);
878
			}
879
		};
880
	}
881
882
	@Override
883
	protected void dropCustomDeathLoot(final ServerLevel level, final DamageSource source, final boolean killedByPlayer) {
884
		super.dropCustomDeathLoot(level, source, killedByPlayer);
885
886
		for (EquipmentSlot slot : EquipmentSlot.VALUES) {
887
			ItemStack itemStack = this.getItemBySlot(slot);
888
			float dropChance = this.dropChances.byEquipment(slot);
889
			if (dropChance != 0.0F) {
890
				boolean preserve = this.dropChances.isPreserved(slot);
891
				if (source.getEntity() instanceof LivingEntity livingSource && this.level() instanceof ServerLevel serverLevel) {
892
					dropChance = EnchantmentHelper.processEquipmentDropChance(serverLevel, livingSource, source, dropChance);
893
				}
894
895
				if (!itemStack.isEmpty()
896
					&& !EnchantmentHelper.has(itemStack, EnchantmentEffectComponents.PREVENT_EQUIPMENT_DROP)
897
					&& (killedByPlayer || preserve)
898
					&& this.random.nextFloat() < dropChance) {
899
					if (!preserve && itemStack.isDamageableItem()) {
900
						itemStack.setDamageValue(itemStack.getMaxDamage() - this.random.nextInt(1 + this.random.nextInt(Math.max(itemStack.getMaxDamage() - 3, 1))));
901
					}
902
903
					this.spawnAtLocation(level, itemStack);
904
					this.setItemSlot(slot, ItemStack.EMPTY);
905
				}
906
			}
907
		}
908
	}
909
910
	public DropChances getDropChances() {
911
		return this.dropChances;
912
	}
913
914
	public void dropPreservedEquipment(final ServerLevel level) {
915
		this.dropPreservedEquipment(level, stack -> true);
916
	}
917
918
	public Set<EquipmentSlot> dropPreservedEquipment(final ServerLevel level, final Predicate<ItemStack> shouldDrop) {
919
		Set<EquipmentSlot> slotsPreventedFromDropping = new HashSet<>();
920
921
		for (EquipmentSlot slot : EquipmentSlot.VALUES) {
922
			ItemStack itemStack = this.getItemBySlot(slot);
923
			if (!itemStack.isEmpty()) {
924
				if (!shouldDrop.test(itemStack)) {
925
					slotsPreventedFromDropping.add(slot);
926
				} else if (this.dropChances.isPreserved(slot)) {
927
					this.setItemSlot(slot, ItemStack.EMPTY);
928
					this.spawnAtLocation(level, itemStack);
929
				}
930
			}
931
		}
932
933
		return slotsPreventedFromDropping;
934
	}
935
936
	private LootParams createEquipmentParams(final ServerLevel serverLevel) {
937
		return new LootParams.Builder(serverLevel)
938
			.withParameter(LootContextParams.ORIGIN, this.position())
939
			.withParameter(LootContextParams.THIS_ENTITY, this)
940
			.create(LootContextParamSets.EQUIPMENT);
941
	}
942
943
	public void equip(final EquipmentTable equipment) {
944
		this.equip(equipment.lootTable(), equipment.slotDropChances());
945
	}
946
947
	public void equip(final ResourceKey<LootTable> lootTable, final Map<EquipmentSlot, Float> dropChances) {
948
		if (this.level() instanceof ServerLevel serverLevel) {
949
			this.equip(lootTable, this.createEquipmentParams(serverLevel), dropChances);
950
		}
951
	}
952
953
	protected void populateDefaultEquipmentSlots(final RandomSource random, final DifficultyInstance difficulty) {
954
		if (random.nextFloat() < 0.15F * difficulty.getSpecialMultiplier()) {
955
			int armorType = random.nextInt(3);
956
957
			for (int i = 1; i <= 3.0F; i++) {
958
				if (random.nextFloat() < 0.1087F) {
959
					armorType++;
960
				}
961
			}
962
963
			float partialChance = this.level().getDifficulty() == Difficulty.HARD ? 0.1F : 0.25F;
964
			boolean first = true;
965
966
			for (EquipmentSlot slot : EQUIPMENT_POPULATION_ORDER) {
967
				ItemStack itemStack = this.getItemBySlot(slot);
968
				if (!first && random.nextFloat() < partialChance) {
969
					break;
970
				}
971
972
				first = false;
973
				if (itemStack.isEmpty()) {
974
					Item equip = getEquipmentForSlot(slot, armorType);
975
					if (equip != null) {
976
						this.setItemSlot(slot, new ItemStack(equip));
977
					}
978
				}
979
			}
980
		}
981
	}
982
983
	public static @Nullable Item getEquipmentForSlot(final EquipmentSlot slot, final int type) {
984
		switch (slot) {
985
			case HEAD:
986
				if (type == 0) {
987
					return Items.LEATHER_HELMET;
988
				} else if (type == 1) {
989
					return Items.COPPER_HELMET;
990
				} else if (type == 2) {
991
					return Items.GOLDEN_HELMET;
992
				} else if (type == 3) {
993
					return Items.CHAINMAIL_HELMET;
994
				} else if (type == 4) {
995
					return Items.IRON_HELMET;
996
				} else if (type == 5) {
997
					return Items.DIAMOND_HELMET;
998
				}
999
			case CHEST:
1000
				if (type == 0) {
1001
					return Items.LEATHER_CHESTPLATE;
1002
				} else if (type == 1) {
1003
					return Items.COPPER_CHESTPLATE;
1004
				} else if (type == 2) {
1005
					return Items.GOLDEN_CHESTPLATE;
1006
				} else if (type == 3) {
1007
					return Items.CHAINMAIL_CHESTPLATE;
1008
				} else if (type == 4) {
1009
					return Items.IRON_CHESTPLATE;
1010
				} else if (type == 5) {
1011
					return Items.DIAMOND_CHESTPLATE;
1012
				}
1013
			case LEGS:
1014
				if (type == 0) {
1015
					return Items.LEATHER_LEGGINGS;
1016
				} else if (type == 1) {
1017
					return Items.COPPER_LEGGINGS;
1018
				} else if (type == 2) {
1019
					return Items.GOLDEN_LEGGINGS;
1020
				} else if (type == 3) {
1021
					return Items.CHAINMAIL_LEGGINGS;
1022
				} else if (type == 4) {
1023
					return Items.IRON_LEGGINGS;
1024
				} else if (type == 5) {
1025
					return Items.DIAMOND_LEGGINGS;
1026
				}
1027
			case FEET:
1028
				if (type == 0) {
1029
					return Items.LEATHER_BOOTS;
1030
				} else if (type == 1) {
1031
					return Items.COPPER_BOOTS;
1032
				} else if (type == 2) {
1033
					return Items.GOLDEN_BOOTS;
1034
				} else if (type == 3) {
1035
					return Items.CHAINMAIL_BOOTS;
1036
				} else if (type == 4) {
1037
					return Items.IRON_BOOTS;
1038
				} else if (type == 5) {
1039
					return Items.DIAMOND_BOOTS;
1040
				}
1041
			default:
1042
				return null;
1043
		}
1044
	}
1045
1046
	protected void populateDefaultEquipmentEnchantments(final ServerLevelAccessor level, final RandomSource random, final DifficultyInstance localDifficulty) {
1047
		this.enchantSpawnedWeapon(level, random, localDifficulty);
1048
1049
		for (EquipmentSlot slot : EquipmentSlot.VALUES) {
1050
			if (slot.getType() == EquipmentSlot.Type.HUMANOID_ARMOR) {
1051
				this.enchantSpawnedArmor(level, random, slot, localDifficulty);
1052
			}
1053
		}
1054
	}
1055
1056
	protected void enchantSpawnedWeapon(final ServerLevelAccessor level, final RandomSource random, final DifficultyInstance difficulty) {
1057
		this.enchantSpawnedEquipment(level, EquipmentSlot.MAINHAND, random, 0.25F, difficulty);
1058
	}
1059
1060
	protected void enchantSpawnedArmor(final ServerLevelAccessor level, final RandomSource random, final EquipmentSlot slot, final DifficultyInstance difficulty) {
1061
		this.enchantSpawnedEquipment(level, slot, random, 0.5F, difficulty);
1062
	}
1063
1064
	private void enchantSpawnedEquipment(
1065
		final ServerLevelAccessor level, final EquipmentSlot slot, final RandomSource random, final float chance, final DifficultyInstance difficulty
1066
	) {
1067
		ItemStack itemStack = this.getItemBySlot(slot);
1068
		if (!itemStack.isEmpty() && random.nextFloat() < chance * difficulty.getSpecialMultiplier()) {
1069
			EnchantmentHelper.enchantItemFromProvider(itemStack, level.registryAccess(), VanillaEnchantmentProviders.MOB_SPAWN_EQUIPMENT, difficulty, random);
1070
			this.setItemSlot(slot, itemStack);
1071
		}
1072
	}
1073
1074
	public @Nullable SpawnGroupData finalizeSpawn(
1075
		final ServerLevelAccessor level, final DifficultyInstance difficulty, final EntitySpawnReason spawnReason, final @Nullable SpawnGroupData groupData
1076
	) {
1077
		RandomSource random = level.getRandom();
1078
		AttributeInstance followRange = Objects.requireNonNull(this.getAttribute(Attributes.FOLLOW_RANGE));
1079
		if (!followRange.hasModifier(RANDOM_SPAWN_BONUS_ID)) {
1080
			followRange.addPermanentModifier(
1081
				new AttributeModifier(RANDOM_SPAWN_BONUS_ID, random.triangle(0.0, 0.11485000000000001), AttributeModifier.Operation.ADD_MULTIPLIED_BASE)
1082
			);
1083
		}
1084
1085
		this.setLeftHanded(random.nextFloat() < 0.05F);
1086
		return groupData;
1087
	}
1088
1089
	public void setPersistenceRequired() {
1090
		this.persistenceRequired = true;
1091
	}
1092
1093
	@Override
1094
	public void setDropChance(final EquipmentSlot slot, final float percent) {
1095
		this.dropChances = this.dropChances.withEquipmentChance(slot, percent);
1096
	}
1097
1098
	@Override
1099
	public boolean canPickUpLoot() {
1100
		return this.canPickUpLoot;
1101
	}
1102
1103
	public void setCanPickUpLoot(final boolean canPickUpLoot) {
1104
		this.canPickUpLoot = canPickUpLoot;
1105
	}
1106
1107
	@Override
1108
	protected boolean canDispenserEquipIntoSlot(final EquipmentSlot slot) {
1109
		return this.canPickUpLoot();
1110
	}
1111
1112
	public boolean isPersistenceRequired() {
1113
		return this.persistenceRequired;
1114
	}
1115
1116
	@Override
1117
	public InteractionResult interact(final Player player, final InteractionHand hand, final Vec3 location) {
1118
		if (!this.isAlive()) {
1119
			return InteractionResult.PASS;
1120
		} else {
1121
			InteractionResult interactionResult = this.checkAndHandleImportantInteractions(player, hand);
1122
			if (interactionResult.consumesAction()) {
1123
				this.gameEvent(GameEvent.ENTITY_INTERACT, player);
1124
				return interactionResult;
1125
			} else {
1126
				InteractionResult superReaction = super.interact(player, hand, location);
1127
				if (superReaction != InteractionResult.PASS) {
1128
					return superReaction;
1129
				} else {
1130
					interactionResult = this.mobInteract(player, hand);
1131
					if (interactionResult.consumesAction()) {
1132
						this.gameEvent(GameEvent.ENTITY_INTERACT, player);
1133
						return interactionResult;
1134
					} else {
1135
						return InteractionResult.PASS;
1136
					}
1137
				}
1138
			}
1139
		}
1140
	}
1141
1142
	private InteractionResult checkAndHandleImportantInteractions(final Player player, final InteractionHand hand) {
1143
		ItemStack itemStack = player.getItemInHand(hand);
1144
		if (itemStack.is(Items.NAME_TAG)) {
1145
			InteractionResult nameTagInteractionResult = itemStack.interactLivingEntity(player, this, hand);
1146
			if (nameTagInteractionResult.consumesAction()) {
1147
				return nameTagInteractionResult;
1148
			}
1149
		}
1150
1151
		if (itemStack.getItem() instanceof SpawnEggItem) {
1152
			if (this.level() instanceof ServerLevel serverLevel) {
1153
				Optional<Mob> offspring = SpawnEggItem.spawnOffspringFromSpawnEgg(
1154
					player, this, (EntityType<? extends Mob>)this.getType(), serverLevel, this.position(), itemStack
1155
				);
1156
				offspring.ifPresent(mob -> this.onOffspringSpawnedFromEgg(player, mob));
1157
				if (offspring.isEmpty()) {
1158
					return InteractionResult.PASS;
1159
				}
1160
			}
1161
1162
			return InteractionResult.SUCCESS_SERVER;
1163
		} else {
1164
			return InteractionResult.PASS;
1165
		}
1166
	}
1167
1168
	protected void onOffspringSpawnedFromEgg(final Player spawner, final Mob offspring) {
1169
	}
1170
1171
	protected InteractionResult mobInteract(final Player player, final InteractionHand hand) {
1172
		return InteractionResult.PASS;
1173
	}
1174
1175
	protected void usePlayerItem(final Player player, final InteractionHand hand, final ItemStack itemStack) {
1176
		int beforeUseCount = itemStack.getCount();
1177
		UseRemainder useRemainder = itemStack.get(DataComponents.USE_REMAINDER);
1178
		itemStack.consume(1, player);
1179
		if (useRemainder != null) {
1180
			ItemStack newHandStack = useRemainder.convertIntoRemainder(itemStack, beforeUseCount, player.hasInfiniteMaterials(), player::handleExtraItemsCreatedOnUse);
1181
			player.setItemInHand(hand, newHandStack);
1182
		}
1183
	}
1184
1185
	public boolean isWithinHome() {
1186
		return this.isWithinHome(this.blockPosition());
1187
	}
1188
1189
	public boolean isWithinHome(final BlockPos pos) {
1190
		return this.homeRadius == -1 ? true : this.homePosition.distSqr(pos) < this.homeRadius * this.homeRadius;
1191
	}
1192
1193
	public boolean isWithinHome(final Vec3 pos) {
1194
		return this.homeRadius == -1 ? true : this.homePosition.distToCenterSqr(pos) < this.homeRadius * this.homeRadius;
1195
	}
1196
1197
	public void setHomeTo(final BlockPos newCenter, final int radius) {
1198
		this.homePosition = newCenter;
1199
		this.homeRadius = radius;
1200
	}
1201
1202
	public BlockPos getHomePosition() {
1203
		return this.homePosition;
1204
	}
1205
1206
	public int getHomeRadius() {
1207
		return this.homeRadius;
1208
	}
1209
1210
	public void clearHome() {
1211
		this.homeRadius = -1;
1212
	}
1213
1214
	public boolean hasHome() {
1215
		return this.homeRadius != -1;
1216
	}
1217
1218
	public <T extends Mob> @Nullable T convertTo(
1219
		final EntityType<T> entityType, final ConversionParams params, final EntitySpawnReason spawnReason, final ConversionParams.AfterConversion<T> afterConversion
1220
	) {
1221
		if (this.isRemoved()) {
1222
			return null;
1223
		}
1224
1225
		T newMob = (T)entityType.create(this.level(), spawnReason);
1226
		if (newMob == null) {
1227
			return null;
1228
		}
1229
1230
		params.type().convert(this, newMob, params);
1231
		afterConversion.finalizeConversion(newMob);
1232
		if (this.level() instanceof ServerLevel serverLevel) {
1233
			serverLevel.addFreshEntity(newMob);
1234
		}
1235
1236
		if (params.type().shouldDiscardAfterConversion()) {
1237
			this.discard();
1238
		}
1239
1240
		return newMob;
1241
	}
1242
1243
	public <T extends Mob> @Nullable T convertTo(
1244
		final EntityType<T> entityType, final ConversionParams params, final ConversionParams.AfterConversion<T> afterConversion
1245
	) {
1246
		return this.convertTo(entityType, params, EntitySpawnReason.CONVERSION, afterConversion);
1247
	}
1248
1249
	@Override
1250
	public Leashable.@Nullable LeashData getLeashData() {
1251
		return this.leashData;
1252
	}
1253
1254
	private void resetAngularLeashMomentum() {
1255
		if (this.leashData != null) {
1256
			this.leashData.angularMomentum = 0.0;
1257
		}
1258
	}
1259
1260
	@Override
1261
	public void setLeashData(final Leashable.@Nullable LeashData leashData) {
1262
		this.leashData = leashData;
1263
	}
1264
1265
	@Override
1266
	public void onLeashRemoved() {
1267
		if (this.getLeashData() == null) {
1268
			this.clearHome();
1269
		}
1270
	}
1271
1272
	@Override
1273
	public void leashTooFarBehaviour() {
1274
		Leashable.super.leashTooFarBehaviour();
1275
		this.goalSelector.disableControlFlag(Goal.Flag.MOVE);
1276
	}
1277
1278
	@Override
1279
	public boolean canBeLeashed() {
1280
		return !(this instanceof Enemy);
1281
	}
1282
1283
	@Override
1284
	public boolean startRiding(final Entity entity, final boolean force, final boolean sendEventAndTriggers) {
1285
		boolean result = super.startRiding(entity, force, sendEventAndTriggers);
1286
		if (result && this.isLeashed()) {
1287
			this.dropLeash();
1288
		}
1289
1290
		return result;
1291
	}
1292
1293
	@Override
1294
	public boolean isEffectiveAi() {
1295
		return super.isEffectiveAi() && !this.isNoAi();
1296
	}
1297
1298
	public void setNoAi(final boolean flag) {
1299
		byte val = this.entityData.get(DATA_MOB_FLAGS_ID);
1300
		this.entityData.set(DATA_MOB_FLAGS_ID, flag ? (byte)(val | 1) : (byte)(val & -2));
1301
	}
1302
1303
	public void setLeftHanded(final boolean flag) {
1304
		byte val = this.entityData.get(DATA_MOB_FLAGS_ID);
1305
		this.entityData.set(DATA_MOB_FLAGS_ID, flag ? (byte)(val | 2) : (byte)(val & -3));
1306
	}
1307
1308
	public void setAggressive(final boolean flag) {
1309
		byte val = this.entityData.get(DATA_MOB_FLAGS_ID);
1310
		this.entityData.set(DATA_MOB_FLAGS_ID, flag ? (byte)(val | 4) : (byte)(val & -5));
1311
	}
1312
1313
	public boolean isNoAi() {
1314
		return (this.entityData.get(DATA_MOB_FLAGS_ID) & 1) != 0;
1315
	}
1316
1317
	public boolean isLeftHanded() {
1318
		return (this.entityData.get(DATA_MOB_FLAGS_ID) & 2) != 0;
1319
	}
1320
1321
	public boolean isAggressive() {
1322
		return (this.entityData.get(DATA_MOB_FLAGS_ID) & 4) != 0;
1323
	}
1324
1325
	public void setBaby(final boolean baby) {
1326
	}
1327
1328
	@Override
1329
	public HumanoidArm getMainArm() {
1330
		return this.isLeftHanded() ? HumanoidArm.LEFT : HumanoidArm.RIGHT;
1331
	}
1332
1333
	public boolean isWithinMeleeAttackRange(final LivingEntity target) {
1334
		AttackRange attackRange = this.getActiveItem().get(DataComponents.ATTACK_RANGE);
1335
		double maxRange;
1336
		double minRange;
1337
		if (attackRange == null) {
1338
			maxRange = DEFAULT_ATTACK_REACH;
1339
			minRange = 0.0;
1340
		} else {
1341
			maxRange = attackRange.effectiveMaxRange(this);
1342
			minRange = attackRange.effectiveMinRange(this);
1343
		}
1344
1345
		AABB hitbox = target.getHitbox();
1346
		return this.getAttackBoundingBox(maxRange).intersects(hitbox) && (minRange <= 0.0 || !this.getAttackBoundingBox(minRange).intersects(hitbox));
1347
	}
1348
1349
	protected AABB getAttackBoundingBox(final double horizontalExpansion) {
1350
		Entity vehicle = this.getVehicle();
1351
		AABB aabb;
1352
		if (vehicle != null) {
1353
			AABB mountAabb = vehicle.getBoundingBox();
1354
			AABB ownAabb = this.getBoundingBox();
1355
			aabb = new AABB(
1356
				Math.min(ownAabb.minX, mountAabb.minX),
1357
				ownAabb.minY,
1358
				Math.min(ownAabb.minZ, mountAabb.minZ),
1359
				Math.max(ownAabb.maxX, mountAabb.maxX),
1360
				ownAabb.maxY,
1361
				Math.max(ownAabb.maxZ, mountAabb.maxZ)
1362
			);
1363
		} else {
1364
			aabb = this.getBoundingBox();
1365
		}
1366
1367
		return aabb.inflate(horizontalExpansion, 0.0, horizontalExpansion);
1368
	}
1369
1370
	@Override
1371
	public boolean doHurtTarget(final ServerLevel level, final Entity target) {
1372
		float dmg = (float)this.getAttributeValue(Attributes.ATTACK_DAMAGE);
1373
		ItemStack weaponItem = this.getWeaponItem();
1374
		DamageSource damageSource = weaponItem.getDamageSource(this);
1375
		dmg = EnchantmentHelper.modifyDamage(level, weaponItem, target, damageSource, dmg);
1376
		dmg += weaponItem.getItem().getAttackDamageBonus(target, dmg, damageSource);
1377
		Vec3 oldMovement = target.getDeltaMovement();
1378
		boolean wasHurt = target.hurtServer(level, damageSource, dmg);
1379
		if (wasHurt) {
1380
			this.causeExtraKnockback(target, this.getKnockback(target, damageSource), oldMovement, damageSource, dmg, true);
1381
			if (target instanceof LivingEntity livingTarget) {
1382
				weaponItem.hurtEnemy(livingTarget, this);
1383
			}
1384
1385
			EnchantmentHelper.doPostAttackEffects(level, target, damageSource);
1386
			this.setLastHurtMob(target);
1387
			this.playAttackSound();
1388
		}
1389
1390
		this.postPiercingAttack();
1391
		return wasHurt;
1392
	}
1393
1394
	@Override
1395
	protected void jumpInLiquid(final TagKey<Fluid> type) {
1396
		if (this.getNavigation().canFloat()) {
1397
			super.jumpInLiquid(type);
1398
		} else {
1399
			this.setDeltaMovement(this.getDeltaMovement().add(0.0, 0.3, 0.0));
1400
		}
1401
	}
1402
1403
	@VisibleForTesting
1404
	public void removeFreeWill() {
1405
		this.removeAllGoals(goal -> true);
1406
		this.getBrain().removeAllBehaviors();
1407
	}
1408
1409
	@VisibleForDebug
1410
	@VisibleForTesting
1411
	public GoalSelector getGoalSelector() {
1412
		return this.goalSelector;
1413
	}
1414
1415
	public void removeAllGoals(final Predicate<Goal> predicate) {
1416
		this.goalSelector.removeAllGoals(predicate);
1417
	}
1418
1419
	@Override
1420
	protected void removeAfterChangingDimensions() {
1421
		super.removeAfterChangingDimensions();
1422
1423
		for (EquipmentSlot slot : EquipmentSlot.VALUES) {
1424
			ItemStack itemStack = this.getItemBySlot(slot);
1425
			if (!itemStack.isEmpty()) {
1426
				itemStack.setCount(0);
1427
			}
1428
		}
1429
	}
1430
1431
	@Override
1432
	public @Nullable ItemStack getPickResult() {
1433
		return SpawnEggItem.byId(this.getType()).map(ItemStack::new).orElse(null);
1434
	}
1435
1436
	@Override
1437
	protected void onAttributeUpdated(final Holder<Attribute> attribute) {
1438
		super.onAttributeUpdated(attribute);
1439
		if (attribute.is(Attributes.FOLLOW_RANGE) || attribute.is(Attributes.TEMPT_RANGE)) {
1440
			this.getNavigation().updatePathfinderMaxVisitedNodes();
1441
		}
1442
	}
1443
1444
	@Override
1445
	public void registerDebugValues(final ServerLevel level, final DebugValueSource.Registration registration) {
1446
		registration.register(DebugSubscriptions.ENTITY_PATHS, () -> {
1447
			Path path = this.getNavigation().getPath();
1448
			return path != null && path.debugData() != null ? new DebugPathInfo(path.copy(), this.getNavigation().getMaxDistanceToWaypoint()) : null;
1449
		});
1450
		registration.register(DebugSubscriptions.GOAL_SELECTORS, () -> {
1451
			Set<WrappedGoal> availableGoals = this.goalSelector.getAvailableGoals();
1452
			List<DebugGoalInfo.DebugGoal> goalInfo = new ArrayList<>(availableGoals.size());
1453
			availableGoals.forEach(goal -> goalInfo.add(new DebugGoalInfo.DebugGoal(goal.getPriority(), goal.isRunning(), goal.getGoal().getClass().getSimpleName())));
1454
			return new DebugGoalInfo(goalInfo);
1455
		});
1456
		if (!this.brain.isBrainDead()) {
1457
			registration.register(DebugSubscriptions.BRAINS, () -> DebugBrainDump.takeBrainDump(level, this));
1458
		}
1459
	}
1460
1461
	public float chargeSpeedModifier() {
1462
		return 1.0F;
1463
	}
1464
1465
	public void swingForAttack(final InteractionHand hand) {
1466
		SwingAnimation swingAnimation = this.getItemInHand(hand).getAttackAnimation();
1467
		this.swing(hand, swingAnimation, false);
1468
	}
1469
1470
	public void swing(final InteractionHand hand, final SwingAnimation animation) {
1471
		this.swing(hand, animation, false);
1472
	}
1473
}
1474

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