Sniffer .java

net.minecraft.world.entity.animal.sniffer.Sniffer (class, 484 lines): members: DIGGING_PARTICLES_DURATION_TICKS, DIGGING_DROP_SEED_OFFSET_TICKS, isTempted.

net.minecraft.world.entity.animal.snifferclass484 linescommonextends Animal15.9 KB

API Surface (33)

AttributeSupplier.Builder createAttributes()
void defineSynchedData(final SynchedEntityData.Builder entityData)
void onPathfindingStart()
void onPathfindingDone()
int getBabyStartAge()
EntityDimensions getDefaultDimensions(final Pose pose)
boolean isSearching()
boolean isTempted()
boolean canSniff()
boolean canPlayDiggingSound()
boolean supportQuadLeash()
Vec3[] getQuadLeashOffsets()
void onSyncedDataUpdated(final EntityDataAccessor<?> accessor)
Sniffer transitionTo(final Sniffer.State state)
Sniffer onDiggingComplete(final boolean success)
void jumpFromGround()
void spawnChildFromBreeding(final ServerLevel level, final Animal partner)
void die(final DamageSource source)
void tick()
InteractionResult mobInteract(final Player player, final InteractionHand hand)
void playEatingSound()
void playStepSound(final BlockPos pos, final BlockState blockState)
SoundEvent getAmbientSound()
SoundEvent getHurtSound(final DamageSource source)
SoundEvent getDeathSound()
int getMaxHeadYRot()
AgeableMob getBreedOffspring(final ServerLevel level, final AgeableMob partner)
boolean canMate(final Animal partner)
boolean isFood(final ItemStack itemStack)
Brain<Sniffer> makeBrain(final Brain.Packed packedBrain)
Brain<Sniffer> getBrain()
void customServerAiStep(final ServerLevel level)
int id()

Fields & Constants (15)

BRAIN_PROVIDER
DIGGING_PARTICLES_DELAY_TICKS
DIGGING_PARTICLES_DURATION_TICKS
DIGGING_PARTICLES_AMOUNT
DIGGING_DROP_SEED_OFFSET_TICKS
SNIFFER_BABY_START_AGE
DIGGING_BB_HEIGHT_OFFSET
DIGGING_DIMENSIONS
DATA_STATE
DATA_DROP_SEED_AT_TICK
feelingHappyAnimationState
scentingAnimationState
sniffingAnimationState
diggingAnimationState
risingAnimationState

String literals (2)

"snifferBrain"
"snifferActivityUpdate"

Same Package (2)

Full Source

Sniffer.java484 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.entity.animal.sniffer;
2
3
import io.netty.buffer.ByteBuf;
4
import java.util.Collection;
5
import java.util.List;
6
import java.util.Objects;
7
import java.util.Optional;
8
import java.util.Set;
9
import java.util.function.IntFunction;
10
import java.util.stream.Collectors;
11
import java.util.stream.IntStream;
12
import java.util.stream.Stream;
13
import net.minecraft.core.BlockPos;
14
import net.minecraft.core.GlobalPos;
15
import net.minecraft.core.particles.BlockParticleOption;
16
import net.minecraft.core.particles.ParticleTypes;
17
import net.minecraft.network.codec.ByteBufCodecs;
18
import net.minecraft.network.codec.StreamCodec;
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.server.level.ServerLevel;
23
import net.minecraft.sounds.SoundEvent;
24
import net.minecraft.sounds.SoundEvents;
25
import net.minecraft.sounds.SoundSource;
26
import net.minecraft.tags.BlockTags;
27
import net.minecraft.tags.ItemTags;
28
import net.minecraft.util.ByIdMap;
29
import net.minecraft.util.Mth;
30
import net.minecraft.util.profiling.Profiler;
31
import net.minecraft.util.profiling.ProfilerFiller;
32
import net.minecraft.world.InteractionHand;
33
import net.minecraft.world.InteractionResult;
34
import net.minecraft.world.damagesource.DamageSource;
35
import net.minecraft.world.entity.AgeableMob;
36
import net.minecraft.world.entity.AnimationState;
37
import net.minecraft.world.entity.EntityDimensions;
38
import net.minecraft.world.entity.EntitySpawnReason;
39
import net.minecraft.world.entity.EntityType;
40
import net.minecraft.world.entity.EntityTypes;
41
import net.minecraft.world.entity.Leashable;
42
import net.minecraft.world.entity.Pose;
43
import net.minecraft.world.entity.ai.Brain;
44
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
45
import net.minecraft.world.entity.ai.attributes.Attributes;
46
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
47
import net.minecraft.world.entity.ai.sensing.SensorType;
48
import net.minecraft.world.entity.ai.util.LandRandomPos;
49
import net.minecraft.world.entity.animal.Animal;
50
import net.minecraft.world.entity.item.ItemEntity;
51
import net.minecraft.world.entity.player.Player;
52
import net.minecraft.world.item.ItemStack;
53
import net.minecraft.world.item.Items;
54
import net.minecraft.world.level.Level;
55
import net.minecraft.world.level.block.RenderShape;
56
import net.minecraft.world.level.block.state.BlockState;
57
import net.minecraft.world.level.gameevent.GameEvent;
58
import net.minecraft.world.level.pathfinder.Path;
59
import net.minecraft.world.level.pathfinder.PathType;
60
import net.minecraft.world.level.storage.loot.BuiltInLootTables;
61
import net.minecraft.world.phys.Vec3;
62
63
public class Sniffer extends Animal {
64
	private static final Brain.Provider<Sniffer> BRAIN_PROVIDER = Brain.provider(
65
		List.of(MemoryModuleType.SNIFFER_EXPLORED_POSITIONS),
66
		List.of(SensorType.NEAREST_LIVING_ENTITIES, SensorType.HURT_BY, SensorType.NEAREST_PLAYERS, SensorType.FOOD_TEMPTATIONS),
67
		var0 -> SnifferAi.getActivities()
68
	);
69
	private static final int DIGGING_PARTICLES_DELAY_TICKS = 1700;
70
	private static final int DIGGING_PARTICLES_DURATION_TICKS = 6000;
71
	private static final int DIGGING_PARTICLES_AMOUNT = 30;
72
	private static final int DIGGING_DROP_SEED_OFFSET_TICKS = 120;
73
	private static final int SNIFFER_BABY_START_AGE = -48000;
74
	private static final float DIGGING_BB_HEIGHT_OFFSET = 0.4F;
75
	private static final EntityDimensions DIGGING_DIMENSIONS = EntityDimensions.scalable(EntityTypes.SNIFFER.getWidth(), EntityTypes.SNIFFER.getHeight() - 0.4F)
76
		.withEyeHeight(0.81F);
77
	private static final EntityDataAccessor<Sniffer.State> DATA_STATE = SynchedEntityData.defineId(Sniffer.class, EntityDataSerializers.SNIFFER_STATE);
78
	private static final EntityDataAccessor<Integer> DATA_DROP_SEED_AT_TICK = SynchedEntityData.defineId(Sniffer.class, EntityDataSerializers.INT);
79
	public final AnimationState feelingHappyAnimationState = new AnimationState();
80
	public final AnimationState scentingAnimationState = new AnimationState();
81
	public final AnimationState sniffingAnimationState = new AnimationState();
82
	public final AnimationState diggingAnimationState = new AnimationState();
83
	public final AnimationState risingAnimationState = new AnimationState();
84
85
	public static AttributeSupplier.Builder createAttributes() {
86
		return Animal.createAnimalAttributes().add(Attributes.MOVEMENT_SPEED, 0.1F).add(Attributes.MAX_HEALTH, 14.0);
87
	}
88
89
	public Sniffer(final EntityType<? extends Animal> type, final Level level) {
90
		super(type, level);
91
		this.getNavigation().setCanFloat(true);
92
		this.setPathfindingMalus(PathType.WATER, -1.0F);
93
		this.setPathfindingMalus(PathType.ON_TOP_OF_POWDER_SNOW, -1.0F);
94
		this.setPathfindingMalus(PathType.DAMAGE_CAUTIOUS, -1.0F);
95
	}
96
97
	@Override
98
	protected void defineSynchedData(final SynchedEntityData.Builder entityData) {
99
		super.defineSynchedData(entityData);
100
		entityData.define(DATA_STATE, Sniffer.State.IDLING);
101
		entityData.define(DATA_DROP_SEED_AT_TICK, 0);
102
	}
103
104
	@Override
105
	public void onPathfindingStart() {
106
		super.onPathfindingStart();
107
		if (this.isOnFire() || this.isInWater()) {
108
			this.setPathfindingMalus(PathType.WATER, 0.0F);
109
		}
110
	}
111
112
	@Override
113
	public void onPathfindingDone() {
114
		this.setPathfindingMalus(PathType.WATER, -1.0F);
115
	}
116
117
	@Override
118
	public int getBabyStartAge() {
119
		return -48000;
120
	}
121
122
	@Override
123
	public EntityDimensions getDefaultDimensions(final Pose pose) {
124
		return this.getState() == Sniffer.State.DIGGING ? DIGGING_DIMENSIONS.scale(this.getAgeScale()) : super.getDefaultDimensions(pose);
125
	}
126
127
	public boolean isSearching() {
128
		return this.getState() == Sniffer.State.SEARCHING;
129
	}
130
131
	public boolean isTempted() {
132
		return this.brain.getMemory(MemoryModuleType.TEMPTING_PLAYER).isPresent();
133
	}
134
135
	public boolean canSniff() {
136
		return !this.isTempted() && !this.isPanicking() && !this.isInWater() && !this.isInLove() && this.onGround() && !this.isPassenger() && !this.isLeashed();
137
	}
138
139
	public boolean canPlayDiggingSound() {
140
		return this.getState() == Sniffer.State.DIGGING || this.getState() == Sniffer.State.SEARCHING;
141
	}
142
143
	private BlockPos getHeadBlock() {
144
		Vec3 position = this.getHeadPosition();
145
		return BlockPos.containing(position.x(), this.getY() + 0.2F, position.z());
146
	}
147
148
	private Vec3 getHeadPosition() {
149
		return this.position().add(this.getForward().scale(2.25));
150
	}
151
152
	@Override
153
	public boolean supportQuadLeash() {
154
		return true;
155
	}
156
157
	@Override
158
	public Vec3[] getQuadLeashOffsets() {
159
		return Leashable.createQuadLeashOffsets(this, -0.01, 0.63, 0.38, 1.15);
160
	}
161
162
	private Sniffer.State getState() {
163
		return this.entityData.get(DATA_STATE);
164
	}
165
166
	private Sniffer setState(final Sniffer.State state) {
167
		this.entityData.set(DATA_STATE, state);
168
		return this;
169
	}
170
171
	@Override
172
	public void onSyncedDataUpdated(final EntityDataAccessor<?> accessor) {
173
		if (DATA_STATE.equals(accessor)) {
174
			Sniffer.State state = this.getState();
175
			this.resetAnimations();
176
			switch (state) {
177
				case FEELING_HAPPY:
178
					this.feelingHappyAnimationState.startIfStopped(this.tickCount);
179
					break;
180
				case SCENTING:
181
					this.scentingAnimationState.startIfStopped(this.tickCount);
182
					break;
183
				case SNIFFING:
184
					this.sniffingAnimationState.startIfStopped(this.tickCount);
185
				case SEARCHING:
186
				default:
187
					break;
188
				case DIGGING:
189
					this.diggingAnimationState.startIfStopped(this.tickCount);
190
					break;
191
				case RISING:
192
					this.risingAnimationState.startIfStopped(this.tickCount);
193
			}
194
195
			this.refreshDimensions();
196
		}
197
198
		super.onSyncedDataUpdated(accessor);
199
	}
200
201
	private void resetAnimations() {
202
		this.diggingAnimationState.stop();
203
		this.sniffingAnimationState.stop();
204
		this.risingAnimationState.stop();
205
		this.feelingHappyAnimationState.stop();
206
		this.scentingAnimationState.stop();
207
	}
208
209
	public Sniffer transitionTo(final Sniffer.State state) {
210
		switch (state) {
211
			case IDLING:
212
				this.setState(Sniffer.State.IDLING);
213
				break;
214
			case FEELING_HAPPY:
215
				this.playSound(SoundEvents.SNIFFER_HAPPY, 1.0F, 1.0F);
216
				this.setState(Sniffer.State.FEELING_HAPPY);
217
				break;
218
			case SCENTING:
219
				this.setState(Sniffer.State.SCENTING).onScentingStart();
220
				break;
221
			case SNIFFING:
222
				this.playSound(SoundEvents.SNIFFER_SNIFFING, 1.0F, 1.0F);
223
				this.setState(Sniffer.State.SNIFFING);
224
				break;
225
			case SEARCHING:
226
				this.setState(Sniffer.State.SEARCHING);
227
				break;
228
			case DIGGING:
229
				this.setState(Sniffer.State.DIGGING).onDiggingStart();
230
				break;
231
			case RISING:
232
				this.playSound(SoundEvents.SNIFFER_DIGGING_STOP, 1.0F, 1.0F);
233
				this.setState(Sniffer.State.RISING);
234
		}
235
236
		return this;
237
	}
238
239
	private Sniffer onScentingStart() {
240
		this.playSound(SoundEvents.SNIFFER_SCENTING, 1.0F, this.isBaby() ? 1.3F : 1.0F);
241
		return this;
242
	}
243
244
	private Sniffer onDiggingStart() {
245
		this.entityData.set(DATA_DROP_SEED_AT_TICK, this.tickCount + 120);
246
		this.level().broadcastEntityEvent(this, (byte)63);
247
		return this;
248
	}
249
250
	public Sniffer onDiggingComplete(final boolean success) {
251
		if (success) {
252
			this.storeExploredPosition(this.getOnPos());
253
		}
254
255
		return this;
256
	}
257
258
	Optional<BlockPos> calculateDigPosition() {
259
		return IntStream.range(0, 5)
260
			.mapToObj(idx -> LandRandomPos.getPos(this, 10 + 2 * idx, 3))
261
			.filter(Objects::nonNull)
262
			.map(BlockPos::containing)
263
			.filter(position -> this.level().getWorldBorder().isWithinBounds(position))
264
			.map(BlockPos::below)
265
			.filter(this::canDig)
266
			.findFirst();
267
	}
268
269
	boolean canDig() {
270
		return !this.isPanicking()
271
			&& !this.isTempted()
272
			&& !this.isBaby()
273
			&& !this.isInWater()
274
			&& this.onGround()
275
			&& !this.isPassenger()
276
			&& this.canDig(this.getHeadBlock().below());
277
	}
278
279
	private boolean canDig(final BlockPos position) {
280
		return this.level().getBlockState(position).is(BlockTags.SNIFFER_DIGGABLE_BLOCK)
281
			&& this.getExploredPositions().noneMatch(explored -> GlobalPos.of(this.level().dimension(), position).equals(explored))
282
			&& Optional.ofNullable(this.getNavigation().createPath(position, 1)).map(Path::canReach).orElse(false);
283
	}
284
285
	private void dropSeed() {
286
		if (this.level() instanceof ServerLevel level && this.entityData.get(DATA_DROP_SEED_AT_TICK) == this.tickCount) {
287
			BlockPos head = this.getHeadBlock();
288
			this.dropFromGiftLootTable(level, BuiltInLootTables.SNIFFER_DIGGING, (l, itemStack) -> {
289
				ItemEntity entity = new ItemEntity(this.level(), head.getX(), head.getY(), head.getZ(), itemStack);
290
				entity.setDefaultPickUpDelay();
291
				l.addFreshEntity(entity);
292
			});
293
			this.playSound(SoundEvents.SNIFFER_DROP_SEED, 1.0F, 1.0F);
294
		}
295
	}
296
297
	private Sniffer emitDiggingParticles(final AnimationState state) {
298
		boolean emit = state.getTimeInMillis(this.tickCount) > 1700L && state.getTimeInMillis(this.tickCount) < 6000L;
299
		if (emit) {
300
			BlockPos head = this.getHeadBlock();
301
			BlockState stateBelow = this.level().getBlockState(head.below());
302
			if (stateBelow.getRenderShape() != RenderShape.INVISIBLE) {
303
				for (int i = 0; i < 30; i++) {
304
					Vec3 centered = Vec3.atCenterOf(head).add(0.0, -0.65F, 0.0);
305
					this.level().addParticle(new BlockParticleOption(ParticleTypes.BLOCK, stateBelow), centered.x, centered.y, centered.z, 0.0, 0.0, 0.0);
306
				}
307
308
				if (this.tickCount % 10 == 0) {
309
					this.level().playLocalSound(this, stateBelow.getSoundType().getHitSound(), this.getSoundSource(), 0.5F, 0.5F);
310
				}
311
			}
312
		}
313
314
		if (this.tickCount % 10 == 0) {
315
			this.level().gameEvent(GameEvent.ENTITY_ACTION, this.getHeadBlock(), GameEvent.Context.of(this));
316
		}
317
318
		return this;
319
	}
320
321
	private Sniffer storeExploredPosition(final BlockPos position) {
322
		List<GlobalPos> updated = this.getExploredPositions().limit(20L).collect(Collectors.toList());
323
		updated.add(0, GlobalPos.of(this.level().dimension(), position));
324
		this.getBrain().setMemory(MemoryModuleType.SNIFFER_EXPLORED_POSITIONS, updated);
325
		return this;
326
	}
327
328
	private Stream<GlobalPos> getExploredPositions() {
329
		return this.getBrain().getMemory(MemoryModuleType.SNIFFER_EXPLORED_POSITIONS).stream().flatMap(Collection::stream);
330
	}
331
332
	@Override
333
	public void jumpFromGround() {
334
		super.jumpFromGround();
335
		double speedModifier = this.moveControl.getSpeedModifier();
336
		if (speedModifier > 0.0) {
337
			double current = this.getDeltaMovement().horizontalDistanceSqr();
338
			if (current < 0.01) {
339
				this.moveRelative(0.1F, new Vec3(0.0, 0.0, 1.0));
340
			}
341
		}
342
	}
343
344
	@Override
345
	public void spawnChildFromBreeding(final ServerLevel level, final Animal partner) {
346
		ItemStack itemStack = new ItemStack(Items.SNIFFER_EGG);
347
		ItemEntity entity = new ItemEntity(level, this.position().x(), this.position().y(), this.position().z(), itemStack);
348
		entity.setDefaultPickUpDelay();
349
		this.finalizeSpawnChildFromBreeding(level, partner, null);
350
		this.playSound(SoundEvents.SNIFFER_EGG_PLOP, 1.0F, (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 0.5F);
351
		level.addFreshEntity(entity);
352
	}
353
354
	@Override
355
	public void die(final DamageSource source) {
356
		this.transitionTo(Sniffer.State.IDLING);
357
		super.die(source);
358
	}
359
360
	@Override
361
	public void tick() {
362
		switch (this.getState()) {
363
			case SEARCHING:
364
				this.playSearchingSound();
365
				break;
366
			case DIGGING:
367
				this.emitDiggingParticles(this.diggingAnimationState).dropSeed();
368
		}
369
370
		super.tick();
371
	}
372
373
	@Override
374
	public InteractionResult mobInteract(final Player player, final InteractionHand hand) {
375
		ItemStack heldItem = player.getItemInHand(hand);
376
		boolean isFood = this.isFood(heldItem);
377
		InteractionResult interactionResult = super.mobInteract(player, hand);
378
		if (interactionResult.consumesAction() && isFood) {
379
			this.playEatingSound();
380
		}
381
382
		return interactionResult;
383
	}
384
385
	@Override
386
	protected void playEatingSound() {
387
		this.level().playSound(null, this, SoundEvents.SNIFFER_EAT, SoundSource.NEUTRAL, 1.0F, Mth.randomBetween(this.level().getRandom(), 0.8F, 1.2F));
388
	}
389
390
	private void playSearchingSound() {
391
		if (this.level().isClientSide() && this.tickCount % 20 == 0) {
392
			this.level().playLocalSound(this, SoundEvents.SNIFFER_SEARCHING, this.getSoundSource(), 1.0F, 1.0F);
393
		}
394
	}
395
396
	@Override
397
	protected void playStepSound(final BlockPos pos, final BlockState blockState) {
398
		this.playSound(SoundEvents.SNIFFER_STEP, 0.15F, 1.0F);
399
	}
400
401
	@Override
402
	protected SoundEvent getAmbientSound() {
403
		return Set.of(Sniffer.State.DIGGING, Sniffer.State.SEARCHING).contains(this.getState()) ? null : SoundEvents.SNIFFER_IDLE;
404
	}
405
406
	@Override
407
	protected SoundEvent getHurtSound(final DamageSource source) {
408
		return SoundEvents.SNIFFER_HURT;
409
	}
410
411
	@Override
412
	protected SoundEvent getDeathSound() {
413
		return SoundEvents.SNIFFER_DEATH;
414
	}
415
416
	@Override
417
	public int getMaxHeadYRot() {
418
		return 50;
419
	}
420
421
	@Override
422
	public AgeableMob getBreedOffspring(final ServerLevel level, final AgeableMob partner) {
423
		return EntityTypes.SNIFFER.create(level, EntitySpawnReason.BREEDING);
424
	}
425
426
	@Override
427
	public boolean canMate(final Animal partner) {
428
		if (!(partner instanceof Sniffer snifferPartner)) {
429
			return false;
430
		} else {
431
			Set<Sniffer.State> states = Set.of(Sniffer.State.IDLING, Sniffer.State.SCENTING, Sniffer.State.FEELING_HAPPY);
432
			return states.contains(this.getState()) && states.contains(snifferPartner.getState()) && super.canMate(partner);
433
		}
434
	}
435
436
	@Override
437
	public boolean isFood(final ItemStack itemStack) {
438
		return itemStack.is(ItemTags.SNIFFER_FOOD);
439
	}
440
441
	@Override
442
	protected Brain<Sniffer> makeBrain(final Brain.Packed packedBrain) {
443
		return BRAIN_PROVIDER.makeBrain(this, packedBrain);
444
	}
445
446
	@Override
447
	public Brain<Sniffer> getBrain() {
448
		return super.getBrain();
449
	}
450
451
	@Override
452
	protected void customServerAiStep(final ServerLevel level) {
453
		ProfilerFiller profiler = Profiler.get();
454
		profiler.push("snifferBrain");
455
		this.getBrain().tick(level, this);
456
		profiler.popPush("snifferActivityUpdate");
457
		SnifferAi.updateActivity(this);
458
		profiler.pop();
459
		super.customServerAiStep(level);
460
	}
461
462
	public enum State {
463
		IDLING(0),
464
		FEELING_HAPPY(1),
465
		SCENTING(2),
466
		SNIFFING(3),
467
		SEARCHING(4),
468
		DIGGING(5),
469
		RISING(6);
470
471
		public static final IntFunction<Sniffer.State> BY_ID = ByIdMap.continuous(Sniffer.State::id, values(), ByIdMap.OutOfBoundsStrategy.ZERO);
472
		public static final StreamCodec<ByteBuf, Sniffer.State> STREAM_CODEC = ByteBufCodecs.idMapper(BY_ID, Sniffer.State::id);
473
		private final int id;
474
475
		State(final int id) {
476
			this.id = id;
477
		}
478
479
		public int id() {
480
			return this.id;
481
		}
482
	}
483
}
484

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