Bee .java

net.minecraft.world.entity.animal.bee.Bee (class): members: remainingCooldownBeforeLocatingNewFlower, resetTicksWithoutNectarSinceExitingHive, hasStung.

net.minecraft.world.entity.animal.beeclass1,346 linescommonextends Animal42.8 KB

Implements

API Surface (89)

void defineSynchedData(final SynchedEntityData.Builder entityData)
float getWalkTargetValue(final BlockPos pos, final LevelReader level)
void registerGoals()
void addAdditionalSaveData(final ValueOutput output)
void readAdditionalSaveData(final ValueInput input)
boolean doHurtTarget(final ServerLevel level, final Entity target)
void tick()
boolean hasSavedFlowerPos()
void setSavedFlowerPos(final BlockPos savedFlowerPos)
int getTravellingTicks()
List<BlockPos> getBlacklistedHives()
void setStayOutOfHiveCountdown(final int ticks)
float getRollAmount(final float a)
void customServerAiStep(final ServerLevel level)
void resetTicksWithoutNectarSinceExitingHive()
long getPersistentAngerEndTime()
void setPersistentAngerEndTime(final long endTime)
void setPersistentAngerTarget(final @Nullable EntityReference<LivingEntity> persistentAngerTarget)
void startPersistentAngerTimer()
boolean hasHive()
void aiStep()
boolean hasNectar()
boolean hasStung()
AttributeSupplier.Builder createAttributes()
PathNavigation createNavigation(final Level level)
boolean isStableDestination(final BlockPos pos)
void tick()
InteractionResult mobInteract(final Player player, final InteractionHand hand)
boolean isFood(final ItemStack itemStack)
void playStepSound(final BlockPos pos, final BlockState blockState)
SoundEvent getAmbientSound()
SoundEvent getHurtSound(final DamageSource source)
SoundEvent getDeathSound()
float getSoundVolume()
void checkFallDamage(final double ya, final boolean onGround, final BlockState onState, final BlockPos pos)
boolean isFlapping()
boolean isFlying()
boolean omnidirectionalAirMover()
void dropOffNectar()
boolean hurtServer(final ServerLevel level, final DamageSource source, final float damage)
void jumpInLiquid(final TagKey<Fluid> type)
Vec3 getLeashOffset()
void setHivePos(final BlockPos hivePos)
boolean attractsBees(final BlockState state)
void registerDebugValues(final ServerLevel level, final DebugValueSource.Registration registration)
boolean canUse()
boolean canContinueToUse()
boolean canUse()
boolean canContinueToUse()
boolean canUse()
boolean canContinueToUse()
boolean canBeeUse()
boolean canBeeContinueToUse()
void start()
boolean canBeeUse()
boolean canBeeContinueToUse()
void start()
void stop()
void tick()
boolean canBeeUse()
boolean canBeeContinueToUse()
void start()
void stop()
void tick()
boolean canBeeUse()
boolean canBeeContinueToUse()
void tick()
boolean canContinueToUse()
void alertOther(final Mob other, final LivingEntity hurtByMob)
boolean canBeeUse()
boolean canBeeContinueToUse()
void start()
void tick()
boolean resetXRotOnTick()
boolean canBeeUse()
boolean canBeeContinueToUse()
void start()
void stop()
boolean requiresUpdateEveryTick()
void tick()
boolean canUse()
boolean canContinueToUse()
void start()
void start()
boolean canBeeUse()
boolean canBeeContinueToUse()
void start()
boolean canBeeUse()
boolean canBeeContinueToUse()

Fields & Constants (53)

FLAP_DEGREES_PER_TICK
TICKS_PER_FLAP
DATA_FLAGS_ID
DATA_ANGER_END_TIME
FLAG_ROLL
FLAG_HAS_STUNG
FLAG_HAS_NECTAR
STING_DEATH_COUNTDOWN
TICKS_BEFORE_GOING_TO_KNOWN_FLOWER
TICKS_WITHOUT_NECTAR_BEFORE_GOING_HOME
MIN_ATTACK_DIST
MAX_CROPS_GROWABLE
POISON_SECONDS_NORMAL
POISON_SECONDS_HARD
TOO_FAR_DISTANCE
HIVE_CLOSE_ENOUGH_DISTANCE
RESTRICTED_WANDER_DISTANCE_REDUCTION
DEFAULT_WANDER_DISTANCE_REDUCTION
PATHFIND_TO_HIVE_WHEN_CLOSER_THAN
HIVE_SEARCH_DISTANCE
TAG_CROPS_GROWN_SINCE_POLLINATION
TAG_CANNOT_ENTER_HIVE_TICKS
TAG_TICKS_SINCE_POLLINATION
TAG_HAS_STUNG
TAG_HAS_NECTAR
TAG_FLOWER_POS
TAG_HIVE_POS
DEFAULT_HAS_NECTAR
DEFAULT_HAS_STUNG
DEFAULT_TICKS_SINCE_POLLINATION
DEFAULT_CANNOT_ENTER_HIVE_TICKS
DEFAULT_CROPS_GROWN_SINCE_POLLINATION
PERSISTENT_ANGER_TIME
COOLDOWN_BEFORE_LOCATING_NEW_HIVE
COOLDOWN_BEFORE_LOCATING_NEW_FLOWER
MIN_FIND_FLOWER_RETRY_COOLDOWN
MAX_FIND_FLOWER_RETRY_COOLDOWN
persistentAngerTarget
rollAmount
rollAmountO
timeSinceSting
ticksWithoutNectarSinceExitingHive
stayOutOfHiveCountdown
numCropsGrownSincePollination
remainingCooldownBeforeLocatingNewHive
remainingCooldownBeforeLocatingNewFlower
savedFlowerPos
hivePos
beePollinateGoal
goToHiveGoal
goToKnownFlowerGoal
underWaterTicks
y

String literals (7)

"CropsGrownSincePollination"
"CannotEnterHiveTicks"
"TicksSincePollination"
"HasStung"
"HasNectar"
"flower_pos"
"hive_pos"

Same Package (1)

Code Graph: Dependencies (80)

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

Full Source

Bee.java1346 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.entity.animal.bee;
2
3
import com.google.common.collect.Lists;
4
import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap;
5
import java.util.Comparator;
6
import java.util.EnumSet;
7
import java.util.List;
8
import java.util.Optional;
9
import java.util.stream.Collectors;
10
import java.util.stream.Stream;
11
import net.minecraft.core.BlockPos;
12
import net.minecraft.core.particles.ParticleOptions;
13
import net.minecraft.core.particles.ParticleTypes;
14
import net.minecraft.network.syncher.EntityDataAccessor;
15
import net.minecraft.network.syncher.EntityDataSerializers;
16
import net.minecraft.network.syncher.SynchedEntityData;
17
import net.minecraft.server.level.ServerLevel;
18
import net.minecraft.sounds.SoundEvent;
19
import net.minecraft.sounds.SoundEvents;
20
import net.minecraft.tags.BlockTags;
21
import net.minecraft.tags.ItemTags;
22
import net.minecraft.tags.PoiTypeTags;
23
import net.minecraft.tags.TagKey;
24
import net.minecraft.util.Mth;
25
import net.minecraft.util.TimeUtil;
26
import net.minecraft.util.VisibleForDebug;
27
import net.minecraft.util.debug.DebugBeeInfo;
28
import net.minecraft.util.debug.DebugSubscriptions;
29
import net.minecraft.util.debug.DebugValueSource;
30
import net.minecraft.util.valueproviders.UniformInt;
31
import net.minecraft.world.Difficulty;
32
import net.minecraft.world.InteractionHand;
33
import net.minecraft.world.InteractionResult;
34
import net.minecraft.world.attribute.EnvironmentAttributes;
35
import net.minecraft.world.damagesource.DamageSource;
36
import net.minecraft.world.effect.MobEffectInstance;
37
import net.minecraft.world.effect.MobEffects;
38
import net.minecraft.world.entity.AgeableMob;
39
import net.minecraft.world.entity.Entity;
40
import net.minecraft.world.entity.EntityReference;
41
import net.minecraft.world.entity.EntitySpawnReason;
42
import net.minecraft.world.entity.EntityType;
43
import net.minecraft.world.entity.EntityTypes;
44
import net.minecraft.world.entity.LivingEntity;
45
import net.minecraft.world.entity.Mob;
46
import net.minecraft.world.entity.NeutralMob;
47
import net.minecraft.world.entity.PathfinderMob;
48
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
49
import net.minecraft.world.entity.ai.attributes.Attributes;
50
import net.minecraft.world.entity.ai.control.FlyingMoveControl;
51
import net.minecraft.world.entity.ai.control.LookControl;
52
import net.minecraft.world.entity.ai.goal.BreedGoal;
53
import net.minecraft.world.entity.ai.goal.FloatGoal;
54
import net.minecraft.world.entity.ai.goal.FollowParentGoal;
55
import net.minecraft.world.entity.ai.goal.Goal;
56
import net.minecraft.world.entity.ai.goal.MeleeAttackGoal;
57
import net.minecraft.world.entity.ai.goal.TemptGoal;
58
import net.minecraft.world.entity.ai.goal.target.HurtByTargetGoal;
59
import net.minecraft.world.entity.ai.goal.target.NearestAttackableTargetGoal;
60
import net.minecraft.world.entity.ai.goal.target.ResetUniversalAngerTargetGoal;
61
import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation;
62
import net.minecraft.world.entity.ai.navigation.PathNavigation;
63
import net.minecraft.world.entity.ai.util.AirAndWaterRandomPos;
64
import net.minecraft.world.entity.ai.util.AirRandomPos;
65
import net.minecraft.world.entity.ai.util.HoverRandomPos;
66
import net.minecraft.world.entity.ai.village.poi.PoiManager;
67
import net.minecraft.world.entity.ai.village.poi.PoiRecord;
68
import net.minecraft.world.entity.animal.Animal;
69
import net.minecraft.world.entity.player.Player;
70
import net.minecraft.world.item.BlockItem;
71
import net.minecraft.world.item.ItemStack;
72
import net.minecraft.world.item.enchantment.EnchantmentHelper;
73
import net.minecraft.world.level.Level;
74
import net.minecraft.world.level.LevelReader;
75
import net.minecraft.world.level.block.Block;
76
import net.minecraft.world.level.block.Blocks;
77
import net.minecraft.world.level.block.BonemealSource;
78
import net.minecraft.world.level.block.BonemealableBlock;
79
import net.minecraft.world.level.block.CropBlock;
80
import net.minecraft.world.level.block.DoublePlantBlock;
81
import net.minecraft.world.level.block.FlowerBlock;
82
import net.minecraft.world.level.block.StemBlock;
83
import net.minecraft.world.level.block.SweetBerryBushBlock;
84
import net.minecraft.world.level.block.entity.BeehiveBlockEntity;
85
import net.minecraft.world.level.block.entity.BlockEntityTypes;
86
import net.minecraft.world.level.block.state.BlockState;
87
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
88
import net.minecraft.world.level.block.state.properties.DoubleBlockHalf;
89
import net.minecraft.world.level.material.Fluid;
90
import net.minecraft.world.level.pathfinder.Path;
91
import net.minecraft.world.level.pathfinder.PathType;
92
import net.minecraft.world.level.storage.ValueInput;
93
import net.minecraft.world.level.storage.ValueOutput;
94
import net.minecraft.world.phys.Vec3;
95
import org.jspecify.annotations.Nullable;
96
97
public class Bee extends Animal implements NeutralMob {
98
	public static final float FLAP_DEGREES_PER_TICK = 120.32113F;
99
	public static final int TICKS_PER_FLAP = Mth.ceil(1.4959966F);
100
	private static final EntityDataAccessor<Byte> DATA_FLAGS_ID = SynchedEntityData.defineId(Bee.class, EntityDataSerializers.BYTE);
101
	private static final EntityDataAccessor<Long> DATA_ANGER_END_TIME = SynchedEntityData.defineId(Bee.class, EntityDataSerializers.LONG);
102
	private static final int FLAG_ROLL = 2;
103
	private static final int FLAG_HAS_STUNG = 4;
104
	private static final int FLAG_HAS_NECTAR = 8;
105
	private static final int STING_DEATH_COUNTDOWN = 1200;
106
	private static final int TICKS_BEFORE_GOING_TO_KNOWN_FLOWER = 600;
107
	private static final int TICKS_WITHOUT_NECTAR_BEFORE_GOING_HOME = 3600;
108
	private static final int MIN_ATTACK_DIST = 4;
109
	private static final int MAX_CROPS_GROWABLE = 10;
110
	private static final int POISON_SECONDS_NORMAL = 10;
111
	private static final int POISON_SECONDS_HARD = 18;
112
	private static final int TOO_FAR_DISTANCE = 48;
113
	private static final int HIVE_CLOSE_ENOUGH_DISTANCE = 2;
114
	private static final int RESTRICTED_WANDER_DISTANCE_REDUCTION = 24;
115
	private static final int DEFAULT_WANDER_DISTANCE_REDUCTION = 16;
116
	private static final int PATHFIND_TO_HIVE_WHEN_CLOSER_THAN = 16;
117
	private static final int HIVE_SEARCH_DISTANCE = 20;
118
	public static final String TAG_CROPS_GROWN_SINCE_POLLINATION = "CropsGrownSincePollination";
119
	public static final String TAG_CANNOT_ENTER_HIVE_TICKS = "CannotEnterHiveTicks";
120
	public static final String TAG_TICKS_SINCE_POLLINATION = "TicksSincePollination";
121
	public static final String TAG_HAS_STUNG = "HasStung";
122
	public static final String TAG_HAS_NECTAR = "HasNectar";
123
	public static final String TAG_FLOWER_POS = "flower_pos";
124
	public static final String TAG_HIVE_POS = "hive_pos";
125
	public static final boolean DEFAULT_HAS_NECTAR = false;
126
	private static final boolean DEFAULT_HAS_STUNG = false;
127
	private static final int DEFAULT_TICKS_SINCE_POLLINATION = 0;
128
	private static final int DEFAULT_CANNOT_ENTER_HIVE_TICKS = 0;
129
	private static final int DEFAULT_CROPS_GROWN_SINCE_POLLINATION = 0;
130
	private static final UniformInt PERSISTENT_ANGER_TIME = TimeUtil.rangeOfSeconds(20, 39);
131
	private @Nullable EntityReference<LivingEntity> persistentAngerTarget;
132
	private float rollAmount;
133
	private float rollAmountO;
134
	private int timeSinceSting;
135
	private int ticksWithoutNectarSinceExitingHive = 0;
136
	private int stayOutOfHiveCountdown = 0;
137
	private int numCropsGrownSincePollination = 0;
138
	private static final int COOLDOWN_BEFORE_LOCATING_NEW_HIVE = 200;
139
	private int remainingCooldownBeforeLocatingNewHive;
140
	private static final int COOLDOWN_BEFORE_LOCATING_NEW_FLOWER = 200;
141
	private static final int MIN_FIND_FLOWER_RETRY_COOLDOWN = 20;
142
	private static final int MAX_FIND_FLOWER_RETRY_COOLDOWN = 60;
143
	private int remainingCooldownBeforeLocatingNewFlower = Mth.nextInt(this.random, 20, 60);
144
	private @Nullable BlockPos savedFlowerPos;
145
	private @Nullable BlockPos hivePos;
146
	private Bee.BeePollinateGoal beePollinateGoal;
147
	private Bee.BeeGoToHiveGoal goToHiveGoal;
148
	private Bee.BeeGoToKnownFlowerGoal goToKnownFlowerGoal;
149
	private int underWaterTicks;
150
151
	public Bee(final EntityType<? extends Bee> type, final Level level) {
152
		super(type, level);
153
		this.moveControl = new FlyingMoveControl<>(this, 20, true);
154
		this.lookControl = new Bee.BeeLookControl(this);
155
		this.setPathfindingMalus(PathType.FIRE, -1.0F);
156
		this.setPathfindingMalus(PathType.WATER, -1.0F);
157
		this.setPathfindingMalus(PathType.WATER_BORDER, 16.0F);
158
		this.setPathfindingMalus(PathType.COCOA, -1.0F);
159
		this.setPathfindingMalus(PathType.FENCE, -1.0F);
160
	}
161
162
	@Override
163
	protected void defineSynchedData(final SynchedEntityData.Builder entityData) {
164
		super.defineSynchedData(entityData);
165
		entityData.define(DATA_FLAGS_ID, (byte)0);
166
		entityData.define(DATA_ANGER_END_TIME, -1L);
167
	}
168
169
	@Override
170
	public float getWalkTargetValue(final BlockPos pos, final LevelReader level) {
171
		return level.getBlockState(pos).isAir() ? 10.0F : 0.0F;
172
	}
173
174
	@Override
175
	protected void registerGoals() {
176
		this.goalSelector.addGoal(0, new Bee.BeeAttackGoal(this, 1.4F, true));
177
		this.goalSelector.addGoal(1, new Bee.BeeEnterHiveGoal());
178
		this.goalSelector.addGoal(2, new BreedGoal(this, 1.0));
179
		this.goalSelector.addGoal(3, new TemptGoal(this, 1.25, i -> i.is(ItemTags.BEE_FOOD), false));
180
		this.goalSelector.addGoal(3, new Bee.ValidateHiveGoal());
181
		this.goalSelector.addGoal(3, new Bee.ValidateFlowerGoal());
182
		this.beePollinateGoal = new Bee.BeePollinateGoal();
183
		this.goalSelector.addGoal(4, this.beePollinateGoal);
184
		this.goalSelector.addGoal(5, new FollowParentGoal(this, 1.25));
185
		this.goalSelector.addGoal(5, new Bee.BeeLocateHiveGoal());
186
		this.goToHiveGoal = new Bee.BeeGoToHiveGoal();
187
		this.goalSelector.addGoal(5, this.goToHiveGoal);
188
		this.goToKnownFlowerGoal = new Bee.BeeGoToKnownFlowerGoal();
189
		this.goalSelector.addGoal(6, this.goToKnownFlowerGoal);
190
		this.goalSelector.addGoal(7, new Bee.BeeGrowCropGoal());
191
		this.goalSelector.addGoal(8, new Bee.BeeWanderGoal());
192
		this.goalSelector.addGoal(9, new FloatGoal(this));
193
		this.targetSelector.addGoal(1, new Bee.BeeHurtByOtherGoal(this).setAlertOthers());
194
		this.targetSelector.addGoal(2, new Bee.BeeBecomeAngryTargetGoal(this));
195
		this.targetSelector.addGoal(3, new ResetUniversalAngerTargetGoal<>(this, true));
196
	}
197
198
	@Override
199
	protected void addAdditionalSaveData(final ValueOutput output) {
200
		super.addAdditionalSaveData(output);
201
		output.storeNullable("hive_pos", BlockPos.CODEC, this.hivePos);
202
		output.storeNullable("flower_pos", BlockPos.CODEC, this.savedFlowerPos);
203
		output.putBoolean("HasNectar", this.hasNectar());
204
		output.putBoolean("HasStung", this.hasStung());
205
		output.putInt("TicksSincePollination", this.ticksWithoutNectarSinceExitingHive);
206
		output.putInt("CannotEnterHiveTicks", this.stayOutOfHiveCountdown);
207
		output.putInt("CropsGrownSincePollination", this.numCropsGrownSincePollination);
208
		this.addPersistentAngerSaveData(output);
209
	}
210
211
	@Override
212
	protected void readAdditionalSaveData(final ValueInput input) {
213
		super.readAdditionalSaveData(input);
214
		this.setHasNectar(input.getBooleanOr("HasNectar", false));
215
		this.setHasStung(input.getBooleanOr("HasStung", false));
216
		this.ticksWithoutNectarSinceExitingHive = input.getIntOr("TicksSincePollination", 0);
217
		this.stayOutOfHiveCountdown = input.getIntOr("CannotEnterHiveTicks", 0);
218
		this.numCropsGrownSincePollination = input.getIntOr("CropsGrownSincePollination", 0);
219
		this.hivePos = input.read("hive_pos", BlockPos.CODEC).orElse(null);
220
		this.savedFlowerPos = input.read("flower_pos", BlockPos.CODEC).orElse(null);
221
		this.readPersistentAngerSaveData(this.level(), input);
222
	}
223
224
	@Override
225
	public boolean doHurtTarget(final ServerLevel level, final Entity target) {
226
		DamageSource damageSource = this.damageSources().sting(this);
227
		boolean wasHurt = target.hurtServer(level, damageSource, (int)this.getAttributeValue(Attributes.ATTACK_DAMAGE));
228
		if (wasHurt) {
229
			EnchantmentHelper.doPostAttackEffects(level, target, damageSource);
230
			if (target instanceof LivingEntity livingTarget) {
231
				livingTarget.setStingerCount(livingTarget.getStingerCount() + 1);
232
				int poisonTime = 0;
233
				if (this.level().getDifficulty() == Difficulty.NORMAL) {
234
					poisonTime = 10;
235
				} else if (this.level().getDifficulty() == Difficulty.HARD) {
236
					poisonTime = 18;
237
				}
238
239
				if (poisonTime > 0) {
240
					livingTarget.addEffect(new MobEffectInstance(MobEffects.POISON, poisonTime * 20, 0), this);
241
				}
242
			}
243
244
			this.setHasStung(true);
245
			this.stopBeingAngry();
246
			this.playSound(SoundEvents.BEE_STING, 1.0F, 1.0F);
247
		}
248
249
		return wasHurt;
250
	}
251
252
	@Override
253
	public void tick() {
254
		super.tick();
255
		if (this.hasNectar() && this.getCropsGrownSincePollination() < 10 && this.random.nextFloat() < 0.05F) {
256
			for (int i = 0; i < this.random.nextInt(2) + 1; i++) {
257
				this.spawnFluidParticle(
258
					this.level(), this.getX() - 0.3F, this.getX() + 0.3F, this.getZ() - 0.3F, this.getZ() + 0.3F, this.getY(0.5), ParticleTypes.FALLING_NECTAR
259
				);
260
			}
261
		}
262
263
		this.updateRollAmount();
264
	}
265
266
	private void spawnFluidParticle(
267
		final Level level, final double x1, final double x2, final double z1, final double z2, final double y, final ParticleOptions dripParticle
268
	) {
269
		level.addParticle(dripParticle, Mth.lerp(level.getRandom().nextDouble(), x1, x2), y, Mth.lerp(level.getRandom().nextDouble(), z1, z2), 0.0, 0.0, 0.0);
270
	}
271
272
	private void pathfindRandomlyTowards(final BlockPos targetPos) {
273
		Vec3 targetVec = Vec3.atBottomCenterOf(targetPos);
274
		int yAdjust = 0;
275
		BlockPos beePos = this.blockPosition();
276
		int yDelta = (int)targetVec.y - beePos.getY();
277
		if (yDelta > 2) {
278
			yAdjust = 4;
279
		} else if (yDelta < -2) {
280
			yAdjust = -4;
281
		}
282
283
		int xzDist = 6;
284
		int yDist = 8;
285
		int dist = beePos.distManhattan(targetPos);
286
		if (dist < 15) {
287
			xzDist = dist / 2;
288
			yDist = dist / 2;
289
		}
290
291
		Vec3 nextPosTowards = AirRandomPos.getPosTowards(this, xzDist, yDist, yAdjust, targetVec, (float) (Math.PI / 10));
292
		if (nextPosTowards != null) {
293
			this.navigation.setMaxVisitedNodesMultiplier(0.5F);
294
			this.navigation.moveTo(nextPosTowards.x, nextPosTowards.y, nextPosTowards.z, 1.0);
295
		}
296
	}
297
298
	public @Nullable BlockPos getSavedFlowerPos() {
299
		return this.savedFlowerPos;
300
	}
301
302
	public boolean hasSavedFlowerPos() {
303
		return this.savedFlowerPos != null;
304
	}
305
306
	public void setSavedFlowerPos(final BlockPos savedFlowerPos) {
307
		this.savedFlowerPos = savedFlowerPos;
308
	}
309
310
	@VisibleForDebug
311
	public int getTravellingTicks() {
312
		return Math.max(this.goToHiveGoal.travellingTicks, this.goToKnownFlowerGoal.travellingTicks);
313
	}
314
315
	@VisibleForDebug
316
	public List<BlockPos> getBlacklistedHives() {
317
		return this.goToHiveGoal.blacklistedTargets;
318
	}
319
320
	private boolean isTiredOfLookingForNectar() {
321
		return this.ticksWithoutNectarSinceExitingHive > 3600;
322
	}
323
324
	private void dropHive() {
325
		this.hivePos = null;
326
		this.remainingCooldownBeforeLocatingNewHive = 200;
327
	}
328
329
	private void dropFlower() {
330
		this.savedFlowerPos = null;
331
		this.remainingCooldownBeforeLocatingNewFlower = Mth.nextInt(this.random, 20, 60);
332
	}
333
334
	private boolean wantsToEnterHive() {
335
		if (this.stayOutOfHiveCountdown <= 0 && !this.beePollinateGoal.isPollinating() && !this.hasStung() && this.getTarget() == null) {
336
			boolean wantsToEnterHive = this.hasNectar()
337
				|| this.isTiredOfLookingForNectar()
338
				|| this.level().environmentAttributes().getValue(EnvironmentAttributes.BEES_STAY_IN_HIVE, this.position());
339
			return wantsToEnterHive && !this.isHiveNearFire();
340
		} else {
341
			return false;
342
		}
343
	}
344
345
	public void setStayOutOfHiveCountdown(final int ticks) {
346
		this.stayOutOfHiveCountdown = ticks;
347
	}
348
349
	public float getRollAmount(final float a) {
350
		return Mth.lerp(a, this.rollAmountO, this.rollAmount);
351
	}
352
353
	private void updateRollAmount() {
354
		this.rollAmountO = this.rollAmount;
355
		if (this.isRolling()) {
356
			this.rollAmount = Math.min(1.0F, this.rollAmount + 0.2F);
357
		} else {
358
			this.rollAmount = Math.max(0.0F, this.rollAmount - 0.24F);
359
		}
360
	}
361
362
	@Override
363
	protected void customServerAiStep(final ServerLevel level) {
364
		boolean hasStung = this.hasStung();
365
		if (this.isInWater()) {
366
			this.underWaterTicks++;
367
		} else {
368
			this.underWaterTicks = 0;
369
		}
370
371
		if (this.underWaterTicks > 20) {
372
			this.hurtServer(level, this.damageSources().drown(), 1.0F);
373
		}
374
375
		if (hasStung) {
376
			this.timeSinceSting++;
377
			if (this.timeSinceSting % 5 == 0 && this.random.nextInt(Mth.clamp(1200 - this.timeSinceSting, 1, 1200)) == 0) {
378
				this.hurtServer(level, this.damageSources().generic(), this.getHealth());
379
			}
380
		}
381
382
		if (!this.hasNectar()) {
383
			this.ticksWithoutNectarSinceExitingHive++;
384
		}
385
386
		this.updatePersistentAnger(level, false);
387
	}
388
389
	public void resetTicksWithoutNectarSinceExitingHive() {
390
		this.ticksWithoutNectarSinceExitingHive = 0;
391
	}
392
393
	private boolean isHiveNearFire() {
394
		BeehiveBlockEntity beehiveBlockEntity = this.getBeehiveBlockEntity();
395
		return beehiveBlockEntity != null && beehiveBlockEntity.isFireNearby();
396
	}
397
398
	@Override
399
	public long getPersistentAngerEndTime() {
400
		return this.entityData.get(DATA_ANGER_END_TIME);
401
	}
402
403
	@Override
404
	public void setPersistentAngerEndTime(final long endTime) {
405
		this.entityData.set(DATA_ANGER_END_TIME, endTime);
406
	}
407
408
	@Override
409
	public @Nullable EntityReference<LivingEntity> getPersistentAngerTarget() {
410
		return this.persistentAngerTarget;
411
	}
412
413
	@Override
414
	public void setPersistentAngerTarget(final @Nullable EntityReference<LivingEntity> persistentAngerTarget) {
415
		this.persistentAngerTarget = persistentAngerTarget;
416
	}
417
418
	@Override
419
	public void startPersistentAngerTimer() {
420
		this.setTimeToRemainAngry(PERSISTENT_ANGER_TIME.sample(this.random));
421
	}
422
423
	private boolean doesHiveHaveSpace(final BlockPos hivePos) {
424
		return this.level().getBlockEntity(hivePos) instanceof BeehiveBlockEntity beehiveBlockEntity ? !beehiveBlockEntity.isFull() : false;
425
	}
426
427
	@VisibleForDebug
428
	public boolean hasHive() {
429
		return this.hivePos != null;
430
	}
431
432
	@VisibleForDebug
433
	public @Nullable BlockPos getHivePos() {
434
		return this.hivePos;
435
	}
436
437
	private int getCropsGrownSincePollination() {
438
		return this.numCropsGrownSincePollination;
439
	}
440
441
	private void resetNumCropsGrownSincePollination() {
442
		this.numCropsGrownSincePollination = 0;
443
	}
444
445
	private void incrementNumCropsGrownSincePollination() {
446
		this.numCropsGrownSincePollination++;
447
	}
448
449
	@Override
450
	public void aiStep() {
451
		super.aiStep();
452
		if (!this.level().isClientSide()) {
453
			if (this.stayOutOfHiveCountdown > 0) {
454
				this.stayOutOfHiveCountdown--;
455
			}
456
457
			if (this.remainingCooldownBeforeLocatingNewHive > 0) {
458
				this.remainingCooldownBeforeLocatingNewHive--;
459
			}
460
461
			if (this.remainingCooldownBeforeLocatingNewFlower > 0) {
462
				this.remainingCooldownBeforeLocatingNewFlower--;
463
			}
464
465
			boolean shouldRoll = this.isAngry() && !this.hasStung() && this.getTarget() != null && this.getTarget().distanceToSqr(this) < 4.0;
466
			this.setRolling(shouldRoll);
467
			if (this.tickCount % 20 == 0 && !this.isHiveValid()) {
468
				this.hivePos = null;
469
			}
470
		}
471
	}
472
473
	private @Nullable BeehiveBlockEntity getBeehiveBlockEntity() {
474
		if (this.hivePos == null) {
475
			return null;
476
		} else {
477
			return this.isTooFarAway(this.hivePos) ? null : this.level().getBlockEntity(this.hivePos, BlockEntityTypes.BEEHIVE).orElse(null);
478
		}
479
	}
480
481
	private boolean isHiveValid() {
482
		return this.getBeehiveBlockEntity() != null;
483
	}
484
485
	public boolean hasNectar() {
486
		return this.getFlag(8);
487
	}
488
489
	private void setHasNectar(final boolean hasNectar) {
490
		if (hasNectar) {
491
			this.resetTicksWithoutNectarSinceExitingHive();
492
		}
493
494
		this.setFlag(8, hasNectar);
495
	}
496
497
	public boolean hasStung() {
498
		return this.getFlag(4);
499
	}
500
501
	private void setHasStung(final boolean hasStung) {
502
		this.setFlag(4, hasStung);
503
	}
504
505
	private boolean isRolling() {
506
		return this.getFlag(2);
507
	}
508
509
	private void setRolling(final boolean rolling) {
510
		this.setFlag(2, rolling);
511
	}
512
513
	private boolean isTooFarAway(final BlockPos targetPos) {
514
		return !this.closerThan(targetPos, 48);
515
	}
516
517
	private void setFlag(final int flag, final boolean value) {
518
		if (value) {
519
			this.entityData.set(DATA_FLAGS_ID, (byte)(this.entityData.get(DATA_FLAGS_ID) | flag));
520
		} else {
521
			this.entityData.set(DATA_FLAGS_ID, (byte)(this.entityData.get(DATA_FLAGS_ID) & ~flag));
522
		}
523
	}
524
525
	private boolean getFlag(final int flag) {
526
		return (this.entityData.get(DATA_FLAGS_ID) & flag) != 0;
527
	}
528
529
	public static AttributeSupplier.Builder createAttributes() {
530
		return Animal.createAnimalAttributes()
531
			.add(Attributes.MAX_HEALTH, 10.0)
532
			.add(Attributes.FLYING_SPEED, 0.6F)
533
			.add(Attributes.MOVEMENT_SPEED, 0.3F)
534
			.add(Attributes.ATTACK_DAMAGE, 2.0);
535
	}
536
537
	@Override
538
	protected PathNavigation createNavigation(final Level level) {
539
		FlyingPathNavigation flyingPathNavigation = new FlyingPathNavigation(this, level) {
540
			@Override
541
			public boolean isStableDestination(final BlockPos pos) {
542
				return !this.level.getBlockState(pos.below()).isAir();
543
			}
544
545
			@Override
546
			public void tick() {
547
				if (!Bee.this.beePollinateGoal.isPollinating()) {
548
					super.tick();
549
				}
550
			}
551
		};
552
		flyingPathNavigation.setCanOpenDoors(false);
553
		flyingPathNavigation.setCanFloat(false);
554
		flyingPathNavigation.setRequiredPathLength(48.0F);
555
		return flyingPathNavigation;
556
	}
557
558
	@Override
559
	public InteractionResult mobInteract(final Player player, final InteractionHand hand) {
560
		ItemStack heldItem = player.getItemInHand(hand);
561
		if (this.isFood(heldItem) && heldItem.getItem() instanceof BlockItem blockItem && blockItem.getBlock() instanceof FlowerBlock flower) {
562
			MobEffectInstance effect = flower.getBeeInteractionEffect();
563
			if (effect != null) {
564
				this.usePlayerItem(player, hand, heldItem);
565
				if (!this.level().isClientSide()) {
566
					this.addEffect(effect);
567
				}
568
569
				return InteractionResult.SUCCESS;
570
			}
571
		}
572
573
		return super.mobInteract(player, hand);
574
	}
575
576
	@Override
577
	public boolean isFood(final ItemStack itemStack) {
578
		return itemStack.is(ItemTags.BEE_FOOD);
579
	}
580
581
	@Override
582
	protected void playStepSound(final BlockPos pos, final BlockState blockState) {
583
	}
584
585
	@Override
586
	protected SoundEvent getAmbientSound() {
587
		return null;
588
	}
589
590
	@Override
591
	protected SoundEvent getHurtSound(final DamageSource source) {
592
		return SoundEvents.BEE_HURT;
593
	}
594
595
	@Override
596
	protected SoundEvent getDeathSound() {
597
		return SoundEvents.BEE_DEATH;
598
	}
599
600
	@Override
601
	protected float getSoundVolume() {
602
		return 0.4F;
603
	}
604
605
	public @Nullable Bee getBreedOffspring(final ServerLevel level, final AgeableMob partner) {
606
		return EntityTypes.BEE.create(level, EntitySpawnReason.BREEDING);
607
	}
608
609
	@Override
610
	protected void checkFallDamage(final double ya, final boolean onGround, final BlockState onState, final BlockPos pos) {
611
	}
612
613
	@Override
614
	public boolean isFlapping() {
615
		return this.isFlying() && this.tickCount % TICKS_PER_FLAP == 0;
616
	}
617
618
	public boolean isFlying() {
619
		return !this.onGround();
620
	}
621
622
	@Override
623
	protected boolean omnidirectionalAirMover() {
624
		return true;
625
	}
626
627
	public void dropOffNectar() {
628
		this.setHasNectar(false);
629
		this.resetNumCropsGrownSincePollination();
630
	}
631
632
	@Override
633
	public boolean hurtServer(final ServerLevel level, final DamageSource source, final float damage) {
634
		if (this.isInvulnerableTo(level, source)) {
635
			return false;
636
		}
637
638
		this.beePollinateGoal.stopPollinating();
639
		return super.hurtServer(level, source, damage);
640
	}
641
642
	@Override
643
	protected void jumpInLiquid(final TagKey<Fluid> type) {
644
		this.setDeltaMovement(this.getDeltaMovement().add(0.0, 0.01, 0.0));
645
	}
646
647
	@Override
648
	public Vec3 getLeashOffset() {
649
		return new Vec3(0.0, 0.5F * this.getEyeHeight(), this.getBbWidth() * 0.2F);
650
	}
651
652
	private boolean closerThan(final BlockPos targetPos, final int distance) {
653
		return targetPos.closerThan(this.blockPosition(), distance);
654
	}
655
656
	public void setHivePos(final BlockPos hivePos) {
657
		this.hivePos = hivePos;
658
	}
659
660
	public static boolean attractsBees(final BlockState state) {
661
		if (state.is(BlockTags.BEE_ATTRACTIVE)) {
662
			if (state.getValueOrElse(BlockStateProperties.WATERLOGGED, false)) {
663
				return false;
664
			} else {
665
				return state.is(Blocks.SUNFLOWER) ? state.getValue(DoublePlantBlock.HALF) == DoubleBlockHalf.UPPER : true;
666
			}
667
		} else {
668
			return false;
669
		}
670
	}
671
672
	@Override
673
	public void registerDebugValues(final ServerLevel level, final DebugValueSource.Registration registration) {
674
		super.registerDebugValues(level, registration);
675
		registration.register(
676
			DebugSubscriptions.BEES,
677
			() -> new DebugBeeInfo(
678
				Optional.ofNullable(this.getHivePos()), Optional.ofNullable(this.getSavedFlowerPos()), this.getTravellingTicks(), this.getBlacklistedHives()
679
			)
680
		);
681
	}
682
683
	private abstract class BaseBeeGoal extends Goal {
684
		public abstract boolean canBeeUse();
685
686
		public abstract boolean canBeeContinueToUse();
687
688
		@Override
689
		public boolean canUse() {
690
			return this.canBeeUse() && !Bee.this.isAngry();
691
		}
692
693
		@Override
694
		public boolean canContinueToUse() {
695
			return this.canBeeContinueToUse() && !Bee.this.isAngry();
696
		}
697
	}
698
699
	private class BeeAttackGoal extends MeleeAttackGoal {
700
		public BeeAttackGoal(final PathfinderMob mob, final double speedModifier, final boolean trackTarget) {
701
			super(mob, speedModifier, trackTarget);
702
		}
703
704
		@Override
705
		public boolean canUse() {
706
			return super.canUse() && Bee.this.isAngry() && !Bee.this.hasStung();
707
		}
708
709
		@Override
710
		public boolean canContinueToUse() {
711
			return super.canContinueToUse() && Bee.this.isAngry() && !Bee.this.hasStung();
712
		}
713
	}
714
715
	private static class BeeBecomeAngryTargetGoal extends NearestAttackableTargetGoal<Player> {
716
		public BeeBecomeAngryTargetGoal(final Bee bee) {
717
			super(bee, Player.class, 10, true, false, bee::isAngryAt);
718
		}
719
720
		@Override
721
		public boolean canUse() {
722
			return this.beeCanTarget() && super.canUse();
723
		}
724
725
		@Override
726
		public boolean canContinueToUse() {
727
			boolean beeCanTarget = this.beeCanTarget();
728
			if (beeCanTarget && this.mob.getTarget() != null) {
729
				return super.canContinueToUse();
730
			}
731
732
			this.targetMob = null;
733
			return false;
734
		}
735
736
		private boolean beeCanTarget() {
737
			Bee bee = (Bee)this.mob;
738
			return bee.isAngry() && !bee.hasStung();
739
		}
740
	}
741
742
	private class BeeEnterHiveGoal extends Bee.BaseBeeGoal {
743
		@Override
744
		public boolean canBeeUse() {
745
			if (Bee.this.hivePos != null && Bee.this.wantsToEnterHive() && Bee.this.hivePos.closerToCenterThan(Bee.this.position(), 2.0)) {
746
				BeehiveBlockEntity beehiveBlockEntity = Bee.this.getBeehiveBlockEntity();
747
				if (beehiveBlockEntity != null) {
748
					if (!beehiveBlockEntity.isFull()) {
749
						return true;
750
					}
751
752
					Bee.this.hivePos = null;
753
				}
754
			}
755
756
			return false;
757
		}
758
759
		@Override
760
		public boolean canBeeContinueToUse() {
761
			return false;
762
		}
763
764
		@Override
765
		public void start() {
766
			BeehiveBlockEntity beehiveBlockEntity = Bee.this.getBeehiveBlockEntity();
767
			if (beehiveBlockEntity != null) {
768
				beehiveBlockEntity.addOccupant(Bee.this);
769
			}
770
		}
771
	}
772
773
	@VisibleForDebug
774
	public class BeeGoToHiveGoal extends Bee.BaseBeeGoal {
775
		public static final int MAX_TRAVELLING_TICKS = 2400;
776
		private int travellingTicks;
777
		private static final int MAX_BLACKLISTED_TARGETS = 3;
778
		private final List<BlockPos> blacklistedTargets = Lists.newArrayList();
779
		private @Nullable Path lastPath;
780
		private static final int TICKS_BEFORE_HIVE_DROP = 60;
781
		private int ticksStuck;
782
783
		public BeeGoToHiveGoal() {
784
			this.setFlags(EnumSet.of(Goal.Flag.MOVE));
785
		}
786
787
		@Override
788
		public boolean canBeeUse() {
789
			return Bee.this.hivePos != null
790
				&& !Bee.this.isTooFarAway(Bee.this.hivePos)
791
				&& !Bee.this.hasHome()
792
				&& Bee.this.wantsToEnterHive()
793
				&& !this.hasReachedTarget(Bee.this.hivePos)
794
				&& Bee.this.level().getBlockState(Bee.this.hivePos).is(BlockTags.BEEHIVES);
795
		}
796
797
		@Override
798
		public boolean canBeeContinueToUse() {
799
			return this.canBeeUse();
800
		}
801
802
		@Override
803
		public void start() {
804
			this.travellingTicks = 0;
805
			this.ticksStuck = 0;
806
			super.start();
807
		}
808
809
		@Override
810
		public void stop() {
811
			this.travellingTicks = 0;
812
			this.ticksStuck = 0;
813
			Bee.this.navigation.stop();
814
			Bee.this.navigation.resetMaxVisitedNodesMultiplier();
815
		}
816
817
		@Override
818
		public void tick() {
819
			if (Bee.this.hivePos != null) {
820
				this.travellingTicks++;
821
				if (this.travellingTicks > this.adjustedTickDelay(2400)) {
822
					this.dropAndBlacklistHive();
823
				} else if (!Bee.this.navigation.isInProgress()) {
824
					if (!Bee.this.closerThan(Bee.this.hivePos, 16)) {
825
						if (Bee.this.isTooFarAway(Bee.this.hivePos)) {
826
							Bee.this.dropHive();
827
						} else {
828
							Bee.this.pathfindRandomlyTowards(Bee.this.hivePos);
829
						}
830
					} else {
831
						boolean canReachAllTheWayToTarget = this.pathfindDirectlyTowards(Bee.this.hivePos);
832
						if (!canReachAllTheWayToTarget) {
833
							this.dropAndBlacklistHive();
834
						} else if (this.lastPath != null && Bee.this.navigation.getPath().sameAs(this.lastPath)) {
835
							this.ticksStuck++;
836
							if (this.ticksStuck > 60) {
837
								Bee.this.dropHive();
838
								this.ticksStuck = 0;
839
							}
840
						} else {
841
							this.lastPath = Bee.this.navigation.getPath();
842
						}
843
					}
844
				}
845
			}
846
		}
847
848
		private boolean pathfindDirectlyTowards(final BlockPos targetPos) {
849
			int closeEnough = Bee.this.closerThan(targetPos, 3) ? 1 : 2;
850
			Bee.this.navigation.setMaxVisitedNodesMultiplier(10.0F);
851
			Bee.this.navigation.moveTo(targetPos.getX(), targetPos.getY(), targetPos.getZ(), closeEnough, 1.0);
852
			return Bee.this.navigation.getPath() != null && Bee.this.navigation.getPath().canReach();
853
		}
854
855
		private boolean isTargetBlacklisted(final BlockPos targetPos) {
856
			return this.blacklistedTargets.contains(targetPos);
857
		}
858
859
		private void blacklistTarget(final BlockPos targetPos) {
860
			this.blacklistedTargets.add(targetPos);
861
862
			while (this.blacklistedTargets.size() > 3) {
863
				this.blacklistedTargets.remove(0);
864
			}
865
		}
866
867
		private void clearBlacklist() {
868
			this.blacklistedTargets.clear();
869
		}
870
871
		private void dropAndBlacklistHive() {
872
			if (Bee.this.hivePos != null) {
873
				this.blacklistTarget(Bee.this.hivePos);
874
			}
875
876
			Bee.this.dropHive();
877
		}
878
879
		private boolean hasReachedTarget(final BlockPos targetPos) {
880
			if (Bee.this.closerThan(targetPos, 2)) {
881
				return true;
882
			}
883
884
			Path path = Bee.this.navigation.getPath();
885
			return path != null && path.getTarget().equals(targetPos) && path.canReach() && path.isDone();
886
		}
887
	}
888
889
	public class BeeGoToKnownFlowerGoal extends Bee.BaseBeeGoal {
890
		private static final int MAX_TRAVELLING_TICKS = 2400;
891
		private int travellingTicks;
892
893
		public BeeGoToKnownFlowerGoal() {
894
			this.setFlags(EnumSet.of(Goal.Flag.MOVE));
895
		}
896
897
		@Override
898
		public boolean canBeeUse() {
899
			return Bee.this.savedFlowerPos != null && !Bee.this.hasHome() && this.wantsToGoToKnownFlower() && !Bee.this.closerThan(Bee.this.savedFlowerPos, 2);
900
		}
901
902
		@Override
903
		public boolean canBeeContinueToUse() {
904
			return this.canBeeUse();
905
		}
906
907
		@Override
908
		public void start() {
909
			this.travellingTicks = 0;
910
			super.start();
911
		}
912
913
		@Override
914
		public void stop() {
915
			this.travellingTicks = 0;
916
			Bee.this.navigation.stop();
917
			Bee.this.navigation.resetMaxVisitedNodesMultiplier();
918
		}
919
920
		@Override
921
		public void tick() {
922
			if (Bee.this.savedFlowerPos != null) {
923
				this.travellingTicks++;
924
				if (this.travellingTicks > this.adjustedTickDelay(2400)) {
925
					Bee.this.dropFlower();
926
				} else if (!Bee.this.navigation.isInProgress()) {
927
					if (Bee.this.isTooFarAway(Bee.this.savedFlowerPos)) {
928
						Bee.this.dropFlower();
929
					} else {
930
						Bee.this.pathfindRandomlyTowards(Bee.this.savedFlowerPos);
931
					}
932
				}
933
			}
934
		}
935
936
		private boolean wantsToGoToKnownFlower() {
937
			return Bee.this.ticksWithoutNectarSinceExitingHive > 600;
938
		}
939
	}
940
941
	private class BeeGrowCropGoal extends Bee.BaseBeeGoal {
942
		private static final int GROW_CHANCE = 30;
943
944
		@Override
945
		public boolean canBeeUse() {
946
			if (Bee.this.getCropsGrownSincePollination() >= 10) {
947
				return false;
948
			} else {
949
				return Bee.this.random.nextFloat() < 0.3F ? false : Bee.this.hasNectar() && Bee.this.isHiveValid();
950
			}
951
		}
952
953
		@Override
954
		public boolean canBeeContinueToUse() {
955
			return this.canBeeUse();
956
		}
957
958
		@Override
959
		public void tick() {
960
			if (Bee.this.random.nextInt(this.adjustedTickDelay(30)) == 0) {
961
				for (int i = 1; i <= 2; i++) {
962
					BlockPos belowPos = Bee.this.blockPosition().below(i);
963
					BlockState belowState = Bee.this.level().getBlockState(belowPos);
964
					Block belowBlock = belowState.getBlock();
965
					BlockState growState = null;
966
					if (belowState.is(BlockTags.BEE_GROWABLES)) {
967
						if (belowBlock instanceof CropBlock cropBlockBelow) {
968
							if (!cropBlockBelow.isMaxAge(belowState)) {
969
								growState = cropBlockBelow.getStateForAge(cropBlockBelow.getAge(belowState) + 1);
970
							}
971
						} else if (belowBlock instanceof StemBlock) {
972
							int age = belowState.getValue(StemBlock.AGE);
973
							if (age < 7) {
974
								growState = belowState.setValue(StemBlock.AGE, age + 1);
975
							}
976
						} else if (belowState.is(Blocks.SWEET_BERRY_BUSH)) {
977
							int age = belowState.getValue(SweetBerryBushBlock.AGE);
978
							if (age < 3) {
979
								growState = belowState.setValue(SweetBerryBushBlock.AGE, age + 1);
980
							}
981
						} else if (belowState.is(Blocks.CAVE_VINES) || belowState.is(Blocks.CAVE_VINES_PLANT)) {
982
							BonemealableBlock bonemealableBlock = (BonemealableBlock)belowState.getBlock();
983
							if (bonemealableBlock.isValidBonemealTarget(Bee.this.level(), belowPos, belowState, BonemealSource.MOB)) {
984
								bonemealableBlock.performBonemeal((ServerLevel)Bee.this.level(), Bee.this.random, belowPos, belowState, BonemealSource.MOB);
985
								growState = Bee.this.level().getBlockState(belowPos);
986
							}
987
						}
988
989
						if (growState != null) {
990
							Bee.this.level().levelEvent(2011, belowPos, 15);
991
							Bee.this.level().setBlockAndUpdate(belowPos, growState);
992
							Bee.this.incrementNumCropsGrownSincePollination();
993
						}
994
					}
995
				}
996
			}
997
		}
998
	}
999
1000
	private class BeeHurtByOtherGoal extends HurtByTargetGoal {
1001
		public BeeHurtByOtherGoal(final Bee bee) {
1002
			super(bee);
1003
		}
1004
1005
		@Override
1006
		public boolean canContinueToUse() {
1007
			return Bee.this.isAngry() && super.canContinueToUse();
1008
		}
1009
1010
		@Override
1011
		protected void alertOther(final Mob other, final LivingEntity hurtByMob) {
1012
			if (other instanceof Bee && this.mob.hasLineOfSight(hurtByMob)) {
1013
				other.setTarget(hurtByMob);
1014
			}
1015
		}
1016
	}
1017
1018
	private class BeeLocateHiveGoal extends Bee.BaseBeeGoal {
1019
		@Override
1020
		public boolean canBeeUse() {
1021
			return Bee.this.remainingCooldownBeforeLocatingNewHive == 0 && !Bee.this.hasHive() && Bee.this.wantsToEnterHive();
1022
		}
1023
1024
		@Override
1025
		public boolean canBeeContinueToUse() {
1026
			return false;
1027
		}
1028
1029
		@Override
1030
		public void start() {
1031
			Bee.this.remainingCooldownBeforeLocatingNewHive = 200;
1032
			List<BlockPos> hivesWithSpace = this.findNearbyHivesWithSpace();
1033
			if (!hivesWithSpace.isEmpty()) {
1034
				for (BlockPos posToCheck : hivesWithSpace) {
1035
					if (!Bee.this.goToHiveGoal.isTargetBlacklisted(posToCheck)) {
1036
						Bee.this.hivePos = posToCheck;
1037
						return;
1038
					}
1039
				}
1040
1041
				Bee.this.goToHiveGoal.clearBlacklist();
1042
				Bee.this.hivePos = hivesWithSpace.get(0);
1043
			}
1044
		}
1045
1046
		private List<BlockPos> findNearbyHivesWithSpace() {
1047
			BlockPos beePos = Bee.this.blockPosition();
1048
			PoiManager poiManager = ((ServerLevel)Bee.this.level()).getPoiManager();
1049
			Stream<PoiRecord> nearbyHives = poiManager.getInRange(p -> p.is(PoiTypeTags.BEE_HOME), beePos, 20, PoiManager.Occupancy.ANY);
1050
			return nearbyHives.map(PoiRecord::getPos)
1051
				.filter(Bee.this::doesHiveHaveSpace)
1052
				.sorted(Comparator.comparingDouble(pos -> pos.distSqr(beePos)))
1053
				.collect(Collectors.toList());
1054
		}
1055
	}
1056
1057
	private class BeeLookControl extends LookControl {
1058
		public BeeLookControl(final Mob mob) {
1059
			super(mob);
1060
		}
1061
1062
		@Override
1063
		public void tick() {
1064
			if (!Bee.this.isAngry()) {
1065
				super.tick();
1066
			}
1067
		}
1068
1069
		@Override
1070
		protected boolean resetXRotOnTick() {
1071
			return !Bee.this.beePollinateGoal.isPollinating();
1072
		}
1073
	}
1074
1075
	private class BeePollinateGoal extends Bee.BaseBeeGoal {
1076
		private static final int MIN_POLLINATION_TICKS = 400;
1077
		private static final double ARRIVAL_THRESHOLD = 0.1;
1078
		private static final int POSITION_CHANGE_CHANCE = 25;
1079
		private static final float SPEED_MODIFIER = 0.35F;
1080
		private static final float HOVER_HEIGHT_WITHIN_FLOWER = 0.6F;
1081
		private static final float HOVER_POS_OFFSET = 0.33333334F;
1082
		private static final int FLOWER_SEARCH_RADIUS = 5;
1083
		private int successfulPollinatingTicks;
1084
		private int lastSoundPlayedTick;
1085
		private boolean pollinating;
1086
		private @Nullable Vec3 hoverPos;
1087
		private int pollinatingTicks;
1088
		private static final int MAX_POLLINATING_TICKS = 600;
1089
		private Long2LongOpenHashMap unreachableFlowerCache = new Long2LongOpenHashMap();
1090
1091
		public BeePollinateGoal() {
1092
			this.setFlags(EnumSet.of(Goal.Flag.MOVE));
1093
		}
1094
1095
		@Override
1096
		public boolean canBeeUse() {
1097
			if (Bee.this.remainingCooldownBeforeLocatingNewFlower > 0) {
1098
				return false;
1099
			} else if (Bee.this.hasNectar()) {
1100
				return false;
1101
			} else if (Bee.this.level().isRaining()) {
1102
				return false;
1103
			} else {
1104
				Optional<BlockPos> nearbyPos = this.findNearbyFlower();
1105
				if (nearbyPos.isPresent()) {
1106
					Bee.this.savedFlowerPos = nearbyPos.get();
1107
					Bee.this.navigation.moveTo(Bee.this.savedFlowerPos.getX() + 0.5, Bee.this.savedFlowerPos.getY() + 0.5, Bee.this.savedFlowerPos.getZ() + 0.5, 1.2F);
1108
					return true;
1109
				} else {
1110
					Bee.this.remainingCooldownBeforeLocatingNewFlower = Mth.nextInt(Bee.this.random, 20, 60);
1111
					return false;
1112
				}
1113
			}
1114
		}
1115
1116
		@Override
1117
		public boolean canBeeContinueToUse() {
1118
			if (!this.pollinating) {
1119
				return false;
1120
			} else if (!Bee.this.hasSavedFlowerPos()) {
1121
				return false;
1122
			} else if (Bee.this.level().isRaining()) {
1123
				return false;
1124
			} else {
1125
				return this.hasPollinatedLongEnough() ? Bee.this.random.nextFloat() < 0.2F : true;
1126
			}
1127
		}
1128
1129
		private boolean hasPollinatedLongEnough() {
1130
			return this.successfulPollinatingTicks > 400;
1131
		}
1132
1133
		private boolean isPollinating() {
1134
			return this.pollinating;
1135
		}
1136
1137
		private void stopPollinating() {
1138
			this.pollinating = false;
1139
		}
1140
1141
		@Override
1142
		public void start() {
1143
			this.successfulPollinatingTicks = 0;
1144
			this.pollinatingTicks = 0;
1145
			this.lastSoundPlayedTick = 0;
1146
			this.pollinating = true;
1147
			Bee.this.resetTicksWithoutNectarSinceExitingHive();
1148
		}
1149
1150
		@Override
1151
		public void stop() {
1152
			if (this.hasPollinatedLongEnough()) {
1153
				Bee.this.setHasNectar(true);
1154
			}
1155
1156
			this.pollinating = false;
1157
			Bee.this.navigation.stop();
1158
			Bee.this.remainingCooldownBeforeLocatingNewFlower = 200;
1159
		}
1160
1161
		@Override
1162
		public boolean requiresUpdateEveryTick() {
1163
			return true;
1164
		}
1165
1166
		@Override
1167
		public void tick() {
1168
			if (Bee.this.hasSavedFlowerPos()) {
1169
				this.pollinatingTicks++;
1170
				if (this.pollinatingTicks > 600) {
1171
					Bee.this.dropFlower();
1172
					this.pollinating = false;
1173
					Bee.this.remainingCooldownBeforeLocatingNewFlower = 200;
1174
				} else {
1175
					Vec3 flowerPos = Vec3.atBottomCenterOf(Bee.this.savedFlowerPos).add(0.0, 0.6F, 0.0);
1176
					if (flowerPos.distanceTo(Bee.this.position()) > 1.0) {
1177
						this.hoverPos = flowerPos;
1178
						this.setWantedPos();
1179
					} else {
1180
						if (this.hoverPos == null) {
1181
							this.hoverPos = flowerPos;
1182
						}
1183
1184
						boolean arrivedAtHoverPos = Bee.this.position().distanceTo(this.hoverPos) <= 0.1;
1185
						boolean shouldSetWantedPos = true;
1186
						if (!arrivedAtHoverPos && this.pollinatingTicks > 600) {
1187
							Bee.this.dropFlower();
1188
						} else {
1189
							if (arrivedAtHoverPos) {
1190
								boolean shouldChangeHoverPositions = Bee.this.random.nextInt(25) == 0;
1191
								if (shouldChangeHoverPositions) {
1192
									this.hoverPos = new Vec3(flowerPos.x() + this.getOffset(), flowerPos.y(), flowerPos.z() + this.getOffset());
1193
									Bee.this.navigation.stop();
1194
								} else {
1195
									shouldSetWantedPos = false;
1196
								}
1197
1198
								Bee.this.getLookControl().setLookAt(flowerPos.x(), flowerPos.y(), flowerPos.z());
1199
							}
1200
1201
							if (shouldSetWantedPos) {
1202
								this.setWantedPos();
1203
							}
1204
1205
							this.successfulPollinatingTicks++;
1206
							if (Bee.this.random.nextFloat() < 0.05F && this.successfulPollinatingTicks > this.lastSoundPlayedTick + 60) {
1207
								this.lastSoundPlayedTick = this.successfulPollinatingTicks;
1208
								Bee.this.playSound(SoundEvents.BEE_POLLINATE, 1.0F, 1.0F);
1209
							}
1210
						}
1211
					}
1212
				}
1213
			}
1214
		}
1215
1216
		private void setWantedPos() {
1217
			Bee.this.getMoveControl().setWantedPosition(this.hoverPos.x(), this.hoverPos.y(), this.hoverPos.z(), 0.35F);
1218
		}
1219
1220
		private float getOffset() {
1221
			return (Bee.this.random.nextFloat() * 2.0F - 1.0F) * 0.33333334F;
1222
		}
1223
1224
		private Optional<BlockPos> findNearbyFlower() {
1225
			Long2LongOpenHashMap tempCache = new Long2LongOpenHashMap();
1226
			Optional<BlockPos> result = Bee.this.level()
1227
				.findBlocksInBoxByManhattanDistance(Bee.this.blockPosition(), 5)
1228
				.filterState(Bee::attractsBees)
1229
				.findFirst((pos, var3) -> {
1230
					long unreachableUntilTime = this.unreachableFlowerCache.getOrDefault(pos.asLong(), Long.MIN_VALUE);
1231
					if (Bee.this.level().getGameTime() < unreachableUntilTime) {
1232
						tempCache.put(pos.asLong(), unreachableUntilTime);
1233
						return false;
1234
					}
1235
1236
					Path path = Bee.this.navigation.createPath(pos, 1);
1237
					if (path != null && path.canReach()) {
1238
						return true;
1239
					}
1240
1241
					tempCache.put(pos.asLong(), Bee.this.level().getGameTime() + 600L);
1242
					return false;
1243
				});
1244
			this.unreachableFlowerCache = tempCache;
1245
			return result;
1246
		}
1247
	}
1248
1249
	private class BeeWanderGoal extends Goal {
1250
		public BeeWanderGoal() {
1251
			this.setFlags(EnumSet.of(Goal.Flag.MOVE));
1252
		}
1253
1254
		@Override
1255
		public boolean canUse() {
1256
			return Bee.this.navigation.isDone() && Bee.this.random.nextInt(10) == 0;
1257
		}
1258
1259
		@Override
1260
		public boolean canContinueToUse() {
1261
			return Bee.this.navigation.isInProgress();
1262
		}
1263
1264
		@Override
1265
		public void start() {
1266
			Vec3 targetPos = this.findPos();
1267
			if (targetPos != null) {
1268
				Bee.this.navigation.moveTo(Bee.this.navigation.createPath(BlockPos.containing(targetPos), 1), 1.0);
1269
			}
1270
		}
1271
1272
		private @Nullable Vec3 findPos() {
1273
			Vec3 wanderDirection;
1274
			if (Bee.this.isHiveValid() && !Bee.this.closerThan(Bee.this.hivePos, this.getWanderThreshold())) {
1275
				Vec3 hivePosVec = Vec3.atCenterOf(Bee.this.hivePos);
1276
				wanderDirection = hivePosVec.subtract(Bee.this.position()).normalize();
1277
			} else {
1278
				wanderDirection = Bee.this.getViewVector(0.0F);
1279
			}
1280
1281
			int xzDist = 8;
1282
			Vec3 groundBasedPosition = HoverRandomPos.getPos(Bee.this, 8, 7, wanderDirection.x, wanderDirection.z, (float) (Math.PI / 2), 3, 1);
1283
			return groundBasedPosition != null
1284
				? groundBasedPosition
1285
				: AirAndWaterRandomPos.getPos(Bee.this, 8, 4, -2, wanderDirection.x, wanderDirection.z, (float) (Math.PI / 2));
1286
		}
1287
1288
		private int getWanderThreshold() {
1289
			int distanceReduction = !Bee.this.hasHive() && !Bee.this.hasSavedFlowerPos() ? 16 : 24;
1290
			return 48 - distanceReduction;
1291
		}
1292
	}
1293
1294
	private class ValidateFlowerGoal extends Bee.BaseBeeGoal {
1295
		private final int validateFlowerCooldown = Mth.nextInt(Bee.this.random, 20, 40);
1296
		private long lastValidateTick = -1L;
1297
1298
		@Override
1299
		public void start() {
1300
			if (Bee.this.savedFlowerPos != null && Bee.this.level().isLoaded(Bee.this.savedFlowerPos) && !this.isFlower(Bee.this.savedFlowerPos)) {
1301
				Bee.this.dropFlower();
1302
			}
1303
1304
			this.lastValidateTick = Bee.this.level().getGameTime();
1305
		}
1306
1307
		@Override
1308
		public boolean canBeeUse() {
1309
			return Bee.this.level().getGameTime() > this.lastValidateTick + this.validateFlowerCooldown;
1310
		}
1311
1312
		@Override
1313
		public boolean canBeeContinueToUse() {
1314
			return false;
1315
		}
1316
1317
		private boolean isFlower(final BlockPos flowerPos) {
1318
			return Bee.attractsBees(Bee.this.level().getBlockState(flowerPos));
1319
		}
1320
	}
1321
1322
	private class ValidateHiveGoal extends Bee.BaseBeeGoal {
1323
		private final int VALIDATE_HIVE_COOLDOWN = Mth.nextInt(Bee.this.random, 20, 40);
1324
		private long lastValidateTick = -1L;
1325
1326
		@Override
1327
		public void start() {
1328
			if (Bee.this.hivePos != null && Bee.this.level().isLoaded(Bee.this.hivePos) && !Bee.this.isHiveValid()) {
1329
				Bee.this.dropHive();
1330
			}
1331
1332
			this.lastValidateTick = Bee.this.level().getGameTime();
1333
		}
1334
1335
		@Override
1336
		public boolean canBeeUse() {
1337
			return Bee.this.level().getGameTime() > this.lastValidateTick + this.VALIDATE_HIVE_COOLDOWN;
1338
		}
1339
1340
		@Override
1341
		public boolean canBeeContinueToUse() {
1342
			return false;
1343
		}
1344
	}
1345
}
1346

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