--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -140,7 +_,65 @@
 import net.minecraft.world.scores.Team;
 import org.jetbrains.annotations.Contract;
 
-public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess, ScoreHolder, DataComponentGetter {
+public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess, ScoreHolder, DataComponentGetter, ca.spottedleaf.moonrise.patches.chunk_system.entity.ChunkSystemEntity, ca.spottedleaf.moonrise.patches.entity_tracker.EntityTrackerEntity { // Paper - rewrite chunk system // Paper - optimise entity tracker
+    // CraftBukkit start
+    private static final org.slf4j.Logger LOGGER = com.mojang.logging.LogUtils.getLogger();
+    private static final int CURRENT_LEVEL = 2;
+    public boolean preserveMotion = true; // Paper - Fix Entity Teleportation and cancel velocity if teleported; keep initial motion on first snapTo
+    static boolean isLevelAtLeast(CompoundTag tag, int level) {
+        return tag.getIntOr("Bukkit.updateLevel", CURRENT_LEVEL) >= level;
+    }
+
+    // Paper start - Share random for entities to make them more random
+    public static RandomSource SHARED_RANDOM = new RandomRandomSource();
+    // Paper start - replace random
+    private static final class RandomRandomSource extends ca.spottedleaf.moonrise.common.util.ThreadUnsafeRandom {
+        public RandomRandomSource() {
+            this(net.minecraft.world.level.levelgen.RandomSupport.generateUniqueSeed());
+        }
+
+        public RandomRandomSource(long seed) {
+            super(seed);
+        }
+
+        // Paper end - replace random
+        private boolean locked = false;
+
+        @Override
+        public synchronized void setSeed(long seed) {
+            if (locked) {
+                LOGGER.error("Ignoring setSeed on Entity.SHARED_RANDOM", new Throwable());
+            } else {
+                super.setSeed(seed);
+                locked = true;
+            }
+        }
+
+        // Paper - replace random
+    }
+    // Paper end - Share random for entities to make them more random
+    public @Nullable org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason; // Paper - Entity#getEntitySpawnReason
+
+    public boolean collisionLoadChunks = false; // Paper
+    private @Nullable org.bukkit.craftbukkit.entity.CraftEntity bukkitEntity;
+
+    public org.bukkit.craftbukkit.entity.CraftEntity getBukkitEntity() {
+        if (this.bukkitEntity == null) {
+            // Paper start - Folia schedulers
+            synchronized (this) {
+                if (this.bukkitEntity == null) {
+                    return this.bukkitEntity = org.bukkit.craftbukkit.entity.CraftEntity.getEntity(this.level.getCraftServer(), this);
+                }
+            }
+            // Paper end - Folia schedulers
+        }
+        return this.bukkitEntity;
+    }
+    // Paper start
+    public @Nullable org.bukkit.craftbukkit.entity.CraftEntity getBukkitEntityRaw() {
+        return this.bukkitEntity;
+    }
+    // Paper end
     public static final String ID_TAG = "id";
     public static final String PASSENGERS_TAG = "Passengers";
     private static final String DATA_TAG = "data";
@@ -167,7 +_,7 @@
     private final EntityType<?> type;
     private int id = ENTITY_COUNTER.incrementAndGet();
     public boolean blocksBuilding;
-    private ImmutableList<Entity> passengers = ImmutableList.of();
+    public ImmutableList<Entity> passengers = ImmutableList.of();
     protected int boardingCooldown;
     @Nullable
     private Entity vehicle;
@@ -184,7 +_,7 @@
     public float yRotO;
     public float xRotO;
     private AABB bb = INITIAL_AABB;
-    private boolean onGround;
+    public boolean onGround;
     public boolean horizontalCollision;
     public boolean verticalCollision;
     public boolean verticalCollisionBelow;
@@ -203,10 +_,10 @@
     public double yOld;
     public double zOld;
     public boolean noPhysics;
-    protected final RandomSource random = RandomSource.create();
+    public final RandomSource random = SHARED_RANDOM; // Paper - Share random for entities to make them more random
     public int tickCount;
     private int remainingFireTicks = -this.getFireImmuneTicks();
-    protected boolean wasTouchingWater;
+    public boolean wasTouchingWater;
     protected Object2DoubleMap<TagKey<Fluid>> fluidHeight = new Object2DoubleArrayMap<>(2);
     protected boolean wasEyeInWater;
     private final Set<TagKey<Fluid>> fluidOnEyes = new HashSet<>();
@@ -218,7 +_,7 @@
     private static final int FLAG_SHIFT_KEY_DOWN = 1;
     private static final int FLAG_SPRINTING = 3;
     private static final int FLAG_SWIMMING = 4;
-    private static final int FLAG_INVISIBLE = 5;
+    public static final int FLAG_INVISIBLE = 5;
     protected static final int FLAG_GLOWING = 6;
     protected static final int FLAG_FALL_FLYING = 7;
     private static final EntityDataAccessor<Integer> DATA_AIR_SUPPLY_ID = SynchedEntityData.defineId(Entity.class, EntityDataSerializers.INT);
@@ -235,12 +_,12 @@
     public boolean hasImpulse;
     @Nullable
     public PortalProcessor portalProcess;
-    private int portalCooldown;
+    public int portalCooldown;
     private boolean invulnerable;
     protected UUID uuid = Mth.createInsecureUUID(this.random);
     protected String stringUUID = this.uuid.toString();
     private boolean hasGlowingTag;
-    private final Set<String> tags = Sets.newHashSet();
+    private final Set<String> tags = new io.papermc.paper.util.SizeLimitedSet<>(new it.unimi.dsi.fastutil.objects.ObjectOpenHashSet<>(), MAX_ENTITY_TAG_COUNT); // Paper - fully limit tag size - replace set impl
     private final double[] pistonDeltas = new double[]{0.0, 0.0, 0.0};
     private long pistonDeltasGameTime;
     private EntityDimensions dimensions;
@@ -251,7 +_,7 @@
     private boolean onGroundNoBlocks = false;
     private float crystalSoundIntensity;
     private int lastCrystalSoundPlayTick;
-    private boolean hasVisualFire;
+    public net.kyori.adventure.util.TriState visualFire = net.kyori.adventure.util.TriState.NOT_SET; // Paper - improve visual fire API
     @Nullable
     private BlockState inBlockState = null;
     private final List<List<Entity.Movement>> movementThisTick = new ObjectArrayList<>();
@@ -259,6 +_,204 @@
     private final LongSet visitedBlocks = new LongOpenHashSet();
     private final InsideBlockEffectApplier.StepBasedCollector insideEffectCollector = new InsideBlockEffectApplier.StepBasedCollector();
     private CustomData customData = CustomData.EMPTY;
+    // CraftBukkit start
+    public boolean forceDrops;
+    public boolean persist = true;
+    public boolean visibleByDefault = true;
+    public boolean valid;
+    public boolean inWorld = false;
+    public boolean generation;
+    public int maxAirTicks = this.getDefaultMaxAirSupply(); // CraftBukkit - SPIGOT-6907: re-implement LivingEntity#setMaximumAir()
+    @Nullable // Paper - Refresh ProjectileSource for projectiles
+    public org.bukkit.projectiles.ProjectileSource projectileSource; // For projectiles only
+    public boolean lastDamageCancelled; // SPIGOT-5339, SPIGOT-6252, SPIGOT-6777: Keep track if the event was canceled
+    public boolean persistentInvisibility = false;
+    public @Nullable BlockPos lastLavaContact;
+    // Marks an entity, that it was removed by a plugin via Entity#remove
+    // Main use case currently is for SPIGOT-7487, preventing dropping of leash when leash is removed
+    public boolean pluginRemoved = false;
+    protected int numCollisions = 0; // Paper - Cap entity collisions
+    public boolean fromNetherPortal; // Paper - Add option to nerf pigmen from nether portals
+    public boolean spawnedViaMobSpawner; // Paper - Yes this name is similar to above, upstream took the better one
+    // Paper start
+    public @Nullable Vec3 origin;
+    public @Nullable UUID originWorld;
+    // Paper end
+    public boolean freezeLocked = false; // Paper - Freeze Tick Lock API
+    public boolean fixedPose = false; // Paper - Expand Pose API
+    private final int despawnTime; // Paper - entity despawn time limit
+    public int totalEntityAge; // Paper - age-like counter for all entities
+    public final io.papermc.paper.entity.activation.ActivationType activationType = io.papermc.paper.entity.activation.ActivationType.activationTypeFor(this); // Paper - EAR 2/tracking ranges
+    // Paper start - EAR 2
+    public final boolean defaultActivationState;
+    public long activatedTick = Integer.MIN_VALUE;
+    public boolean isTemporarilyActive;
+    public long activatedImmunityTick = Integer.MIN_VALUE;
+
+    public void inactiveTick() {
+    }
+    // Paper end - EAR 2
+    // CraftBukkit end
+
+    // Paper start
+    public final AABB getBoundingBoxAt(double x, double y, double z) {
+        return this.dimensions.makeBoundingBox(x, y, z);
+    }
+    // MC-296337
+    protected void clearMovementsThisTick() {
+        this.movementThisTick.clear();
+    }
+    // Paper end
+    // Paper start - rewrite chunk system
+    private final boolean isHardColliding = this.moonrise$isHardCollidingUncached();
+    private net.minecraft.server.level.FullChunkStatus chunkStatus;
+    private ca.spottedleaf.moonrise.patches.chunk_system.level.chunk.ChunkData chunkData;
+    private int sectionX = Integer.MIN_VALUE;
+    private int sectionY = Integer.MIN_VALUE;
+    private int sectionZ = Integer.MIN_VALUE;
+    private boolean updatingSectionStatus;
+
+    @Override
+    public final boolean moonrise$isHardColliding() {
+        return this.isHardColliding;
+    }
+
+    @Override
+    public final net.minecraft.server.level.FullChunkStatus moonrise$getChunkStatus() {
+        return this.chunkStatus;
+    }
+
+    @Override
+    public final void moonrise$setChunkStatus(final net.minecraft.server.level.FullChunkStatus status) {
+        this.chunkStatus = status;
+    }
+
+    @Override
+    public final ca.spottedleaf.moonrise.patches.chunk_system.level.chunk.ChunkData moonrise$getChunkData() {
+        return this.chunkData;
+    }
+
+    @Override
+    public final void moonrise$setChunkData(final ca.spottedleaf.moonrise.patches.chunk_system.level.chunk.ChunkData chunkData) {
+        this.chunkData = chunkData;
+    }
+
+    @Override
+    public final int moonrise$getSectionX() {
+        return this.sectionX;
+    }
+
+    @Override
+    public final void moonrise$setSectionX(final int x) {
+        this.sectionX = x;
+    }
+
+    @Override
+    public final int moonrise$getSectionY() {
+        return this.sectionY;
+    }
+
+    @Override
+    public final void moonrise$setSectionY(final int y) {
+        this.sectionY = y;
+    }
+
+    @Override
+    public final int moonrise$getSectionZ() {
+        return this.sectionZ;
+    }
+
+    @Override
+    public final void moonrise$setSectionZ(final int z) {
+        this.sectionZ = z;
+    }
+
+    @Override
+    public final boolean moonrise$isUpdatingSectionStatus() {
+        return this.updatingSectionStatus;
+    }
+
+    @Override
+    public final void moonrise$setUpdatingSectionStatus(final boolean to) {
+        this.updatingSectionStatus = to;
+    }
+
+    @Override
+    public final boolean moonrise$hasAnyPlayerPassengers() {
+        if (this.passengers.isEmpty()) {
+            return false;
+        }
+        return this.getIndirectPassengersStream().anyMatch((entity) -> entity instanceof Player);
+    }
+    // Paper end - rewrite chunk system
+    // Paper start - optimise collisions
+    private static float[] calculateStepHeights(final AABB box, final List<VoxelShape> voxels, final List<AABB> aabbs, final float stepHeight,
+                                                final float collidedY) {
+        final FloatArraySet ret = new FloatArraySet();
+
+        for (int i = 0, len = voxels.size(); i < len; ++i) {
+            final VoxelShape shape = voxels.get(i);
+
+            final double[] yCoords = ((ca.spottedleaf.moonrise.patches.collisions.shape.CollisionVoxelShape)shape).moonrise$rootCoordinatesY();
+            final double yOffset = ((ca.spottedleaf.moonrise.patches.collisions.shape.CollisionVoxelShape)shape).moonrise$offsetY();
+
+            for (final double yUnoffset : yCoords) {
+                final double y = yUnoffset + yOffset;
+
+                final float step = (float)(y - box.minY);
+
+                if (step > stepHeight) {
+                    break;
+                }
+
+                if (step < 0.0f || !(step != collidedY)) {
+                    continue;
+                }
+
+                ret.add(step);
+            }
+        }
+
+        for (int i = 0, len = aabbs.size(); i < len; ++i) {
+            final AABB shape = aabbs.get(i);
+
+            final float step1 = (float)(shape.minY - box.minY);
+            final float step2 = (float)(shape.maxY - box.minY);
+
+            if (!(step1 < 0.0f) && step1 != collidedY && !(step1 > stepHeight)) {
+                ret.add(step1);
+            }
+
+            if (!(step2 < 0.0f) && step2 != collidedY && !(step2 > stepHeight)) {
+                ret.add(step2);
+            }
+        }
+
+        final float[] steps = ret.toFloatArray();
+        FloatArrays.unstableSort(steps);
+        return steps;
+    }
+    // Paper end - optimise collisions
+    // Paper start - optimise entity tracker
+    private net.minecraft.server.level.ChunkMap.TrackedEntity trackedEntity;
+
+    @Override
+    public final net.minecraft.server.level.ChunkMap.TrackedEntity moonrise$getTrackedEntity() {
+        return this.trackedEntity;
+    }
+
+    @Override
+    public final void moonrise$setTrackedEntity(final net.minecraft.server.level.ChunkMap.TrackedEntity trackedEntity) {
+        this.trackedEntity = trackedEntity;
+    }
+
+    private static void collectIndirectPassengers(final List<Entity> into, final List<Entity> from) {
+        for (final Entity passenger : from) {
+            into.add(passenger);
+            collectIndirectPassengers(into, ((Entity)(Object)passenger).passengers);
+        }
+    }
+    // Paper end - optimise entity tracker
 
     public Entity(EntityType<?> entityType, Level level) {
         this.type = entityType;
@@ -267,6 +_,13 @@
         this.position = Vec3.ZERO;
         this.blockPosition = BlockPos.ZERO;
         this.chunkPosition = ChunkPos.ZERO;
+        // Paper start - EAR 2
+        if (level != null) {
+            this.defaultActivationState = io.papermc.paper.entity.activation.ActivationRange.initializeEntityActivationState(this, level.spigotConfig);
+        } else {
+            this.defaultActivationState = false;
+        }
+        // Paper end - EAR 2
         SynchedEntityData.Builder builder = new SynchedEntityData.Builder(this);
         builder.define(DATA_SHARED_FLAGS_ID, (byte)0);
         builder.define(DATA_AIR_SUPPLY_ID, this.getMaxAirSupply());
@@ -280,6 +_,7 @@
         this.entityData = builder.build();
         this.setPos(0.0, 0.0, 0.0);
         this.eyeHeight = this.dimensions.eyeHeight();
+        this.despawnTime = level == null || type == EntityType.PLAYER ? -1 : level.paperConfig().entities.spawning.despawnTime.getOrDefault(type, io.papermc.paper.configuration.type.number.IntOr.Disabled.DISABLED).or(-1); // Paper - entity despawn time limit
     }
 
     public boolean isColliding(BlockPos pos, BlockState state) {
@@ -292,6 +_,12 @@
         return team != null && team.getColor().getColor() != null ? team.getColor().getColor() : 16777215;
     }
 
+    // CraftBukkit start - SPIGOT-6907: re-implement LivingEntity#setMaximumAir()
+    public int getDefaultMaxAirSupply() {
+        return Entity.TOTAL_AIR_SUPPLY;
+    }
+    // CraftBukkit end
+
     public boolean isSpectator() {
         return false;
     }
@@ -332,7 +_,7 @@
     }
 
     public boolean addTag(String tag) {
-        return this.tags.size() < 1024 && this.tags.add(tag);
+        return this.tags.add(tag); // Paper - fully limit tag size - replace set impl
     }
 
     public boolean removeTag(String tag) {
@@ -340,12 +_,18 @@
     }
 
     public void kill(ServerLevel level) {
-        this.remove(Entity.RemovalReason.KILLED);
+        this.remove(Entity.RemovalReason.KILLED, org.bukkit.event.entity.EntityRemoveEvent.Cause.DEATH); // CraftBukkit - add Bukkit remove cause
         this.gameEvent(GameEvent.ENTITY_DIE);
     }
 
     public final void discard() {
-        this.remove(Entity.RemovalReason.DISCARDED);
+        // CraftBukkit start - add Bukkit remove cause
+        this.discard(null);
+    }
+
+    public final void discard(@Nullable org.bukkit.event.entity.EntityRemoveEvent.Cause cause) {
+        this.remove(Entity.RemovalReason.DISCARDED, cause);
+        // CraftBukkit end
     }
 
     protected abstract void defineSynchedData(SynchedEntityData.Builder builder);
@@ -354,6 +_,48 @@
         return this.entityData;
     }
 
+    // CraftBukkit start
+    public void refreshEntityData(ServerPlayer to) {
+        List<SynchedEntityData.DataValue<?>> list = this.entityData.packAll(); // Paper - Update EVERYTHING not just not default
+
+        if (to.getBukkitEntity().canSee(this.getBukkitEntity())) { // Paper
+            to.connection.send(new net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket(this.getId(), list));
+        }
+    }
+    // CraftBukkit end
+    // Paper start
+    // This method should only be used if the data of an entity could have become desynced
+    // due to interactions on the client.
+    public void resendPossiblyDesyncedEntityData(net.minecraft.server.level.ServerPlayer player) {
+        if (player.getBukkitEntity().canSee(this.getBukkitEntity())) {
+            ServerLevel world = (net.minecraft.server.level.ServerLevel)this.level();
+            net.minecraft.server.level.ChunkMap.TrackedEntity tracker = world == null ? null : world.getChunkSource().chunkMap.entityMap.get(this.getId());
+            if (tracker == null) {
+                return;
+            }
+            final net.minecraft.server.level.ServerEntity serverEntity = tracker.serverEntity;
+            final List<net.minecraft.network.protocol.Packet<? super net.minecraft.network.protocol.game.ClientGamePacketListener>> list = new java.util.ArrayList<>();
+            serverEntity.sendPairingData(player, list::add);
+            player.connection.send(new net.minecraft.network.protocol.game.ClientboundBundlePacket(list));
+        }
+    }
+
+    // This method allows you to specifically resend certain data accessor keys to the client
+    public void resendPossiblyDesyncedDataValues(List<EntityDataAccessor<?>> keys, ServerPlayer to) {
+        if (!to.getBukkitEntity().canSee(this.getBukkitEntity())) {
+            return;
+        }
+
+        final List<SynchedEntityData.DataValue<?>> values = new java.util.ArrayList<>(keys.size());
+        for (final EntityDataAccessor<?> key : keys) {
+            final SynchedEntityData.DataItem<?> synchedValue = this.entityData.getItem(key);
+            values.add(synchedValue.value());
+        }
+
+        to.connection.send(new net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket(this.id, values));
+    }
+    // Paper end
+
     @Override
     public boolean equals(Object object) {
         return object instanceof Entity && ((Entity)object).id == this.id;
@@ -365,7 +_,13 @@
     }
 
     public void remove(Entity.RemovalReason reason) {
-        this.setRemoved(reason);
+        // CraftBukkit start - add Bukkit remove cause
+        this.remove(reason, null);
+    }
+
+    public void remove(Entity.RemovalReason reason, @Nullable org.bukkit.event.entity.EntityRemoveEvent.Cause eventCause) {
+        this.setRemoved(reason, eventCause);
+        // CraftBukkit end
     }
 
     public void onClientRemoval() {
@@ -375,6 +_,15 @@
     }
 
     public void setPose(Pose pose) {
+        if (this.fixedPose) return; // Paper - Expand Pose API
+        // CraftBukkit start
+        if (pose == this.getPose()) {
+            return;
+        }
+        if (!this.generation) {
+            this.level.getCraftServer().getPluginManager().callEvent(new org.bukkit.event.entity.EntityPoseChangeEvent(this.getBukkitEntity(), org.bukkit.entity.Pose.values()[pose.ordinal()]));
+        }
+        // CraftBukkit end
         this.entityData.set(DATA_POSE, pose);
     }
 
@@ -397,7 +_,33 @@
         return Mth.lengthSquared(d, d2) < Mth.square(horizontalDistance) && Mth.square(d1) < Mth.square(verticalDistance);
     }
 
-    protected void setRot(float yRot, float xRot) {
+    public void setRot(float yRot, float xRot) {
+        // CraftBukkit start - yaw was sometimes set to NaN, so we need to set it back to 0
+        if (Float.isNaN(yRot)) {
+            yRot = 0;
+        }
+
+        if (yRot == Float.POSITIVE_INFINITY || yRot == Float.NEGATIVE_INFINITY) {
+            if (this instanceof ServerPlayer) {
+                this.level.getCraftServer().getLogger().warning(this.getScoreboardName() + " was caught trying to crash the server with an invalid yaw");
+                ((org.bukkit.craftbukkit.entity.CraftPlayer) this.getBukkitEntity()).kickPlayer("Infinite yaw (Hacking?)");
+            }
+            yRot = 0;
+        }
+
+        // pitch was sometimes set to NaN, so we need to set it back to 0
+        if (Float.isNaN(xRot)) {
+            xRot = 0;
+        }
+
+        if (xRot == Float.POSITIVE_INFINITY || xRot == Float.NEGATIVE_INFINITY) {
+            if (this instanceof ServerPlayer) {
+                this.level.getCraftServer().getLogger().warning(this.getScoreboardName() + " was caught trying to crash the server with an invalid pitch");
+                ((org.bukkit.craftbukkit.entity.CraftPlayer) this.getBukkitEntity()).kickPlayer("Infinite pitch (Hacking?)");
+            }
+            xRot = 0;
+        }
+        // CraftBukkit end
         this.setYRot(yRot % 360.0F);
         this.setXRot(xRot % 360.0F);
     }
@@ -407,8 +_,8 @@
     }
 
     public void setPos(double x, double y, double z) {
-        this.setPosRaw(x, y, z);
-        this.setBoundingBox(this.makeBoundingBox());
+        this.setPosRaw(x, y, z, true); // Paper - Block invalid positions and bounding box; force update
+        // this.setBoundingBox(this.makeBoundingBox()); // Paper - Block invalid positions and bounding box; move into setPosRaw
     }
 
     protected final AABB makeBoundingBox() {
@@ -438,12 +_,28 @@
     }
 
     public void tick() {
+        // Paper start - entity despawn time limit
+        if (this.despawnTime >= 0 && this.totalEntityAge >= this.despawnTime) {
+            this.discard(org.bukkit.event.entity.EntityRemoveEvent.Cause.DESPAWN);
+            return;
+        }
+        // Paper end - entity despawn time limit
         this.baseTick();
     }
 
+    // CraftBukkit start
+    public void postTick() {
+        // No clean way to break out of ticking once the entity has been copied to a new world, so instead we move the portalling later in the tick cycle
+        if (!(this instanceof ServerPlayer) && this.isAlive()) { // Paper - don't attempt to teleport dead entities
+            this.handlePortal();
+        }
+    }
+    // CraftBukkit end
+
     public void baseTick() {
         ProfilerFiller profilerFiller = Profiler.get();
         profilerFiller.push("entityBaseTick");
+        if (firstTick && this instanceof net.minecraft.world.entity.NeutralMob neutralMob) neutralMob.tickInitialPersistentAnger(level); // Paper - Prevent entity loading causing async lookups
         this.inBlockState = null;
         if (this.isPassenger() && this.getVehicle().isRemoved()) {
             this.stopRiding();
@@ -453,7 +_,7 @@
             this.boardingCooldown--;
         }
 
-        this.handlePortal();
+        if (this instanceof ServerPlayer) this.handlePortal(); // CraftBukkit - Moved up to postTick
         if (this.canSpawnSprintParticle()) {
             this.spawnSprintParticle();
         }
@@ -484,6 +_,10 @@
 
         if (this.isInLava()) {
             this.fallDistance *= 0.5;
+            // CraftBukkit start
+        } else {
+            this.lastLavaContact = null;
+            // CraftBukkit end
         }
 
         this.checkBelowWorld();
@@ -500,11 +_,16 @@
     }
 
     public void setSharedFlagOnFire(boolean isOnFire) {
-        this.setSharedFlag(0, isOnFire || this.hasVisualFire);
+        this.setSharedFlag(0, this.visualFire.toBooleanOrElse(isOnFire)); // Paper - improve visual fire API
     }
 
     public void checkBelowWorld() {
-        if (this.getY() < this.level().getMinY() - 64) {
+        if (!this.level.getWorld().isVoidDamageEnabled()) return; // Paper - check if void damage is enabled on the world
+        // Paper start - Configurable nether ceiling damage
+        if (this.getY() < (this.level.getMinY() + this.level.getWorld().getVoidDamageMinBuildHeightOffset()) || (this.level.getWorld().getEnvironment() == org.bukkit.World.Environment.NETHER // Paper - use configured min build height offset
+            && this.level.paperConfig().environment.netherCeilingVoidDamageHeight.test(v -> this.getY() >= v)
+            && (!(this instanceof Player player) || !player.getAbilities().invulnerable))) {
+            // Paper end - Configurable nether ceiling damage
             this.onBelowWorld();
         }
     }
@@ -532,15 +_,41 @@
     }
 
     public void lavaIgnite() {
+        // Paper start - track lava contact
+        this.lavaIgnite(this.lastLavaContact); // fallback for minecarts if defined
+    }
+
+    public void lavaIgnite(@Nullable BlockPos pos) {
+        // Paper end - track lava contact
         if (!this.fireImmune()) {
-            this.igniteForSeconds(15.0F);
+            // CraftBukkit start - Fallen in lava TODO: this event spams!
+            if (this instanceof net.minecraft.world.entity.LivingEntity && this.remainingFireTicks <= 0) {
+                // not on fire yet
+                org.bukkit.block.Block damager = pos == null ? null : org.bukkit.craftbukkit.block.CraftBlock.at(this.level, pos);
+                org.bukkit.entity.Entity damagee = this.getBukkitEntity();
+                org.bukkit.event.entity.EntityCombustEvent combustEvent = new org.bukkit.event.entity.EntityCombustByBlockEvent(damager, damagee, 15.0F);
+
+                if (combustEvent.callEvent()) {
+                    this.igniteForSeconds(combustEvent.getDuration(), false);
+                }
+            } else {
+                // This will be called every single tick the entity is in lava, so don't throw an event
+                this.igniteForSeconds(15.0F, false);
+            }
+            // CraftBukkit end
         }
     }
 
     public void lavaHurt() {
+        // Paper start - track lava contact
+        this.lavaHurt(this.lastLavaContact); // fallback for minecarts if defined
+    }
+
+    public void lavaHurt(@Nullable BlockPos pos) {
+        // Paper end - track lava contact
         if (!this.fireImmune()) {
             if (this.level() instanceof ServerLevel serverLevel
-                && this.hurtServer(serverLevel, this.damageSources().lava(), 4.0F)
+                && this.hurtServer(serverLevel, this.damageSources().lava().eventBlockDamager(this.level, pos), 4.0F) // CraftBukkit - we also don't throw an event unless the object in lava is living, to save on some event calls
                 && this.shouldPlayLavaHurtSound()
                 && !this.isSilent()) {
                 serverLevel.playSound(
@@ -555,6 +_,20 @@
     }
 
     public final void igniteForSeconds(float seconds) {
+        // CraftBukkit start
+        this.igniteForSeconds(seconds, true);
+    }
+
+    public final void igniteForSeconds(float seconds, boolean callEvent) {
+        if (callEvent) {
+            org.bukkit.event.entity.EntityCombustEvent event = new org.bukkit.event.entity.EntityCombustEvent(this.getBukkitEntity(), seconds);
+            if (!event.callEvent()) {
+                return;
+            }
+
+            seconds = event.getDuration();
+        }
+        // CraftBukkit end
         this.igniteForTicks(Mth.floor(seconds * 20.0F));
     }
 
@@ -579,7 +_,7 @@
     }
 
     protected void onBelowWorld() {
-        this.discard();
+        this.discard(org.bukkit.event.entity.EntityRemoveEvent.Cause.OUT_OF_WORLD); // CraftBukkit - add Bukkit remove cause
     }
 
     public boolean isFree(double x, double y, double z) {
@@ -635,11 +_,36 @@
         return this.onGround;
     }
 
+    // Paper start - detailed watchdog information
+    public final Object posLock = new Object(); // Paper - log detailed entity tick information
+
+    @Nullable
+    private Vec3 moveVector;
+    private double moveStartX;
+    private double moveStartY;
+    private double moveStartZ;
+    // Paper end - detailed watchdog information
+
     public void move(MoverType type, Vec3 movement) {
+        final Vec3 originalMovement = movement; // Paper - Expose pre-collision velocity
+        // Paper start - detailed watchdog information
+        ca.spottedleaf.moonrise.common.util.TickThread.ensureTickThread("Cannot move an entity off-main");
+        synchronized (this.posLock) {
+            this.moveStartX = this.getX();
+            this.moveStartY = this.getY();
+            this.moveStartZ = this.getZ();
+            this.moveVector = movement;
+        }
+        try {
+        // Paper end - detailed watchdog information
         if (this.noPhysics) {
             this.setPos(this.getX() + movement.x, this.getY() + movement.y, this.getZ() + movement.z);
         } else {
             if (type == MoverType.PISTON) {
+                // Paper start - EAR 2
+                this.activatedTick = Math.max(this.activatedTick, MinecraftServer.currentTick + 20);
+                this.activatedImmunityTick = Math.max(this.activatedImmunityTick, MinecraftServer.currentTick + 20);
+                // Paper end - EAR 2
                 movement = this.limitPistonMovement(movement);
                 if (movement.equals(Vec3.ZERO)) {
                     return;
@@ -653,6 +_,13 @@
                 this.stuckSpeedMultiplier = Vec3.ZERO;
                 this.setDeltaMovement(Vec3.ZERO);
             }
+            // Paper start - ignore movement changes while inactive.
+            if (isTemporarilyActive && !(this instanceof ItemEntity) && movement == getDeltaMovement() && type == MoverType.SELF) {
+                setDeltaMovement(Vec3.ZERO);
+                profilerFiller.pop();
+                return;
+            }
+            // Paper end
 
             movement = this.maybeBackOffFromEdge(movement, type);
             Vec3 vec3 = this.collide(movement);
@@ -721,6 +_,27 @@
                         block.updateEntityMovementAfterFallOn(this.level(), this);
                     }
                 }
+                // CraftBukkit start
+                if (this.horizontalCollision && this.getBukkitEntity() instanceof org.bukkit.entity.Vehicle) {
+                    org.bukkit.entity.Vehicle vehicle = (org.bukkit.entity.Vehicle) this.getBukkitEntity();
+                    org.bukkit.block.Block block = this.level.getWorld().getBlockAt(Mth.floor(this.getX()), Mth.floor(this.getY()), Mth.floor(this.getZ()));
+
+                    if (movement.x > vec3.x) {
+                        block = block.getRelative(org.bukkit.block.BlockFace.EAST);
+                    } else if (movement.x < vec3.x) {
+                        block = block.getRelative(org.bukkit.block.BlockFace.WEST);
+                    } else if (movement.z > vec3.z) {
+                        block = block.getRelative(org.bukkit.block.BlockFace.SOUTH);
+                    } else if (movement.z < vec3.z) {
+                        block = block.getRelative(org.bukkit.block.BlockFace.NORTH);
+                    }
+
+                    if (!block.getType().isAir()) {
+                        org.bukkit.event.vehicle.VehicleBlockCollisionEvent event = new org.bukkit.event.vehicle.VehicleBlockCollisionEvent(vehicle, block, org.bukkit.craftbukkit.util.CraftVector.toBukkit(originalMovement)); // Paper - Expose pre-collision velocity
+                        event.callEvent();
+                    }
+                }
+                // CraftBukkit end
 
                 if (!this.level().isClientSide() || this.isLocalInstanceAuthoritative()) {
                     Entity.MovementEmission movementEmission = this.getMovementEmission();
@@ -734,6 +_,13 @@
                 profilerFiller.pop();
             }
         }
+        // Paper start - detailed watchdog information
+        } finally {
+            synchronized (this.posLock) { // Paper
+                this.moveVector = null;
+            } // Paper
+        }
+        // Paper end - detailed watchdog information
     }
 
     private void applyMovementEmissionAndPlaySound(Entity.MovementEmission movementEmission, Vec3 movement, BlockPos pos, BlockState state) {
@@ -818,7 +_,7 @@
         }
     }
 
-    protected boolean isAffectedByBlocks() {
+    public boolean isAffectedByBlocks() {
         return !this.isRemoved() && !this.noPhysics;
     }
 
@@ -898,7 +_,7 @@
     }
 
     protected BlockPos getOnPos(float yOffset) {
-        if (this.mainSupportingBlockPos.isPresent()) {
+        if (this.mainSupportingBlockPos.isPresent() && this.level().getChunkIfLoadedImmediately(this.mainSupportingBlockPos.get()) != null) { // Paper - ensure no loads
             BlockPos blockPos = this.mainSupportingBlockPos.get();
             if (!(yOffset > 1.0E-5F)) {
                 return blockPos;
@@ -971,35 +_,77 @@
         return distance;
     }
 
-    private Vec3 collide(Vec3 vec) {
-        AABB boundingBox = this.getBoundingBox();
-        List<VoxelShape> entityCollisions = this.level().getEntityCollisions(this, boundingBox.expandTowards(vec));
-        Vec3 vec3 = vec.lengthSqr() == 0.0 ? vec : collideBoundingBox(this, vec, boundingBox, this.level(), entityCollisions);
-        boolean flag = vec.x != vec3.x;
-        boolean flag1 = vec.y != vec3.y;
-        boolean flag2 = vec.z != vec3.z;
-        boolean flag3 = flag1 && vec.y < 0.0;
-        if (this.maxUpStep() > 0.0F && (flag3 || this.onGround()) && (flag || flag2)) {
-            AABB aabb = flag3 ? boundingBox.move(0.0, vec3.y, 0.0) : boundingBox;
-            AABB aabb1 = aabb.expandTowards(vec.x, this.maxUpStep(), vec.z);
-            if (!flag3) {
-                aabb1 = aabb1.expandTowards(0.0, -1.0E-5F, 0.0);
-            }
-
-            List<VoxelShape> list = collectColliders(this, this.level, entityCollisions, aabb1);
-            float f = (float)vec3.y;
-            float[] floats = collectCandidateStepUpHeights(aabb, list, this.maxUpStep(), f);
-
-            for (float f1 : floats) {
-                Vec3 vec31 = collideWithShapes(new Vec3(vec.x, f1, vec.z), aabb, list);
-                if (vec31.horizontalDistanceSqr() > vec3.horizontalDistanceSqr()) {
-                    double d = boundingBox.minY - aabb.minY;
-                    return vec31.subtract(0.0, d, 0.0);
-                }
-            }
-        }
-
-        return vec3;
+    // Paper start - optimise collisions
+    private Vec3 collide(Vec3 movement) {
+        final boolean xZero = movement.x == 0.0;
+        final boolean yZero = movement.y == 0.0;
+        final boolean zZero = movement.z == 0.0;
+        if (xZero & yZero & zZero) {
+            return movement;
+        }
+
+        final AABB currentBox = this.getBoundingBox();
+
+        final List<VoxelShape> potentialCollisionsVoxel = new ArrayList<>();
+        final List<AABB> potentialCollisionsBB = new ArrayList<>();
+
+        final AABB initialCollisionBox;
+        if (xZero & zZero) {
+            // note: xZero & zZero -> collision on x/z == 0 -> no step height calculation
+            // this specifically optimises entities standing still
+            initialCollisionBox = movement.y < 0.0 ?
+                ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.cutDownwards(currentBox, movement.y) : ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.cutUpwards(currentBox, movement.y);
+        } else {
+            initialCollisionBox = currentBox.expandTowards(movement);
+        }
+
+        final List<AABB> entityAABBs = new ArrayList<>();
+        ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.getEntityHardCollisions(
+            this.level, (Entity)(Object)this, initialCollisionBox, entityAABBs, 0, null
+        );
+
+        ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.getCollisionsForBlocksOrWorldBorder(
+            this.level, (Entity)(Object)this, initialCollisionBox, potentialCollisionsVoxel, potentialCollisionsBB,
+            ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.COLLISION_FLAG_CHECK_BORDER, null
+        );
+        potentialCollisionsBB.addAll(entityAABBs);
+        final Vec3 collided = ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.performCollisions(movement, currentBox, potentialCollisionsVoxel, potentialCollisionsBB);
+
+        final boolean collidedX = collided.x != movement.x;
+        final boolean collidedY = collided.y != movement.y;
+        final boolean collidedZ = collided.z != movement.z;
+
+        final boolean collidedDownwards = collidedY && movement.y < 0.0;
+
+        final double stepHeight;
+
+        if ((!collidedDownwards && !this.onGround) || (!collidedX && !collidedZ) || (stepHeight = (double)this.maxUpStep()) <= 0.0) {
+            return collided;
+        }
+
+        final AABB collidedYBox = collidedDownwards ? currentBox.move(0.0, collided.y, 0.0) : currentBox;
+        AABB stepRetrievalBox = collidedYBox.expandTowards(movement.x, stepHeight, movement.z);
+        if (!collidedDownwards) {
+            stepRetrievalBox = stepRetrievalBox.expandTowards(0.0, (double)-1.0E-5F, 0.0);
+        }
+
+        final List<VoxelShape> stepVoxels = new ArrayList<>();
+        final List<AABB> stepAABBs = entityAABBs;
+
+        ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.getCollisionsForBlocksOrWorldBorder(
+            this.level, (Entity)(Object)this, stepRetrievalBox, stepVoxels, stepAABBs,
+            ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.COLLISION_FLAG_CHECK_BORDER, null
+        );
+
+        for (final float step : calculateStepHeights(collidedYBox, stepVoxels, stepAABBs, (float)stepHeight, (float)collided.y)) {
+            final Vec3 stepResult = ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.performCollisions(new Vec3(movement.x, (double)step, movement.z), collidedYBox, stepVoxels, stepAABBs);
+            if (stepResult.horizontalDistanceSqr() > collided.horizontalDistanceSqr()) {
+                return stepResult.add(0.0, collidedYBox.minY - currentBox.minY, 0.0);
+            }
+        }
+
+        return collided;
+        // Paper end - optimise collisions
     }
 
     private static float[] collectCandidateStepUpHeights(AABB box, List<VoxelShape> colliders, float deltaY, float maxUpStep) {
@@ -1070,15 +_,15 @@
         return (int)this.moveDist + 1;
     }
 
-    protected SoundEvent getSwimSound() {
+    public SoundEvent getSwimSound() {
         return SoundEvents.GENERIC_SWIM;
     }
 
-    protected SoundEvent getSwimSplashSound() {
+    public SoundEvent getSwimSplashSound() {
         return SoundEvents.GENERIC_SPLASH;
     }
 
-    protected SoundEvent getSwimHighSpeedSplashSound() {
+    public SoundEvent getSwimHighSpeedSplashSound() {
         return SoundEvents.GENERIC_SPLASH;
     }
 
@@ -1104,7 +_,7 @@
                                         || this.collidedWithShapeMovingFrom(vec3, vec31, entityInsideCollisionShape.move(new Vec3(pos)).toAabbs());
                                     if (flag) {
                                         try {
-                                            stepBasedCollector.advanceStep(step);
+                                            stepBasedCollector.advanceStep(step, pos); // Paper - track position inside effect was triggered on
                                             blockState.entityInside(this.level(), pos, this, stepBasedCollector);
                                             this.onInsideBlock(blockState);
                                         } catch (Throwable var14) {
@@ -1119,7 +_,7 @@
 
                                     boolean flag1 = this.collidedWithFluid(blockState.getFluidState(), pos, vec3, vec31);
                                     if (flag1) {
-                                        stepBasedCollector.advanceStep(step);
+                                        stepBasedCollector.advanceStep(step, pos); // Paper - track position inside effect was triggered on
                                         blockState.getFluidState().entityInside(this.level(), pos, this, stepBasedCollector);
                                     }
                                 }
@@ -1332,7 +_,7 @@
         return this.wasTouchingWater;
     }
 
-    boolean isInRain() {
+    public boolean isInRain() {
         BlockPos blockPos = this.blockPosition();
         return this.level().isRainingAt(blockPos)
             || this.level().isRainingAt(BlockPos.containing(blockPos.getX(), this.getBoundingBox().maxY, blockPos.getZ()));
@@ -1519,6 +_,7 @@
         this.setXRot(Mth.clamp(xRot, -90.0F, 90.0F) % 360.0F);
         this.yRotO = this.getYRot();
         this.xRotO = this.getXRot();
+        this.setYHeadRot(yRot); // Paper - Update head rotation
     }
 
     public void absSnapTo(double x, double y, double z) {
@@ -1528,6 +_,7 @@
         this.yo = y;
         this.zo = d1;
         this.setPos(d, y, d1);
+        if (this.valid) this.level.getChunk((int) Math.floor(this.getX()) >> 4, (int) Math.floor(this.getZ()) >> 4); // CraftBukkit
     }
 
     public void snapTo(Vec3 pos) {
@@ -1547,11 +_,19 @@
     }
 
     public void snapTo(double x, double y, double z, float yRot, float xRot) {
+        // Paper start - Fix Entity Teleportation and cancel velocity if teleported
+        if (!this.preserveMotion) {
+            this.deltaMovement = Vec3.ZERO;
+        } else {
+            this.preserveMotion = false;
+        }
+        // Paper end - Fix Entity Teleportation and cancel velocity if teleported
         this.setPosRaw(x, y, z);
         this.setYRot(yRot);
         this.setXRot(xRot);
         this.setOldPosAndRot();
         this.reapplyPosition();
+        this.setYHeadRot(yRot); // Paper - Update head rotation
     }
 
     public final void setOldPosAndRot() {
@@ -1618,6 +_,7 @@
     public void push(Entity entity) {
         if (!this.isPassengerOfSameVehicle(entity)) {
             if (!entity.noPhysics && !this.noPhysics) {
+                if (this.level.paperConfig().collisions.onlyPlayersCollide && !(entity instanceof ServerPlayer || this instanceof ServerPlayer)) return; // Paper - Collision option for requiring a player participant
                 double d = entity.getX() - this.getX();
                 double d1 = entity.getZ() - this.getZ();
                 double max = Mth.absMax(d, d1);
@@ -1651,7 +_,21 @@
     }
 
     public void push(double x, double y, double z) {
-        this.setDeltaMovement(this.getDeltaMovement().add(x, y, z));
+        // Paper start - Add EntityKnockbackByEntityEvent and EntityPushedByEntityAttackEvent
+        this.push(x, y, z, null);
+    }
+
+    public void push(double x, double y, double z, @Nullable Entity pushingEntity) {
+        org.bukkit.util.Vector delta = new org.bukkit.util.Vector(x, y, z);
+        if (pushingEntity != null) {
+            io.papermc.paper.event.entity.EntityPushedByEntityAttackEvent event = new io.papermc.paper.event.entity.EntityPushedByEntityAttackEvent(this.getBukkitEntity(), io.papermc.paper.event.entity.EntityKnockbackEvent.Cause.PUSH, pushingEntity.getBukkitEntity(), delta);
+            if (!event.callEvent()) {
+                return;
+            }
+            delta = event.getKnockback();
+        }
+        this.setDeltaMovement(this.getDeltaMovement().add(delta.getX(), delta.getY(), delta.getZ()));
+        // Paper end - Add EntityKnockbackByEntityEvent and EntityPushedByEntityAttackEvent
         this.hasImpulse = true;
     }
 
@@ -1758,8 +_,20 @@
     }
 
     public boolean isPushable() {
+        // Paper start - Climbing should not bypass cramming gamerule
+        return isCollidable(false);
+    }
+
+    public boolean isCollidable(boolean ignoreClimbing) {
+        // Paper end - Climbing should not bypass cramming gamerule
         return false;
     }
+
+    // CraftBukkit start - collidable API
+    public boolean canCollideWithBukkit(Entity entity) {
+        return this.isPushable();
+    }
+    // CraftBukkit end
 
     public void awardKillScore(Entity entity, DamageSource damageSource) {
         if (entity instanceof ServerPlayer) {
@@ -1786,15 +_,23 @@
     }
 
     public boolean saveAsPassenger(CompoundTag compound) {
-        if (this.removalReason != null && !this.removalReason.shouldSave()) {
+        // CraftBukkit start - allow excluding certain data when saving
+        // Paper start - Raw entity serialization API
+        return this.saveAsPassenger(compound, true, false, false);
+    }
+
+    public boolean saveAsPassenger(CompoundTag compound, boolean includeAll, boolean includeNonSaveable, boolean forceSerialization) {
+        // Paper end - Raw entity serialization API
+        // CraftBukkit end
+        if (this.removalReason != null && !this.removalReason.shouldSave() && !forceSerialization) { // Paper - Raw entity serialization API
             return false;
         } else {
-            String encodeId = this.getEncodeId();
-            if (encodeId == null) {
+            String encodeId = this.getEncodeId(includeNonSaveable); // Paper - Raw entity serialization API
+            if ((!this.persist && !forceSerialization) || encodeId == null) { // CraftBukkit - persist flag // Paper - Raw entity serialization API
                 return false;
             } else {
                 compound.putString("id", encodeId);
-                this.saveWithoutId(compound);
+                this.saveWithoutId(compound, includeAll, includeNonSaveable, forceSerialization); // CraftBukkit - pass on includeAll // Paper - Raw entity serialization API
                 return true;
             }
         }
@@ -1805,14 +_,35 @@
     }
 
     public CompoundTag saveWithoutId(CompoundTag compound) {
+        // CraftBukkit start - allow excluding certain data when saving
+        // Paper start - Raw entity serialization API
+        return this.saveWithoutId(compound, true, false, false);
+    }
+
+    public CompoundTag saveWithoutId(CompoundTag compound, boolean includeAll, boolean includeNonSaveable, boolean forceSerialization) {
+        // Paper end - Raw entity serialization API
+        // CraftBukkit end
         try {
+            if (includeAll) { // CraftBukkit - selectively save position
             if (this.vehicle != null) {
                 compound.store("Pos", Vec3.CODEC, new Vec3(this.vehicle.getX(), this.getY(), this.vehicle.getZ()));
             } else {
                 compound.store("Pos", Vec3.CODEC, this.position());
             }
+            } // CraftBukkit
 
+            this.setDeltaMovement(io.papermc.paper.util.MCUtil.sanitizeNanInf(this.deltaMovement, 0D)); // Paper - remove NaN values before usage in saving
             compound.store("Motion", Vec3.CODEC, this.getDeltaMovement());
+            // CraftBukkit start - Checking for NaN pitch/yaw and resetting to zero
+            // TODO: make sure this is the best way to address this.
+            if (Float.isNaN(this.yRot)) {
+                this.yRot = 0;
+            }
+
+            if (Float.isNaN(this.xRot)) {
+                this.xRot = 0;
+            }
+            // CraftBukkit end
             compound.store("Rotation", Vec2.CODEC, new Vec2(this.getYRot(), this.getXRot()));
             compound.putDouble("fall_distance", this.fallDistance);
             compound.putShort("Fire", (short)this.remainingFireTicks);
@@ -1820,7 +_,29 @@
             compound.putBoolean("OnGround", this.onGround());
             compound.putBoolean("Invulnerable", this.invulnerable);
             compound.putInt("PortalCooldown", this.portalCooldown);
-            compound.store("UUID", UUIDUtil.CODEC, this.getUUID());
+            // CraftBukkit start - selectively save uuid and world
+            if (includeAll) {
+                compound.store("UUID", UUIDUtil.CODEC, this.getUUID());
+                // PAIL: Check above UUID reads 1.8 properly, ie: UUIDMost / UUIDLeast
+                compound.putLong("WorldUUIDLeast", this.level.getWorld().getUID().getLeastSignificantBits());
+                compound.putLong("WorldUUIDMost", this.level.getWorld().getUID().getMostSignificantBits());
+            }
+            compound.putInt("Bukkit.updateLevel", Entity.CURRENT_LEVEL);
+            if (!this.persist) {
+                compound.putBoolean("Bukkit.persist", this.persist);
+            }
+            if (!this.visibleByDefault) {
+                compound.putBoolean("Bukkit.visibleByDefault", this.visibleByDefault);
+            }
+            if (this.persistentInvisibility) {
+                compound.putBoolean("Bukkit.invisible", this.persistentInvisibility);
+            }
+            // SPIGOT-6907: re-implement LivingEntity#setMaximumAir()
+            if (this.maxAirTicks != this.getDefaultMaxAirSupply()) {
+                compound.putInt("Bukkit.MaxAirSupply", this.getMaxAirSupply());
+            }
+            compound.putInt("Spigot.ticksLived", this.totalEntityAge); // Paper
+            // CraftBukkit end
             Component customName = this.getCustomName();
             if (customName != null) {
                 RegistryOps<Tag> registryOps = this.registryAccess().createSerializationContext(NbtOps.INSTANCE);
@@ -1848,9 +_,12 @@
                 compound.putInt("TicksFrozen", this.getTicksFrozen());
             }
 
-            if (this.hasVisualFire) {
-                compound.putBoolean("HasVisualFire", this.hasVisualFire);
+            // Paper start - improve visual fire API
+            if (this.visualFire.equals(net.kyori.adventure.util.TriState.TRUE)) {
+                compound.putBoolean("HasVisualFire", true);
             }
+            compound.putString("Paper.FireOverride", visualFire.name());
+            // Paper end
 
             if (!this.tags.isEmpty()) {
                 compound.store("Tags", TAG_LIST_CODEC, List.copyOf(this.tags));
@@ -1860,13 +_,13 @@
                 compound.store("data", CustomData.CODEC, this.customData);
             }
 
-            this.addAdditionalSaveData(compound);
+            this.addAdditionalSaveData(compound, includeAll); // CraftBukkit - pass on includeAll
             if (this.isVehicle()) {
                 ListTag listTag = new ListTag();
 
                 for (Entity entity : this.getPassengers()) {
                     CompoundTag compoundTag = new CompoundTag();
-                    if (entity.saveAsPassenger(compoundTag)) {
+                    if (entity.saveAsPassenger(compoundTag, includeAll, includeNonSaveable, forceSerialization)) { // CraftBukkit - pass on includeAll // Paper - Raw entity serialization API
                         listTag.add(compoundTag);
                     }
                 }
@@ -1876,6 +_,33 @@
                 }
             }
 
+            // CraftBukkit start - stores eventually existing bukkit values
+            if (this.bukkitEntity != null) {
+                this.bukkitEntity.storeBukkitValues(compound);
+            }
+            // CraftBukkit end
+            // Paper start
+            if (this.origin != null) {
+                UUID originWorld = this.originWorld != null ? this.originWorld : (this.level != null ? this.level.getWorld().getUID() : null);
+                if (originWorld != null) {
+                    compound.store("Paper.OriginWorld", UUIDUtil.CODEC, originWorld);
+                }
+                compound.store("Paper.Origin", Vec3.CODEC, this.origin);
+            }
+            if (this.spawnReason != null) {
+                compound.putString("Paper.SpawnReason", this.spawnReason.name());
+            }
+            // Save entity's from mob spawner status
+            if (this.spawnedViaMobSpawner) {
+                compound.putBoolean("Paper.FromMobSpawner", true);
+            }
+            if (this.fromNetherPortal) {
+                compound.putBoolean("Paper.FromNetherPortal", true);
+            }
+            if (this.freezeLocked) {
+                compound.putBoolean("Paper.FreezeLock", true);
+            }
+            // Paper end
             return compound;
         } catch (Throwable var8) {
             CrashReport crashReport = CrashReport.forThrowable(var8, "Saving entity NBT");
@@ -1888,7 +_,7 @@
     public void load(CompoundTag compound) {
         try {
             Vec3 vec3 = compound.read("Pos", Vec3.CODEC).orElse(Vec3.ZERO);
-            Vec3 vec31 = compound.read("Motion", Vec3.CODEC).orElse(Vec3.ZERO);
+            Vec3 vec31 = compound.read("Motion", Vec3.CODEC).orElse(Vec3.ZERO); vec31 = io.papermc.paper.util.MCUtil.sanitizeNanInf(vec31, 0D); // Paper - avoid setting NaN values
             Vec2 vec2 = compound.read("Rotation", Vec2.CODEC).orElse(Vec2.ZERO);
             this.setDeltaMovement(Math.abs(vec31.x) > 10.0 ? 0.0 : vec31.x, Math.abs(vec31.y) > 10.0 ? 0.0 : vec31.y, Math.abs(vec31.z) > 10.0 ? 0.0 : vec31.z);
             this.hasImpulse = true;
@@ -1921,7 +_,20 @@
                 this.setNoGravity(compound.getBooleanOr("NoGravity", false));
                 this.setGlowingTag(compound.getBooleanOr("Glowing", false));
                 this.setTicksFrozen(compound.getIntOr("TicksFrozen", 0));
-                this.hasVisualFire = compound.getBooleanOr("HasVisualFire", false);
+                // Paper start - improve visual fire API
+                compound.getString("Paper.FireOverride").ifPresentOrElse(
+                    override -> {
+                        try {
+                            this.visualFire = net.kyori.adventure.util.TriState.valueOf(override);
+                        } catch (final Exception ignored) {
+                            LOGGER.error("Unknown fire override {} for {}", override, this);
+                        }
+                    },
+                    () -> this.visualFire = compound.getBoolean("HasVisualFire")
+                        .map(net.kyori.adventure.util.TriState::byBoolean)
+                        .orElse(net.kyori.adventure.util.TriState.NOT_SET)
+                );
+                // Paper end
                 this.customData = compound.read("data", CustomData.CODEC).orElse(CustomData.EMPTY);
                 this.tags.clear();
                 compound.read("Tags", TAG_LIST_CODEC).ifPresent(this.tags::addAll);
@@ -1932,6 +_,67 @@
             } else {
                 throw new IllegalStateException("Entity has invalid rotation");
             }
+            // CraftBukkit start
+            // Spigot start
+            if (this instanceof net.minecraft.world.entity.LivingEntity) {
+                this.totalEntityAge = compound.getIntOr("Spigot.ticksLived", 0); // Paper
+            }
+            // Spigot end
+            this.persist = compound.getBooleanOr("Bukkit.persist", true);
+            this.visibleByDefault = compound.getBooleanOr("Bukkit.visibleByDefault", true);
+            // SPIGOT-6907: re-implement LivingEntity#setMaximumAir()
+            this.maxAirTicks = compound.getIntOr("Bukkit.MaxAirSupply",this.maxAirTicks);
+            // CraftBukkit end
+
+            // CraftBukkit start
+            // Paper - move world parsing/loading to PlayerList#placeNewPlayer
+            this.getBukkitEntity().readBukkitValues(compound);
+            if (compound.contains("Bukkit.invisible")) {
+                boolean bukkitInvisible = compound.getBooleanOr("Bukkit.invisible", false);
+                this.setInvisible(bukkitInvisible);
+                this.persistentInvisibility = bukkitInvisible;
+            }
+            // CraftBukkit end
+
+            // Paper start
+            Optional<Vec3> originVec = compound.read("Paper.Origin", Vec3.CODEC);
+            if (originVec.isPresent()) {
+                UUID originWorld = null;
+                if (compound.contains("Paper.OriginWorld")) {
+                    originWorld = compound.read("Paper.OriginWorld", UUIDUtil.CODEC).orElse(null);
+                } else if (this.level != null) {
+                    originWorld = this.level.getWorld().getUID();
+                }
+                this.originWorld = originWorld;
+                this.origin = originVec.get();
+            }
+
+            spawnedViaMobSpawner = compound.getBooleanOr("Paper.FromMobSpawner", false); // Restore entity's from mob spawner status
+            fromNetherPortal = compound.getBooleanOr("Paper.FromNetherPortal", false);
+            if (compound.contains("Paper.SpawnReason")) {
+                String spawnReasonName = compound.getString("Paper.SpawnReason").orElse(null);
+                try {
+                    spawnReason = org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.valueOf(spawnReasonName);
+                } catch (Exception ignored) {
+                    LOGGER.error("Unknown SpawnReason " + spawnReasonName + " for " + this);
+                }
+            }
+            if (spawnReason == null) {
+                if (spawnedViaMobSpawner) {
+                    spawnReason = org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.SPAWNER;
+                } else if (this instanceof Mob && (this instanceof net.minecraft.world.entity.animal.Animal || this instanceof net.minecraft.world.entity.animal.AbstractFish) && !((Mob) this).removeWhenFarAway(0.0)) {
+                    if (!compound.getBooleanOr("PersistenceRequired", false)) {
+                        spawnReason = org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.NATURAL;
+                    }
+                }
+            }
+            if (spawnReason == null) {
+                spawnReason = org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DEFAULT;
+            }
+            if (compound.contains("Paper.FreezeLock")) {
+                freezeLocked = compound.getBooleanOr("Paper.FreezeLock", false);
+            }
+            // Paper end
         } catch (Throwable var8) {
             CrashReport crashReport = CrashReport.forThrowable(var8, "Loading entity NBT");
             CrashReportCategory crashReportCategory = crashReport.addCategory("Entity being loaded");
@@ -1945,11 +_,22 @@
     }
 
     @Nullable
-    protected final String getEncodeId() {
+    public final String getEncodeId() {
+        // Paper start - Raw entity serialization API
+        return getEncodeId(false);
+    }
+    public final @Nullable String getEncodeId(boolean includeNonSaveable) {
+        // Paper end - Raw entity serialization API
         EntityType<?> type = this.getType();
         ResourceLocation key = EntityType.getKey(type);
-        return type.canSerialize() && key != null ? key.toString() : null;
-    }
+        return (type.canSerialize() || includeNonSaveable) && key != null ? key.toString() : null; // Paper - Raw entity serialization API
+    }
+
+    // CraftBukkit start - allow excluding certain data when saving
+    protected void addAdditionalSaveData(CompoundTag tag, boolean includeAll) {
+        this.addAdditionalSaveData(tag);
+    }
+    // CraftBukkit end
 
     protected abstract void readAdditionalSaveData(CompoundTag tag);
 
@@ -1972,11 +_,63 @@
 
     @Nullable
     public ItemEntity spawnAtLocation(ServerLevel level, ItemStack stack, float yOffset) {
+        // Paper start - Restore vanilla drops behavior
+        return this.spawnAtLocation(level, stack, yOffset, null);
+    }
+
+    public record DefaultDrop(Item item, org.bukkit.inventory.ItemStack stack, @Nullable java.util.function.Consumer<ItemStack> dropConsumer) {
+        public DefaultDrop(final ItemStack stack, final java.util.function.Consumer<ItemStack> dropConsumer) {
+            this(stack.getItem(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(stack), dropConsumer);
+        }
+
+        public void runConsumer(final java.util.function.Consumer<org.bukkit.inventory.ItemStack> fallback) {
+            if (this.dropConsumer == null || org.bukkit.craftbukkit.inventory.CraftItemType.bukkitToMinecraft(this.stack.getType()) != this.item) {
+                fallback.accept(this.stack);
+            } else {
+                this.dropConsumer.accept(org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(this.stack));
+            }
+        }
+    }
+
+    @Nullable
+    public ItemEntity spawnAtLocation(ServerLevel level, ItemStack stack, float yOffset, @Nullable java.util.function.Consumer<? super ItemEntity> delayedAddConsumer) {
+        // Paper end - Restore vanilla drops behavior
         if (stack.isEmpty()) {
             return null;
         } else {
-            ItemEntity itemEntity = new ItemEntity(level, this.getX(), this.getY() + yOffset, this.getZ(), stack);
+            // CraftBukkit start - Capture drops for death event
+            if (this instanceof net.minecraft.world.entity.LivingEntity && !this.forceDrops) {
+                // Paper start - Restore vanilla drops behavior
+                ((net.minecraft.world.entity.LivingEntity) this).drops.add(new net.minecraft.world.entity.Entity.DefaultDrop(stack, itemStack -> {
+                    ItemEntity itemEntity = new ItemEntity(this.level, this.getX(), this.getY() + (double) yOffset, this.getZ(), itemStack); // stack is copied before consumer
+                    itemEntity.setDefaultPickUpDelay();
+                    this.level.addFreshEntity(itemEntity);
+                    if (delayedAddConsumer != null) delayedAddConsumer.accept(itemEntity);
+                }));
+                // Paper end - Restore vanilla drops behavior
+                return null;
+            }
+            // CraftBukkit end
+            ItemEntity itemEntity = new ItemEntity(level, this.getX(), this.getY() + yOffset, this.getZ(), stack.copy()); // Paper - copy so we can destroy original
+            stack.setCount(0); // Paper - destroy this item - if this ever leaks due to game bugs, ensure it doesn't dupe
+
             itemEntity.setDefaultPickUpDelay();
+            itemEntity.setDefaultPickUpDelay(); // Paper - diff on change (in dropConsumer)
+            // Paper start - Call EntityDropItemEvent
+            return this.spawnAtLocation(level, itemEntity);
+        }
+    }
+    @Nullable
+    public ItemEntity spawnAtLocation(ServerLevel level, ItemEntity itemEntity) {
+        {
+            // Paper end - Call EntityDropItemEvent
+            // CraftBukkit start
+            org.bukkit.event.entity.EntityDropItemEvent event = new org.bukkit.event.entity.EntityDropItemEvent(this.getBukkitEntity(), (org.bukkit.entity.Item) itemEntity.getBukkitEntity());
+            org.bukkit.Bukkit.getPluginManager().callEvent(event);
+            if (event.isCancelled()) {
+                return null;
+            }
+            // CraftBukkit end
             level.addFreshEntity(itemEntity);
             return itemEntity;
         }
@@ -1987,28 +_,126 @@
     }
 
     public boolean isInWall() {
+        // Paper start - optimise collisions
         if (this.noPhysics) {
             return false;
-        } else {
-            float f = this.dimensions.width() * 0.8F;
-            AABB aabb = AABB.ofSize(this.getEyePosition(), f, 1.0E-6, f);
-            return BlockPos.betweenClosedStream(aabb)
-                .anyMatch(
-                    pos -> {
-                        BlockState blockState = this.level().getBlockState(pos);
-                        return !blockState.isAir()
-                            && blockState.isSuffocating(this.level(), pos)
-                            && Shapes.joinIsNotEmpty(blockState.getCollisionShape(this.level(), pos).move(pos), Shapes.create(aabb), BooleanOp.AND);
-                    }
-                );
-        }
+        }
+
+        final double reducedWith = (double)(this.dimensions.width() * 0.8F);
+        final AABB boundingBox = AABB.ofSize(this.getEyePosition(), reducedWith, 1.0E-6D, reducedWith);
+        final Level world = this.level;
+
+        if (ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.isEmpty(boundingBox)) {
+            return false;
+        }
+
+        final int minBlockX = Mth.floor(boundingBox.minX);
+        final int minBlockY = Mth.floor(boundingBox.minY);
+        final int minBlockZ = Mth.floor(boundingBox.minZ);
+
+        final int maxBlockX = Mth.floor(boundingBox.maxX);
+        final int maxBlockY = Mth.floor(boundingBox.maxY);
+        final int maxBlockZ = Mth.floor(boundingBox.maxZ);
+
+        final int minChunkX = minBlockX >> 4;
+        final int minChunkY = minBlockY >> 4;
+        final int minChunkZ = minBlockZ >> 4;
+
+        final int maxChunkX = maxBlockX >> 4;
+        final int maxChunkY = maxBlockY >> 4;
+        final int maxChunkZ = maxBlockZ >> 4;
+
+        final int minSection = ca.spottedleaf.moonrise.common.util.WorldUtil.getMinSection(world);
+        final net.minecraft.world.level.chunk.ChunkSource chunkSource = world.getChunkSource();
+        final BlockPos.MutableBlockPos mutablePos = new BlockPos.MutableBlockPos();
+
+        for (int currChunkZ = minChunkZ; currChunkZ <= maxChunkZ; ++currChunkZ) {
+            for (int currChunkX = minChunkX; currChunkX <= maxChunkX; ++currChunkX) {
+                final net.minecraft.world.level.chunk.LevelChunkSection[] sections = chunkSource.getChunk(currChunkX, currChunkZ, net.minecraft.world.level.chunk.status.ChunkStatus.FULL, true).getSections();
+
+                for (int currChunkY = minChunkY; currChunkY <= maxChunkY; ++currChunkY) {
+                    final int sectionIdx = currChunkY - minSection;
+                    if (sectionIdx < 0 || sectionIdx >= sections.length) {
+                        continue;
+                    }
+                    final net.minecraft.world.level.chunk.LevelChunkSection section = sections[sectionIdx];
+                    if (section.hasOnlyAir()) {
+                        // empty
+                        continue;
+                    }
+
+                    final net.minecraft.world.level.chunk.PalettedContainer<net.minecraft.world.level.block.state.BlockState> blocks = section.states;
+
+                    final int minXIterate = currChunkX == minChunkX ? (minBlockX & 15) : 0;
+                    final int maxXIterate = currChunkX == maxChunkX ? (maxBlockX & 15) : 15;
+                    final int minZIterate = currChunkZ == minChunkZ ? (minBlockZ & 15) : 0;
+                    final int maxZIterate = currChunkZ == maxChunkZ ? (maxBlockZ & 15) : 15;
+                    final int minYIterate = currChunkY == minChunkY ? (minBlockY & 15) : 0;
+                    final int maxYIterate = currChunkY == maxChunkY ? (maxBlockY & 15) : 15;
+
+                    for (int currY = minYIterate; currY <= maxYIterate; ++currY) {
+                        final int blockY = currY | (currChunkY << 4);
+                        mutablePos.setY(blockY);
+                        for (int currZ = minZIterate; currZ <= maxZIterate; ++currZ) {
+                            final int blockZ = currZ | (currChunkZ << 4);
+                            mutablePos.setZ(blockZ);
+                            for (int currX = minXIterate; currX <= maxXIterate; ++currX) {
+                                final int blockX = currX | (currChunkX << 4);
+                                mutablePos.setX(blockX);
+
+                                final BlockState blockState = blocks.get((currX) | (currZ << 4) | ((currY) << 8));
+
+                                if (((ca.spottedleaf.moonrise.patches.collisions.block.CollisionBlockState)blockState).moonrise$emptyCollisionShape()
+                                    || !blockState.isSuffocating(world, mutablePos)) {
+                                    continue;
+                                }
+
+                                // Yes, it does not use the Entity context stuff.
+                                final VoxelShape collisionShape = blockState.getCollisionShape(world, mutablePos);
+
+                                if (collisionShape.isEmpty()) {
+                                    continue;
+                                }
+
+                                final AABB toCollide = boundingBox.move(-(double)blockX, -(double)blockY, -(double)blockZ);
+
+                                final AABB singleAABB = ((ca.spottedleaf.moonrise.patches.collisions.shape.CollisionVoxelShape)collisionShape).moonrise$getSingleAABBRepresentation();
+                                if (singleAABB != null) {
+                                    if (ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.voxelShapeIntersect(singleAABB, toCollide)) {
+                                        return true;
+                                    }
+                                    continue;
+                                }
+
+                                if (ca.spottedleaf.moonrise.patches.collisions.CollisionUtil.voxelShapeIntersectNoEmpty(collisionShape, toCollide)) {
+                                    return true;
+                                }
+                                continue;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        return false;
+        // Paper end - optimise collisions
     }
 
     public InteractionResult interact(Player player, InteractionHand hand) {
         if (this.isAlive() && this instanceof Leashable leashable) {
             if (leashable.getLeashHolder() == player) {
                 if (!this.level().isClientSide()) {
-                    if (player.hasInfiniteMaterials()) {
+                    // CraftBukkit start - fire PlayerUnleashEntityEvent
+                    // Paper start - Expand EntityUnleashEvent
+                    org.bukkit.event.player.PlayerUnleashEntityEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerUnleashEntityEvent(this, player, hand, !player.hasInfiniteMaterials());
+                    if (event.isCancelled()) {
+                        // Paper end - Expand EntityUnleashEvent
+                        ((ServerPlayer) player).connection.send(new net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket(this, leashable.getLeashHolder()));
+                        return InteractionResult.PASS;
+                    }
+                    // CraftBukkit end
+                    if (!event.isDropLeash()) { // Paper - Expand EntityUnleashEvent
                         leashable.removeLeash();
                     } else {
                         leashable.dropLeash();
@@ -2023,6 +_,13 @@
             ItemStack itemInHand = player.getItemInHand(hand);
             if (itemInHand.is(Items.LEAD) && leashable.canHaveALeashAttachedToIt()) {
                 if (!this.level().isClientSide()) {
+                    // CraftBukkit start - fire PlayerLeashEntityEvent
+                    if (org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerLeashEntityEvent(this, player, player, hand).isCancelled()) {
+                        ((ServerPlayer) player).connection.send(new net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket(this, leashable.getLeashHolder()));
+                        player.containerMenu.sendAllDataToRemote(); // Paper - Fix inventory desync
+                        return InteractionResult.PASS;
+                    }
+                    // CraftBukkit end
                     leashable.setLeashedTo(player, true);
                 }
 
@@ -2096,11 +_,11 @@
     }
 
     public boolean startRiding(Entity vehicle, boolean force) {
-        if (vehicle == this.vehicle) {
+        if (vehicle == this.vehicle || vehicle.level != this.level) { // Paper - Ensure entity passenger world matches ridden entity (bad plugins)
             return false;
         } else if (!vehicle.couldAcceptPassenger()) {
             return false;
-        } else if (!this.level().isClientSide() && !vehicle.type.canSerialize()) {
+        } else if (!force && !this.level().isClientSide() && !vehicle.type.canSerialize()) { // SPIGOT-7947: Allow force riding all entities
             return false;
         } else {
             for (Entity entity = vehicle; entity.vehicle != null; entity = entity.vehicle) {
@@ -2110,6 +_,27 @@
             }
 
             if (force || this.canRide(vehicle) && vehicle.canAddPassenger(this)) {
+                // CraftBukkit start
+                if (vehicle.getBukkitEntity() instanceof org.bukkit.entity.Vehicle && this.getBukkitEntity() instanceof org.bukkit.entity.LivingEntity) {
+                    org.bukkit.event.vehicle.VehicleEnterEvent event = new org.bukkit.event.vehicle.VehicleEnterEvent((org.bukkit.entity.Vehicle) vehicle.getBukkitEntity(), this.getBukkitEntity());
+                    // Suppress during worldgen
+                    if (this.valid) {
+                        org.bukkit.Bukkit.getPluginManager().callEvent(event);
+                    }
+                    if (event.isCancelled()) {
+                        return false;
+                    }
+                }
+
+                org.bukkit.event.entity.EntityMountEvent event = new org.bukkit.event.entity.EntityMountEvent(this.getBukkitEntity(), vehicle.getBukkitEntity());
+                // Suppress during worldgen
+                if (this.valid) {
+                    org.bukkit.Bukkit.getPluginManager().callEvent(event);
+                }
+                if (event.isCancelled()) {
+                    return false;
+                }
+                // CraftBukkit end
                 if (this.isPassenger()) {
                     this.stopRiding();
                 }
@@ -2138,15 +_,26 @@
     }
 
     public void removeVehicle() {
+        // Paper start - Force entity dismount during teleportation
+        this.removeVehicle(false);
+    }
+    public void removeVehicle(boolean suppressCancellation) {
+        // Paper end - Force entity dismount during teleportation
         if (this.vehicle != null) {
             Entity entity = this.vehicle;
             this.vehicle = null;
-            entity.removePassenger(this);
+            if (!entity.removePassenger(this, suppressCancellation)) this.vehicle = entity; // CraftBukkit // Paper - Force entity dismount during teleportation
         }
     }
 
     public void stopRiding() {
-        this.removeVehicle();
+        // Paper start - Force entity dismount during teleportation
+        this.stopRiding(false);
+    }
+
+    public void stopRiding(boolean suppressCancellation) {
+        this.removeVehicle(suppressCancellation);
+        // Paper end - Force entity dismount during teleportation
     }
 
     protected void addPassenger(Entity passenger) {
@@ -2170,10 +_,43 @@
         }
     }
 
-    protected void removePassenger(Entity passenger) {
+    // Paper start - Force entity dismount during teleportation
+    protected boolean removePassenger(Entity passenger) {
+        return removePassenger(passenger, false);
+    }
+    protected boolean removePassenger(Entity passenger, boolean suppressCancellation) { // CraftBukkit
+        // Paper end - Force entity dismount during teleportation
         if (passenger.getVehicle() == this) {
             throw new IllegalStateException("Use x.stopRiding(y), not y.removePassenger(x)");
         } else {
+            // CraftBukkit start
+            org.bukkit.craftbukkit.entity.CraftEntity craft = (org.bukkit.craftbukkit.entity.CraftEntity) passenger.getBukkitEntity().getVehicle();
+            Entity orig = craft == null ? null : craft.getHandle();
+            if (this.getBukkitEntity() instanceof org.bukkit.entity.Vehicle && passenger.getBukkitEntity() instanceof org.bukkit.entity.LivingEntity) {
+                org.bukkit.event.vehicle.VehicleExitEvent event = new org.bukkit.event.vehicle.VehicleExitEvent(
+                        (org.bukkit.entity.Vehicle) this.getBukkitEntity(),
+                        (org.bukkit.entity.LivingEntity) passenger.getBukkitEntity(), !suppressCancellation // Paper - Force entity dismount during teleportation
+                );
+                // Suppress during worldgen
+                if (this.valid) {
+                    org.bukkit.Bukkit.getPluginManager().callEvent(event);
+                }
+                org.bukkit.craftbukkit.entity.CraftEntity craftn = (org.bukkit.craftbukkit.entity.CraftEntity) passenger.getBukkitEntity().getVehicle();
+                Entity n = craftn == null ? null : craftn.getHandle();
+                if (event.isCancelled() || n != orig) {
+                    return false;
+                }
+            }
+
+            org.bukkit.event.entity.EntityDismountEvent event = new org.bukkit.event.entity.EntityDismountEvent(passenger.getBukkitEntity(), this.getBukkitEntity(), !suppressCancellation); // Paper - Force entity dismount during teleportation
+            // Suppress during worldgen
+            if (this.valid) {
+                org.bukkit.Bukkit.getPluginManager().callEvent(event);
+            }
+            if (event.isCancelled()) {
+                return false;
+            }
+            // CraftBukkit end
             if (this.passengers.size() == 1 && this.passengers.get(0) == passenger) {
                 this.passengers = ImmutableList.of();
             } else {
@@ -2183,6 +_,7 @@
             passenger.boardingCooldown = 60;
             this.gameEvent(GameEvent.ENTITY_DISMOUNT, passenger);
         }
+        return true; // CraftBukkit
     }
 
     protected boolean canAddPassenger(Entity passenger) {
@@ -2266,8 +_,8 @@
                     TeleportTransition portalDestination = this.portalProcess.getPortalDestination(serverLevel, this);
                     if (portalDestination != null) {
                         ServerLevel level = portalDestination.newLevel();
-                        if (serverLevel.getServer().isLevelEnabled(level)
-                            && (level.dimension() == serverLevel.dimension() || this.canTeleport(serverLevel, level))) {
+                        if (this instanceof ServerPlayer // CraftBukkit - always call event for players
+                            || (level != null && (level.dimension() == serverLevel.dimension() || this.canTeleport(serverLevel, level)))) { // CraftBukkit
                             this.teleport(portalDestination);
                         }
                     }
@@ -2348,7 +_,7 @@
     }
 
     public boolean isCrouching() {
-        return this.hasPose(Pose.CROUCHING);
+        return this.hasPose(net.minecraft.world.entity.Pose.CROUCHING);
     }
 
     public boolean isSprinting() {
@@ -2364,7 +_,7 @@
     }
 
     public boolean isVisuallySwimming() {
-        return this.hasPose(Pose.SWIMMING);
+        return this.hasPose(net.minecraft.world.entity.Pose.SWIMMING);
     }
 
     public boolean isVisuallyCrawling() {
@@ -2372,6 +_,13 @@
     }
 
     public void setSwimming(boolean swimming) {
+        // CraftBukkit start
+        if (this.valid && this.isSwimming() != swimming && this instanceof net.minecraft.world.entity.LivingEntity) {
+            if (org.bukkit.craftbukkit.event.CraftEventFactory.callToggleSwimEvent((net.minecraft.world.entity.LivingEntity) this, swimming).isCancelled()) {
+                return;
+            }
+        }
+        // CraftBukkit end
         this.setSharedFlag(4, swimming);
     }
 
@@ -2410,6 +_,7 @@
 
     @Nullable
     public PlayerTeam getTeam() {
+        if (!this.level().paperConfig().scoreboards.allowNonPlayerEntitiesOnScoreboards && !(this instanceof Player)) { return null; } // Paper - Perf: Disable Scoreboards for non players by default
         return this.level().getScoreboard().getPlayersTeam(this.getScoreboardName());
     }
 
@@ -2426,14 +_,18 @@
     }
 
     public void setInvisible(boolean invisible) {
-        this.setSharedFlag(5, invisible);
+        // CraftBukkit - start
+        if (!this.persistentInvisibility) { // Prevent Minecraft from removing our invisibility flag
+            this.setSharedFlag(5, invisible);
+        }
+        // CraftBukkit - end
     }
 
-    protected boolean getSharedFlag(int flag) {
+    public boolean getSharedFlag(int flag) {
         return (this.entityData.get(DATA_SHARED_FLAGS_ID) & 1 << flag) != 0;
     }
 
-    protected void setSharedFlag(int flag, boolean set) {
+    public void setSharedFlag(int flag, boolean set) {
         byte b = this.entityData.get(DATA_SHARED_FLAGS_ID);
         if (set) {
             this.entityData.set(DATA_SHARED_FLAGS_ID, (byte)(b | 1 << flag));
@@ -2443,7 +_,7 @@
     }
 
     public int getMaxAirSupply() {
-        return 300;
+        return this.maxAirTicks; // CraftBukkit - SPIGOT-6907: re-implement LivingEntity#setMaximumAir()
     }
 
     public int getAirSupply() {
@@ -2451,10 +_,22 @@
     }
 
     public void setAirSupply(int air) {
-        this.entityData.set(DATA_AIR_SUPPLY_ID, air);
+        // CraftBukkit start
+        org.bukkit.event.entity.EntityAirChangeEvent event = new org.bukkit.event.entity.EntityAirChangeEvent(this.getBukkitEntity(), air);
+        // Suppress during worldgen
+        if (this.valid) {
+            event.getEntity().getServer().getPluginManager().callEvent(event);
+        }
+        if (event.isCancelled() && this.getAirSupply() != air) {
+            this.entityData.markDirty(Entity.DATA_AIR_SUPPLY_ID);
+            return;
+        }
+        this.entityData.set(Entity.DATA_AIR_SUPPLY_ID, event.getAmount());
+        // CraftBukkit end
     }
 
     public void clearFreeze() {
+        if (this.freezeLocked) return; // Paper - Freeze Tick Lock API
         this.setTicksFrozen(0);
     }
 
@@ -2481,11 +_,43 @@
 
     public void thunderHit(ServerLevel level, LightningBolt lightning) {
         this.setRemainingFireTicks(this.remainingFireTicks + 1);
+        // CraftBukkit start
+        final org.bukkit.entity.Entity thisBukkitEntity = this.getBukkitEntity();
+        final org.bukkit.entity.Entity stormBukkitEntity = lightning.getBukkitEntity();
+        final org.bukkit.plugin.PluginManager pluginManager = org.bukkit.Bukkit.getPluginManager();
+        // CraftBukkit end
         if (this.remainingFireTicks == 0) {
-            this.igniteForSeconds(8.0F);
-        }
-
-        this.hurtServer(level, this.damageSources().lightningBolt(), 5.0F);
+            // CraftBukkit start - Call a combust event when lightning strikes
+            org.bukkit.event.entity.EntityCombustByEntityEvent entityCombustEvent = new org.bukkit.event.entity.EntityCombustByEntityEvent(stormBukkitEntity, thisBukkitEntity, 8.0F);
+            pluginManager.callEvent(entityCombustEvent);
+            if (!entityCombustEvent.isCancelled()) {
+                this.igniteForSeconds(entityCombustEvent.getDuration(), false);
+            // Paper start - fix EntityCombustEvent cancellation
+            } else {
+                this.setRemainingFireTicks(this.remainingFireTicks - 1);
+            // Paper end - fix EntityCombustEvent cancellation
+            }
+            // CraftBukkit end
+        }
+
+        // CraftBukkit start
+        if (thisBukkitEntity instanceof org.bukkit.entity.Hanging) {
+            org.bukkit.event.hanging.HangingBreakByEntityEvent hangingEvent = new org.bukkit.event.hanging.HangingBreakByEntityEvent((org.bukkit.entity.Hanging) thisBukkitEntity, stormBukkitEntity);
+            pluginManager.callEvent(hangingEvent);
+
+            if (hangingEvent.isCancelled()) {
+                return;
+            }
+        }
+
+        if (this.fireImmune()) {
+            return;
+        }
+
+        if (!this.hurtServer(level, this.damageSources().lightningBolt().eventEntityDamager(lightning), 5.0F)) { // Paper - fix DamageSource API
+            return;
+        }
+        // CraftBukkit end
     }
 
     public void onAboveBubbleColumn(boolean downwards, BlockPos pos) {
@@ -2641,30 +_,34 @@
         return this.removalReason != null
             ? String.format(
                 Locale.ROOT,
-                "%s['%s'/%d, l='%s', x=%.2f, y=%.2f, z=%.2f, removed=%s]",
+                "%s['%s'/%d, uuid='%s', l='%s', x=%.2f, y=%.2f, z=%.2f, cpos=%s, tl=%d, v=%b, removed=%s]", // Paper - add more info
                 this.getClass().getSimpleName(),
                 this.getName().getString(),
                 this.id,
+                this.uuid, // Paper - add more info
                 string,
                 this.getX(),
                 this.getY(),
                 this.getZ(),
+                this.chunkPosition(), this.tickCount, this.valid, // Paper - add more info
                 this.removalReason
             )
             : String.format(
                 Locale.ROOT,
-                "%s['%s'/%d, l='%s', x=%.2f, y=%.2f, z=%.2f]",
+                "%s['%s'/%d, uuid='%s', l='%s', x=%.2f, y=%.2f, z=%.2f, cpos=%s, tl=%d, v=%b]", // Paper - add more info
                 this.getClass().getSimpleName(),
                 this.getName().getString(),
                 this.id,
+                this.uuid, // Paper - add more info
                 string,
                 this.getX(),
                 this.getY(),
-                this.getZ()
+                this.getZ(),
+                this.chunkPosition(), this.tickCount, this.valid // Paper - add more info
             );
     }
 
-    protected final boolean isInvulnerableToBase(DamageSource damageSource) {
+    public final boolean isInvulnerableToBase(DamageSource damageSource) {
         return this.isRemoved()
             || this.invulnerable && !damageSource.is(DamageTypeTags.BYPASSES_INVULNERABILITY) && !damageSource.isCreativePlayer()
             || damageSource.is(DamageTypeTags.IS_FIRE) && this.fireImmune()
@@ -2684,6 +_,13 @@
     }
 
     public void restoreFrom(Entity entity) {
+        // Paper start - Forward CraftEntity in teleport command
+        org.bukkit.craftbukkit.entity.CraftEntity bukkitEntity = entity.bukkitEntity;
+        if (bukkitEntity != null) {
+            bukkitEntity.setHandle(this);
+            this.bukkitEntity = bukkitEntity;
+        }
+        // Paper end - Forward CraftEntity in teleport command
         CompoundTag compoundTag = entity.saveWithoutId(new CompoundTag());
         compoundTag.remove("Dimension");
         this.load(compoundTag);
@@ -2693,7 +_,56 @@
 
     @Nullable
     public Entity teleport(TeleportTransition teleportTransition) {
+        // Paper start - Fix item duplication and teleport issues
+        if ((!this.isAlive() || !this.valid) && (teleportTransition.newLevel() != this.level)) {
+            LOGGER.warn("Illegal Entity Teleport {} to {}:{}", this, teleportTransition.newLevel(), teleportTransition.position(), new Throwable());
+            return null;
+        }
+        // Paper end - Fix item duplication and teleport issues
         if (this.level() instanceof ServerLevel serverLevel && !this.isRemoved()) {
+            // CraftBukkit start
+            PositionMoveRotation absolutePosition = PositionMoveRotation.calculateAbsolute(PositionMoveRotation.of(this), PositionMoveRotation.of(teleportTransition), teleportTransition.relatives());
+            Vec3 velocity = absolutePosition.deltaMovement(); // Paper
+            org.bukkit.Location to = org.bukkit.craftbukkit.util.CraftLocation.toBukkit(absolutePosition.position(), teleportTransition.newLevel().getWorld(), absolutePosition.yRot(), absolutePosition.xRot());
+            // Paper start - gateway-specific teleport event
+            final org.bukkit.event.entity.EntityTeleportEvent teleEvent;
+            if (this.portalProcess != null && this.portalProcess.isSamePortal(((net.minecraft.world.level.block.EndGatewayBlock) net.minecraft.world.level.block.Blocks.END_GATEWAY)) && this.level.getBlockEntity(this.portalProcess.getEntryPosition()) instanceof net.minecraft.world.level.block.entity.TheEndGatewayBlockEntity theEndGatewayBlockEntity) {
+                teleEvent = new com.destroystokyo.paper.event.entity.EntityTeleportEndGatewayEvent(this.getBukkitEntity(), this.getBukkitEntity().getLocation(), to, new org.bukkit.craftbukkit.block.CraftEndGateway(to.getWorld(), theEndGatewayBlockEntity));
+                teleEvent.callEvent();
+            } else {
+                teleEvent = org.bukkit.craftbukkit.event.CraftEventFactory.callEntityTeleportEvent(this, to);
+            }
+            // Paper end - gateway-specific teleport event
+            if (teleEvent.isCancelled() || teleEvent.getTo() == null) {
+                return null;
+            }
+            if (!to.equals(teleEvent.getTo())) {
+                to = teleEvent.getTo();
+                teleportTransition = new TeleportTransition(((org.bukkit.craftbukkit.CraftWorld) to.getWorld()).getHandle(), org.bukkit.craftbukkit.util.CraftLocation.toVec3(to), Vec3.ZERO, to.getYaw(), to.getPitch(), teleportTransition.missingRespawnBlock(), teleportTransition.asPassenger(), Set.of(), teleportTransition.postTeleportTransition(), teleportTransition.cause());
+                // Paper start - Call EntityPortalExitEvent
+                velocity = Vec3.ZERO;
+            }
+            if (this.portalProcess != null) { // if in a portal
+                org.bukkit.craftbukkit.entity.CraftEntity bukkitEntity = this.getBukkitEntity();
+                org.bukkit.event.entity.EntityPortalExitEvent event = new org.bukkit.event.entity.EntityPortalExitEvent(
+                    bukkitEntity,
+                    bukkitEntity.getLocation(), to.clone(),
+                    bukkitEntity.getVelocity(), org.bukkit.craftbukkit.util.CraftVector.toBukkit(velocity)
+                );
+                event.callEvent();
+
+                // Only change the target if actually needed, since we reset relative flags
+                if (!event.isCancelled() && event.getTo() != null && (!event.getTo().equals(event.getFrom()) || !event.getAfter().equals(event.getBefore()))) { // todo this looks broken
+                    to = event.getTo().clone();
+                    velocity = org.bukkit.craftbukkit.util.CraftVector.toVec3(event.getAfter());
+                    teleportTransition = new TeleportTransition(((org.bukkit.craftbukkit.CraftWorld) to.getWorld()).getHandle(), org.bukkit.craftbukkit.util.CraftLocation.toVec3(to), velocity, to.getYaw(), to.getPitch(), teleportTransition.missingRespawnBlock(), teleportTransition.asPassenger(), Set.of(), teleportTransition.postTeleportTransition(), teleportTransition.cause());
+                }
+            }
+            if (this.isRemoved()) {
+                return null;
+            }
+            // Paper end - Call EntityPortalExitEvent
+            // CraftBukkit end
             ServerLevel level = teleportTransition.newLevel();
             boolean flag = level.dimension() != serverLevel.dimension();
             if (!teleportTransition.asPassenger()) {
@@ -2742,10 +_,15 @@
             profilerFiller.pop();
             return null;
         } else {
+            // Paper start - Fix item duplication and teleport issues
+            if (this instanceof Leashable leashable) {
+                leashable.dropLeash(); // Paper drop lead
+            }
+            // Paper end - Fix item duplication and teleport issues
             entityx.restoreFrom(this);
             this.removeAfterChangingDimensions();
             entityx.teleportSetPosition(PositionMoveRotation.of(teleportTransition), teleportTransition.relatives());
-            level.addDuringTeleport(entityx);
+            if (this.inWorld) level.addDuringTeleport(entityx); // CraftBukkit - Don't spawn the new entity if the current entity isn't spawned
 
             for (Entity entity2 : list) {
                 entity2.startRiding(entityx, true);
@@ -2818,9 +_,17 @@
     }
 
     protected void removeAfterChangingDimensions() {
-        this.setRemoved(Entity.RemovalReason.CHANGED_DIMENSION);
-        if (this instanceof Leashable leashable) {
-            leashable.removeLeash();
+        this.setRemoved(Entity.RemovalReason.CHANGED_DIMENSION, null); // CraftBukkit - add Bukkit remove cause
+        if (this instanceof Leashable leashable && leashable.isLeashed()) { // Paper - only call if it is leashed
+            // Paper start - Expand EntityUnleashEvent
+            final org.bukkit.event.entity.EntityUnleashEvent event = new org.bukkit.event.entity.EntityUnleashEvent(this.getBukkitEntity(), org.bukkit.event.entity.EntityUnleashEvent.UnleashReason.UNKNOWN, false); // CraftBukkit
+            event.callEvent();
+            if (!event.isDropLeash()) {
+                leashable.removeLeash();
+            } else {
+                leashable.dropLeash();
+            }
+            // Paper end - Expand EntityUnleashEvent
         }
     }
 
@@ -2828,11 +_,37 @@
         return PortalShape.getRelativePosition(portal, axis, this.position(), this.getDimensions(this.getPose()));
     }
 
+    // CraftBukkit start
+    public @Nullable org.bukkit.craftbukkit.event.CraftPortalEvent callPortalEvent(
+        Entity entity,
+        org.bukkit.Location exit,
+        org.bukkit.event.player.PlayerTeleportEvent.TeleportCause cause,
+        int searchRadius, int creationRadius
+    ) {
+        org.bukkit.entity.Entity bukkitEntity = entity.getBukkitEntity();
+        org.bukkit.Location enter = bukkitEntity.getLocation();
+
+        final org.bukkit.PortalType portalType = switch (cause) {
+            case END_PORTAL -> org.bukkit.PortalType.ENDER;
+            case NETHER_PORTAL -> org.bukkit.PortalType.NETHER;
+            case END_GATEWAY -> org.bukkit.PortalType.END_GATEWAY; // not actually used yet
+            default -> org.bukkit.PortalType.CUSTOM;
+        };
+        org.bukkit.event.entity.EntityPortalEvent event = new org.bukkit.event.entity.EntityPortalEvent(bukkitEntity, enter, exit, searchRadius, true, creationRadius, portalType);
+        event.callEvent();
+        if (event.isCancelled() || event.getTo() == null || event.getTo().getWorld() == null || !entity.isAlive()) {
+            return null;
+        }
+        return new org.bukkit.craftbukkit.event.CraftPortalEvent(event);
+    }
+    // CraftBukkit end
+
     public boolean canUsePortal(boolean allowPassengers) {
         return (allowPassengers || !this.isPassenger()) && this.isAlive();
     }
 
     public boolean canTeleport(Level fromLevel, Level toLevel) {
+        if (!this.isAlive() || !this.valid) return false; // Paper - Fix item duplication and teleport issues
         if (fromLevel.dimension() == Level.END && toLevel.dimension() == Level.OVERWORLD) {
             for (Entity entity : this.getPassengers()) {
                 if (entity instanceof ServerPlayer serverPlayer && !serverPlayer.seenCredits) {
@@ -2940,8 +_,14 @@
         return this.entityData.get(DATA_CUSTOM_NAME_VISIBLE);
     }
 
-    public boolean teleportTo(ServerLevel level, double x, double y, double z, Set<Relative> relativeMovements, float yaw, float pitch, boolean setCamera) {
-        Entity entity = this.teleport(new TeleportTransition(level, new Vec3(x, y, z), Vec3.ZERO, yaw, pitch, relativeMovements, TeleportTransition.DO_NOTHING));
+    // CraftBukkit start
+    public final boolean teleportTo(ServerLevel level, double x, double y, double z, Set<Relative> relativeMovements, float yaw, float pitch, boolean setCamera) {
+        return this.teleportTo(level, x, y, z, relativeMovements, yaw, pitch, setCamera, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.UNKNOWN);
+    }
+
+    public boolean teleportTo(ServerLevel level, double x, double y, double z, Set<Relative> relativeMovements, float yaw, float pitch, boolean setCamera, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause cause) {
+        // CraftBukkit end
+        Entity entity = this.teleport(new TeleportTransition(level, new Vec3(x, y, z), Vec3.ZERO, yaw, pitch, relativeMovements, TeleportTransition.DO_NOTHING, cause)); // CraftBukkit
         return entity != null;
     }
 
@@ -2956,7 +_,7 @@
         }
     }
 
-    private void teleportPassengers() {
+    public void teleportPassengers() {
         this.getSelfAndPassengers().forEach(entity -> {
             for (Entity entity1 : entity.passengers) {
                 entity.positionRider(entity1, Entity::snapTo);
@@ -3055,7 +_,26 @@
     }
 
     public final void setBoundingBox(AABB bb) {
-        this.bb = bb;
+        // CraftBukkit start - block invalid bounding boxes
+        double minX = bb.minX,
+                minY = bb.minY,
+                minZ = bb.minZ,
+                maxX = bb.maxX,
+                maxY = bb.maxY,
+                maxZ = bb.maxZ;
+        double len = bb.maxX - bb.minX;
+        if (len < 0) maxX = minX;
+        if (len > 64) maxX = minX + 64.0;
+
+        len = bb.maxY - bb.minY;
+        if (len < 0) maxY = minY;
+        if (len > 64) maxY = minY + 64.0;
+
+        len = bb.maxZ - bb.minZ;
+        if (len < 0) maxZ = minZ;
+        if (len > 64) maxZ = minZ + 64.0;
+        this.bb = new AABB(minX, minY, minZ, maxX, maxY, maxZ);
+        // CraftBukkit end
     }
 
     public final float getEyeHeight(Pose pose) {
@@ -3099,6 +_,12 @@
     }
 
     public void stopSeenByPlayer(ServerPlayer serverPlayer) {
+        // Paper start - entity tracking events
+        // Since this event cannot be cancelled, we should call it here to catch all "un-tracks"
+        if (io.papermc.paper.event.player.PlayerUntrackEntityEvent.getHandlerList().getRegisteredListeners().length > 0) {
+            new io.papermc.paper.event.player.PlayerUntrackEntityEvent(serverPlayer.getBukkitEntity(), this.getBukkitEntity()).callEvent();
+        }
+        // Paper end - entity tracking events
     }
 
     public float rotate(Rotation transformRotation) {
@@ -3132,7 +_,7 @@
     }
 
     @Nullable
-    public LivingEntity getControllingPassenger() {
+    public net.minecraft.world.entity.LivingEntity getControllingPassenger() {
         return null;
     }
 
@@ -3164,21 +_,34 @@
     }
 
     private Stream<Entity> getIndirectPassengersStream() {
+        if (this.passengers.isEmpty()) { return Stream.of(); } // Paper - Optimize indirect passenger iteration
         return this.passengers.stream().flatMap(Entity::getSelfAndPassengers);
     }
 
     @Override
     public Stream<Entity> getSelfAndPassengers() {
+        if (this.passengers.isEmpty()) { return Stream.of(this); } // Paper - Optimize indirect passenger iteration
         return Stream.concat(Stream.of(this), this.getIndirectPassengersStream());
     }
 
     @Override
     public Stream<Entity> getPassengersAndSelf() {
+        if (this.passengers.isEmpty()) { return Stream.of(this); } // Paper - Optimize indirect passenger iteration
         return Stream.concat(this.passengers.stream().flatMap(Entity::getPassengersAndSelf), Stream.of(this));
     }
 
     public Iterable<Entity> getIndirectPassengers() {
-        return () -> this.getIndirectPassengersStream().iterator();
+        // Paper start - optimise entity tracker
+        final List<Entity> ret = new ArrayList<>();
+
+        if (this.passengers.isEmpty()) {
+            return ret;
+        }
+
+        collectIndirectPassengers(ret, this.passengers);
+
+        return ret;
+        // Paper end - optimise entity tracker
     }
 
     public int countPlayerPassengers() {
@@ -3186,6 +_,7 @@
     }
 
     public boolean hasExactlyOnePlayerPassenger() {
+        if (this.passengers.isEmpty()) { return false; } // Paper - Optimize indirect passenger iteration
         return this.countPlayerPassengers() == 1;
     }
 
@@ -3264,13 +_,42 @@
         return SoundSource.NEUTRAL;
     }
 
-    protected int getFireImmuneTicks() {
+    public int getFireImmuneTicks() {
         return 1;
     }
 
+    // CraftBukkit start
+    private final CommandSource commandSource = new CommandSource() {
+
+        @Override
+        public void sendSystemMessage(Component message) {
+        }
+
+        @Override
+        public org.bukkit.command.CommandSender getBukkitSender(CommandSourceStack wrapper) {
+            return Entity.this.getBukkitEntity();
+        }
+
+        @Override
+        public boolean acceptsSuccess() {
+            return ((ServerLevel) Entity.this.level()).getGameRules().getBoolean(net.minecraft.world.level.GameRules.RULE_SENDCOMMANDFEEDBACK);
+        }
+
+        @Override
+        public boolean acceptsFailure() {
+            return true;
+        }
+
+        @Override
+        public boolean shouldInformAdmins() {
+            return true;
+        }
+    };
+    // CraftBukkit end
+
     public CommandSourceStack createCommandSourceStackForNameResolution(ServerLevel level) {
         return new CommandSourceStack(
-            CommandSource.NULL, this.position(), this.getRotationVector(), level, 0, this.getName().getString(), this.getDisplayName(), level.getServer(), this
+            this.commandSource, this.position(), this.getRotationVector(), level, 0, this.getName().getString(), this.getDisplayName(), level.getServer(), this // CraftBukkit
         );
     }
 
@@ -3291,72 +_,136 @@
         return Mth.lerp(partialTick, this.yRotO, this.yRot);
     }
 
-    public boolean updateFluidHeightAndDoFluidPushing(TagKey<Fluid> fluidTag, double motionScale) {
+    // Paper start - optimise collisions
+    public boolean updateFluidHeightAndDoFluidPushing(final TagKey<Fluid> fluid, final double flowScale) {
         if (this.touchingUnloadedChunk()) {
             return false;
-        } else {
-            AABB aabb = this.getBoundingBox().deflate(0.001);
-            int floor = Mth.floor(aabb.minX);
-            int ceil = Mth.ceil(aabb.maxX);
-            int floor1 = Mth.floor(aabb.minY);
-            int ceil1 = Mth.ceil(aabb.maxY);
-            int floor2 = Mth.floor(aabb.minZ);
-            int ceil2 = Mth.ceil(aabb.maxZ);
-            double d = 0.0;
-            boolean isPushedByFluid = this.isPushedByFluid();
-            boolean flag = false;
-            Vec3 vec3 = Vec3.ZERO;
-            int i = 0;
-            BlockPos.MutableBlockPos mutableBlockPos = new BlockPos.MutableBlockPos();
-
-            for (int i1 = floor; i1 < ceil; i1++) {
-                for (int i2 = floor1; i2 < ceil1; i2++) {
-                    for (int i3 = floor2; i3 < ceil2; i3++) {
-                        mutableBlockPos.set(i1, i2, i3);
-                        FluidState fluidState = this.level().getFluidState(mutableBlockPos);
-                        if (fluidState.is(fluidTag)) {
-                            double d1 = i2 + fluidState.getHeight(this.level(), mutableBlockPos);
-                            if (d1 >= aabb.minY) {
-                                flag = true;
-                                d = Math.max(d1 - aabb.minY, d);
-                                if (isPushedByFluid) {
-                                    Vec3 flow = fluidState.getFlow(this.level(), mutableBlockPos);
-                                    if (d < 0.4) {
-                                        flow = flow.scale(d);
-                                    }
-
-                                    vec3 = vec3.add(flow);
-                                    i++;
+        }
+
+        final AABB boundingBox = this.getBoundingBox().deflate(1.0E-3);
+
+        final Level world = this.level;
+        final int minSection = ca.spottedleaf.moonrise.common.util.WorldUtil.getMinSection(world);
+
+        final int minBlockX = Mth.floor(boundingBox.minX);
+        final int minBlockY = Math.max((minSection << 4), Mth.floor(boundingBox.minY));
+        final int minBlockZ = Mth.floor(boundingBox.minZ);
+
+        // note: bounds are exclusive in Vanilla, so we subtract 1 - our loop expects bounds to be inclusive
+        final int maxBlockX = Mth.ceil(boundingBox.maxX) - 1;
+        final int maxBlockY = Math.min((ca.spottedleaf.moonrise.common.util.WorldUtil.getMaxSection(world) << 4) | 15, Mth.ceil(boundingBox.maxY) - 1);
+        final int maxBlockZ = Mth.ceil(boundingBox.maxZ) - 1;
+
+        final boolean isPushable = this.isPushedByFluid();
+        final BlockPos.MutableBlockPos mutablePos = new BlockPos.MutableBlockPos();
+
+        Vec3 pushVector = Vec3.ZERO;
+        double totalPushes = 0.0;
+        double maxHeightDiff = 0.0;
+        boolean inFluid = false;
+
+        final int minChunkX = minBlockX >> 4;
+        final int maxChunkX = maxBlockX >> 4;
+
+        final int minChunkY = minBlockY >> 4;
+        final int maxChunkY = maxBlockY >> 4;
+
+        final int minChunkZ = minBlockZ >> 4;
+        final int maxChunkZ = maxBlockZ >> 4;
+
+        final net.minecraft.world.level.chunk.ChunkSource chunkSource = world.getChunkSource();
+
+        for (int currChunkZ = minChunkZ; currChunkZ <= maxChunkZ; ++currChunkZ) {
+            for (int currChunkX = minChunkX; currChunkX <= maxChunkX; ++currChunkX) {
+                final net.minecraft.world.level.chunk.LevelChunkSection[] sections = chunkSource.getChunk(currChunkX, currChunkZ, net.minecraft.world.level.chunk.status.ChunkStatus.FULL, false).getSections();
+
+                // bound y
+                for (int currChunkY = minChunkY; currChunkY <= maxChunkY; ++currChunkY) {
+                    final int sectionIdx = currChunkY - minSection;
+                    if (sectionIdx < 0 || sectionIdx >= sections.length) {
+                        continue;
+                    }
+                    final net.minecraft.world.level.chunk.LevelChunkSection section = sections[sectionIdx];
+                    if (section.hasOnlyAir()) {
+                        // empty
+                        continue;
+                    }
+
+                    final net.minecraft.world.level.chunk.PalettedContainer<net.minecraft.world.level.block.state.BlockState> blocks = section.states;
+
+                    final int minXIterate = currChunkX == minChunkX ? (minBlockX & 15) : 0;
+                    final int maxXIterate = currChunkX == maxChunkX ? (maxBlockX & 15) : 15;
+                    final int minZIterate = currChunkZ == minChunkZ ? (minBlockZ & 15) : 0;
+                    final int maxZIterate = currChunkZ == maxChunkZ ? (maxBlockZ & 15) : 15;
+                    final int minYIterate = currChunkY == minChunkY ? (minBlockY & 15) : 0;
+                    final int maxYIterate = currChunkY == maxChunkY ? (maxBlockY & 15) : 15;
+
+                    for (int currY = minYIterate; currY <= maxYIterate; ++currY) {
+                        for (int currZ = minZIterate; currZ <= maxZIterate; ++currZ) {
+                            for (int currX = minXIterate; currX <= maxXIterate; ++currX) {
+                                final FluidState fluidState = blocks.get((currX) | (currZ << 4) | ((currY) << 8)).getFluidState();
+
+                                if (fluidState.isEmpty() || !fluidState.is(fluid)) {
+                                    continue;
+                                }
+
+                                mutablePos.set(currX | (currChunkX << 4), currY | (currChunkY << 4), currZ | (currChunkZ << 4));
+
+                                final double height = (double)((float)mutablePos.getY() + fluidState.getHeight(world, mutablePos));
+                                final double diff = height - boundingBox.minY;
+
+                                if (diff < 0.0) {
+                                    continue;
+                                }
+
+                                inFluid = true;
+                                maxHeightDiff = Math.max(maxHeightDiff, diff);
+
+                                if (!isPushable) {
+                                    continue;
+                                }
+
+                                ++totalPushes;
+
+                                final Vec3 flow = fluidState.getFlow(world, mutablePos);
+
+                                if (diff < 0.4) {
+                                    pushVector = pushVector.add(flow.scale(diff));
+                                } else {
+                                    pushVector = pushVector.add(flow);
                                 }
                             }
                         }
                     }
                 }
             }
-
-            if (vec3.length() > 0.0) {
-                if (i > 0) {
-                    vec3 = vec3.scale(1.0 / i);
-                }
-
-                if (!(this instanceof Player)) {
-                    vec3 = vec3.normalize();
-                }
-
-                Vec3 deltaMovement = this.getDeltaMovement();
-                vec3 = vec3.scale(motionScale);
-                double d2 = 0.003;
-                if (Math.abs(deltaMovement.x) < 0.003 && Math.abs(deltaMovement.z) < 0.003 && vec3.length() < 0.0045000000000000005) {
-                    vec3 = vec3.normalize().scale(0.0045000000000000005);
-                }
-
-                this.setDeltaMovement(this.getDeltaMovement().add(vec3));
-            }
-
-            this.fluidHeight.put(fluidTag, d);
-            return flag;
-        }
+        }
+
+        this.fluidHeight.put(fluid, maxHeightDiff);
+
+        if (pushVector.lengthSqr() == 0.0) {
+            return inFluid;
+        }
+
+        // note: totalPushes != 0 as pushVector != 0
+        pushVector = pushVector.scale(1.0 / totalPushes);
+        final Vec3 currMovement = this.getDeltaMovement();
+
+        if (!((Entity)(Object)this instanceof Player)) {
+            pushVector = pushVector.normalize();
+        }
+
+        pushVector = pushVector.scale(flowScale);
+        if (Math.abs(currMovement.x) < 0.003 && Math.abs(currMovement.z) < 0.003 && pushVector.length() < 0.0045000000000000005) {
+            pushVector = pushVector.normalize().scale(0.0045000000000000005);
+        }
+
+        this.setDeltaMovement(currMovement.add(pushVector));
+
+        // note: inFluid = true here as pushVector != 0
+        return true;
     }
+    // Paper end - optimise collisions
 
     public boolean touchingUnloadedChunk() {
         AABB aabb = this.getBoundingBox().inflate(1.0);
@@ -3425,7 +_,9 @@
     }
 
     public void setDeltaMovement(Vec3 deltaMovement) {
+        synchronized (this.posLock) { // Paper - detailed watchdog information
         this.deltaMovement = deltaMovement;
+        } // Paper - detailed watchdog information
     }
 
     public void addDeltaMovement(Vec3 addend) {
@@ -3488,9 +_,54 @@
         return this.getZ((2.0 * this.random.nextDouble() - 1.0) * scale);
     }
 
+    // Paper start - Block invalid positions and bounding box
+    public static boolean checkPosition(Entity entity, double newX, double newY, double newZ) {
+        if (Double.isFinite(newX) && Double.isFinite(newY) && Double.isFinite(newZ)) {
+            return true;
+        }
+
+        String entityInfo;
+        try {
+            entityInfo = entity.toString();
+        } catch (Exception ex) {
+            entityInfo = "[Entity info unavailable] ";
+        }
+        LOGGER.error("New entity position is invalid! Tried to set invalid position ({},{},{}) for entity {} located at {}, entity info: {}", newX, newY, newZ, entity.getClass().getName(), entity.position(), entityInfo, new Throwable());
+        return false;
+    }
+
     public final void setPosRaw(double x, double y, double z) {
+        this.setPosRaw(x, y, z, false);
+    }
+
+    public final void setPosRaw(double x, double y, double z, boolean forceBoundingBoxUpdate) {
+        // Paper start - rewrite chunk system
+        if (this.updatingSectionStatus) {
+            LOGGER.error(
+                "Refusing to update position for entity " + this + " to position " + new Vec3(x, y, z)
+                    + " since it is processing a section status update", new Throwable()
+            );
+            return;
+        }
+        // Paper end - rewrite chunk system
+        if (!checkPosition(this, x, y, z)) {
+            return;
+        }
+        // Paper end - Block invalid positions and bounding box
+        // Paper start - Fix MC-4
+        if (this instanceof ItemEntity) {
+            if (io.papermc.paper.configuration.GlobalConfiguration.get().misc.fixEntityPositionDesync) {
+                // encode/decode from VecDeltaCodec todo computation changed?
+                x = Mth.lfloor(x * 4096.0) * (1 / 4096.0);
+                y = Mth.lfloor(y * 4096.0) * (1 / 4096.0);
+                z = Mth.lfloor(z * 4096.0) * (1 / 4096.0);
+            }
+        }
+        // Paper end - Fix MC-4
         if (this.position.x != x || this.position.y != y || this.position.z != z) {
+            synchronized (this.posLock) { // Paper - detailed watchdog information
             this.position = new Vec3(x, y, z);
+            } // Paper - detailed watchdog information
             int floor = Mth.floor(x);
             int floor1 = Mth.floor(y);
             int floor2 = Mth.floor(z);
@@ -3504,6 +_,12 @@
 
             this.levelCallback.onMove();
         }
+        // Paper start - Block invalid positions and bounding box; don't allow desync of pos and AABB
+        // hanging has its own special logic
+        if (!(this instanceof net.minecraft.world.entity.decoration.HangingEntity) && (forceBoundingBoxUpdate || this.position.x != x || this.position.y != y || this.position.z != z)) {
+            this.setBoundingBox(this.makeBoundingBox());
+        }
+        // Paper end - Block invalid positions and bounding box
     }
 
     public void checkDespawn() {
@@ -3543,6 +_,12 @@
         return this.getTicksFrozen() > 0;
     }
 
+    // CraftBukkit start
+    public float getBukkitYaw() {
+        return this.yRot;
+    }
+    // CraftBukkit end
+
     public float getYRot() {
         return this.yRot;
     }
@@ -3593,7 +_,15 @@
     }
 
     @Override
-    public final void setRemoved(Entity.RemovalReason removalReason) {
+    public final void setRemoved(Entity.RemovalReason removalReason, @Nullable org.bukkit.event.entity.EntityRemoveEvent.Cause cause) { // CraftBukkit - add Bukkit remove cause
+        // Paper start - rewrite chunk system
+        if (!((ca.spottedleaf.moonrise.patches.chunk_system.level.ChunkSystemLevel)this.level).moonrise$getEntityLookup().canRemoveEntity((Entity)(Object)this)) {
+            LOGGER.warn("Entity " + this + " is currently prevented from being removed from the world since it is processing section status updates", new Throwable());
+            return;
+        }
+        // Paper end - rewrite chunk system
+        org.bukkit.craftbukkit.event.CraftEventFactory.callEntityRemoveEvent(this, cause); // CraftBukkit
+        final boolean alreadyRemoved = this.removalReason != null; // Paper - Folia schedulers
         if (this.removalReason == null) {
             this.removalReason = removalReason;
         }
@@ -3602,15 +_,31 @@
             this.stopRiding();
         }
 
-        this.getPassengers().forEach(Entity::stopRiding);
+        if (this.removalReason != Entity.RemovalReason.UNLOADED_TO_CHUNK) { this.getPassengers().forEach(Entity::stopRiding); } // Paper - rewrite chunk system
         this.levelCallback.onRemove(removalReason);
         this.onRemoval(removalReason);
+        // Paper start - Folia schedulers
+        if (!(this instanceof ServerPlayer) && removalReason != RemovalReason.CHANGED_DIMENSION && !alreadyRemoved) {
+            // Players need to be special cased, because they are regularly removed from the world
+            this.retireScheduler();
+        }
+        // Paper end - Folia schedulers
     }
 
-    protected void unsetRemoved() {
+    public void unsetRemoved() {
         this.removalReason = null;
     }
 
+    // Paper start - Folia schedulers
+    /**
+     * Invoked only when the entity is truly removed from the server, never to be added to any world.
+     */
+    public final void retireScheduler() {
+        // we need to force create the bukkit entity so that the scheduler can be retired...
+        this.getBukkitEntity().taskScheduler.retire();
+    }
+    // Paper end - Folia schedulers
+
     @Override
     public void setLevelCallback(EntityInLevelCallback levelCallback) {
         this.levelCallback = levelCallback;
@@ -3620,7 +_,7 @@
     public boolean shouldBeSaved() {
         return (this.removalReason == null || this.removalReason.shouldSave())
             && !this.isPassenger()
-            && (!this.isVehicle() || !this.hasExactlyOnePlayerPassenger());
+            && (!this.isVehicle() || !((ca.spottedleaf.moonrise.patches.chunk_system.entity.ChunkSystemEntity)this).moonrise$hasAnyPlayerPassengers()); // Paper - rewrite chunk system
     }
 
     @Override
@@ -3636,7 +_,7 @@
         return this.level;
     }
 
-    protected void setLevel(Level level) {
+    public void setLevel(Level level) {
         this.level = level;
     }
 
@@ -3780,4 +_,14 @@
             return this.save;
         }
     }
+
+    // Paper start - Expose entity id counter
+    public static int nextEntityId() {
+        return ENTITY_COUNTER.incrementAndGet();
+    }
+
+    public boolean isTicking() {
+        return ((ServerLevel) this.level()).isPositionEntityTicking(this.blockPosition());
+    }
+    // Paper end - Expose entity id counter
 }
