--- a/net/minecraft/server/level/EntityPlayer.java
+++ b/net/minecraft/server/level/EntityPlayer.java
@@ -184,6 +184,41 @@
 import net.minecraft.world.scores.criteria.IScoreboardCriteria;
 import org.slf4j.Logger;
 
+// CraftBukkit start
+import net.minecraft.world.damagesource.CombatTracker;
+import net.minecraft.world.food.FoodMetaData;
+import net.minecraft.world.inventory.ContainerPlayer;
+import net.minecraft.world.item.enchantment.EnchantmentEffectComponents;
+import net.minecraft.world.level.block.BlockChest;
+import net.minecraft.world.level.dimension.WorldDimension;
+import net.minecraft.world.scores.Scoreboard;
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.WeatherType;
+import org.bukkit.command.CommandSender;
+import org.bukkit.craftbukkit.CraftWorld;
+import org.bukkit.craftbukkit.CraftWorldBorder;
+import org.bukkit.craftbukkit.entity.CraftPlayer;
+import org.bukkit.craftbukkit.event.CraftEventFactory;
+import org.bukkit.craftbukkit.event.CraftPortalEvent;
+import org.bukkit.craftbukkit.inventory.CraftItemStack;
+import org.bukkit.craftbukkit.util.CraftDimensionUtil;
+import org.bukkit.craftbukkit.util.CraftLocation;
+import org.bukkit.entity.Player;
+import org.bukkit.event.entity.EntityExhaustionEvent;
+import org.bukkit.event.player.PlayerBedLeaveEvent;
+import org.bukkit.event.player.PlayerChangedMainHandEvent;
+import org.bukkit.event.player.PlayerChangedWorldEvent;
+import org.bukkit.event.player.PlayerDropItemEvent;
+import org.bukkit.event.player.PlayerLocaleChangeEvent;
+import org.bukkit.event.player.PlayerPortalEvent;
+import org.bukkit.event.player.PlayerRespawnEvent;
+import org.bukkit.event.player.PlayerSpawnChangeEvent;
+import org.bukkit.event.player.PlayerTeleportEvent;
+import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
+import org.bukkit.inventory.MainHand;
+// CraftBukkit end
+
 public class EntityPlayer extends EntityHuman {
 
     private static final Logger LOGGER = LogUtils.getLogger();
@@ -227,7 +262,7 @@
     private int levitationStartTime;
     private boolean disconnected;
     private int requestedViewDistance;
-    public String language;
+    public String language = "en_us"; // CraftBukkit - default
     @Nullable
     private Vec3D startingToFallPosition;
     @Nullable
@@ -261,6 +296,22 @@
     private int containerCounter;
     public boolean wonGame;
 
+    // CraftBukkit start
+    public CraftPlayer.TransferCookieConnection transferCookieConnection;
+    public String displayName;
+    public IChatBaseComponent listName;
+    public int listOrder = 0;
+    public org.bukkit.Location compassTarget;
+    public int newExp = 0;
+    public int newLevel = 0;
+    public int newTotalExp = 0;
+    public boolean keepLevel = false;
+    public double maxHealthCache;
+    public boolean joining = true;
+    public boolean sentListPacket = false;
+    public String kickLeaveMessage = null; // SPIGOT-3034: Forward leave message to PlayerQuitEvent
+    // CraftBukkit end
+
     public EntityPlayer(MinecraftServer minecraftserver, WorldServer worldserver, GameProfile gameprofile, ClientInformation clientinformation) {
         super(worldserver, worldserver.getSharedSpawnPos(), worldserver.getSharedSpawnAngle(), gameprofile);
         this.chatVisibility = EnumChatVisibility.FULL;
@@ -342,6 +393,13 @@
             public void sendSystemMessage(IChatBaseComponent ichatbasecomponent) {
                 EntityPlayer.this.sendSystemMessage(ichatbasecomponent);
             }
+
+            // CraftBukkit start
+            @Override
+            public CommandSender getBukkitSender(CommandListenerWrapper wrapper) {
+                return getBukkitEntity();
+            }
+            // CraftBukkit end
         };
         this.textFilter = minecraftserver.createTextFilterForPlayer(this);
         this.gameMode = minecraftserver.createGameModeForPlayer(this);
@@ -354,14 +412,67 @@
         this.moveTo(this.adjustSpawnLocation(worldserver, worldserver.getSharedSpawnPos()).getBottomCenter(), 0.0F, 0.0F);
         this.updateOptions(clientinformation);
         this.object = null;
+
+        // CraftBukkit start
+        this.displayName = this.getScoreboardName();
+        this.bukkitPickUpLoot = true;
+        this.maxHealthCache = this.getMaxHealth();
+    }
+
+    // Use method to resend items in hands in case of client desync, because the item use got cancelled.
+    // For example, when cancelling the leash event
+    public void resendItemInHands() {
+        containerMenu.findSlot(getInventory(), getInventory().selected).ifPresent(s -> {
+            containerSynchronizer.sendSlotChange(containerMenu, s, getMainHandItem());
+        });
+        containerSynchronizer.sendSlotChange(inventoryMenu, ContainerPlayer.SHIELD_SLOT, getOffhandItem());
+    }
+
+    // Yes, this doesn't match Vanilla, but it's the best we can do for now.
+    // If this is an issue, PRs are welcome
+    public final BlockPosition getSpawnPoint(WorldServer worldserver) {
+        BlockPosition blockposition = worldserver.getSharedSpawnPos();
+
+        if (worldserver.dimensionType().hasSkyLight() && worldserver.serverLevelData.getGameType() != EnumGamemode.ADVENTURE) {
+            int i = Math.max(0, this.server.getSpawnRadius(worldserver));
+            int j = MathHelper.floor(worldserver.getWorldBorder().getDistanceToBorder((double) blockposition.getX(), (double) blockposition.getZ()));
+
+            if (j < i) {
+                i = j;
+            }
+
+            if (j <= 1) {
+                i = 1;
+            }
+
+            long k = (long) (i * 2 + 1);
+            long l = k * k;
+            int i1 = l > 2147483647L ? Integer.MAX_VALUE : (int) l;
+            int j1 = this.getCoprime(i1);
+            int k1 = RandomSource.create().nextInt(i1);
+
+            for (int l1 = 0; l1 < i1; ++l1) {
+                int i2 = (k1 + j1 * l1) % i1;
+                int j2 = i2 % (i * 2 + 1);
+                int k2 = i2 / (i * 2 + 1);
+                BlockPosition blockposition1 = WorldProviderNormal.getOverworldRespawnPos(worldserver, blockposition.getX() + j2 - i, blockposition.getZ() + k2 - i);
+
+                if (blockposition1 != null) {
+                    return blockposition1;
+                }
+            }
+        }
+
+        return blockposition;
     }
+    // CraftBukkit end
 
     @Override
     public BlockPosition adjustSpawnLocation(WorldServer worldserver, BlockPosition blockposition) {
         AxisAlignedBB axisalignedbb = this.getDimensions(EntityPose.STANDING).makeBoundingBox(Vec3D.ZERO);
         BlockPosition blockposition1 = blockposition;
 
-        if (worldserver.dimensionType().hasSkyLight() && worldserver.getServer().getWorldData().getGameType() != EnumGamemode.ADVENTURE) {
+        if (worldserver.dimensionType().hasSkyLight() && worldserver.serverLevelData.getGameType() != EnumGamemode.ADVENTURE) { // CraftBukkit
             int i = Math.max(0, this.server.getSpawnRadius(worldserver));
             int j = MathHelper.floor(worldserver.getWorldBorder().getDistanceToBorder((double) blockposition.getX(), (double) blockposition.getZ()));
 
@@ -397,14 +508,20 @@
 
                     Objects.requireNonNull(blockposition);
                     crashreportsystemdetails.setDetail("Origin", blockposition::toString);
+                    // CraftBukkit start - decompile error
+                    int finalI = i;
                     crashreportsystemdetails.setDetail("Radius", () -> {
-                        return Integer.toString(i);
+                        return Integer.toString(finalI);
+                        // CraftBukkit end
                     });
                     crashreportsystemdetails.setDetail("Candidate", () -> {
                         return "[" + l2 + "," + i3 + "]";
                     });
+                    // CraftBukkit start - decompile error
+                    int finalL1 = l1;
                     crashreportsystemdetails.setDetail("Progress", () -> {
-                        return "" + l1 + " out of " + i1;
+                        return "" + finalL1 + " out of " + i1;
+                        // CraftBukkit end
                     });
                     throw new ReportedException(crashreport);
                 }
@@ -442,7 +559,7 @@
             dataresult = WardenSpawnTracker.CODEC.parse(new Dynamic(DynamicOpsNBT.INSTANCE, nbttagcompound.get("warden_spawn_tracker")));
             logger = EntityPlayer.LOGGER;
             Objects.requireNonNull(logger);
-            dataresult.resultOrPartial(logger::error).ifPresent((wardenspawntracker) -> {
+            ((DataResult<WardenSpawnTracker>) dataresult).resultOrPartial(logger::error).ifPresent((wardenspawntracker) -> {
                 this.wardenSpawnTracker = wardenspawntracker;
             });
         }
@@ -459,17 +576,26 @@
                 return this.server.getRecipeManager().byKey(resourcekey).isPresent();
             });
         }
+        this.getBukkitEntity().readExtraData(nbttagcompound); // CraftBukkit
 
         if (this.isSleeping()) {
             this.stopSleeping();
         }
 
+        // CraftBukkit start
+        String spawnWorld = nbttagcompound.getString("SpawnWorld");
+        CraftWorld oldWorld = (CraftWorld) Bukkit.getWorld(spawnWorld);
+        if (oldWorld != null) {
+            this.respawnDimension = oldWorld.getHandle().dimension();
+        }
+        // CraftBukkit end
+
         if (nbttagcompound.contains("SpawnX", 99) && nbttagcompound.contains("SpawnY", 99) && nbttagcompound.contains("SpawnZ", 99)) {
             this.respawnPosition = new BlockPosition(nbttagcompound.getInt("SpawnX"), nbttagcompound.getInt("SpawnY"), nbttagcompound.getInt("SpawnZ"));
             this.respawnForced = nbttagcompound.getBoolean("SpawnForced");
             this.respawnAngle = nbttagcompound.getFloat("SpawnAngle");
             if (nbttagcompound.contains("SpawnDimension")) {
-                DataResult dataresult1 = World.RESOURCE_KEY_CODEC.parse(DynamicOpsNBT.INSTANCE, nbttagcompound.get("SpawnDimension"));
+                DataResult<ResourceKey<World>> dataresult1 = World.RESOURCE_KEY_CODEC.parse(DynamicOpsNBT.INSTANCE, nbttagcompound.get("SpawnDimension")); // CraftBukkit - decompile error
                 Logger logger1 = EntityPlayer.LOGGER;
 
                 Objects.requireNonNull(logger1);
@@ -484,7 +610,7 @@
             dataresult = BlockPosition.CODEC.parse(DynamicOpsNBT.INSTANCE, nbtbase);
             logger = EntityPlayer.LOGGER;
             Objects.requireNonNull(logger);
-            dataresult.resultOrPartial(logger::error).ifPresent((blockposition) -> {
+            ((DataResult<BlockPosition>) dataresult).resultOrPartial(logger::error).ifPresent((blockposition) -> { // CraftBukkit - decompile error
                 this.raidOmenPosition = blockposition;
             });
         }
@@ -494,7 +620,7 @@
     @Override
     public void addAdditionalSaveData(NBTTagCompound nbttagcompound) {
         super.addAdditionalSaveData(nbttagcompound);
-        DataResult dataresult = WardenSpawnTracker.CODEC.encodeStart(DynamicOpsNBT.INSTANCE, this.wardenSpawnTracker);
+        DataResult<NBTBase> dataresult = WardenSpawnTracker.CODEC.encodeStart(DynamicOpsNBT.INSTANCE, this.wardenSpawnTracker); // CraftBukkit - decompile error
         Logger logger = EntityPlayer.LOGGER;
 
         Objects.requireNonNull(logger);
@@ -528,6 +654,7 @@
                 nbttagcompound.put("SpawnDimension", nbtbase);
             });
         }
+        this.getBukkitEntity().setExtraData(nbttagcompound); // CraftBukkit
 
         nbttagcompound.putBoolean("spawn_extra_particles_on_fall", this.spawnExtraParticlesOnFall);
         if (this.raidOmenPosition != null) {
@@ -546,7 +673,20 @@
         Entity entity = this.getRootVehicle();
         Entity entity1 = this.getVehicle();
 
-        if (entity1 != null && entity != this && entity.hasExactlyOnePlayerPassenger()) {
+        // CraftBukkit start - handle non-persistent vehicles
+        boolean persistVehicle = true;
+        if (entity1 != null) {
+            Entity vehicle;
+            for (vehicle = entity1; vehicle != null; vehicle = vehicle.getVehicle()) {
+                if (!vehicle.persist) {
+                    persistVehicle = false;
+                    break;
+                }
+            }
+        }
+
+        if (persistVehicle && entity1 != null && entity != this && entity.hasExactlyOnePlayerPassenger()) {
+            // CraftBukkit end
             NBTTagCompound nbttagcompound1 = new NBTTagCompound();
             NBTTagCompound nbttagcompound2 = new NBTTagCompound();
 
@@ -600,12 +740,12 @@
 
                 if (!this.isPassenger()) {
                     EntityPlayer.LOGGER.warn("Couldn't reattach entity to player");
-                    entity.discard();
+                    entity.discard(null); // CraftBukkit - add Bukkit remove cause
                     iterator = entity.getIndirectPassengers().iterator();
 
                     while (iterator.hasNext()) {
                         entity1 = (Entity) iterator.next();
-                        entity1.discard();
+                        entity1.discard(null); // CraftBukkit - add Bukkit remove cause
                     }
                 }
             }
@@ -627,7 +767,7 @@
                     NBTTagCompound nbttagcompound1 = new NBTTagCompound();
 
                     entityenderpearl.save(nbttagcompound1);
-                    DataResult dataresult = MinecraftKey.CODEC.encodeStart(DynamicOpsNBT.INSTANCE, entityenderpearl.level().dimension().location());
+                    DataResult<NBTBase> dataresult = MinecraftKey.CODEC.encodeStart(DynamicOpsNBT.INSTANCE, entityenderpearl.level().dimension().location()); // CraftBukkit - decompile error
                     Logger logger = EntityPlayer.LOGGER;
 
                     Objects.requireNonNull(logger);
@@ -653,7 +793,7 @@
                 nbttaglist.forEach((nbtbase1) -> {
                     if (nbtbase1 instanceof NBTTagCompound nbttagcompound) {
                         if (nbttagcompound.contains("ender_pearl_dimension")) {
-                            DataResult dataresult = World.RESOURCE_KEY_CODEC.parse(DynamicOpsNBT.INSTANCE, nbttagcompound.get("ender_pearl_dimension"));
+                            DataResult<ResourceKey<World>> dataresult = World.RESOURCE_KEY_CODEC.parse(DynamicOpsNBT.INSTANCE, nbttagcompound.get("ender_pearl_dimension")); // CraftBukkit - decompile error
                             Logger logger = EntityPlayer.LOGGER;
 
                             Objects.requireNonNull(logger);
@@ -688,6 +828,29 @@
 
     }
 
+    // CraftBukkit start - World fallback code, either respawn location or global spawn
+    public void spawnIn(World world) {
+        this.setLevel(world);
+        if (world == null) {
+            this.unsetRemoved();
+            Vec3D position = null;
+            if (this.respawnDimension != null) {
+                world = this.server.getLevel(this.respawnDimension);
+                if (world != null && this.getRespawnPosition() != null) {
+                    position = EntityPlayer.findRespawnAndUseSpawnBlock((WorldServer) world, this.getRespawnPosition(), this.getRespawnAngle(), false, false).map(EntityPlayer.RespawnPosAngle::position).orElse(null);
+                }
+            }
+            if (world == null || position == null) {
+                world = ((CraftWorld) Bukkit.getServer().getWorlds().get(0)).getHandle();
+                position = Vec3D.atCenterOf(world.getSharedSpawnPos());
+            }
+            this.setLevel(world);
+            this.setPos(position);
+        }
+        this.gameMode.setLevel((WorldServer) world);
+    }
+    // CraftBukkit end
+
     public void setExperiencePoints(int i) {
         float f = (float) this.getXpNeededForNextLevel();
         float f1 = (f - 1.0F) / f;
@@ -746,6 +909,11 @@
 
     @Override
     public void tick() {
+        // CraftBukkit start
+        if (this.joining) {
+            this.joining = false;
+        }
+        // CraftBukkit end
         this.gameMode.tick();
         this.wardenSpawnTracker.tick();
         --this.spawnInvulnerableTime;
@@ -822,7 +990,7 @@
             }
 
             if (this.getHealth() != this.lastSentHealth || this.lastSentFood != this.foodData.getFoodLevel() || this.foodData.getSaturationLevel() == 0.0F != this.lastFoodSaturationZero) {
-                this.connection.send(new PacketPlayOutUpdateHealth(this.getHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel()));
+                this.connection.send(new PacketPlayOutUpdateHealth(this.getBukkitEntity().getScaledHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel())); // CraftBukkit
                 this.lastSentHealth = this.getHealth();
                 this.lastSentFood = this.foodData.getFoodLevel();
                 this.lastFoodSaturationZero = this.foodData.getSaturationLevel() == 0.0F;
@@ -853,6 +1021,12 @@
                 this.updateScoreForCriteria(IScoreboardCriteria.EXPERIENCE, MathHelper.ceil((float) this.lastRecordedExperience));
             }
 
+            // CraftBukkit start - Force max health updates
+            if (this.maxHealthCache != this.getMaxHealth()) {
+                this.getBukkitEntity().updateScaledHealth();
+            }
+            // CraftBukkit end
+
             if (this.experienceLevel != this.lastRecordedLevel) {
                 this.lastRecordedLevel = this.experienceLevel;
                 this.updateScoreForCriteria(IScoreboardCriteria.LEVEL, MathHelper.ceil((float) this.lastRecordedLevel));
@@ -867,6 +1041,20 @@
                 CriterionTriggers.LOCATION.trigger(this);
             }
 
+            // CraftBukkit start - initialize oldLevel, fire PlayerLevelChangeEvent, and tick client-sided world border
+            if (this.oldLevel == -1) {
+                this.oldLevel = this.experienceLevel;
+            }
+
+            if (this.oldLevel != this.experienceLevel) {
+                CraftEventFactory.callPlayerLevelChangeEvent(this.getBukkitEntity(), this.oldLevel, this.experienceLevel);
+                this.oldLevel = this.experienceLevel;
+            }
+
+            if (this.getBukkitEntity().hasClientWorldBorder()) {
+                ((CraftWorldBorder) this.getBukkitEntity().getWorldBorder()).getHandle().tick();
+            }
+            // CraftBukkit end
         } catch (Throwable throwable) {
             CrashReport crashreport = CrashReport.forThrowable(throwable, "Ticking player");
             CrashReportSystemDetails crashreportsystemdetails = crashreport.addCategory("Player being ticked");
@@ -895,7 +1083,7 @@
         if (this.level().getDifficulty() == EnumDifficulty.PEACEFUL && this.serverLevel().getGameRules().getBoolean(GameRules.RULE_NATURAL_REGENERATION)) {
             if (this.tickCount % 20 == 0) {
                 if (this.getHealth() < this.getMaxHealth()) {
-                    this.heal(1.0F);
+                    this.heal(1.0F, org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason.REGEN); // CraftBukkit - added regain reason of "REGEN" for filtering purposes.
                 }
 
                 float f = this.foodData.getSaturationLevel();
@@ -948,7 +1136,8 @@
     }
 
     private void updateScoreForCriteria(IScoreboardCriteria iscoreboardcriteria, int i) {
-        this.getScoreboard().forAllObjectives(iscoreboardcriteria, this, (scoreaccess) -> {
+        // CraftBukkit - Use our scores instead
+        this.level().getCraftServer().getScoreboardManager().forAllObjectives(iscoreboardcriteria, this, (scoreaccess) -> {
             scoreaccess.set(i);
         });
     }
@@ -957,9 +1146,47 @@
     public void die(DamageSource damagesource) {
         this.gameEvent(GameEvent.ENTITY_DIE);
         boolean flag = this.serverLevel().getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES);
+        // CraftBukkit start - fire PlayerDeathEvent
+        if (this.isRemoved()) {
+            return;
+        }
+        java.util.List<org.bukkit.inventory.ItemStack> loot = new java.util.ArrayList<>(this.getInventory().getContainerSize());
+        boolean keepInventory = this.serverLevel().getGameRules().getBoolean(GameRules.RULE_KEEPINVENTORY) || this.isSpectator();
 
-        if (flag) {
-            IChatBaseComponent ichatbasecomponent = this.getCombatTracker().getDeathMessage();
+        if (!keepInventory) {
+            for (ItemStack item : this.getInventory().getContents()) {
+                if (!item.isEmpty() && !EnchantmentManager.has(item, EnchantmentEffectComponents.PREVENT_EQUIPMENT_DROP)) {
+                    loot.add(CraftItemStack.asCraftMirror(item).markForInventoryDrop());
+                }
+            }
+        }
+        // SPIGOT-5071: manually add player loot tables (SPIGOT-5195 - ignores keepInventory rule)
+        this.dropFromLootTable(this.serverLevel(), damagesource, this.lastHurtByPlayerTime > 0);
+        this.dropCustomDeathLoot(this.serverLevel(), damagesource, flag);
+
+        loot.addAll(this.drops);
+        this.drops.clear(); // SPIGOT-5188: make sure to clear
+
+        IChatBaseComponent defaultMessage = this.getCombatTracker().getDeathMessage();
+
+        String deathmessage = defaultMessage.getString();
+        keepLevel = keepInventory; // SPIGOT-2222: pre-set keepLevel
+        org.bukkit.event.entity.PlayerDeathEvent event = CraftEventFactory.callPlayerDeathEvent(this, damagesource, loot, deathmessage, keepInventory);
+
+        // SPIGOT-943 - only call if they have an inventory open
+        if (this.containerMenu != this.inventoryMenu) {
+            this.closeContainer();
+        }
+
+        String deathMessage = event.getDeathMessage();
+
+        if (deathMessage != null && deathMessage.length() > 0 && flag) { // TODO: allow plugins to override?
+            IChatBaseComponent ichatbasecomponent;
+            if (deathMessage.equals(deathmessage)) {
+                ichatbasecomponent = this.getCombatTracker().getDeathMessage();
+            } else {
+                ichatbasecomponent = org.bukkit.craftbukkit.util.CraftChatMessage.fromStringOrNull(deathMessage);
+            }
 
             this.connection.send(new ClientboundPlayerCombatKillPacket(this.getId(), ichatbasecomponent), PacketSendListener.exceptionallySend(() -> {
                 boolean flag1 = true;
@@ -990,12 +1217,18 @@
         if (this.serverLevel().getGameRules().getBoolean(GameRules.RULE_FORGIVE_DEAD_PLAYERS)) {
             this.tellNeutralMobsThatIDied();
         }
-
-        if (!this.isSpectator()) {
-            this.dropAllDeathLoot(this.serverLevel(), damagesource);
+        // SPIGOT-5478 must be called manually now
+        this.dropExperience(this.serverLevel(), damagesource.getEntity());
+        // we clean the player's inventory after the EntityDeathEvent is called so plugins can get the exact state of the inventory.
+        if (!event.getKeepInventory()) {
+            this.getInventory().clearContent();
         }
 
-        this.getScoreboard().forAllObjectives(IScoreboardCriteria.DEATH_COUNT, this, ScoreAccess::increment);
+        this.setCamera(this); // Remove spectated target
+        // CraftBukkit end
+
+        // CraftBukkit - Get our scores instead
+        this.level().getCraftServer().getScoreboardManager().forAllObjectives(IScoreboardCriteria.DEATH_COUNT, this, ScoreAccess::increment);
         EntityLiving entityliving = this.getKillCredit();
 
         if (entityliving != null) {
@@ -1030,10 +1263,12 @@
         if (entity != this) {
             super.awardKillScore(entity, i, damagesource);
             this.increaseScore(i);
-            this.getScoreboard().forAllObjectives(IScoreboardCriteria.KILL_COUNT_ALL, this, ScoreAccess::increment);
+            // CraftBukkit - Get our scores instead
+            this.level().getCraftServer().getScoreboardManager().forAllObjectives(IScoreboardCriteria.KILL_COUNT_ALL, this, ScoreAccess::increment);
             if (entity instanceof EntityHuman) {
                 this.awardStat(StatisticList.PLAYER_KILLS);
-                this.getScoreboard().forAllObjectives(IScoreboardCriteria.KILL_COUNT_PLAYERS, this, ScoreAccess::increment);
+                // CraftBukkit - Get our scores instead
+                this.level().getCraftServer().getScoreboardManager().forAllObjectives(IScoreboardCriteria.KILL_COUNT_PLAYERS, this, ScoreAccess::increment);
             } else {
                 this.awardStat(StatisticList.MOB_KILLS);
             }
@@ -1051,7 +1286,8 @@
             int i = scoreboardteam.getColor().getId();
 
             if (i >= 0 && i < aiscoreboardcriteria.length) {
-                this.getScoreboard().forAllObjectives(aiscoreboardcriteria[i], scoreholder, ScoreAccess::increment);
+                // CraftBukkit - Get our scores instead
+                this.level().getCraftServer().getScoreboardManager().forAllObjectives(aiscoreboardcriteria[i], scoreholder, ScoreAccess::increment);
             }
         }
 
@@ -1101,10 +1337,16 @@
     }
 
     private boolean isPvpAllowed() {
-        return this.server.isPvpAllowed();
+        // CraftBukkit - this.server.isPvpAllowed() -> this.world.pvpMode
+        return this.level().pvpMode;
     }
 
-    public TeleportTransition findRespawnPositionAndUseSpawnBlock(boolean flag, TeleportTransition.a teleporttransition_a) {
+    // CraftBukkit start
+    public TeleportTransition findRespawnPositionAndUseSpawnBlock(boolean flag, TeleportTransition.a teleporttransition_a, PlayerRespawnEvent.RespawnReason reason) {
+        TeleportTransition teleportTransition;
+        boolean isBedSpawn = false;
+        boolean isAnchorSpawn = false;
+        // CraftBukkit end
         BlockPosition blockposition = this.getRespawnPosition();
         float f = this.getRespawnAngle();
         boolean flag1 = this.isRespawnForced();
@@ -1116,13 +1358,32 @@
             if (optional.isPresent()) {
                 EntityPlayer.RespawnPosAngle entityplayer_respawnposangle = (EntityPlayer.RespawnPosAngle) optional.get();
 
-                return new TeleportTransition(worldserver, entityplayer_respawnposangle.position(), Vec3D.ZERO, entityplayer_respawnposangle.yaw(), 0.0F, teleporttransition_a);
+                // CraftBukkit start
+                isBedSpawn = entityplayer_respawnposangle.isBedSpawn();
+                isAnchorSpawn = entityplayer_respawnposangle.isAnchorSpawn();
+                teleportTransition = new TeleportTransition(worldserver, entityplayer_respawnposangle.position(), Vec3D.ZERO, entityplayer_respawnposangle.yaw(), 0.0F, teleporttransition_a);
+                // CraftBukkit end
             } else {
-                return TeleportTransition.missingRespawnBlock(this.server.overworld(), this, teleporttransition_a);
+                teleportTransition = TeleportTransition.missingRespawnBlock(this.server.overworld(), this, teleporttransition_a); // CraftBukkit
             }
         } else {
-            return new TeleportTransition(this.server.overworld(), this, teleporttransition_a);
+            teleportTransition = new TeleportTransition(this.server.overworld(), this, teleporttransition_a); // CraftBukkit
         }
+        // CraftBukkit start
+        if (reason == null) {
+            return teleportTransition;
+        }
+
+        Player respawnPlayer = this.getBukkitEntity();
+        Location location = CraftLocation.toBukkit(teleportTransition.position(), teleportTransition.newLevel().getWorld(), teleportTransition.yRot(), teleportTransition.xRot());
+
+        PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(respawnPlayer, location, isBedSpawn, isAnchorSpawn, reason);
+        this.level().getCraftServer().getPluginManager().callEvent(respawnEvent);
+
+        location = respawnEvent.getRespawnLocation();
+
+        return new TeleportTransition(((CraftWorld) location.getWorld()).getHandle(), CraftLocation.toVec3D(location), teleportTransition.deltaMovement(), location.getYaw(), location.getPitch(), teleportTransition.missingRespawnBlock(), teleportTransition.asPassenger(), teleportTransition.relatives(), teleportTransition.postTeleportTransition(), teleportTransition.cause());
+        // CraftBukkit end
     }
 
     public static Optional<EntityPlayer.RespawnPosAngle> findRespawnAndUseSpawnBlock(WorldServer worldserver, BlockPosition blockposition, float f, boolean flag, boolean flag1) {
@@ -1137,11 +1398,11 @@
             }
 
             return optional.map((vec3d) -> {
-                return EntityPlayer.RespawnPosAngle.of(vec3d, blockposition);
+                return EntityPlayer.RespawnPosAngle.of(vec3d, blockposition, false, true); // CraftBukkit
             });
         } else if (block instanceof BlockBed && BlockBed.canSetSpawn(worldserver)) {
             return BlockBed.findStandUpPosition(EntityTypes.PLAYER, worldserver, blockposition, (EnumDirection) iblockdata.getValue(BlockBed.FACING), f).map((vec3d) -> {
-                return EntityPlayer.RespawnPosAngle.of(vec3d, blockposition);
+                return EntityPlayer.RespawnPosAngle.of(vec3d, blockposition, true, false); // CraftBukkit
             });
         } else if (!flag) {
             return Optional.empty();
@@ -1150,7 +1411,7 @@
             IBlockData iblockdata1 = worldserver.getBlockState(blockposition.above());
             boolean flag3 = iblockdata1.getBlock().isPossibleToRespawnInThis(iblockdata1);
 
-            return flag2 && flag3 ? Optional.of(new EntityPlayer.RespawnPosAngle(new Vec3D((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.1D, (double) blockposition.getZ() + 0.5D), f)) : Optional.empty();
+            return flag2 && flag3 ? Optional.of(new EntityPlayer.RespawnPosAngle(new Vec3D((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.1D, (double) blockposition.getZ() + 0.5D), f, false, false)) : Optional.empty(); // CraftBukkit
         }
     }
 
@@ -1168,6 +1429,7 @@
     @Nullable
     @Override
     public EntityPlayer teleport(TeleportTransition teleporttransition) {
+        if (this.isSleeping()) return null; // CraftBukkit - SPIGOT-3154
         if (this.isRemoved()) {
             return null;
         } else {
@@ -1177,18 +1439,38 @@
 
             WorldServer worldserver = teleporttransition.newLevel();
             WorldServer worldserver1 = this.serverLevel();
-            ResourceKey<World> resourcekey = worldserver1.dimension();
+            // CraftBukkit start
+            ResourceKey<WorldDimension> resourcekey = worldserver1.getTypeKey();
+
+            Location enter = this.getBukkitEntity().getLocation();
+            PositionMoveRotation absolutePosition = PositionMoveRotation.calculateAbsolute(PositionMoveRotation.of(this), PositionMoveRotation.of(teleporttransition), teleporttransition.relatives());
+            Location exit = (worldserver == null) ? null : CraftLocation.toBukkit(absolutePosition.position(), worldserver.getWorld(), absolutePosition.yRot(), absolutePosition.xRot());
+            PlayerTeleportEvent tpEvent = new PlayerTeleportEvent(this.getBukkitEntity(), enter, exit, teleporttransition.cause());
+            Bukkit.getServer().getPluginManager().callEvent(tpEvent);
+            Location newExit = tpEvent.getTo();
+            if (tpEvent.isCancelled() || newExit == null) {
+                return null;
+            }
+            if (!newExit.equals(exit)) {
+                worldserver = ((CraftWorld) newExit.getWorld()).getHandle();
+                teleporttransition = new TeleportTransition(worldserver, CraftLocation.toVec3D(newExit), Vec3D.ZERO, newExit.getYaw(), newExit.getPitch(), teleporttransition.missingRespawnBlock(), teleporttransition.asPassenger(), Set.of(), teleporttransition.postTeleportTransition(), teleporttransition.cause());
+            }
+            // CraftBukkit end
 
             if (!teleporttransition.asPassenger()) {
                 this.stopRiding();
             }
 
-            if (worldserver.dimension() == resourcekey) {
-                this.connection.teleport(PositionMoveRotation.of(teleporttransition), teleporttransition.relatives());
+            // CraftBukkit start
+            if (worldserver != null && worldserver.dimension() == worldserver1.dimension()) {
+                this.connection.internalTeleport(PositionMoveRotation.of(teleporttransition), teleporttransition.relatives());
+                // CraftBukkit end
                 this.connection.resetPosition();
                 teleporttransition.postTeleportTransition().onTransition(this);
                 return this;
             } else {
+                // CraftBukkit start
+                /*
                 this.isChangingDimension = true;
                 WorldData worlddata = worldserver.getLevelData();
 
@@ -1199,17 +1481,31 @@
                 playerlist.sendPlayerPermissionLevel(this);
                 worldserver1.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION);
                 this.unsetRemoved();
+                */
+                // CraftBukkit end
                 GameProfilerFiller gameprofilerfiller = Profiler.get();
 
                 gameprofilerfiller.push("moving");
-                if (resourcekey == World.OVERWORLD && worldserver.dimension() == World.NETHER) {
+                if (worldserver != null && resourcekey == WorldDimension.OVERWORLD && worldserver.getTypeKey() == WorldDimension.NETHER) { // CraftBukkit - empty to fall through to null to event
                     this.enteredNetherPosition = this.position();
                 }
 
                 gameprofilerfiller.pop();
                 gameprofilerfiller.push("placing");
+                // CraftBukkit start
+                this.isChangingDimension = true; // CraftBukkit - Set teleport invulnerability only if player changing worlds
+                WorldData worlddata = worldserver.getLevelData();
+
+                this.connection.send(new PacketPlayOutRespawn(this.createCommonSpawnInfo(worldserver), (byte) 3));
+                this.connection.send(new PacketPlayOutServerDifficulty(worlddata.getDifficulty(), worlddata.isDifficultyLocked()));
+                PlayerList playerlist = this.server.getPlayerList();
+
+                playerlist.sendPlayerPermissionLevel(this);
+                worldserver1.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION);
+                this.unsetRemoved();
+                // CraftBukkit end
                 this.setServerLevel(worldserver);
-                this.connection.teleport(PositionMoveRotation.of(teleporttransition), teleporttransition.relatives());
+                this.connection.internalTeleport(PositionMoveRotation.of(teleporttransition), teleporttransition.relatives()); // CraftBukkit - use internal teleport without event
                 this.connection.resetPosition();
                 worldserver.addDuringTeleport(this);
                 gameprofilerfiller.pop();
@@ -1223,11 +1519,29 @@
                 this.lastSentExp = -1;
                 this.lastSentHealth = -1.0F;
                 this.lastSentFood = -1;
+
+                // CraftBukkit start
+                PlayerChangedWorldEvent changeEvent = new PlayerChangedWorldEvent(this.getBukkitEntity(), worldserver1.getWorld());
+                this.level().getCraftServer().getPluginManager().callEvent(changeEvent);
+                // CraftBukkit end
                 return this;
             }
         }
     }
 
+    // CraftBukkit start
+    @Override
+    public CraftPortalEvent callPortalEvent(Entity entity, Location exit, TeleportCause cause, int searchRadius, int creationRadius) {
+        Location enter = this.getBukkitEntity().getLocation();
+        PlayerPortalEvent event = new PlayerPortalEvent(this.getBukkitEntity(), enter, exit, cause, searchRadius, true, creationRadius);
+        Bukkit.getServer().getPluginManager().callEvent(event);
+        if (event.isCancelled() || event.getTo() == null || event.getTo().getWorld() == null) {
+            return null;
+        }
+        return new CraftPortalEvent(event);
+    }
+    // CraftBukkit end
+
     @Override
     public void forceSetRotation(float f, float f1) {
         this.connection.send(new ClientboundPlayerRotationPacket(f, f1));
@@ -1236,13 +1550,21 @@
     public void triggerDimensionChangeTriggers(WorldServer worldserver) {
         ResourceKey<World> resourcekey = worldserver.dimension();
         ResourceKey<World> resourcekey1 = this.level().dimension();
+        // CraftBukkit start
+        ResourceKey<World> maindimensionkey = CraftDimensionUtil.getMainDimensionKey(worldserver);
+        ResourceKey<World> maindimensionkey1 = CraftDimensionUtil.getMainDimensionKey(this.level());
 
-        CriterionTriggers.CHANGED_DIMENSION.trigger(this, resourcekey, resourcekey1);
-        if (resourcekey == World.NETHER && resourcekey1 == World.OVERWORLD && this.enteredNetherPosition != null) {
+        CriterionTriggers.CHANGED_DIMENSION.trigger(this, maindimensionkey, maindimensionkey1);
+        if (maindimensionkey != resourcekey || maindimensionkey1 != resourcekey1) {
+            CriterionTriggers.CHANGED_DIMENSION.trigger(this, resourcekey, resourcekey1);
+        }
+
+        if (maindimensionkey == World.NETHER && maindimensionkey1 == World.OVERWORLD && this.enteredNetherPosition != null) {
+            // CraftBukkit end
             CriterionTriggers.NETHER_TRAVEL.trigger(this, this.enteredNetherPosition);
         }
 
-        if (resourcekey1 != World.NETHER) {
+        if (maindimensionkey1 != World.NETHER) { // CraftBukkit
             this.enteredNetherPosition = null;
         }
 
@@ -1259,19 +1581,17 @@
         this.containerMenu.broadcastChanges();
     }
 
-    @Override
-    public Either<EntityHuman.EnumBedResult, Unit> startSleepInBed(BlockPosition blockposition) {
-        EnumDirection enumdirection = (EnumDirection) this.level().getBlockState(blockposition).getValue(BlockFacingHorizontal.FACING);
-
+    // CraftBukkit start - moved bed result checks from below into separate method
+    private Either<EntityHuman.EnumBedResult, Unit> getBedResult(BlockPosition blockposition, EnumDirection enumdirection) {
         if (!this.isSleeping() && this.isAlive()) {
-            if (!this.level().dimensionType().natural()) {
+            if (!this.level().dimensionType().natural() || !this.level().dimensionType().bedWorks()) {
                 return Either.left(EntityHuman.EnumBedResult.NOT_POSSIBLE_HERE);
             } else if (!this.bedInRange(blockposition, enumdirection)) {
                 return Either.left(EntityHuman.EnumBedResult.TOO_FAR_AWAY);
             } else if (this.bedBlocked(blockposition, enumdirection)) {
                 return Either.left(EntityHuman.EnumBedResult.OBSTRUCTED);
             } else {
-                this.setRespawnPosition(this.level().dimension(), blockposition, this.getYRot(), false, true);
+                this.setRespawnPosition(this.level().dimension(), blockposition, this.getYRot(), false, true, PlayerSpawnChangeEvent.Cause.BED); // CraftBukkit
                 if (this.level().isDay()) {
                     return Either.left(EntityHuman.EnumBedResult.NOT_POSSIBLE_NOW);
                 } else {
@@ -1288,7 +1608,36 @@
                         }
                     }
 
-                    Either<EntityHuman.EnumBedResult, Unit> either = super.startSleepInBed(blockposition).ifRight((unit) -> {
+                    return Either.right(Unit.INSTANCE);
+                }
+            }
+        } else {
+            return Either.left(EntityHuman.EnumBedResult.OTHER_PROBLEM);
+        }
+    }
+
+    @Override
+    public Either<EntityHuman.EnumBedResult, Unit> startSleepInBed(BlockPosition blockposition, boolean force) {
+        EnumDirection enumdirection = (EnumDirection) this.level().getBlockState(blockposition).getValue(BlockFacingHorizontal.FACING);
+        Either<EntityHuman.EnumBedResult, Unit> bedResult = this.getBedResult(blockposition, enumdirection);
+
+        if (bedResult.left().orElse(null) == EntityHuman.EnumBedResult.OTHER_PROBLEM) {
+            return bedResult; // return immediately if the result is not bypassable by plugins
+        }
+
+        if (force) {
+            bedResult = Either.right(Unit.INSTANCE);
+        }
+
+        bedResult = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerBedEnterEvent(this, blockposition, bedResult);
+        if (bedResult.left().isPresent()) {
+            return bedResult;
+        }
+
+        {
+            {
+                {
+                    Either<EntityHuman.EnumBedResult, Unit> either = super.startSleepInBed(blockposition, force).ifRight((unit) -> {
                         this.awardStat(StatisticList.SLEEP_IN_BED);
                         CriterionTriggers.SLEPT_IN_BED.trigger(this);
                     });
@@ -1301,9 +1650,8 @@
                     return either;
                 }
             }
-        } else {
-            return Either.left(EntityHuman.EnumBedResult.OTHER_PROBLEM);
         }
+        // CraftBukkit end
     }
 
     @Override
@@ -1330,13 +1678,31 @@
 
     @Override
     public void stopSleepInBed(boolean flag, boolean flag1) {
+        if (!this.isSleeping()) return; // CraftBukkit - Can't leave bed if not in one!
+        // CraftBukkit start - fire PlayerBedLeaveEvent
+        CraftPlayer player = this.getBukkitEntity();
+        BlockPosition bedPosition = this.getSleepingPos().orElse(null);
+
+        org.bukkit.block.Block bed;
+        if (bedPosition != null) {
+            bed = this.level().getWorld().getBlockAt(bedPosition.getX(), bedPosition.getY(), bedPosition.getZ());
+        } else {
+            bed = this.level().getWorld().getBlockAt(player.getLocation());
+        }
+
+        PlayerBedLeaveEvent event = new PlayerBedLeaveEvent(player, bed, true);
+        this.level().getCraftServer().getPluginManager().callEvent(event);
+        if (event.isCancelled()) {
+            return;
+        }
+        // CraftBukkit end
         if (this.isSleeping()) {
             this.serverLevel().getChunkSource().broadcastAndSend(this, new PacketPlayOutAnimation(this, 2));
         }
 
         super.stopSleepInBed(flag, flag1);
         if (this.connection != null) {
-            this.connection.teleport(this.getX(), this.getY(), this.getZ(), this.getYRot(), this.getXRot());
+            this.connection.teleport(this.getX(), this.getY(), this.getZ(), this.getYRot(), this.getXRot(), TeleportCause.EXIT_BED); // CraftBukkit
         }
 
     }
@@ -1403,8 +1769,9 @@
         this.connection.send(new PacketPlayOutOpenSignEditor(tileentitysign.getBlockPos(), flag));
     }
 
-    public void nextContainerCounter() {
+    public int nextContainerCounter() { // CraftBukkit - void -> int
         this.containerCounter = this.containerCounter % 100 + 1;
+        return containerCounter; // CraftBukkit
     }
 
     @Override
@@ -1412,13 +1779,35 @@
         if (itileinventory == null) {
             return OptionalInt.empty();
         } else {
+            // CraftBukkit start - SPIGOT-6552: Handle inventory closing in CraftEventFactory#callInventoryOpenEvent(...)
+            /*
             if (this.containerMenu != this.inventoryMenu) {
                 this.closeContainer();
             }
+            */
+            // CraftBukkit end
 
             this.nextContainerCounter();
             Container container = itileinventory.createMenu(this.containerCounter, this.getInventory(), this);
 
+            // CraftBukkit start - Inventory open hook
+            if (container != null) {
+                container.setTitle(itileinventory.getDisplayName());
+
+                boolean cancelled = false;
+                container = CraftEventFactory.callInventoryOpenEvent(this, container, cancelled);
+                if (container == null && !cancelled) { // Let pre-cancelled events fall through
+                    // SPIGOT-5263 - close chest if cancelled
+                    if (itileinventory instanceof IInventory) {
+                        ((IInventory) itileinventory).stopOpen(this);
+                    } else if (itileinventory instanceof BlockChest.DoubleInventory) {
+                        // SPIGOT-5355 - double chests too :(
+                        ((BlockChest.DoubleInventory) itileinventory).inventorylargechest.stopOpen(this);
+                    }
+                    return OptionalInt.empty();
+                }
+            }
+            // CraftBukkit end
             if (container == null) {
                 if (this.isSpectator()) {
                     this.displayClientMessage(IChatBaseComponent.translatable("container.spectatorCantOpen").withStyle(EnumChatFormat.RED), true);
@@ -1426,9 +1815,11 @@
 
                 return OptionalInt.empty();
             } else {
-                this.connection.send(new PacketPlayOutOpenWindow(container.containerId, container.getType(), itileinventory.getDisplayName()));
-                this.initMenu(container);
+                // CraftBukkit start
                 this.containerMenu = container;
+                this.connection.send(new PacketPlayOutOpenWindow(container.containerId, container.getType(), container.getTitle()));
+                // CraftBukkit end
+                this.initMenu(container);
                 return OptionalInt.of(this.containerCounter);
             }
         }
@@ -1441,15 +1832,26 @@
 
     @Override
     public void openHorseInventory(EntityHorseAbstract entityhorseabstract, IInventory iinventory) {
+        // CraftBukkit start - Inventory open hook
+        this.nextContainerCounter();
+        Container container = new ContainerHorse(this.containerCounter, this.getInventory(), iinventory, entityhorseabstract, entityhorseabstract.getInventoryColumns());
+        container.setTitle(entityhorseabstract.getDisplayName());
+        container = CraftEventFactory.callInventoryOpenEvent(this, container);
+
+        if (container == null) {
+            iinventory.stopOpen(this);
+            return;
+        }
+        // CraftBukkit end
         if (this.containerMenu != this.inventoryMenu) {
             this.closeContainer();
         }
 
-        this.nextContainerCounter();
+        // this.nextContainerCounter(); // CraftBukkit - moved up
         int i = entityhorseabstract.getInventoryColumns();
 
         this.connection.send(new PacketPlayOutOpenWindowHorse(this.containerCounter, i, entityhorseabstract.getId()));
-        this.containerMenu = new ContainerHorse(this.containerCounter, this.getInventory(), iinventory, entityhorseabstract, i);
+        this.containerMenu = container; // CraftBukkit
         this.initMenu(this.containerMenu);
     }
 
@@ -1472,6 +1874,7 @@
 
     @Override
     public void closeContainer() {
+        CraftEventFactory.handleInventoryCloseEvent(this); // CraftBukkit
         this.connection.send(new PacketPlayOutCloseWindow(this.containerMenu.containerId));
         this.doCloseContainer();
     }
@@ -1501,19 +1904,19 @@
                 i = Math.round((float) Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2) * 100.0F);
                 if (i > 0) {
                     this.awardStat(StatisticList.SWIM_ONE_CM, i);
-                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F);
+                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.SWIM); // CraftBukkit - EntityExhaustionEvent
                 }
             } else if (this.isEyeInFluid(TagsFluid.WATER)) {
                 i = Math.round((float) Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2) * 100.0F);
                 if (i > 0) {
                     this.awardStat(StatisticList.WALK_UNDER_WATER_ONE_CM, i);
-                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F);
+                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.WALK_UNDERWATER); // CraftBukkit - EntityExhaustionEvent
                 }
             } else if (this.isInWater()) {
                 i = Math.round((float) Math.sqrt(d0 * d0 + d2 * d2) * 100.0F);
                 if (i > 0) {
                     this.awardStat(StatisticList.WALK_ON_WATER_ONE_CM, i);
-                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F);
+                    this.causeFoodExhaustion(0.01F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.WALK_ON_WATER); // CraftBukkit - EntityExhaustionEvent
                 }
             } else if (this.onClimbable()) {
                 if (d1 > 0.0D) {
@@ -1524,13 +1927,13 @@
                 if (i > 0) {
                     if (this.isSprinting()) {
                         this.awardStat(StatisticList.SPRINT_ONE_CM, i);
-                        this.causeFoodExhaustion(0.1F * (float) i * 0.01F);
+                        this.causeFoodExhaustion(0.1F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.SPRINT); // CraftBukkit - EntityExhaustionEvent
                     } else if (this.isCrouching()) {
                         this.awardStat(StatisticList.CROUCH_ONE_CM, i);
-                        this.causeFoodExhaustion(0.0F * (float) i * 0.01F);
+                        this.causeFoodExhaustion(0.0F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.CROUCH); // CraftBukkit - EntityExhaustionEvent
                     } else {
                         this.awardStat(StatisticList.WALK_ONE_CM, i);
-                        this.causeFoodExhaustion(0.0F * (float) i * 0.01F);
+                        this.causeFoodExhaustion(0.0F * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.WALK); // CraftBukkit - EntityExhaustionEvent
                     }
                 }
             } else if (this.isFallFlying()) {
@@ -1573,7 +1976,7 @@
     @Override
     public void awardStat(Statistic<?> statistic, int i) {
         this.stats.increment(this, statistic, i);
-        this.getScoreboard().forAllObjectives(statistic, this, (scoreaccess) -> {
+        this.level().getCraftServer().getScoreboardManager().forAllObjectives(statistic, this, (scoreaccess) -> {
             scoreaccess.add(i);
         });
     }
@@ -1581,7 +1984,7 @@
     @Override
     public void resetStat(Statistic<?> statistic) {
         this.stats.setValue(this, statistic, 0);
-        this.getScoreboard().forAllObjectives(statistic, this, ScoreAccess::reset);
+        this.level().getCraftServer().getScoreboardManager().forAllObjectives(statistic, this, ScoreAccess::reset); // CraftBukkit - Get our scores instead
     }
 
     @Override
@@ -1613,9 +2016,9 @@
         super.jumpFromGround();
         this.awardStat(StatisticList.JUMP);
         if (this.isSprinting()) {
-            this.causeFoodExhaustion(0.2F);
+            this.causeFoodExhaustion(0.2F, EntityExhaustionEvent.ExhaustionReason.JUMP_SPRINT); // CraftBukkit - EntityExhaustionEvent
         } else {
-            this.causeFoodExhaustion(0.05F);
+            this.causeFoodExhaustion(0.05F, EntityExhaustionEvent.ExhaustionReason.JUMP); // CraftBukkit - EntityExhaustionEvent
         }
 
     }
@@ -1641,6 +2044,7 @@
 
     public void resetSentInfo() {
         this.lastSentHealth = -1.0E8F;
+        this.lastSentExp = -1; // CraftBukkit - Added to reset
     }
 
     @Override
@@ -1685,7 +2089,7 @@
             while (iterator.hasNext()) {
                 MobEffect mobeffect = (MobEffect) iterator.next();
 
-                this.addEffect(new MobEffect(mobeffect));
+                // this.addEffect(new MobEffect(mobeffect)); // CraftBukkit
             }
 
             this.getInventory().replaceWith(entityplayer.getInventory());
@@ -1696,7 +2100,7 @@
             this.portalProcess = entityplayer.portalProcess;
         } else {
             this.getAttributes().assignBaseValues(entityplayer.getAttributes());
-            this.setHealth(this.getMaxHealth());
+            // this.setHealth(this.getMaxHealth()); // CraftBukkit
             if (this.serverLevel().getGameRules().getBoolean(GameRules.RULE_KEEPINVENTORY) || entityplayer.isSpectator()) {
                 this.getInventory().replaceWith(entityplayer.getInventory());
                 this.experienceLevel = entityplayer.experienceLevel;
@@ -1712,7 +2116,7 @@
         this.lastSentExp = -1;
         this.lastSentHealth = -1.0F;
         this.lastSentFood = -1;
-        this.recipeBook.copyOverData(entityplayer.recipeBook);
+        // this.recipeBook.copyOverData(entityplayer.recipeBook); // CraftBukkit
         this.seenCredits = entityplayer.seenCredits;
         this.enteredNetherPosition = entityplayer.enteredNetherPosition;
         this.chunkTrackingView = entityplayer.chunkTrackingView;
@@ -1768,7 +2172,7 @@
     }
 
     @Override
-    public boolean teleportTo(WorldServer worldserver, double d0, double d1, double d2, Set<Relative> set, float f, float f1, boolean flag) {
+    public boolean teleportTo(WorldServer worldserver, double d0, double d1, double d2, Set<Relative> set, float f, float f1, boolean flag, TeleportCause cause) { // CraftBukkit
         ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(BlockPosition.containing(d0, d1, d2));
 
         worldserver.getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, chunkcoordintpair, 1, this.getId());
@@ -1780,7 +2184,7 @@
             this.setCamera(this);
         }
 
-        boolean flag1 = super.teleportTo(worldserver, d0, d1, d2, set, f, f1, flag);
+        boolean flag1 = super.teleportTo(worldserver, d0, d1, d2, set, f, f1, flag, cause); // CraftBukkit
 
         if (flag1) {
             this.setYHeadRot(set.contains(Relative.Y_ROT) ? this.getYHeadRot() + f : f);
@@ -1897,6 +2301,16 @@
     }
 
     public void updateOptions(ClientInformation clientinformation) {
+        // CraftBukkit start
+        if (getMainArm() != clientinformation.mainHand()) {
+            PlayerChangedMainHandEvent event = new PlayerChangedMainHandEvent(getBukkitEntity(), getMainArm() == EnumMainHand.LEFT ? MainHand.LEFT : MainHand.RIGHT);
+            this.server.server.getPluginManager().callEvent(event);
+        }
+        if (!this.language.equals(clientinformation.language())) {
+            PlayerLocaleChangeEvent event = new PlayerLocaleChangeEvent(getBukkitEntity(), clientinformation.language());
+            this.server.server.getPluginManager().callEvent(event);
+        }
+        // CraftBukkit end
         this.language = clientinformation.language();
         this.requestedViewDistance = clientinformation.viewDistance();
         this.chatVisibility = clientinformation.chatVisibility();
@@ -1981,7 +2395,7 @@
             if (world instanceof WorldServer) {
                 WorldServer worldserver = (WorldServer) world;
 
-                this.teleportTo(worldserver, this.camera.getX(), this.camera.getY(), this.camera.getZ(), Set.of(), this.getYRot(), this.getXRot(), false);
+                this.teleportTo(worldserver, this.camera.getX(), this.camera.getY(), this.camera.getZ(), Set.of(), this.getYRot(), this.getXRot(), false, TeleportCause.SPECTATE); // CraftBukkit
             }
 
             if (entity != null) {
@@ -2018,11 +2432,11 @@
 
     @Nullable
     public IChatBaseComponent getTabListDisplayName() {
-        return null;
+        return listName; // CraftBukkit
     }
 
     public int getTabListOrder() {
-        return 0;
+        return listOrder; // CraftBukkit
     }
 
     @Override
@@ -2065,6 +2479,32 @@
     }
 
     public void setRespawnPosition(ResourceKey<World> resourcekey, @Nullable BlockPosition blockposition, float f, boolean flag, boolean flag1) {
+        // CraftBukkit start
+        this.setRespawnPosition(resourcekey, blockposition, f, flag, flag1, PlayerSpawnChangeEvent.Cause.UNKNOWN);
+    }
+
+    public void setRespawnPosition(ResourceKey<World> resourcekey, @Nullable BlockPosition blockposition, float f, boolean flag, boolean flag1, PlayerSpawnChangeEvent.Cause cause) {
+        WorldServer newWorld = this.server.getLevel(resourcekey);
+        Location newSpawn = (blockposition != null) ? CraftLocation.toBukkit(blockposition, newWorld.getWorld(), f, 0) : null;
+
+        PlayerSpawnChangeEvent event = new PlayerSpawnChangeEvent(this.getBukkitEntity(), newSpawn, flag, cause);
+        Bukkit.getServer().getPluginManager().callEvent(event);
+        if (event.isCancelled()) {
+            return;
+        }
+        newSpawn = event.getNewSpawn();
+        flag = event.isForced();
+
+        if (newSpawn != null) {
+            resourcekey = ((CraftWorld) newSpawn.getWorld()).getHandle().dimension();
+            blockposition = BlockPosition.containing(newSpawn.getX(), newSpawn.getY(), newSpawn.getZ());
+            f = newSpawn.getYaw();
+        } else {
+            resourcekey = World.OVERWORLD;
+            blockposition = null;
+            f = 0.0F;
+        }
+        // CraftBukkit end
         if (blockposition != null) {
             boolean flag2 = blockposition.equals(this.respawnPosition) && resourcekey.equals(this.respawnDimension);
 
@@ -2107,12 +2547,38 @@
     }
 
     @Override
-    public EntityItem drop(ItemStack itemstack, boolean flag, boolean flag1) {
+    public EntityItem drop(ItemStack itemstack, boolean flag, boolean flag1, boolean callEvent) { // CraftBukkit - SPIGOT-2942: Add boolean to call event
         EntityItem entityitem = this.createItemStackToDrop(itemstack, flag, flag1);
 
         if (entityitem == null) {
             return null;
         } else {
+            // CraftBukkit start - fire PlayerDropItemEvent
+            if (callEvent) {
+                Player player = (Player) this.getBukkitEntity();
+                org.bukkit.entity.Item drop = (org.bukkit.entity.Item) entityitem.getBukkitEntity();
+
+                PlayerDropItemEvent event = new PlayerDropItemEvent(player, drop);
+                this.level().getCraftServer().getPluginManager().callEvent(event);
+
+                if (event.isCancelled()) {
+                    org.bukkit.inventory.ItemStack cur = player.getInventory().getItemInHand();
+                    if (flag1 && (cur == null || cur.getAmount() == 0)) {
+                        // The complete stack was dropped
+                        player.getInventory().setItemInHand(drop.getItemStack());
+                    } else if (flag1 && cur.isSimilar(drop.getItemStack()) && cur.getAmount() < cur.getMaxStackSize() && drop.getItemStack().getAmount() == 1) {
+                        // Only one item is dropped
+                        cur.setAmount(cur.getAmount() + 1);
+                        player.getInventory().setItemInHand(cur);
+                    } else {
+                        // Fallback
+                        player.getInventory().addItem(drop.getItemStack());
+                    }
+                    return null;
+                }
+            }
+            // CraftBukkit end
+
             this.level().addFreshEntity(entityitem);
             ItemStack itemstack1 = entityitem.getItem();
 
@@ -2394,10 +2860,12 @@
         return TicketType.ENDER_PEARL.timeout();
     }
 
-    public static record RespawnPosAngle(Vec3D position, float yaw) {
+    // CraftBukkit start
+    public static record RespawnPosAngle(Vec3D position, float yaw, boolean isBedSpawn, boolean isAnchorSpawn) {
 
-        public static EntityPlayer.RespawnPosAngle of(Vec3D vec3d, BlockPosition blockposition) {
-            return new EntityPlayer.RespawnPosAngle(vec3d, calculateLookAtYaw(vec3d, blockposition));
+        public static EntityPlayer.RespawnPosAngle of(Vec3D vec3d, BlockPosition blockposition, boolean isBedSpawn, boolean isAnchorSpawn) {
+            return new EntityPlayer.RespawnPosAngle(vec3d, calculateLookAtYaw(vec3d, blockposition), isBedSpawn, isAnchorSpawn);
+            // CraftBukkit end
         }
 
         private static float calculateLookAtYaw(Vec3D vec3d, BlockPosition blockposition) {
@@ -2406,4 +2874,146 @@
             return (float) MathHelper.wrapDegrees(MathHelper.atan2(vec3d1.z, vec3d1.x) * 57.2957763671875D - 90.0D);
         }
     }
+
+    // CraftBukkit start - Add per-player time and weather.
+    public long timeOffset = 0;
+    public boolean relativeTime = true;
+
+    public long getPlayerTime() {
+        if (this.relativeTime) {
+            // Adds timeOffset to the current server time.
+            return this.level().getDayTime() + this.timeOffset;
+        } else {
+            // Adds timeOffset to the beginning of this day.
+            return this.level().getDayTime() - (this.level().getDayTime() % 24000) + this.timeOffset;
+        }
+    }
+
+    public WeatherType weather = null;
+
+    public WeatherType getPlayerWeather() {
+        return this.weather;
+    }
+
+    public void setPlayerWeather(WeatherType type, boolean plugin) {
+        if (!plugin && this.weather != null) {
+            return;
+        }
+
+        if (plugin) {
+            this.weather = type;
+        }
+
+        if (type == WeatherType.DOWNFALL) {
+            this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.STOP_RAINING, 0));
+        } else {
+            this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.START_RAINING, 0));
+        }
+    }
+
+    private float pluginRainPosition;
+    private float pluginRainPositionPrevious;
+
+    public void updateWeather(float oldRain, float newRain, float oldThunder, float newThunder) {
+        if (this.weather == null) {
+            // Vanilla
+            if (oldRain != newRain) {
+                this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.RAIN_LEVEL_CHANGE, newRain));
+            }
+        } else {
+            // Plugin
+            if (pluginRainPositionPrevious != pluginRainPosition) {
+                this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.RAIN_LEVEL_CHANGE, pluginRainPosition));
+            }
+        }
+
+        if (oldThunder != newThunder) {
+            if (weather == WeatherType.DOWNFALL || weather == null) {
+                this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.THUNDER_LEVEL_CHANGE, newThunder));
+            } else {
+                this.connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.THUNDER_LEVEL_CHANGE, 0));
+            }
+        }
+    }
+
+    public void tickWeather() {
+        if (this.weather == null) return;
+
+        pluginRainPositionPrevious = pluginRainPosition;
+        if (weather == WeatherType.DOWNFALL) {
+            pluginRainPosition += 0.01;
+        } else {
+            pluginRainPosition -= 0.01;
+        }
+
+        pluginRainPosition = MathHelper.clamp(pluginRainPosition, 0.0F, 1.0F);
+    }
+
+    public void resetPlayerWeather() {
+        this.weather = null;
+        this.setPlayerWeather(this.level().getLevelData().isRaining() ? WeatherType.DOWNFALL : WeatherType.CLEAR, false);
+    }
+
+    @Override
+    public String toString() {
+        return super.toString() + "(" + this.getScoreboardName() + " at " + this.getX() + "," + this.getY() + "," + this.getZ() + ")";
+    }
+
+    // SPIGOT-1903, MC-98153
+    public void forceSetPositionRotation(double x, double y, double z, float yaw, float pitch) {
+        this.moveTo(x, y, z, yaw, pitch);
+        this.connection.resetPosition();
+    }
+
+    @Override
+    public boolean isImmobile() {
+        return super.isImmobile() || !getBukkitEntity().isOnline();
+    }
+
+    @Override
+    public Scoreboard getScoreboard() {
+        return getBukkitEntity().getScoreboard().getHandle();
+    }
+
+    public void reset() {
+        float exp = 0;
+
+        if (this.keepLevel) { // CraftBukkit - SPIGOT-6687: Only use keepLevel (was pre-set with RULE_KEEPINVENTORY value in PlayerDeathEvent)
+            exp = this.experienceProgress;
+            this.newTotalExp = this.totalExperience;
+            this.newLevel = this.experienceLevel;
+        }
+
+        this.setHealth(this.getMaxHealth());
+        this.stopUsingItem(); // CraftBukkit - SPIGOT-6682: Clear active item on reset
+        this.setRemainingFireTicks(0);
+        this.fallDistance = 0;
+        this.foodData = new FoodMetaData();
+        this.experienceLevel = this.newLevel;
+        this.totalExperience = this.newTotalExp;
+        this.experienceProgress = 0;
+        this.deathTime = 0;
+        this.setArrowCount(0, true); // CraftBukkit - ArrowBodyCountChangeEvent
+        this.removeAllEffects(org.bukkit.event.entity.EntityPotionEffectEvent.Cause.DEATH);
+        this.effectsDirty = true;
+        this.containerMenu = this.inventoryMenu;
+        this.lastHurtByPlayer = null;
+        this.lastHurtByMob = null;
+        this.combatTracker = new CombatTracker(this);
+        this.lastSentExp = -1;
+        if (this.keepLevel) { // CraftBukkit - SPIGOT-6687: Only use keepLevel (was pre-set with RULE_KEEPINVENTORY value in PlayerDeathEvent)
+            this.experienceProgress = exp;
+        } else {
+            this.giveExperiencePoints(this.newExp);
+        }
+        this.keepLevel = false;
+        this.setDeltaMovement(0, 0, 0); // CraftBukkit - SPIGOT-6948: Reset velocity on death
+        this.skipDropExperience = false; // CraftBukkit - SPIGOT-7462: Reset experience drop skip, so that further deaths drop xp
+    }
+
+    @Override
+    public CraftPlayer getBukkitEntity() {
+        return (CraftPlayer) super.getBukkitEntity();
+    }
+    // CraftBukkit end
 }