| 1 | package net.minecraft.server.level;
|
| 2 |
|
| 3 | import com.google.common.cache.CacheBuilder;
|
| 4 | import com.google.common.cache.CacheLoader;
|
| 5 | import com.google.common.cache.LoadingCache;
|
| 6 | import com.google.common.hash.HashCode;
|
| 7 | import com.google.common.net.InetAddresses;
|
| 8 | import com.mojang.authlib.GameProfile;
|
| 9 | import com.mojang.datafixers.util.Either;
|
| 10 | import com.mojang.logging.LogUtils;
|
| 11 | import com.mojang.serialization.Codec;
|
| 12 | import com.mojang.serialization.DynamicOps;
|
| 13 | import com.mojang.serialization.MapCodec;
|
| 14 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 15 | import java.net.InetSocketAddress;
|
| 16 | import java.util.Collection;
|
| 17 | import java.util.HashSet;
|
| 18 | import java.util.List;
|
| 19 | import java.util.Map;
|
| 20 | import java.util.Optional;
|
| 21 | import java.util.OptionalInt;
|
| 22 | import java.util.Set;
|
| 23 | import java.util.UUID;
|
| 24 | import java.util.concurrent.CompletableFuture;
|
| 25 | import java.util.stream.Collectors;
|
| 26 | import net.fabricmc.fabric.api.networking.v1.context.PacketContextProvider;
|
| 27 | import net.minecraft.ChatFormatting;
|
| 28 | import net.minecraft.CrashReport;
|
| 29 | import net.minecraft.CrashReportCategory;
|
| 30 | import net.minecraft.ReportedException;
|
| 31 | import net.minecraft.advancements.triggers.CriteriaTriggers;
|
| 32 | import net.minecraft.commands.CommandSource;
|
| 33 | import net.minecraft.commands.CommandSourceStack;
|
| 34 | import net.minecraft.commands.arguments.EntityAnchorArgument;
|
| 35 | import net.minecraft.core.BlockPos;
|
| 36 | import net.minecraft.core.Direction;
|
| 37 | import net.minecraft.core.GlobalPos;
|
| 38 | import net.minecraft.core.Holder;
|
| 39 | import net.minecraft.core.SectionPos;
|
| 40 | import net.minecraft.core.UUIDUtil;
|
| 41 | import net.minecraft.core.component.DataComponents;
|
| 42 | import net.minecraft.core.component.TypedDataComponent;
|
| 43 | import net.minecraft.core.particles.BlockParticleOption;
|
| 44 | import net.minecraft.core.particles.ParticleTypes;
|
| 45 | import net.minecraft.nbt.CompoundTag;
|
| 46 | import net.minecraft.network.PacketSendListener;
|
| 47 | import net.minecraft.network.chat.ChatType;
|
| 48 | import net.minecraft.network.chat.CommonComponents;
|
| 49 | import net.minecraft.network.chat.Component;
|
| 50 | import net.minecraft.network.chat.HoverEvent;
|
| 51 | import net.minecraft.network.chat.OutgoingChatMessage;
|
| 52 | import net.minecraft.network.chat.RemoteChatSession;
|
| 53 | import net.minecraft.network.chat.ResolutionContext;
|
| 54 | import net.minecraft.network.protocol.Packet;
|
| 55 | import net.minecraft.network.protocol.common.ClientboundPostEffectsPacket;
|
| 56 | import net.minecraft.network.protocol.common.ClientboundShowDialogPacket;
|
| 57 | import net.minecraft.network.protocol.game.ClientboundAnimatePacket;
|
| 58 | import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
|
| 59 | import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket;
|
| 60 | import net.minecraft.network.protocol.game.ClientboundChangeDifficultyPacket;
|
| 61 | import net.minecraft.network.protocol.game.ClientboundContainerClosePacket;
|
| 62 | import net.minecraft.network.protocol.game.ClientboundContainerSetContentPacket;
|
| 63 | import net.minecraft.network.protocol.game.ClientboundContainerSetDataPacket;
|
| 64 | import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
|
| 65 | import net.minecraft.network.protocol.game.ClientboundEntityEventPacket;
|
| 66 | import net.minecraft.network.protocol.game.ClientboundGameEventPacket;
|
| 67 | import net.minecraft.network.protocol.game.ClientboundHurtAnimationPacket;
|
| 68 | import net.minecraft.network.protocol.game.ClientboundMerchantOffersPacket;
|
| 69 | import net.minecraft.network.protocol.game.ClientboundMountScreenOpenPacket;
|
| 70 | import net.minecraft.network.protocol.game.ClientboundOpenBookPacket;
|
| 71 | import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket;
|
| 72 | import net.minecraft.network.protocol.game.ClientboundOpenSignEditorPacket;
|
| 73 | import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket;
|
| 74 | import net.minecraft.network.protocol.game.ClientboundPlayerCombatEndPacket;
|
| 75 | import net.minecraft.network.protocol.game.ClientboundPlayerCombatEnterPacket;
|
| 76 | import net.minecraft.network.protocol.game.ClientboundPlayerCombatKillPacket;
|
| 77 | import net.minecraft.network.protocol.game.ClientboundPlayerLookAtPacket;
|
| 78 | import net.minecraft.network.protocol.game.ClientboundPlayerRotationPacket;
|
| 79 | import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket;
|
| 80 | import net.minecraft.network.protocol.game.ClientboundRespawnPacket;
|
| 81 | import net.minecraft.network.protocol.game.ClientboundServerDataPacket;
|
| 82 | import net.minecraft.network.protocol.game.ClientboundSetCameraPacket;
|
| 83 | import net.minecraft.network.protocol.game.ClientboundSetCursorItemPacket;
|
| 84 | import net.minecraft.network.protocol.game.ClientboundSetExperiencePacket;
|
| 85 | import net.minecraft.network.protocol.game.ClientboundSetHealthPacket;
|
| 86 | import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket;
|
| 87 | import net.minecraft.network.protocol.game.ClientboundSystemChatPacket;
|
| 88 | import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket;
|
| 89 | import net.minecraft.network.protocol.game.CommonPlayerSpawnInfo;
|
| 90 | import net.minecraft.network.protocol.status.ServerStatus;
|
| 91 | import net.minecraft.resources.Identifier;
|
| 92 | import net.minecraft.resources.ResourceKey;
|
| 93 | import net.minecraft.server.MinecraftServer;
|
| 94 | import net.minecraft.server.PlayerAdvancements;
|
| 95 | import net.minecraft.server.dedicated.DedicatedServer;
|
| 96 | import net.minecraft.server.dialog.Dialog;
|
| 97 | import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
| 98 | import net.minecraft.server.network.TextFilter;
|
| 99 | import net.minecraft.server.permissions.PermissionSet;
|
| 100 | import net.minecraft.server.permissions.Permissions;
|
| 101 | import net.minecraft.server.players.PlayerList;
|
| 102 | import net.minecraft.server.waypoints.ServerWaypointManager;
|
| 103 | import net.minecraft.stats.ServerRecipeBook;
|
| 104 | import net.minecraft.stats.ServerStatsCounter;
|
| 105 | import net.minecraft.stats.Stat;
|
| 106 | import net.minecraft.stats.Stats;
|
| 107 | import net.minecraft.tags.FluidTags;
|
| 108 | import net.minecraft.util.HashOps;
|
| 109 | import net.minecraft.util.Mth;
|
| 110 | import net.minecraft.util.Prediction;
|
| 111 | import net.minecraft.util.ProblemReporter;
|
| 112 | import net.minecraft.util.Unit;
|
| 113 | import net.minecraft.util.Util;
|
| 114 | import net.minecraft.util.debug.DebugSubscription;
|
| 115 | import net.minecraft.util.profiling.Profiler;
|
| 116 | import net.minecraft.util.profiling.ProfilerFiller;
|
| 117 | import net.minecraft.world.Container;
|
| 118 | import net.minecraft.world.Difficulty;
|
| 119 | import net.minecraft.world.InteractionHand;
|
| 120 | import net.minecraft.world.MenuProvider;
|
| 121 | import net.minecraft.world.attribute.BedRule;
|
| 122 | import net.minecraft.world.damagesource.DamageSource;
|
| 123 | import net.minecraft.world.damagesource.DamageTypes;
|
| 124 | import net.minecraft.world.effect.MobEffectInstance;
|
| 125 | import net.minecraft.world.effect.MobEffects;
|
| 126 | import net.minecraft.world.entity.Entity;
|
| 127 | import net.minecraft.world.entity.EntitySelector;
|
| 128 | import net.minecraft.world.entity.EntitySpawnReason;
|
| 129 | import net.minecraft.world.entity.EntitySpawnRequest;
|
| 130 | import net.minecraft.world.entity.EntityType;
|
| 131 | import net.minecraft.world.entity.EntityTypes;
|
| 132 | import net.minecraft.world.entity.EquipmentSlot;
|
| 133 | import net.minecraft.world.entity.LivingEntity;
|
| 134 | import net.minecraft.world.entity.Mob;
|
| 135 | import net.minecraft.world.entity.NeutralMob;
|
| 136 | import net.minecraft.world.entity.PositionMoveRotation;
|
| 137 | import net.minecraft.world.entity.Relative;
|
| 138 | import net.minecraft.world.entity.TamableAnimal;
|
| 139 | import net.minecraft.world.entity.ai.attributes.Attribute;
|
| 140 | import net.minecraft.world.entity.ai.attributes.AttributeInstance;
|
| 141 | import net.minecraft.world.entity.ai.attributes.AttributeModifier;
|
| 142 | import net.minecraft.world.entity.ai.attributes.Attributes;
|
| 143 | import net.minecraft.world.entity.animal.equine.AbstractHorse;
|
| 144 | import net.minecraft.world.entity.animal.happyghast.HappyGhast;
|
| 145 | import net.minecraft.world.entity.animal.nautilus.AbstractNautilus;
|
| 146 | import net.minecraft.world.entity.animal.parrot.Parrot;
|
| 147 | import net.minecraft.world.entity.animal.pig.Pig;
|
| 148 | import net.minecraft.world.entity.item.ItemEntity;
|
| 149 | import net.minecraft.world.entity.monster.Monster;
|
| 150 | import net.minecraft.world.entity.monster.Strider;
|
| 151 | import net.minecraft.world.entity.monster.warden.WardenSpawnTracker;
|
| 152 | import net.minecraft.world.entity.player.ChatVisiblity;
|
| 153 | import net.minecraft.world.entity.player.Input;
|
| 154 | import net.minecraft.world.entity.player.Inventory;
|
| 155 | import net.minecraft.world.entity.player.Player;
|
| 156 | import net.minecraft.world.entity.projectile.arrow.AbstractArrow;
|
| 157 | import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownEnderpearl;
|
| 158 | import net.minecraft.world.entity.vehicle.boat.AbstractBoat;
|
| 159 | import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
| 160 | import net.minecraft.world.inventory.AbstractContainerMenu;
|
| 161 | import net.minecraft.world.inventory.ContainerListener;
|
| 162 | import net.minecraft.world.inventory.ContainerSynchronizer;
|
| 163 | import net.minecraft.world.inventory.HorseInventoryMenu;
|
| 164 | import net.minecraft.world.inventory.NautilusInventoryMenu;
|
| 165 | import net.minecraft.world.inventory.RemoteSlot;
|
| 166 | import net.minecraft.world.inventory.ResultSlot;
|
| 167 | import net.minecraft.world.inventory.Slot;
|
| 168 | import net.minecraft.world.item.ItemCooldowns;
|
| 169 | import net.minecraft.world.item.ItemStack;
|
| 170 | import net.minecraft.world.item.MapItem;
|
| 171 | import net.minecraft.world.item.ServerItemCooldowns;
|
| 172 | import net.minecraft.world.item.component.SwingAnimation;
|
| 173 | import net.minecraft.world.item.component.WrittenBookContent;
|
| 174 | import net.minecraft.world.item.crafting.Recipe;
|
| 175 | import net.minecraft.world.item.crafting.RecipeHolder;
|
| 176 | import net.minecraft.world.item.enchantment.EnchantmentHelper;
|
| 177 | import net.minecraft.world.item.trading.MerchantOffers;
|
| 178 | import net.minecraft.world.level.ChunkPos;
|
| 179 | import net.minecraft.world.level.GameType;
|
| 180 | import net.minecraft.world.level.Level;
|
| 181 | import net.minecraft.world.level.biome.BiomeManager;
|
| 182 | import net.minecraft.world.level.block.AbstractBedBlock;
|
| 183 | import net.minecraft.world.level.block.Block;
|
| 184 | import net.minecraft.world.level.block.HorizontalDirectionalBlock;
|
| 185 | import net.minecraft.world.level.block.RespawnAnchorBlock;
|
| 186 | import net.minecraft.world.level.block.entity.BlockEntity;
|
| 187 | import net.minecraft.world.level.block.entity.CommandBlockEntity;
|
| 188 | import net.minecraft.world.level.block.entity.SignBlockEntity;
|
| 189 | import net.minecraft.world.level.block.entity.SignTextSlot;
|
| 190 | import net.minecraft.world.level.block.state.BlockState;
|
| 191 | import net.minecraft.world.level.gameevent.GameEvent;
|
| 192 | import net.minecraft.world.level.gamerules.GameRules;
|
| 193 | import net.minecraft.world.level.portal.TeleportTransition;
|
| 194 | import net.minecraft.world.level.saveddata.maps.MapId;
|
| 195 | import net.minecraft.world.level.saveddata.maps.MapItemSavedData;
|
| 196 | import net.minecraft.world.level.storage.LevelData;
|
| 197 | import net.minecraft.world.level.storage.TagValueInput;
|
| 198 | import net.minecraft.world.level.storage.ValueInput;
|
| 199 | import net.minecraft.world.level.storage.ValueOutput;
|
| 200 | import net.minecraft.world.phys.AABB;
|
| 201 | import net.minecraft.world.phys.Vec2;
|
| 202 | import net.minecraft.world.phys.Vec3;
|
| 203 | import net.minecraft.world.scores.PlayerTeam;
|
| 204 | import net.minecraft.world.scores.ScoreAccess;
|
| 205 | import net.minecraft.world.scores.ScoreHolder;
|
| 206 | import net.minecraft.world.scores.Scoreboard;
|
| 207 | import net.minecraft.world.scores.Team;
|
| 208 | import net.minecraft.world.scores.TeamColor;
|
| 209 | import net.minecraft.world.scores.criteria.ObjectiveCriteria;
|
| 210 | import org.jspecify.annotations.Nullable;
|
| 211 | import org.slf4j.Logger;
|
| 212 |
|
| 213 | public class ServerPlayer extends Player implements PacketContextProvider {
|
| 214 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 215 | private static final int NEUTRAL_MOB_DEATH_NOTIFICATION_RADII_XZ = 32;
|
| 216 | private static final int NEUTRAL_MOB_DEATH_NOTIFICATION_RADII_Y = 10;
|
| 217 | private static final int FLY_STAT_RECORDING_SPEED = 25;
|
| 218 | public static final double BLOCK_INTERACTION_DISTANCE_VERIFICATION_BUFFER = 1.0;
|
| 219 | public static final double ENTITY_INTERACTION_DISTANCE_VERIFICATION_BUFFER = 3.0;
|
| 220 | public static final int ENDER_PEARL_TICKET_RADIUS = 2;
|
| 221 | public static final String ENDER_PEARLS_TAG = "ender_pearls";
|
| 222 | public static final String ENDER_PEARL_DIMENSION_TAG = "ender_pearl_dimension";
|
| 223 | public static final String TAG_DIMENSION = "Dimension";
|
| 224 | private static final AttributeModifier CREATIVE_BLOCK_INTERACTION_RANGE_MODIFIER = new AttributeModifier(
|
| 225 | Identifier.withDefaultNamespace("creative_mode_block_range"), 0.5, AttributeModifier.Operation.ADD_VALUE
|
| 226 | );
|
| 227 | private static final AttributeModifier CREATIVE_ENTITY_INTERACTION_RANGE_MODIFIER = new AttributeModifier(
|
| 228 | Identifier.withDefaultNamespace("creative_mode_entity_range"), 2.0, AttributeModifier.Operation.ADD_VALUE
|
| 229 | );
|
| 230 | private static final Component SPAWN_SET_MESSAGE = Component.translatable("block.minecraft.set_spawn");
|
| 231 | private static final AttributeModifier WAYPOINT_TRANSMIT_RANGE_CROUCH_MODIFIER = new AttributeModifier(
|
| 232 | Identifier.withDefaultNamespace("waypoint_transmit_range_crouch"), -1.0, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL
|
| 233 | );
|
| 234 | private static final boolean DEFAULT_SEEN_CREDITS = false;
|
| 235 | private static final boolean DEFAULT_SPAWN_EXTRA_PARTICLES_ON_FALL = false;
|
| 236 | public ServerGamePacketListenerImpl connection;
|
| 237 | private final MinecraftServer server;
|
| 238 | public final ServerPlayerGameMode gameMode;
|
| 239 | private final PlayerAdvancements advancements;
|
| 240 | private final ServerStatsCounter stats;
|
| 241 | private float lastRecordedHealthAndAbsorption = Float.MIN_VALUE;
|
| 242 | private int lastRecordedFoodLevel = Integer.MIN_VALUE;
|
| 243 | private int lastRecordedAirLevel = Integer.MIN_VALUE;
|
| 244 | private int lastRecordedArmor = Integer.MIN_VALUE;
|
| 245 | private int lastRecordedLevel = Integer.MIN_VALUE;
|
| 246 | private int lastRecordedExperience = Integer.MIN_VALUE;
|
| 247 | private float lastSentHealth = -1.0E8F;
|
| 248 | private int lastSentFood = -99999999;
|
| 249 | private boolean lastFoodSaturationZero = true;
|
| 250 | private int lastSentExp = -99999999;
|
| 251 | private ChatVisiblity chatVisibility = ChatVisiblity.FULL;
|
| 252 | private ParticleStatus particleStatus = ParticleStatus.ALL;
|
| 253 | private boolean canChatColor = true;
|
| 254 | private long lastActionTime = Util.getMillis();
|
| 255 | private @Nullable Entity camera;
|
| 256 | private boolean isChangingDimension;
|
| 257 | public boolean seenCredits = false;
|
| 258 | private final ServerRecipeBook recipeBook;
|
| 259 | private @Nullable Vec3 levitationStartPos;
|
| 260 | private int levitationStartTime;
|
| 261 | private boolean disconnected;
|
| 262 | private int requestedViewDistance = 2;
|
| 263 | private String language = "en_us";
|
| 264 | private @Nullable Vec3 startingToFallPosition;
|
| 265 | private @Nullable Vec3 enteredNetherPosition;
|
| 266 | private @Nullable Vec3 enteredLavaOnVehiclePosition;
|
| 267 | private @Nullable Vec3 currentExplosionImpactPos;
|
| 268 | private @Nullable Entity currentExplosionCause;
|
| 269 | private SectionPos lastSectionPos = SectionPos.of(0, 0, 0);
|
| 270 | private ChunkTrackingView chunkTrackingView = ChunkTrackingView.EMPTY;
|
| 271 | private ServerPlayer.@Nullable RespawnConfig respawnConfig;
|
| 272 | private final TextFilter textFilter;
|
| 273 | private boolean textFilteringEnabled;
|
| 274 | private boolean allowsListing;
|
| 275 | private boolean spawnExtraParticlesOnFall = false;
|
| 276 | private WardenSpawnTracker wardenSpawnTracker = new WardenSpawnTracker();
|
| 277 | private @Nullable BlockPos raidOmenPosition;
|
| 278 | private Vec3 lastKnownClientMovement = Vec3.ZERO;
|
| 279 | private Input lastClientInput = Input.EMPTY;
|
| 280 | private final Set<ThrownEnderpearl> enderPearls = new HashSet<>();
|
| 281 | private boolean postEffectsDirty = true;
|
| 282 | private long timeEntitySatOnShoulder;
|
| 283 | private CompoundTag shoulderEntityLeft = new CompoundTag();
|
| 284 | private CompoundTag shoulderEntityRight = new CompoundTag();
|
| 285 | private final ContainerSynchronizer containerSynchronizer = new ContainerSynchronizer() {
|
| 286 | private final LoadingCache<TypedDataComponent<?>, Integer> cache = CacheBuilder.newBuilder()
|
| 287 | .maximumSize(256L)
|
| 288 | .build(new CacheLoader<TypedDataComponent<?>, Integer>() {
|
| 289 | private final DynamicOps<HashCode> registryHashOps = ServerPlayer.this.registryAccess().createSerializationContext(HashOps.CRC32C_INSTANCE);
|
| 290 |
|
| 291 | public Integer load(final TypedDataComponent<?> component) {
|
| 292 | return component.encodeValue(this.registryHashOps).getOrThrow(msg -> new IllegalArgumentException("Failed to hash " + component + ": " + msg)).asInt();
|
| 293 | }
|
| 294 | });
|
| 295 |
|
| 296 | @Override
|
| 297 | public void sendInitialData(final AbstractContainerMenu container, final List<ItemStack> slotItems, final ItemStack carriedItem, final int[] dataSlots) {
|
| 298 | ServerPlayer.this.connection.send(new ClientboundContainerSetContentPacket(container.containerId, container.incrementStateId(), slotItems, carriedItem));
|
| 299 |
|
| 300 | for (int slot = 0; slot < dataSlots.length; slot++) {
|
| 301 | this.broadcastDataValue(container, slot, dataSlots[slot]);
|
| 302 | }
|
| 303 | }
|
| 304 |
|
| 305 | @Override
|
| 306 | public void sendSlotChange(final AbstractContainerMenu container, final int slotIndex, final ItemStack itemStack) {
|
| 307 | ServerPlayer.this.connection.send(new ClientboundContainerSetSlotPacket(container.containerId, container.incrementStateId(), slotIndex, itemStack));
|
| 308 | }
|
| 309 |
|
| 310 | @Override
|
| 311 | public void sendCarriedChange(final AbstractContainerMenu container, final ItemStack itemStack) {
|
| 312 | ServerPlayer.this.connection.send(new ClientboundSetCursorItemPacket(itemStack));
|
| 313 | }
|
| 314 |
|
| 315 | @Override
|
| 316 | public void sendDataChange(final AbstractContainerMenu container, final int id, final int value) {
|
| 317 | this.broadcastDataValue(container, id, value);
|
| 318 | }
|
| 319 |
|
| 320 | private void broadcastDataValue(final AbstractContainerMenu container, final int id, final int value) {
|
| 321 | ServerPlayer.this.connection.send(new ClientboundContainerSetDataPacket(container.containerId, id, value));
|
| 322 | }
|
| 323 |
|
| 324 | @Override
|
| 325 | public RemoteSlot createSlot() {
|
| 326 | return new RemoteSlot.Synchronized(this.cache::getUnchecked);
|
| 327 | }
|
| 328 | };
|
| 329 | private final ContainerListener containerListener = new ContainerListener() {
|
| 330 | @Override
|
| 331 | public void slotChanged(final AbstractContainerMenu container, final int slotIndex, final ItemStack changedItem) {
|
| 332 | Slot slot = container.getSlot(slotIndex);
|
| 333 | if (!(slot instanceof ResultSlot)) {
|
| 334 | if (slot.container == ServerPlayer.this.getInventory()) {
|
| 335 | CriteriaTriggers.INVENTORY_CHANGED.trigger(ServerPlayer.this, ServerPlayer.this.getInventory(), changedItem);
|
| 336 | }
|
| 337 | }
|
| 338 | }
|
| 339 |
|
| 340 | @Override
|
| 341 | public void dataChanged(final AbstractContainerMenu container, final int id, final int value) {
|
| 342 | }
|
| 343 | };
|
| 344 | private @Nullable RemoteChatSession chatSession;
|
| 345 | public final @Nullable Object object;
|
| 346 | private final CommandSource commandSource = new CommandSource() {
|
| 347 | @Override
|
| 348 | public boolean acceptsSuccess() {
|
| 349 | return ServerPlayer.this.level().getGameRules().get(GameRules.SEND_COMMAND_FEEDBACK);
|
| 350 | }
|
| 351 |
|
| 352 | @Override
|
| 353 | public boolean acceptsFailure() {
|
| 354 | return true;
|
| 355 | }
|
| 356 |
|
| 357 | @Override
|
| 358 | public boolean shouldInformAdmins() {
|
| 359 | return true;
|
| 360 | }
|
| 361 |
|
| 362 | @Override
|
| 363 | public void sendSystemMessage(final Component message) {
|
| 364 | ServerPlayer.this.sendSystemMessage(message);
|
| 365 | }
|
| 366 | };
|
| 367 | private Set<DebugSubscription<?>> requestedDebugSubscriptions = Set.of();
|
| 368 | private int containerCounter;
|
| 369 | public boolean wonGame;
|
| 370 |
|
| 371 | public ServerPlayer(final MinecraftServer server, final ServerLevel level, final GameProfile gameProfile, final ClientInformation clientInformation) {
|
| 372 | super(level, gameProfile);
|
| 373 | this.server = server;
|
| 374 | this.textFilter = server.createTextFilterForPlayer(this);
|
| 375 | this.gameMode = server.createGameModeForPlayer(this);
|
| 376 | this.gameMode.setGameModeForPlayer(this.calculateGameModeForNewPlayer(null), null);
|
| 377 | this.recipeBook = new ServerRecipeBook((id, output) -> server.getRecipeManager().listDisplaysForRecipe(id, output));
|
| 378 | this.stats = server.getPlayerList().getPlayerStats(this);
|
| 379 | this.advancements = server.getPlayerList().getPlayerAdvancements(this);
|
| 380 | this.updateOptions(clientInformation);
|
| 381 | this.object = null;
|
| 382 | }
|
| 383 |
|
| 384 | @Override
|
| 385 | public BlockPos adjustSpawnLocation(final ServerLevel level, final BlockPos spawnSuggestion) {
|
| 386 | CompletableFuture<Vec3> future = PlayerSpawnFinder.findSpawn(level, spawnSuggestion);
|
| 387 | this.server.managedBlock(future::isDone);
|
| 388 | return BlockPos.containing(future.join());
|
| 389 | }
|
| 390 |
|
| 391 | @Override
|
| 392 | protected void readAdditionalSaveData(final ValueInput input) {
|
| 393 | super.readAdditionalSaveData(input);
|
| 394 | this.wardenSpawnTracker = input.read("warden_spawn_tracker", WardenSpawnTracker.CODEC).orElseGet(WardenSpawnTracker::new);
|
| 395 | this.enteredNetherPosition = input.read("entered_nether_pos", Vec3.CODEC).orElse(null);
|
| 396 | this.currentExplosionImpactPos = input.read("last_explosion_impact_pos", Vec3.CODEC).orElse(null);
|
| 397 | this.seenCredits = input.getBooleanOr("seenCredits", false);
|
| 398 | input.read("recipeBook", ServerRecipeBook.Packed.CODEC)
|
| 399 | .ifPresent(p -> this.recipeBook.loadUntrusted(p, id -> this.server.getRecipeManager().byKey(id).isPresent()));
|
| 400 | if (this.isSleeping()) {
|
| 401 | this.stopSleeping();
|
| 402 | }
|
| 403 |
|
| 404 | this.respawnConfig = input.read("respawn", ServerPlayer.RespawnConfig.CODEC).orElse(null);
|
| 405 | this.spawnExtraParticlesOnFall = input.getBooleanOr("spawn_extra_particles_on_fall", false);
|
| 406 | this.raidOmenPosition = input.read("raid_omen_position", BlockPos.CODEC).orElse(null);
|
| 407 | this.gameMode
|
| 408 | .setGameModeForPlayer(this.calculateGameModeForNewPlayer(readPlayerMode(input, "playerGameType")), readPlayerMode(input, "previousPlayerGameType"));
|
| 409 | input.read("post_effects", Codec.list(Identifier.CODEC)).ifPresent(this.postEffects::addAll);
|
| 410 | this.setShoulderEntityLeft(input.read("ShoulderEntityLeft", CompoundTag.CODEC).orElseGet(CompoundTag::new));
|
| 411 | this.setShoulderEntityRight(input.read("ShoulderEntityRight", CompoundTag.CODEC).orElseGet(CompoundTag::new));
|
| 412 | }
|
| 413 |
|
| 414 | @Override
|
| 415 | protected void addAdditionalSaveData(final ValueOutput output) {
|
| 416 | super.addAdditionalSaveData(output);
|
| 417 | output.store("warden_spawn_tracker", WardenSpawnTracker.CODEC, this.wardenSpawnTracker);
|
| 418 | this.storeGameTypes(output);
|
| 419 | output.putBoolean("seenCredits", this.seenCredits);
|
| 420 | output.storeNullable("entered_nether_pos", Vec3.CODEC, this.enteredNetherPosition);
|
| 421 | output.storeNullable("last_explosion_impact_pos", Vec3.CODEC, this.currentExplosionImpactPos);
|
| 422 | this.saveParentVehicle(output);
|
| 423 | output.store("recipeBook", ServerRecipeBook.Packed.CODEC, this.recipeBook.pack());
|
| 424 | output.putString("Dimension", this.level().dimension().identifier().toString());
|
| 425 | output.storeNullable("respawn", ServerPlayer.RespawnConfig.CODEC, this.respawnConfig);
|
| 426 | output.putBoolean("spawn_extra_particles_on_fall", this.spawnExtraParticlesOnFall);
|
| 427 | output.storeNullable("raid_omen_position", BlockPos.CODEC, this.raidOmenPosition);
|
| 428 | this.saveEnderPearls(output);
|
| 429 | output.store("post_effects", Codec.list(Identifier.CODEC), this.postEffects);
|
| 430 | if (!this.getShoulderEntityLeft().isEmpty()) {
|
| 431 | output.store("ShoulderEntityLeft", CompoundTag.CODEC, this.getShoulderEntityLeft());
|
| 432 | }
|
| 433 |
|
| 434 | if (!this.getShoulderEntityRight().isEmpty()) {
|
| 435 | output.store("ShoulderEntityRight", CompoundTag.CODEC, this.getShoulderEntityRight());
|
| 436 | }
|
| 437 | }
|
| 438 |
|
| 439 | private void saveParentVehicle(final ValueOutput playerOutput) {
|
| 440 | Entity rootVehicle = this.getRootVehicle();
|
| 441 | Entity vehicle = this.getVehicle();
|
| 442 | if (vehicle != null && rootVehicle != this && rootVehicle.hasExactlyOnePlayerPassenger()) {
|
| 443 | ValueOutput vehicleWrapper = playerOutput.child("RootVehicle");
|
| 444 | vehicleWrapper.store("Attach", UUIDUtil.CODEC, vehicle.getUUID());
|
| 445 | rootVehicle.save(vehicleWrapper.child("Entity"));
|
| 446 | }
|
| 447 | }
|
| 448 |
|
| 449 | public void loadAndSpawnParentVehicle(final ValueInput playerInput) {
|
| 450 | Optional<ValueInput> rootTag = playerInput.child("RootVehicle");
|
| 451 | if (!rootTag.isEmpty()) {
|
| 452 | ServerLevel serverLevel = this.level();
|
| 453 | Entity vehicle = EntityType.loadEntityRecursive(
|
| 454 | rootTag.get().childOrEmpty("Entity"), serverLevel, EntitySpawnReason.LOAD, e -> !serverLevel.addWithUUID(e) ? null : e
|
| 455 | );
|
| 456 | if (vehicle != null) {
|
| 457 | UUID attachTo = rootTag.get().read("Attach", UUIDUtil.CODEC).orElse(null);
|
| 458 | if (vehicle.getUUID().equals(attachTo)) {
|
| 459 | this.startRiding(vehicle, true, false);
|
| 460 | } else {
|
| 461 | for (Entity entity : vehicle.getIndirectPassengers()) {
|
| 462 | if (entity.getUUID().equals(attachTo)) {
|
| 463 | this.startRiding(entity, true, false);
|
| 464 | break;
|
| 465 | }
|
| 466 | }
|
| 467 | }
|
| 468 |
|
| 469 | if (!this.isPassenger()) {
|
| 470 | LOGGER.warn("Couldn't reattach entity to player");
|
| 471 | vehicle.discard();
|
| 472 |
|
| 473 | for (Entity entity : vehicle.getIndirectPassengers()) {
|
| 474 | entity.discard();
|
| 475 | }
|
| 476 | }
|
| 477 | }
|
| 478 | }
|
| 479 | }
|
| 480 |
|
| 481 | private void saveEnderPearls(final ValueOutput playerOutput) {
|
| 482 | if (!this.enderPearls.isEmpty()) {
|
| 483 | ValueOutput.ValueOutputList pearlsOutput = playerOutput.childrenList("ender_pearls");
|
| 484 |
|
| 485 | for (ThrownEnderpearl enderPearl : this.enderPearls) {
|
| 486 | if (enderPearl.isRemoved()) {
|
| 487 | LOGGER.warn("Trying to save removed ender pearl, skipping");
|
| 488 | } else {
|
| 489 | ValueOutput pearlTag = pearlsOutput.addChild();
|
| 490 | enderPearl.save(pearlTag);
|
| 491 | pearlTag.store("ender_pearl_dimension", Level.RESOURCE_KEY_CODEC, enderPearl.level().dimension());
|
| 492 | }
|
| 493 | }
|
| 494 | }
|
| 495 | }
|
| 496 |
|
| 497 | public void loadAndSpawnEnderPearls(final ValueInput playerInput) {
|
| 498 | playerInput.childrenListOrEmpty("ender_pearls").forEach(this::loadAndSpawnEnderPearl);
|
| 499 | }
|
| 500 |
|
| 501 | private void loadAndSpawnEnderPearl(final ValueInput pearlInput) {
|
| 502 | Optional<ResourceKey<Level>> pearlLevelKey = pearlInput.read("ender_pearl_dimension", Level.RESOURCE_KEY_CODEC);
|
| 503 | if (!pearlLevelKey.isEmpty()) {
|
| 504 | ServerLevel pearlLevel = this.level().getServer().getLevel(pearlLevelKey.get());
|
| 505 | if (pearlLevel != null) {
|
| 506 | Entity pearl = EntityType.loadEntityRecursive(pearlInput, pearlLevel, EntitySpawnReason.LOAD, entity -> !pearlLevel.addWithUUID(entity) ? null : entity);
|
| 507 | if (pearl != null) {
|
| 508 | placeEnderPearlTicket(pearlLevel, pearl.chunkPosition());
|
| 509 | } else {
|
| 510 | LOGGER.warn("Failed to spawn player ender pearl in level ({}), skipping", pearlLevelKey.get());
|
| 511 | }
|
| 512 | } else {
|
| 513 | LOGGER.warn("Trying to load ender pearl without level ({}) being loaded, skipping", pearlLevelKey.get());
|
| 514 | }
|
| 515 | }
|
| 516 | }
|
| 517 |
|
| 518 | public void setExperiencePoints(final int amount) {
|
| 519 | float limit = this.getXpNeededForNextLevel();
|
| 520 | float max = (limit - 1.0F) / limit;
|
| 521 | float experiencePointsToSet = Mth.clamp(amount / limit, 0.0F, max);
|
| 522 | if (experiencePointsToSet != this.experienceProgress) {
|
| 523 | this.experienceProgress = experiencePointsToSet;
|
| 524 | this.lastSentExp = -1;
|
| 525 | }
|
| 526 | }
|
| 527 |
|
| 528 | public void setExperienceLevels(final int amount) {
|
| 529 | if (amount != this.experienceLevel) {
|
| 530 | this.experienceLevel = amount;
|
| 531 | this.lastSentExp = -1;
|
| 532 | }
|
| 533 | }
|
| 534 |
|
| 535 | @Override
|
| 536 | public void giveExperienceLevels(final int amount) {
|
| 537 | if (amount != 0) {
|
| 538 | super.giveExperienceLevels(amount);
|
| 539 | this.lastSentExp = -1;
|
| 540 | }
|
| 541 | }
|
| 542 |
|
| 543 | @Override
|
| 544 | public void onEnchantmentPerformed(final ItemStack itemStack, final int enchantmentCost) {
|
| 545 | super.onEnchantmentPerformed(itemStack, enchantmentCost);
|
| 546 | this.lastSentExp = -1;
|
| 547 | }
|
| 548 |
|
| 549 | private void initMenu(final AbstractContainerMenu container) {
|
| 550 | container.addSlotListener(this.containerListener);
|
| 551 | container.setSynchronizer(this.containerSynchronizer);
|
| 552 | }
|
| 553 |
|
| 554 | public void initInventoryMenu() {
|
| 555 | this.initMenu(this.inventoryMenu);
|
| 556 | }
|
| 557 |
|
| 558 | @Override
|
| 559 | public void onEnterCombat() {
|
| 560 | super.onEnterCombat();
|
| 561 | this.connection.send(ClientboundPlayerCombatEnterPacket.INSTANCE);
|
| 562 | }
|
| 563 |
|
| 564 | @Override
|
| 565 | public void onLeaveCombat() {
|
| 566 | super.onLeaveCombat();
|
| 567 | this.connection.send(new ClientboundPlayerCombatEndPacket(this.getCombatTracker()));
|
| 568 | }
|
| 569 |
|
| 570 | @Override
|
| 571 | public void onInsideBlock(final BlockState state) {
|
| 572 | CriteriaTriggers.ENTER_BLOCK.trigger(this, state);
|
| 573 | }
|
| 574 |
|
| 575 | @Override
|
| 576 | protected ItemCooldowns createItemCooldowns() {
|
| 577 | return new ServerItemCooldowns(this);
|
| 578 | }
|
| 579 |
|
| 580 | @Override
|
| 581 | public void tick() {
|
| 582 | this.connection.tickClientLoadTimeout();
|
| 583 | this.gameMode.tick();
|
| 584 | this.wardenSpawnTracker.tick();
|
| 585 | if (this.damageCooldownTime > 0) {
|
| 586 | this.damageCooldownTime--;
|
| 587 | }
|
| 588 |
|
| 589 | this.containerMenu.broadcastChanges();
|
| 590 | if (!this.containerMenu.stillValid(this)) {
|
| 591 | this.closeContainer();
|
| 592 | this.containerMenu = this.inventoryMenu;
|
| 593 | }
|
| 594 |
|
| 595 | Entity camera = this.getCamera();
|
| 596 | if (camera != this) {
|
| 597 | if (camera.isAlive()) {
|
| 598 | this.absSnapTo(camera.getX(), camera.getY(), camera.getZ(), camera.getYRot(), camera.getXRot());
|
| 599 | this.level().getChunkSource().move(this);
|
| 600 | if (this.wantsToStopRiding()) {
|
| 601 | this.setCamera(this);
|
| 602 | }
|
| 603 | } else {
|
| 604 | this.setCamera(this);
|
| 605 | }
|
| 606 | }
|
| 607 |
|
| 608 | CriteriaTriggers.TICK.trigger(this);
|
| 609 | if (this.levitationStartPos != null) {
|
| 610 | CriteriaTriggers.LEVITATION.trigger(this, this.levitationStartPos, this.tickCount - this.levitationStartTime);
|
| 611 | }
|
| 612 |
|
| 613 | this.trackStartFallingPosition();
|
| 614 | this.trackEnteredOrExitedLavaOnVehicle();
|
| 615 | this.updatePlayerAttributes();
|
| 616 | this.advancements.flushDirty(this, true);
|
| 617 | if (this.postEffectsDirty) {
|
| 618 | this.sendPostEffects();
|
| 619 | }
|
| 620 | }
|
| 621 |
|
| 622 | private void updatePlayerAttributes() {
|
| 623 | AttributeInstance blockInteractionRange = this.getAttribute(Attributes.BLOCK_INTERACTION_RANGE);
|
| 624 | if (blockInteractionRange != null) {
|
| 625 | if (this.isCreative()) {
|
| 626 | blockInteractionRange.addOrUpdateTransientModifier(CREATIVE_BLOCK_INTERACTION_RANGE_MODIFIER);
|
| 627 | } else {
|
| 628 | blockInteractionRange.removeModifier(CREATIVE_BLOCK_INTERACTION_RANGE_MODIFIER);
|
| 629 | }
|
| 630 | }
|
| 631 |
|
| 632 | AttributeInstance entityInteractionRange = this.getAttribute(Attributes.ENTITY_INTERACTION_RANGE);
|
| 633 | if (entityInteractionRange != null) {
|
| 634 | if (this.isCreative()) {
|
| 635 | entityInteractionRange.addOrUpdateTransientModifier(CREATIVE_ENTITY_INTERACTION_RANGE_MODIFIER);
|
| 636 | } else {
|
| 637 | entityInteractionRange.removeModifier(CREATIVE_ENTITY_INTERACTION_RANGE_MODIFIER);
|
| 638 | }
|
| 639 | }
|
| 640 |
|
| 641 | AttributeInstance waypointTransmitRange = this.getAttribute(Attributes.WAYPOINT_TRANSMIT_RANGE);
|
| 642 | if (waypointTransmitRange != null) {
|
| 643 | if (this.isCrouching()) {
|
| 644 | waypointTransmitRange.addOrUpdateTransientModifier(WAYPOINT_TRANSMIT_RANGE_CROUCH_MODIFIER);
|
| 645 | } else {
|
| 646 | waypointTransmitRange.removeModifier(WAYPOINT_TRANSMIT_RANGE_CROUCH_MODIFIER);
|
| 647 | }
|
| 648 | }
|
| 649 | }
|
| 650 |
|
| 651 | public void doTick() {
|
| 652 | try {
|
| 653 | if (!this.isSpectator() || !this.touchingUnloadedChunk()) {
|
| 654 | super.tick();
|
| 655 | if (!this.containerMenu.stillValid(this)) {
|
| 656 | this.closeContainer();
|
| 657 | this.containerMenu = this.inventoryMenu;
|
| 658 | }
|
| 659 |
|
| 660 | this.foodData.tick(this);
|
| 661 | this.awardStat(Stats.PLAY_TIME);
|
| 662 | this.awardStat(Stats.TOTAL_WORLD_TIME);
|
| 663 | if (this.isAlive()) {
|
| 664 | this.awardStat(Stats.TIME_SINCE_DEATH);
|
| 665 | }
|
| 666 |
|
| 667 | if (this.isDiscrete()) {
|
| 668 | this.awardStat(Stats.CROUCH_TIME);
|
| 669 | }
|
| 670 |
|
| 671 | if (!this.isSleeping()) {
|
| 672 | this.awardStat(Stats.TIME_SINCE_REST);
|
| 673 | }
|
| 674 | }
|
| 675 |
|
| 676 | for (int i = 0; i < this.getInventory().getContainerSize(); i++) {
|
| 677 | ItemStack itemStack = this.getInventory().getItem(i);
|
| 678 | if (!itemStack.isEmpty()) {
|
| 679 | this.synchronizeSpecialItemUpdates(itemStack);
|
| 680 | }
|
| 681 | }
|
| 682 |
|
| 683 | if (this.getHealth() != this.lastSentHealth
|
| 684 | || this.lastSentFood != this.foodData.getFoodLevel()
|
| 685 | || this.foodData.getSaturationLevel() == 0.0F != this.lastFoodSaturationZero) {
|
| 686 | this.connection.send(new ClientboundSetHealthPacket(this.getHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel()));
|
| 687 | this.lastSentHealth = this.getHealth();
|
| 688 | this.lastSentFood = this.foodData.getFoodLevel();
|
| 689 | this.lastFoodSaturationZero = this.foodData.getSaturationLevel() == 0.0F;
|
| 690 | }
|
| 691 |
|
| 692 | if (this.getHealth() + this.getAbsorptionAmount() != this.lastRecordedHealthAndAbsorption) {
|
| 693 | this.lastRecordedHealthAndAbsorption = this.getHealth() + this.getAbsorptionAmount();
|
| 694 | this.updateScoreForCriteria(ObjectiveCriteria.HEALTH, Mth.ceil(this.lastRecordedHealthAndAbsorption));
|
| 695 | }
|
| 696 |
|
| 697 | if (this.foodData.getFoodLevel() != this.lastRecordedFoodLevel) {
|
| 698 | this.lastRecordedFoodLevel = this.foodData.getFoodLevel();
|
| 699 | this.updateScoreForCriteria(ObjectiveCriteria.FOOD, Mth.ceil(this.lastRecordedFoodLevel));
|
| 700 | }
|
| 701 |
|
| 702 | if (this.getAirSupply() != this.lastRecordedAirLevel) {
|
| 703 | this.lastRecordedAirLevel = this.getAirSupply();
|
| 704 | this.updateScoreForCriteria(ObjectiveCriteria.AIR, Mth.ceil(this.lastRecordedAirLevel));
|
| 705 | }
|
| 706 |
|
| 707 | if (this.getArmorValue() != this.lastRecordedArmor) {
|
| 708 | this.lastRecordedArmor = this.getArmorValue();
|
| 709 | this.updateScoreForCriteria(ObjectiveCriteria.ARMOR, Mth.ceil(this.lastRecordedArmor));
|
| 710 | }
|
| 711 |
|
| 712 | if (this.totalExperience != this.lastRecordedExperience) {
|
| 713 | this.lastRecordedExperience = this.totalExperience;
|
| 714 | this.updateScoreForCriteria(ObjectiveCriteria.EXPERIENCE, Mth.ceil(this.lastRecordedExperience));
|
| 715 | }
|
| 716 |
|
| 717 | if (this.experienceLevel != this.lastRecordedLevel) {
|
| 718 | this.lastRecordedLevel = this.experienceLevel;
|
| 719 | this.updateScoreForCriteria(ObjectiveCriteria.LEVEL, Mth.ceil(this.lastRecordedLevel));
|
| 720 | }
|
| 721 |
|
| 722 | if (this.totalExperience != this.lastSentExp) {
|
| 723 | this.lastSentExp = this.totalExperience;
|
| 724 | this.connection.send(new ClientboundSetExperiencePacket(this.experienceProgress, this.totalExperience, this.experienceLevel));
|
| 725 | }
|
| 726 |
|
| 727 | if (this.tickCount % 20 == 0) {
|
| 728 | CriteriaTriggers.LOCATION.trigger(this);
|
| 729 | }
|
| 730 | } catch (Throwable t) {
|
| 731 | CrashReport report = CrashReport.forThrowable(t, "Ticking player");
|
| 732 | CrashReportCategory category = report.addCategory("Player being ticked");
|
| 733 | this.fillCrashReportCategory(category);
|
| 734 | throw new ReportedException(report);
|
| 735 | }
|
| 736 | }
|
| 737 |
|
| 738 | private void synchronizeSpecialItemUpdates(final ItemStack itemStack) {
|
| 739 | MapId mapId = itemStack.get(DataComponents.MAP_ID);
|
| 740 | MapItemSavedData data = MapItem.getSavedData(mapId, this.level());
|
| 741 | if (data != null) {
|
| 742 | Packet<?> packet = data.getUpdatePacket(mapId, this);
|
| 743 | if (packet != null) {
|
| 744 | this.connection.send(packet);
|
| 745 | }
|
| 746 | }
|
| 747 | }
|
| 748 |
|
| 749 | @Override
|
| 750 | protected void tickRegeneration() {
|
| 751 | if (this.level().getDifficulty() == Difficulty.PEACEFUL && this.level().getGameRules().get(GameRules.NATURAL_HEALTH_REGENERATION)) {
|
| 752 | if (this.tickCount % 20 == 0) {
|
| 753 | if (this.getHealth() < this.getMaxHealth()) {
|
| 754 | this.heal(1.0F);
|
| 755 | }
|
| 756 |
|
| 757 | float saturation = this.foodData.getSaturationLevel();
|
| 758 | if (saturation < 20.0F) {
|
| 759 | this.foodData.setSaturation(saturation + 1.0F);
|
| 760 | }
|
| 761 | }
|
| 762 |
|
| 763 | if (this.tickCount % 10 == 0 && this.foodData.needsFood()) {
|
| 764 | this.foodData.setFoodLevel(this.foodData.getFoodLevel() + 1);
|
| 765 | }
|
| 766 | }
|
| 767 | }
|
| 768 |
|
| 769 | @Override
|
| 770 | public void handleShoulderEntities() {
|
| 771 | this.playShoulderEntityAmbientSound(this.getShoulderEntityLeft());
|
| 772 | this.playShoulderEntityAmbientSound(this.getShoulderEntityRight());
|
| 773 | if (this.fallDistance > 0.5 || this.isInWater() || this.getAbilities().flying || this.isSleeping() || this.isInPowderSnow) {
|
| 774 | this.removeEntitiesOnShoulder();
|
| 775 | }
|
| 776 | }
|
| 777 |
|
| 778 | private void playShoulderEntityAmbientSound(final CompoundTag shoulderEntityTag) {
|
| 779 | if (!shoulderEntityTag.isEmpty() && !shoulderEntityTag.getBooleanOr("Silent", false)) {
|
| 780 | if (this.random.nextInt(200) == 0) {
|
| 781 | EntityType<?> entityType = shoulderEntityTag.read("id", EntityType.CODEC).orElse(null);
|
| 782 | if (entityType == EntityTypes.PARROT && !Parrot.imitateNearbyMobs(this.level(), this)) {
|
| 783 | this.level()
|
| 784 | .playSound(
|
| 785 | null, this.getX(), this.getY(), this.getZ(), Parrot.getAmbient(this.level(), this.random), this.getSoundSource(), 1.0F, Parrot.getPitch(this.random)
|
| 786 | );
|
| 787 | }
|
| 788 | }
|
| 789 | }
|
| 790 | }
|
| 791 |
|
| 792 | public boolean setEntityOnShoulder(final CompoundTag entityTag) {
|
| 793 | if (this.isPassenger() || !this.onGround() || this.isInWater() || this.isInPowderSnow) {
|
| 794 | return false;
|
| 795 | } else if (this.getShoulderEntityLeft().isEmpty()) {
|
| 796 | this.setShoulderEntityLeft(entityTag);
|
| 797 | this.timeEntitySatOnShoulder = this.level().getGameTime();
|
| 798 | return true;
|
| 799 | } else if (this.getShoulderEntityRight().isEmpty()) {
|
| 800 | this.setShoulderEntityRight(entityTag);
|
| 801 | this.timeEntitySatOnShoulder = this.level().getGameTime();
|
| 802 | return true;
|
| 803 | } else {
|
| 804 | return false;
|
| 805 | }
|
| 806 | }
|
| 807 |
|
| 808 | @Override
|
| 809 | protected void removeEntitiesOnShoulder() {
|
| 810 | if (this.timeEntitySatOnShoulder + 20L < this.level().getGameTime()) {
|
| 811 | this.respawnEntityOnShoulder(this.getShoulderEntityLeft());
|
| 812 | this.setShoulderEntityLeft(new CompoundTag());
|
| 813 | this.respawnEntityOnShoulder(this.getShoulderEntityRight());
|
| 814 | this.setShoulderEntityRight(new CompoundTag());
|
| 815 | }
|
| 816 | }
|
| 817 |
|
| 818 | private void respawnEntityOnShoulder(final CompoundTag tag) {
|
| 819 | ServerLevel serverLevel = this.level();
|
| 820 | if (!tag.isEmpty()) {
|
| 821 | try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(this.problemPath(), LOGGER)) {
|
| 822 | EntityType.create(
|
| 823 | TagValueInput.create(reporter.forChild(() -> ".shoulder"), serverLevel.registryAccess(), tag),
|
| 824 | serverLevel,
|
| 825 | new EntitySpawnRequest(EntitySpawnReason.LOAD, false)
|
| 826 | )
|
| 827 | .ifPresent(entity -> {
|
| 828 | if (entity instanceof TamableAnimal tamed) {
|
| 829 | tamed.setOwner(this);
|
| 830 | }
|
| 831 |
|
| 832 | entity.setPos(this.getX(), this.getY() + 0.7F, this.getZ());
|
| 833 | serverLevel.addWithUUID(entity);
|
| 834 | });
|
| 835 | }
|
| 836 | }
|
| 837 | }
|
| 838 |
|
| 839 | @Override
|
| 840 | public void resetFallDistance() {
|
| 841 | if (this.getHealth() > 0.0F && this.startingToFallPosition != null) {
|
| 842 | CriteriaTriggers.FALL_FROM_HEIGHT.trigger(this, this.startingToFallPosition);
|
| 843 | }
|
| 844 |
|
| 845 | this.startingToFallPosition = null;
|
| 846 | super.resetFallDistance();
|
| 847 | }
|
| 848 |
|
| 849 | public void trackStartFallingPosition() {
|
| 850 | if (this.fallDistance > 0.0 && this.startingToFallPosition == null) {
|
| 851 | this.startingToFallPosition = this.position();
|
| 852 | if (this.currentExplosionImpactPos != null && this.currentExplosionImpactPos.y <= this.startingToFallPosition.y) {
|
| 853 | CriteriaTriggers.FALL_AFTER_EXPLOSION.trigger(this, this.currentExplosionImpactPos, this.currentExplosionCause);
|
| 854 | }
|
| 855 |
|
| 856 | this.currentExplosionImpactPos = null;
|
| 857 | this.currentExplosionCause = null;
|
| 858 | }
|
| 859 | }
|
| 860 |
|
| 861 | public void trackEnteredOrExitedLavaOnVehicle() {
|
| 862 | if (this.getVehicle() != null && this.getVehicle().isInLava()) {
|
| 863 | if (this.enteredLavaOnVehiclePosition == null) {
|
| 864 | this.enteredLavaOnVehiclePosition = this.position();
|
| 865 | } else {
|
| 866 | CriteriaTriggers.RIDE_ENTITY_IN_LAVA_TRIGGER.trigger(this, this.enteredLavaOnVehiclePosition);
|
| 867 | }
|
| 868 | }
|
| 869 |
|
| 870 | if (this.enteredLavaOnVehiclePosition != null && (this.getVehicle() == null || !this.getVehicle().isInLava())) {
|
| 871 | this.enteredLavaOnVehiclePosition = null;
|
| 872 | }
|
| 873 | }
|
| 874 |
|
| 875 | private void updateScoreForCriteria(final ObjectiveCriteria criteria, final int value) {
|
| 876 | this.level().getScoreboard().forAllObjectives(criteria, this, score -> score.set(value));
|
| 877 | }
|
| 878 |
|
| 879 | @Override
|
| 880 | public void die(final DamageSource source) {
|
| 881 | this.gameEvent(GameEvent.ENTITY_DIE);
|
| 882 | boolean showDeathMessage = this.level().getGameRules().get(GameRules.SHOW_DEATH_MESSAGES);
|
| 883 | if (showDeathMessage) {
|
| 884 | Component deathMessage = this.getCombatTracker().getDeathMessage();
|
| 885 | this.connection
|
| 886 | .send(
|
| 887 | new ClientboundPlayerCombatKillPacket(this.getId(), deathMessage),
|
| 888 | PacketSendListener.exceptionallySend(
|
| 889 | () -> {
|
| 890 | int truncatedMessageSize = 256;
|
| 891 | String truncatedDeathMessage = deathMessage.getString(256);
|
| 892 | Component explanation = Component.translatable(
|
| 893 | "death.attack.message_too_long", Component.literal(truncatedDeathMessage).withStyle(ChatFormatting.YELLOW)
|
| 894 | );
|
| 895 | Component fakeDeathMessage = Component.translatable("death.attack.even_more_magic", this.getDisplayName())
|
| 896 | .withStyle(style -> style.withHoverEvent(new HoverEvent.ShowText(explanation)));
|
| 897 | return new ClientboundPlayerCombatKillPacket(this.getId(), fakeDeathMessage);
|
| 898 | }
|
| 899 | )
|
| 900 | );
|
| 901 | Team team = this.getTeam();
|
| 902 | if (team == null || team.getDeathMessageVisibility() == Team.Visibility.ALWAYS) {
|
| 903 | this.server.getPlayerList().broadcastSystemMessage(deathMessage, false);
|
| 904 | } else if (team.getDeathMessageVisibility() == Team.Visibility.HIDE_FOR_OTHER_TEAMS) {
|
| 905 | this.server.getPlayerList().broadcastSystemToTeam(this, deathMessage);
|
| 906 | } else if (team.getDeathMessageVisibility() == Team.Visibility.HIDE_FOR_OWN_TEAM) {
|
| 907 | this.server.getPlayerList().broadcastSystemToAllExceptTeam(this, deathMessage);
|
| 908 | }
|
| 909 | } else {
|
| 910 | this.connection.send(new ClientboundPlayerCombatKillPacket(this.getId(), CommonComponents.EMPTY));
|
| 911 | }
|
| 912 |
|
| 913 | this.removeEntitiesOnShoulder();
|
| 914 | if (this.level().getGameRules().get(GameRules.FORGIVE_DEAD_PLAYERS)) {
|
| 915 | this.tellNeutralMobsThatIDied();
|
| 916 | }
|
| 917 |
|
| 918 | if (!this.isSpectator()) {
|
| 919 | this.dropAllDeathLoot(this.level(), source);
|
| 920 | }
|
| 921 |
|
| 922 | this.level().getScoreboard().forAllObjectives(ObjectiveCriteria.DEATH_COUNT, this, ScoreAccess::increment);
|
| 923 | LivingEntity killer = this.getKillCredit();
|
| 924 | if (killer != null) {
|
| 925 | this.awardStat(Stats.ENTITY_KILLED_BY.get(killer.getType()));
|
| 926 | killer.awardKillScore(this, source);
|
| 927 | this.createWitherRose(killer);
|
| 928 | }
|
| 929 |
|
| 930 | this.level().broadcastEntityEvent(this, (byte)3);
|
| 931 | this.awardStat(Stats.DEATHS);
|
| 932 | this.resetStat(Stats.CUSTOM.get(Stats.TIME_SINCE_DEATH));
|
| 933 | this.resetStat(Stats.CUSTOM.get(Stats.TIME_SINCE_REST));
|
| 934 | this.clearFire();
|
| 935 | this.setTicksFrozen(0);
|
| 936 | this.setSharedFlagOnFire(false);
|
| 937 | this.getCombatTracker().recheckStatus();
|
| 938 | this.setLastDeathLocation(Optional.of(GlobalPos.of(this.level().dimension(), this.blockPosition())));
|
| 939 | this.connection.markClientUnloadedAfterDeath();
|
| 940 | }
|
| 941 |
|
| 942 | private void tellNeutralMobsThatIDied() {
|
| 943 | AABB aabb = new AABB(this.blockPosition()).inflate(32.0, 10.0, 32.0);
|
| 944 | this.level()
|
| 945 | .getEntitiesOfClass(Mob.class, aabb, EntitySelector.NO_SPECTATORS)
|
| 946 | .stream()
|
| 947 | .filter(mob -> mob instanceof NeutralMob)
|
| 948 | .forEach(mob -> ((NeutralMob)mob).playerDied(this.level(), this));
|
| 949 | }
|
| 950 |
|
| 951 | @Override
|
| 952 | public void awardKillScore(final Entity victim, final DamageSource killingBlow) {
|
| 953 | if (victim != this) {
|
| 954 | super.awardKillScore(victim, killingBlow);
|
| 955 | Scoreboard scoreboard = this.level().getScoreboard();
|
| 956 | scoreboard.forAllObjectives(ObjectiveCriteria.KILL_COUNT_ALL, this, ScoreAccess::increment);
|
| 957 | if (victim instanceof Player) {
|
| 958 | this.awardStat(Stats.PLAYER_KILLS);
|
| 959 | scoreboard.forAllObjectives(ObjectiveCriteria.KILL_COUNT_PLAYERS, this, ScoreAccess::increment);
|
| 960 | } else {
|
| 961 | this.awardStat(Stats.MOB_KILLS);
|
| 962 | }
|
| 963 |
|
| 964 | this.handleTeamKill(this, victim, ObjectiveCriteria.TEAM_KILL);
|
| 965 | this.handleTeamKill(victim, this, ObjectiveCriteria.KILLED_BY_TEAM);
|
| 966 | CriteriaTriggers.PLAYER_KILLED_ENTITY.trigger(this, victim, killingBlow);
|
| 967 | }
|
| 968 | }
|
| 969 |
|
| 970 | private void handleTeamKill(final ScoreHolder source, final ScoreHolder target, final Map<TeamColor, ObjectiveCriteria> criteriaByTeam) {
|
| 971 | Scoreboard scoreboard = this.level().getScoreboard();
|
| 972 | PlayerTeam ownTeam = scoreboard.getPlayersTeam(target.getScoreboardName());
|
| 973 | if (ownTeam != null && ownTeam.getColor().isPresent()) {
|
| 974 | ObjectiveCriteria criteria = criteriaByTeam.get(ownTeam.getColor().get());
|
| 975 | if (criteria != null) {
|
| 976 | scoreboard.forAllObjectives(criteria, source, ScoreAccess::increment);
|
| 977 | }
|
| 978 | }
|
| 979 | }
|
| 980 |
|
| 981 | @Override
|
| 982 | public boolean hurtServer(final ServerLevel level, final DamageSource source, final float damage) {
|
| 983 | if (this.isInvulnerableTo(level, source)) {
|
| 984 | return false;
|
| 985 | } else {
|
| 986 | Entity entity = source.getEntity();
|
| 987 | if (entity instanceof Player player && !this.canHarmPlayer(player)) {
|
| 988 | return false;
|
| 989 | } else {
|
| 990 | return entity instanceof AbstractArrow arrow && arrow.getOwner() instanceof Player player && !this.canHarmPlayer(player)
|
| 991 | ? false
|
| 992 | : super.hurtServer(level, source, damage);
|
| 993 | }
|
| 994 | }
|
| 995 | }
|
| 996 |
|
| 997 | @Override
|
| 998 | public boolean canHarmPlayer(final Player target) {
|
| 999 | return !this.isPvpAllowed() ? false : super.canHarmPlayer(target);
|
| 1000 | }
|
| 1001 |
|
| 1002 | private boolean isPvpAllowed() {
|
| 1003 | return this.level().isPvpAllowed();
|
| 1004 | }
|
| 1005 |
|
| 1006 | public TeleportTransition findRespawnPositionAndUseSpawnBlock(
|
| 1007 | final boolean consumeSpawnBlock, final TeleportTransition.PostTeleportTransition postTeleportTransition
|
| 1008 | ) {
|
| 1009 | ServerPlayer.RespawnConfig respawnConfig = this.getRespawnConfig();
|
| 1010 | ServerLevel respawnLevel = this.server.getLevel(ServerPlayer.RespawnConfig.getDimensionOrDefault(respawnConfig));
|
| 1011 | if (respawnLevel != null && respawnConfig != null) {
|
| 1012 | Optional<ServerPlayer.RespawnPosAngle> respawn = findRespawnAndUseSpawnBlock(respawnLevel, respawnConfig, consumeSpawnBlock);
|
| 1013 | if (respawn.isPresent()) {
|
| 1014 | ServerPlayer.RespawnPosAngle respawnPosAngle = respawn.get();
|
| 1015 | return new TeleportTransition(respawnLevel, respawnPosAngle.position(), Vec3.ZERO, respawnPosAngle.yaw(), respawnPosAngle.pitch(), postTeleportTransition);
|
| 1016 | } else {
|
| 1017 | return TeleportTransition.missingRespawnBlock(this, postTeleportTransition);
|
| 1018 | }
|
| 1019 | } else {
|
| 1020 | return TeleportTransition.createDefault(this, postTeleportTransition);
|
| 1021 | }
|
| 1022 | }
|
| 1023 |
|
| 1024 | public boolean isReceivingWaypoints() {
|
| 1025 | return this.getAttributeValue(Attributes.WAYPOINT_RECEIVE_RANGE) > 0.0;
|
| 1026 | }
|
| 1027 |
|
| 1028 | @Override
|
| 1029 | protected void onAttributeUpdated(final Holder<Attribute> attribute) {
|
| 1030 | if (attribute.is(Attributes.WAYPOINT_RECEIVE_RANGE)) {
|
| 1031 | ServerWaypointManager waypointManager = this.level().getWaypointManager();
|
| 1032 | if (this.getAttributes().getValue(attribute) > 0.0) {
|
| 1033 | waypointManager.addPlayer(this);
|
| 1034 | } else {
|
| 1035 | waypointManager.removePlayer(this);
|
| 1036 | }
|
| 1037 | }
|
| 1038 |
|
| 1039 | super.onAttributeUpdated(attribute);
|
| 1040 | }
|
| 1041 |
|
| 1042 | public void sendPostEffects() {
|
| 1043 | this.postEffectsDirty = false;
|
| 1044 | this.connection.send(new ClientboundPostEffectsPacket(this.postEffects));
|
| 1045 | }
|
| 1046 |
|
| 1047 | public boolean addPostEffect(final Identifier postEffect) {
|
| 1048 | if (this.postEffects.contains(postEffect)) {
|
| 1049 | return false;
|
| 1050 | }
|
| 1051 |
|
| 1052 | this.postEffects.add(postEffect);
|
| 1053 | this.postEffectsDirty = true;
|
| 1054 | return true;
|
| 1055 | }
|
| 1056 |
|
| 1057 | public boolean clearPostEffects() {
|
| 1058 | if (this.postEffects.isEmpty()) {
|
| 1059 | return false;
|
| 1060 | }
|
| 1061 |
|
| 1062 | this.postEffects.clear();
|
| 1063 | this.postEffectsDirty = true;
|
| 1064 | return true;
|
| 1065 | }
|
| 1066 |
|
| 1067 | public List<Identifier> getPostEffects() {
|
| 1068 | return this.postEffects;
|
| 1069 | }
|
| 1070 |
|
| 1071 | public boolean removePostEffect(final Identifier postEffect) {
|
| 1072 | if (this.postEffects.remove(postEffect)) {
|
| 1073 | this.postEffectsDirty = true;
|
| 1074 | return true;
|
| 1075 | } else {
|
| 1076 | return false;
|
| 1077 | }
|
| 1078 | }
|
| 1079 |
|
| 1080 | private static Optional<ServerPlayer.RespawnPosAngle> findRespawnAndUseSpawnBlock(
|
| 1081 | final ServerLevel level, final ServerPlayer.RespawnConfig respawnConfig, final boolean consumeSpawnBlock
|
| 1082 | ) {
|
| 1083 | LevelData.RespawnData respawnData = respawnConfig.respawnData;
|
| 1084 | BlockPos pos = respawnData.pos();
|
| 1085 | float yaw = respawnData.yaw();
|
| 1086 | float pitch = respawnData.pitch();
|
| 1087 | boolean forced = respawnConfig.forced;
|
| 1088 | BlockState blockState = level.getBlockState(pos);
|
| 1089 | Block block = blockState.getBlock();
|
| 1090 | if (block instanceof RespawnAnchorBlock && (forced || blockState.getValue(RespawnAnchorBlock.CHARGE) > 0) && RespawnAnchorBlock.canSetSpawn(level, pos)) {
|
| 1091 | Optional<Vec3> standUpPosition = RespawnAnchorBlock.findStandUpPosition(EntityTypes.PLAYER, level, pos);
|
| 1092 | if (!forced && consumeSpawnBlock && standUpPosition.isPresent()) {
|
| 1093 | level.setBlockAndUpdate(pos, blockState.setValue(RespawnAnchorBlock.CHARGE, blockState.getValue(RespawnAnchorBlock.CHARGE) - 1));
|
| 1094 | }
|
| 1095 |
|
| 1096 | return standUpPosition.map(p -> ServerPlayer.RespawnPosAngle.of(p, pos, 0.0F));
|
| 1097 | } else if (block instanceof AbstractBedBlock abstractBedBlock && abstractBedBlock.getBedRule(level, pos).canSetSpawn(level)) {
|
| 1098 | return AbstractBedBlock.findStandUpPosition(EntityTypes.PLAYER, level, pos, blockState.getValue(AbstractBedBlock.FACING), yaw)
|
| 1099 | .map(p -> ServerPlayer.RespawnPosAngle.of(p, pos, 0.0F));
|
| 1100 | } else {
|
| 1101 | if (!forced) {
|
| 1102 | return Optional.empty();
|
| 1103 | }
|
| 1104 |
|
| 1105 | boolean freeBottom = block.isPossibleToRespawnInThis(blockState);
|
| 1106 | BlockState topState = level.getBlockState(pos.above());
|
| 1107 | boolean freeTop = topState.getBlock().isPossibleToRespawnInThis(topState);
|
| 1108 | return freeBottom && freeTop
|
| 1109 | ? Optional.of(new ServerPlayer.RespawnPosAngle(new Vec3(pos.getX() + 0.5, pos.getY() + 0.1, pos.getZ() + 0.5), yaw, pitch))
|
| 1110 | : Optional.empty();
|
| 1111 | }
|
| 1112 | }
|
| 1113 |
|
| 1114 | public void showEndCredits() {
|
| 1115 | this.unRide();
|
| 1116 | this.level().removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION);
|
| 1117 | if (!this.wonGame) {
|
| 1118 | this.wonGame = true;
|
| 1119 | this.connection.send(new ClientboundGameEventPacket(ClientboundGameEventPacket.WIN_GAME, 0.0F));
|
| 1120 | this.seenCredits = true;
|
| 1121 | }
|
| 1122 | }
|
| 1123 |
|
| 1124 | public @Nullable ServerPlayer teleport(final TeleportTransition transition) {
|
| 1125 | if (this.isRemoved()) {
|
| 1126 | return null;
|
| 1127 | }
|
| 1128 |
|
| 1129 | if (transition.missingRespawnBlock()) {
|
| 1130 | this.connection.send(new ClientboundGameEventPacket(ClientboundGameEventPacket.NO_RESPAWN_BLOCK_AVAILABLE, 0.0F));
|
| 1131 | }
|
| 1132 |
|
| 1133 | ServerLevel newLevel = transition.newLevel();
|
| 1134 | ServerLevel oldLevel = this.level();
|
| 1135 | ResourceKey<Level> lastDimension = oldLevel.dimension();
|
| 1136 | if (!transition.asPassenger()) {
|
| 1137 | this.removeVehicle();
|
| 1138 | }
|
| 1139 |
|
| 1140 | if (newLevel.dimension() == lastDimension) {
|
| 1141 | this.connection.teleport(PositionMoveRotation.of(transition), transition.relatives());
|
| 1142 | this.connection.resetPosition();
|
| 1143 | transition.postTeleportTransition().onTransition(this);
|
| 1144 | return this;
|
| 1145 | }
|
| 1146 |
|
| 1147 | this.isChangingDimension = true;
|
| 1148 | LevelData levelData = newLevel.getLevelData();
|
| 1149 | this.connection.send(new ClientboundRespawnPacket(this.createCommonSpawnInfo(newLevel), (byte)3));
|
| 1150 | this.connection.send(new ClientboundChangeDifficultyPacket(levelData.getDifficulty(), levelData.isDifficultyLocked()));
|
| 1151 | PlayerList playerList = this.server.getPlayerList();
|
| 1152 | playerList.sendPlayerPermissionLevel(this);
|
| 1153 | oldLevel.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION);
|
| 1154 | this.unsetRemoved();
|
| 1155 | ProfilerFiller profiler = Profiler.get();
|
| 1156 | profiler.push("moving");
|
| 1157 | if (lastDimension == Level.OVERWORLD && newLevel.dimension() == Level.NETHER) {
|
| 1158 | this.enteredNetherPosition = this.position();
|
| 1159 | }
|
| 1160 |
|
| 1161 | profiler.pop();
|
| 1162 | profiler.push("placing");
|
| 1163 | this.setServerLevel(newLevel);
|
| 1164 | this.connection.teleport(PositionMoveRotation.of(transition), transition.relatives());
|
| 1165 | this.connection.resetPosition();
|
| 1166 | newLevel.addDuringTeleport(this);
|
| 1167 | profiler.pop();
|
| 1168 | this.triggerDimensionChangeTriggers(oldLevel);
|
| 1169 | this.stopUsingItem();
|
| 1170 | this.connection.send(new ClientboundPlayerAbilitiesPacket(this.getAbilities()));
|
| 1171 | playerList.sendLevelInfo(this, newLevel);
|
| 1172 | playerList.sendAllPlayerInfo(this);
|
| 1173 | playerList.sendActivePlayerEffects(this);
|
| 1174 | this.sendPostEffects();
|
| 1175 | transition.postTeleportTransition().onTransition(this);
|
| 1176 | this.lastSentExp = -1;
|
| 1177 | this.lastSentHealth = -1.0F;
|
| 1178 | this.lastSentFood = -1;
|
| 1179 | this.teleportSpectators(transition, oldLevel);
|
| 1180 | return this;
|
| 1181 | }
|
| 1182 |
|
| 1183 | @Override
|
| 1184 | public void forceSetRotation(final float yRot, final boolean relativeY, final float xRot, final boolean relativeX) {
|
| 1185 | super.forceSetRotation(yRot, relativeY, xRot, relativeX);
|
| 1186 | this.connection.send(new ClientboundPlayerRotationPacket(yRot, relativeY, xRot, relativeX));
|
| 1187 | }
|
| 1188 |
|
| 1189 | private void triggerDimensionChangeTriggers(final ServerLevel oldLevel) {
|
| 1190 | ResourceKey<Level> oldKey = oldLevel.dimension();
|
| 1191 | ResourceKey<Level> newKey = this.level().dimension();
|
| 1192 | CriteriaTriggers.CHANGED_DIMENSION.trigger(this, oldKey, newKey);
|
| 1193 | if (oldKey == Level.NETHER && newKey == Level.OVERWORLD && this.enteredNetherPosition != null) {
|
| 1194 | CriteriaTriggers.NETHER_TRAVEL.trigger(this, this.enteredNetherPosition);
|
| 1195 | }
|
| 1196 |
|
| 1197 | if (newKey != Level.NETHER) {
|
| 1198 | this.enteredNetherPosition = null;
|
| 1199 | }
|
| 1200 | }
|
| 1201 |
|
| 1202 | @Override
|
| 1203 | public boolean broadcastToPlayer(final ServerPlayer player) {
|
| 1204 | if (player.isSpectator()) {
|
| 1205 | return this.getCamera() == this;
|
| 1206 | } else {
|
| 1207 | return this.isSpectator() ? false : super.broadcastToPlayer(player);
|
| 1208 | }
|
| 1209 | }
|
| 1210 |
|
| 1211 | @Override
|
| 1212 | public void take(final Entity entity, final int orgCount) {
|
| 1213 | super.take(entity, orgCount);
|
| 1214 | this.containerMenu.broadcastChanges();
|
| 1215 | }
|
| 1216 |
|
| 1217 | @Override
|
| 1218 | public Either<Player.BedSleepingProblem, Unit> startSleepInBed(
|
| 1219 | final AbstractBedBlock bedBlock, final BlockState bedBlockState, final BedRule rule, final BlockPos pos
|
| 1220 | ) {
|
| 1221 | Direction direction = bedBlockState.getValue(HorizontalDirectionalBlock.FACING);
|
| 1222 | if (!this.isSleeping() && this.isAlive()) {
|
| 1223 | boolean canSleep = rule.canSleep(this.level());
|
| 1224 | boolean canSetSpawn = rule.canSetSpawn(this.level());
|
| 1225 | if (!this.bedInRange(pos, direction)) {
|
| 1226 | return Either.left(Player.BedSleepingProblem.TOO_FAR_AWAY);
|
| 1227 | }
|
| 1228 |
|
| 1229 | if (this.bedBlocked(pos, direction)) {
|
| 1230 | return Either.left(Player.BedSleepingProblem.OBSTRUCTED);
|
| 1231 | }
|
| 1232 |
|
| 1233 | if (canSetSpawn) {
|
| 1234 | this.setRespawnPosition(
|
| 1235 | new ServerPlayer.RespawnConfig(LevelData.RespawnData.of(this.level().dimension(), pos, this.getYRot(), this.getXRot()), false), true
|
| 1236 | );
|
| 1237 | }
|
| 1238 |
|
| 1239 | if (!canSleep) {
|
| 1240 | return Either.left(rule.asProblem());
|
| 1241 | }
|
| 1242 |
|
| 1243 | if (!this.isCreative()) {
|
| 1244 | double hRange = 8.0;
|
| 1245 | double vRange = 5.0;
|
| 1246 | Vec3 bedCenter = Vec3.atBottomCenterOf(pos);
|
| 1247 | List<Monster> monsters = this.level()
|
| 1248 | .getEntitiesOfClass(
|
| 1249 | Monster.class,
|
| 1250 | new AABB(bedCenter.x() - 8.0, bedCenter.y() - 5.0, bedCenter.z() - 8.0, bedCenter.x() + 8.0, bedCenter.y() + 5.0, bedCenter.z() + 8.0),
|
| 1251 | monster -> monster.isPreventingPlayerRest(this.level(), this)
|
| 1252 | );
|
| 1253 | if (!monsters.isEmpty()) {
|
| 1254 | return Either.left(Player.BedSleepingProblem.NOT_SAFE);
|
| 1255 | }
|
| 1256 | }
|
| 1257 |
|
| 1258 | Either<Player.BedSleepingProblem, Unit> result = super.startSleepInBed(bedBlock, bedBlockState, rule, pos).ifRight(unit -> {
|
| 1259 | this.awardStat(bedBlock.getSleptInBedStatType());
|
| 1260 | if (canSetSpawn) {
|
| 1261 | CriteriaTriggers.SLEPT_IN_BED.trigger(this);
|
| 1262 | }
|
| 1263 | });
|
| 1264 | if (!this.level().canSleepThroughNights()) {
|
| 1265 | this.sendOverlayMessage(Component.translatable("sleep.not_possible"));
|
| 1266 | }
|
| 1267 |
|
| 1268 | this.level().updateSleepingPlayerList();
|
| 1269 | return result;
|
| 1270 | } else {
|
| 1271 | return Either.left(Player.BedSleepingProblem.OTHER_PROBLEM);
|
| 1272 | }
|
| 1273 | }
|
| 1274 |
|
| 1275 | @Override
|
| 1276 | public boolean startSleeping(final BlockPos bedPosition) {
|
| 1277 | if (!super.startSleeping(bedPosition)) {
|
| 1278 | return false;
|
| 1279 | }
|
| 1280 |
|
| 1281 | this.resetStat(Stats.CUSTOM.get(Stats.TIME_SINCE_REST));
|
| 1282 | if (this.connection != null) {
|
| 1283 | this.connection.teleport(this.getX(), this.getY(), this.getZ(), this.getYRot(), this.getXRot());
|
| 1284 | }
|
| 1285 |
|
| 1286 | return true;
|
| 1287 | }
|
| 1288 |
|
| 1289 | private boolean bedInRange(final BlockPos pos, final Direction direction) {
|
| 1290 | return this.isReachableBedBlock(pos) || this.isReachableBedBlock(pos.relative(direction.getOpposite()));
|
| 1291 | }
|
| 1292 |
|
| 1293 | private boolean isReachableBedBlock(final BlockPos bedBlockPos) {
|
| 1294 | Vec3 bedBlockCenter = Vec3.atBottomCenterOf(bedBlockPos);
|
| 1295 | return Math.abs(this.getX() - bedBlockCenter.x()) <= 3.0
|
| 1296 | && Math.abs(this.getY() - bedBlockCenter.y()) <= 2.0
|
| 1297 | && Math.abs(this.getZ() - bedBlockCenter.z()) <= 3.0;
|
| 1298 | }
|
| 1299 |
|
| 1300 | private boolean bedBlocked(final BlockPos pos, final Direction direction) {
|
| 1301 | BlockPos above = pos.above();
|
| 1302 | return !this.freeAt(above) || !this.freeAt(above.relative(direction.getOpposite()));
|
| 1303 | }
|
| 1304 |
|
| 1305 | @Override
|
| 1306 | public void stopSleepInBed(final boolean forcefulWakeUp, final boolean updateLevelList) {
|
| 1307 | if (this.isSleeping()) {
|
| 1308 | this.level().getChunkSource().sendToTrackingPlayersAndSelf(this, new ClientboundAnimatePacket(this, 0));
|
| 1309 | }
|
| 1310 |
|
| 1311 | super.stopSleepInBed(forcefulWakeUp, updateLevelList);
|
| 1312 | if (this.connection != null) {
|
| 1313 | this.connection.teleport(this.getX(), this.getY(), this.getZ(), this.getYRot(), this.getXRot());
|
| 1314 | }
|
| 1315 | }
|
| 1316 |
|
| 1317 | @Override
|
| 1318 | public boolean isInvulnerableTo(final ServerLevel level, final DamageSource source) {
|
| 1319 | return super.isInvulnerableTo(level, source) || this.isChangingDimension() && !source.is(DamageTypes.ENDER_PEARL) || !this.connection.hasClientLoaded();
|
| 1320 | }
|
| 1321 |
|
| 1322 | @Override
|
| 1323 | protected void onChangedBlock(final ServerLevel level, final BlockPos pos) {
|
| 1324 | if (!this.isSpectator()) {
|
| 1325 | super.onChangedBlock(level, pos);
|
| 1326 | }
|
| 1327 | }
|
| 1328 |
|
| 1329 | @Override
|
| 1330 | protected void checkFallDamage(final double ya, final boolean onGround, final BlockState onState, final BlockPos pos) {
|
| 1331 | if (this.spawnExtraParticlesOnFall && onGround && this.fallDistance > 0.0) {
|
| 1332 | Vec3 centered = Vec3.atCenterOf(pos).add(0.0, 0.5, 0.0);
|
| 1333 | int particles = (int)Mth.clamp(50.0 * this.fallDistance, 0.0, 200.0);
|
| 1334 | this.level().sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, onState), centered.x, centered.y, centered.z, particles, 0.3F, 0.3F, 0.3F, 0.15F);
|
| 1335 | this.spawnExtraParticlesOnFall = false;
|
| 1336 | }
|
| 1337 |
|
| 1338 | super.checkFallDamage(ya, onGround, onState, pos);
|
| 1339 | }
|
| 1340 |
|
| 1341 | @Override
|
| 1342 | public void onExplosionHit(final @Nullable Entity explosionCausedBy) {
|
| 1343 | super.onExplosionHit(explosionCausedBy);
|
| 1344 | this.currentExplosionImpactPos = this.position();
|
| 1345 | this.currentExplosionCause = explosionCausedBy;
|
| 1346 | this.setIgnoreFallDamageFromCurrentImpulse(explosionCausedBy != null && explosionCausedBy.is(EntityTypes.WIND_CHARGE), this.position());
|
| 1347 | }
|
| 1348 |
|
| 1349 | @Override
|
| 1350 | protected void pushEntities() {
|
| 1351 | if (this.level().tickRateManager().runsNormally()) {
|
| 1352 | super.pushEntities();
|
| 1353 | }
|
| 1354 | }
|
| 1355 |
|
| 1356 | @Override
|
| 1357 | public void openTextEdit(final SignBlockEntity sign, final SignTextSlot slot) {
|
| 1358 | this.connection.send(new ClientboundBlockUpdatePacket(this.level(), sign.getBlockPos()));
|
| 1359 | this.connection.send(new ClientboundOpenSignEditorPacket(sign.getBlockPos(), slot));
|
| 1360 | }
|
| 1361 |
|
| 1362 | @Override
|
| 1363 | public void openDialog(final Holder<Dialog> dialog) {
|
| 1364 | this.connection.send(new ClientboundShowDialogPacket(dialog));
|
| 1365 | }
|
| 1366 |
|
| 1367 | private void nextContainerCounter() {
|
| 1368 | this.containerCounter = this.containerCounter % 100 + 1;
|
| 1369 | }
|
| 1370 |
|
| 1371 | @Override
|
| 1372 | public OptionalInt openMenu(final @Nullable MenuProvider provider) {
|
| 1373 | if (provider == null) {
|
| 1374 | return OptionalInt.empty();
|
| 1375 | }
|
| 1376 |
|
| 1377 | if (this.containerMenu != this.inventoryMenu) {
|
| 1378 | this.closeContainer();
|
| 1379 | }
|
| 1380 |
|
| 1381 | this.nextContainerCounter();
|
| 1382 | AbstractContainerMenu menu = provider.createMenu(this.containerCounter, this.getInventory(), this);
|
| 1383 | if (menu == null) {
|
| 1384 | if (this.isSpectator()) {
|
| 1385 | this.sendOverlayMessage(Component.translatable("container.spectatorCantOpen").withStyle(ChatFormatting.RED));
|
| 1386 | }
|
| 1387 |
|
| 1388 | return OptionalInt.empty();
|
| 1389 | } else {
|
| 1390 | this.connection.send(new ClientboundOpenScreenPacket(menu.containerId, menu.getType(), provider.getDisplayName()));
|
| 1391 | this.initMenu(menu);
|
| 1392 | this.containerMenu = menu;
|
| 1393 | return OptionalInt.of(this.containerCounter);
|
| 1394 | }
|
| 1395 | }
|
| 1396 |
|
| 1397 | @Override
|
| 1398 | public void sendMerchantOffers(
|
| 1399 | final int containerId, final MerchantOffers offers, final int merchantLevel, final int merchantXp, final boolean showProgressBar, final boolean canRestock
|
| 1400 | ) {
|
| 1401 | this.connection.send(new ClientboundMerchantOffersPacket(containerId, offers, merchantLevel, merchantXp, showProgressBar, canRestock));
|
| 1402 | }
|
| 1403 |
|
| 1404 | @Override
|
| 1405 | public void openHorseInventory(final AbstractHorse horse, final Container container) {
|
| 1406 | if (this.containerMenu != this.inventoryMenu) {
|
| 1407 | this.closeContainer();
|
| 1408 | }
|
| 1409 |
|
| 1410 | this.nextContainerCounter();
|
| 1411 | int inventoryColumns = horse.getInventoryColumns();
|
| 1412 | this.connection.send(new ClientboundMountScreenOpenPacket(this.containerCounter, inventoryColumns, horse.getId()));
|
| 1413 | this.containerMenu = new HorseInventoryMenu(this.containerCounter, this.getInventory(), container, horse, inventoryColumns);
|
| 1414 | this.initMenu(this.containerMenu);
|
| 1415 | }
|
| 1416 |
|
| 1417 | @Override
|
| 1418 | public void openNautilusInventory(final AbstractNautilus nautilus, final Container container) {
|
| 1419 | if (this.containerMenu != this.inventoryMenu) {
|
| 1420 | this.closeContainer();
|
| 1421 | }
|
| 1422 |
|
| 1423 | this.nextContainerCounter();
|
| 1424 | int inventoryColumns = nautilus.getInventoryColumns();
|
| 1425 | this.connection.send(new ClientboundMountScreenOpenPacket(this.containerCounter, inventoryColumns, nautilus.getId()));
|
| 1426 | this.containerMenu = new NautilusInventoryMenu(this.containerCounter, this.getInventory(), container, nautilus, inventoryColumns);
|
| 1427 | this.initMenu(this.containerMenu);
|
| 1428 | }
|
| 1429 |
|
| 1430 | @Override
|
| 1431 | public void openItemGui(final ItemStack itemStack, final InteractionHand hand) {
|
| 1432 | if (itemStack.has(DataComponents.WRITTEN_BOOK_CONTENT)) {
|
| 1433 | if (WrittenBookContent.resolveForItem(itemStack, ResolutionContext.create(this.createCommandSourceStack()), this.registryAccess())) {
|
| 1434 | this.containerMenu.broadcastChanges();
|
| 1435 | }
|
| 1436 |
|
| 1437 | this.connection.send(new ClientboundOpenBookPacket(hand));
|
| 1438 | }
|
| 1439 | }
|
| 1440 |
|
| 1441 | @Override
|
| 1442 | public void openCommandBlock(final CommandBlockEntity commandBlock) {
|
| 1443 | this.connection.send(ClientboundBlockEntityDataPacket.create(commandBlock, BlockEntity::saveCustomOnly));
|
| 1444 | }
|
| 1445 |
|
| 1446 | @Override
|
| 1447 | public void closeContainer() {
|
| 1448 | this.connection.send(new ClientboundContainerClosePacket(this.containerMenu.containerId));
|
| 1449 | this.doCloseContainer();
|
| 1450 | }
|
| 1451 |
|
| 1452 | @Override
|
| 1453 | public void doCloseContainer() {
|
| 1454 | this.containerMenu.removed(this);
|
| 1455 | this.inventoryMenu.transferState(this.containerMenu);
|
| 1456 | this.containerMenu = this.inventoryMenu;
|
| 1457 | }
|
| 1458 |
|
| 1459 | @Override
|
| 1460 | public void rideTick() {
|
| 1461 | double preX = this.getX();
|
| 1462 | double preY = this.getY();
|
| 1463 | double preZ = this.getZ();
|
| 1464 | super.rideTick();
|
| 1465 | this.checkRidingStatistics(this.getX() - preX, this.getY() - preY, this.getZ() - preZ);
|
| 1466 | }
|
| 1467 |
|
| 1468 | public void checkMovementStatistics(final double dx, final double dy, final double dz) {
|
| 1469 | if (!this.isPassenger() && !didNotMove(dx, dy, dz)) {
|
| 1470 | if (this.isSwimming()) {
|
| 1471 | int distance = Math.round((float)Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
|
| 1472 | if (distance > 0) {
|
| 1473 | this.awardStat(Stats.SWIM_ONE_CM, distance);
|
| 1474 | this.causeFoodExhaustion(0.01F * distance * 0.01F);
|
| 1475 | }
|
| 1476 | } else if (this.isEyeInFluid(FluidTags.WATER)) {
|
| 1477 | int distance = Math.round((float)Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
|
| 1478 | if (distance > 0) {
|
| 1479 | this.awardStat(Stats.WALK_UNDER_WATER_ONE_CM, distance);
|
| 1480 | this.causeFoodExhaustion(0.01F * distance * 0.01F);
|
| 1481 | }
|
| 1482 | } else if (this.isInWater()) {
|
| 1483 | int horizontalDistance = Math.round((float)Math.sqrt(dx * dx + dz * dz) * 100.0F);
|
| 1484 | if (horizontalDistance > 0) {
|
| 1485 | this.awardStat(Stats.WALK_ON_WATER_ONE_CM, horizontalDistance);
|
| 1486 | this.causeFoodExhaustion(0.01F * horizontalDistance * 0.01F);
|
| 1487 | }
|
| 1488 | } else if (this.onClimbable()) {
|
| 1489 | if (dy > 0.0) {
|
| 1490 | this.awardStat(Stats.CLIMB_ONE_CM, (int)Math.round(dy * 100.0));
|
| 1491 | }
|
| 1492 | } else if (this.onGround()) {
|
| 1493 | int horizontalDistance = Math.round((float)Math.sqrt(dx * dx + dz * dz) * 100.0F);
|
| 1494 | if (horizontalDistance > 0) {
|
| 1495 | if (this.isSprinting()) {
|
| 1496 | this.awardStat(Stats.SPRINT_ONE_CM, horizontalDistance);
|
| 1497 | this.causeFoodExhaustion(0.1F * horizontalDistance * 0.01F);
|
| 1498 | } else if (this.isCrouching()) {
|
| 1499 | this.awardStat(Stats.CROUCH_ONE_CM, horizontalDistance);
|
| 1500 | this.causeFoodExhaustion(0.0F * horizontalDistance * 0.01F);
|
| 1501 | } else {
|
| 1502 | this.awardStat(Stats.WALK_ONE_CM, horizontalDistance);
|
| 1503 | this.causeFoodExhaustion(0.0F * horizontalDistance * 0.01F);
|
| 1504 | }
|
| 1505 | }
|
| 1506 | } else if (this.isFallFlying()) {
|
| 1507 | int distance = Math.round((float)Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
|
| 1508 | this.awardStat(Stats.AVIATE_ONE_CM, distance);
|
| 1509 | } else {
|
| 1510 | int horizontalDistance = Math.round((float)Math.sqrt(dx * dx + dz * dz) * 100.0F);
|
| 1511 | if (horizontalDistance > 25) {
|
| 1512 | this.awardStat(Stats.FLY_ONE_CM, horizontalDistance);
|
| 1513 | }
|
| 1514 | }
|
| 1515 | }
|
| 1516 | }
|
| 1517 |
|
| 1518 | private void checkRidingStatistics(final double dx, final double dy, final double dz) {
|
| 1519 | if (this.isPassenger() && !didNotMove(dx, dy, dz)) {
|
| 1520 | int distance = Math.round((float)Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
|
| 1521 | Entity vehicle = this.getVehicle();
|
| 1522 | if (vehicle instanceof AbstractMinecart) {
|
| 1523 | this.awardStat(Stats.MINECART_ONE_CM, distance);
|
| 1524 | } else if (vehicle instanceof AbstractBoat) {
|
| 1525 | this.awardStat(Stats.BOAT_ONE_CM, distance);
|
| 1526 | } else if (vehicle instanceof Pig) {
|
| 1527 | this.awardStat(Stats.PIG_ONE_CM, distance);
|
| 1528 | } else if (vehicle instanceof AbstractHorse) {
|
| 1529 | this.awardStat(Stats.HORSE_ONE_CM, distance);
|
| 1530 | } else if (vehicle instanceof Strider) {
|
| 1531 | this.awardStat(Stats.STRIDER_ONE_CM, distance);
|
| 1532 | } else if (vehicle instanceof HappyGhast) {
|
| 1533 | this.awardStat(Stats.HAPPY_GHAST_ONE_CM, distance);
|
| 1534 | } else if (vehicle instanceof AbstractNautilus) {
|
| 1535 | this.awardStat(Stats.NAUTILUS_ONE_CM, distance);
|
| 1536 | }
|
| 1537 | }
|
| 1538 | }
|
| 1539 |
|
| 1540 | private static boolean didNotMove(final double dx, final double dy, final double dz) {
|
| 1541 | return dx == 0.0 && dy == 0.0 && dz == 0.0;
|
| 1542 | }
|
| 1543 |
|
| 1544 | @Override
|
| 1545 | public void awardStat(final Stat<?> stat, final int count) {
|
| 1546 | this.stats.increment(this, stat, count);
|
| 1547 | this.level().getScoreboard().forAllObjectives(stat, this, score -> score.add(count));
|
| 1548 | }
|
| 1549 |
|
| 1550 | @Override
|
| 1551 | public void resetStat(final Stat<?> stat) {
|
| 1552 | this.stats.setValue(this, stat, 0);
|
| 1553 | this.level().getScoreboard().forAllObjectives(stat, this, ScoreAccess::reset);
|
| 1554 | }
|
| 1555 |
|
| 1556 | @Override
|
| 1557 | public int awardRecipes(final Collection<RecipeHolder<?>> recipes) {
|
| 1558 | return this.recipeBook.addRecipes(recipes, this);
|
| 1559 | }
|
| 1560 |
|
| 1561 | @Override
|
| 1562 | public void triggerRecipeCrafted(final RecipeHolder<?> recipe, final List<ItemStack> itemStacks) {
|
| 1563 | CriteriaTriggers.RECIPE_CRAFTED.trigger(this, recipe.id(), itemStacks);
|
| 1564 | }
|
| 1565 |
|
| 1566 | public void awardRecipesByKey(final List<ResourceKey<Recipe<?>>> recipeIds) {
|
| 1567 | List<RecipeHolder<?>> recipes = recipeIds.stream()
|
| 1568 | .flatMap(id -> this.server.getRecipeManager().byKey((ResourceKey<Recipe<?>>)id).stream())
|
| 1569 | .collect(Collectors.toList());
|
| 1570 | this.awardRecipes(recipes);
|
| 1571 | }
|
| 1572 |
|
| 1573 | public int resetRecipes(final Collection<RecipeHolder<?>> recipe) {
|
| 1574 | return this.recipeBook.removeRecipes(recipe, this);
|
| 1575 | }
|
| 1576 |
|
| 1577 | @Override
|
| 1578 | public void jumpFromGround() {
|
| 1579 | super.jumpFromGround();
|
| 1580 | this.awardStat(Stats.JUMP);
|
| 1581 | if (this.isSprinting()) {
|
| 1582 | this.causeFoodExhaustion(0.2F);
|
| 1583 | } else {
|
| 1584 | this.causeFoodExhaustion(0.05F);
|
| 1585 | }
|
| 1586 | }
|
| 1587 |
|
| 1588 | @Override
|
| 1589 | public void giveExperiencePoints(final int i) {
|
| 1590 | if (i != 0) {
|
| 1591 | super.giveExperiencePoints(i);
|
| 1592 | this.lastSentExp = -1;
|
| 1593 | }
|
| 1594 | }
|
| 1595 |
|
| 1596 | public void disconnect() {
|
| 1597 | this.disconnected = true;
|
| 1598 | this.ejectPassengers();
|
| 1599 | if (this.isSleeping()) {
|
| 1600 | this.stopSleepInBed(true, false);
|
| 1601 | }
|
| 1602 | }
|
| 1603 |
|
| 1604 | public boolean hasDisconnected() {
|
| 1605 | return this.disconnected;
|
| 1606 | }
|
| 1607 |
|
| 1608 | public void resetSentInfo() {
|
| 1609 | this.lastSentHealth = -1.0E8F;
|
| 1610 | }
|
| 1611 |
|
| 1612 | @Override
|
| 1613 | protected void completeUsingItem() {
|
| 1614 | if (!this.useItem.isEmpty() && this.isUsingItem()) {
|
| 1615 | this.connection.send(new ClientboundEntityEventPacket(this, (byte)9));
|
| 1616 | super.completeUsingItem();
|
| 1617 | }
|
| 1618 | }
|
| 1619 |
|
| 1620 | @Override
|
| 1621 | public void lookAt(final EntityAnchorArgument.Anchor anchor, final Vec3 pos) {
|
| 1622 | super.lookAt(anchor, pos);
|
| 1623 | this.connection.send(new ClientboundPlayerLookAtPacket(anchor, pos.x, pos.y, pos.z));
|
| 1624 | }
|
| 1625 |
|
| 1626 | public void lookAt(final EntityAnchorArgument.Anchor fromAnchor, final Entity entity, final EntityAnchorArgument.Anchor toAnchor) {
|
| 1627 | Vec3 pos = toAnchor.apply(entity);
|
| 1628 | super.lookAt(fromAnchor, pos);
|
| 1629 | this.connection.send(new ClientboundPlayerLookAtPacket(fromAnchor, entity, toAnchor));
|
| 1630 | }
|
| 1631 |
|
| 1632 | public void restoreFrom(final ServerPlayer oldPlayer, final boolean restoreAll) {
|
| 1633 | this.wardenSpawnTracker = oldPlayer.wardenSpawnTracker;
|
| 1634 | this.chatSession = oldPlayer.chatSession;
|
| 1635 | this.gameMode.setGameModeForPlayer(oldPlayer.gameMode.getGameModeForPlayer(), oldPlayer.gameMode.getPreviousGameModeForPlayer());
|
| 1636 | this.onUpdateAbilities();
|
| 1637 | this.getAttributes().assignBaseValues(oldPlayer.getAttributes());
|
| 1638 | if (restoreAll) {
|
| 1639 | this.getAttributes().assignPermanentModifiers(oldPlayer.getAttributes());
|
| 1640 | this.setHealth(oldPlayer.getHealth());
|
| 1641 | this.foodData = oldPlayer.foodData;
|
| 1642 |
|
| 1643 | for (MobEffectInstance effect : oldPlayer.getActiveEffects()) {
|
| 1644 | this.addEffect(new MobEffectInstance(effect));
|
| 1645 | }
|
| 1646 |
|
| 1647 | this.transferInventoryXpAndScore(oldPlayer);
|
| 1648 | this.portalProcess = oldPlayer.portalProcess;
|
| 1649 | } else {
|
| 1650 | this.setHealth(this.getMaxHealth());
|
| 1651 | if (this.level().getGameRules().get(GameRules.KEEP_INVENTORY) || oldPlayer.isSpectator()) {
|
| 1652 | this.transferInventoryXpAndScore(oldPlayer);
|
| 1653 | }
|
| 1654 | }
|
| 1655 |
|
| 1656 | this.enchantmentSeed = oldPlayer.enchantmentSeed;
|
| 1657 | this.enderChestInventory = oldPlayer.enderChestInventory;
|
| 1658 | this.getEntityData().set(DATA_PLAYER_MODE_CUSTOMISATION, oldPlayer.getEntityData().get(DATA_PLAYER_MODE_CUSTOMISATION));
|
| 1659 | this.lastSentExp = -1;
|
| 1660 | this.lastSentHealth = -1.0F;
|
| 1661 | this.lastSentFood = -1;
|
| 1662 | this.recipeBook.copyOverData(oldPlayer.recipeBook);
|
| 1663 | this.seenCredits = oldPlayer.seenCredits;
|
| 1664 | this.enteredNetherPosition = oldPlayer.enteredNetherPosition;
|
| 1665 | this.currentExplosionImpactPos = oldPlayer.currentExplosionImpactPos;
|
| 1666 | this.currentExplosionCause = oldPlayer.currentExplosionCause;
|
| 1667 | this.chunkTrackingView = oldPlayer.chunkTrackingView;
|
| 1668 | this.requestedDebugSubscriptions = oldPlayer.requestedDebugSubscriptions;
|
| 1669 | this.setShoulderEntityLeft(oldPlayer.getShoulderEntityLeft());
|
| 1670 | this.setShoulderEntityRight(oldPlayer.getShoulderEntityRight());
|
| 1671 | this.setLastDeathLocation(oldPlayer.getLastDeathLocation());
|
| 1672 | this.waypointIcon().copyFrom(oldPlayer.waypointIcon());
|
| 1673 | }
|
| 1674 |
|
| 1675 | private void transferInventoryXpAndScore(final Player oldPlayer) {
|
| 1676 | this.getInventory().replaceWith(oldPlayer.getInventory());
|
| 1677 | this.experienceLevel = oldPlayer.experienceLevel;
|
| 1678 | this.totalExperience = oldPlayer.totalExperience;
|
| 1679 | this.experienceProgress = oldPlayer.experienceProgress;
|
| 1680 | this.setScore(oldPlayer.getScore());
|
| 1681 | }
|
| 1682 |
|
| 1683 | @Override
|
| 1684 | protected void onEffectAdded(final MobEffectInstance effect, final @Nullable Entity source) {
|
| 1685 | super.onEffectAdded(effect, source);
|
| 1686 | this.connection.send(new ClientboundUpdateMobEffectPacket(this.getId(), effect, true));
|
| 1687 | if (effect.is(MobEffects.LEVITATION)) {
|
| 1688 | this.levitationStartTime = this.tickCount;
|
| 1689 | this.levitationStartPos = this.position();
|
| 1690 | }
|
| 1691 |
|
| 1692 | CriteriaTriggers.EFFECTS_CHANGED.trigger(this, source);
|
| 1693 | }
|
| 1694 |
|
| 1695 | @Override
|
| 1696 | protected void onEffectUpdated(final MobEffectInstance effect, final boolean doRefreshAttributes, final @Nullable Entity source) {
|
| 1697 | super.onEffectUpdated(effect, doRefreshAttributes, source);
|
| 1698 | this.connection.send(new ClientboundUpdateMobEffectPacket(this.getId(), effect, false));
|
| 1699 | CriteriaTriggers.EFFECTS_CHANGED.trigger(this, source);
|
| 1700 | }
|
| 1701 |
|
| 1702 | @Override
|
| 1703 | protected void onEffectsRemoved(final Collection<MobEffectInstance> effects) {
|
| 1704 | super.onEffectsRemoved(effects);
|
| 1705 |
|
| 1706 | for (MobEffectInstance effect : effects) {
|
| 1707 | this.connection.send(new ClientboundRemoveMobEffectPacket(this.getId(), effect.getEffect()));
|
| 1708 | if (effect.is(MobEffects.LEVITATION)) {
|
| 1709 | this.levitationStartPos = null;
|
| 1710 | }
|
| 1711 | }
|
| 1712 |
|
| 1713 | CriteriaTriggers.EFFECTS_CHANGED.trigger(this, null);
|
| 1714 | }
|
| 1715 |
|
| 1716 | @Override
|
| 1717 | public void teleportTo(final double x, final double y, final double z) {
|
| 1718 | this.connection.teleport(new PositionMoveRotation(new Vec3(x, y, z), Vec3.ZERO, 0.0F, 0.0F), Relative.union(Relative.DELTA, Relative.ROTATION));
|
| 1719 | }
|
| 1720 |
|
| 1721 | @Override
|
| 1722 | public void teleportRelative(final double dx, final double dy, final double dz) {
|
| 1723 | this.connection.teleport(new PositionMoveRotation(new Vec3(dx, dy, dz), Vec3.ZERO, 0.0F, 0.0F), Relative.ALL);
|
| 1724 | }
|
| 1725 |
|
| 1726 | @Override
|
| 1727 | public boolean teleportTo(
|
| 1728 | final ServerLevel level,
|
| 1729 | final double x,
|
| 1730 | final double y,
|
| 1731 | final double z,
|
| 1732 | final Set<Relative> relatives,
|
| 1733 | final float newYRot,
|
| 1734 | final float newXRot,
|
| 1735 | final boolean resetCamera
|
| 1736 | ) {
|
| 1737 | if (this.isSleeping()) {
|
| 1738 | this.stopSleepInBed(true, true);
|
| 1739 | }
|
| 1740 |
|
| 1741 | if (resetCamera) {
|
| 1742 | this.setCamera(this);
|
| 1743 | }
|
| 1744 |
|
| 1745 | boolean success = super.teleportTo(level, x, y, z, relatives, newYRot, newXRot, resetCamera);
|
| 1746 | if (success) {
|
| 1747 | this.setYHeadRot(relatives.contains(Relative.Y_ROT) ? this.getYHeadRot() + newYRot : newYRot);
|
| 1748 | this.connection.resetFlyingTicks();
|
| 1749 | }
|
| 1750 |
|
| 1751 | return success;
|
| 1752 | }
|
| 1753 |
|
| 1754 | @Override
|
| 1755 | public void snapTo(final double x, final double y, final double z) {
|
| 1756 | super.snapTo(x, y, z);
|
| 1757 | this.connection.resetPosition();
|
| 1758 | }
|
| 1759 |
|
| 1760 | @Override
|
| 1761 | public void crit(final Entity entity) {
|
| 1762 | this.level().getChunkSource().sendToTrackingPlayersAndSelf(this, new ClientboundAnimatePacket(entity, 1));
|
| 1763 | }
|
| 1764 |
|
| 1765 | @Override
|
| 1766 | public void magicCrit(final Entity entity) {
|
| 1767 | this.level().getChunkSource().sendToTrackingPlayersAndSelf(this, new ClientboundAnimatePacket(entity, 2));
|
| 1768 | }
|
| 1769 |
|
| 1770 | @Override
|
| 1771 | public void onUpdateAbilities() {
|
| 1772 | if (this.connection != null) {
|
| 1773 | this.connection.send(new ClientboundPlayerAbilitiesPacket(this.getAbilities()));
|
| 1774 | this.updateInvisibilityStatus();
|
| 1775 | }
|
| 1776 | }
|
| 1777 |
|
| 1778 | public ServerLevel level() {
|
| 1779 | return (ServerLevel)super.level();
|
| 1780 | }
|
| 1781 |
|
| 1782 | public boolean setGameMode(final GameType mode) {
|
| 1783 | boolean wasSpectator = this.isSpectator();
|
| 1784 | if (!this.gameMode.changeGameModeForPlayer(mode)) {
|
| 1785 | return false;
|
| 1786 | }
|
| 1787 |
|
| 1788 | this.connection.send(new ClientboundGameEventPacket(ClientboundGameEventPacket.CHANGE_GAME_MODE, mode.getId()));
|
| 1789 | if (mode == GameType.SPECTATOR) {
|
| 1790 | this.removeEntitiesOnShoulder();
|
| 1791 | this.stopRiding();
|
| 1792 | this.stopUsingItem();
|
| 1793 | EnchantmentHelper.stopLocationBasedEffects(this);
|
| 1794 | } else {
|
| 1795 | this.setCamera(this);
|
| 1796 | if (wasSpectator) {
|
| 1797 | EnchantmentHelper.runLocationChangedEffects(this.level(), this);
|
| 1798 | }
|
| 1799 | }
|
| 1800 |
|
| 1801 | this.onUpdateAbilities();
|
| 1802 | this.updateEffectVisibility();
|
| 1803 | return true;
|
| 1804 | }
|
| 1805 |
|
| 1806 | @Override
|
| 1807 | public GameType gameMode() {
|
| 1808 | return this.gameMode.getGameModeForPlayer();
|
| 1809 | }
|
| 1810 |
|
| 1811 | public CommandSource commandSource() {
|
| 1812 | return this.commandSource;
|
| 1813 | }
|
| 1814 |
|
| 1815 | public CommandSourceStack createCommandSourceStack() {
|
| 1816 | return new CommandSourceStack(this.commandSource(), this.position(), this.getRotationVector(), this.level(), this.permissions(), this.server, this);
|
| 1817 | }
|
| 1818 |
|
| 1819 | @Override
|
| 1820 | public void sendSystemMessage(final Component message) {
|
| 1821 | this.sendSystemMessage(message, false);
|
| 1822 | }
|
| 1823 |
|
| 1824 | @Override
|
| 1825 | public void sendOverlayMessage(final Component message) {
|
| 1826 | this.sendSystemMessage(message, true);
|
| 1827 | }
|
| 1828 |
|
| 1829 | public void sendBuildLimitMessage(final boolean isTooHigh, final int limit) {
|
| 1830 | this.sendOverlayMessage(Component.translatable(isTooHigh ? "build.tooHigh" : "build.tooLow", limit).withStyle(ChatFormatting.RED));
|
| 1831 | }
|
| 1832 |
|
| 1833 | public void sendSpawnProtectionMessage(final BlockPos pos) {
|
| 1834 | this.sendOverlayMessage(Component.translatable("build.spawn_protection", pos.toShortString()).withStyle(ChatFormatting.RED));
|
| 1835 | }
|
| 1836 |
|
| 1837 | public void sendSystemMessage(final Component message, final boolean overlay) {
|
| 1838 | if (this.acceptsSystemMessages(overlay)) {
|
| 1839 | this.connection.send(new ClientboundSystemChatPacket(message, overlay), PacketSendListener.exceptionallySend(() -> {
|
| 1840 | if (this.acceptsSystemMessages(false)) {
|
| 1841 | int truncatedMessageSize = 256;
|
| 1842 | String contents = message.getString(256);
|
| 1843 | Component contentsMsg = Component.literal(contents).withStyle(ChatFormatting.YELLOW);
|
| 1844 | return new ClientboundSystemChatPacket(Component.translatable("multiplayer.message_not_delivered", contentsMsg).withStyle(ChatFormatting.RED), false);
|
| 1845 | } else {
|
| 1846 | return null;
|
| 1847 | }
|
| 1848 | }));
|
| 1849 | }
|
| 1850 | }
|
| 1851 |
|
| 1852 | public void sendChatMessage(final OutgoingChatMessage message, final boolean filtered, final ChatType.Bound chatType) {
|
| 1853 | if (this.acceptsChatMessages()) {
|
| 1854 | message.sendToPlayer(this, filtered, chatType);
|
| 1855 | }
|
| 1856 | }
|
| 1857 |
|
| 1858 | public String getIpAddress() {
|
| 1859 | return this.connection.getRemoteAddress() instanceof InetSocketAddress ipSocketAddress
|
| 1860 | ? InetAddresses.toAddrString(ipSocketAddress.getAddress())
|
| 1861 | : "<unknown>";
|
| 1862 | }
|
| 1863 |
|
| 1864 | public void updateOptions(final ClientInformation information) {
|
| 1865 | this.language = information.language();
|
| 1866 | this.requestedViewDistance = information.viewDistance();
|
| 1867 | this.chatVisibility = information.chatVisibility();
|
| 1868 | this.canChatColor = information.chatColors();
|
| 1869 | this.textFilteringEnabled = information.textFilteringEnabled();
|
| 1870 | this.allowsListing = information.allowsListing();
|
| 1871 | this.particleStatus = information.particleStatus();
|
| 1872 | this.getEntityData().set(DATA_PLAYER_MODE_CUSTOMISATION, (byte)information.modelCustomisation());
|
| 1873 | this.getEntityData().set(DATA_PLAYER_MAIN_HAND, information.mainHand());
|
| 1874 | }
|
| 1875 |
|
| 1876 | public ClientInformation clientInformation() {
|
| 1877 | int modelCustomization = this.getEntityData().get(DATA_PLAYER_MODE_CUSTOMISATION);
|
| 1878 | return new ClientInformation(
|
| 1879 | this.language,
|
| 1880 | this.requestedViewDistance,
|
| 1881 | this.chatVisibility,
|
| 1882 | this.canChatColor,
|
| 1883 | modelCustomization,
|
| 1884 | this.getMainArm(),
|
| 1885 | this.textFilteringEnabled,
|
| 1886 | this.allowsListing,
|
| 1887 | this.particleStatus
|
| 1888 | );
|
| 1889 | }
|
| 1890 |
|
| 1891 | public boolean canChatInColor() {
|
| 1892 | return this.canChatColor;
|
| 1893 | }
|
| 1894 |
|
| 1895 | public ChatVisiblity getChatVisibility() {
|
| 1896 | return this.chatVisibility;
|
| 1897 | }
|
| 1898 |
|
| 1899 | private boolean acceptsSystemMessages(final boolean overlay) {
|
| 1900 | return this.chatVisibility == ChatVisiblity.HIDDEN ? overlay : true;
|
| 1901 | }
|
| 1902 |
|
| 1903 | private boolean acceptsChatMessages() {
|
| 1904 | return this.chatVisibility == ChatVisiblity.FULL;
|
| 1905 | }
|
| 1906 |
|
| 1907 | public int requestedViewDistance() {
|
| 1908 | return this.requestedViewDistance;
|
| 1909 | }
|
| 1910 |
|
| 1911 | public void sendServerStatus(final ServerStatus status) {
|
| 1912 | this.connection.send(new ClientboundServerDataPacket(status.description(), status.favicon().map(ServerStatus.Favicon::iconBytes)));
|
| 1913 | }
|
| 1914 |
|
| 1915 | @Override
|
| 1916 | public PermissionSet permissions() {
|
| 1917 | return this.server.getProfilePermissions(this.nameAndId());
|
| 1918 | }
|
| 1919 |
|
| 1920 | public void resetLastActionTime() {
|
| 1921 | this.lastActionTime = Util.getMillis();
|
| 1922 | }
|
| 1923 |
|
| 1924 | public ServerStatsCounter getStats() {
|
| 1925 | return this.stats;
|
| 1926 | }
|
| 1927 |
|
| 1928 | public ServerRecipeBook getRecipeBook() {
|
| 1929 | return this.recipeBook;
|
| 1930 | }
|
| 1931 |
|
| 1932 | @Override
|
| 1933 | protected void updateInvisibilityStatus() {
|
| 1934 | if (this.isSpectator()) {
|
| 1935 | this.removeEffectParticles();
|
| 1936 | this.setInvisible(true);
|
| 1937 | } else {
|
| 1938 | super.updateInvisibilityStatus();
|
| 1939 | }
|
| 1940 | }
|
| 1941 |
|
| 1942 | public Entity getCamera() {
|
| 1943 | return this.camera == null ? this : this.camera;
|
| 1944 | }
|
| 1945 |
|
| 1946 | public void setCamera(final @Nullable Entity newCamera) {
|
| 1947 | Entity oldCamera = this.getCamera();
|
| 1948 | this.camera = newCamera == null ? this : newCamera;
|
| 1949 | if (oldCamera != this.camera) {
|
| 1950 | if (this.camera.level() instanceof ServerLevel level) {
|
| 1951 | this.teleportTo(level, this.camera.getX(), this.camera.getY(), this.camera.getZ(), Set.of(), this.getYRot(), this.getXRot(), false);
|
| 1952 | }
|
| 1953 |
|
| 1954 | if (newCamera != null) {
|
| 1955 | this.level().getChunkSource().move(this);
|
| 1956 | }
|
| 1957 |
|
| 1958 | this.connection.send(new ClientboundSetCameraPacket(this.camera));
|
| 1959 | this.connection.resetPosition();
|
| 1960 | }
|
| 1961 | }
|
| 1962 |
|
| 1963 | @Override
|
| 1964 | protected void processPortalCooldown() {
|
| 1965 | if (!this.isChangingDimension) {
|
| 1966 | super.processPortalCooldown();
|
| 1967 | }
|
| 1968 | }
|
| 1969 |
|
| 1970 | public long getLastActionTime() {
|
| 1971 | return this.lastActionTime;
|
| 1972 | }
|
| 1973 |
|
| 1974 | public @Nullable Component getTabListDisplayName() {
|
| 1975 | return null;
|
| 1976 | }
|
| 1977 |
|
| 1978 | public int getTabListOrder() {
|
| 1979 | return 0;
|
| 1980 | }
|
| 1981 |
|
| 1982 | public boolean isChangingDimension() {
|
| 1983 | return this.isChangingDimension;
|
| 1984 | }
|
| 1985 |
|
| 1986 | public void hasChangedDimension() {
|
| 1987 | this.isChangingDimension = false;
|
| 1988 | }
|
| 1989 |
|
| 1990 | public PlayerAdvancements getAdvancements() {
|
| 1991 | return this.advancements;
|
| 1992 | }
|
| 1993 |
|
| 1994 | public ServerPlayer.@Nullable RespawnConfig getRespawnConfig() {
|
| 1995 | return this.respawnConfig;
|
| 1996 | }
|
| 1997 |
|
| 1998 | public void copyRespawnPosition(final ServerPlayer player) {
|
| 1999 | this.setRespawnPosition(player.respawnConfig, false);
|
| 2000 | }
|
| 2001 |
|
| 2002 | public void setRespawnPosition(final ServerPlayer.@Nullable RespawnConfig respawnConfig, final boolean showMessage) {
|
| 2003 | if (showMessage && respawnConfig != null && !respawnConfig.isSamePosition(this.respawnConfig)) {
|
| 2004 | this.sendSystemMessage(SPAWN_SET_MESSAGE);
|
| 2005 | }
|
| 2006 |
|
| 2007 | this.respawnConfig = respawnConfig;
|
| 2008 | }
|
| 2009 |
|
| 2010 | public SectionPos getLastSectionPos() {
|
| 2011 | return this.lastSectionPos;
|
| 2012 | }
|
| 2013 |
|
| 2014 | public void setLastSectionPos(final SectionPos lastSectionPos) {
|
| 2015 | this.lastSectionPos = lastSectionPos;
|
| 2016 | }
|
| 2017 |
|
| 2018 | public ChunkTrackingView getChunkTrackingView() {
|
| 2019 | return this.chunkTrackingView;
|
| 2020 | }
|
| 2021 |
|
| 2022 | public void setChunkTrackingView(final ChunkTrackingView chunkTrackingView) {
|
| 2023 | this.chunkTrackingView = chunkTrackingView;
|
| 2024 | }
|
| 2025 |
|
| 2026 | @Override
|
| 2027 | public @Nullable ItemEntity drop(final ItemStack itemStack, final boolean thrownFromHand, final Prediction prediction) {
|
| 2028 | ItemEntity entity = super.drop(itemStack, thrownFromHand, prediction);
|
| 2029 | if (thrownFromHand) {
|
| 2030 | ItemStack droppedItemStack = entity != null ? entity.getItem() : ItemStack.EMPTY;
|
| 2031 | if (!droppedItemStack.isEmpty()) {
|
| 2032 | this.awardStat(Stats.ITEM_DROPPED.get(droppedItemStack.getItem()), itemStack.getCount());
|
| 2033 | this.awardStat(Stats.DROP);
|
| 2034 | }
|
| 2035 | }
|
| 2036 |
|
| 2037 | return entity;
|
| 2038 | }
|
| 2039 |
|
| 2040 | public TextFilter getTextFilter() {
|
| 2041 | return this.textFilter;
|
| 2042 | }
|
| 2043 |
|
| 2044 | public void setServerLevel(final ServerLevel level) {
|
| 2045 | this.setLevel(level);
|
| 2046 | this.gameMode.setLevel(level);
|
| 2047 | }
|
| 2048 |
|
| 2049 | private static @Nullable GameType readPlayerMode(final ValueInput playerInput, final String modeTag) {
|
| 2050 | return playerInput.read(modeTag, GameType.LEGACY_ID_CODEC).orElse(null);
|
| 2051 | }
|
| 2052 |
|
| 2053 | private GameType calculateGameModeForNewPlayer(final @Nullable GameType loadedGameType) {
|
| 2054 | GameType forcedGameType = this.server.getForcedGameType();
|
| 2055 | if (forcedGameType == null
|
| 2056 | || !(this.server instanceof DedicatedServer) && this.server.getProfilePermissions(this.nameAndId()).hasPermission(Permissions.COMMANDS_GAMEMASTER)) {
|
| 2057 | return loadedGameType != null ? loadedGameType : this.server.getDefaultGameType();
|
| 2058 | } else {
|
| 2059 | return forcedGameType;
|
| 2060 | }
|
| 2061 | }
|
| 2062 |
|
| 2063 | private void storeGameTypes(final ValueOutput playerOutput) {
|
| 2064 | playerOutput.store("playerGameType", GameType.LEGACY_ID_CODEC, this.gameMode.getGameModeForPlayer());
|
| 2065 | GameType previousGameMode = this.gameMode.getPreviousGameModeForPlayer();
|
| 2066 | playerOutput.storeNullable("previousPlayerGameType", GameType.LEGACY_ID_CODEC, previousGameMode);
|
| 2067 | }
|
| 2068 |
|
| 2069 | @Override
|
| 2070 | public boolean isTextFilteringEnabled() {
|
| 2071 | return this.textFilteringEnabled;
|
| 2072 | }
|
| 2073 |
|
| 2074 | public boolean shouldFilterMessageTo(final ServerPlayer serverPlayer) {
|
| 2075 | return serverPlayer == this ? false : this.textFilteringEnabled || serverPlayer.textFilteringEnabled;
|
| 2076 | }
|
| 2077 |
|
| 2078 | @Override
|
| 2079 | public boolean mayInteract(final ServerLevel level, final BlockPos pos) {
|
| 2080 | return super.mayInteract(level, pos) && level.mayInteract(this, pos);
|
| 2081 | }
|
| 2082 |
|
| 2083 | @Override
|
| 2084 | protected void updateUsingItem(final ItemStack useItem) {
|
| 2085 | CriteriaTriggers.USING_ITEM.trigger(this, useItem);
|
| 2086 | super.updateUsingItem(useItem);
|
| 2087 | }
|
| 2088 |
|
| 2089 | public void drop(final boolean all) {
|
| 2090 | Inventory inventory = this.getInventory();
|
| 2091 | ItemStack removed = inventory.removeFromSelected(all);
|
| 2092 | this.containerMenu
|
| 2093 | .findSlot(inventory, inventory.getSelectedSlot())
|
| 2094 | .ifPresent(slotIndex -> this.containerMenu.setRemoteSlot(slotIndex, inventory.getSelectedItem()));
|
| 2095 | if (this.useItem.isEmpty()) {
|
| 2096 | this.stopUsingItem();
|
| 2097 | }
|
| 2098 |
|
| 2099 | this.drop(removed, true, Prediction.PREDICTED);
|
| 2100 | this.resetAttackStrengthTicker();
|
| 2101 | }
|
| 2102 |
|
| 2103 | @Override
|
| 2104 | public void handleExtraItemsCreatedOnUse(final ItemStack extraItems) {
|
| 2105 | if (!this.getInventory().add(extraItems)) {
|
| 2106 | this.drop(extraItems, false, Prediction.PREDICTED);
|
| 2107 | }
|
| 2108 | }
|
| 2109 |
|
| 2110 | public boolean allowsListing() {
|
| 2111 | return this.allowsListing;
|
| 2112 | }
|
| 2113 |
|
| 2114 | public WardenSpawnTracker getWardenSpawnTracker() {
|
| 2115 | return this.wardenSpawnTracker;
|
| 2116 | }
|
| 2117 |
|
| 2118 | public void setSpawnExtraParticlesOnFall(final boolean toggle) {
|
| 2119 | this.spawnExtraParticlesOnFall = toggle;
|
| 2120 | }
|
| 2121 |
|
| 2122 | @Override
|
| 2123 | public void onItemPickup(final ItemEntity entity) {
|
| 2124 | super.onItemPickup(entity);
|
| 2125 | Entity thrower = entity.getOwner();
|
| 2126 | if (thrower != null) {
|
| 2127 | CriteriaTriggers.THROWN_ITEM_PICKED_UP_BY_PLAYER.trigger(this, entity.getItem(), thrower);
|
| 2128 | }
|
| 2129 | }
|
| 2130 |
|
| 2131 | public void setChatSession(final RemoteChatSession chatSession) {
|
| 2132 | this.chatSession = chatSession;
|
| 2133 | }
|
| 2134 |
|
| 2135 | public @Nullable RemoteChatSession getChatSession() {
|
| 2136 | return this.chatSession != null && this.chatSession.hasExpired() ? null : this.chatSession;
|
| 2137 | }
|
| 2138 |
|
| 2139 | @Override
|
| 2140 | public void indicateDamage(final double xd, final double zd) {
|
| 2141 | this.hurtDir = (float)(Mth.atan2(zd, xd) * 180.0F / (float)Math.PI - this.getYRot());
|
| 2142 | this.connection.send(new ClientboundHurtAnimationPacket(this));
|
| 2143 | }
|
| 2144 |
|
| 2145 | @Override
|
| 2146 | public boolean startRiding(final Entity entityToRide, final boolean force, final boolean sendEventAndTriggers) {
|
| 2147 | if (super.startRiding(entityToRide, force, sendEventAndTriggers)) {
|
| 2148 | entityToRide.positionRider(this);
|
| 2149 | this.connection.teleport(new PositionMoveRotation(this.position(), Vec3.ZERO, 0.0F, 0.0F), Relative.ROTATION);
|
| 2150 | if (entityToRide instanceof LivingEntity livingEntity) {
|
| 2151 | this.server.getPlayerList().sendActiveEffects(livingEntity, this.connection);
|
| 2152 | }
|
| 2153 |
|
| 2154 | this.connection.send(new ClientboundSetPassengersPacket(entityToRide));
|
| 2155 | return true;
|
| 2156 | } else {
|
| 2157 | return false;
|
| 2158 | }
|
| 2159 | }
|
| 2160 |
|
| 2161 | @Override
|
| 2162 | public void removeVehicle() {
|
| 2163 | Entity oldVehicle = this.getVehicle();
|
| 2164 | super.removeVehicle();
|
| 2165 | if (oldVehicle instanceof LivingEntity livingEntity) {
|
| 2166 | for (MobEffectInstance effect : livingEntity.getActiveEffects()) {
|
| 2167 | this.connection.send(new ClientboundRemoveMobEffectPacket(oldVehicle.getId(), effect.getEffect()));
|
| 2168 | }
|
| 2169 | }
|
| 2170 |
|
| 2171 | if (oldVehicle != null) {
|
| 2172 | this.connection.send(new ClientboundSetPassengersPacket(oldVehicle));
|
| 2173 | }
|
| 2174 | }
|
| 2175 |
|
| 2176 | public CommonPlayerSpawnInfo createCommonSpawnInfo(final ServerLevel level) {
|
| 2177 | return new CommonPlayerSpawnInfo(
|
| 2178 | level.dimensionTypeRegistration(),
|
| 2179 | level.dimension(),
|
| 2180 | BiomeManager.obfuscateSeed(level.getSeed()),
|
| 2181 | this.gameMode.getGameModeForPlayer(),
|
| 2182 | Optional.ofNullable(this.gameMode.getPreviousGameModeForPlayer()),
|
| 2183 | level.isDebug(),
|
| 2184 | level.isFlat(),
|
| 2185 | this.getLastDeathLocation(),
|
| 2186 | this.getPortalCooldown(),
|
| 2187 | level.getSeaLevel()
|
| 2188 | );
|
| 2189 | }
|
| 2190 |
|
| 2191 | public void setRaidOmenPosition(final BlockPos raidOmenPosition) {
|
| 2192 | this.raidOmenPosition = raidOmenPosition;
|
| 2193 | }
|
| 2194 |
|
| 2195 | public void clearRaidOmenPosition() {
|
| 2196 | this.raidOmenPosition = null;
|
| 2197 | }
|
| 2198 |
|
| 2199 | public @Nullable BlockPos getRaidOmenPosition() {
|
| 2200 | return this.raidOmenPosition;
|
| 2201 | }
|
| 2202 |
|
| 2203 | @Override
|
| 2204 | public Vec3 getKnownMovement() {
|
| 2205 | Entity vehicle = this.getVehicle();
|
| 2206 | return vehicle != null && vehicle.getControllingPassenger() != this ? vehicle.getKnownMovement() : this.lastKnownClientMovement;
|
| 2207 | }
|
| 2208 |
|
| 2209 | @Override
|
| 2210 | public Vec3 getKnownSpeed() {
|
| 2211 | Entity vehicle = this.getVehicle();
|
| 2212 | return vehicle != null && vehicle.getControllingPassenger() != this ? vehicle.getKnownSpeed() : this.lastKnownClientMovement;
|
| 2213 | }
|
| 2214 |
|
| 2215 | public void setKnownMovement(final Vec3 lastKnownClientMovement) {
|
| 2216 | this.lastKnownClientMovement = lastKnownClientMovement;
|
| 2217 | }
|
| 2218 |
|
| 2219 | @Override
|
| 2220 | protected float getEnchantedDamage(final Entity entity, final float dmg, final DamageSource damageSource) {
|
| 2221 | return EnchantmentHelper.modifyDamage(this.level(), this.getWeaponItem(), entity, damageSource, dmg);
|
| 2222 | }
|
| 2223 |
|
| 2224 | @Override
|
| 2225 | public void onEquippedItemBroken(final ItemStack brokenItem, final EquipmentSlot inSlot) {
|
| 2226 | super.onEquippedItemBroken(brokenItem, inSlot);
|
| 2227 | this.awardStat(Stats.ITEM_BROKEN.get(brokenItem.getItem()));
|
| 2228 | }
|
| 2229 |
|
| 2230 | public Input getLastClientInput() {
|
| 2231 | return this.lastClientInput;
|
| 2232 | }
|
| 2233 |
|
| 2234 | public void setLastClientInput(final Input lastClientInput) {
|
| 2235 | this.lastClientInput = lastClientInput;
|
| 2236 | }
|
| 2237 |
|
| 2238 | public Vec3 getLastClientMoveIntent() {
|
| 2239 | float leftIntent = this.lastClientInput.left() == this.lastClientInput.right() ? 0.0F : (this.lastClientInput.left() ? 1.0F : -1.0F);
|
| 2240 | float forwardIntent = this.lastClientInput.forward() == this.lastClientInput.backward() ? 0.0F : (this.lastClientInput.forward() ? 1.0F : -1.0F);
|
| 2241 | return getInputVector(new Vec3(leftIntent, 0.0, forwardIntent), 1.0F, this.getYRot());
|
| 2242 | }
|
| 2243 |
|
| 2244 | public void registerEnderPearl(final ThrownEnderpearl enderPearl) {
|
| 2245 | this.enderPearls.add(enderPearl);
|
| 2246 | }
|
| 2247 |
|
| 2248 | public void deregisterEnderPearl(final ThrownEnderpearl enderPearl) {
|
| 2249 | this.enderPearls.remove(enderPearl);
|
| 2250 | }
|
| 2251 |
|
| 2252 | public Set<ThrownEnderpearl> getEnderPearls() {
|
| 2253 | return this.enderPearls;
|
| 2254 | }
|
| 2255 |
|
| 2256 | public CompoundTag getShoulderEntityLeft() {
|
| 2257 | return this.shoulderEntityLeft;
|
| 2258 | }
|
| 2259 |
|
| 2260 | protected void setShoulderEntityLeft(final CompoundTag tag) {
|
| 2261 | this.shoulderEntityLeft = tag;
|
| 2262 | this.setShoulderParrotLeft(extractParrotVariant(tag));
|
| 2263 | }
|
| 2264 |
|
| 2265 | public CompoundTag getShoulderEntityRight() {
|
| 2266 | return this.shoulderEntityRight;
|
| 2267 | }
|
| 2268 |
|
| 2269 | protected void setShoulderEntityRight(final CompoundTag tag) {
|
| 2270 | this.shoulderEntityRight = tag;
|
| 2271 | this.setShoulderParrotRight(extractParrotVariant(tag));
|
| 2272 | }
|
| 2273 |
|
| 2274 | public long registerAndUpdateEnderPearlTicket(final ThrownEnderpearl enderpearl) {
|
| 2275 | if (enderpearl.level() instanceof ServerLevel enderPearlLevel) {
|
| 2276 | ChunkPos chunkPos = enderpearl.chunkPosition();
|
| 2277 | this.registerEnderPearl(enderpearl);
|
| 2278 | enderPearlLevel.resetEmptyTime();
|
| 2279 | return placeEnderPearlTicket(enderPearlLevel, chunkPos) - 1L;
|
| 2280 | } else {
|
| 2281 | return 0L;
|
| 2282 | }
|
| 2283 | }
|
| 2284 |
|
| 2285 | public static long placeEnderPearlTicket(final ServerLevel level, final ChunkPos chunk) {
|
| 2286 | level.getChunkSource().addTicketWithRadius(TicketType.ENDER_PEARL, chunk, 2);
|
| 2287 | return TicketType.ENDER_PEARL.timeout();
|
| 2288 | }
|
| 2289 |
|
| 2290 | public void requestDebugSubscriptions(final Set<DebugSubscription<?>> subscriptions) {
|
| 2291 | this.requestedDebugSubscriptions = Set.copyOf(subscriptions);
|
| 2292 | }
|
| 2293 |
|
| 2294 | public Set<DebugSubscription<?>> debugSubscriptions() {
|
| 2295 | return !this.server.debugSubscribers().hasRequiredPermissions(this) ? Set.of() : this.requestedDebugSubscriptions;
|
| 2296 | }
|
| 2297 |
|
| 2298 | @Override
|
| 2299 | public void swingAndResetAttackStrength(final InteractionHand hand, final SwingAnimation animation, final boolean sendToSwingingEntity) {
|
| 2300 | if (this.swing(hand, animation, sendToSwingingEntity)) {
|
| 2301 | this.resetAttackStrengthTicker();
|
| 2302 | }
|
| 2303 | }
|
| 2304 |
|
| 2305 | public record RespawnConfig(LevelData.RespawnData respawnData, boolean forced) {
|
| 2306 | public static final Codec<ServerPlayer.RespawnConfig> CODEC = RecordCodecBuilder.create(
|
| 2307 | i -> i.group(
|
| 2308 | LevelData.RespawnData.MAP_CODEC.forGetter(ServerPlayer.RespawnConfig::respawnData),
|
| 2309 | Codec.BOOL.optionalFieldOf("forced", false).forGetter(ServerPlayer.RespawnConfig::forced)
|
| 2310 | )
|
| 2311 | .apply(i, ServerPlayer.RespawnConfig::new)
|
| 2312 | );
|
| 2313 |
|
| 2314 | private static ResourceKey<Level> getDimensionOrDefault(final ServerPlayer.@Nullable RespawnConfig respawnConfig) {
|
| 2315 | return respawnConfig != null ? respawnConfig.respawnData().dimension() : Level.OVERWORLD;
|
| 2316 | }
|
| 2317 |
|
| 2318 | public boolean isSamePosition(final ServerPlayer.@Nullable RespawnConfig other) {
|
| 2319 | return other != null && this.respawnData.globalPos().equals(other.respawnData.globalPos());
|
| 2320 | }
|
| 2321 | }
|
| 2322 |
|
| 2323 | private record RespawnPosAngle(Vec3 position, float yaw, float pitch) {
|
| 2324 | public static ServerPlayer.RespawnPosAngle of(final Vec3 position, final BlockPos lookAtBlockPos, final float pitch) {
|
| 2325 | return new ServerPlayer.RespawnPosAngle(position, calculateLookAtYaw(position, lookAtBlockPos), pitch);
|
| 2326 | }
|
| 2327 |
|
| 2328 | private static float calculateLookAtYaw(final Vec3 position, final BlockPos lookAtBlockPos) {
|
| 2329 | Vec3 lookDirection = Vec3.atBottomCenterOf(lookAtBlockPos).subtract(position).normalize();
|
| 2330 | return (float)Mth.wrapDegrees(Mth.atan2(lookDirection.z, lookDirection.x) * 180.0F / (float)Math.PI - 90.0);
|
| 2331 | }
|
| 2332 | }
|
| 2333 |
|
| 2334 | public record SavedPosition(Optional<ResourceKey<Level>> dimension, Optional<Vec3> position, Optional<Vec2> rotation) {
|
| 2335 | public static final MapCodec<ServerPlayer.SavedPosition> MAP_CODEC = RecordCodecBuilder.mapCodec(
|
| 2336 | i -> i.group(
|
| 2337 | Level.RESOURCE_KEY_CODEC.optionalFieldOf("Dimension").forGetter(ServerPlayer.SavedPosition::dimension),
|
| 2338 | Vec3.CODEC.optionalFieldOf("Pos").forGetter(ServerPlayer.SavedPosition::position),
|
| 2339 | Vec2.CODEC.optionalFieldOf("Rotation").forGetter(ServerPlayer.SavedPosition::rotation)
|
| 2340 | )
|
| 2341 | .apply(i, ServerPlayer.SavedPosition::new)
|
| 2342 | );
|
| 2343 | public static final ServerPlayer.SavedPosition EMPTY = new ServerPlayer.SavedPosition(Optional.empty(), Optional.empty(), Optional.empty());
|
| 2344 | }
|
| 2345 | }
|
| 2346 |
|