--- a/net/minecraft/server/players/PlayerList.java +++ b/net/minecraft/server/players/PlayerList.java @@ -95,6 +95,26 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +// CraftBukkit start +import com.google.common.base.Predicate; +import java.util.stream.Collectors; +import net.minecraft.network.protocol.game.PacketPlayOutChat; +import net.minecraft.network.protocol.game.PacketPlayOutEntityMetadata; +import net.minecraft.server.dedicated.DedicatedServer; +import net.minecraft.server.network.LoginListener; +import org.bukkit.Location; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +// CraftBukkit end + public abstract class PlayerList { public static final File USERBANLIST_FILE = new File("banned-players.json"); @@ -105,14 +125,16 @@ private static final int SEND_PLAYER_INFO_INTERVAL = 600; private static final SimpleDateFormat BAN_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); private final MinecraftServer server; - public final List players = Lists.newArrayList(); + public final List players = new java.util.concurrent.CopyOnWriteArrayList(); // CraftBukkit - ArrayList -> CopyOnWriteArrayList: Iterator safety private final Map playersByUUID = Maps.newHashMap(); private final GameProfileBanList bans; private final IpBanList ipBans; private final OpList ops; private final WhiteList whitelist; - private final Map stats; - private final Map advancements; + // CraftBukkit start + // private final Map stats; + // private final Map advancements; + // CraftBukkit end public final WorldNBTStorage playerIo; private boolean doWhiteList; private final IRegistryCustom.Dimension registryHolder; @@ -122,13 +144,23 @@ private static final boolean ALLOW_LOGOUTIVATOR = false; private int sendAllPlayerInfoIn; + // CraftBukkit start + private CraftServer cserver; + public PlayerList(MinecraftServer minecraftserver, IRegistryCustom.Dimension iregistrycustom_dimension, WorldNBTStorage worldnbtstorage, int i) { + this.cserver = minecraftserver.server = new CraftServer((DedicatedServer) minecraftserver, this); + minecraftserver.console = org.bukkit.craftbukkit.command.ColouredConsoleSender.getInstance(); + minecraftserver.reader.addCompleter(new org.bukkit.craftbukkit.command.ConsoleCommandCompleter(minecraftserver.server)); + // CraftBukkit end + this.bans = new GameProfileBanList(PlayerList.USERBANLIST_FILE); this.ipBans = new IpBanList(PlayerList.IPBANLIST_FILE); this.ops = new OpList(PlayerList.OPLIST_FILE); this.whitelist = new WhiteList(PlayerList.WHITELIST_FILE); - this.stats = Maps.newHashMap(); - this.advancements = Maps.newHashMap(); + // CraftBukkit start + // this.stats = Maps.newHashMap(); + // this.advancements = Maps.newHashMap(); + // CraftBukkit end this.server = minecraftserver; this.registryHolder = iregistrycustom_dimension; this.maxPlayers = i; @@ -144,6 +176,12 @@ usercache.a(gameprofile); NBTTagCompound nbttagcompound = this.a(entityplayer); ResourceKey resourcekey; + // CraftBukkit start - Better rename detection + if (nbttagcompound != null && nbttagcompound.hasKey("bukkit")) { + NBTTagCompound bukkit = nbttagcompound.getCompound("bukkit"); + s = bukkit.hasKeyOfType("lastKnownName", 8) ? bukkit.getString("lastKnownName") : s; + } + // CraftBukkit end if (nbttagcompound != null) { DataResult dataresult = DimensionManager.a(new Dynamic(DynamicOpsNBT.INSTANCE, nbttagcompound.get("Dimension"))); @@ -173,7 +211,8 @@ s1 = networkmanager.getSocketAddress().toString(); } - PlayerList.LOGGER.info("{}[{}] logged in with entity id {} at ({}, {}, {})", entityplayer.getDisplayName().getString(), s1, entityplayer.getId(), entityplayer.locX(), entityplayer.locY(), entityplayer.locZ()); + // CraftBukkit - Moved message to after join + // PlayerList.LOGGER.info("{}[{}] logged in with entity id {} at ({}, {}, {})", entityplayer.getDisplayName().getString(), s1, entityplayer.getId(), entityplayer.locX(), entityplayer.locY(), entityplayer.locZ()); WorldData worlddata = worldserver1.getWorldData(); entityplayer.c(nbttagcompound); @@ -183,6 +222,7 @@ boolean flag1 = gamerules.getBoolean(GameRules.RULE_REDUCEDDEBUGINFO); playerconnection.sendPacket(new PacketPlayOutLogin(entityplayer.getId(), entityplayer.gameMode.getGameMode(), entityplayer.gameMode.c(), BiomeManager.a(worldserver1.getSeed()), worlddata.isHardcore(), this.server.F(), this.registryHolder, worldserver1.getDimensionManager(), worldserver1.getDimensionKey(), this.getMaxPlayers(), this.viewDistance, flag1, !flag, worldserver1.isDebugWorld(), worldserver1.isFlatWorld())); + entityplayer.getBukkitEntity().sendSupportedChannels(); // CraftBukkit playerconnection.sendPacket(new PacketPlayOutCustomPayload(PacketPlayOutCustomPayload.BRAND, (new PacketDataSerializer(Unpooled.buffer())).a(this.getServer().getServerModName()))); playerconnection.sendPacket(new PacketPlayOutServerDifficulty(worlddata.getDifficulty(), worlddata.isDifficultyLocked())); playerconnection.sendPacket(new PacketPlayOutAbilities(entityplayer.getAbilities())); @@ -201,19 +241,66 @@ } else { chatmessage = new ChatMessage("multiplayer.player.joined.renamed", new Object[]{entityplayer.getScoreboardDisplayName(), s}); } + // CraftBukkit start + chatmessage.a(EnumChatFormat.YELLOW); + String joinMessage = CraftChatMessage.fromComponent(chatmessage); - this.sendMessage(chatmessage.a(EnumChatFormat.YELLOW), ChatMessageType.SYSTEM, SystemUtils.NIL_UUID); playerconnection.b(entityplayer.locX(), entityplayer.locY(), entityplayer.locZ(), entityplayer.getYRot(), entityplayer.getXRot()); this.players.add(entityplayer); this.playersByUUID.put(entityplayer.getUniqueID(), entityplayer); - this.sendAll(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, new EntityPlayer[]{entityplayer})); + // this.sendAll(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, new EntityPlayer[]{entityplayer})); // CraftBukkit - replaced with loop below + + // CraftBukkit start + CraftPlayer bukkitPlayer = entityplayer.getBukkitEntity(); + + // Ensure that player inventory is populated with its viewer + entityplayer.containerMenu.transferTo(entityplayer.containerMenu, bukkitPlayer); + + PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(bukkitPlayer, joinMessage); + cserver.getPluginManager().callEvent(playerJoinEvent); + + if (!entityplayer.connection.connection.isConnected()) { + return; + } + + joinMessage = playerJoinEvent.getJoinMessage(); + + if (joinMessage != null && joinMessage.length() > 0) { + for (IChatBaseComponent line : org.bukkit.craftbukkit.util.CraftChatMessage.fromString(joinMessage)) { + server.getPlayerList().sendAll(new PacketPlayOutChat(line, ChatMessageType.SYSTEM, SystemUtils.NIL_UUID)); + } + } + // CraftBukkit end + + // CraftBukkit start - sendAll above replaced with this loop + PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, entityplayer); for (int i = 0; i < this.players.size(); ++i) { - entityplayer.connection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, new EntityPlayer[]{(EntityPlayer) this.players.get(i)})); + EntityPlayer entityplayer1 = (EntityPlayer) this.players.get(i); + + if (entityplayer1.getBukkitEntity().canSee(bukkitPlayer)) { + entityplayer1.connection.sendPacket(packet); + } + + if (!bukkitPlayer.canSee(entityplayer1.getBukkitEntity())) { + continue; + } + + entityplayer.connection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, new EntityPlayer[] { entityplayer1})); } + entityplayer.sentListPacket = true; + // CraftBukkit end - worldserver1.addPlayerJoin(entityplayer); - this.server.getBossBattleCustomData().a(entityplayer); + entityplayer.connection.sendPacket(new PacketPlayOutEntityMetadata(entityplayer.getId(), entityplayer.getDataWatcher(), true)); // CraftBukkit - BungeeCord#2321, send complete data to self on spawn + + // CraftBukkit start - Only add if the player wasn't moved in the event + if (entityplayer.level == worldserver1 && !worldserver1.getPlayers().contains(entityplayer)) { + worldserver1.addPlayerJoin(entityplayer); + this.server.getBossBattleCustomData().a(entityplayer); + } + + worldserver1 = entityplayer.getWorldServer(); // CraftBukkit - Update in case join event changed it + // CraftBukkit end this.a(entityplayer, worldserver1); if (!this.server.getResourcePack().isEmpty()) { entityplayer.setResourcePack(this.server.getResourcePack(), this.server.getResourcePackHash(), this.server.aX(), this.server.ba()); @@ -229,8 +316,11 @@ if (nbttagcompound != null && nbttagcompound.hasKeyOfType("RootVehicle", 10)) { NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("RootVehicle"); - Entity entity = EntityTypes.a(nbttagcompound1.getCompound("Entity"), worldserver1, (entity1) -> { - return !worldserver1.addEntitySerialized(entity1) ? null : entity1; + // CraftBukkit start + WorldServer finalWorldServer = worldserver1; + Entity entity = EntityTypes.a(nbttagcompound1.getCompound("Entity"), finalWorldServer, (entity1) -> { + return !finalWorldServer.addEntitySerialized(entity1) ? null : entity1; + // CraftBukkit end }); if (entity != null) { @@ -273,6 +363,8 @@ } entityplayer.syncInventory(); + // CraftBukkit - Moved from above, added world + PlayerList.LOGGER.info("{}[{}] logged in with entity id {} at ([{}]{}, {}, {})", entityplayer.getDisplayName().getString(), s1, entityplayer.getId(), worldserver1.serverLevelData.getName(), entityplayer.locX(), entityplayer.locY(), entityplayer.locZ()); } public void sendScoreboard(ScoreboardServer scoreboardserver, EntityPlayer entityplayer) { @@ -305,30 +397,31 @@ } public void setPlayerFileData(WorldServer worldserver) { + if (playerIo != null) return; // CraftBukkit worldserver.getWorldBorder().a(new IWorldBorderListener() { @Override public void a(WorldBorder worldborder, double d0) { - PlayerList.this.sendAll(new ClientboundSetBorderSizePacket(worldborder)); + PlayerList.this.sendAll(new ClientboundSetBorderSizePacket(worldborder), worldborder.world); // CraftBukkit } @Override public void a(WorldBorder worldborder, double d0, double d1, long i) { - PlayerList.this.sendAll(new ClientboundSetBorderLerpSizePacket(worldborder)); + PlayerList.this.sendAll(new ClientboundSetBorderLerpSizePacket(worldborder), worldborder.world); // CraftBukkit } @Override public void a(WorldBorder worldborder, double d0, double d1) { - PlayerList.this.sendAll(new ClientboundSetBorderCenterPacket(worldborder)); + PlayerList.this.sendAll(new ClientboundSetBorderCenterPacket(worldborder), worldborder.world); // CraftBukkit } @Override public void a(WorldBorder worldborder, int i) { - PlayerList.this.sendAll(new ClientboundSetBorderWarningDelayPacket(worldborder)); + PlayerList.this.sendAll(new ClientboundSetBorderWarningDelayPacket(worldborder), worldborder.world); // CraftBukkit } @Override public void b(WorldBorder worldborder, int i) { - PlayerList.this.sendAll(new ClientboundSetBorderWarningDistancePacket(worldborder)); + PlayerList.this.sendAll(new ClientboundSetBorderWarningDistancePacket(worldborder), worldborder.world); // CraftBukkit } @Override @@ -356,14 +449,15 @@ } protected void savePlayerFile(EntityPlayer entityplayer) { + if (!entityplayer.getBukkitEntity().isPersistent()) return; // CraftBukkit this.playerIo.save(entityplayer); - ServerStatisticManager serverstatisticmanager = (ServerStatisticManager) this.stats.get(entityplayer.getUniqueID()); + ServerStatisticManager serverstatisticmanager = (ServerStatisticManager) entityplayer.getStatisticManager(); // CraftBukkit if (serverstatisticmanager != null) { serverstatisticmanager.save(); } - AdvancementDataPlayer advancementdataplayer = (AdvancementDataPlayer) this.advancements.get(entityplayer.getUniqueID()); + AdvancementDataPlayer advancementdataplayer = (AdvancementDataPlayer) entityplayer.getAdvancementData(); // CraftBukkit if (advancementdataplayer != null) { advancementdataplayer.b(); @@ -371,10 +465,24 @@ } - public void disconnect(EntityPlayer entityplayer) { + public String disconnect(EntityPlayer entityplayer) { // CraftBukkit - return string WorldServer worldserver = entityplayer.getWorldServer(); entityplayer.a(StatisticList.LEAVE_GAME); + + // CraftBukkit start - Quitting must be before we do final save of data, in case plugins need to modify it + // See SPIGOT-5799, SPIGOT-6145 + if (entityplayer.containerMenu != entityplayer.inventoryMenu) { + entityplayer.closeInventory(); + } + + PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(entityplayer.getBukkitEntity(), "\u00A7e" + entityplayer.getName() + " left the game"); + cserver.getPluginManager().callEvent(playerQuitEvent); + entityplayer.getBukkitEntity().disconnect(playerQuitEvent.getQuitMessage()); + + entityplayer.playerTick(); // SPIGOT-924 + // CraftBukkit end + this.savePlayerFile(entityplayer); if (entityplayer.isPassenger()) { Entity entity = entityplayer.getRootVehicle(); @@ -398,18 +506,66 @@ if (entityplayer1 == entityplayer) { this.playersByUUID.remove(uuid); - this.stats.remove(uuid); - this.advancements.remove(uuid); + // CraftBukkit start + // this.stats.remove(uuid); + // this.advancements.remove(uuid); + // CraftBukkit end + } + + // CraftBukkit start + // this.sendAll(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, new EntityPlayer[]{entityplayer})); + PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, entityplayer); + for (int i = 0; i < players.size(); i++) { + EntityPlayer entityplayer2 = (EntityPlayer) this.players.get(i); + + if (entityplayer2.getBukkitEntity().canSee(entityplayer.getBukkitEntity())) { + entityplayer2.connection.sendPacket(packet); + } else { + entityplayer2.getBukkitEntity().removeDisconnectingPlayer(entityplayer.getBukkitEntity()); + } } + // This removes the scoreboard (and player reference) for the specific player in the manager + cserver.getScoreboardManager().removePlayer(entityplayer.getBukkitEntity()); + // CraftBukkit end - this.sendAll(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, new EntityPlayer[]{entityplayer})); + return playerQuitEvent.getQuitMessage(); // CraftBukkit } - @Nullable - public IChatBaseComponent attemptLogin(SocketAddress socketaddress, GameProfile gameprofile) { + // CraftBukkit start - Whole method, SocketAddress to LoginListener, added hostname to signature, return EntityPlayer + public EntityPlayer attemptLogin(LoginListener loginlistener, GameProfile gameprofile, String hostname) { ChatMessage chatmessage; - if (this.bans.isBanned(gameprofile)) { + // Moved from processLogin + UUID uuid = EntityHuman.a(gameprofile); + List list = Lists.newArrayList(); + + EntityPlayer entityplayer; + + for (int i = 0; i < this.players.size(); ++i) { + entityplayer = (EntityPlayer) this.players.get(i); + if (entityplayer.getUniqueID().equals(uuid)) { + list.add(entityplayer); + } + } + + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + entityplayer = (EntityPlayer) iterator.next(); + savePlayerFile(entityplayer); // CraftBukkit - Force the player's inventory to be saved + entityplayer.connection.disconnect(new ChatMessage("multiplayer.disconnect.duplicate_login", new Object[0])); + } + + // Instead of kicking then returning, we need to store the kick reason + // in the event, check with plugins to see if it's ok, and THEN kick + // depending on the outcome. + SocketAddress socketaddress = loginlistener.connection.getSocketAddress(); + + EntityPlayer entity = new EntityPlayer(this.server, this.server.getWorldServer(World.OVERWORLD), gameprofile); + Player player = entity.getBukkitEntity(); + PlayerLoginEvent event = new PlayerLoginEvent(player, hostname, ((java.net.InetSocketAddress) socketaddress).getAddress()); + + if (getProfileBans().isBanned(gameprofile) && !getProfileBans().get(gameprofile).hasExpired()) { GameProfileBanEntry gameprofilebanentry = (GameProfileBanEntry) this.bans.get(gameprofile); chatmessage = new ChatMessage("multiplayer.disconnect.banned.reason", new Object[]{gameprofilebanentry.getReason()}); @@ -417,10 +573,12 @@ chatmessage.addSibling(new ChatMessage("multiplayer.disconnect.banned.expiration", new Object[]{PlayerList.BAN_DATE_FORMAT.format(gameprofilebanentry.getExpires())})); } - return chatmessage; + // return chatmessage; + event.disallow(PlayerLoginEvent.Result.KICK_BANNED, CraftChatMessage.fromComponent(chatmessage)); } else if (!this.isWhitelisted(gameprofile)) { - return new ChatMessage("multiplayer.disconnect.not_whitelisted"); - } else if (this.ipBans.isBanned(socketaddress)) { + chatmessage = new ChatMessage("multiplayer.disconnect.not_whitelisted"); + event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, CraftChatMessage.fromComponent(chatmessage)); + } else if (getIPBans().isBanned(socketaddress) && !getIPBans().get(socketaddress).hasExpired()) { IpBanEntry ipbanentry = this.ipBans.get(socketaddress); chatmessage = new ChatMessage("multiplayer.disconnect.banned_ip.reason", new Object[]{ipbanentry.getReason()}); @@ -428,13 +586,25 @@ chatmessage.addSibling(new ChatMessage("multiplayer.disconnect.banned_ip.expiration", new Object[]{PlayerList.BAN_DATE_FORMAT.format(ipbanentry.getExpires())})); } - return chatmessage; + // return chatmessage; + event.disallow(PlayerLoginEvent.Result.KICK_BANNED, CraftChatMessage.fromComponent(chatmessage)); } else { - return this.players.size() >= this.maxPlayers && !this.d(gameprofile) ? new ChatMessage("multiplayer.disconnect.server_full") : null; + // return this.players.size() >= this.maxPlayers && !this.d(gameprofile) ? new ChatMessage("multiplayer.disconnect.server_full") : null; + if (this.players.size() >= this.maxPlayers && !this.d(gameprofile)) { + event.disallow(PlayerLoginEvent.Result.KICK_FULL, "The server is full"); + } } + + cserver.getPluginManager().callEvent(event); + if (event.getResult() != PlayerLoginEvent.Result.ALLOWED) { + loginlistener.disconnect(event.getKickMessage()); + return null; + } + return entity; } - public EntityPlayer processLogin(GameProfile gameprofile) { + public EntityPlayer processLogin(GameProfile gameprofile, EntityPlayer player) { // CraftBukkit - added EntityPlayer + /* CraftBukkit startMoved up UUID uuid = EntityHuman.a(gameprofile); List list = Lists.newArrayList(); @@ -461,14 +631,24 @@ } return new EntityPlayer(this.server, this.server.E(), gameprofile); + */ + return player; + // CraftBukkit end } + // CraftBukkit start public EntityPlayer moveToWorld(EntityPlayer entityplayer, boolean flag) { + return this.moveToWorld(entityplayer, this.server.getWorldServer(entityplayer.getSpawnDimension()), flag, null, true); + } + + public EntityPlayer moveToWorld(EntityPlayer entityplayer, WorldServer worldserver, boolean flag, Location location, boolean avoidSuffocation) { + entityplayer.stopRiding(); // CraftBukkit this.players.remove(entityplayer); entityplayer.getWorldServer().a(entityplayer, Entity.RemovalReason.DISCARDED); BlockPosition blockposition = entityplayer.getSpawn(); float f = entityplayer.getSpawnAngle(); boolean flag1 = entityplayer.isSpawnForced(); + /* CraftBukkit start WorldServer worldserver = this.server.getWorldServer(entityplayer.getSpawnDimension()); Optional optional; @@ -480,6 +660,11 @@ WorldServer worldserver1 = worldserver != null && optional.isPresent() ? worldserver : this.server.E(); EntityPlayer entityplayer1 = new EntityPlayer(this.server, worldserver1, entityplayer.getProfile()); + // */ + EntityPlayer entityplayer1 = entityplayer; + org.bukkit.World fromWorld = entityplayer.getBukkitEntity().getWorld(); + entityplayer.wonGame = false; + // CraftBukkit end entityplayer1.connection = entityplayer.connection; entityplayer1.copyFrom(entityplayer, flag); @@ -495,49 +680,110 @@ boolean flag2 = false; - if (optional.isPresent()) { - IBlockData iblockdata = worldserver1.getType(blockposition); - boolean flag3 = iblockdata.a(Blocks.RESPAWN_ANCHOR); - Vec3D vec3d = (Vec3D) optional.get(); - float f1; + // CraftBukkit start - fire PlayerRespawnEvent + if (location == null) { + boolean isBedSpawn = false; + WorldServer worldserver1 = this.server.getWorldServer(entityplayer.getSpawnDimension()); + if (worldserver1 != null) { + Optional optional; - if (!iblockdata.a((Tag) TagsBlock.BEDS) && !flag3) { - f1 = f; - } else { - Vec3D vec3d1 = Vec3D.c((BaseBlockPosition) blockposition).d(vec3d).d(); + if (blockposition != null) { + optional = EntityHuman.getBed(worldserver1, blockposition, f, flag1, flag); + } else { + optional = Optional.empty(); + } + + if (optional.isPresent()) { + IBlockData iblockdata = worldserver1.getType(blockposition); + boolean flag3 = iblockdata.a(Blocks.RESPAWN_ANCHOR); + Vec3D vec3d = (Vec3D) optional.get(); + float f1; + + if (!iblockdata.a((Tag) TagsBlock.BEDS) && !flag3) { + f1 = f; + } else { + Vec3D vec3d1 = Vec3D.c((BaseBlockPosition) blockposition).d(vec3d).d(); - f1 = (float) MathHelper.f(MathHelper.d(vec3d1.z, vec3d1.x) * 57.2957763671875D - 90.0D); + f1 = (float) MathHelper.f(MathHelper.d(vec3d1.z, vec3d1.x) * 57.2957763671875D - 90.0D); + } + + entityplayer1.setRespawnPosition(worldserver1.getDimensionKey(), blockposition, f, flag1, false); + flag2 = !flag && flag3; + isBedSpawn = true; + location = new Location(worldserver1.getWorld(), vec3d.x, vec3d.y, vec3d.z, f1, 0.0F); + } else if (blockposition != null) { + entityplayer1.connection.sendPacket(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.NO_RESPAWN_BLOCK_AVAILABLE, 0.0F)); + } + } + + if (location == null) { + worldserver1 = this.server.getWorldServer(World.OVERWORLD); + blockposition = entityplayer1.getSpawnPoint(worldserver1); + location = new Location(worldserver1.getWorld(), (double) ((float) blockposition.getX() + 0.5F), (double) ((float) blockposition.getY() + 0.1F), (double) ((float) blockposition.getZ() + 0.5F)); } - entityplayer1.setPositionRotation(vec3d.x, vec3d.y, vec3d.z, f1, 0.0F); - entityplayer1.setRespawnPosition(worldserver1.getDimensionKey(), blockposition, f, flag1, false); - flag2 = !flag && flag3; - } else if (blockposition != null) { - entityplayer1.connection.sendPacket(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.NO_RESPAWN_BLOCK_AVAILABLE, 0.0F)); + Player respawnPlayer = entityplayer1.getBukkitEntity(); + PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(respawnPlayer, location, isBedSpawn && !flag2, flag2); + cserver.getPluginManager().callEvent(respawnEvent); + + location = respawnEvent.getRespawnLocation(); + if (!flag) entityplayer.reset(); // SPIGOT-4785 + } else { + location.setWorld(worldserver.getWorld()); } + WorldServer worldserver1 = ((CraftWorld) location.getWorld()).getHandle(); + entityplayer1.forceSetPositionRotation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); + // CraftBukkit end - while (!worldserver1.getCubes(entityplayer1) && entityplayer1.locY() < (double) worldserver1.getMaxBuildHeight()) { + while (avoidSuffocation && !worldserver1.getCubes(entityplayer1) && entityplayer1.locY() < (double) worldserver1.getMaxBuildHeight()) { entityplayer1.setPosition(entityplayer1.locX(), entityplayer1.locY() + 1.0D, entityplayer1.locZ()); } + // CraftBukkit start + WorldData worlddata = worldserver1.getWorldData(); + entityplayer1.connection.sendPacket(new PacketPlayOutRespawn(worldserver1.getDimensionManager(), worldserver1.getDimensionKey(), BiomeManager.a(worldserver1.getSeed()), entityplayer1.gameMode.getGameMode(), entityplayer1.gameMode.c(), worldserver1.isDebugWorld(), worldserver1.isFlatWorld(), flag)); + entityplayer1.spawnIn(worldserver1); + entityplayer1.unsetRemoved(); + entityplayer1.connection.teleport(new Location(worldserver1.getWorld(), entityplayer1.locX(), entityplayer1.locY(), entityplayer1.locZ(), entityplayer1.getYRot(), entityplayer1.getXRot())); + entityplayer1.setSneaking(false); - WorldData worlddata = entityplayer1.level.getWorldData(); - - entityplayer1.connection.sendPacket(new PacketPlayOutRespawn(entityplayer1.level.getDimensionManager(), entityplayer1.level.getDimensionKey(), BiomeManager.a(entityplayer1.getWorldServer().getSeed()), entityplayer1.gameMode.getGameMode(), entityplayer1.gameMode.c(), entityplayer1.getWorldServer().isDebugWorld(), entityplayer1.getWorldServer().isFlatWorld(), flag)); - entityplayer1.connection.b(entityplayer1.locX(), entityplayer1.locY(), entityplayer1.locZ(), entityplayer1.getYRot(), entityplayer1.getXRot()); + // entityplayer1.connection.b(entityplayer1.locX(), entityplayer1.locY(), entityplayer1.locZ(), entityplayer1.getYRot(), entityplayer1.getXRot()); entityplayer1.connection.sendPacket(new PacketPlayOutSpawnPosition(worldserver1.getSpawn(), worldserver1.x())); entityplayer1.connection.sendPacket(new PacketPlayOutServerDifficulty(worlddata.getDifficulty(), worlddata.isDifficultyLocked())); entityplayer1.connection.sendPacket(new PacketPlayOutExperience(entityplayer1.experienceProgress, entityplayer1.totalExperience, entityplayer1.experienceLevel)); this.a(entityplayer1, worldserver1); this.d(entityplayer1); - worldserver1.addPlayerRespawn(entityplayer1); - this.players.add(entityplayer1); - this.playersByUUID.put(entityplayer1.getUniqueID(), entityplayer1); - entityplayer1.syncInventory(); + if (!entityplayer.connection.isDisconnected()) { + worldserver1.addPlayerRespawn(entityplayer1); + this.players.add(entityplayer1); + this.playersByUUID.put(entityplayer1.getUniqueID(), entityplayer1); + } + // entityplayer1.syncInventory(); entityplayer1.setHealth(entityplayer1.getHealth()); if (flag2) { entityplayer1.connection.sendPacket(new PacketPlayOutNamedSoundEffect(SoundEffects.RESPAWN_ANCHOR_DEPLETE, SoundCategory.BLOCKS, (double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), 1.0F, 1.0F)); } + // Added from changeDimension + updateClient(entityplayer); // Update health, etc... + entityplayer.updateAbilities(); + for (Object o1 : entityplayer.getEffects()) { + MobEffect mobEffect = (MobEffect) o1; + entityplayer.connection.sendPacket(new PacketPlayOutEntityEffect(entityplayer.getId(), mobEffect)); + } + + // Fire advancement trigger + entityplayer.triggerDimensionAdvancements(((CraftWorld) fromWorld).getHandle()); + // Don't fire on respawn + if (fromWorld != location.getWorld()) { + PlayerChangedWorldEvent event = new PlayerChangedWorldEvent(entityplayer.getBukkitEntity(), fromWorld); + server.server.getPluginManager().callEvent(event); + } + + // Save player file again if they were disconnected + if (entityplayer.connection.isDisconnected()) { + this.savePlayerFile(entityplayer); + } + // CraftBukkit end return entityplayer1; } @@ -550,7 +796,18 @@ public void tick() { if (++this.sendAllPlayerInfoIn > 600) { - this.sendAll(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_LATENCY, this.players)); + // CraftBukkit start + for (int i = 0; i < this.players.size(); ++i) { + final EntityPlayer target = (EntityPlayer) this.players.get(i); + + target.connection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_LATENCY, this.players.stream().filter(new Predicate() { + @Override + public boolean apply(EntityPlayer input) { + return target.getBukkitEntity().canSee(input.getBukkitEntity()); + } + }).collect(Collectors.toList()))); + } + // CraftBukkit end this.sendAllPlayerInfoIn = 0; } @@ -567,6 +824,25 @@ } + // CraftBukkit start - add a world/entity limited version + public void sendAll(Packet packet, EntityHuman entityhuman) { + for (int i = 0; i < this.players.size(); ++i) { + EntityPlayer entityplayer = this.players.get(i); + if (entityhuman != null && entityhuman instanceof EntityPlayer && !entityplayer.getBukkitEntity().canSee(((EntityPlayer) entityhuman).getBukkitEntity())) { + continue; + } + ((EntityPlayer) this.players.get(i)).connection.sendPacket(packet); + } + } + + public void sendAll(Packet packet, World world) { + for (int i = 0; i < world.getPlayers().size(); ++i) { + ((EntityPlayer) world.getPlayers().get(i)).connection.sendPacket(packet); + } + + } + // CraftBukkit end + public void a(Packet packet, ResourceKey resourcekey) { Iterator iterator = this.players.iterator(); @@ -669,6 +945,7 @@ entityplayer.connection.sendPacket(new PacketPlayOutEntityStatus(entityplayer, b0)); } + entityplayer.getBukkitEntity().recalculatePermissions(); // CraftBukkit this.server.getCommandDispatcher().a(entityplayer); } @@ -701,6 +978,12 @@ for (int i = 0; i < this.players.size(); ++i) { EntityPlayer entityplayer = (EntityPlayer) this.players.get(i); + // CraftBukkit start - Test if player receiving packet can see the source of the packet + if (entityhuman != null && entityhuman instanceof EntityPlayer && !entityplayer.getBukkitEntity().canSee(((EntityPlayer) entityhuman).getBukkitEntity())) { + continue; + } + // CraftBukkit end + if (entityplayer != entityhuman && entityplayer.level.getDimensionKey() == resourcekey) { double d4 = d0 - entityplayer.locX(); double d5 = d1 - entityplayer.locY(); @@ -740,23 +1023,34 @@ public void reloadWhitelist() {} public void a(EntityPlayer entityplayer, WorldServer worldserver) { - WorldBorder worldborder = this.server.E().getWorldBorder(); + WorldBorder worldborder = entityplayer.level.getWorldBorder(); // CraftBukkit entityplayer.connection.sendPacket(new ClientboundInitializeBorderPacket(worldborder)); entityplayer.connection.sendPacket(new PacketPlayOutUpdateTime(worldserver.getTime(), worldserver.getDayTime(), worldserver.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT))); entityplayer.connection.sendPacket(new PacketPlayOutSpawnPosition(worldserver.getSpawn(), worldserver.x())); if (worldserver.isRaining()) { - entityplayer.connection.sendPacket(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.START_RAINING, 0.0F)); - entityplayer.connection.sendPacket(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.RAIN_LEVEL_CHANGE, worldserver.d(1.0F))); - entityplayer.connection.sendPacket(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.THUNDER_LEVEL_CHANGE, worldserver.b(1.0F))); + // CraftBukkit start - handle player weather + // entityplayer.playerConnection.sendPacket(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.b, 0.0F)); + // entityplayer.playerConnection.sendPacket(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.h, worldserver.d(1.0F))); + // entityplayer.playerConnection.sendPacket(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.i, worldserver.b(1.0F))); + entityplayer.setPlayerWeather(org.bukkit.WeatherType.DOWNFALL, false); + entityplayer.updateWeather(-worldserver.rainLevel, worldserver.rainLevel, -worldserver.thunderLevel, worldserver.thunderLevel); + // CraftBukkit end } } public void updateClient(EntityPlayer entityplayer) { entityplayer.inventoryMenu.updateInventory(); - entityplayer.triggerHealthUpdate(); + // entityplayer.triggerHealthUpdate(); + entityplayer.getBukkitEntity().updateScaledHealth(); // CraftBukkit - Update scaled health on respawn and worldchange entityplayer.connection.sendPacket(new PacketPlayOutHeldItemSlot(entityplayer.getInventory().selected)); + // CraftBukkit start - from GameRules + int i = entityplayer.level.getGameRules().getBoolean(GameRules.RULE_REDUCEDDEBUGINFO) ? 22 : 23; + entityplayer.connection.sendPacket(new PacketPlayOutEntityStatus(entityplayer, (byte) i)); + float immediateRespawn = entityplayer.level.getGameRules().getBoolean(GameRules.RULE_DO_IMMEDIATE_RESPAWN) ? 1.0F: 0.0F; + entityplayer.connection.sendPacket(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.IMMEDIATE_RESPAWN, immediateRespawn)); + // CraftBukkit end } public int getPlayerCount() { @@ -807,12 +1101,22 @@ } public void shutdown() { - for (int i = 0; i < this.players.size(); ++i) { - ((EntityPlayer) this.players.get(i)).connection.disconnect(new ChatMessage("multiplayer.disconnect.server_shutdown")); + // CraftBukkit start - disconnect safely + for (EntityPlayer player : this.players) { + player.connection.disconnect(this.server.server.getShutdownMessage()); // CraftBukkit - add custom shutdown message } + // CraftBukkit end } + // CraftBukkit start + public void sendMessage(IChatBaseComponent[] iChatBaseComponents) { + for (IChatBaseComponent component : iChatBaseComponents) { + sendMessage(component, ChatMessageType.SYSTEM, SystemUtils.NIL_UUID); + } + } + // CraftBukkit end + public void sendMessage(IChatBaseComponent ichatbasecomponent, ChatMessageType chatmessagetype, UUID uuid) { this.server.sendMessage(ichatbasecomponent, uuid); Iterator iterator = this.players.iterator(); @@ -840,16 +1144,23 @@ } - public ServerStatisticManager getStatisticManager(EntityHuman entityhuman) { - UUID uuid = entityhuman.getUniqueID(); - ServerStatisticManager serverstatisticmanager = uuid == null ? null : (ServerStatisticManager) this.stats.get(uuid); + // CraftBukkit start + public ServerStatisticManager getStatisticManager(EntityPlayer entityhuman) { + ServerStatisticManager serverstatisticmanager = entityhuman.getStatisticManager(); + return serverstatisticmanager == null ? getStatisticManager(entityhuman.getUniqueID(), entityhuman.getDisplayName().getString()) : serverstatisticmanager; + } + + public ServerStatisticManager getStatisticManager(UUID uuid, String displayName) { + EntityPlayer entityhuman = this.getPlayer(uuid); + ServerStatisticManager serverstatisticmanager = entityhuman == null ? null : (ServerStatisticManager) entityhuman.getStatisticManager(); + // CraftBukkit end if (serverstatisticmanager == null) { File file = this.server.a(SavedFile.PLAYER_STATS_DIR).toFile(); File file1 = new File(file, uuid + ".json"); if (!file1.exists()) { - File file2 = new File(file, entityhuman.getDisplayName().getString() + ".json"); + File file2 = new File(file, displayName + ".json"); // CraftBukkit Path path = file2.toPath(); if (FileUtils.a(path) && FileUtils.b(path) && path.startsWith(file.getPath()) && file2.isFile()) { @@ -858,7 +1169,7 @@ } serverstatisticmanager = new ServerStatisticManager(this.server, file1); - this.stats.put(uuid, serverstatisticmanager); + // this.stats.put(uuid, serverstatisticmanager); // CraftBukkit } return serverstatisticmanager; @@ -866,14 +1177,14 @@ public AdvancementDataPlayer f(EntityPlayer entityplayer) { UUID uuid = entityplayer.getUniqueID(); - AdvancementDataPlayer advancementdataplayer = (AdvancementDataPlayer) this.advancements.get(uuid); + AdvancementDataPlayer advancementdataplayer = (AdvancementDataPlayer) entityplayer.getAdvancementData(); // CraftBukkit if (advancementdataplayer == null) { File file = this.server.a(SavedFile.PLAYER_ADVANCEMENTS_DIR).toFile(); File file1 = new File(file, uuid + ".json"); advancementdataplayer = new AdvancementDataPlayer(this.server.getDataFixer(), this, this.server.getAdvancementData(), file1, entityplayer); - this.advancements.put(uuid, advancementdataplayer); + // this.advancements.put(uuid, advancementdataplayer); // CraftBukkit } advancementdataplayer.a(entityplayer); @@ -909,13 +1220,20 @@ } public void reload() { - Iterator iterator = this.advancements.values().iterator(); + // CraftBukkit start + /*Iterator iterator = this.advancements.values().iterator(); while (iterator.hasNext()) { AdvancementDataPlayer advancementdataplayer = (AdvancementDataPlayer) iterator.next(); advancementdataplayer.a(this.server.getAdvancementData()); + }*/ + + for (EntityPlayer player : players) { + player.getAdvancementData().a(this.server.getAdvancementData()); + player.getAdvancementData().b(player); // CraftBukkit - trigger immediate flush of advancements } + // CraftBukkit end this.sendAll(new PacketPlayOutTags(this.server.getTagRegistry().a((IRegistryCustom) this.registryHolder))); PacketPlayOutRecipeUpdate packetplayoutrecipeupdate = new PacketPlayOutRecipeUpdate(this.server.getCraftingManager().b());