From 3b7830d80641368bc6590f240a7c77ae00209db3 Mon Sep 17 00:00:00 2001 From: Jason Penilla <11360596+jpenilla@users.noreply.github.com> Date: Wed, 24 Nov 2021 03:06:34 -0800 Subject: [PATCH] p a t c h e s --- .../api/Add-Player-Client-Options-API.patch | 0 .../Broadcast-join-message-to-console.patch | 0 ...layer-is-attempted-to-be-removed-fro.patch | 0 ...-entity-collision-code-if-not-needed.patch | 2 +- .../Implement-Player-Client-Options-API.patch | 6 +- .../server/Improved-Watchdog-Support.patch | 16 +- patches/server/MC-Utils.patch | 25 + .../Optimise-ArraySetSorted-removeIf.patch | 0 ...alSelector-Goal.Flag-Set-operations.patch} | 166 +-- .../server/Optimize-Pathfinding.patch | 0 ...vent-opening-inventories-when-frozen.patch | 0 .../Reduce-Either-Optional-allocation.patch | 0 ...e-memory-footprint-of-NBTTagCompound.patch | 0 ...No-Tick-view-distance-implementation.patch | 699 ---------- ...imise-TickListServer-by-rewriting-it.patch | 1127 ----------------- ...ptimize-Collision-to-not-load-chunks.patch | 121 -- .../Remove-streams-from-PairedQueue.patch | 46 - ...-teleport-command-to-valid-locations.patch | 24 - 18 files changed, 96 insertions(+), 2136 deletions(-) rename patches/{unapplied => }/api/Add-Player-Client-Options-API.patch (100%) rename patches/{unapplied => }/server/Broadcast-join-message-to-console.patch (100%) rename patches/{unapplied => }/server/Don-t-crash-if-player-is-attempted-to-be-removed-fro.patch (100%) rename patches/{unapplied => }/server/Don-t-run-entity-collision-code-if-not-needed.patch (92%) rename patches/{unapplied => }/server/Implement-Player-Client-Options-API.patch (94%) rename patches/{unapplied => }/server/Improved-Watchdog-Support.patch (98%) rename patches/{unapplied => }/server/Optimise-ArraySetSorted-removeIf.patch (100%) rename patches/{unapplied/server/Remove-streams-from-Mob-AI-System.patch => server/Optimize-GoalSelector-Goal.Flag-Set-operations.patch} (53%) rename patches/{unapplied => }/server/Optimize-Pathfinding.patch (100%) rename patches/{unapplied => }/server/Prevent-opening-inventories-when-frozen.patch (100%) rename patches/{unapplied => }/server/Reduce-Either-Optional-allocation.patch (100%) rename patches/{unapplied => }/server/Reduce-memory-footprint-of-NBTTagCompound.patch (100%) delete mode 100644 patches/unapplied/server/No-Tick-view-distance-implementation.patch delete mode 100644 patches/unapplied/server/Optimise-TickListServer-by-rewriting-it.patch delete mode 100644 patches/unapplied/server/Optimize-Collision-to-not-load-chunks.patch delete mode 100644 patches/unapplied/server/Remove-streams-from-PairedQueue.patch delete mode 100644 patches/unapplied/server/Restrict-vanilla-teleport-command-to-valid-locations.patch diff --git a/patches/unapplied/api/Add-Player-Client-Options-API.patch b/patches/api/Add-Player-Client-Options-API.patch similarity index 100% rename from patches/unapplied/api/Add-Player-Client-Options-API.patch rename to patches/api/Add-Player-Client-Options-API.patch diff --git a/patches/unapplied/server/Broadcast-join-message-to-console.patch b/patches/server/Broadcast-join-message-to-console.patch similarity index 100% rename from patches/unapplied/server/Broadcast-join-message-to-console.patch rename to patches/server/Broadcast-join-message-to-console.patch diff --git a/patches/unapplied/server/Don-t-crash-if-player-is-attempted-to-be-removed-fro.patch b/patches/server/Don-t-crash-if-player-is-attempted-to-be-removed-fro.patch similarity index 100% rename from patches/unapplied/server/Don-t-crash-if-player-is-attempted-to-be-removed-fro.patch rename to patches/server/Don-t-crash-if-player-is-attempted-to-be-removed-fro.patch diff --git a/patches/unapplied/server/Don-t-run-entity-collision-code-if-not-needed.patch b/patches/server/Don-t-run-entity-collision-code-if-not-needed.patch similarity index 92% rename from patches/unapplied/server/Don-t-run-entity-collision-code-if-not-needed.patch rename to patches/server/Don-t-run-entity-collision-code-if-not-needed.patch index ac2b692c1a..a32e441ff2 100644 --- a/patches/unapplied/server/Don-t-run-entity-collision-code-if-not-needed.patch +++ b/patches/server/Don-t-run-entity-collision-code-if-not-needed.patch @@ -20,7 +20,7 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000 + return; + } + // Paper end - don't run getEntities if we're not going to use its result - List list = this.level.getEntities(this, this.getBoundingBox(), EntitySelector.pushableBy(this)); + List list = this.level.getEntities((Entity) this, this.getBoundingBox(), EntitySelector.pushableBy(this)); if (!list.isEmpty()) { - int i = this.level.getGameRules().getInt(GameRules.RULE_MAX_ENTITY_CRAMMING); diff --git a/patches/unapplied/server/Implement-Player-Client-Options-API.patch b/patches/server/Implement-Player-Client-Options-API.patch similarity index 94% rename from patches/unapplied/server/Implement-Player-Client-Options-API.patch rename to patches/server/Implement-Player-Client-Options-API.patch index 89f6592911..4ea5f4f350 100644 --- a/patches/unapplied/server/Implement-Player-Client-Options-API.patch +++ b/patches/server/Implement-Player-Client-Options-API.patch @@ -92,16 +92,16 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000 public String locale = null; // CraftBukkit - add, lowercase // Paper - default to null public java.util.Locale adventure$locale = java.util.Locale.US; // Paper public void updateOptions(ServerboundClientInformationPacket packet) { -+ new com.destroystokyo.paper.event.player.PlayerClientOptionsChangeEvent(getBukkitEntity(), packet.language, packet.viewDistance, com.destroystokyo.paper.ClientOption.ChatVisibility.valueOf(packet.getChatVisibility().name()), packet.getChatColors(), new com.destroystokyo.paper.PaperSkinParts(packet.getModelCustomisation()), packet.getMainHand() == HumanoidArm.LEFT ? MainHand.LEFT : MainHand.RIGHT).callEvent(); // Paper - settings event ++ new com.destroystokyo.paper.event.player.PlayerClientOptionsChangeEvent(getBukkitEntity(), packet.language, packet.viewDistance, com.destroystokyo.paper.ClientOption.ChatVisibility.valueOf(packet.chatVisibility().name()), packet.chatColors(), new com.destroystokyo.paper.PaperSkinParts(packet.modelCustomisation()), packet.mainHand() == HumanoidArm.LEFT ? MainHand.LEFT : MainHand.RIGHT).callEvent(); // Paper - settings event // CraftBukkit start - if (getMainArm() != packet.getMainHand()) { + if (getMainArm() != packet.mainHand()) { PlayerChangedMainHandEvent event = new PlayerChangedMainHandEvent(this.getBukkitEntity(), getMainArm() == HumanoidArm.LEFT ? MainHand.LEFT : MainHand.RIGHT); diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java @@ -0,0 +0,0 @@ public class CraftPlayer extends CraftHumanEntity implements Player { - public void setViewDistance(int viewDistance) { + public void setSendViewDistance(int viewDistance) { throw new NotImplementedException("Per-Player View Distance APIs need further understanding to properly implement (There are per world view distances though!)"); // TODO } + diff --git a/patches/unapplied/server/Improved-Watchdog-Support.patch b/patches/server/Improved-Watchdog-Support.patch similarity index 98% rename from patches/unapplied/server/Improved-Watchdog-Support.patch rename to patches/server/Improved-Watchdog-Support.patch index 06f7956581..ac44397338 100644 --- a/patches/unapplied/server/Improved-Watchdog-Support.patch +++ b/patches/server/Improved-Watchdog-Support.patch @@ -181,9 +181,9 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000 // Spigot Start if ( throwable.getCause() != null ) @@ -0,0 +0,0 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop @@ -2020,6 +2022,29 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000 + public boolean hasCommonElements(final OptimizedSmallEnumSet other) { + return (other.backingSet & this.backingSet) != 0; + } ++ ++ public void forEach(final E[] values, final Consumer action) { ++ long iterator = this.getBackingSet(); ++ int wrappedGoalSize = this.size(); ++ for (int i = 0; i < wrappedGoalSize; ++i) { ++ final E type = values[Long.numberOfTrailingZeros(iterator)]; ++ iterator ^= io.papermc.paper.util.IntegerUtil.getTrailingBit(iterator); ++ action.accept(type); ++ } ++ } ++ ++ public boolean anyMatch(final E[] values, final Predicate predicate) { ++ long iterator = this.getBackingSet(); ++ int wrappedGoalSize = this.size(); ++ for (int i = 0; i < wrappedGoalSize; ++i) { ++ final E type = values[Long.numberOfTrailingZeros(iterator)]; ++ iterator ^= io.papermc.paper.util.IntegerUtil.getTrailingBit(iterator); ++ if (predicate.test(type)) { ++ return true; ++ } ++ } ++ return false; ++ } +} diff --git a/src/main/java/io/papermc/paper/chunk/SingleThreadChunkRegionManager.java b/src/main/java/io/papermc/paper/chunk/SingleThreadChunkRegionManager.java new file mode 100644 diff --git a/patches/unapplied/server/Optimise-ArraySetSorted-removeIf.patch b/patches/server/Optimise-ArraySetSorted-removeIf.patch similarity index 100% rename from patches/unapplied/server/Optimise-ArraySetSorted-removeIf.patch rename to patches/server/Optimise-ArraySetSorted-removeIf.patch diff --git a/patches/unapplied/server/Remove-streams-from-Mob-AI-System.patch b/patches/server/Optimize-GoalSelector-Goal.Flag-Set-operations.patch similarity index 53% rename from patches/unapplied/server/Remove-streams-from-Mob-AI-System.patch rename to patches/server/Optimize-GoalSelector-Goal.Flag-Set-operations.patch index d45bd20ff8..9a46927a95 100644 --- a/patches/unapplied/server/Remove-streams-from-Mob-AI-System.patch +++ b/patches/server/Optimize-GoalSelector-Goal.Flag-Set-operations.patch @@ -1,20 +1,17 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Spottedleaf Date: Mon, 6 Apr 2020 17:53:29 -0700 -Subject: [PATCH] Remove streams from Mob AI System +Subject: [PATCH] Optimize GoalSelector Goal.Flag Set operations -The streams hurt performance and allocate tons of garbage, so -replace them with the standard iterator. - -Also optimise the stream.anyMatch statement to move to a bitset +Optimise the stream.anyMatch statement to move to a bitset where we can replace the call with a single bitwise operation. diff --git a/src/main/java/net/minecraft/world/entity/ai/goal/Goal.java b/src/main/java/net/minecraft/world/entity/ai/goal/Goal.java index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 --- a/src/main/java/net/minecraft/world/entity/ai/goal/Goal.java +++ b/src/main/java/net/minecraft/world/entity/ai/goal/Goal.java -@@ -0,0 +0,0 @@ package net.minecraft.world.entity.ai.goal; - import java.util.EnumSet; +@@ -0,0 +0,0 @@ import java.util.EnumSet; + import net.minecraft.util.Mth; public abstract class Goal { - private final EnumSet flags = EnumSet.noneOf(Goal.Flag.class); @@ -48,7 +45,7 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000 + // Paper end - remove streams from pathfindergoalselector } - public static enum Flag { + protected int adjustedTickDelay(int ticks) { diff --git a/src/main/java/net/minecraft/world/entity/ai/goal/GoalSelector.java b/src/main/java/net/minecraft/world/entity/ai/goal/GoalSelector.java index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 --- a/src/main/java/net/minecraft/world/entity/ai/goal/GoalSelector.java @@ -63,7 +60,7 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000 private int tickCount; private int newGoalRate = 3; private int curRate; -+ private static final Goal.Flag[] PATHFINDER_GOAL_TYPES = Goal.Flag.values(); // Paper - remove streams from pathfindergoalselector ++ private static final Goal.Flag[] GOAL_FLAG_VALUES = Goal.Flag.values(); // Paper - remove streams from pathfindergoalselector public GoalSelector(Supplier profiler) { this.profiler = profiler; @@ -77,6 +74,12 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000 - this.availableGoals.removeIf((wrappedGoal) -> { - return wrappedGoal.getGoal() == goal; - }); +- } +- +- private static boolean goalContainsAnyFlags(WrappedGoal goal, EnumSet controls) { +- for(Goal.Flag flag : goal.getFlags()) { +- if (controls.contains(flag)) { +- return true; + // Paper start - remove streams from pathfindergoalselector + for (java.util.Iterator iterator = this.availableGoals.iterator(); iterator.hasNext();) { + WrappedGoal goalWrapped = iterator.next(); @@ -85,111 +88,61 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000 + } + if (goalWrapped.isRunning()) { + goalWrapped.stop(); -+ } + } + iterator.remove(); -+ } + } + // Paper end - remove streams from pathfindergoalselector ++ } + +- return false; ++ private static boolean goalContainsAnyFlags(WrappedGoal goal, com.destroystokyo.paper.util.set.OptimizedSmallEnumSet controls) { ++ return goal.getFlags().hasCommonElements(controls); // Paper + } + + private static boolean goalCanBeReplacedForAllFlags(WrappedGoal goal, Map goalsByControl) { +- for(Goal.Flag flag : goal.getFlags()) { ++ // Paper start ++ return !goal.getFlags().anyMatch(GOAL_FLAG_VALUES, flag -> { + if (!goalsByControl.getOrDefault(flag, NO_GOAL).canBeReplacedBy(goal)) { +- return false; ++ return true; + } +- } +- +- return true; ++ return false; ++ }); ++ // Paper end } public void tick() { - ProfilerFiller profilerFiller = this.profiler.get(); +@@ -0,0 +0,0 @@ public class GoalSelector { profilerFiller.push("goalCleanup"); -- this.getRunningGoals().filter((wrappedGoal) -> { -- return !wrappedGoal.isRunning() || wrappedGoal.getFlags().stream().anyMatch(this.disabledFlags::contains) || !wrappedGoal.canContinueToUse(); -- }).forEach(Goal::stop); -- this.lockedFlags.forEach((flag, wrappedGoal) -> { -+ // Paper start - remove streams from pathfindergoalselector -+ for (java.util.Iterator iterator = this.availableGoals.iterator(); iterator.hasNext();) { -+ WrappedGoal wrappedGoal = iterator.next(); - if (!wrappedGoal.isRunning()) { -- this.lockedFlags.remove(flag); -+ continue; -+ } -+ if (!this.goalTypes.hasCommonElements(wrappedGoal.getFlags()) && wrappedGoal.canContinueToUse()) { -+ continue; -+ } -+ wrappedGoal.stop(); -+ } -+ // Paper end - remove streams from pathfindergoalselector -+ this.lockedFlags.forEach((pathfindergoal_type, pathfindergoalwrapped) -> { -+ if (!pathfindergoalwrapped.isRunning()) { -+ this.lockedFlags.remove(pathfindergoal_type); + + for(WrappedGoal wrappedGoal : this.availableGoals) { +- if (wrappedGoal.isRunning() && (goalContainsAnyFlags(wrappedGoal, this.disabledFlags) || !wrappedGoal.canContinueToUse())) { ++ if (wrappedGoal.isRunning() && (goalContainsAnyFlags(wrappedGoal, this.goalTypes) || !wrappedGoal.canContinueToUse())) { + wrappedGoal.stop(); } - - }); - profilerFiller.pop(); + } +@@ -0,0 +0,0 @@ public class GoalSelector { profilerFiller.push("goalUpdate"); -- this.availableGoals.stream().filter((wrappedGoal) -> { -- return !wrappedGoal.isRunning(); -- }).filter((wrappedGoal) -> { -- return wrappedGoal.getFlags().stream().noneMatch(this.disabledFlags::contains); -- }).filter((wrappedGoal) -> { -- return wrappedGoal.getFlags().stream().allMatch((flag) -> { -- return this.lockedFlags.getOrDefault(flag, NO_GOAL).canBeReplacedBy(wrappedGoal); -- }); -- }).filter(WrappedGoal::canUse).forEach((wrappedGoal) -> { -- wrappedGoal.getFlags().forEach((flag) -> { -- WrappedGoal wrappedGoal2 = this.lockedFlags.getOrDefault(flag, NO_GOAL); -- wrappedGoal2.stop(); -- this.lockedFlags.put(flag, wrappedGoal); -- }); -+ -+ // Paper start - remove streams from pathfindergoalselector -+ goal_update_loop: for (java.util.Iterator iterator = this.availableGoals.iterator(); iterator.hasNext();) { -+ WrappedGoal wrappedGoal = iterator.next(); -+ if (wrappedGoal.isRunning()) { -+ continue; -+ } -+ -+ com.destroystokyo.paper.util.set.OptimizedSmallEnumSet wrappedGoalSet = wrappedGoal.getFlags(); -+ -+ if (this.goalTypes.hasCommonElements(wrappedGoalSet)) { -+ continue; -+ } -+ -+ long iterator1 = wrappedGoalSet.getBackingSet(); -+ int wrappedGoalSize = wrappedGoalSet.size(); -+ for (int i = 0; i < wrappedGoalSize; ++i) { -+ Goal.Flag type = PATHFINDER_GOAL_TYPES[Long.numberOfTrailingZeros(iterator1)]; -+ iterator1 ^= io.papermc.paper.util.IntegerUtil.getTrailingBit(iterator1); -+ WrappedGoal wrapped = this.lockedFlags.getOrDefault(type, GoalSelector.NO_GOAL); -+ if (!wrapped.canBeReplacedBy(wrappedGoal)) { -+ continue goal_update_loop; -+ } -+ } -+ -+ if (!wrappedGoal.canUse()) { -+ continue; -+ } -+ -+ iterator1 = wrappedGoalSet.getBackingSet(); -+ wrappedGoalSize = wrappedGoalSet.size(); -+ for (int i = 0; i < wrappedGoalSize; ++i) { -+ Goal.Flag type = PATHFINDER_GOAL_TYPES[Long.numberOfTrailingZeros(iterator1)]; -+ iterator1 ^= io.papermc.paper.util.IntegerUtil.getTrailingBit(iterator1); -+ WrappedGoal wrapped = this.lockedFlags.getOrDefault(type, GoalSelector.NO_GOAL); -+ -+ wrapped.stop(); -+ this.lockedFlags.put(type, wrappedGoal); -+ } - wrappedGoal.start(); -- }); -+ } -+ // Paper end - remove streams from pathfindergoalselector - profilerFiller.pop(); - profilerFiller.push("goalTick"); -- this.getRunningGoals().forEach(WrappedGoal::tick); -+ // Paper start - remove streams from pathfindergoalselector -+ for (java.util.Iterator iterator = this.availableGoals.iterator(); iterator.hasNext();) { -+ WrappedGoal wrappedGoal = iterator.next(); -+ if (wrappedGoal.isRunning()) { -+ wrappedGoal.tick(); -+ } -+ } -+ // Paper end - remove streams from pathfindergoalselector - profilerFiller.pop(); - } + for(WrappedGoal wrappedGoal2 : this.availableGoals) { +- if (!wrappedGoal2.isRunning() && !goalContainsAnyFlags(wrappedGoal2, this.disabledFlags) && goalCanBeReplacedForAllFlags(wrappedGoal2, this.lockedFlags) && wrappedGoal2.canUse()) { +- for(Goal.Flag flag : wrappedGoal2.getFlags()) { ++ // Paper start ++ if (!wrappedGoal2.isRunning() && !goalContainsAnyFlags(wrappedGoal2, this.goalTypes) && goalCanBeReplacedForAllFlags(wrappedGoal2, this.lockedFlags) && wrappedGoal2.canUse()) { ++ wrappedGoal2.getFlags().forEach(GOAL_FLAG_VALUES, flag -> { ++ // Paper end + WrappedGoal wrappedGoal3 = this.lockedFlags.getOrDefault(flag, NO_GOAL); + wrappedGoal3.stop(); + this.lockedFlags.put(flag, wrappedGoal2); +- } ++ }); // Paper + + wrappedGoal2.start(); + } @@ -0,0 +0,0 @@ public class GoalSelector { } @@ -209,10 +162,9 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000 --- a/src/main/java/net/minecraft/world/entity/ai/goal/WrappedGoal.java +++ b/src/main/java/net/minecraft/world/entity/ai/goal/WrappedGoal.java @@ -0,0 +0,0 @@ public class WrappedGoal extends Goal { - this.goal.setFlags(controls); } -- @Override + @Override - public EnumSet getFlags() { + // Paper start - remove streams from pathfindergoalselector + public com.destroystokyo.paper.util.set.OptimizedSmallEnumSet getFlags() { diff --git a/patches/unapplied/server/Optimize-Pathfinding.patch b/patches/server/Optimize-Pathfinding.patch similarity index 100% rename from patches/unapplied/server/Optimize-Pathfinding.patch rename to patches/server/Optimize-Pathfinding.patch diff --git a/patches/unapplied/server/Prevent-opening-inventories-when-frozen.patch b/patches/server/Prevent-opening-inventories-when-frozen.patch similarity index 100% rename from patches/unapplied/server/Prevent-opening-inventories-when-frozen.patch rename to patches/server/Prevent-opening-inventories-when-frozen.patch diff --git a/patches/unapplied/server/Reduce-Either-Optional-allocation.patch b/patches/server/Reduce-Either-Optional-allocation.patch similarity index 100% rename from patches/unapplied/server/Reduce-Either-Optional-allocation.patch rename to patches/server/Reduce-Either-Optional-allocation.patch diff --git a/patches/unapplied/server/Reduce-memory-footprint-of-NBTTagCompound.patch b/patches/server/Reduce-memory-footprint-of-NBTTagCompound.patch similarity index 100% rename from patches/unapplied/server/Reduce-memory-footprint-of-NBTTagCompound.patch rename to patches/server/Reduce-memory-footprint-of-NBTTagCompound.patch diff --git a/patches/unapplied/server/No-Tick-view-distance-implementation.patch b/patches/unapplied/server/No-Tick-view-distance-implementation.patch deleted file mode 100644 index 32f058c1b5..0000000000 --- a/patches/unapplied/server/No-Tick-view-distance-implementation.patch +++ /dev/null @@ -1,699 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Spottedleaf -Date: Tue, 5 May 2020 21:23:34 -0700 -Subject: [PATCH] No-Tick view distance implementation - -Implements world view distance getters/setters - -Per-Player is absent due to difficulty of maintaining -the diff required to make it happen. - -diff --git a/src/main/java/co/aikar/timings/TimingsExport.java b/src/main/java/co/aikar/timings/TimingsExport.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/co/aikar/timings/TimingsExport.java -+++ b/src/main/java/co/aikar/timings/TimingsExport.java -@@ -0,0 +0,0 @@ public class TimingsExport extends Thread { - pair("gamerules", toObjectMapper(world.getWorld().getGameRules(), rule -> { - return pair(rule, world.getWorld().getGameRuleValue(rule)); - })), -- pair("ticking-distance", world.getChunkSource().chunkMap.getEffectiveViewDistance()) -+ pair("ticking-distance", world.getChunkSource().chunkMap.getEffectiveViewDistance()), -+ pair("notick-viewdistance", world.getChunkSource().chunkMap.getEffectiveNoTickViewDistance()) - )); - })); - -diff --git a/src/main/java/com/destroystokyo/paper/PaperWorldConfig.java b/src/main/java/com/destroystokyo/paper/PaperWorldConfig.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/com/destroystokyo/paper/PaperWorldConfig.java -+++ b/src/main/java/com/destroystokyo/paper/PaperWorldConfig.java -@@ -0,0 +0,0 @@ public class PaperWorldConfig { - lightQueueSize = getInt("light-queue-size", lightQueueSize); - } - -+ public int noTickViewDistance; -+ private void viewDistance() { -+ this.noTickViewDistance = this.getInt("viewdistances.no-tick-view-distance", -1); -+ } -+ - public boolean antiXray; - public EngineMode engineMode; - public int maxBlockHeight; -diff --git a/src/main/java/net/minecraft/server/MCUtil.java b/src/main/java/net/minecraft/server/MCUtil.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/server/MCUtil.java -+++ b/src/main/java/net/minecraft/server/MCUtil.java -@@ -0,0 +0,0 @@ public final class MCUtil { - }); - - worldData.addProperty("name", world.getWorld().getName()); -- worldData.addProperty("view-distance", world.spigotConfig.viewDistance); -+ worldData.addProperty("view-distance", world.getChunkSource().chunkMap.getEffectiveViewDistance()); -+ worldData.addProperty("no-view-distance", world.getChunkSource().chunkMap.getRawNoTickViewDistance()); - worldData.addProperty("keep-spawn-loaded", world.keepSpawnInMemory); - worldData.addProperty("keep-spawn-loaded-range", world.paperConfig.keepLoadedRange); - worldData.addProperty("visible-chunk-count", visibleChunks.size()); -diff --git a/src/main/java/net/minecraft/server/level/ChunkHolder.java b/src/main/java/net/minecraft/server/level/ChunkHolder.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/server/level/ChunkHolder.java -+++ b/src/main/java/net/minecraft/server/level/ChunkHolder.java -@@ -0,0 +0,0 @@ public class ChunkHolder { - - boolean isUpdateQueued = false; // Paper - private final ChunkMap chunkMap; // Paper -+ // Paper start - no-tick view distance -+ public final LevelChunk getSendingChunk() { -+ // it's important that we use getChunkAtIfLoadedImmediately to mirror the chunk sending logic used -+ // in Chunk's neighbour callback -+ LevelChunk ret = this.chunkMap.level.getChunkSource().getChunkAtIfLoadedImmediately(this.pos.x, this.pos.z); -+ if (ret != null && ret.areNeighboursLoaded(1)) { -+ return ret; -+ } -+ return null; -+ } -+ // Paper end - no-tick view distance - - public ChunkHolder(ChunkPos pos, int level, LevelHeightAccessor world, LevelLightEngine lightingProvider, ChunkHolder.LevelChangeListener levelUpdateListener, ChunkHolder.PlayerProvider playersWatchingChunkProvider) { - this.futures = new AtomicReferenceArray(ChunkHolder.CHUNK_STATUSES.size()); -@@ -0,0 +0,0 @@ public class ChunkHolder { - } - - public void blockChanged(BlockPos pos) { -- LevelChunk chunk = this.getTickingChunk(); -+ LevelChunk chunk = this.getSendingChunk(); // Paper - no-tick view distance - - if (chunk != null) { - int i = this.levelHeightAccessor.getSectionIndex(pos.getY()); -@@ -0,0 +0,0 @@ public class ChunkHolder { - } - - public void sectionLightChanged(LightLayer lightType, int y) { -- LevelChunk chunk = this.getTickingChunk(); -+ LevelChunk chunk = this.getSendingChunk(); // Paper - no-tick view distance - - if (chunk != null) { - chunk.setUnsaved(true); -@@ -0,0 +0,0 @@ public class ChunkHolder { - } - - public void broadcast(Packet packet, boolean onlyOnWatchDistanceEdge) { -- this.playerProvider.getPlayers(this.pos, onlyOnWatchDistanceEdge).forEach((entityplayer) -> { -- entityplayer.connection.send(packet); -- }); -+ // Paper start - per player view distance -+ // there can be potential desync with player's last mapped section and the view distance map, so use the -+ // view distance map here. -+ com.destroystokyo.paper.util.misc.PlayerAreaMap viewDistanceMap = this.chunkMap.playerViewDistanceBroadcastMap; -+ com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet players = viewDistanceMap.getObjectsInRange(this.pos); -+ if (players == null) { -+ return; -+ } -+ -+ if (onlyOnWatchDistanceEdge) { // flag -> border only -+ Object[] backingSet = players.getBackingSet(); -+ for (int i = 0, len = backingSet.length; i < len; ++i) { -+ Object temp = backingSet[i]; -+ if (!(temp instanceof ServerPlayer)) { -+ continue; -+ } -+ ServerPlayer player = (ServerPlayer)temp; -+ -+ int viewDistance = viewDistanceMap.getLastViewDistance(player); -+ long lastPosition = viewDistanceMap.getLastCoordinate(player); -+ -+ int distX = Math.abs(net.minecraft.server.MCUtil.getCoordinateX(lastPosition) - this.pos.x); -+ int distZ = Math.abs(net.minecraft.server.MCUtil.getCoordinateZ(lastPosition) - this.pos.z); -+ -+ if (Math.max(distX, distZ) == viewDistance) { -+ player.connection.send(packet); -+ } -+ } -+ } else { -+ Object[] backingSet = players.getBackingSet(); -+ for (int i = 0, len = backingSet.length; i < len; ++i) { -+ Object temp = backingSet[i]; -+ if (!(temp instanceof ServerPlayer)) { -+ continue; -+ } -+ ServerPlayer player = (ServerPlayer)temp; -+ player.connection.send(packet); -+ } -+ } -+ -+ return; -+ // Paper end - per player view distance - } - - public CompletableFuture> getOrScheduleFuture(ChunkStatus targetStatus, ChunkMap chunkStorage) { -diff --git a/src/main/java/net/minecraft/server/level/ChunkMap.java b/src/main/java/net/minecraft/server/level/ChunkMap.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/server/level/ChunkMap.java -+++ b/src/main/java/net/minecraft/server/level/ChunkMap.java -@@ -0,0 +0,0 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider - - // Paper start - distance maps - private final com.destroystokyo.paper.util.misc.PooledLinkedHashSets pooledLinkedPlayerHashSets = new com.destroystokyo.paper.util.misc.PooledLinkedHashSets<>(); -+ // Paper start - no-tick view distance -+ int noTickViewDistance; -+ public final int getRawNoTickViewDistance() { -+ return this.noTickViewDistance; -+ } -+ public final int getEffectiveNoTickViewDistance() { -+ return this.noTickViewDistance == -1 ? this.getEffectiveViewDistance() : this.noTickViewDistance; -+ } -+ public final int getLoadViewDistance() { -+ return Math.max(this.getEffectiveViewDistance(), this.getEffectiveNoTickViewDistance()); -+ } -+ -+ public final com.destroystokyo.paper.util.misc.PlayerAreaMap playerViewDistanceBroadcastMap; -+ public final com.destroystokyo.paper.util.misc.PlayerAreaMap playerViewDistanceTickMap; -+ public final com.destroystokyo.paper.util.misc.PlayerAreaMap playerViewDistanceNoTickMap; -+ // Paper end - no-tick view distance - - void addPlayerToDistanceMaps(ServerPlayer player) { - int chunkX = MCUtil.getChunkCoordinate(player.getX()); - int chunkZ = MCUtil.getChunkCoordinate(player.getZ()); - // Note: players need to be explicitly added to distance maps before they can be updated -+ // Paper start - no-tick view distance -+ int effectiveTickViewDistance = this.getEffectiveViewDistance(); -+ int effectiveNoTickViewDistance = Math.max(this.getEffectiveNoTickViewDistance(), effectiveTickViewDistance); -+ -+ if (!this.skipPlayer(player)) { -+ this.playerViewDistanceTickMap.add(player, chunkX, chunkZ, effectiveTickViewDistance); -+ this.playerViewDistanceNoTickMap.add(player, chunkX, chunkZ, effectiveNoTickViewDistance + 2); // clients need chunk 1 neighbour, and we need another 1 for sending those extra neighbours (as we require neighbours to send) -+ } -+ -+ player.needsChunkCenterUpdate = true; -+ this.playerViewDistanceBroadcastMap.add(player, chunkX, chunkZ, effectiveNoTickViewDistance + 1); // clients need an extra neighbour to render the full view distance configured -+ player.needsChunkCenterUpdate = false; -+ // Paper end - no-tick view distance - } - - void removePlayerFromDistanceMaps(ServerPlayer player) { - -+ // Paper start - no-tick view distance -+ this.playerViewDistanceBroadcastMap.remove(player); -+ this.playerViewDistanceTickMap.remove(player); -+ this.playerViewDistanceNoTickMap.remove(player); -+ // Paper end - no-tick view distance - } - - void updateMaps(ServerPlayer player) { - int chunkX = MCUtil.getChunkCoordinate(player.getX()); - int chunkZ = MCUtil.getChunkCoordinate(player.getZ()); - // Note: players need to be explicitly added to distance maps before they can be updated -+ // Paper start - no-tick view distance -+ int effectiveTickViewDistance = this.getEffectiveViewDistance(); -+ int effectiveNoTickViewDistance = Math.max(this.getEffectiveNoTickViewDistance(), effectiveTickViewDistance); -+ -+ if (!this.skipPlayer(player)) { -+ this.playerViewDistanceTickMap.update(player, chunkX, chunkZ, effectiveTickViewDistance); -+ this.playerViewDistanceNoTickMap.update(player, chunkX, chunkZ, effectiveNoTickViewDistance + 2); // clients need chunk 1 neighbour, and we need another 1 for sending those extra neighbours (as we require neighbours to send) -+ } -+ -+ player.needsChunkCenterUpdate = true; -+ this.playerViewDistanceBroadcastMap.update(player, chunkX, chunkZ, effectiveNoTickViewDistance + 1); // clients need an extra neighbour to render the full view distance configured -+ player.needsChunkCenterUpdate = false; -+ // Paper end - no-tick view distance - } - // Paper end - // Paper start -@@ -0,0 +0,0 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider - this.dataRegionManager = new io.papermc.paper.chunk.SingleThreadChunkRegionManager(this.level, 2, (1.0 / 3.0), 1, 6, "Data", DataRegionData::new, DataRegionSectionData::new); - this.regionManagers.add(this.dataRegionManager); - // Paper end -+ // Paper start - no-tick view distance -+ this.setNoTickViewDistance(this.level.paperConfig.noTickViewDistance); -+ this.playerViewDistanceTickMap = new com.destroystokyo.paper.util.misc.PlayerAreaMap(this.pooledLinkedPlayerHashSets, -+ (ServerPlayer player, int rangeX, int rangeZ, int currPosX, int currPosZ, int prevPosX, int prevPosZ, -+ com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet newState) -> { -+ if (newState.size() != 1) { -+ return; -+ } -+ LevelChunk chunk = ChunkMap.this.level.getChunkSource().getChunkAtIfLoadedMainThreadNoCache(rangeX, rangeZ); -+ if (chunk == null || !chunk.areNeighboursLoaded(2)) { -+ return; -+ } -+ -+ ChunkPos chunkPos = new ChunkPos(rangeX, rangeZ); -+ ChunkMap.this.level.getChunkSource().addTicketAtLevel(TicketType.PLAYER, chunkPos, 31, chunkPos); // entity ticking level, TODO check on update -+ }, -+ (ServerPlayer player, int rangeX, int rangeZ, int currPosX, int currPosZ, int prevPosX, int prevPosZ, -+ com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet newState) -> { -+ if (newState != null) { -+ return; -+ } -+ ChunkPos chunkPos = new ChunkPos(rangeX, rangeZ); -+ ChunkMap.this.level.getChunkSource().removeTicketAtLevel(TicketType.PLAYER, chunkPos, 31, chunkPos); // entity ticking level, TODO check on update -+ }); -+ this.playerViewDistanceNoTickMap = new com.destroystokyo.paper.util.misc.PlayerAreaMap(this.pooledLinkedPlayerHashSets); -+ this.playerViewDistanceBroadcastMap = new com.destroystokyo.paper.util.misc.PlayerAreaMap(this.pooledLinkedPlayerHashSets, -+ (ServerPlayer player, int rangeX, int rangeZ, int currPosX, int currPosZ, int prevPosX, int prevPosZ, -+ com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet newState) -> { -+ if (player.needsChunkCenterUpdate) { -+ player.needsChunkCenterUpdate = false; -+ player.connection.send(new ClientboundSetChunkCacheCenterPacket(currPosX, currPosZ)); -+ } -+ ChunkMap.this.updateChunkTracking(player, new ChunkPos(rangeX, rangeZ), new Packet[2], false, true); // unloaded, loaded -+ }, -+ (ServerPlayer player, int rangeX, int rangeZ, int currPosX, int currPosZ, int prevPosX, int prevPosZ, -+ com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet newState) -> { -+ ChunkMap.this.updateChunkTracking(player, new ChunkPos(rangeX, rangeZ), null, true, false); // unloaded, loaded -+ }); -+ // Paper end - no-tick view distance - } - - private static double euclideanDistanceSquared(ChunkPos pos, Entity entity) { -@@ -0,0 +0,0 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider - completablefuture1.thenAcceptAsync((either) -> { - either.ifLeft((chunk) -> { - this.tickingGenerated.getAndIncrement(); -- Packet[] apacket = new Packet[2]; -- -- this.getPlayers(chunkcoordintpair, false).forEach((entityplayer) -> { -- this.playerLoadedChunk(entityplayer, apacket, chunk); -- }); -+ // Paper - no-tick view distance - moved to Chunk neighbour update - }); - }, (runnable) -> { -- this.mainThreadMailbox.tell(ChunkTaskPriorityQueueSorter.message(holder, runnable)); -+ this.mainThreadMailbox.tell(ChunkTaskPriorityQueueSorter.message(holder, runnable)); // Paper - diff on change, this is the scheduling method copied in Chunk used to schedule chunk broadcasts (on change it needs to be copied again) - }); - return completablefuture1; - } -@@ -0,0 +0,0 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider - } - - public void setViewDistance(int watchDistance) { -- int j = Mth.clamp(watchDistance + 1, 3, 33); -+ int j = Mth.clamp(watchDistance + 1, 3, 33); // Paper - diff on change, these make the lower view distance limit 2 and the upper 32 - - if (j != this.viewDistance) { - int k = this.viewDistance; - - this.viewDistance = j; -- this.distanceManager.updatePlayerTickets(this.viewDistance); -- ObjectIterator objectiterator = this.updatingChunkMap.values().iterator(); -+ this.setNoTickViewDistance(this.getRawNoTickViewDistance()); // Paper - no-tick view distance - propagate changes to no-tick, which does the actual chunk loading/sending -+ } - -- while (objectiterator.hasNext()) { -- ChunkHolder playerchunk = (ChunkHolder) objectiterator.next(); -- ChunkPos chunkcoordintpair = playerchunk.getPos(); -- Packet[] apacket = new Packet[2]; -+ } - -- this.getPlayers(chunkcoordintpair, false).forEach((entityplayer) -> { -- int l = ChunkMap.checkerboardDistance(chunkcoordintpair, entityplayer, true); -- boolean flag = l <= k; -- boolean flag1 = l <= this.viewDistance; -+ // Paper start - no-tick view distance -+ public final void setNoTickViewDistance(int viewDistance) { -+ viewDistance = viewDistance == -1 ? -1 : Mth.clamp(viewDistance, 2, 32); - -- this.updateChunkTracking(entityplayer, chunkcoordintpair, apacket, flag, flag1); -- }); -+ this.noTickViewDistance = viewDistance; -+ int loadViewDistance = this.getLoadViewDistance(); -+ this.distanceManager.setNoTickViewDistance(loadViewDistance + 2 + 2); // add 2 to account for the change to 31 -> 33 tickets // see notes in the distance map updating for the other + 2 -+ -+ if (this.level != null && this.level.players != null) { // this can be called from constructor, where these aren't set -+ for (ServerPlayer player : this.level.players) { -+ net.minecraft.server.network.ServerGamePacketListenerImpl connection = player.connection; -+ if (connection != null) { -+ // moved in from PlayerList -+ connection.send(new net.minecraft.network.protocol.game.ClientboundSetChunkCacheRadiusPacket(loadViewDistance)); -+ } -+ this.updateMaps(player); -+ // Paper end - no-tick view distance - } - } - -@@ -0,0 +0,0 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider - ChunkHolder playerchunk = this.getVisibleChunkIfPresent(pos.toLong()); - - if (playerchunk != null) { -- LevelChunk chunk = playerchunk.getTickingChunk(); -+ LevelChunk chunk = playerchunk.getSendingChunk(); // Paper - no-tick view distance - - if (chunk != null) { - this.playerLoadedChunk(player, packets, chunk); -@@ -0,0 +0,0 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider - this.removePlayerFromDistanceMaps(player); // Paper - distance maps - } - -- for (int k = i - this.viewDistance; k <= i + this.viewDistance; ++k) { -- for (int l = j - this.viewDistance; l <= j + this.viewDistance; ++l) { -- ChunkPos chunkcoordintpair = new ChunkPos(k, l); -- -- this.updateChunkTracking(player, chunkcoordintpair, new Packet[2], !added, added); -- } -- } -+ // Paper - broadcast view distance map handles this (see remove/add calls above) - - } - -@@ -0,0 +0,0 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider - SectionPos sectionposition = SectionPos.of((Entity) player); - - player.setLastSectionPos(sectionposition); -- player.connection.send(new ClientboundSetChunkCacheCenterPacket(sectionposition.x(), sectionposition.z())); -+ // player.connection.send(new ClientboundSetChunkCacheCenterPacket(sectionposition.x(), sectionposition.z())); // Paper - distance map handles this now - return sectionposition; - } - -@@ -0,0 +0,0 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider - int k1; - int l1; - -+ /* // Paper start - replaced by distance map - if (Math.abs(i1 - i) <= this.viewDistance * 2 && Math.abs(j1 - j) <= this.viewDistance * 2) { - k1 = Math.min(i, i1) - this.viewDistance; - l1 = Math.min(j, j1) - this.viewDistance; -@@ -0,0 +0,0 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider - } - } - } -+ */ // Paper end - replaced by distance map - - this.updateMaps(player); // Paper - distance maps - -@@ -0,0 +0,0 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider - - @Override - public Stream getPlayers(ChunkPos chunkPos, boolean onlyOnWatchDistanceEdge) { -- return this.playerMap.getPlayers(chunkPos.toLong()).filter((entityplayer) -> { -- int i = ChunkMap.checkerboardDistance(chunkPos, entityplayer, true); -- -- return i > this.viewDistance ? false : !onlyOnWatchDistanceEdge || i == this.viewDistance; -- }); -+ // Paper start - per player view distance -+ // there can be potential desync with player's last mapped section and the view distance map, so use the -+ // view distance map here. -+ com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet inRange = this.playerViewDistanceBroadcastMap.getObjectsInRange(chunkPos); -+ -+ if (inRange == null) { -+ return Stream.empty(); -+ } -+ // all current cases are inlined so we wont hit this code, it's just in case plugins or future updates use it -+ List players = new java.util.ArrayList<>(); -+ Object[] backingSet = inRange.getBackingSet(); -+ -+ if (onlyOnWatchDistanceEdge) { // flag -> border only -+ for (int i = 0, len = backingSet.length; i < len; ++i) { -+ Object temp = backingSet[i]; -+ if (!(temp instanceof ServerPlayer)) { -+ continue; -+ } -+ ServerPlayer player = (ServerPlayer)temp; -+ int viewDistance = this.playerViewDistanceBroadcastMap.getLastViewDistance(player); -+ long lastPosition = this.playerViewDistanceBroadcastMap.getLastCoordinate(player); -+ -+ int distX = Math.abs(MCUtil.getCoordinateX(lastPosition) - chunkPos.x); -+ int distZ = Math.abs(MCUtil.getCoordinateZ(lastPosition) - chunkPos.z); -+ if (Math.max(distX, distZ) == viewDistance) { -+ players.add(player); -+ } -+ } -+ } else { -+ for (int i = 0, len = backingSet.length; i < len; ++i) { -+ Object temp = backingSet[i]; -+ if (!(temp instanceof ServerPlayer)) { -+ continue; -+ } -+ ServerPlayer player = (ServerPlayer)temp; -+ players.add(player); -+ } -+ } -+ return players.stream(); -+ // Paper end - per player view distance - } - - public void addEntity(Entity entity) { -@@ -0,0 +0,0 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider - - } - -+ // Paper start -+ private static int getLightMask(final LevelChunk chunk) { -+ final net.minecraft.world.level.chunk.LevelChunkSection[] chunkSections = chunk.getSections(); -+ int mask = 0; -+ -+ for (int i = 0; i < chunkSections.length; ++i) { -+ /* -+ -+ -+Lightmasks have 18 bits, from the -1 (void) section until the 17th (air) section. -+Sections go from 0..16. Now whenever a section is not empty, it can potentially change lighting for the section itself, the section below and the section above, hence the bitmask 111b, which is 7d. -+ -+ */ -+ mask |= (net.minecraft.world.level.chunk.LevelChunkSection.isEmpty(chunkSections[i]) ? 0 : 7) << i; -+ } -+ -+ return mask; -+ } -+ -+ private static int getCeilingLightMask(final LevelChunk chunk) { -+ int mask = getLightMask(chunk); -+ -+ /* -+ It is similar to get highest bit, it would turn an 001010 into an 001111 so basically the highest bit and all below. -+ We then invert this, so we'd have 110000 and compare that to the "main" chunk. -+ This is because the bug only appears when the current chunks lightmaps are higher than those of the neighbors, thus we can omit sending neighbors which are lower than the current chunks lights. -+ -+ so TLDR is that getCeilingLightMask returns a light mask with all bits set below the highest affected section. We could also count the number of leading zeros and invert them, somehow. -+ @TODO: Implement Leafs suggestion -+ either use Integer#numberOfLeadingZeros or document what this bithack is supposed to be doing then -+ */ -+ mask |= mask >> 1; -+ mask |= mask >> 2; -+ mask |= mask >> 4; -+ mask |= mask >> 8; -+ mask |= mask >> 16; -+ -+ return mask; -+ } -+ // Paper end -+ - public void playerLoadedChunk(ServerPlayer player, Packet[] packets, LevelChunk chunk) { - if (packets[0] == null) { - packets[0] = new ClientboundLevelChunkPacket(chunk, chunk.level.chunkPacketBlockController.shouldModify(player, chunk)); // Paper - Ani-Xray - Bypass -diff --git a/src/main/java/net/minecraft/server/level/DistanceManager.java b/src/main/java/net/minecraft/server/level/DistanceManager.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/server/level/DistanceManager.java -+++ b/src/main/java/net/minecraft/server/level/DistanceManager.java -@@ -0,0 +0,0 @@ public abstract class DistanceManager { - return s; - } - -- protected void updatePlayerTickets(int viewDistance) { -- this.playerTicketManager.updateViewDistance(viewDistance); -+ protected void setNoTickViewDistance(int i) { // Paper - force abi breakage on usage change -+ this.playerTicketManager.updateViewDistance(i); - } - - public int getNaturalSpawnChunkCount() { -@@ -0,0 +0,0 @@ public abstract class DistanceManager { - - private void onLevelChange(long pos, int distance, boolean oldWithinViewDistance, boolean withinViewDistance) { - if (oldWithinViewDistance != withinViewDistance) { -- Ticket ticket = new Ticket<>(TicketType.PLAYER, DistanceManager.PLAYER_TICKET_LEVEL, new ChunkPos(pos)); -+ Ticket ticket = new Ticket<>(TicketType.PLAYER, 33, new ChunkPos(pos)); // Paper - no-tick view distance - - if (withinViewDistance) { - DistanceManager.this.ticketThrottlerInput.tell(ChunkTaskPriorityQueueSorter.message(() -> { -diff --git a/src/main/java/net/minecraft/server/level/ServerPlayer.java b/src/main/java/net/minecraft/server/level/ServerPlayer.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/server/level/ServerPlayer.java -+++ b/src/main/java/net/minecraft/server/level/ServerPlayer.java -@@ -0,0 +0,0 @@ public class ServerPlayer extends Player { - public PlayerNaturallySpawnCreaturesEvent playerNaturallySpawnedEvent; // Paper - - public final com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet cachedSingleHashSet; // Paper -+ boolean needsChunkCenterUpdate; // Paper - no-tick view distance - - public ServerPlayer(MinecraftServer server, ServerLevel world, GameProfile profile) { - super(world, world.getSharedSpawnPos(), world.getSharedSpawnAngle(), profile); -diff --git a/src/main/java/net/minecraft/server/players/PlayerList.java b/src/main/java/net/minecraft/server/players/PlayerList.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/server/players/PlayerList.java -+++ b/src/main/java/net/minecraft/server/players/PlayerList.java -@@ -0,0 +0,0 @@ public abstract class PlayerList { - boolean flag1 = gamerules.getBoolean(GameRules.RULE_REDUCEDDEBUGINFO); - - // Spigot - view distance -- playerconnection.send(new ClientboundLoginPacket(player.getId(), player.gameMode.getGameModeForPlayer(), player.gameMode.getPreviousGameModeForPlayer(), BiomeManager.obfuscateSeed(worldserver1.getSeed()), worlddata.isHardcore(), this.server.levelKeys(), this.registryHolder, worldserver1.dimensionType(), worldserver1.dimension(), this.getMaxPlayers(), worldserver1.spigotConfig.viewDistance, flag1, !flag, worldserver1.isDebug(), worldserver1.isFlat())); -+ playerconnection.send(new ClientboundLoginPacket(player.getId(), player.gameMode.getGameModeForPlayer(), player.gameMode.getPreviousGameModeForPlayer(), BiomeManager.obfuscateSeed(worldserver1.getSeed()), worlddata.isHardcore(), this.server.levelKeys(), this.registryHolder, worldserver1.dimensionType(), worldserver1.dimension(), this.getMaxPlayers(), worldserver1.getChunkSource().chunkMap.getLoadViewDistance(), flag1, !flag, worldserver1.isDebug(), worldserver1.isFlat())); // Paper - no-tick view distance - player.getBukkitEntity().sendSupportedChannels(); // CraftBukkit - playerconnection.send(new ClientboundCustomPayloadPacket(ClientboundCustomPayloadPacket.BRAND, (new FriendlyByteBuf(Unpooled.buffer())).writeUtf(this.getServer().getServerModName()))); - playerconnection.send(new ClientboundChangeDifficultyPacket(worlddata.getDifficulty(), worlddata.isDifficultyLocked())); -@@ -0,0 +0,0 @@ public abstract class PlayerList { - // CraftBukkit start - LevelData worlddata = worldserver1.getLevelData(); - entityplayer1.connection.send(new ClientboundRespawnPacket(worldserver1.dimensionType(), worldserver1.dimension(), BiomeManager.obfuscateSeed(worldserver1.getSeed()), entityplayer1.gameMode.getGameModeForPlayer(), entityplayer1.gameMode.getPreviousGameModeForPlayer(), worldserver1.isDebug(), worldserver1.isFlat(), flag)); -- entityplayer1.connection.send(new ClientboundSetChunkCacheRadiusPacket(worldserver1.spigotConfig.viewDistance)); // Spigot -+ entityplayer1.connection.send(new ClientboundSetChunkCacheRadiusPacket(worldserver1.getChunkSource().chunkMap.getLoadViewDistance())); // Spigot // Paper - no-tick view distance - entityplayer1.setLevel(worldserver1); - entityplayer1.unsetRemoved(); - entityplayer1.connection.teleport(new Location(worldserver1.getWorld(), entityplayer1.getX(), entityplayer1.getY(), entityplayer1.getZ(), entityplayer1.getYRot(), entityplayer1.getXRot())); -@@ -0,0 +0,0 @@ public abstract class PlayerList { - - public void setViewDistance(int viewDistance) { - this.viewDistance = viewDistance; -- this.broadcastAll(new ClientboundSetChunkCacheRadiusPacket(viewDistance)); -+ //this.sendAll(new PacketPlayOutViewDistance(i)); // Paper - move into setViewDistance - Iterator iterator = this.server.getAllLevels().iterator(); - - while (iterator.hasNext()) { -diff --git a/src/main/java/net/minecraft/world/level/Level.java b/src/main/java/net/minecraft/world/level/Level.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/world/level/Level.java -+++ b/src/main/java/net/minecraft/world/level/Level.java -@@ -0,0 +0,0 @@ public abstract class Level implements LevelAccessor, AutoCloseable { - this.setBlocksDirty(blockposition, iblockdata1, iblockdata2); - } - -- if ((i & 2) != 0 && (!this.isClientSide || (i & 4) == 0) && (this.isClientSide || chunk == null || (chunk.getFullStatus() != null && chunk.getFullStatus().isOrAfter(ChunkHolder.FullChunkStatus.TICKING)))) { // allow chunk to be null here as chunk.isReady() is false when we send our notification during block placement -+ if ((i & 2) != 0 && (!this.isClientSide || (i & 4) == 0) && (this.isClientSide || chunk == null || (chunk.getFullStatus() != null && chunk.getFullStatus().isOrAfter(ChunkHolder.FullChunkStatus.TICKING)))) { // allow chunk to be null here as chunk.isReady() is false when we send our notification during block placement // Paper - diff on change, see below - this.sendBlockUpdated(blockposition, iblockdata1, iblockdata, i); -+ // Paper start - per player view distance - allow block updates for non-ticking chunks in player view distance -+ // if copied from above -+ } else if ((i & 2) != 0 && (!this.isClientSide || (i & 4) == 0) && (this.isClientSide || chunk == null || ((ServerLevel)this).getChunkSource().chunkMap.playerViewDistanceBroadcastMap.getObjectsInRange(MCUtil.getCoordinateKey(blockposition)) != null)) { -+ ((ServerLevel)this).getChunkSource().blockChanged(blockposition); -+ // Paper end - per player view distance - } - - if ((i & 1) != 0) { -diff --git a/src/main/java/net/minecraft/world/level/chunk/LevelChunk.java b/src/main/java/net/minecraft/world/level/chunk/LevelChunk.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/world/level/chunk/LevelChunk.java -+++ b/src/main/java/net/minecraft/world/level/chunk/LevelChunk.java -@@ -0,0 +0,0 @@ import net.minecraft.core.Registry; - import net.minecraft.core.SectionPos; - import net.minecraft.nbt.CompoundTag; - import net.minecraft.network.FriendlyByteBuf; -+import net.minecraft.network.protocol.Packet; - import net.minecraft.server.level.ChunkHolder; -+import net.minecraft.server.level.ChunkMap; -+import net.minecraft.server.level.ChunkTaskPriorityQueueSorter; - import net.minecraft.server.level.ServerChunkCache; - import net.minecraft.server.level.ServerLevel; - import net.minecraft.util.profiling.ProfilerFiller; -@@ -0,0 +0,0 @@ public class LevelChunk implements ChunkAccess { - } - - protected void onNeighbourChange(final long bitsetBefore, final long bitsetAfter) { -+ // Paper start - no-tick view distance -+ ServerChunkCache chunkProviderServer = ((ServerLevel)this.level).getChunkSource(); -+ ChunkMap chunkMap = chunkProviderServer.chunkMap; -+ // this code handles the addition of ticking tickets - the distance map handles the removal -+ if (!areNeighboursLoaded(bitsetBefore, 2) && areNeighboursLoaded(bitsetAfter, 2)) { -+ if (chunkMap.playerViewDistanceTickMap.getObjectsInRange(this.coordinateKey) != null) { -+ // now we're ready for entity ticking -+ chunkProviderServer.mainThreadProcessor.execute(() -> { -+ // double check that this condition still holds. -+ if (LevelChunk.this.areNeighboursLoaded(2) && chunkMap.playerViewDistanceTickMap.getObjectsInRange(LevelChunk.this.coordinateKey) != null) { -+ chunkProviderServer.addTicketAtLevel(net.minecraft.server.level.TicketType.PLAYER, LevelChunk.this.chunkPos, 31, LevelChunk.this.chunkPos); // 31 -> entity ticking, TODO check on update -+ } -+ }); -+ } -+ } - -+ // this code handles the chunk sending -+ if (!areNeighboursLoaded(bitsetBefore, 1) && areNeighboursLoaded(bitsetAfter, 1)) { -+ if (chunkMap.playerViewDistanceBroadcastMap.getObjectsInRange(this.coordinateKey) != null) { -+ // now we're ready to send -+ chunkMap.mainThreadMailbox.tell(ChunkTaskPriorityQueueSorter.message(chunkMap.getUpdatingChunkIfPresent(this.coordinateKey), (() -> { // Copied frm PlayerChunkMap -+ // double check that this condition still holds. -+ if (!LevelChunk.this.areNeighboursLoaded(1)) { -+ return; -+ } -+ com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet inRange = chunkMap.playerViewDistanceBroadcastMap.getObjectsInRange(LevelChunk.this.coordinateKey); -+ if (inRange == null) { -+ return; -+ } -+ -+ // broadcast -+ Object[] backingSet = inRange.getBackingSet(); -+ Packet[] chunkPackets = new Packet[2]; -+ for (int index = 0, len = backingSet.length; index < len; ++index) { -+ Object temp = backingSet[index]; -+ if (!(temp instanceof net.minecraft.server.level.ServerPlayer)) { -+ continue; -+ } -+ net.minecraft.server.level.ServerPlayer player = (net.minecraft.server.level.ServerPlayer)temp; -+ chunkMap.playerLoadedChunk(player, chunkPackets, LevelChunk.this); -+ } -+ }))); -+ } -+ } -+ // Paper end - no-tick view distance - } - - public final boolean isAnyNeighborsLoaded() { -@@ -0,0 +0,0 @@ public class LevelChunk implements ChunkAccess { - BlockState iblockdata = this.getBlockState(blockposition); - BlockState iblockdata1 = Block.updateFromNeighbourShapes(iblockdata, (LevelAccessor) this.level, blockposition); - -- this.level.setBlock(blockposition, iblockdata1, 20); -+ this.level.setBlock(blockposition, iblockdata1, 20 | 2); // Paper - We send chunks before they're ticking ready, so we need to notify here - } - - this.postProcessing[i].clear(); -diff --git a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java -+++ b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java -@@ -0,0 +0,0 @@ public class CraftWorld extends CraftRegionAccessor implements World { - // Spigot start - @Override - public int getViewDistance() { -- return world.spigotConfig.viewDistance; -+ return getHandle().getChunkSource().chunkMap.getEffectiveViewDistance(); // Paper - no-tick view distance - } - // Spigot end - -+ // Paper start - per player view distance -+ @Override -+ public void setViewDistance(int viewDistance) { -+ if (viewDistance < 2 || viewDistance > 32) { -+ throw new IllegalArgumentException("View distance " + viewDistance + " is out of range of [2, 32]"); -+ } -+ net.minecraft.server.level.ChunkMap chunkMap = getHandle().getChunkSource().chunkMap; -+ if (viewDistance != chunkMap.getEffectiveViewDistance()) { -+ chunkMap.setViewDistance(viewDistance); -+ } -+ } -+ -+ @Override -+ public int getNoTickViewDistance() { -+ return getHandle().getChunkSource().chunkMap.getEffectiveNoTickViewDistance(); -+ } -+ -+ @Override -+ public void setNoTickViewDistance(int viewDistance) { -+ if ((viewDistance < 2 || viewDistance > 32) && viewDistance != -1) { -+ throw new IllegalArgumentException("View distance " + viewDistance + " is out of range of [2, 32]"); -+ } -+ net.minecraft.server.level.ChunkMap chunkMap = getHandle().getChunkSource().chunkMap; -+ if (viewDistance != chunkMap.getRawNoTickViewDistance()) { -+ chunkMap.setNoTickViewDistance(viewDistance); -+ } -+ } -+ // Paper end - per player view distance -+ - // Spigot start - private final org.bukkit.World.Spigot spigot = new org.bukkit.World.Spigot() - { -diff --git a/src/main/java/org/spigotmc/ActivationRange.java b/src/main/java/org/spigotmc/ActivationRange.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/org/spigotmc/ActivationRange.java -+++ b/src/main/java/org/spigotmc/ActivationRange.java -@@ -0,0 +0,0 @@ public class ActivationRange - maxRange = Math.max( maxRange, waterActivationRange ); - maxRange = Math.max( maxRange, villagerActivationRange ); - // Paper end -- maxRange = Math.min( ( world.spigotConfig.viewDistance << 4 ) - 8, maxRange ); -+ maxRange = Math.min( ( ((net.minecraft.server.level.ServerLevel)world).getChunkSource().chunkMap.getEffectiveViewDistance() << 4 ) - 8, maxRange ); // Paper - no-tick view distance - - for ( Player player : world.players() ) - { diff --git a/patches/unapplied/server/Optimise-TickListServer-by-rewriting-it.patch b/patches/unapplied/server/Optimise-TickListServer-by-rewriting-it.patch deleted file mode 100644 index 8938c5efa3..0000000000 --- a/patches/unapplied/server/Optimise-TickListServer-by-rewriting-it.patch +++ /dev/null @@ -1,1127 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Spottedleaf -Date: Fri, 14 Feb 2020 01:24:39 -0800 -Subject: [PATCH] Optimise TickListServer by rewriting it - -In my profiling TickListServer showed up as -~10% for saving chunks and ~5% for the scheduling -of items on a server with ~90 players at -view distance = 5. Most of the performance -loss is unneccessary. - -TickListServer has numerous performance issues: - 1. Handling scheduled items is O(nlogn) - 2. Getting scheduled items for a chunk is O(n), - with n being the the number of scheduled items - for all chunks (hits saving very hard) - 3. Checking if an item is scheduled for the current tick is O(n), - with n being the number of items scheduled for current tick - 4. Items not in ticking chunks are churned in the scheduler - -The biggest issues are 4 & 2. - -We solve 1 by splitting up scheduled items into short and long scheduled, -where we expect the vast majority of our entries to be in the short scheduled -set. Handling short scheduled items is O(n) due to how the comparison -process is reduced to mapping. See TickListServerInterval. However, -this isn't memory-efficient - which is why long scheduled exists. -Long scheduled is handled the same as TickListServer. - -2 is solved by mapping what entries are in what chunks. - -3 is solved by mapping what blocks have what scheduled for them. - -4 is solved by moving the items that are not in ticking chunks -into a map of entries for that chunk. Once the chunk is moved -to ticking, the items are re-scheduled. - -This patch has also added two flags to debug excessive tick delays: --Dpaper.ticklist-warn-on-excessive-delay=true (false by default) -and -Dpaper.ticklist-excessive-delay-threshold=ticks which -sets the excessive tick delay to the specified ticks (defaults to -60 * 20 ticks, aka 60 seconds) - -diff --git a/src/main/java/com/destroystokyo/paper/PaperConfig.java b/src/main/java/com/destroystokyo/paper/PaperConfig.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/com/destroystokyo/paper/PaperConfig.java -+++ b/src/main/java/com/destroystokyo/paper/PaperConfig.java -@@ -0,0 +0,0 @@ public class PaperConfig { - maxBookTotalSizeMultiplier = getDouble("settings.book-size.total-multiplier", maxBookTotalSizeMultiplier); - } - -+ public static boolean useOptimizedTickList = true; -+ private static void useOptimizedTickList() { -+ if (config.contains("settings.use-optimized-ticklist")) { // don't add default, hopefully temporary config -+ useOptimizedTickList = config.getBoolean("settings.use-optimized-ticklist"); -+ } -+ } -+ - public static boolean asyncChunks = false; - private static void asyncChunks() { - ConfigurationSection section; -diff --git a/src/main/java/com/destroystokyo/paper/server/ticklist/PaperTickList.java b/src/main/java/com/destroystokyo/paper/server/ticklist/PaperTickList.java -new file mode 100644 -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 ---- /dev/null -+++ b/src/main/java/com/destroystokyo/paper/server/ticklist/PaperTickList.java -@@ -0,0 +0,0 @@ -+package com.destroystokyo.paper.server.ticklist; -+ -+import java.util.function.Function; -+import net.minecraft.CrashReport; -+import net.minecraft.CrashReportCategory; -+import net.minecraft.ReportedException; -+import net.minecraft.core.BlockPos; -+import net.minecraft.nbt.ListTag; -+import net.minecraft.resources.ResourceLocation; -+import net.minecraft.server.MCUtil; -+import net.minecraft.server.MinecraftServer; -+import net.minecraft.server.level.ServerChunkCache; -+import net.minecraft.server.level.ServerLevel; -+import net.minecraft.world.level.ChunkPos; -+import net.minecraft.world.level.ServerTickList; -+import net.minecraft.world.level.TickNextTickData; -+import net.minecraft.world.level.TickPriority; -+import net.minecraft.world.level.block.state.BlockState; -+import net.minecraft.world.level.levelgen.structure.BoundingBox; -+import it.unimi.dsi.fastutil.longs.Long2ObjectMap; -+import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -+import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet; -+import java.util.ArrayDeque; -+import java.util.ArrayList; -+import java.util.Collections; -+import java.util.Comparator; -+import java.util.Iterator; -+import java.util.List; -+import java.util.function.Consumer; -+import java.util.function.Predicate; -+ -+public final class PaperTickList extends ServerTickList { // extend to avoid breaking ABI -+ -+ // in the order the state is expected to change (mostly) -+ public static final int STATE_UNSCHEDULED = 1 << 0; -+ public static final int STATE_SCHEDULED = 1 << 1; // scheduled for some tick -+ public static final int STATE_PENDING_TICK = 1 << 2; // for this tick -+ public static final int STATE_TICKING = 1 << 3; -+ public static final int STATE_TICKED = 1 << 4; // after this, it gets thrown back to unscheduled -+ public static final int STATE_CANCELLED_TICK = 1 << 5; // still gets moved to unscheduled after tick -+ -+ private static final int SHORT_SCHEDULE_TICK_THRESHOLD = 20 * 20 + 1; // 20 seconds -+ -+ private final ServerLevel world; -+ private final Predicate excludeFromScheduling; -+ private final Function getMinecraftKeyFrom; -+ //private final Function getObjectFronMinecraftKey; -+ private final Consumer> tickFunction; -+ -+ private final co.aikar.timings.Timing timingCleanup; // Paper -+ private final co.aikar.timings.Timing timingTicking; // Paper -+ private final co.aikar.timings.Timing timingFinished; -+ -+ // note: remove ops / add ops suck on fastutil, a chained hashtable implementation would work better, but Long... -+ // try to alleviate with a very small load factor -+ private final Long2ObjectOpenHashMap>> entriesByBlock = new Long2ObjectOpenHashMap<>(1024, 0.25f); -+ private final Long2ObjectOpenHashMap>> entriesByChunk = new Long2ObjectOpenHashMap<>(1024, 0.25f); -+ private final Long2ObjectOpenHashMap>> pendingChunkTickLoad = new Long2ObjectOpenHashMap<>(1024, 0.5f); -+ -+ // fastutil has O(1) first/last while TreeMap/TreeSet are log(n) -+ private final ObjectRBTreeSet> longScheduled = new ObjectRBTreeSet<>(TickListServerInterval.ENTRY_COMPARATOR); -+ -+ private final ArrayDeque> toTickThisTick = new ArrayDeque<>(); -+ -+ private final TickListServerInterval[] shortScheduled = new TickListServerInterval[SHORT_SCHEDULE_TICK_THRESHOLD]; -+ { -+ for (int i = 0, len = this.shortScheduled.length; i < len; ++i) { -+ this.shortScheduled[i] = new TickListServerInterval<>(); -+ } -+ } -+ private int shortScheduledIndex; -+ -+ private long currentTick; -+ -+ private static final boolean WARN_ON_EXCESSIVE_DELAY = Boolean.getBoolean("paper.ticklist-warn-on-excessive-delay"); -+ private static final long EXCESSIVE_DELAY_THRESHOLD = Long.getLong("paper.ticklist-excessive-delay-threshold", 60 * 20).longValue(); // 1 min dfl -+ -+ // assume index < length -+ private static int getWrappedIndex(final int start, final int length, final int index) { -+ final int next = start + index; -+ return next < length ? next : next - length; -+ } -+ -+ private static int getNextIndex(final int curr, final int length) { -+ final int next = curr + 1; -+ return next < length ? next : 0; -+ } -+ -+ public PaperTickList(final ServerLevel world, final Predicate excludeFromScheduling, final Function getMinecraftKeyFrom, -+ final Consumer> tickFunction, final String timingsType) { -+ super(world, excludeFromScheduling, getMinecraftKeyFrom, tickFunction, timingsType); -+ this.world = world; -+ this.excludeFromScheduling = excludeFromScheduling; -+ this.getMinecraftKeyFrom = getMinecraftKeyFrom; -+ this.tickFunction = tickFunction; -+ this.timingCleanup = co.aikar.timings.WorldTimingsHandler.getTickList(world, timingsType + " - Cleanup"); // Paper -+ this.timingTicking = co.aikar.timings.WorldTimingsHandler.getTickList(world, timingsType + " - Ticking"); // Paper -+ this.timingFinished = co.aikar.timings.WorldTimingsHandler.getTickList(world, timingsType + " - Finish"); -+ this.currentTick = this.world.getGameTime(); -+ } -+ -+ private void queueEntryForTick(final TickNextTickData entry, final ServerChunkCache chunkProvider) { -+ if (entry.tickState == STATE_SCHEDULED) { -+ if (chunkProvider.isPositionTickingWithEntitiesLoaded(entry.pos)) { -+ this.toTickThisTick.add(entry); -+ entry.tickState = STATE_PENDING_TICK; -+ } else { -+ // we dump them to a map to avoid constantly re-scheduling them -+ this.addToNotTickingReady(entry); -+ } -+ } -+ } -+ -+ private void addToNotTickingReady(final TickNextTickData entry) { -+ this.pendingChunkTickLoad.computeIfAbsent(MCUtil.getCoordinateKey(entry.pos), (long keyInMap) -> { -+ return new ArrayList<>(); -+ }).add(entry); -+ } -+ -+ private void addToSchedule(final TickNextTickData entry) { -+ long delay = entry.triggerTick - (this.currentTick + 1); -+ if (delay < SHORT_SCHEDULE_TICK_THRESHOLD) { -+ if (delay < 0) { -+ // longScheduled orders by tick time, short scheduled does not -+ this.longScheduled.add(entry); -+ } else { -+ this.shortScheduled[getWrappedIndex(this.shortScheduledIndex, SHORT_SCHEDULE_TICK_THRESHOLD, (int)delay)].addEntryLast(entry); -+ } -+ } else { -+ this.longScheduled.add(entry); -+ } -+ } -+ -+ private void removeEntry(final TickNextTickData entry) { -+ entry.tickState = STATE_CANCELLED_TICK; -+ // short/long scheduled will skip the entry -+ -+ final BlockPos pos = entry.pos; -+ final long blockKey = MCUtil.getBlockKey(pos); -+ -+ final ArrayList> currentEntries = this.entriesByBlock.get(blockKey); -+ -+ if (currentEntries.size() == 1) { -+ // it should contain our entry -+ this.entriesByBlock.remove(blockKey); -+ } else { -+ // it's more likely that this entry is at the start of the list than the end -+ for (int i = 0, len = currentEntries.size(); i < len; ++i) { -+ final TickNextTickData currentEntry = currentEntries.get(i); -+ if (currentEntry == entry) { -+ currentEntries.remove(i); -+ break; -+ } -+ } -+ } -+ -+ final long chunkKey = MCUtil.getCoordinateKey(entry.pos); -+ -+ ObjectRBTreeSet> set = this.entriesByChunk.get(chunkKey); -+ -+ set.remove(entry); -+ -+ if (set.isEmpty()) { -+ this.entriesByChunk.remove(chunkKey); -+ } -+ -+ ArrayList> pendingTickingLoad = this.pendingChunkTickLoad.get(chunkKey); -+ -+ if (pendingTickingLoad != null) { -+ for (int i = 0, len = pendingTickingLoad.size(); i < len; ++i) { -+ if (pendingTickingLoad.get(i) == entry) { -+ pendingTickingLoad.remove(i); -+ break; -+ } -+ } -+ -+ if (pendingTickingLoad.isEmpty()) { -+ this.pendingChunkTickLoad.remove(chunkKey); -+ } -+ } -+ -+ long delay = entry.triggerTick - (this.currentTick + 1); -+ if (delay >= SHORT_SCHEDULE_TICK_THRESHOLD) { -+ this.longScheduled.remove(entry); -+ } -+ } -+ -+ public void onChunkSetTicking(final int chunkX, final int chunkZ) { -+ final ArrayList> pending = this.pendingChunkTickLoad.remove(MCUtil.getCoordinateKey(chunkX, chunkZ)); -+ if (pending == null) { -+ return; -+ } -+ -+ for (int i = 0, size = pending.size(); i < size; ++i) { -+ final TickNextTickData entry = pending.get(i); -+ // already in all the relevant reference maps, just need to add to longScheduled or shortScheduled -+ this.addToSchedule(entry); -+ } -+ } -+ -+ private void prepare() { -+ final long currentTick = this.currentTick; -+ -+ final ServerChunkCache chunkProvider = this.world.getChunkSource(); -+ -+ // here we setup what's going to tick -+ -+ // we don't remove items from shortScheduled (but do from longScheduled) because they're cleared at the end of -+ // this tick -+ if (this.longScheduled.isEmpty() || this.longScheduled.first().triggerTick > currentTick) { -+ // nothing in longScheduled to worry about -+ final TickListServerInterval interval = this.shortScheduled[this.shortScheduledIndex]; -+ for (int i = 0, len = interval.byPriority.length; i < len; ++i) { -+ for (final Iterator> iterator = interval.byPriority[i].iterator(); iterator.hasNext();) { -+ this.queueEntryForTick(iterator.next(), chunkProvider); -+ } -+ } -+ } else { -+ final TickListServerInterval interval = this.shortScheduled[this.shortScheduledIndex]; -+ -+ // combine interval and longScheduled, keeping order -+ final Comparator> comparator = (Comparator)TickListServerInterval.ENTRY_COMPARATOR; -+ final Iterator> longScheduledIterator = this.longScheduled.iterator(); -+ TickNextTickData longCurrent = longScheduledIterator.next(); -+ -+ for (int i = 0, len = interval.byPriority.length; i < len; ++i) { -+ for (final Iterator> iterator = interval.byPriority[i].iterator(); iterator.hasNext();) { -+ final TickNextTickData shortCurrent = iterator.next(); -+ if (longCurrent != null) { -+ // drain longCurrent until we can add shortCurrent -+ while (comparator.compare(longCurrent, shortCurrent) <= 0) { -+ this.queueEntryForTick(longCurrent, chunkProvider); -+ longScheduledIterator.remove(); -+ if (longScheduledIterator.hasNext()) { -+ longCurrent = longScheduledIterator.next(); -+ if (longCurrent.triggerTick > currentTick) { -+ longCurrent = null; -+ break; -+ } -+ } else { -+ longCurrent = null; -+ break; -+ } -+ } -+ } -+ this.queueEntryForTick(shortCurrent, chunkProvider); -+ } -+ } -+ -+ // add remaining from long scheduled -+ for (;;) { -+ if (longCurrent == null || longCurrent.triggerTick > currentTick) { -+ break; -+ } -+ longScheduledIterator.remove(); -+ this.queueEntryForTick(longCurrent, chunkProvider); -+ -+ if (longScheduledIterator.hasNext()) { -+ longCurrent = longScheduledIterator.next(); -+ } else { -+ break; -+ } -+ } -+ } -+ } -+ -+ private boolean warnedAboutDesync; -+ -+ @Override -+ public void nextTick() { -+ ++this.currentTick; -+ if (this.currentTick != this.world.getGameTime()) { -+ if (!this.warnedAboutDesync) { -+ this.warnedAboutDesync = true; -+ MinecraftServer.LOGGER.error("World tick desync detected! Expected " + this.currentTick + " ticks, but got " + this.world.getGameTime() + " ticks for world '" + this.world.getWorld().getName() + "'", new Throwable()); -+ MinecraftServer.LOGGER.error("Preventing redstone from breaking by refusing to accept new tick time"); -+ } -+ } -+ } -+ -+ @Override -+ public void tick() { -+ final ServerChunkCache chunkProvider = this.world.getChunkSource(); -+ -+ this.world.getProfiler().push("cleaning"); -+ this.timingCleanup.startTiming(); -+ -+ this.prepare(); -+ -+ // this must be done here in case something schedules in the tick code -+ this.shortScheduled[this.shortScheduledIndex].clear(); -+ this.shortScheduledIndex = getNextIndex(this.shortScheduledIndex, SHORT_SCHEDULE_TICK_THRESHOLD); -+ -+ this.timingCleanup.stopTiming(); -+ this.world.getProfiler().popPush("ticking"); -+ this.timingTicking.startTiming(); -+ -+ for (final TickNextTickData toTick : this.toTickThisTick) { -+ if (toTick.tickState != STATE_PENDING_TICK) { -+ // onTickEnd gets called at end of tick -+ continue; -+ } -+ try { -+ if (chunkProvider.isPositionTickingWithEntitiesLoaded(toTick.pos)) { -+ toTick.tickState = STATE_TICKING; -+ this.tickFunction.accept(toTick); -+ if (toTick.tickState == STATE_TICKING) { -+ toTick.tickState = STATE_TICKED; -+ } // else it's STATE_CANCELLED_TICK -+ } else { -+ // re-schedule eventually -+ toTick.tickState = STATE_SCHEDULED; -+ this.addToNotTickingReady(toTick); -+ } -+ } catch (final Throwable thr) { -+ // start copy from TickListServer // TODO check on update -+ CrashReport crashreport = CrashReport.forThrowable(thr, "Exception while ticking"); -+ CrashReportCategory crashreportsystemdetails = crashreport.addCategory("Block being ticked"); -+ -+ CrashReportCategory.populateBlockDetails(crashreportsystemdetails, this.world, toTick.pos, (BlockState) null); -+ throw new ReportedException(crashreport); -+ // end copy from TickListServer -+ } -+ } -+ -+ this.timingTicking.stopTiming(); -+ this.world.getProfiler().pop(); -+ this.timingFinished.startTiming(); -+ -+ // finished ticking, actual cleanup time -+ for (int i = 0, len = this.toTickThisTick.size(); i < len; ++i) { -+ final TickNextTickData entry = this.toTickThisTick.poll(); -+ if (entry.tickState != STATE_SCHEDULED) { -+ // some entries get re-scheduled due to their chunk not being loaded/at correct status, so do not -+ // call onTickEnd for them -+ this.onTickEnd(entry); -+ } -+ } -+ -+ this.timingFinished.stopTiming(); -+ } -+ -+ private void onTickEnd(final TickNextTickData entry) { -+ if (entry.tickState == STATE_CANCELLED_TICK) { -+ return; -+ } -+ entry.tickState = STATE_UNSCHEDULED; -+ -+ final BlockPos pos = entry.pos; -+ final long blockKey = MCUtil.getBlockKey(pos); -+ -+ final ArrayList> currentEntries = this.entriesByBlock.get(blockKey); -+ -+ if (currentEntries.size() == 1) { -+ // it should contain our entry -+ this.entriesByBlock.remove(blockKey); -+ } else { -+ // it's more likely that this entry is at the start of the list than the end -+ for (int i = 0, len = currentEntries.size(); i < len; ++i) { -+ final TickNextTickData currentEntry = currentEntries.get(i); -+ if (currentEntry == entry) { -+ currentEntries.remove(i); -+ break; -+ } -+ } -+ } -+ -+ final long chunkKey = MCUtil.getCoordinateKey(entry.pos); -+ -+ ObjectRBTreeSet> set = this.entriesByChunk.get(chunkKey); -+ -+ set.remove(entry); -+ -+ if (set.isEmpty()) { -+ this.entriesByChunk.remove(chunkKey); -+ } -+ -+ // already removed from longScheduled or shortScheduled -+ } -+ -+ @Override -+ public boolean willTickThisTick(final BlockPos blockposition, final T data) { -+ final ArrayList> entries = this.entriesByBlock.get(MCUtil.getBlockKey(blockposition)); -+ -+ if (entries == null) { -+ return false; -+ } -+ -+ for (int i = 0, size = entries.size(); i < size; ++i) { -+ final TickNextTickData entry = entries.get(i); -+ if (entry.getType() == data && entry.tickState == STATE_PENDING_TICK) { -+ return true; -+ } -+ } -+ -+ return false; -+ } -+ -+ @Override -+ public boolean hasScheduledTick(final BlockPos blockposition, final T data) { -+ final ArrayList> entries = this.entriesByBlock.get(MCUtil.getBlockKey(blockposition)); -+ -+ if (entries == null) { -+ return false; -+ } -+ -+ for (int i = 0, size = entries.size(); i < size; ++i) { -+ final TickNextTickData entry = entries.get(i); -+ if (entry.getType() == data && entry.tickState == STATE_SCHEDULED) { -+ return true; -+ } -+ } -+ -+ return false; -+ } -+ -+ @Override -+ public void scheduleTick(BlockPos blockPosition, T t, int i, TickPriority tickListPriority) { -+ this.schedule(blockPosition, t, i + this.currentTick, tickListPriority); -+ } -+ -+ public void schedule(final TickNextTickData entry) { -+ this.schedule(entry.pos, entry.getType(), entry.triggerTick, entry.priority); -+ } -+ -+ public void schedule(final BlockPos pos, final T data, final long targetTick, final TickPriority priority) { -+ final TickNextTickData entry = new TickNextTickData<>(pos, data, targetTick, priority); -+ if (this.excludeFromScheduling.test(entry.getType())) { -+ return; -+ } -+ -+ if (WARN_ON_EXCESSIVE_DELAY) { -+ final long delay = entry.triggerTick - this.currentTick; -+ if (delay >= EXCESSIVE_DELAY_THRESHOLD) { -+ MinecraftServer.LOGGER.warn("Entry " + entry.toString() + " has been scheduled with an excessive delay of: " + delay, new Throwable()); -+ } -+ } -+ -+ final long blockKey = MCUtil.getBlockKey(pos); -+ -+ final ArrayList> currentEntries = this.entriesByBlock.computeIfAbsent(blockKey, (long keyInMap) -> new ArrayList<>(3)); -+ -+ if (currentEntries.isEmpty()) { -+ currentEntries.add(entry); -+ } else { -+ for (int i = 0, size = currentEntries.size(); i < size; ++i) { -+ final TickNextTickData currentEntry = currentEntries.get(i); -+ -+ // entries are only blocked from scheduling if currentEntry.equals(toSchedule) && currentEntry is scheduled to tick (NOT including pending) -+ if (currentEntry.getType() == entry.getType() && currentEntry.tickState == STATE_SCHEDULED) { -+ // can't add -+ return; -+ } -+ } -+ currentEntries.add(entry); -+ } -+ -+ entry.tickState = STATE_SCHEDULED; -+ -+ this.entriesByChunk.computeIfAbsent(MCUtil.getCoordinateKey(entry.pos), (final long keyInMap) -> { -+ return new ObjectRBTreeSet<>(TickListServerInterval.ENTRY_COMPARATOR); -+ }).add(entry); -+ -+ this.addToSchedule(entry); -+ } -+ -+ public void scheduleAll(final Iterator> iterator) { -+ while (iterator.hasNext()) { -+ this.schedule(iterator.next()); -+ } -+ } -+ -+ // this is not the standard interception calculation, but it's the one vanilla uses -+ // i.e the y value is ignored? the x, z calc isn't correct? -+ // however for the copy op they use the correct intersection, after using this one of course... -+ private static boolean isBlockInSortof(final BoundingBox boundingBox, final BlockPos pos) { -+ return pos.getX() >= boundingBox.minX() && pos.getX() < boundingBox.maxX() && pos.getZ() >= boundingBox.minZ() && pos.getZ() < boundingBox.maxZ(); -+ } -+ -+ @Override -+ public List> fetchTicksInArea(final BoundingBox structureboundingbox, final boolean removeReturned, final boolean excludeTicked) { -+ if (structureboundingbox.minX() == structureboundingbox.maxX() || structureboundingbox.minZ() == structureboundingbox.maxZ()) { -+ return Collections.emptyList(); // vanilla behaviour, check isBlockInSortof above -+ } -+ -+ final int lowerChunkX = structureboundingbox.minX() >> 4; -+ final int upperChunkX = (structureboundingbox.maxX() - 1) >> 4; // subtract 1 since maxX is exclusive -+ final int lowerChunkZ = structureboundingbox.minZ() >> 4; -+ final int upperChunkZ = (structureboundingbox.maxZ() - 1) >> 4; // subtract 1 since maxZ is exclusive -+ -+ final int xChunksLength = (upperChunkX - lowerChunkX + 1); -+ final int zChunksLength = (upperChunkZ - lowerChunkZ + 1); -+ -+ final ObjectRBTreeSet>[] containingChunks = new ObjectRBTreeSet[xChunksLength * zChunksLength]; -+ -+ final int offset = (xChunksLength * -lowerChunkZ - lowerChunkX); -+ int totalEntries = 0; -+ for (int currChunkX = lowerChunkX; currChunkX <= upperChunkX; ++currChunkX) { -+ for (int currChunkZ = lowerChunkZ; currChunkZ <= upperChunkZ; ++currChunkZ) { -+ // todo optimize -+ //final int index = (currChunkX - lowerChunkX) + xChunksLength * (currChunkZ - lowerChunkZ); -+ final int index = offset + currChunkX + xChunksLength * currChunkZ; -+ final ObjectRBTreeSet> set = containingChunks[index] = this.entriesByChunk.get(MCUtil.getCoordinateKey(currChunkX, currChunkZ)); -+ if (set != null) { -+ totalEntries += set.size(); -+ } -+ } -+ } -+ -+ final List> ret = new ArrayList<>(totalEntries); -+ -+ final int matchOne = (STATE_SCHEDULED | STATE_PENDING_TICK) | (excludeTicked ? 0 : (STATE_TICKING | STATE_TICKED)); -+ -+ MCUtil.mergeSortedSets((TickNextTickData entry) -> { -+ if (!isBlockInSortof(structureboundingbox, entry.pos)) { -+ return; -+ } -+ final int tickState = entry.tickState; -+ if ((tickState & matchOne) == 0) { -+ return; -+ } -+ -+ ret.add(entry); -+ return; -+ }, TickListServerInterval.ENTRY_COMPARATOR, containingChunks); -+ -+ if (removeReturned) { -+ for (TickNextTickData entry : ret) { -+ this.removeEntry(entry); -+ } -+ } -+ -+ return ret; -+ } -+ -+ @Override -+ public void copy(BoundingBox structureboundingbox, BlockPos blockposition) { -+ // start copy from TickListServer // TODO check on update -+ List> list = this.fetchTicksInArea(structureboundingbox, false, false); -+ Iterator> iterator = list.iterator(); -+ -+ while (iterator.hasNext()) { -+ TickNextTickData nextticklistentry = iterator.next(); -+ -+ if (structureboundingbox.isInside( nextticklistentry.pos)) { -+ BlockPos blockposition1 = nextticklistentry.pos.offset(blockposition); -+ T t0 = nextticklistentry.getType(); -+ -+ this.schedule(new TickNextTickData<>(blockposition1, t0, nextticklistentry.triggerTick, nextticklistentry.priority)); -+ } -+ } -+ // end copy from TickListServer -+ } -+ -+ @Override -+ public List> fetchTicksInChunk(ChunkPos chunkPos, boolean removeReturned, boolean excludeTicked) { -+ // Vanilla DOES get the entries 2 blocks out of the chunk too, but that doesn't matter since we ignore chunks -+ // not at ticking status, and ticking status requires neighbours loaded -+ // so with this method we will reduce scheduler churning -+ final int matchOne = (STATE_SCHEDULED | STATE_PENDING_TICK) | (excludeTicked ? 0 : (STATE_TICKING | STATE_TICKED)); -+ -+ final ObjectRBTreeSet> entries = this.entriesByChunk.get(MCUtil.getCoordinateKey(chunkPos)); -+ -+ if (entries == null) { -+ return Collections.emptyList(); -+ } -+ -+ final List> ret = new ArrayList<>(entries.size()); -+ -+ for (TickNextTickData entry : entries) { -+ if ((entry.tickState & matchOne) == 0) { -+ continue; -+ } -+ ret.add(entry); -+ } -+ -+ if (removeReturned) { -+ for (TickNextTickData entry : ret) { -+ this.removeEntry(entry); -+ } -+ } -+ -+ return ret; -+ } -+ -+ @Override -+ public ListTag save(ChunkPos chunkcoordintpair) { -+ // start copy from TickListServer // TODO check on update -+ List> list = this.fetchTicksInChunk(chunkcoordintpair, false, true); -+ -+ return ServerTickList.saveTickList(this.getMinecraftKeyFrom, list, this.currentTick); -+ // end copy from TickListServer -+ } -+ -+ @Override -+ public int size() { -+ // good thing this is only used in debug reports // TODO check on update -+ int ret = 0; -+ -+ for (TickNextTickData entry : this.longScheduled) { -+ if (entry.tickState == STATE_SCHEDULED) { -+ ++ret; -+ } -+ } -+ -+ for (Iterator>>> iterator = this.pendingChunkTickLoad.long2ObjectEntrySet().iterator(); iterator.hasNext();) { -+ ArrayList> list = iterator.next().getValue(); -+ -+ for (TickNextTickData entry : list) { -+ if (entry.tickState == STATE_SCHEDULED) { -+ ++ret; -+ } -+ } -+ } -+ -+ for (TickListServerInterval interval : this.shortScheduled) { -+ for (Iterable> set : interval.byPriority) { -+ for (TickNextTickData entry : set) { -+ if (entry.tickState == STATE_SCHEDULED) { -+ ++ret; -+ } -+ } -+ } -+ } -+ -+ return ret; -+ } -+} -diff --git a/src/main/java/com/destroystokyo/paper/server/ticklist/TickListServerInterval.java b/src/main/java/com/destroystokyo/paper/server/ticklist/TickListServerInterval.java -new file mode 100644 -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 ---- /dev/null -+++ b/src/main/java/com/destroystokyo/paper/server/ticklist/TickListServerInterval.java -@@ -0,0 +0,0 @@ -+package com.destroystokyo.paper.server.ticklist; -+ -+import com.destroystokyo.paper.util.set.LinkedSortedSet; -+import java.util.Comparator; -+import net.minecraft.world.level.TickNextTickData; -+import net.minecraft.world.level.TickPriority; -+ -+// represents a set of entries to tick at a specified time -+public final class TickListServerInterval { -+ -+ public static final int TOTAL_PRIORITIES = TickPriority.values().length; -+ public static final Comparator> ENTRY_COMPARATOR_BY_ID = (entry1, entry2) -> { -+ return Long.compare(entry1.getId(), entry2.getId()); -+ }; -+ public static final Comparator> ENTRY_COMPARATOR = (Comparator)TickNextTickData.createTimeComparator(); -+ -+ // we do not record the interval, this class is meant to be used on a ring buffer -+ -+ // inlined enum map for TickListPriority -+ public final LinkedSortedSet>[] byPriority = new LinkedSortedSet[TOTAL_PRIORITIES]; -+ -+ { -+ for (int i = 0, len = this.byPriority.length; i < len; ++i) { -+ this.byPriority[i] = new LinkedSortedSet<>(ENTRY_COMPARATOR_BY_ID); -+ } -+ } -+ -+ public void addEntryLast(final TickNextTickData entry) { -+ this.byPriority[entry.priority.ordinal()].addLast(entry); -+ } -+ -+ public void addEntryFirst(final TickNextTickData entry) { -+ this.byPriority[entry.priority.ordinal()].addFirst(entry); -+ } -+ -+ public void clear() { -+ for (int i = 0, len = this.byPriority.length; i < len; ++i) { -+ this.byPriority[i].clear(); // O(1) clear -+ } -+ } -+} -diff --git a/src/main/java/com/destroystokyo/paper/util/set/LinkedSortedSet.java b/src/main/java/com/destroystokyo/paper/util/set/LinkedSortedSet.java -new file mode 100644 -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 ---- /dev/null -+++ b/src/main/java/com/destroystokyo/paper/util/set/LinkedSortedSet.java -@@ -0,0 +0,0 @@ -+package com.destroystokyo.paper.util.set; -+ -+import java.util.Comparator; -+import java.util.Iterator; -+import java.util.NoSuchElementException; -+ -+public final class LinkedSortedSet implements Iterable { -+ -+ public final Comparator comparator; -+ -+ protected Link head; -+ protected Link tail; -+ -+ public LinkedSortedSet() { -+ this((Comparator)Comparator.naturalOrder()); -+ } -+ -+ public LinkedSortedSet(final Comparator comparator) { -+ this.comparator = comparator; -+ } -+ -+ public void clear() { -+ this.head = this.tail = null; -+ } -+ -+ @Override -+ public Iterator iterator() { -+ return new Iterator() { -+ -+ Link next = LinkedSortedSet.this.head; -+ -+ @Override -+ public boolean hasNext() { -+ return this.next != null; -+ } -+ -+ @Override -+ public E next() { -+ final Link next = this.next; -+ if (next == null) { -+ throw new NoSuchElementException(); -+ } -+ this.next = next.next; -+ return next.element; -+ } -+ }; -+ } -+ -+ public boolean addLast(final E element) { -+ final Comparator comparator = this.comparator; -+ -+ Link curr = this.tail; -+ if (curr != null) { -+ int compare; -+ -+ while ((compare = comparator.compare(element, curr.element)) < 0) { -+ Link prev = curr; -+ curr = curr.prev; -+ if (curr != null) { -+ continue; -+ } -+ this.head = prev.prev = new Link<>(element, null, prev); -+ return true; -+ } -+ -+ if (compare != 0) { -+ // insert after curr -+ final Link next = curr.next; -+ final Link insert = new Link<>(element, curr, next); -+ curr.next = insert; -+ -+ if (next == null) { -+ this.tail = insert; -+ } else { -+ next.prev = insert; -+ } -+ return true; -+ } -+ -+ return false; -+ } else { -+ this.head = this.tail = new Link<>(element); -+ return true; -+ } -+ } -+ -+ public boolean addFirst(final E element) { -+ final Comparator comparator = this.comparator; -+ -+ Link curr = this.head; -+ if (curr != null) { -+ int compare; -+ -+ while ((compare = comparator.compare(element, curr.element)) > 0) { -+ Link prev = curr; -+ curr = curr.next; -+ if (curr != null) { -+ continue; -+ } -+ this.tail = prev.next = new Link<>(element, prev, null); -+ return true; -+ } -+ -+ if (compare != 0) { -+ // insert before curr -+ final Link prev = curr.prev; -+ final Link insert = new Link<>(element, prev, curr); -+ curr.prev = insert; -+ -+ if (prev == null) { -+ this.head = insert; -+ } else { -+ prev.next = insert; -+ } -+ return true; -+ } -+ -+ return false; -+ } else { -+ this.head = this.tail = new Link<>(element); -+ return true; -+ } -+ } -+ -+ protected static final class Link { -+ public E element; -+ public Link prev; -+ public Link next; -+ -+ public Link() {} -+ -+ public Link(final E element) { -+ this.element = element; -+ } -+ -+ public Link(final E element, final Link prev, final Link next) { -+ this.element = element; -+ this.prev = prev; -+ this.next = next; -+ } -+ } -+} -diff --git a/src/main/java/net/minecraft/server/level/ChunkHolder.java b/src/main/java/net/minecraft/server/level/ChunkHolder.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/server/level/ChunkHolder.java -+++ b/src/main/java/net/minecraft/server/level/ChunkHolder.java -@@ -0,0 +0,0 @@ public class ChunkHolder { - return null; - } - // Paper end - no-tick view distance -+ // Paper start -+ public final boolean isEntityTickingReady() { -+ return this.isEntityTickingReady; -+ } -+ -+ public final boolean isTickingReady() { -+ return this.isTickingReady; -+ } -+ -+ public final boolean isFullChunkReady() { -+ return this.isFullChunkReady; -+ } -+ // Paper end - - public ChunkHolder(ChunkPos pos, int level, LevelHeightAccessor world, LevelLightEngine lightingProvider, ChunkHolder.LevelChangeListener levelUpdateListener, ChunkHolder.PlayerProvider playersWatchingChunkProvider) { - this.futures = new AtomicReferenceArray(ChunkHolder.CHUNK_STATUSES.size()); -@@ -0,0 +0,0 @@ public class ChunkHolder { - // Paper start - ticking chunk set - ChunkHolder.this.chunkMap.level.getChunkSource().tickingChunks.add(chunk); - // Paper end - ticking chunk set -+ // Paper start - rewrite ticklistserver -+ if (ChunkHolder.this.chunkMap.level.entityManager.areEntitiesLoaded(this.pos.longKey)) { -+ ChunkHolder.this.chunkMap.level.onChunkSetTicking(ChunkHolder.this.pos.x, ChunkHolder.this.pos.z); -+ } -+ // Paper end - rewrite ticklistserver - }); - }); - // Paper end -diff --git a/src/main/java/net/minecraft/server/level/ServerChunkCache.java b/src/main/java/net/minecraft/server/level/ServerChunkCache.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/server/level/ServerChunkCache.java -+++ b/src/main/java/net/minecraft/server/level/ServerChunkCache.java -@@ -0,0 +0,0 @@ public class ServerChunkCache extends ChunkSource { - }, this.mainThreadProcessor); - } - // Paper end -+ // Paper start - rewrite ticklistserver -+ public final boolean isPositionTickingReady(long pos) { -+ final ChunkHolder chunkHolder = this.chunkMap.getUpdatingChunkIfPresent(pos); -+ return chunkHolder != null && chunkHolder.isTickingReady(); -+ } -+ -+ public final boolean isPositionTickingWithEntitiesLoaded(BlockPos pos) { -+ final long position = net.minecraft.server.MCUtil.getCoordinateKey(pos); -+ final ChunkHolder chunkHolder = this.chunkMap.getUpdatingChunkIfPresent(position); -+ return chunkHolder != null && chunkHolder.isTickingReady() && this.level.entityManager.areEntitiesLoaded(position); -+ } -+ // Paper end - rewrite ticklistserver - - // Paper start - // this will try to avoid chunk neighbours for lighting -diff --git a/src/main/java/net/minecraft/server/level/ServerLevel.java b/src/main/java/net/minecraft/server/level/ServerLevel.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/server/level/ServerLevel.java -+++ b/src/main/java/net/minecraft/server/level/ServerLevel.java -@@ -0,0 +0,0 @@ public class ServerLevel extends Level implements WorldGenLevel { - } - // Paper end - -+ // Paper start - rewrite ticklistserver -+ public void onChunkSetTicking(int chunkX, int chunkZ) { -+ if (com.destroystokyo.paper.PaperConfig.useOptimizedTickList) { -+ ((com.destroystokyo.paper.server.ticklist.PaperTickList) this.blockTicks).onChunkSetTicking(chunkX, chunkZ); -+ ((com.destroystokyo.paper.server.ticklist.PaperTickList) this.liquidTicks).onChunkSetTicking(chunkX, chunkZ); -+ } -+ } -+ // Paper end - rewrite ticklistserver -+ - // Add env and gen to constructor, WorldData -> WorldDataServer - public ServerLevel(MinecraftServer minecraftserver, Executor executor, LevelStorageSource.LevelStorageAccess convertable_conversionsession, ServerLevelData iworlddataserver, ResourceKey resourcekey, DimensionType dimensionmanager, ChunkProgressListener worldloadlistener, ChunkGenerator chunkgenerator, boolean flag, long i, List list, boolean flag1, org.bukkit.World.Environment env, org.bukkit.generator.ChunkGenerator gen, org.bukkit.generator.BiomeProvider biomeProvider) { - // Objects.requireNonNull(minecraftserver); // CraftBukkit - decompile error -@@ -0,0 +0,0 @@ public class ServerLevel extends Level implements WorldGenLevel { - DefaultedRegistry registryblocks = Registry.BLOCK; - - Objects.requireNonNull(registryblocks); -- this.blockTicks = new ServerTickList<>(this, predicate, Registry.BLOCK::getKey, this::tickBlock, "Blocks"); // CraftBukkit - decompile error // Paper - Timings -+ // this.blockTicks = new ServerTickList<>(this, predicate, Registry.BLOCK::getKey, this::tickBlock, "Blocks"); // CraftBukkit - decompile error // Paper - Timings // Paper - copied down - Predicate predicate2 = (fluidtype) -> { // CraftBukkit - decompile error - return fluidtype == null || fluidtype == Fluids.EMPTY; - }; - registryblocks = Registry.FLUID; - Objects.requireNonNull(registryblocks); -+ if (com.destroystokyo.paper.PaperConfig.useOptimizedTickList) { -+ this.blockTicks = new com.destroystokyo.paper.server.ticklist.PaperTickList<>(this, predicate, Registry.BLOCK::getKey, this::tickBlock, "Blocks"); // Paper - Timings -+ this.liquidTicks = new com.destroystokyo.paper.server.ticklist.PaperTickList<>(this, predicate2, Registry.FLUID::getKey, this::tickLiquid, "Fluids"); // Paper timings -+ } else { -+ this.blockTicks = new ServerTickList<>(this, predicate, Registry.BLOCK::getKey, this::tickBlock, "Blocks"); // CraftBukkit - decompile error // Paper - Timings & copied from above - this.liquidTicks = new ServerTickList<>(this, predicate2, Registry.FLUID::getKey, this::tickLiquid, "Fluids"); // CraftBukkit - decompile error // Paper - Timings -+ } - this.navigatingMobs = new ObjectOpenHashSet(); - this.blockEvents = new ObjectLinkedOpenHashSet(); - this.dragonParts = new Int2ObjectOpenHashMap(); -@@ -0,0 +0,0 @@ public class ServerLevel extends Level implements WorldGenLevel { - if (this.tickTime) { - long i = this.levelData.getGameTime() + 1L; - -- this.serverLevelData.setGameTime(i); -+ this.serverLevelData.setGameTime(i); ; // Paper - diff on change, we want the below to be ran right after this -+ this.blockTicks.nextTick(); // Paper -+ this.liquidTicks.nextTick(); // Paper - this.serverLevelData.getScheduledEvents().tick(this.server, i); - if (this.levelData.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT)) { - this.setDayTime(this.levelData.getDayTime() + 1L); -diff --git a/src/main/java/net/minecraft/world/level/ChunkTickList.java b/src/main/java/net/minecraft/world/level/ChunkTickList.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/world/level/ChunkTickList.java -+++ b/src/main/java/net/minecraft/world/level/ChunkTickList.java -@@ -0,0 +0,0 @@ public class ChunkTickList implements TickList { - - public ChunkTickList(Function identifierProvider, List> scheduledTicks, long startTime) { - this(identifierProvider, scheduledTicks.stream().map((tickNextTickData) -> { -- return new ChunkTickList.ScheduledTick(tickNextTickData.getType(), tickNextTickData.pos, (int)(tickNextTickData.triggerTick - startTime), tickNextTickData.priority); -+ return new ChunkTickList.ScheduledTick<>(tickNextTickData.getType(), tickNextTickData.pos, (int)(tickNextTickData.triggerTick - startTime), tickNextTickData.priority); // Paper - decompile error - }).collect(Collectors.toList())); - } - -@@ -0,0 +0,0 @@ public class ChunkTickList implements TickList { - return listTag; - } - -+ private static final int MAX_TICK_DELAY = Integer.getInteger("paper.ticklist-max-tick-delay", -1).intValue(); // Paper - clean up broken entries - public static ChunkTickList create(ListTag ticks, Function function, Function function2) { - List> list = Lists.newArrayList(); - -@@ -0,0 +0,0 @@ public class ChunkTickList implements TickList { - T object = function2.apply(new ResourceLocation(compoundTag.getString("i"))); - if (object != null) { - BlockPos blockPos = new BlockPos(compoundTag.getInt("x"), compoundTag.getInt("y"), compoundTag.getInt("z")); -- list.add(new ChunkTickList.ScheduledTick<>(object, blockPos, compoundTag.getInt("t"), TickPriority.byValue(compoundTag.getInt("p")))); -+ // Paper start - clean up broken entries -+ int delay = compoundTag.getInt("t"); -+ if (MAX_TICK_DELAY > 0 && delay > MAX_TICK_DELAY) { -+ net.minecraft.server.MinecraftServer.LOGGER.warn("Dropping tick for pos " + blockPos + ", tick delay " + delay); -+ continue; -+ } -+ // Paper end - clean up broken entries -+ list.add(new ChunkTickList.ScheduledTick<>(object, blockPos, delay, TickPriority.byValue(compoundTag.getInt("p")))); - } - } - -diff --git a/src/main/java/net/minecraft/world/level/ServerTickList.java b/src/main/java/net/minecraft/world/level/ServerTickList.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/world/level/ServerTickList.java -+++ b/src/main/java/net/minecraft/world/level/ServerTickList.java -@@ -0,0 +0,0 @@ public class ServerTickList implements TickList { - this.ticker = tickConsumer; - } - -+ // Paper start -+ public void nextTick() {} -+ // Paper end - public void tick() { - int i = this.tickNextTickList.size(); - -diff --git a/src/main/java/net/minecraft/world/level/TickNextTickData.java b/src/main/java/net/minecraft/world/level/TickNextTickData.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/world/level/TickNextTickData.java -+++ b/src/main/java/net/minecraft/world/level/TickNextTickData.java -@@ -0,0 +0,0 @@ public class TickNextTickData { - public final BlockPos pos; - public final long triggerTick; - public final TickPriority priority; -- private final long c; -+ private final long c; @Deprecated public final long getId() { return this.c; } // Paper - OBFHELPER -+ private final int hash; // Paper -+ public int tickState; // Paper - - public TickNextTickData(BlockPos pos, T t) { - this(pos, t, 0L, TickPriority.NORMAL); -@@ -0,0 +0,0 @@ public class TickNextTickData { - this.type = t; - this.triggerTick = time; - this.priority = priority; -+ this.hash = this.computeHash(); // Paper - } - - @Override -@@ -0,0 +0,0 @@ public class TickNextTickData { - - @Override - public int hashCode() { -+ // Paper start - optimize hashcode -+ return this.hash; -+ } -+ public final int computeHash() { -+ // Paper end - optimize hashcode - return this.pos.hashCode(); - } - - public static Comparator> createTimeComparator() { -- return Comparator.>comparingLong((tickNextTickData) -> { // Paper - decompile fix -- return tickNextTickData.triggerTick; -- }).thenComparing((tickNextTickData) -> { -- return tickNextTickData.priority; -- }).thenComparingLong((tickNextTickData) -> { -- return tickNextTickData.c; -- }); -+ // Paper start - let's not use more functional code for no reason. -+ return (Comparator) (Comparator) (TickNextTickData nextticklistentry, TickNextTickData nextticklistentry1) -> { -+ int i = Long.compare(nextticklistentry.triggerTick, nextticklistentry1.triggerTick); -+ -+ if (i != 0) { -+ return i; -+ } else { -+ i = nextticklistentry.priority.compareTo(nextticklistentry1.priority); -+ return i != 0 ? i : Long.compare(nextticklistentry.getId(), nextticklistentry1.getId()); -+ } -+ }; -+ // Paper end - let's not use more functional code for no reason. - } - - @Override -diff --git a/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java b/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java -+++ b/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java -@@ -0,0 +0,0 @@ public class PersistentEntitySectionManager implements A - List entities = this.getEntities(chunkentities.getPos()); // PAIL rename getChunkPos - CraftEventFactory.callEntitiesLoadEvent(((EntityStorage) this.permanentStorage).level, chunkentities.getPos(), entities); - // CraftBukkit end -+ // Paper start - rewrite ServerTickList -+ final net.minecraft.server.level.ServerLevel level = ((net.minecraft.world.level.chunk.storage.EntityStorage) this.permanentStorage).level; -+ if (level.chunkSource.isPositionTickingReady(chunkentities.getPos().longKey)) { -+ level.onChunkSetTicking(chunkentities.getPos().x, chunkentities.getPos().z); -+ } -+ // Paper end - } - - } diff --git a/patches/unapplied/server/Optimize-Collision-to-not-load-chunks.patch b/patches/unapplied/server/Optimize-Collision-to-not-load-chunks.patch deleted file mode 100644 index 19e76f851f..0000000000 --- a/patches/unapplied/server/Optimize-Collision-to-not-load-chunks.patch +++ /dev/null @@ -1,121 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Aikar -Date: Thu, 2 Apr 2020 02:37:57 -0400 -Subject: [PATCH] Optimize Collision to not load chunks - -The collision code takes an AABB and generates a cuboid of checks rather -than a cylinder, so at high velocity this can generate a lot of chunk checks. - -Treat an unloaded chunk as a collision for entities, and also for players if -the "prevent moving into unloaded chunks" setting is enabled. - -If that serting is not enabled, collisions will be ignored for players, since -movement will load only the chunk the player enters anyways and avoids loading -massive amounts of surrounding chunks due to large AABB lookups. - -diff --git a/src/main/java/net/minecraft/server/players/PlayerList.java b/src/main/java/net/minecraft/server/players/PlayerList.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/server/players/PlayerList.java -+++ b/src/main/java/net/minecraft/server/players/PlayerList.java -@@ -0,0 +0,0 @@ public abstract class PlayerList { - entityplayer1.forceSetPositionRotation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); - // CraftBukkit end - -+ worldserver1.getChunkSource().addRegionTicket(net.minecraft.server.level.TicketType.POST_TELEPORT, new net.minecraft.world.level.ChunkPos(location.getBlockX() >> 4, location.getBlockZ() >> 4), 1, entityplayer.getId()); // Paper - while (avoidSuffocation && !worldserver1.noCollision(entityplayer1) && entityplayer1.getY() < (double) worldserver1.getMaxBuildHeight()) { - entityplayer1.setPos(entityplayer1.getX(), entityplayer1.getY() + 1.0D, entityplayer1.getZ()); - } -diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/world/entity/Entity.java -+++ b/src/main/java/net/minecraft/world/entity/Entity.java -@@ -0,0 +0,0 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource, n - // Paper end - - public com.destroystokyo.paper.loottable.PaperLootableInventoryData lootableData; // Paper -+ public boolean collisionLoadChunks = false; // Paper - private CraftEntity bukkitEntity; - - public net.minecraft.server.level.ChunkMap.TrackedEntity tracker; // Paper -diff --git a/src/main/java/net/minecraft/world/level/CollisionGetter.java b/src/main/java/net/minecraft/world/level/CollisionGetter.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/world/level/CollisionGetter.java -+++ b/src/main/java/net/minecraft/world/level/CollisionGetter.java -@@ -0,0 +0,0 @@ public interface CollisionGetter extends BlockGetter { - } - - default boolean noCollision(@Nullable Entity entity, AABB box, Predicate filter) { -+ try { if (entity != null) entity.collisionLoadChunks = true; // Paper - return this.getCollisions(entity, box, filter).allMatch(VoxelShape::isEmpty); -+ } finally { if (entity != null) entity.collisionLoadChunks = false; } // Paper - } - - Stream getEntityCollisions(@Nullable Entity entity, AABB box, Predicate predicate); -diff --git a/src/main/java/net/minecraft/world/level/CollisionSpliterator.java b/src/main/java/net/minecraft/world/level/CollisionSpliterator.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/world/level/CollisionSpliterator.java -+++ b/src/main/java/net/minecraft/world/level/CollisionSpliterator.java -@@ -0,0 +0,0 @@ public class CollisionSpliterator extends AbstractSpliterator { - boolean collisionCheck(Consumer action) { - while(true) { - if (this.cursor.advance()) { -- int i = this.cursor.nextX(); -- int j = this.cursor.nextY(); -- int k = this.cursor.nextZ(); -+ int i = this.cursor.nextX(); final int x = i; -+ int j = this.cursor.nextY(); final int y = j; -+ int k = this.cursor.nextZ(); final int z = k; - int l = this.cursor.getNextType(); - if (l == 3) { - continue; - } - -- BlockGetter blockGetter = this.getChunk(i, k); -- if (blockGetter == null) { -+ // Paper start - ensure we don't load chunks -+ boolean far = this.source != null && net.minecraft.server.MCUtil.distanceSq(this.source.getX(), y, this.source.getZ(), x, y, z) > 14; -+ this.pos.set(x, y, z); -+ -+ BlockState blockState; -+ if (this.collisionGetter instanceof net.minecraft.server.level.WorldGenRegion) { -+ BlockGetter blockGetter = this.getChunk(x, z); -+ if (blockGetter == null) { -+ continue; -+ } -+ blockState = blockGetter.getBlockState(this.pos); -+ } else if ((!far && this.source instanceof net.minecraft.server.level.ServerPlayer) || (this.source != null && this.source.collisionLoadChunks)) { -+ blockState = this.collisionGetter.getBlockState(this.pos); -+ } else { -+ blockState = this.collisionGetter.getTypeIfLoaded(this.pos); -+ } -+ -+ if (blockState == null) { -+ if (!(this.source instanceof net.minecraft.server.level.ServerPlayer) || this.source.level.paperConfig.preventMovingIntoUnloadedChunks) { -+ VoxelShape voxelshape3 = Shapes.create(far ? this.source.getBoundingBox() : new AABB(new BlockPos(x, y, z))); -+ action.accept(voxelshape3); -+ return true; -+ } - continue; - } -+ // Paper - moved up -+ // Paper end - -- this.pos.set(i, j, k); -- BlockState blockState = blockGetter.getBlockState(this.pos); - if (!this.predicate.test(blockState, this.pos) || l == 1 && !blockState.hasLargeCollisionShape() || l == 2 && !blockState.is(Blocks.MOVING_PISTON)) { - continue; - } -diff --git a/src/main/java/net/minecraft/world/phys/shapes/Shapes.java b/src/main/java/net/minecraft/world/phys/shapes/Shapes.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/world/phys/shapes/Shapes.java -+++ b/src/main/java/net/minecraft/world/phys/shapes/Shapes.java -@@ -0,0 +0,0 @@ public final class Shapes { - - if (s < 3) { - mutableBlockPos.set(axisCycle, q, r, p); -- BlockState blockState = world.getBlockState(mutableBlockPos); -+ BlockState blockState = world.getTypeIfLoaded(mutableBlockPos); // Paper -+ if (blockState == null) return 0.0D; // Paper - if ((s != 1 || blockState.hasLargeCollisionShape()) && (s != 2 || blockState.is(Blocks.MOVING_PISTON))) { - initial = blockState.getCollisionShape(world, mutableBlockPos, context).collide(axis3, box.move((double)(-mutableBlockPos.getX()), (double)(-mutableBlockPos.getY()), (double)(-mutableBlockPos.getZ())), initial); - if (Math.abs(initial) < 1.0E-7D) { diff --git a/patches/unapplied/server/Remove-streams-from-PairedQueue.patch b/patches/unapplied/server/Remove-streams-from-PairedQueue.patch deleted file mode 100644 index 254a7e495b..0000000000 --- a/patches/unapplied/server/Remove-streams-from-PairedQueue.patch +++ /dev/null @@ -1,46 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Spottedleaf -Date: Mon, 6 Apr 2020 18:10:43 -0700 -Subject: [PATCH] Remove streams from PairedQueue - -We shouldn't be doing stream calls just to see if the queue is -empty. This creates loads of garbage thanks to how often it's called. - -diff --git a/src/main/java/net/minecraft/util/thread/StrictQueue.java b/src/main/java/net/minecraft/util/thread/StrictQueue.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/util/thread/StrictQueue.java -+++ b/src/main/java/net/minecraft/util/thread/StrictQueue.java -@@ -0,0 +0,0 @@ public interface StrictQueue { - private final List> queueList; - - public FixedPriorityQueue(int priorityCount) { -- this.queueList = IntStream.range(0, priorityCount).mapToObj((i) -> { -- return Queues.newConcurrentLinkedQueue(); -- }).collect(Collectors.toList()); -+ // Paper start - remove streams -+ this.queueList = new java.util.ArrayList<>(priorityCount); // queues -+ for (int j = 0; j < priorityCount; ++j) { -+ this.queueList.add(Queues.newConcurrentLinkedQueue()); -+ } -+ // Paper end - remove streams - } - - @Nullable -@@ -0,0 +0,0 @@ public interface StrictQueue { - - @Override - public boolean isEmpty() { -- return this.queueList.stream().allMatch(Collection::isEmpty); -+ // Paper start - remove streams -+ // why are we doing streams every time we might want to execute a task? -+ for (int i = 0, len = this.queueList.size(); i < len; ++i) { -+ Queue queue = this.queueList.get(i); -+ if (!queue.isEmpty()) { -+ return false; -+ } -+ } -+ return true; -+ // Paper end - remove streams - } - - @Override diff --git a/patches/unapplied/server/Restrict-vanilla-teleport-command-to-valid-locations.patch b/patches/unapplied/server/Restrict-vanilla-teleport-command-to-valid-locations.patch deleted file mode 100644 index f59a3681f9..0000000000 --- a/patches/unapplied/server/Restrict-vanilla-teleport-command-to-valid-locations.patch +++ /dev/null @@ -1,24 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Zach Brown <1254957+zachbr@users.noreply.github.com> -Date: Thu, 16 Apr 2020 20:07:29 -0500 -Subject: [PATCH] Restrict vanilla teleport command to valid locations - -Fixes GH-3165, GH-3575 - -diff --git a/src/main/java/net/minecraft/server/commands/TeleportCommand.java b/src/main/java/net/minecraft/server/commands/TeleportCommand.java -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 100644 ---- a/src/main/java/net/minecraft/server/commands/TeleportCommand.java -+++ b/src/main/java/net/minecraft/server/commands/TeleportCommand.java -@@ -0,0 +0,0 @@ public class TeleportCommand { - - private static void performTeleport(CommandSourceStack source, Entity target, ServerLevel world, double x, double y, double z, Set movementFlags, float yaw, float pitch, @Nullable TeleportCommand.LookAt facingLocation) throws CommandSyntaxException { - BlockPos blockposition = new BlockPos(x, y, z); -+ // Paper start - Don't allow teleport command to invalid locations -+ if (x <= -30000000 || z <= -30000000 || x > 30000000 || z > 30000000 || y > 30000000 || y <= -30000000) { // Copy/pasta from BaseBlockPosition#isValidLocation -+ org.bukkit.Bukkit.getLogger().warning("Refused to teleport " + target.getScoreboardName() + " to " + x + ", " + y + ", " + z); -+ return; -+ } -+ // Paper end - - if (!Level.isInSpawnableBounds(blockposition)) { - throw TeleportCommand.INVALID_POSITION.create();