| 1 | package net.minecraft.world.entity.npc.villager;
|
| 2 |
|
| 3 | import com.google.common.annotations.VisibleForTesting;
|
| 4 | import com.google.common.collect.Lists;
|
| 5 | import com.mojang.logging.LogUtils;
|
| 6 | import java.util.List;
|
| 7 | import java.util.Optional;
|
| 8 | import net.minecraft.advancements.triggers.CriteriaTriggers;
|
| 9 | import net.minecraft.core.Holder;
|
| 10 | import net.minecraft.core.HolderSet;
|
| 11 | import net.minecraft.core.particles.ParticleOptions;
|
| 12 | import net.minecraft.core.registries.Registries;
|
| 13 | import net.minecraft.network.syncher.EntityDataAccessor;
|
| 14 | import net.minecraft.network.syncher.EntityDataSerializers;
|
| 15 | import net.minecraft.network.syncher.SynchedEntityData;
|
| 16 | import net.minecraft.resources.ResourceKey;
|
| 17 | import net.minecraft.server.level.ServerLevel;
|
| 18 | import net.minecraft.server.level.ServerPlayer;
|
| 19 | import net.minecraft.sounds.SoundEvent;
|
| 20 | import net.minecraft.sounds.SoundEvents;
|
| 21 | import net.minecraft.util.Mth;
|
| 22 | import net.minecraft.util.Unit;
|
| 23 | import net.minecraft.world.DifficultyInstance;
|
| 24 | import net.minecraft.world.SimpleContainer;
|
| 25 | import net.minecraft.world.damagesource.DamageSource;
|
| 26 | import net.minecraft.world.entity.AgeableMob;
|
| 27 | import net.minecraft.world.entity.Entity;
|
| 28 | import net.minecraft.world.entity.EntitySpawnReason;
|
| 29 | import net.minecraft.world.entity.EntityType;
|
| 30 | import net.minecraft.world.entity.SlotAccess;
|
| 31 | import net.minecraft.world.entity.SpawnGroupData;
|
| 32 | import net.minecraft.world.entity.npc.InventoryCarrier;
|
| 33 | import net.minecraft.world.entity.npc.Npc;
|
| 34 | import net.minecraft.world.entity.player.Player;
|
| 35 | import net.minecraft.world.item.ItemStack;
|
| 36 | import net.minecraft.world.item.trading.Merchant;
|
| 37 | import net.minecraft.world.item.trading.MerchantOffer;
|
| 38 | import net.minecraft.world.item.trading.MerchantOffers;
|
| 39 | import net.minecraft.world.item.trading.TradeSet;
|
| 40 | import net.minecraft.world.item.trading.VillagerTrade;
|
| 41 | import net.minecraft.world.level.Level;
|
| 42 | import net.minecraft.world.level.ServerLevelAccessor;
|
| 43 | import net.minecraft.world.level.pathfinder.PathType;
|
| 44 | import net.minecraft.world.level.portal.TeleportTransition;
|
| 45 | import net.minecraft.world.level.storage.ValueInput;
|
| 46 | import net.minecraft.world.level.storage.ValueOutput;
|
| 47 | import net.minecraft.world.level.storage.loot.LootContext;
|
| 48 | import net.minecraft.world.level.storage.loot.LootParams;
|
| 49 | import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
|
| 50 | import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
|
| 51 | import net.minecraft.world.phys.Vec3;
|
| 52 | import org.jspecify.annotations.Nullable;
|
| 53 | import org.slf4j.Logger;
|
| 54 |
|
| 55 | public abstract class AbstractVillager extends AgeableMob implements Npc, Merchant, InventoryCarrier {
|
| 56 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 57 | private static final EntityDataAccessor<Integer> DATA_UNHAPPY_COUNTER = SynchedEntityData.defineId(AbstractVillager.class, EntityDataSerializers.INT);
|
| 58 | private @Nullable Player tradingPlayer;
|
| 59 | protected @Nullable MerchantOffers offers;
|
| 60 | private final SimpleContainer inventory = new SimpleContainer(8);
|
| 61 |
|
| 62 | public AbstractVillager(final EntityType<? extends AbstractVillager> type, final Level level) {
|
| 63 | super(type, level);
|
| 64 | this.setPathfindingMalus(PathType.FIRE_IN_NEIGHBOR, 16.0F);
|
| 65 | this.setPathfindingMalus(PathType.FIRE, -1.0F);
|
| 66 | }
|
| 67 |
|
| 68 | @Override
|
| 69 | public @Nullable SpawnGroupData finalizeSpawn(
|
| 70 | final ServerLevelAccessor level, final DifficultyInstance difficulty, final EntitySpawnReason spawnReason, @Nullable SpawnGroupData groupData
|
| 71 | ) {
|
| 72 | if (groupData == null) {
|
| 73 | groupData = new AgeableMob.AgeableMobGroupData(false);
|
| 74 | }
|
| 75 |
|
| 76 | return super.finalizeSpawn(level, difficulty, spawnReason, groupData);
|
| 77 | }
|
| 78 |
|
| 79 | public int getUnhappyCounter() {
|
| 80 | return this.entityData.get(DATA_UNHAPPY_COUNTER);
|
| 81 | }
|
| 82 |
|
| 83 | public void setUnhappyCounter(final int value) {
|
| 84 | this.entityData.set(DATA_UNHAPPY_COUNTER, value);
|
| 85 | }
|
| 86 |
|
| 87 | @Override
|
| 88 | public int getVillagerXp() {
|
| 89 | return 0;
|
| 90 | }
|
| 91 |
|
| 92 | @Override
|
| 93 | protected void defineSynchedData(final SynchedEntityData.Builder entityData) {
|
| 94 | super.defineSynchedData(entityData);
|
| 95 | entityData.define(DATA_UNHAPPY_COUNTER, 0);
|
| 96 | }
|
| 97 |
|
| 98 | @Override
|
| 99 | public void setTradingPlayer(final @Nullable Player player) {
|
| 100 | this.tradingPlayer = player;
|
| 101 | }
|
| 102 |
|
| 103 | @Override
|
| 104 | public @Nullable Player getTradingPlayer() {
|
| 105 | return this.tradingPlayer;
|
| 106 | }
|
| 107 |
|
| 108 | public boolean isTrading() {
|
| 109 | return this.tradingPlayer != null;
|
| 110 | }
|
| 111 |
|
| 112 | @Override
|
| 113 | public MerchantOffers getOffers() {
|
| 114 | if (this.level() instanceof ServerLevel serverLevel) {
|
| 115 | if (this.offers == null) {
|
| 116 | this.offers = new MerchantOffers();
|
| 117 | this.updateTrades(serverLevel);
|
| 118 | }
|
| 119 |
|
| 120 | return this.offers;
|
| 121 | } else {
|
| 122 | throw new IllegalStateException("Cannot load Villager offers on the client");
|
| 123 | }
|
| 124 | }
|
| 125 |
|
| 126 | @Override
|
| 127 | public void overrideOffers(final @Nullable MerchantOffers offers) {
|
| 128 | }
|
| 129 |
|
| 130 | @Override
|
| 131 | public void overrideXp(final int xp) {
|
| 132 | }
|
| 133 |
|
| 134 | @Override
|
| 135 | public void notifyTrade(final MerchantOffer offer) {
|
| 136 | offer.increaseUses();
|
| 137 | this.ambientSoundTime = -this.getAmbientSoundInterval();
|
| 138 | this.rewardTradeXp(offer);
|
| 139 | if (this.tradingPlayer instanceof ServerPlayer) {
|
| 140 | CriteriaTriggers.TRADE.trigger((ServerPlayer)this.tradingPlayer, this, offer.getResult());
|
| 141 | }
|
| 142 | }
|
| 143 |
|
| 144 | protected abstract void rewardTradeXp(final MerchantOffer offer);
|
| 145 |
|
| 146 | @Override
|
| 147 | public boolean showProgressBar() {
|
| 148 | return true;
|
| 149 | }
|
| 150 |
|
| 151 | @Override
|
| 152 | public void notifyTradeUpdated(final ItemStack itemStack) {
|
| 153 | if (!this.level().isClientSide() && this.ambientSoundTime > -this.getAmbientSoundInterval() + 20) {
|
| 154 | this.ambientSoundTime = -this.getAmbientSoundInterval();
|
| 155 | this.makeSound(this.getTradeUpdatedSound(!itemStack.isEmpty()));
|
| 156 | }
|
| 157 | }
|
| 158 |
|
| 159 | @Override
|
| 160 | public SoundEvent getNotifyTradeSound() {
|
| 161 | return SoundEvents.VILLAGER_YES;
|
| 162 | }
|
| 163 |
|
| 164 | protected SoundEvent getTradeUpdatedSound(final boolean validTrade) {
|
| 165 | return validTrade ? SoundEvents.VILLAGER_YES : SoundEvents.VILLAGER_NO;
|
| 166 | }
|
| 167 |
|
| 168 | public void playCelebrateSound() {
|
| 169 | this.makeSound(SoundEvents.VILLAGER_CELEBRATE);
|
| 170 | }
|
| 171 |
|
| 172 | @Override
|
| 173 | protected void addAdditionalSaveData(final ValueOutput output) {
|
| 174 | super.addAdditionalSaveData(output);
|
| 175 | if (!this.level().isClientSide() && this.offers != null) {
|
| 176 | output.store("Offers", MerchantOffers.CODEC, this.offers);
|
| 177 | }
|
| 178 |
|
| 179 | this.writeInventoryToTag(output);
|
| 180 | }
|
| 181 |
|
| 182 | @Override
|
| 183 | protected void readAdditionalSaveData(final ValueInput input) {
|
| 184 | super.readAdditionalSaveData(input);
|
| 185 | this.offers = input.read("Offers", MerchantOffers.CODEC).orElse(null);
|
| 186 | this.readInventoryFromTag(input);
|
| 187 | }
|
| 188 |
|
| 189 | @Override
|
| 190 | public @Nullable Entity teleport(final TeleportTransition transition) {
|
| 191 | this.stopTrading();
|
| 192 | return super.teleport(transition);
|
| 193 | }
|
| 194 |
|
| 195 | protected void stopTrading() {
|
| 196 | this.setTradingPlayer(null);
|
| 197 | }
|
| 198 |
|
| 199 | @Override
|
| 200 | public void die(final DamageSource source) {
|
| 201 | super.die(source);
|
| 202 | this.stopTrading();
|
| 203 | }
|
| 204 |
|
| 205 | protected void addParticlesAroundSelf(final ParticleOptions particle) {
|
| 206 | for (int i = 0; i < 5; i++) {
|
| 207 | double xa = this.random.nextGaussian() * 0.02;
|
| 208 | double ya = this.random.nextGaussian() * 0.02;
|
| 209 | double za = this.random.nextGaussian() * 0.02;
|
| 210 | this.level().addParticle(particle, this.getRandomX(1.0), this.getRandomY() + 1.0, this.getRandomZ(1.0), xa, ya, za);
|
| 211 | }
|
| 212 | }
|
| 213 |
|
| 214 | @Override
|
| 215 | public boolean canBeLeashed() {
|
| 216 | return false;
|
| 217 | }
|
| 218 |
|
| 219 | @Override
|
| 220 | public SimpleContainer getInventory() {
|
| 221 | return this.inventory;
|
| 222 | }
|
| 223 |
|
| 224 | @Override
|
| 225 | public @Nullable SlotAccess getSlot(final int slot) {
|
| 226 | int inventorySlot = slot - 300;
|
| 227 | return inventorySlot >= 0 && inventorySlot < this.inventory.getContainerSize() ? this.inventory.getSlot(inventorySlot) : super.getSlot(slot);
|
| 228 | }
|
| 229 |
|
| 230 | protected abstract void updateTrades(ServerLevel level);
|
| 231 |
|
| 232 | protected void addOffersFromTradeSet(final ServerLevel level, final MerchantOffers offers, final ResourceKey<TradeSet> resourceKey) {
|
| 233 | Optional<TradeSet> tradeSetOpt = this.registryAccess().lookupOrThrow(Registries.TRADE_SET).getOptional(resourceKey);
|
| 234 | if (tradeSetOpt.isEmpty()) {
|
| 235 | LOGGER.debug("Missing expected trade set {}", resourceKey);
|
| 236 | } else {
|
| 237 | TradeSet tradeSet = tradeSetOpt.get();
|
| 238 | LootContext lootContext = new LootContext.Builder(
|
| 239 | new LootParams.Builder(level)
|
| 240 | .withParameter(LootContextParams.ORIGIN, this.position())
|
| 241 | .withParameter(LootContextParams.THIS_ENTITY, this)
|
| 242 | .withParameter(LootContextParams.ADDITIONAL_COST_COMPONENT_ALLOWED, Unit.INSTANCE)
|
| 243 | .create(LootContextParamSets.VILLAGER_TRADE)
|
| 244 | )
|
| 245 | .create(tradeSet.randomSequence());
|
| 246 | int numberOfOffers = tradeSet.calculateNumberOfTrades(lootContext);
|
| 247 | if (tradeSet.allowDuplicates()) {
|
| 248 | addOffersFromItemListings(lootContext, offers, tradeSet.trades(), numberOfOffers);
|
| 249 | } else {
|
| 250 | addOffersFromItemListingsWithoutDuplicates(lootContext, offers, tradeSet.trades(), numberOfOffers);
|
| 251 | }
|
| 252 | }
|
| 253 | }
|
| 254 |
|
| 255 | @VisibleForTesting
|
| 256 | static void addOffersFromItemListings(
|
| 257 | final LootContext lootContext, final MerchantOffers merchantOffers, final HolderSet<VillagerTrade> potentialOffers, final int numberOfOffers
|
| 258 | ) {
|
| 259 | List<Holder<VillagerTrade>> potentialOffersList = Lists.newArrayList(potentialOffers);
|
| 260 | int offersFound = 0;
|
| 261 |
|
| 262 | while (offersFound < numberOfOffers && !potentialOffersList.isEmpty()) {
|
| 263 | int roll = lootContext.getRandom().nextInt(potentialOffersList.size());
|
| 264 | Holder<VillagerTrade> villagerTrade = potentialOffersList.get(roll);
|
| 265 | MerchantOffer offer = villagerTrade.value().getOffer(lootContext);
|
| 266 | if (offer == null) {
|
| 267 | potentialOffersList.remove(roll);
|
| 268 | } else {
|
| 269 | merchantOffers.add(offer);
|
| 270 | offersFound++;
|
| 271 | }
|
| 272 | }
|
| 273 | }
|
| 274 |
|
| 275 | private static void addOffersFromItemListingsWithoutDuplicates(
|
| 276 | final LootContext lootContext, final MerchantOffers merchantOffers, final HolderSet<VillagerTrade> potentialOffers, final int numberOfOffers
|
| 277 | ) {
|
| 278 | List<Holder<VillagerTrade>> leftoverOffers = Lists.newArrayList(potentialOffers);
|
| 279 | int offersFound = 0;
|
| 280 |
|
| 281 | while (offersFound < numberOfOffers && !leftoverOffers.isEmpty()) {
|
| 282 | Holder<VillagerTrade> villagerTrade = leftoverOffers.remove(lootContext.getRandom().nextInt(leftoverOffers.size()));
|
| 283 | MerchantOffer offer = villagerTrade.value().getOffer(lootContext);
|
| 284 | if (offer != null) {
|
| 285 | merchantOffers.add(offer);
|
| 286 | offersFound++;
|
| 287 | }
|
| 288 | }
|
| 289 | }
|
| 290 |
|
| 291 | @Override
|
| 292 | public Vec3 getRopeHoldPosition(final float partialTickTime) {
|
| 293 | float yRot = Mth.lerp(partialTickTime, this.yBodyRotO, this.yBodyRot) * (float) (Math.PI / 180.0);
|
| 294 | Vec3 offset = new Vec3(0.0, this.getBoundingBox().getYsize() - 1.0, 0.2);
|
| 295 | return this.getPosition(partialTickTime).add(offset.yRot(-yRot));
|
| 296 | }
|
| 297 |
|
| 298 | @Override
|
| 299 | public boolean isClientSide() {
|
| 300 | return this.level().isClientSide();
|
| 301 | }
|
| 302 |
|
| 303 | @Override
|
| 304 | public boolean stillValid(final Player player) {
|
| 305 | return this.getTradingPlayer() == player && this.isAlive() && player.isWithinEntityInteractionRange(this, 4.0);
|
| 306 | }
|
| 307 | }
|
| 308 |
|