Villager .java

net.minecraft.world.entity.npc.villager.Villager (class): members: HOW_FAR_AWAY_TO_TALK_TO_OTHER_VILLAGERS_ABOUT_GOLEMS, DEFAULT_LAST_GOSSIP_DECAY, gossip.

net.minecraft.world.entity.npc.villagerclass932 linescommonextends AbstractVillager32.1 KB

Implements

API Surface (54)

Brain<Villager> getBrain()
Brain<Villager> makeBrain(final Brain.Packed packedBrain)
void refreshBrain(final ServerLevel level)
void ageBoundaryReached()
AttributeSupplier.Builder createAttributes()
void customServerAiStep(final ServerLevel level)
void tick()
InteractionResult mobInteract(final Player player, final InteractionHand hand)
void setTradingPlayer(final @Nullable Player player)
EntityDimensions getDefaultDimensions(final Pose pose)
boolean canRestock()
void restock()
boolean shouldRestock(final ServerLevel level)
void defineSynchedData(final SynchedEntityData.Builder entityData)
VillagerData createDefaultVillagerData()
void addAdditionalSaveData(final ValueOutput output)
void readAdditionalSaveData(final ValueInput input)
void postDataManipulated()
boolean removeWhenFarAway(final double distSqr)
SoundEvent getHurtSound(final DamageSource source)
SoundEvent getDeathSound()
void playWorkSound()
void setVillagerData(final VillagerData data)
boolean getVillagerDataFinalized()
void setVillagerDataFinalized(final boolean villagerDataFinalized)
VillagerData getVillagerData()
void rewardTradeXp(final MerchantOffer offer)
void setLastHurtByMob(final @Nullable LivingEntity hurtBy)
void die(final DamageSource source)
void releasePoi(final MemoryModuleType<GlobalPos> memoryType)
boolean canBreed()
int getPlayerReputation(final Player player)
void eatAndDigestFood()
void setOffers(final MerchantOffers offers)
Component getTypeName()
void handleEntityEvent(final @EntityEvent.Value byte id)
void thunderHit(final ServerLevel level, final LightningBolt lightningBolt)
void pickUpItem(final ServerLevel level, final ItemEntity entity)
boolean wantsToPickUp(final ServerLevel level, final ItemStack itemStack)
boolean hasExcessFood()
boolean wantsMoreFood()
boolean hasFarmSeeds()
void updateTrades(final ServerLevel level)
void gossip(final ServerLevel level, final Villager target, final long timestamp)
void spawnGolemIfNeeded(final ServerLevel level, final long timestamp, final int villagersNeededToAgree)
boolean wantsToSpawnGolem(final long timestamp)
void onReputationEventFrom(final ReputationEventType type, final Entity source)
int getVillagerXp()
void setVillagerXp(final int value)
GossipContainer getGossips()
void setGossips(final GossipContainer gossips)
void stopSleeping()
void applyImplicitComponents(final DataComponentGetter components)
<T> boolean applyImplicitComponent(final DataComponentType<T> type, final T value)

Fields & Constants (29)

LOGGER
DATA_VILLAGER_DATA
DATA_VILLAGER_DATA_FINALIZED
BREEDING_FOOD_THRESHOLD
MAX_GOSSIP_TOPICS
GOSSIP_COOLDOWN
GOSSIP_DECAY_INTERVAL
HOW_FAR_AWAY_TO_TALK_TO_OTHER_VILLAGERS_ABOUT_GOLEMS
HOW_MANY_VILLAGERS_NEED_TO_AGREE_TO_SPAWN_A_GOLEM
TIME_SINCE_SLEEPING_FOR_GOLEM_SPAWNING
SPEED_MODIFIER
DEFAULT_XP
DEFAULT_FOOD_LEVEL
DEFAULT_LAST_RESTOCK
DEFAULT_LAST_GOSSIP_DECAY
DEFAULT_RESTOCKS_TODAY
BABY_DIMENSIONS
BRAIN_PROVIDER
POI_MEMORIES
lastTradedPlayer
foodLevel
gossips
lastGossipTime
lastGossipDecayTime
villagerXp
lastRestockGameTime
numberOfRestocksToday
lastRestockCheckDay
spawnReason

String literals (8)

"villagerBrain"
"VillagerData"
"VillagerDataFinalized"
"FoodLevel"
"Gossips"
"LastRestock"
"LastGossipDecay"
"RestocksToday"

Code Graph: Dependencies (80)

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

Full Source

Villager.java932 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.entity.npc.villager;
2
3
import com.google.common.annotations.VisibleForTesting;
4
import com.google.common.collect.ImmutableMap;
5
import com.google.common.collect.ImmutableSet;
6
import com.mojang.datafixers.util.Pair;
7
import com.mojang.logging.LogUtils;
8
import java.util.ArrayList;
9
import java.util.List;
10
import java.util.Map;
11
import java.util.Optional;
12
import java.util.function.BiPredicate;
13
import net.minecraft.SharedConstants;
14
import net.minecraft.core.GlobalPos;
15
import net.minecraft.core.Holder;
16
import net.minecraft.core.component.DataComponentGetter;
17
import net.minecraft.core.component.DataComponentType;
18
import net.minecraft.core.component.DataComponents;
19
import net.minecraft.core.particles.ParticleTypes;
20
import net.minecraft.core.registries.BuiltInRegistries;
21
import net.minecraft.network.chat.Component;
22
import net.minecraft.network.syncher.EntityDataAccessor;
23
import net.minecraft.network.syncher.EntityDataSerializers;
24
import net.minecraft.network.syncher.SynchedEntityData;
25
import net.minecraft.resources.ResourceKey;
26
import net.minecraft.server.MinecraftServer;
27
import net.minecraft.server.level.ServerLevel;
28
import net.minecraft.sounds.SoundEvent;
29
import net.minecraft.sounds.SoundEvents;
30
import net.minecraft.stats.Stats;
31
import net.minecraft.tags.ItemTags;
32
import net.minecraft.util.Mth;
33
import net.minecraft.util.SpawnUtil;
34
import net.minecraft.util.profiling.Profiler;
35
import net.minecraft.util.profiling.ProfilerFiller;
36
import net.minecraft.world.Difficulty;
37
import net.minecraft.world.DifficultyInstance;
38
import net.minecraft.world.InteractionHand;
39
import net.minecraft.world.InteractionResult;
40
import net.minecraft.world.SimpleContainer;
41
import net.minecraft.world.attribute.EnvironmentAttributes;
42
import net.minecraft.world.damagesource.DamageSource;
43
import net.minecraft.world.effect.MobEffectInstance;
44
import net.minecraft.world.effect.MobEffects;
45
import net.minecraft.world.entity.AgeableMob;
46
import net.minecraft.world.entity.ConversionParams;
47
import net.minecraft.world.entity.Entity;
48
import net.minecraft.world.entity.EntityDimensions;
49
import net.minecraft.world.entity.EntityEvent;
50
import net.minecraft.world.entity.EntitySpawnReason;
51
import net.minecraft.world.entity.EntityType;
52
import net.minecraft.world.entity.EntityTypes;
53
import net.minecraft.world.entity.ExperienceOrb;
54
import net.minecraft.world.entity.LightningBolt;
55
import net.minecraft.world.entity.LivingEntity;
56
import net.minecraft.world.entity.Mob;
57
import net.minecraft.world.entity.Pose;
58
import net.minecraft.world.entity.ReputationEventHandler;
59
import net.minecraft.world.entity.SpawnGroupData;
60
import net.minecraft.world.entity.ai.ActivityData;
61
import net.minecraft.world.entity.ai.Brain;
62
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
63
import net.minecraft.world.entity.ai.attributes.Attributes;
64
import net.minecraft.world.entity.ai.behavior.VillagerGoalPackages;
65
import net.minecraft.world.entity.ai.gossip.GossipContainer;
66
import net.minecraft.world.entity.ai.gossip.GossipType;
67
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
68
import net.minecraft.world.entity.ai.memory.MemoryStatus;
69
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities;
70
import net.minecraft.world.entity.ai.sensing.GolemSensor;
71
import net.minecraft.world.entity.ai.sensing.SensorType;
72
import net.minecraft.world.entity.ai.village.ReputationEventType;
73
import net.minecraft.world.entity.ai.village.poi.PoiManager;
74
import net.minecraft.world.entity.ai.village.poi.PoiType;
75
import net.minecraft.world.entity.ai.village.poi.PoiTypes;
76
import net.minecraft.world.entity.item.ItemEntity;
77
import net.minecraft.world.entity.monster.Witch;
78
import net.minecraft.world.entity.npc.InventoryCarrier;
79
import net.minecraft.world.entity.player.Player;
80
import net.minecraft.world.entity.raid.Raid;
81
import net.minecraft.world.entity.schedule.Activity;
82
import net.minecraft.world.food.VillagerFood;
83
import net.minecraft.world.inventory.MerchantMenu;
84
import net.minecraft.world.item.Item;
85
import net.minecraft.world.item.ItemStack;
86
import net.minecraft.world.item.Items;
87
import net.minecraft.world.item.trading.MerchantOffer;
88
import net.minecraft.world.item.trading.MerchantOffers;
89
import net.minecraft.world.item.trading.TradeSet;
90
import net.minecraft.world.level.Level;
91
import net.minecraft.world.level.ServerLevelAccessor;
92
import net.minecraft.world.level.storage.ValueInput;
93
import net.minecraft.world.level.storage.ValueOutput;
94
import net.minecraft.world.phys.AABB;
95
import net.minecraft.world.timeline.Timelines;
96
import org.jspecify.annotations.Nullable;
97
import org.slf4j.Logger;
98
99
public class Villager extends AbstractVillager implements VillagerDataHolder, ReputationEventHandler {
100
	private static final Logger LOGGER = LogUtils.getLogger();
101
	private static final EntityDataAccessor<VillagerData> DATA_VILLAGER_DATA = SynchedEntityData.defineId(Villager.class, EntityDataSerializers.VILLAGER_DATA);
102
	private static final EntityDataAccessor<Boolean> DATA_VILLAGER_DATA_FINALIZED = SynchedEntityData.defineId(Villager.class, EntityDataSerializers.BOOLEAN);
103
	public static final int BREEDING_FOOD_THRESHOLD = 12;
104
	private static final int MAX_GOSSIP_TOPICS = 10;
105
	private static final int GOSSIP_COOLDOWN = 1200;
106
	private static final int GOSSIP_DECAY_INTERVAL = 24000;
107
	private static final int HOW_FAR_AWAY_TO_TALK_TO_OTHER_VILLAGERS_ABOUT_GOLEMS = 10;
108
	private static final int HOW_MANY_VILLAGERS_NEED_TO_AGREE_TO_SPAWN_A_GOLEM = 5;
109
	private static final long TIME_SINCE_SLEEPING_FOR_GOLEM_SPAWNING = 24000L;
110
	@VisibleForTesting
111
	public static final float SPEED_MODIFIER = 0.5F;
112
	private static final int DEFAULT_XP = 0;
113
	private static final byte DEFAULT_FOOD_LEVEL = 0;
114
	private static final int DEFAULT_LAST_RESTOCK = 0;
115
	private static final int DEFAULT_LAST_GOSSIP_DECAY = 0;
116
	private static final int DEFAULT_RESTOCKS_TODAY = 0;
117
	private static final EntityDimensions BABY_DIMENSIONS = EntityDimensions.scalable(0.49F, 0.98F).withEyeHeight(0.63F);
118
	private @Nullable Player lastTradedPlayer;
119
	private int foodLevel = 0;
120
	private final GossipContainer gossips = new GossipContainer();
121
	private long lastGossipTime;
122
	private long lastGossipDecayTime = 0L;
123
	private int villagerXp = 0;
124
	private long lastRestockGameTime = 0L;
125
	private int numberOfRestocksToday = 0;
126
	private long lastRestockCheckDay;
127
	private static final Brain.Provider<Villager> BRAIN_PROVIDER = Brain.provider(
128
		List.of(
129
			SensorType.NEAREST_LIVING_ENTITIES,
130
			SensorType.NEAREST_PLAYERS,
131
			SensorType.NEAREST_ITEMS,
132
			SensorType.NEAREST_BED,
133
			SensorType.HURT_BY,
134
			SensorType.VILLAGER_HOSTILES,
135
			SensorType.VILLAGER_BABIES,
136
			SensorType.SECONDARY_POIS,
137
			SensorType.GOLEM_DETECTED
138
		),
139
		body -> {
140
			Holder<VillagerProfession> profession = body.getVillagerData().profession();
141
			List<ActivityData<Villager>> activities = new ArrayList<>();
142
			if (body.isBaby()) {
143
				activities.add(ActivityData.create(Activity.PLAY, VillagerGoalPackages.getPlayPackage(0.5F)));
144
			} else {
145
				activities.add(
146
					ActivityData.create(
147
						Activity.WORK, VillagerGoalPackages.getWorkPackage(profession, 0.5F), ImmutableSet.of(Pair.of(MemoryModuleType.JOB_SITE, MemoryStatus.VALUE_PRESENT))
148
					)
149
				);
150
			}
151
152
			activities.add(ActivityData.create(Activity.CORE, VillagerGoalPackages.getCorePackage(profession, 0.5F)));
153
			activities.add(
154
				ActivityData.create(
155
					Activity.MEET, VillagerGoalPackages.getMeetPackage(0.5F), ImmutableSet.of(Pair.of(MemoryModuleType.MEETING_POINT, MemoryStatus.VALUE_PRESENT))
156
				)
157
			);
158
			activities.add(ActivityData.create(Activity.REST, VillagerGoalPackages.getRestPackage(0.5F)));
159
			activities.add(ActivityData.create(Activity.IDLE, VillagerGoalPackages.getIdlePackage(0.5F)));
160
			activities.add(ActivityData.create(Activity.PANIC, VillagerGoalPackages.getPanicPackage(0.5F)));
161
			activities.add(ActivityData.create(Activity.PRE_RAID, VillagerGoalPackages.getPreRaidPackage(0.5F)));
162
			activities.add(ActivityData.create(Activity.RAID, VillagerGoalPackages.getRaidPackage(0.5F)));
163
			activities.add(ActivityData.create(Activity.HIDE, VillagerGoalPackages.getHidePackage(0.5F)));
164
			return activities;
165
		}
166
	);
167
	public static final Map<MemoryModuleType<GlobalPos>, BiPredicate<Villager, Holder<PoiType>>> POI_MEMORIES = ImmutableMap.of(
168
		MemoryModuleType.HOME,
169
		(villager, poiType) -> poiType.is(PoiTypes.HOME),
170
		MemoryModuleType.JOB_SITE,
171
		(villager, poiType) -> villager.getVillagerData().profession().value().heldJobSite().test(poiType),
172
		MemoryModuleType.POTENTIAL_JOB_SITE,
173
		(villager, poiType) -> VillagerProfession.ALL_ACQUIRABLE_JOBS.test(poiType),
174
		MemoryModuleType.MEETING_POINT,
175
		(villager, poiType) -> poiType.is(PoiTypes.MEETING)
176
	);
177
178
	public Villager(final EntityType<? extends Villager> entityType, final Level level) {
179
		super(entityType, level);
180
		this.getNavigation().setCanOpenDoors(true);
181
		this.getNavigation().setCanFloat(true);
182
		this.getNavigation().setRequiredPathLength(48.0F);
183
		this.setCanPickUpLoot(true);
184
	}
185
186
	@Override
187
	public Brain<Villager> getBrain() {
188
		return super.getBrain();
189
	}
190
191
	@Override
192
	protected Brain<Villager> makeBrain(final Brain.Packed packedBrain) {
193
		Brain<Villager> brain = BRAIN_PROVIDER.makeBrain(this, packedBrain);
194
		this.registerBrainGoals(brain);
195
		return brain;
196
	}
197
198
	public void refreshBrain(final ServerLevel level) {
199
		Brain<Villager> oldBrain = this.getBrain();
200
		oldBrain.stopAll(level, this);
201
		this.brain = BRAIN_PROVIDER.makeBrain(this, oldBrain.pack());
202
		this.registerBrainGoals(this.getBrain());
203
	}
204
205
	private void registerBrainGoals(final Brain<Villager> brain) {
206
		if (this.isBaby()) {
207
			brain.setSchedule(EnvironmentAttributes.BABY_VILLAGER_ACTIVITY);
208
		} else {
209
			brain.setSchedule(EnvironmentAttributes.VILLAGER_ACTIVITY);
210
		}
211
212
		brain.updateActivityFromSchedule(this.level().environmentAttributes(), this.level().getGameTime(), this.position());
213
	}
214
215
	@Override
216
	protected void ageBoundaryReached() {
217
		super.ageBoundaryReached();
218
		if (this.level() instanceof ServerLevel) {
219
			this.refreshBrain((ServerLevel)this.level());
220
		}
221
	}
222
223
	public static AttributeSupplier.Builder createAttributes() {
224
		return Mob.createMobAttributes().add(Attributes.MOVEMENT_SPEED, 0.5);
225
	}
226
227
	@Override
228
	protected void customServerAiStep(final ServerLevel level) {
229
		ProfilerFiller profiler = Profiler.get();
230
		profiler.push("villagerBrain");
231
		this.getBrain().tick(level, this);
232
		profiler.pop();
233
		if (this.lastTradedPlayer != null) {
234
			level.onReputationEvent(ReputationEventType.TRADE, this.lastTradedPlayer, this);
235
			level.broadcastEntityEvent(this, (byte)14);
236
			this.lastTradedPlayer = null;
237
		}
238
239
		if (!this.isNoAi() && this.random.nextInt(100) == 0) {
240
			Raid raid = level.getRaidAt(this.blockPosition());
241
			if (raid != null && raid.isActive() && !raid.isOver()) {
242
				level.broadcastEntityEvent(this, (byte)42);
243
			}
244
		}
245
246
		if ((this.offers == null || this.offers.isEmpty()) && this.isTrading()) {
247
			this.stopTrading();
248
		}
249
250
		super.customServerAiStep(level);
251
	}
252
253
	@Override
254
	public void tick() {
255
		super.tick();
256
		if (this.getUnhappyCounter() > 0) {
257
			this.setUnhappyCounter(this.getUnhappyCounter() - 1);
258
		}
259
260
		this.maybeDecayGossip();
261
	}
262
263
	@Override
264
	public InteractionResult mobInteract(final Player player, final InteractionHand hand) {
265
		ItemStack itemStack = player.getItemInHand(hand);
266
		if (itemStack.is(Items.VILLAGER_SPAWN_EGG) || !this.isAlive() || this.isTrading() || this.isSleeping()) {
267
			return super.mobInteract(player, hand);
268
		}
269
270
		if (this.isBaby()) {
271
			this.setUnhappy();
272
			return InteractionResult.SUCCESS;
273
		}
274
275
		if (!this.level().isClientSide()) {
276
			boolean noOffers = this.getOffers().isEmpty();
277
			if (hand == InteractionHand.MAIN_HAND) {
278
				if (noOffers) {
279
					this.setUnhappy();
280
				}
281
282
				player.awardStat(Stats.TALKED_TO_VILLAGER);
283
			}
284
285
			if (noOffers) {
286
				return InteractionResult.CONSUME;
287
			}
288
289
			this.startTrading(player);
290
		}
291
292
		return InteractionResult.SUCCESS;
293
	}
294
295
	private void setUnhappy() {
296
		this.setUnhappyCounter(40);
297
		if (!this.level().isClientSide()) {
298
			this.makeSound(SoundEvents.VILLAGER_NO);
299
		}
300
	}
301
302
	private void startTrading(final Player player) {
303
		this.updateSpecialPrices(player);
304
		this.setTradingPlayer(player);
305
		this.openTradingScreen(player, this.getDisplayName(), this.getVillagerData().level());
306
	}
307
308
	@Override
309
	public void setTradingPlayer(final @Nullable Player player) {
310
		boolean shouldStop = this.getTradingPlayer() != null && player == null;
311
		super.setTradingPlayer(player);
312
		if (shouldStop) {
313
			this.stopTrading();
314
		}
315
	}
316
317
	private void resetSpecialPrices() {
318
		if (!this.level().isClientSide()) {
319
			for (MerchantOffer offer : this.getOffers()) {
320
				offer.resetSpecialPriceDiff();
321
			}
322
		}
323
	}
324
325
	@Override
326
	public EntityDimensions getDefaultDimensions(final Pose pose) {
327
		return this.isBaby() ? BABY_DIMENSIONS : super.getDefaultDimensions(pose);
328
	}
329
330
	@Override
331
	public boolean canRestock() {
332
		return true;
333
	}
334
335
	public void restock() {
336
		this.updateDemand();
337
338
		for (MerchantOffer offer : this.getOffers()) {
339
			offer.resetUses();
340
		}
341
342
		Player tradingPlayer = this.getTradingPlayer();
343
		if (tradingPlayer != null) {
344
			this.updateSpecialPrices(tradingPlayer);
345
		}
346
347
		this.lastRestockGameTime = this.level().getGameTime();
348
		this.numberOfRestocksToday++;
349
	}
350
351
	private boolean needsToRestock() {
352
		for (MerchantOffer offer : this.getOffers()) {
353
			if (offer.needsRestock()) {
354
				return true;
355
			}
356
		}
357
358
		return false;
359
	}
360
361
	private boolean allowedToRestock() {
362
		return this.numberOfRestocksToday == 0 || this.numberOfRestocksToday < 2 && this.level().getGameTime() > this.lastRestockGameTime + 2400L;
363
	}
364
365
	public boolean shouldRestock(final ServerLevel level) {
366
		long halfDayPassedTime = this.lastRestockGameTime + 12000L;
367
		long gameTime = this.level().getGameTime();
368
		boolean isNewDay = gameTime > halfDayPassedTime;
369
		long currentDay = this.level()
370
			.registryAccess()
371
			.get(Timelines.OVERWORLD_DAY)
372
			.map(timeline -> timeline.value().getPeriodCount(level.clockManager()))
373
			.orElse(0)
374
			.intValue();
375
		isNewDay |= this.lastRestockCheckDay > 0L && currentDay > this.lastRestockCheckDay;
376
		this.lastRestockCheckDay = currentDay;
377
		if (isNewDay) {
378
			this.lastRestockGameTime = gameTime;
379
			this.resetNumberOfRestocks();
380
		}
381
382
		return this.allowedToRestock() && this.needsToRestock();
383
	}
384
385
	private void catchUpDemand() {
386
		int missedUpdates = 2 - this.numberOfRestocksToday;
387
		if (missedUpdates > 0) {
388
			for (MerchantOffer offer : this.getOffers()) {
389
				offer.resetUses();
390
			}
391
		}
392
393
		for (int i = 0; i < missedUpdates; i++) {
394
			this.updateDemand();
395
		}
396
397
		Player tradingPlayer = this.getTradingPlayer();
398
		if (tradingPlayer != null) {
399
			this.updateSpecialPrices(tradingPlayer);
400
		}
401
	}
402
403
	private void updateDemand() {
404
		for (MerchantOffer offer : this.getOffers()) {
405
			offer.updateDemand();
406
		}
407
	}
408
409
	private void updateSpecialPrices(final Player player) {
410
		this.resetSpecialPrices();
411
		int reputation = this.getPlayerReputation(player);
412
		MobEffectInstance heroOfTheVillage = player.getEffect(MobEffects.HERO_OF_THE_VILLAGE);
413
		double heroModifier = heroOfTheVillage == null ? 0.0 : 0.3F + 0.0625F * heroOfTheVillage.getAmplifier();
414
		MerchantOffers merchantOffers = this.getOffers();
415
416
		for (MerchantOffer offer : merchantOffers) {
417
			if (reputation != 0) {
418
				offer.addToSpecialPriceDiff(-Mth.floor(reputation * offer.getPriceMultiplier()));
419
			}
420
421
			if (heroModifier > 0.0) {
422
				int costReduction = (int)Math.floor(heroModifier * offer.getBaseCostA().getCount());
423
				offer.addToSpecialPriceDiff(-Math.max(costReduction, 1));
424
			}
425
		}
426
427
		Player tradingPlayer = this.getTradingPlayer();
428
		if (tradingPlayer != null && !merchantOffers.isEmpty()) {
429
			if (tradingPlayer.containerMenu instanceof MerchantMenu menu) {
430
				menu.updateSellItem();
431
			}
432
433
			tradingPlayer.sendMerchantOffers(
434
				tradingPlayer.containerMenu.containerId, merchantOffers, this.getVillagerData().level(), this.getVillagerXp(), this.showProgressBar(), this.canRestock()
435
			);
436
		}
437
	}
438
439
	@Override
440
	protected void defineSynchedData(final SynchedEntityData.Builder entityData) {
441
		super.defineSynchedData(entityData);
442
		entityData.define(DATA_VILLAGER_DATA, createDefaultVillagerData());
443
		entityData.define(DATA_VILLAGER_DATA_FINALIZED, false);
444
	}
445
446
	public static VillagerData createDefaultVillagerData() {
447
		return new VillagerData(
448
			BuiltInRegistries.VILLAGER_TYPE.getOrThrow(VillagerData.DEFAULT_TYPE), BuiltInRegistries.VILLAGER_PROFESSION.getOrThrow(VillagerProfession.NONE), 1
449
		);
450
	}
451
452
	@Override
453
	protected void addAdditionalSaveData(final ValueOutput output) {
454
		super.addAdditionalSaveData(output);
455
		output.store("VillagerData", VillagerData.CODEC, this.getVillagerData());
456
		output.putBoolean("VillagerDataFinalized", this.getVillagerDataFinalized());
457
		output.putByte("FoodLevel", (byte)this.foodLevel);
458
		output.store("Gossips", GossipContainer.CODEC, this.gossips);
459
		output.putInt("Xp", this.villagerXp);
460
		output.putLong("LastRestock", this.lastRestockGameTime);
461
		output.putLong("LastGossipDecay", this.lastGossipDecayTime);
462
		output.putInt("RestocksToday", this.numberOfRestocksToday);
463
	}
464
465
	@Override
466
	protected void readAdditionalSaveData(final ValueInput input) {
467
		super.readAdditionalSaveData(input);
468
		Optional<VillagerData> villagerDataOptional = input.read("VillagerData", VillagerData.CODEC);
469
		if (input.getBooleanOr("VillagerDataFinalized", false) || villagerDataOptional.isPresent()) {
470
			this.setVillagerDataFinalized(true);
471
			VillagerData villagerData = villagerDataOptional.orElseGet(Villager::createDefaultVillagerData);
472
			this.entityData.set(DATA_VILLAGER_DATA, villagerData);
473
		}
474
475
		this.foodLevel = input.getByteOr("FoodLevel", (byte)0);
476
		this.gossips.clear();
477
		input.read("Gossips", GossipContainer.CODEC).ifPresent(this.gossips::putAll);
478
		this.villagerXp = input.getIntOr("Xp", 0);
479
		this.lastRestockGameTime = input.getLongOr("LastRestock", 0L);
480
		this.lastGossipDecayTime = input.getLongOr("LastGossipDecay", 0L);
481
		this.numberOfRestocksToday = input.getIntOr("RestocksToday", 0);
482
		if (this.level() instanceof ServerLevel serverLevel) {
483
			this.refreshBrain(serverLevel);
484
		}
485
	}
486
487
	@Override
488
	public void postDataManipulated() {
489
		Player tradingPlayer = this.getTradingPlayer();
490
		if (tradingPlayer != null) {
491
			this.updateSpecialPrices(tradingPlayer);
492
		}
493
	}
494
495
	@Override
496
	public boolean removeWhenFarAway(final double distSqr) {
497
		return false;
498
	}
499
500
	@Override
501
	protected @Nullable SoundEvent getAmbientSound() {
502
		if (this.isSleeping()) {
503
			return null;
504
		} else {
505
			return this.isTrading() ? SoundEvents.VILLAGER_TRADE : SoundEvents.VILLAGER_AMBIENT;
506
		}
507
	}
508
509
	@Override
510
	protected SoundEvent getHurtSound(final DamageSource source) {
511
		return SoundEvents.VILLAGER_HURT;
512
	}
513
514
	@Override
515
	protected SoundEvent getDeathSound() {
516
		return SoundEvents.VILLAGER_DEATH;
517
	}
518
519
	public void playWorkSound() {
520
		this.makeSound(this.getVillagerData().profession().value().workSound());
521
	}
522
523
	@Override
524
	public void setVillagerData(final VillagerData data) {
525
		VillagerData currentData = this.getVillagerData();
526
		if (!currentData.profession().equals(data.profession())) {
527
			this.offers = null;
528
		}
529
530
		this.entityData.set(DATA_VILLAGER_DATA, data);
531
	}
532
533
	@Override
534
	public boolean getVillagerDataFinalized() {
535
		return this.entityData.get(DATA_VILLAGER_DATA_FINALIZED);
536
	}
537
538
	@Override
539
	public void setVillagerDataFinalized(final boolean villagerDataFinalized) {
540
		this.entityData.set(DATA_VILLAGER_DATA_FINALIZED, villagerDataFinalized);
541
	}
542
543
	@Override
544
	public VillagerData getVillagerData() {
545
		return this.entityData.get(DATA_VILLAGER_DATA);
546
	}
547
548
	@Override
549
	protected void rewardTradeXp(final MerchantOffer offer) {
550
		int popXp = 3 + this.random.nextInt(4);
551
		this.villagerXp = this.villagerXp + offer.getXp();
552
		this.lastTradedPlayer = this.getTradingPlayer();
553
		if (this.shouldIncreaseLevel()) {
554
			if (this.level() instanceof ServerLevel serverLevel) {
555
				this.increaseMerchantCareer(serverLevel);
556
				this.addEffect(new MobEffectInstance(MobEffects.REGENERATION, 200, 0));
557
			}
558
559
			popXp += 5;
560
		}
561
562
		if (offer.shouldRewardExp()) {
563
			this.level().addFreshEntity(new ExperienceOrb(this.level(), this.getX(), this.getY() + 0.5, this.getZ(), popXp));
564
		}
565
	}
566
567
	@Override
568
	public void setLastHurtByMob(final @Nullable LivingEntity hurtBy) {
569
		if (hurtBy != null && this.level() instanceof ServerLevel serverLevel) {
570
			serverLevel.onReputationEvent(ReputationEventType.VILLAGER_HURT, hurtBy, this);
571
			if (this.isAlive() && hurtBy instanceof Player) {
572
				this.level().broadcastEntityEvent(this, (byte)13);
573
			}
574
		}
575
576
		super.setLastHurtByMob(hurtBy);
577
	}
578
579
	@Override
580
	public void die(final DamageSource source) {
581
		LOGGER.info("Villager {} died, message: '{}'", this, source.getLocalizedDeathMessage(this).getString());
582
		Entity murderer = source.getEntity();
583
		if (murderer != null) {
584
			this.tellWitnessesThatIWasMurdered(murderer);
585
		}
586
587
		this.releaseAllPois();
588
		super.die(source);
589
	}
590
591
	private void releaseAllPois() {
592
		this.releasePoi(MemoryModuleType.HOME);
593
		this.releasePoi(MemoryModuleType.JOB_SITE);
594
		this.releasePoi(MemoryModuleType.POTENTIAL_JOB_SITE);
595
		this.releasePoi(MemoryModuleType.MEETING_POINT);
596
	}
597
598
	private void tellWitnessesThatIWasMurdered(final Entity murderer) {
599
		if (this.level() instanceof ServerLevel serverLevel) {
600
			Optional<NearestVisibleLivingEntities> witnesses = this.brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES);
601
			if (!witnesses.isEmpty()) {
602
				witnesses.get()
603
					.findAll(ReputationEventHandler.class::isInstance)
604
					.forEach(witness -> serverLevel.onReputationEvent(ReputationEventType.VILLAGER_KILLED, murderer, (ReputationEventHandler)witness));
605
			}
606
		}
607
	}
608
609
	public void releasePoi(final MemoryModuleType<GlobalPos> memoryType) {
610
		if (this.level() instanceof ServerLevel) {
611
			MinecraftServer server = ((ServerLevel)this.level()).getServer();
612
			this.brain.getMemory(memoryType).ifPresent(memory -> {
613
				ServerLevel poiLevel = server.getLevel(memory.dimension());
614
				if (poiLevel != null) {
615
					PoiManager poiManager = poiLevel.getPoiManager();
616
					Optional<Holder<PoiType>> type = poiManager.getType(memory.pos());
617
					BiPredicate<Villager, Holder<PoiType>> poiTypePredicate = POI_MEMORIES.get(memoryType);
618
					if (type.isPresent() && poiTypePredicate.test(this, type.get())) {
619
						poiManager.release(memory.pos());
620
						poiLevel.debugSynchronizers().updatePoi(memory.pos());
621
					}
622
				}
623
			});
624
		}
625
	}
626
627
	@Override
628
	public boolean canBreed() {
629
		return this.foodLevel + this.countFoodPointsInInventory() >= 12 && !this.isSleeping() && this.getAge() == 0;
630
	}
631
632
	private boolean hungry() {
633
		return this.foodLevel < 12;
634
	}
635
636
	private void eatUntilFull() {
637
		if (this.hungry()) {
638
			for (int slot = 0; slot < this.getInventory().getContainerSize(); slot++) {
639
				ItemStack itemStack = this.getInventory().getItem(slot);
640
				VillagerFood villagerFood = itemStack.get(DataComponents.VILLAGER_FOOD);
641
				if (villagerFood != null) {
642
					int itemCount = itemStack.getCount();
643
					int toRemove = 0;
644
645
					for (int count = itemCount; count > 0; count--) {
646
						this.foodLevel = this.foodLevel + villagerFood.nutrition();
647
						toRemove++;
648
						if (!this.hungry()) {
649
							this.getInventory().removeItem(slot, toRemove);
650
							return;
651
						}
652
					}
653
654
					this.getInventory().removeItem(slot, toRemove);
655
				}
656
			}
657
		}
658
	}
659
660
	public int getPlayerReputation(final Player player) {
661
		return this.gossips.getReputation(player.getUUID(), t -> true);
662
	}
663
664
	private void digestFood(final int amount) {
665
		this.foodLevel -= amount;
666
	}
667
668
	public void eatAndDigestFood() {
669
		this.eatUntilFull();
670
		this.digestFood(12);
671
	}
672
673
	public void setOffers(final MerchantOffers offers) {
674
		this.offers = offers;
675
	}
676
677
	private boolean shouldIncreaseLevel() {
678
		int currentLevel = this.getVillagerData().level();
679
		return VillagerData.canLevelUp(currentLevel) && this.villagerXp >= VillagerData.getMaxXpPerLevel(currentLevel);
680
	}
681
682
	private void increaseMerchantCareer(final ServerLevel level) {
683
		this.setVillagerData(this.getVillagerData().withLevel(this.getVillagerData().level() + 1));
684
		this.updateTrades(level);
685
	}
686
687
	@Override
688
	protected Component getTypeName() {
689
		return this.getVillagerData().profession().value().name();
690
	}
691
692
	@Override
693
	public void handleEntityEvent(final @EntityEvent.Value byte id) {
694
		if (id == 12) {
695
			this.addParticlesAroundSelf(ParticleTypes.HEART);
696
		} else if (id == 13) {
697
			this.addParticlesAroundSelf(ParticleTypes.ANGRY_VILLAGER);
698
		} else if (id == 14) {
699
			this.addParticlesAroundSelf(ParticleTypes.HAPPY_VILLAGER);
700
		} else if (id == 42) {
701
			this.addParticlesAroundSelf(ParticleTypes.SPLASH);
702
		} else {
703
			super.handleEntityEvent(id);
704
		}
705
	}
706
707
	@Override
708
	public @Nullable SpawnGroupData finalizeSpawn(
709
		final ServerLevelAccessor level, final DifficultyInstance difficulty, final EntitySpawnReason spawnReason, final @Nullable SpawnGroupData groupData
710
	) {
711
		if (spawnReason == EntitySpawnReason.BREEDING) {
712
			this.setVillagerData(this.getVillagerData().withProfession(level.registryAccess(), VillagerProfession.NONE));
713
		}
714
715
		this.finalizeVillagerType(level, this.blockPosition());
716
		return super.finalizeSpawn(level, difficulty, spawnReason, groupData);
717
	}
718
719
	public @Nullable Villager getBreedOffspring(final ServerLevel level, final AgeableMob partner) {
720
		double biomeRoll = this.random.nextDouble();
721
		Holder<VillagerType> type;
722
		if (biomeRoll < 0.5) {
723
			type = level.registryAccess().getOrThrow(VillagerType.byBiome(level.getBiome(this.blockPosition())));
724
		} else if (biomeRoll < 0.75) {
725
			type = this.getVillagerData().type();
726
		} else {
727
			type = ((Villager)partner).getVillagerData().type();
728
		}
729
730
		Villager baby = new Villager(EntityTypes.VILLAGER, level);
731
		baby.setVillagerData(baby.getVillagerData().withType(type).withProfession(level.registryAccess(), VillagerProfession.NONE));
732
		baby.setVillagerDataFinalized(true);
733
		return baby;
734
	}
735
736
	@Override
737
	public void thunderHit(final ServerLevel level, final LightningBolt lightningBolt) {
738
		if (level.getDifficulty() != Difficulty.PEACEFUL) {
739
			LOGGER.info("Villager {} was struck by lightning {}.", this, lightningBolt);
740
			Witch witch = this.convertTo(EntityTypes.WITCH, ConversionParams.single(this, false, false), w -> {
741
				w.finalizeSpawn(level, level.getCurrentDifficultyAt(w.blockPosition()), EntitySpawnReason.CONVERSION, null);
742
				w.setPersistenceRequired();
743
				this.releaseAllPois();
744
			});
745
			if (witch == null) {
746
				super.thunderHit(level, lightningBolt);
747
			}
748
		} else {
749
			super.thunderHit(level, lightningBolt);
750
		}
751
	}
752
753
	@Override
754
	protected void pickUpItem(final ServerLevel level, final ItemEntity entity) {
755
		InventoryCarrier.pickUpItem(level, this, this, entity);
756
	}
757
758
	@Override
759
	public boolean wantsToPickUp(final ServerLevel level, final ItemStack itemStack) {
760
		Item item = itemStack.getItem();
761
		return (
762
				itemStack.is(ItemTags.VILLAGER_PICKS_UP)
763
					|| itemStack.has(DataComponents.VILLAGER_FOOD)
764
					|| this.getVillagerData().profession().value().requestedItems().contains(item)
765
			)
766
			&& this.getInventory().canAddItem(itemStack);
767
	}
768
769
	public boolean hasExcessFood() {
770
		return this.countFoodPointsInInventory() >= 24;
771
	}
772
773
	public boolean wantsMoreFood() {
774
		return this.countFoodPointsInInventory() < 12;
775
	}
776
777
	private int countFoodPointsInInventory() {
778
		SimpleContainer inventory = this.getInventory();
779
		int points = 0;
780
781
		for (ItemStack item : inventory.getItems()) {
782
			VillagerFood villagerFood = item.get(DataComponents.VILLAGER_FOOD);
783
			if (villagerFood != null) {
784
				points += item.count() * villagerFood.nutrition();
785
			}
786
		}
787
788
		return points;
789
	}
790
791
	public boolean hasFarmSeeds() {
792
		return this.getInventory().hasAnyMatching(item -> item.is(ItemTags.VILLAGER_PLANTABLE_SEEDS));
793
	}
794
795
	@Override
796
	protected void updateTrades(final ServerLevel level) {
797
		VillagerData data = this.getVillagerData();
798
		VillagerProfession profession = data.profession().value();
799
		ResourceKey<TradeSet> trades = profession.getTrades(data.level());
800
		if (trades != null) {
801
			this.addOffersFromTradeSet(level, this.getOffers(), trades);
802
			if (SharedConstants.DEBUG_UNLOCK_ALL_TRADES && data.level() < 5) {
803
				this.increaseMerchantCareer(level);
804
			}
805
806
			Player tradingPlayer = this.getTradingPlayer();
807
			if (tradingPlayer != null) {
808
				this.updateSpecialPrices(tradingPlayer);
809
			}
810
		}
811
	}
812
813
	public void gossip(final ServerLevel level, final Villager target, final long timestamp) {
814
		if ((timestamp < this.lastGossipTime || timestamp >= this.lastGossipTime + 1200L)
815
			&& (timestamp < target.lastGossipTime || timestamp >= target.lastGossipTime + 1200L)) {
816
			int newGossip = this.gossips.transferFrom(target.gossips, this.random, 10);
817
			this.lastGossipTime = timestamp;
818
			target.lastGossipTime = timestamp;
819
			this.spawnGolemIfNeeded(level, timestamp, 5);
820
			Player tradingPlayer = this.getTradingPlayer();
821
			if (tradingPlayer != null && newGossip > 0) {
822
				this.updateSpecialPrices(tradingPlayer);
823
			}
824
		}
825
	}
826
827
	private void maybeDecayGossip() {
828
		long timestamp = this.level().getGameTime();
829
		if (this.lastGossipDecayTime == 0L) {
830
			this.lastGossipDecayTime = timestamp;
831
		} else if (timestamp >= this.lastGossipDecayTime + 24000L) {
832
			this.gossips.decay();
833
			this.lastGossipDecayTime = timestamp;
834
		}
835
	}
836
837
	public void spawnGolemIfNeeded(final ServerLevel level, final long timestamp, final int villagersNeededToAgree) {
838
		if (this.wantsToSpawnGolem(timestamp)) {
839
			AABB villagerSearchBox = this.getBoundingBox().inflate(10.0, 10.0, 10.0);
840
			List<Villager> nearbyVillagers = level.getEntitiesOfClass(Villager.class, villagerSearchBox);
841
			List<Villager> nearbyVillagersThatWantAGolem = nearbyVillagers.stream().filter(villager -> villager.wantsToSpawnGolem(timestamp)).limit(5L).toList();
842
			if (nearbyVillagersThatWantAGolem.size() >= villagersNeededToAgree) {
843
				if (!SpawnUtil.trySpawnMob(
844
						EntityTypes.IRON_GOLEM, EntitySpawnReason.MOB_SUMMONED, level, this.blockPosition(), 10, 8, 6, SpawnUtil.Strategy.LEGACY_IRON_GOLEM, false
845
					)
846
					.isEmpty()) {
847
					nearbyVillagers.forEach(GolemSensor::golemDetected);
848
				}
849
			}
850
		}
851
	}
852
853
	public boolean wantsToSpawnGolem(final long timestamp) {
854
		return !this.golemSpawnConditionsMet(this.level().getGameTime()) ? false : !this.brain.hasMemoryValue(MemoryModuleType.GOLEM_DETECTED_RECENTLY);
855
	}
856
857
	@Override
858
	public void onReputationEventFrom(final ReputationEventType type, final Entity source) {
859
		if (type == ReputationEventType.ZOMBIE_VILLAGER_CURED) {
860
			this.gossips.add(source.getUUID(), GossipType.MAJOR_POSITIVE, 20);
861
			this.gossips.add(source.getUUID(), GossipType.MINOR_POSITIVE, 25);
862
		} else if (type == ReputationEventType.TRADE) {
863
			this.gossips.add(source.getUUID(), GossipType.TRADING, 2);
864
		} else if (type == ReputationEventType.VILLAGER_HURT) {
865
			this.gossips.add(source.getUUID(), GossipType.MINOR_NEGATIVE, 25);
866
		} else if (type == ReputationEventType.VILLAGER_KILLED) {
867
			this.gossips.add(source.getUUID(), GossipType.MAJOR_NEGATIVE, 25);
868
		}
869
870
		Player tradingPlayer = this.getTradingPlayer();
871
		if (tradingPlayer != null && tradingPlayer.getUUID().equals(source.getUUID())) {
872
			this.updateSpecialPrices(tradingPlayer);
873
		}
874
	}
875
876
	@Override
877
	public int getVillagerXp() {
878
		return this.villagerXp;
879
	}
880
881
	public void setVillagerXp(final int value) {
882
		this.villagerXp = value;
883
	}
884
885
	private void resetNumberOfRestocks() {
886
		this.catchUpDemand();
887
		this.numberOfRestocksToday = 0;
888
	}
889
890
	public GossipContainer getGossips() {
891
		return this.gossips;
892
	}
893
894
	public void setGossips(final GossipContainer gossips) {
895
		this.gossips.putAll(gossips);
896
	}
897
898
	@Override
899
	public void stopSleeping() {
900
		super.stopSleeping();
901
		this.brain.setMemory(MemoryModuleType.LAST_WOKEN, this.level().getGameTime());
902
	}
903
904
	private boolean golemSpawnConditionsMet(final long gameTime) {
905
		Optional<Long> sleepMemory = this.brain.getMemory(MemoryModuleType.LAST_SLEPT);
906
		return sleepMemory.filter(aLong -> gameTime - aLong < 24000L).isPresent();
907
	}
908
909
	@Override
910
	public <T> @Nullable T get(final DataComponentType<? extends T> type) {
911
		return type == DataComponents.VILLAGER_VARIANT ? castComponentValue((DataComponentType<T>)type, this.getVillagerData().type()) : super.get(type);
912
	}
913
914
	@Override
915
	protected void applyImplicitComponents(final DataComponentGetter components) {
916
		this.applyImplicitComponentIfPresent(components, DataComponents.VILLAGER_VARIANT);
917
		super.applyImplicitComponents(components);
918
	}
919
920
	@Override
921
	protected <T> boolean applyImplicitComponent(final DataComponentType<T> type, final T value) {
922
		if (type == DataComponents.VILLAGER_VARIANT) {
923
			Holder<VillagerType> variant = castComponentValue(DataComponents.VILLAGER_VARIANT, value);
924
			this.setVillagerData(this.getVillagerData().withType(variant));
925
			this.setVillagerDataFinalized(true);
926
			return true;
927
		} else {
928
			return super.applyImplicitComponent(type, value);
929
		}
930
	}
931
}
932

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