From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Thu, 26 Jul 2018 00:11:12 -0400
Subject: [PATCH] Prevent Saving Bad entities to chunks

See https://github.com/PaperMC/Paper/issues/1223

Minecraft is saving invalid entities to the chunk files.

Avoid saving bad data, and also make improvements to handle
loading these chunks. Any invalid entity will be instant killed,
so lets avoid adding it to the world...

This lets us be safer about the dupe UUID resolver too, as now
we can ignore instant killed entities and avoid risk of duplicating
an invalid entity.

This should reduce log occurrences of dupe uuid messages.

diff --git a/src/main/java/net/minecraft/server/ChunkRegionLoader.java b/src/main/java/net/minecraft/server/ChunkRegionLoader.java
index 13d99de2cd08de02215031a1f699110c13ef35ff..f54572773c25b6716a68166efa8d3fc8b22b6258 100644
--- a/src/main/java/net/minecraft/server/ChunkRegionLoader.java
+++ b/src/main/java/net/minecraft/server/ChunkRegionLoader.java
@@ -300,6 +300,7 @@ public class ChunkRegionLoader {
         nbttagcompound1.set("TileEntities", nbttaglist1);
         NBTTagList nbttaglist2 = new NBTTagList();
 
+        java.util.List<Entity> toUpdate = new java.util.ArrayList<>(); // Paper
         if (ichunkaccess.getChunkStatus().getType() == ChunkStatus.Type.LEVELCHUNK) {
             Chunk chunk = (Chunk) ichunkaccess;
 
@@ -311,13 +312,28 @@ public class ChunkRegionLoader {
                 while (iterator1.hasNext()) {
                     Entity entity = (Entity) iterator1.next();
                     NBTTagCompound nbttagcompound4 = new NBTTagCompound();
-
+                    // Paper start
+                    if ((int) Math.floor(entity.locX()) >> 4 != chunk.getPos().x || (int) Math.floor(entity.locZ()) >> 4 != chunk.getPos().z) {
+                        toUpdate.add(entity);
+                        continue;
+                    }
+                    if (entity.dead || hasPlayerPassenger(entity)) {
+                        continue;
+                    }
+                    // Paper end
                     if (entity.d(nbttagcompound4)) {
                         chunk.d(true);
                         nbttaglist2.add(nbttagcompound4);
                     }
                 }
             }
+
+            // Paper start - move entities to the correct chunk
+            for (Entity entity : toUpdate) {
+                worldserver.chunkCheck(entity);
+            }
+            // Paper end
+
         } else {
             ProtoChunk protochunk = (ProtoChunk) ichunkaccess;
 
@@ -373,6 +389,19 @@ public class ChunkRegionLoader {
         nbttagcompound1.set("Structures", a(chunkcoordintpair, ichunkaccess.h(), ichunkaccess.v()));
         return nbttagcompound;
     }
+    // Paper start - this is saved with the player
+    private static boolean hasPlayerPassenger(Entity entity) {
+        for (Entity passenger : entity.passengers) {
+            if (passenger instanceof EntityPlayer) {
+                return true;
+            }
+            if (hasPlayerPassenger(passenger)) {
+                return true;
+            }
+        }
+        return false;
+    }
+    // Paper end
 
     public static ChunkStatus.Type a(@Nullable NBTTagCompound nbttagcompound) {
         if (nbttagcompound != null) {
diff --git a/src/main/java/net/minecraft/server/WorldServer.java b/src/main/java/net/minecraft/server/WorldServer.java
index 5086a854b84b05e5b9c0f5677051d19dfa42f343..426ca12970e0c75ba75eee6c3e3cdbf833730737 100644
--- a/src/main/java/net/minecraft/server/WorldServer.java
+++ b/src/main/java/net/minecraft/server/WorldServer.java
@@ -1078,6 +1078,7 @@ public class WorldServer extends World {
         List[] aentityslice = chunk.getEntitySlices(); // Spigot
         int i = aentityslice.length;
 
+        java.util.List<Entity> toMoveChunks = new java.util.ArrayList<>(); // Paper
         for (int j = 0; j < i; ++j) {
             List<Entity> entityslice = aentityslice[j]; // Spigot
             Iterator iterator = entityslice.iterator();
@@ -1090,11 +1091,25 @@ public class WorldServer extends World {
                         throw (IllegalStateException) SystemUtils.c(new IllegalStateException("Removing entity while ticking!"));
                     }
 
+                    // Paper start - move out entities that shouldn't be in this chunk before it unloads
+                    if (!entity.dead && (int) Math.floor(entity.locX()) >> 4 != chunk.getPos().x || (int) Math.floor(entity.locZ()) >> 4 != chunk.getPos().z) {
+                        toMoveChunks.add(entity);
+                        continue;
+                    }
+                    // Paper end
+
                     this.entitiesById.remove(entity.getId());
                     this.unregisterEntity(entity);
+
+                    if (entity.dead) iterator.remove(); // Paper - don't save dead entities during unload
                 }
             }
         }
+        // Paper start - move out entities that shouldn't be in this chunk before it unloads
+        for (Entity entity : toMoveChunks) {
+            this.chunkCheck(entity);
+        }
+        // Paper end
 
     }
 
