From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Thu, 9 Apr 2020 00:09:26 -0400
Subject: [PATCH] Mid Tick Chunk Tasks - Speed up processing of chunk loads and
 generation

Credit to Spotted for the idea

A lot of the new chunk system requires constant back and forth the main thread
to handle priority scheduling and ensuring conflicting tasks do not run at the
same time.

The issue is, these queues are only checked at either:

A) Sync Chunk Loads
B) End of Tick while sleeping

This results in generating chunks sitting waiting for a full tick to
complete before it will even start the next unit of work to do.

Additionally, this also delays loading of chunks until this same timing.

We will now periodically poll the chunk task queues throughout the tick,
looking for work to do.
We do this in a fair method that considers all worlds, not just the one being
ticked, so that each world can get 1 task procesed each before the next pass.

In a view distance of 15, chunk loading performance was visually faster on the client.

Flying at high speed in spectator mode was able to keep up with chunk loading (as long as they are already generated)

diff --git a/src/main/java/co/aikar/timings/MinecraftTimings.java b/src/main/java/co/aikar/timings/MinecraftTimings.java
index 11fe3524f38f7756ebd0e3807678e8848fd2217d..884b59d478aa7de49906520e77866a7949bed19d 100644
--- a/src/main/java/co/aikar/timings/MinecraftTimings.java
+++ b/src/main/java/co/aikar/timings/MinecraftTimings.java
@@ -13,6 +13,7 @@ import java.util.Map;
 public final class MinecraftTimings {
 
     public static final Timing serverOversleep = Timings.ofSafe("Server Oversleep");
+    public static final Timing midTickChunkTasks = Timings.ofSafe("Mid Tick Chunk Tasks");
     public static final Timing playerListTimer = Timings.ofSafe("Player List");
     public static final Timing commandFunctionsTimer = Timings.ofSafe("Command Functions");
     public static final Timing connectionTimer = Timings.ofSafe("Connection Handler");
diff --git a/src/main/java/com/destroystokyo/paper/PaperConfig.java b/src/main/java/com/destroystokyo/paper/PaperConfig.java
index 9b1845024d16a7875ba3406da92efb003f58f8cb..01d7ad6778d4bbef6e07f7529f40dd9da6cd2ea8 100644
--- a/src/main/java/com/destroystokyo/paper/PaperConfig.java
+++ b/src/main/java/com/destroystokyo/paper/PaperConfig.java
@@ -405,4 +405,9 @@ public class PaperConfig {
             log("Async Chunks: Enabled - Chunks will be loaded much faster, without lag.");
         }
     }
+
+    public static int midTickChunkTasks = 1000;
+    private static void midTickChunkTasks() {
+        midTickChunkTasks = getInt("settings.chunk-tasks-per-tick", midTickChunkTasks);
+    }
 }
diff --git a/src/main/java/net/minecraft/server/ChunkProviderServer.java b/src/main/java/net/minecraft/server/ChunkProviderServer.java
index dea7ff47f7a2934708d887c2c40f9328b78fc84e..e31ebda893112b932ee314fc72263fc163ed04ba 100644
--- a/src/main/java/net/minecraft/server/ChunkProviderServer.java
+++ b/src/main/java/net/minecraft/server/ChunkProviderServer.java
@@ -695,6 +695,7 @@ public class ChunkProviderServer extends IChunkProvider {
         this.world.getMethodProfiler().enter("purge");
         this.world.timings.doChunkMap.startTiming(); // Spigot
         this.chunkMapDistance.purgeTickets();
+        this.world.getMinecraftServer().midTickLoadChunks(); // Paper
         this.tickDistanceManager();
         this.world.timings.doChunkMap.stopTiming(); // Spigot
         this.world.getMethodProfiler().exitEnter("chunks");
@@ -704,6 +705,7 @@ public class ChunkProviderServer extends IChunkProvider {
         this.world.timings.doChunkUnload.startTiming(); // Spigot
         this.world.getMethodProfiler().exitEnter("unload");
         this.playerChunkMap.unloadChunks(booleansupplier);
+        this.world.getMinecraftServer().midTickLoadChunks(); // Paper
         this.world.timings.doChunkUnload.stopTiming(); // Spigot
         this.world.getMethodProfiler().exit();
         this.clearCache();
@@ -757,7 +759,7 @@ public class ChunkProviderServer extends IChunkProvider {
                 entityPlayer.playerNaturallySpawnedEvent.callEvent();
             };
             // Paper end
-            this.playerChunkMap.forEachVisibleChunk((playerchunk) -> { // Paper - safe iterator incase chunk loads, also no wrapping
+            final int[] chunksTicked = {0}; this.playerChunkMap.forEachVisibleChunk((playerchunk) -> { // Paper - safe iterator incase chunk loads, also no wrapping
                 Optional<Chunk> optional = ((Either) playerchunk.a().getNow(PlayerChunk.UNLOADED_CHUNK)).left();
 
                 if (optional.isPresent()) {
@@ -781,6 +783,7 @@ public class ChunkProviderServer extends IChunkProvider {
                             this.world.timings.chunkTicks.startTiming(); // Spigot // Paper
                             this.world.a(chunk, k);
                             this.world.timings.chunkTicks.stopTiming(); // Spigot // Paper
+                            if (chunksTicked[0]++ % 10 == 0) this.world.getMinecraftServer().midTickLoadChunks(); // Paper
                         }
                     }
                 }
@@ -937,6 +940,41 @@ public class ChunkProviderServer extends IChunkProvider {
             super.executeTask(runnable);
         }
 
+        // Paper start
+        private long lastMidTickChunkTask = 0;
+        public boolean pollChunkLoadTasks() {
+            if (com.destroystokyo.paper.io.chunk.ChunkTaskManager.pollChunkWaitQueue() || ChunkProviderServer.this.world.asyncChunkTaskManager.pollNextChunkTask()) {
+                try {
+                    ChunkProviderServer.this.tickDistanceManager();
+                } finally {
+                    // from below: process pending Chunk loadCallback() and unloadCallback() after each run task
+                    playerChunkMap.callbackExecutor.run();
+                }
+                return true;
+            }
+            return false;
+        }
+        public void midTickLoadChunks() {
+            MinecraftServer server = ChunkProviderServer.this.world.getMinecraftServer();
+            // always try to load chunks, restrain generation/other updates only. don't count these towards tick count
+            //noinspection StatementWithEmptyBody
+            while (pollChunkLoadTasks()) {}
+
+            if (System.nanoTime() - lastMidTickChunkTask < 200000) {
+                return;
+            }
+
+            for (;server.midTickChunksTasksRan < com.destroystokyo.paper.PaperConfig.midTickChunkTasks && server.canSleepForTick();) {
+                if (this.executeNext()) {
+                    server.midTickChunksTasksRan++;
+                    lastMidTickChunkTask = System.nanoTime();
+                } else {
+                    break;
+                }
+            }
+        }
+        // Paper end
+
         @Override
         protected boolean executeNext() {
         // CraftBukkit start - process pending Chunk loadCallback() and unloadCallback() after each run task
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
index 8e2300e22ca76562acf29c42c0025b4d4c2689b1..664daf13341285a7e24c67a62e765627d79ee578 100644
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
@@ -940,6 +940,7 @@ public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant<TickTas
                         // Paper end
                         tickSection = curTime;
                     }
+                    midTickChunksTasksRan = 0; // Paper
                     // Spigot end
 
                     //MinecraftServer.currentTick = (int) (System.currentTimeMillis() / 50); // CraftBukkit // Paper - don't overwrite current tick time
@@ -1009,7 +1010,7 @@ public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant<TickTas
 
     }
 
-    private boolean canSleepForTick() {
+    public boolean canSleepForTick() { // Paper
         // CraftBukkit start
         if (isOversleep) return canOversleep();// Paper - because of our changes, this logic is broken
         return this.forceTicks || this.isEntered() || SystemUtils.getMonotonicMillis() < (this.X ? this.W : this.nextTick);
@@ -1039,6 +1040,23 @@ public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant<TickTas
         });
     }
 
+    // Paper start
+    public int midTickChunksTasksRan = 0;
+    private long midTickLastRan = 0;
+    public void midTickLoadChunks() {
+        if (!isMainThread() || System.nanoTime() - midTickLastRan < 1000000) {
+            // only check once per 0.25ms incase this code is called in a hot method
+            return;
+        }
+        try (co.aikar.timings.Timing ignored = co.aikar.timings.MinecraftTimings.midTickChunkTasks.startTiming()) {
+            for (WorldServer value : this.getWorlds()) {
+                value.getChunkProvider().serverThreadQueue.midTickLoadChunks();
+            }
+            midTickLastRan = System.nanoTime();
+        }
+    }
+    // Paper end
+
     @Override
     protected TickTask postToMainThread(Runnable runnable) {
         return new TickTask(this.ticks, runnable);
@@ -1125,6 +1143,7 @@ public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant<TickTas
         // Paper start - move oversleep into full server tick
         isOversleep = true;MinecraftTimings.serverOversleep.startTiming();
         this.awaitTasks(() -> {
+            midTickLoadChunks(); // will only do loads since we are still considered !canSleepForTick
             return !this.canOversleep();
         });
         isOversleep = false;MinecraftTimings.serverOversleep.stopTiming();
@@ -1203,13 +1222,16 @@ public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant<TickTas
     }
 
     protected void b(BooleanSupplier booleansupplier) {
+        midTickLoadChunks(); // Paper
         MinecraftTimings.bukkitSchedulerTimer.startTiming(); // Spigot // Paper
         this.server.getScheduler().mainThreadHeartbeat(this.ticks); // CraftBukkit
         MinecraftTimings.bukkitSchedulerTimer.stopTiming(); // Spigot // Paper
+        midTickLoadChunks(); // Paper
         this.methodProfiler.enter("commandFunctions");
         MinecraftTimings.commandFunctionsTimer.startTiming(); // Spigot // Paper
         this.getFunctionData().tick();
         MinecraftTimings.commandFunctionsTimer.stopTiming(); // Spigot // Paper
+        midTickLoadChunks(); // Paper
         this.methodProfiler.exitEnter("levels");
         Iterator iterator = this.getWorlds().iterator();
 
@@ -1220,7 +1242,7 @@ public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant<TickTas
             processQueue.remove().run();
         }
         MinecraftTimings.processQueueTimer.stopTiming(); // Spigot
-
+        midTickLoadChunks(); // Paper
         MinecraftTimings.timeUpdateTimer.startTiming(); // Spigot // Paper
         // Send time updates to everyone, it will get the right time from the world the player is in.
         // Paper start - optimize time updates
@@ -1262,9 +1284,11 @@ public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant<TickTas
             this.methodProfiler.enter("tick");
 
             try {
+                midTickLoadChunks(); // Paper
                 worldserver.timings.doTick.startTiming(); // Spigot
                 worldserver.doTick(booleansupplier);
                 worldserver.timings.doTick.stopTiming(); // Spigot
+                midTickLoadChunks(); // Paper
             } catch (Throwable throwable) {
                 // Spigot Start
                 CrashReport crashreport;
diff --git a/src/main/java/net/minecraft/server/WorldServer.java b/src/main/java/net/minecraft/server/WorldServer.java
index ed13a1bc54cebebbafbf9a3822d2942fbc09249e..87c581fe9c4e12f2cdf93d864ccc7383f2933304 100644
--- a/src/main/java/net/minecraft/server/WorldServer.java
+++ b/src/main/java/net/minecraft/server/WorldServer.java
@@ -457,6 +457,7 @@ public class WorldServer extends World implements GeneratorAccessSeed {
         }
         timings.scheduledBlocks.stopTiming(); // Paper
 
+        this.getMinecraftServer().midTickLoadChunks(); // Paper
         gameprofilerfiller.exitEnter("raid");
         this.timings.raids.startTiming(); // Paper - timings
         this.persistentRaid.a();
@@ -465,6 +466,7 @@ public class WorldServer extends World implements GeneratorAccessSeed {
         timings.doSounds.startTiming(); // Spigot
         this.ak();
         timings.doSounds.stopTiming(); // Spigot
+        this.getMinecraftServer().midTickLoadChunks(); // Paper
         this.ticking = false;
         gameprofilerfiller.exitEnter("entities");
         boolean flag3 = true || !this.players.isEmpty() || !this.getForceLoadedChunks().isEmpty(); // CraftBukkit - this prevents entity cleanup, other issues on servers with no players
@@ -531,6 +533,7 @@ public class WorldServer extends World implements GeneratorAccessSeed {
             timings.entityTick.stopTiming(); // Spigot
 
             this.tickingEntities = false;
+            this.getMinecraftServer().midTickLoadChunks(); // Paper
 
             Entity entity2;
 
@@ -540,6 +543,7 @@ public class WorldServer extends World implements GeneratorAccessSeed {
             }
 
             timings.tickEntities.stopTiming(); // Spigot
+            this.getMinecraftServer().midTickLoadChunks(); // Paper
             this.tickBlockEntities();
         }
 
