aboutsummaryrefslogtreecommitdiffhomepage
path: root/patches/server/0768-Replace-player-chunk-loader-system.patch
blob: fb0535210ff64f18155d51d0ddfa0e7b17b1542a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Spottedleaf <spottedleaf@spottedleaf.dev>
Date: Sun, 24 Jan 2021 20:27:32 -0800
Subject: [PATCH] Replace player chunk loader system

The old one has undebuggable problems. Rewriting seems
the most sensible option.

This new player chunk manager will also strictly rate limit
chunk sends so that netty threads do not get overloaded, whether
it be from the anti-xray logic or the compression itself.

Chunk loading is also rate limited in the same manner, so this
will result in a maximum responsiveness for change.

Config:
```
chunk-loading:
  min-load-radius: 2
  max-concurrent-sends: 2
  autoconfig-send-distance: true
  target-player-chunk-send-rate: 100.0
  global-max-chunk-send-rate: -1
  enable-frustum-priority: false
  global-max-chunk-load-rate: -1.0
  player-max-concurrent-loads: 4.0
  global-max-concurrent-loads: 500.0
```

min-load-radius - The radius of chunks around a player that
are not throttled for loading. The number of chunks
affected is actually the configured value plus one as this
config controls the chunks the client will be able to render.

max-concurrent-sends - The maximum number of chunks that
can be queued to send at any given time. Low values
are generally going to solve server-sided networking
bottlenecks like anti-xray and chunk compression. Client
side networking is unlikely to be helped (i.e this wont help
people running off McDonald's wifi).

autoconfig-send-distance - Whether to try to use the client's
view distance for the send view distance in the server. In the
case that no plugin has explicitly set the send distance and
the client view distance is less-than the server's send distance,
the client's view distance will be used. This will not affect
tick view distance or no-tick view distance.

target-player-chunk-send-rate - The maximum chunk send rate
an individual player will have. -1 means no limit

global-max-chunk-send-rate - The maximum chunk send rate for
the whole server. -1 means no limit

enable-frustum-priority - Whether chunks in front of a player
are prioritised to load/send first. Disabled by default
because the client can bug out due to the out of order
chunk sending.

global-max-chunk-load-rate - The maximum chunk load rate
for the whole server. -1 means no limit

player-max-concurrent-loads and global-max-concurrent-loads
The maximum number of concurrent loads for the server is
determined by the number of players on the server multiplied by the
`player-max-concurrent-loads`. It is then limited to
whatever `global-max-concurrent-loads` is configured to.

diff --git a/src/main/java/co/aikar/timings/TimingsExport.java b/src/main/java/co/aikar/timings/TimingsExport.java
index cfe293881f68c8db337c3a48948362bb7b3e3522..7d44abcb4fff9717a1af55879deb7eb9c2d9e7e9 100644
--- a/src/main/java/co/aikar/timings/TimingsExport.java
+++ b/src/main/java/co/aikar/timings/TimingsExport.java
@@ -153,7 +153,7 @@ public class TimingsExport extends Thread {
                     return pair(rule, world.getWorld().getGameRuleValue(rule));
                 })),
                 pair("ticking-distance", world.getChunkSource().chunkMap.getEffectiveViewDistance()),
-                pair("notick-viewdistance", world.getChunkSource().chunkMap.getEffectiveNoTickViewDistance())
+                pair("notick-viewdistance", world.getChunkSource().chunkMap.playerChunkManager.getTargetNoTickViewDistance()) // Paper - replace old player chunk management
             ));
         }));
 
diff --git a/src/main/java/com/destroystokyo/paper/PaperConfig.java b/src/main/java/com/destroystokyo/paper/PaperConfig.java
index c0d5eaf617f5c1a814986a9954b16bb59b3616fa..6a1957f9ab333e0c662895a14d83c015660a8a0f 100644
--- a/src/main/java/com/destroystokyo/paper/PaperConfig.java
+++ b/src/main/java/com/destroystokyo/paper/PaperConfig.java
@@ -526,4 +526,29 @@ public class PaperConfig {
         itemValidationBookAuthorLength = getInt("settings.item-validation.book.author", itemValidationBookAuthorLength);
         itemValidationBookPageLength = getInt("settings.item-validation.book.page", itemValidationBookPageLength);
     }
+
+    public static int playerMinChunkLoadRadius;
+    public static boolean playerAutoConfigureSendViewDistance;
+    public static int playerMaxConcurrentChunkSends;
+    public static double playerTargetChunkSendRate;
+    public static double globalMaxChunkSendRate;
+    public static boolean playerFrustumPrioritisation;
+    public static double globalMaxChunkLoadRate;
+    public static double playerMaxConcurrentChunkLoads;
+    public static double globalMaxConcurrentChunkLoads;
+
+    private static void newPlayerChunkManagement() {
+        playerMinChunkLoadRadius = getInt("settings.chunk-loading.min-load-radius", 2);
+        playerMaxConcurrentChunkSends = getInt("settings.chunk-loading.max-concurrent-sends", 2);
+        playerAutoConfigureSendViewDistance = getBoolean("settings.chunk-loading.autoconfig-send-distance", true);
+        playerTargetChunkSendRate = getDouble("settings.chunk-loading.target-player-chunk-send-rate", 100.0);
+        globalMaxChunkSendRate = getDouble("settings.chunk-loading.global-max-chunk-send-rate", -1.0);
+        playerFrustumPrioritisation = getBoolean("settings.chunk-loading.enable-frustum-priority", false);
+        globalMaxChunkLoadRate = getDouble("settings.chunk-loading.global-max-chunk-load-rate", -1.0);
+        if (version < 23 && globalMaxChunkLoadRate == 300.0) {
+            set("settings.chunk-loading.global-max-chunk-load-rate", -1.0);
+        }
+        playerMaxConcurrentChunkLoads = getDouble("settings.chunk-loading.player-max-concurrent-loads", 4.0);
+        globalMaxConcurrentChunkLoads = getDouble("settings.chunk-loading.global-max-concurrent-loads", 500.0);
+    }
 }
diff --git a/src/main/java/io/papermc/paper/chunk/PlayerChunkLoader.java b/src/main/java/io/papermc/paper/chunk/PlayerChunkLoader.java
new file mode 100644
index 0000000000000000000000000000000000000000..4eadc15f747528b59349f095171dd5a649a46ed9
--- /dev/null
+++ b/src/main/java/io/papermc/paper/chunk/PlayerChunkLoader.java
@@ -0,0 +1,989 @@
+package io.papermc.paper.chunk;
+
+import com.destroystokyo.paper.PaperConfig;
+import com.destroystokyo.paper.util.misc.PlayerAreaMap;
+import com.destroystokyo.paper.util.misc.PooledLinkedHashSets;
+import io.papermc.paper.util.CoordinateUtils;
+import io.papermc.paper.util.IntervalledCounter;
+import io.papermc.paper.util.TickThread;
+import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
+import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap;
+import it.unimi.dsi.fastutil.objects.Reference2ObjectLinkedOpenHashMap;
+import it.unimi.dsi.fastutil.objects.ReferenceLinkedOpenHashSet;
+import net.minecraft.network.protocol.Packet;
+import net.minecraft.network.protocol.game.ClientboundSetChunkCacheCenterPacket;
+import net.minecraft.network.protocol.game.ClientboundSetChunkCacheRadiusPacket;
+import net.minecraft.server.MCUtil;
+import net.minecraft.server.MinecraftServer;
+import net.minecraft.server.level.ChunkHolder;
+import net.minecraft.server.level.ChunkMap;
+import net.minecraft.server.level.ServerPlayer;
+import net.minecraft.server.level.TicketType;
+import net.minecraft.util.Mth;
+import net.minecraft.world.level.ChunkPos;
+import net.minecraft.world.level.chunk.LevelChunk;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.TreeSet;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public final class PlayerChunkLoader {
+
+    public static final int MIN_VIEW_DISTANCE = 2;
+    public static final int MAX_VIEW_DISTANCE = 32;
+
+    public static final int TICK_TICKET_LEVEL = 31;
+    public static final int LOADED_TICKET_LEVEL = 33;
+
+    protected final ChunkMap chunkMap;
+    protected final Reference2ObjectLinkedOpenHashMap<ServerPlayer, PlayerLoaderData> playerMap = new Reference2ObjectLinkedOpenHashMap<>(512, 0.7f);
+    protected final ReferenceLinkedOpenHashSet<PlayerLoaderData> chunkSendQueue = new ReferenceLinkedOpenHashSet<>(512, 0.7f);
+
+    protected final TreeSet<PlayerLoaderData> chunkLoadQueue = new TreeSet<>((final PlayerLoaderData p1, final PlayerLoaderData p2) -> {
+        if (p1 == p2) {
+            return 0;
+        }
+
+        final ChunkPriorityHolder holder1 = p1.loadQueue.peekFirst();
+        final ChunkPriorityHolder holder2 = p2.loadQueue.peekFirst();
+
+        final int priorityCompare = Double.compare(holder1 == null ? Double.MAX_VALUE : holder1.priority, holder2 == null ? Double.MAX_VALUE : holder2.priority);
+
+        if (priorityCompare != 0) {
+            return priorityCompare;
+        }
+
+        final int idCompare = Integer.compare(p1.player.getId(), p2.player.getId());
+
+        if (idCompare != 0) {
+            return idCompare;
+        }
+
+        // last resort
+        return Integer.compare(System.identityHashCode(p1), System.identityHashCode(p2));
+    });
+
+    protected final TreeSet<PlayerLoaderData> chunkSendWaitQueue = new TreeSet<>((final PlayerLoaderData p1, final PlayerLoaderData p2) -> {
+        if (p1 == p2) {
+            return 0;
+        }
+
+        final int timeCompare = Long.compare(p1.nextChunkSendTarget, p2.nextChunkSendTarget);
+        if (timeCompare != 0) {
+            return timeCompare;
+        }
+
+        final int idCompare = Integer.compare(p1.player.getId(), p2.player.getId());
+
+        if (idCompare != 0) {
+            return idCompare;
+        }
+
+        // last resort
+        return Integer.compare(System.identityHashCode(p1), System.identityHashCode(p2));
+    });
+
+
+    // no throttling is applied below this VD for loading
+
+    /**
+     * The chunks to be sent to players, provided they're send-ready. Send-ready means the chunk and its 1 radius neighbours are loaded.
+     */
+    public final PlayerAreaMap broadcastMap;
+
+    /**
+     * The chunks to be brought up to send-ready status. Send-ready means the chunk and its 1 radius neighbours are loaded.
+     */
+    public final PlayerAreaMap loadMap;
+
+    /**
+     * Areamap used only to remove tickets for send-ready chunks. View distance is always + 1 of load view distance. Thus,
+     * this map is always representing the chunks we are actually going to load.
+     */
+    public final PlayerAreaMap loadTicketCleanup;
+
+    /**
+     * The chunks to brought to ticking level. Each chunk must have 2 radius neighbours loaded before this can happen.
+     */
+    public final PlayerAreaMap tickMap;
+
+    /**
+     * -1 if defaulting to [load distance], else always in [2, load distance]
+     */
+    protected int rawSendDistance = -1;
+
+    /**
+     * -1 if defaulting to [tick view distance + 1], else always in [tick view distance + 1, 32 + 1]
+     */
+    protected int rawLoadDistance = -1;
+
+    /**
+     * Never -1, always in [2, 32]
+     */
+    protected int rawTickDistance = -1;
+
+    // methods to bridge for API
+
+    public int getTargetViewDistance() {
+        return this.getTickDistance();
+    }
+
+    public void setTargetViewDistance(final int distance) {
+        this.setTickDistance(distance);
+    }
+
+    public int getTargetNoTickViewDistance() {
+        return this.getLoadDistance() - 1;
+    }
+
+    public void setTargetNoTickViewDistance(final int distance) {
+        this.setLoadDistance(distance == -1 ? -1 : distance + 1);
+    }
+
+    public int getTargetSendDistance() {
+        return this.rawSendDistance == -1 ? this.getLoadDistance() : this.rawSendDistance;
+    }
+
+    public void setTargetSendDistance(final int distance) {
+        this.setSendDistance(distance);
+    }
+
+    // internal methods
+
+    public int getSendDistance() {
+        final int loadDistance = this.getLoadDistance();
+        return this.rawSendDistance == -1 ? loadDistance : Math.min(this.rawSendDistance, loadDistance);
+    }
+
+    public void setSendDistance(final int distance) {
+        if (distance != -1 && (distance < MIN_VIEW_DISTANCE || distance > MAX_VIEW_DISTANCE + 1)) {
+            throw new IllegalArgumentException(Integer.toString(distance));
+        }
+        this.rawSendDistance = distance;
+    }
+
+    public int getLoadDistance() {
+        final int tickDistance = this.getTickDistance();
+        return this.rawLoadDistance == -1 ? tickDistance + 1 : Math.max(tickDistance + 1, this.rawLoadDistance);
+    }
+
+    public void setLoadDistance(final int distance) {
+        if (distance != -1 && (distance < MIN_VIEW_DISTANCE || distance > MAX_VIEW_DISTANCE + 1)) {
+            throw new IllegalArgumentException(Integer.toString(distance));
+        }
+        this.rawLoadDistance = distance;
+    }
+
+    public int getTickDistance() {
+        return this.rawTickDistance;
+    }
+
+    public void setTickDistance(final int distance) {
+        if (distance < MIN_VIEW_DISTANCE || distance > MAX_VIEW_DISTANCE) {
+            throw new IllegalArgumentException(Integer.toString(distance));
+        }
+        this.rawTickDistance = distance;
+    }
+
+    /*
+      Players have 3 different types of view distance:
+      1. Sending view distance
+      2. Loading view distance
+      3. Ticking view distance
+
+      But for configuration purposes (and API) there are:
+      1. No-tick view distance
+      2. Tick view distance
+      3. Broadcast view distance
+
+      These aren't always the same as the types we represent internally.
+
+      Loading view distance is always max(no-tick + 1, tick + 1)
+      - no-tick has 1 added because clients need an extra radius to render chunks
+      - tick has 1 added because it needs an extra radius of chunks to load before they can be marked ticking
+
+      Loading view distance is defined as the radius of chunks that will be brought to send-ready status, which means
+      it loads chunks in radius load-view-distance + 1.
+
+      The maximum value for send view distance is the load view distance. API can set it lower.
+     */
+
+    public PlayerChunkLoader(final ChunkMap chunkMap, final PooledLinkedHashSets<ServerPlayer> pooledHashSets) {
+        this.chunkMap = chunkMap;
+        this.broadcastMap = new PlayerAreaMap(pooledHashSets,
+                (ServerPlayer player, int rangeX, int rangeZ, int currPosX, int currPosZ, int prevPosX, int prevPosZ,
+                 com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> newState) -> {
+                    if (player.needsChunkCenterUpdate) {
+                        player.needsChunkCenterUpdate = false;
+                        player.connection.send(new ClientboundSetChunkCacheCenterPacket(currPosX, currPosZ));
+                    }
+                    PlayerChunkLoader.this.onChunkEnter(player, rangeX, rangeZ);
+                },
+                (ServerPlayer player, int rangeX, int rangeZ, int currPosX, int currPosZ, int prevPosX, int prevPosZ,
+                 com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> newState) -> {
+                    PlayerChunkLoader.this.onChunkLeave(player, rangeX, rangeZ);
+                });
+        this.loadMap = new PlayerAreaMap(pooledHashSets,
+                null,
+                (ServerPlayer player, int rangeX, int rangeZ, int currPosX, int currPosZ, int prevPosX, int prevPosZ,
+                 com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> newState) -> {
+                    if (newState != null) {
+                        return;
+                    }
+                    PlayerChunkLoader.this.isTargetedForPlayerLoad.remove(CoordinateUtils.getChunkKey(rangeX, rangeZ));
+                });
+        this.loadTicketCleanup = new PlayerAreaMap(pooledHashSets,
+                null,
+                (ServerPlayer player, int rangeX, int rangeZ, int currPosX, int currPosZ, int prevPosX, int prevPosZ,
+                 com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> newState) -> {
+                    if (newState != null) {
+                        return;
+                    }
+                    ChunkPos chunkPos = new ChunkPos(rangeX, rangeZ);
+                    PlayerChunkLoader.this.chunkMap.level.getChunkSource().removeTicketAtLevel(TicketType.PLAYER, chunkPos, LOADED_TICKET_LEVEL, chunkPos);
+                    if (PlayerChunkLoader.this.chunkTicketTracker.remove(chunkPos.toLong())) {
+                        --PlayerChunkLoader.this.concurrentChunkLoads;
+                    }
+                });
+        this.tickMap = new PlayerAreaMap(pooledHashSets,
+                (ServerPlayer player, int rangeX, int rangeZ, int currPosX, int currPosZ, int prevPosX, int prevPosZ,
+                 com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> newState) -> {
+                    if (newState.size() != 1) {
+                        return;
+                    }
+                    LevelChunk chunk = PlayerChunkLoader.this.chunkMap.level.getChunkSource().getChunkAtIfLoadedMainThreadNoCache(rangeX, rangeZ);
+                    if (chunk == null || !chunk.areNeighboursLoaded(2)) {
+                        return;
+                    }
+
+                    ChunkPos chunkPos = new ChunkPos(rangeX, rangeZ);
+                    PlayerChunkLoader.this.chunkMap.level.getChunkSource().addTicketAtLevel(TicketType.PLAYER, chunkPos, TICK_TICKET_LEVEL, chunkPos);
+                },
+                (ServerPlayer player, int rangeX, int rangeZ, int currPosX, int currPosZ, int prevPosX, int prevPosZ,
+                 com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> newState) -> {
+                    if (newState != null) {
+                        return;
+                    }
+                    ChunkPos chunkPos = new ChunkPos(rangeX, rangeZ);
+                    PlayerChunkLoader.this.chunkMap.level.getChunkSource().removeTicketAtLevel(TicketType.PLAYER, chunkPos, TICK_TICKET_LEVEL, chunkPos);
+                });
+    }
+
+    protected final LongOpenHashSet isTargetedForPlayerLoad = new LongOpenHashSet();
+    protected final LongOpenHashSet chunkTicketTracker = new LongOpenHashSet();
+
+    // rets whether the chunk is at a loaded stage that is ready to be sent to players
+    public boolean isChunkPlayerLoaded(final int chunkX, final int chunkZ) {
+        final long key = CoordinateUtils.getChunkKey(chunkX, chunkZ);
+        final ChunkHolder chunk = this.chunkMap.getVisibleChunkIfPresent(key);
+
+        if (chunk == null) {
+            return false;
+        }
+
+        return chunk.getSendingChunk() != null && this.isTargetedForPlayerLoad.contains(key);
+    }
+
+    public boolean isChunkSent(final ServerPlayer player, final int chunkX, final int chunkZ) {
+        final PlayerLoaderData data = this.playerMap.get(player);
+        if (data == null) {
+            return false;
+        }
+
+        return data.hasSentChunk(chunkX, chunkZ);
+    }
+
+    protected int getMaxConcurrentChunkSends() {
+        return PaperConfig.playerMaxConcurrentChunkSends;
+    }
+
+    protected int getMaxChunkLoads() {
+        double config = PaperConfig.playerMaxConcurrentChunkLoads;
+        double max = PaperConfig.globalMaxConcurrentChunkLoads;
+        return (int)Math.ceil(Math.min(config * MinecraftServer.getServer().getPlayerCount(), max <= 1.0 ? Double.MAX_VALUE : max));
+    }
+
+    protected long getTargetSendPerPlayerAddend() {
+        return PaperConfig.playerTargetChunkSendRate <= 1.0 ? 0L : (long)Math.round(1.0e9 / PaperConfig.playerTargetChunkSendRate);
+    }
+
+    protected long getMaxSendAddend() {
+        return PaperConfig.globalMaxChunkSendRate <= 1.0 ? 0L : (long)Math.round(1.0e9 / PaperConfig.globalMaxChunkSendRate);
+    }
+
+    public void onChunkPlayerTickReady(final int chunkX, final int chunkZ) {
+        final ChunkPos chunkPos = new ChunkPos(chunkX, chunkZ);
+        this.chunkMap.level.getChunkSource().addTicketAtLevel(TicketType.PLAYER, chunkPos, TICK_TICKET_LEVEL, chunkPos);
+    }
+
+    public void onChunkSendReady(final int chunkX, final int chunkZ) {
+        final PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> playersInSendRange = this.broadcastMap.getObjectsInRange(chunkX, chunkZ);
+
+        if (playersInSendRange == null) {
+            return;
+        }
+
+        final Object[] rawData = playersInSendRange.getBackingSet();
+        for (int i = 0, len = rawData.length; i < len; ++i) {
+            final Object raw = rawData[i];
+
+            if (!(raw instanceof ServerPlayer)) {
+                continue;
+            }
+            this.onChunkEnter((ServerPlayer)raw, chunkX, chunkZ);
+        }
+
+        // now let's try and queue mid tick logic again
+    }
+
+    public void onChunkEnter(final ServerPlayer player, final int chunkX, final int chunkZ) {
+        final PlayerLoaderData data = this.playerMap.get(player);
+
+        if (data == null) {
+            return;
+        }
+
+        if (data.hasSentChunk(chunkX, chunkZ) || !this.isChunkPlayerLoaded(chunkX, chunkZ)) {
+            // if we don't have player tickets, then the load logic will pick this up and queue to send
+            return;
+        }
+
+        final long playerPos = this.broadcastMap.getLastCoordinate(player);
+        final int playerChunkX = CoordinateUtils.getChunkX(playerPos);
+        final int playerChunkZ = CoordinateUtils.getChunkZ(playerPos);
+        final int manhattanDistance = Math.abs(playerChunkX - chunkX) + Math.abs(playerChunkZ - chunkZ);
+
+        final ChunkPriorityHolder holder = new ChunkPriorityHolder(chunkX, chunkZ, manhattanDistance, 0.0);
+        data.sendQueue.add(holder);
+    }
+
+    public void onChunkLoad(final int chunkX, final int chunkZ) {
+        if (this.chunkTicketTracker.remove(CoordinateUtils.getChunkKey(chunkX, chunkZ))) {
+            --this.concurrentChunkLoads;
+        }
+    }
+
+    public void onChunkLeave(final ServerPlayer player, final int chunkX, final int chunkZ) {
+        final PlayerLoaderData data = this.playerMap.get(player);
+
+        if (data == null) {
+            return;
+        }
+
+        data.unloadChunk(chunkX, chunkZ);
+    }
+
+    public void addPlayer(final ServerPlayer player) {
+        TickThread.ensureTickThread("Cannot add player async");
+        if (!player.isRealPlayer) {
+            return;
+        }
+        final PlayerLoaderData data = new PlayerLoaderData(player, this);
+        if (this.playerMap.putIfAbsent(player, data) == null) {
+            data.update();
+        }
+    }
+
+    public void removePlayer(final ServerPlayer player) {
+        TickThread.ensureTickThread("Cannot remove player async");
+        if (!player.isRealPlayer) {
+            return;
+        }
+
+        final PlayerLoaderData loaderData = this.playerMap.remove(player);
+        if (loaderData == null) {
+            return;
+        }
+        loaderData.remove();
+        this.chunkLoadQueue.remove(loaderData);
+        this.chunkSendQueue.remove(loaderData);
+        this.chunkSendWaitQueue.remove(loaderData);
+        synchronized (this.sendingChunkCounts) {
+            final int count = this.sendingChunkCounts.removeInt(loaderData);
+            if (count != 0) {
+                concurrentChunkSends.getAndAdd(-count);
+            }
+        }
+    }
+
+    public void updatePlayer(final ServerPlayer player) {
+        TickThread.ensureTickThread("Cannot update player async");
+        if (!player.isRealPlayer) {
+            return;
+        }
+        final PlayerLoaderData loaderData = this.playerMap.get(player);
+        if (loaderData != null) {
+            loaderData.update();
+        }
+    }
+
+    public PlayerLoaderData getData(final ServerPlayer player) {
+        return this.playerMap.get(player);
+    }
+
+    public void tick() {
+        TickThread.ensureTickThread("Cannot tick async");
+        for (final PlayerLoaderData data : this.playerMap.values()) {
+            data.update();
+        }
+        this.tickMidTick();
+    }
+
+    protected static final AtomicInteger concurrentChunkSends = new AtomicInteger();
+    protected final Reference2IntOpenHashMap<PlayerLoaderData> sendingChunkCounts = new Reference2IntOpenHashMap<>();
+    private static long nextChunkSend;
+    private void trySendChunks() {
+        final long time = System.nanoTime();
+        if (time < nextChunkSend) {
+            return;
+        }
+        // drain entries from wait queue
+        while (!this.chunkSendWaitQueue.isEmpty()) {
+            final PlayerLoaderData data = this.chunkSendWaitQueue.first();
+
+            if (data.nextChunkSendTarget > time) {
+                break;
+            }
+
+            this.chunkSendWaitQueue.pollFirst();
+
+            this.chunkSendQueue.add(data);
+        }
+
+        if (this.chunkSendQueue.isEmpty()) {
+            return;
+        }
+
+        final int maxSends = this.getMaxConcurrentChunkSends();
+        final long nextPlayerDeadline = this.getTargetSendPerPlayerAddend() + time;
+        for (;;) {
+            if (this.chunkSendQueue.isEmpty()) {
+                break;
+            }
+            final int currSends = concurrentChunkSends.get();
+            if (currSends >= maxSends) {
+                break;
+            }
+
+            if (!concurrentChunkSends.compareAndSet(currSends, currSends + 1)) {
+                continue;
+            }
+
+            // send chunk
+
+            final PlayerLoaderData data = this.chunkSendQueue.removeFirst();
+
+            final ChunkPriorityHolder queuedSend = data.sendQueue.pollFirst();
+            if (queuedSend == null) {
+                concurrentChunkSends.getAndDecrement(); // we never sent, so decrease
+                // stop iterating over players who have nothing to send
+                if (this.chunkSendQueue.isEmpty()) {
+                    // nothing left
+                    break;
+                }
+                continue;
+            }
+
+            if (!this.isChunkPlayerLoaded(queuedSend.chunkX, queuedSend.chunkZ)) {
+                throw new IllegalStateException();
+            }
+
+            data.nextChunkSendTarget = nextPlayerDeadline;
+            this.chunkSendWaitQueue.add(data);
+
+            synchronized (this.sendingChunkCounts) {
+                this.sendingChunkCounts.addTo(data, 1);
+            }
+
+            data.sendChunk(queuedSend.chunkX, queuedSend.chunkZ, () -> {
+                synchronized (this.sendingChunkCounts) {
+                    final int count = this.sendingChunkCounts.getInt(data);
+                    if (count == 0) {
+                        // disconnected, so we don't need to decrement: it will be decremented for us
+                        return;
+                    }
+                    if (count == 1) {
+                        this.sendingChunkCounts.removeInt(data);
+                    } else {
+                        this.sendingChunkCounts.put(data, count - 1);
+                    }
+                }
+
+                concurrentChunkSends.getAndDecrement();
+            });
+
+            nextChunkSend = this.getMaxSendAddend() + time;
+            if (time < nextChunkSend) {
+                break;
+            }
+        }
+    }
+
+    protected int concurrentChunkLoads;
+    // this interval prevents bursting a lot of chunk loads
+    protected static final IntervalledCounter TICKET_ADDITION_COUNTER_SHORT = new IntervalledCounter((long)(1.0e6 * 50.0)); // 50ms
+    // this interval ensures the rate is kept between ticks correctly
+    protected static final IntervalledCounter TICKET_ADDITION_COUNTER_LONG = new IntervalledCounter((long)(1.0e6 * 1000.0)); // 1000ms
+    private void tryLoadChunks() {
+        if (this.chunkLoadQueue.isEmpty()) {
+            return;
+        }
+
+        final int maxLoads = this.getMaxChunkLoads();
+        final long time = System.nanoTime();
+        boolean updatedCounters = false;
+        for (;;) {
+            final PlayerLoaderData data = this.chunkLoadQueue.pollFirst();
+
+            final ChunkPriorityHolder queuedLoad = data.loadQueue.peekFirst();
+            if (queuedLoad == null) {
+                if (this.chunkLoadQueue.isEmpty()) {
+                    break;
+                }
+                continue;
+            }
+
+            if (!updatedCounters) {
+                updatedCounters = true;
+                TICKET_ADDITION_COUNTER_SHORT.updateCurrentTime(time);
+                TICKET_ADDITION_COUNTER_LONG.updateCurrentTime(time);
+            }
+
+            if (this.isChunkPlayerLoaded(queuedLoad.chunkX, queuedLoad.chunkZ)) {
+                // already loaded!
+                data.loadQueue.pollFirst(); // already loaded so we just skip
+                this.chunkLoadQueue.add(data);
+
+                // ensure the chunk is queued to send
+                this.onChunkSendReady(queuedLoad.chunkX, queuedLoad.chunkZ);
+                continue;
+            }
+
+            final long chunkKey = CoordinateUtils.getChunkKey(queuedLoad.chunkX, queuedLoad.chunkZ);
+
+            final double priority = queuedLoad.priority;
+            // while we do need to rate limit chunk loads, the logic for sending chunks requires that tickets are present.
+            // when chunks are loaded (i.e spawn) but do not have this player's tickets, they have to wait behind the
+            // load queue. To avoid this problem, we check early here if tickets are required to load the chunk - if they
+            // aren't required, it bypasses the limiter system.
+            boolean unloadedTargetChunk = false;
+            unloaded_check:
+            for (int dz = -1; dz <= 1; ++dz) {
+                for (int dx = -1; dx <= 1; ++dx) {
+                    final int offX = queuedLoad.chunkX + dx;
+                    final int offZ = queuedLoad.chunkZ + dz;
+                    if (this.chunkMap.level.getChunkSource().getChunkAtIfLoadedMainThreadNoCache(offX, offZ) == null) {
+                        unloadedTargetChunk = true;
+                        break unloaded_check;
+                    }
+                }
+            }
+            if (unloadedTargetChunk && priority > 0.0) {
+                // priority > 0.0 implies rate limited chunks
+
+                final int currentChunkLoads = this.concurrentChunkLoads;
+                if (currentChunkLoads >= maxLoads || (PaperConfig.globalMaxChunkLoadRate > 0 && (TICKET_ADDITION_COUNTER_SHORT.getRate() >= PaperConfig.globalMaxChunkLoadRate || TICKET_ADDITION_COUNTER_LONG.getRate() >= PaperConfig.globalMaxChunkLoadRate))) {
+                    // don't poll, we didn't load it
+                    this.chunkLoadQueue.add(data);
+                    break;
+                }
+            }
+
+            // can only poll after we decide to load
+            data.loadQueue.pollFirst();
+
+            // now that we've polled we can re-add to load queue
+            this.chunkLoadQueue.add(data);
+
+            // add necessary tickets to load chunk up to send-ready
+            for (int dz = -1; dz <= 1; ++dz) {
+                for (int dx = -1; dx <= 1; ++dx) {
+                    final int offX = queuedLoad.chunkX + dx;
+                    final int offZ = queuedLoad.chunkZ + dz;
+                    final ChunkPos chunkPos = new ChunkPos(offX, offZ);
+
+                    this.chunkMap.level.getChunkSource().addTicketAtLevel(TicketType.PLAYER, chunkPos, LOADED_TICKET_LEVEL, chunkPos);
+                    if (this.chunkMap.level.getChunkSource().getChunkAtIfLoadedMainThreadNoCache(offX, offZ) != null) {
+                        continue;
+                    }
+
+                    if (priority > 0.0 && this.chunkTicketTracker.add(CoordinateUtils.getChunkKey(offX, offZ))) {
+                        // won't reach here if unloadedTargetChunk is false
+                        ++this.concurrentChunkLoads;
+                        TICKET_ADDITION_COUNTER_SHORT.addTime(time);
+                        TICKET_ADDITION_COUNTER_LONG.addTime(time);
+                    }
+                }
+            }
+
+            // mark that we've added tickets here
+            this.isTargetedForPlayerLoad.add(chunkKey);
+
+            // it's possible all we needed was the player tickets to queue up the send.
+            if (this.isChunkPlayerLoaded(queuedLoad.chunkX, queuedLoad.chunkZ)) {
+                // yup, all we needed.
+                this.onChunkSendReady(queuedLoad.chunkX, queuedLoad.chunkZ);
+            }
+        }
+    }
+
+    public void tickMidTick() {
+        // try to send more chunks
+        this.trySendChunks();
+
+        // try to queue more chunks to load
+        this.tryLoadChunks();
+    }
+
+    static final class ChunkPriorityHolder {
+        public final int chunkX;
+        public final int chunkZ;
+        public final int manhattanDistanceToPlayer;
+        public final double priority;
+
+        public ChunkPriorityHolder(final int chunkX, final int chunkZ, final int manhattanDistanceToPlayer, final double priority) {
+            this.chunkX = chunkX;
+            this.chunkZ = chunkZ;
+            this.manhattanDistanceToPlayer = manhattanDistanceToPlayer;
+            this.priority = priority;
+        }
+    }
+
+    public static final class PlayerLoaderData {
+
+        protected static final float FOV = 110.0f;
+        protected static final double PRIORITISED_DISTANCE = 12.0 * 16.0;
+
+        // Player max sprint speed is approximately 8m/s
+        protected static final double LOOK_PRIORITY_SPEED_THRESHOLD = (10.0/20.0) * (10.0/20.0);
+        protected static final double LOOK_PRIORITY_YAW_DELTA_RECALC_THRESHOLD = 3.0f;
+
+        protected double lastLocX = Double.NEGATIVE_INFINITY;
+        protected double lastLocZ = Double.NEGATIVE_INFINITY;
+
+        protected int lastChunkX;
+        protected int lastChunkZ;
+
+        // this is corrected so that 0 is along the positive x-axis
+        protected float lastYaw = Float.NEGATIVE_INFINITY;
+
+        protected int lastSendDistance = Integer.MIN_VALUE;
+        protected int lastLoadDistance = Integer.MIN_VALUE;
+        protected int lastTickDistance = Integer.MIN_VALUE;
+        protected boolean usingLookingPriority;
+
+        protected final ServerPlayer player;
+        protected final PlayerChunkLoader loader;
+
+        // warning: modifications of this field must be aware that the loadQueue inside PlayerChunkLoader uses this field
+        // in a comparator!
+        protected final ArrayDeque<ChunkPriorityHolder> loadQueue = new ArrayDeque<>();
+        protected final LongOpenHashSet sentChunks = new LongOpenHashSet();
+
+        protected final TreeSet<ChunkPriorityHolder> sendQueue = new TreeSet<>((final ChunkPriorityHolder p1, final ChunkPriorityHolder p2) -> {
+            final int distanceCompare = Integer.compare(p1.manhattanDistanceToPlayer, p2.manhattanDistanceToPlayer);
+            if (distanceCompare != 0) {
+                return distanceCompare;
+            }
+
+            final int coordinateXCompare = Integer.compare(p1.chunkX, p2.chunkX);
+            if (coordinateXCompare != 0) {
+                return coordinateXCompare;
+            }
+
+            return Integer.compare(p1.chunkZ, p2.chunkZ);
+        });
+
+        protected int sendViewDistance = -1;
+        protected int loadViewDistance = -1;
+        protected int tickViewDistance = -1;
+
+        protected long nextChunkSendTarget;
+
+        public PlayerLoaderData(final ServerPlayer player, final PlayerChunkLoader loader) {
+            this.player = player;
+            this.loader = loader;
+        }
+
+        // these view distance methods are for api
+        public int getTargetSendViewDistance() {
+            final int tickViewDistance = this.tickViewDistance == -1 ? this.loader.getTickDistance() : this.tickViewDistance;
+            final int loadViewDistance = Math.max(tickViewDistance + 1, this.loadViewDistance == -1 ? this.loader.getLoadDistance() : this.loadViewDistance);
+            final int clientViewDistance = this.getClientViewDistance();
+            final int sendViewDistance = Math.min(loadViewDistance, this.sendViewDistance == -1 ? (!PaperConfig.playerAutoConfigureSendViewDistance || clientViewDistance == -1 ? this.loader.getSendDistance() : clientViewDistance + 1) : this.sendViewDistance);
+            return sendViewDistance;
+        }
+
+        public void setTargetSendViewDistance(final int distance) {
+            if (distance != -1 && (distance < MIN_VIEW_DISTANCE || distance > MAX_VIEW_DISTANCE + 1)) {
+                throw new IllegalArgumentException(Integer.toString(distance));
+            }
+            this.sendViewDistance = distance;
+        }
+
+        public int getTargetNoTickViewDistance() {
+            return (this.loadViewDistance == -1 ? this.getLoadDistance() : this.loadViewDistance) - 1;
+        }
+
+        public void setTargetNoTickViewDistance(final int distance) {
+            if (distance != -1 && (distance < MIN_VIEW_DISTANCE || distance > MAX_VIEW_DISTANCE)) {
+                throw new IllegalArgumentException(Integer.toString(distance));
+            }
+            this.loadViewDistance = distance == -1 ? -1 : distance + 1;
+        }
+
+        public int getTargetTickViewDistance() {
+            return this.tickViewDistance == -1 ? this.loader.getTickDistance() : this.tickViewDistance;
+        }
+
+        public void setTargetTickViewDistance(final int distance) {
+            if (distance < MIN_VIEW_DISTANCE || distance > MAX_VIEW_DISTANCE) {
+                throw new IllegalArgumentException(Integer.toString(distance));
+            }
+            this.tickViewDistance = distance;
+        }
+
+        protected int getLoadDistance() {
+            final int tickViewDistance = this.tickViewDistance == -1 ? this.loader.getTickDistance() : this.tickViewDistance;
+
+            return Math.max(tickViewDistance + 1, this.loadViewDistance == -1 ? this.loader.getLoadDistance() : this.loadViewDistance);
+        }
+
+        public boolean hasSentChunk(final int chunkX, final int chunkZ) {
+            return this.sentChunks.contains(CoordinateUtils.getChunkKey(chunkX, chunkZ));
+        }
+
+        public void sendChunk(final int chunkX, final int chunkZ, final Runnable onChunkSend) {
+            if (this.sentChunks.add(CoordinateUtils.getChunkKey(chunkX, chunkZ))) {
+                this.player.getLevel().getChunkSource().chunkMap.updateChunkTracking(this.player,
+                        new ChunkPos(chunkX, chunkZ), new Packet[2], false, true); // unloaded, loaded
+                this.player.connection.connection.execute(onChunkSend);
+            } else {
+                throw new IllegalStateException();
+            }
+        }
+
+        public void unloadChunk(final int chunkX, final int chunkZ) {
+            if (this.sentChunks.remove(CoordinateUtils.getChunkKey(chunkX, chunkZ))) {
+                this.player.getLevel().getChunkSource().chunkMap.updateChunkTracking(this.player,
+                        new ChunkPos(chunkX, chunkZ), null, true, false); // unloaded, loaded
+            }
+        }
+
+        protected static boolean triangleIntersects(final double p1x, final double p1z, // triangle point
+                                                    final double p2x, final double p2z, // triangle point
+                                                    final double p3x, final double p3z, // triangle point
+
+                                                    final double targetX, final double targetZ) { // point
+            // from barycentric coordinates:
+            // targetX = a*p1x + b*p2x + c*p3x
+            // targetZ = a*p1z + b*p2z + c*p3z
+            // 1.0     = a*1.0 + b*1.0 + c*1.0
+            // where a, b, c >= 0.0
+            // so, if any of a, b, c are less-than zero then there is no intersection.
+
+            // d = ((p2z - p3z)(p1x - p3x) + (p3x - p2x)(p1z - p3z))
+            // a = ((p2z - p3z)(targetX - p3x) + (p3x - p2x)(targetZ - p3z)) / d
+            // b = ((p3z - p1z)(targetX - p3x) + (p1x - p3x)(targetZ - p3z)) / d
+            // c = 1.0 - a - b
+
+            final double d = (p2z - p3z)*(p1x - p3x) + (p3x - p2x)*(p1z - p3z);
+            final double a = ((p2z - p3z)*(targetX - p3x) + (p3x - p2x)*(targetZ - p3z)) / d;
+
+            if (a < 0.0 || a > 1.0) {
+                return false;
+            }
+
+            final double b = ((p3z - p1z)*(targetX - p3x) + (p1x - p3x)*(targetZ - p3z)) / d;
+            if (b < 0.0 || b > 1.0) {
+                return false;
+            }
+
+            final double c = 1.0 - a - b;
+
+            return c >= 0.0 && c <= 1.0;
+        }
+
+        public void remove() {
+            this.loader.broadcastMap.remove(this.player);
+            this.loader.loadMap.remove(this.player);
+            this.loader.loadTicketCleanup.remove(this.player);
+            this.loader.tickMap.remove(this.player);
+        }
+
+        protected int getClientViewDistance() {
+            return this.player.clientViewDistance == null ? -1 : this.player.clientViewDistance.intValue();
+        }
+
+        public void update() {
+            final int tickViewDistance = this.tickViewDistance == -1 ? this.loader.getTickDistance() : this.tickViewDistance;
+            // load view cannot be less-than tick view + 1
+            final int loadViewDistance = Math.max(tickViewDistance + 1, this.loadViewDistance == -1 ? this.loader.getLoadDistance() : this.loadViewDistance);
+            // send view cannot be greater-than load view
+            final int clientViewDistance = this.getClientViewDistance();
+            final int sendViewDistance = Math.min(loadViewDistance, this.sendViewDistance == -1 ? (!PaperConfig.playerAutoConfigureSendViewDistance || clientViewDistance == -1 ? this.loader.getSendDistance() : clientViewDistance + 1) : this.sendViewDistance);
+
+            final double posX = this.player.getX();
+            final double posZ = this.player.getZ();
+            final float yaw = MCUtil.normalizeYaw(this.player.yRot + 90.0f); // mc yaw 0 is along the positive z axis, but obviously this is really dumb - offset so we are at positive x-axis
+
+            // in general, we really only want to prioritise chunks in front if we know we're moving pretty fast into them.
+            final boolean useLookPriority = PaperConfig.playerFrustumPrioritisation && (this.player.getDeltaMovement().horizontalDistanceSqr() > LOOK_PRIORITY_SPEED_THRESHOLD ||
+                    this.player.getAbilities().flying);
+
+            // make sure we're in the send queue
+            this.loader.chunkSendWaitQueue.add(this);
+
+            if (
+                // has view distance stayed the same?
+                    sendViewDistance == this.lastSendDistance
+                            && loadViewDistance == this.lastLoadDistance
+                            && tickViewDistance == this.lastTickDistance
+
+                            && (this.usingLookingPriority ? (
+                                    // has our block stayed the same (this also accounts for chunk change)?
+                                    Mth.floor(this.lastLocX) == Mth.floor(posX)
+                                    && Mth.floor(this.lastLocZ) == Mth.floor(posZ)
+                            ) : (
+                                    // has our chunk stayed the same
+                                    (Mth.floor(this.lastLocX) >> 4) == (Mth.floor(posX) >> 4)
+                                    && (Mth.floor(this.lastLocZ) >> 4) == (Mth.floor(posZ) >> 4)
+                            ))
+
+                            // has our decision about look priority changed?
+                            && this.usingLookingPriority == useLookPriority
+
+                            // if we are currently using look priority, has our yaw stayed within recalc threshold?
+                            && (!this.usingLookingPriority || Math.abs(yaw - this.lastYaw) <= LOOK_PRIORITY_YAW_DELTA_RECALC_THRESHOLD)
+            ) {
+                // nothing we care about changed, so we're not re-calculating
+                return;
+            }
+
+            final int centerChunkX = Mth.floor(posX) >> 4;
+            final int centerChunkZ = Mth.floor(posZ) >> 4;
+
+            this.player.needsChunkCenterUpdate = true;
+            this.loader.broadcastMap.addOrUpdate(this.player, centerChunkX, centerChunkZ, sendViewDistance);
+            this.player.needsChunkCenterUpdate = false;
+            this.loader.loadMap.addOrUpdate(this.player, centerChunkX, centerChunkZ, loadViewDistance);
+            this.loader.loadTicketCleanup.addOrUpdate(this.player, centerChunkX, centerChunkZ, loadViewDistance + 1);
+            this.loader.tickMap.addOrUpdate(this.player, centerChunkX, centerChunkZ, tickViewDistance);
+
+            if (sendViewDistance != this.lastSendDistance) {
+                // update the view radius for client
+                // note that this should be after the map calls because the client wont expect unload calls not in its VD
+                // and it's possible we decreased VD here
+                this.player.connection.send(new ClientboundSetChunkCacheRadiusPacket(sendViewDistance - 1)); // client already expects the 1 radius neighbours, so subtract 1.
+            }
+
+            this.lastLocX = posX;
+            this.lastLocZ = posZ;
+            this.lastYaw = yaw;
+            this.lastSendDistance = sendViewDistance;
+            this.lastLoadDistance = loadViewDistance;
+            this.lastTickDistance = tickViewDistance;
+            this.usingLookingPriority = useLookPriority;
+
+            this.lastChunkX = centerChunkX;
+            this.lastChunkZ = centerChunkZ;
+
+            // points for player "view" triangle:
+
+            // obviously, the player pos is a vertex
+            final double p1x = posX;
+            final double p1z = posZ;
+
+            // to the left of the looking direction
+            final double p2x = PRIORITISED_DISTANCE * Math.cos(Math.toRadians(yaw + (double)(FOV / 2.0))) // calculate rotated vector
+                    + p1x; // offset vector
+            final double p2z = PRIORITISED_DISTANCE * Math.sin(Math.toRadians(yaw + (double)(FOV / 2.0))) // calculate rotated vector
+                    + p1z; // offset vector
+
+            // to the right of the looking direction
+            final double p3x = PRIORITISED_DISTANCE * Math.cos(Math.toRadians(yaw - (double)(FOV / 2.0))) // calculate rotated vector
+                    + p1x; // offset vector
+            final double p3z = PRIORITISED_DISTANCE * Math.sin(Math.toRadians(yaw - (double)(FOV / 2.0))) // calculate rotated vector
+                    + p1z; // offset vector
+
+            // now that we have all of our points, we can recalculate the load queue
+
+            final List<ChunkPriorityHolder> loadQueue = new ArrayList<>();
+
+            // clear send queue, we are re-sorting
+            this.sendQueue.clear();
+
+            final int searchViewDistance = Math.max(loadViewDistance, sendViewDistance);
+
+            for (int dx = -searchViewDistance; dx <= searchViewDistance; ++dx) {
+                for (int dz = -searchViewDistance; dz <= searchViewDistance; ++dz) {
+                    final int chunkX = dx + centerChunkX;
+                    final int chunkZ = dz + centerChunkZ;
+                    final int squareDistance = Math.max(Math.abs(dx), Math.abs(dz));
+
+                    if (this.hasSentChunk(chunkX, chunkZ)) {
+                        // already sent (which means it is also loaded)
+                        continue;
+                    }
+
+                    final boolean loadChunk = squareDistance <= loadViewDistance;
+                    final boolean sendChunk = squareDistance <= sendViewDistance;
+
+                    final boolean prioritised = useLookPriority && triangleIntersects(
+                            // prioritisation triangle
+                            p1x, p1z, p2x, p2z, p3x, p3z,
+
+                            // center of chunk
+                            (double)((chunkX << 4) | 8), (double)((chunkZ << 4) | 8)
+                    );
+
+
+                    final int manhattanDistance = (Math.abs(dx) + Math.abs(dz));
+
+                    final double priority;
+
+                    if (squareDistance <= PaperConfig.playerMinChunkLoadRadius) {
+                        // priority should be negative, and we also want to order it from center outwards
+                        // so we want (0,0) to be the smallest, and (minLoadedRadius,minLoadedRadius) to be the greatest
+                        priority = -((2 * PaperConfig.playerMinChunkLoadRadius + 1) - (dx + dz));
+                    } else {
+                        if (prioritised) {
+                            // we don't prioritise these chunks above others because we also want to make sure some chunks
+                            // will be loaded if the player changes direction
+                            priority = (double)manhattanDistance / 6.0;
+                        } else {
+                            priority = (double)manhattanDistance;
+                        }
+                    }
+
+                    final ChunkPriorityHolder holder = new ChunkPriorityHolder(chunkX, chunkZ, manhattanDistance, priority);
+
+                    if (!this.loader.isChunkPlayerLoaded(chunkX, chunkZ)) {
+                        if (loadChunk) {
+                            loadQueue.add(holder);
+                        }
+                    } else {
+                        // loaded but not sent: so queue it!
+                        if (sendChunk) {
+                            this.sendQueue.add(holder);
+                        }
+                    }
+                }
+            }
+
+            loadQueue.sort((final ChunkPriorityHolder p1, final ChunkPriorityHolder p2) -> {
+                return Double.compare(p1.priority, p2.priority);
+            });
+
+            // we're modifying loadQueue, must remove
+            this.loader.chunkLoadQueue.remove(this);
+
+            this.loadQueue.clear();
+            this.loadQueue.addAll(loadQueue);
+
+            // must re-add
+            this.loader.chunkLoadQueue.add(this);
+        }
+    }
+}
diff --git a/src/main/java/net/minecraft/network/Connection.java b/src/main/java/net/minecraft/network/Connection.java
index 032d65a489d65e9b5b5066dff80c65d2e1b28c82..580bdaa99129c8edb82b835edfa822892f1cd243 100644
--- a/src/main/java/net/minecraft/network/Connection.java
+++ b/src/main/java/net/minecraft/network/Connection.java
@@ -93,6 +93,28 @@ public class Connection extends SimpleChannelInboundHandler<Packet<?>> {
     public boolean queueImmunity = false;
     public ConnectionProtocol protocol;
     // Paper end
+    // Paper start - add pending task queue
+    private final Queue<Runnable> pendingTasks = new java.util.concurrent.ConcurrentLinkedQueue<>();
+    public void execute(final Runnable run) {
+        if (this.channel == null || !this.channel.isRegistered()) {
+            run.run();
+            return;
+        }
+        final boolean queue = !this.queue.isEmpty();
+        if (!queue) {
+            this.channel.eventLoop().execute(run);
+        } else {
+            this.pendingTasks.add(run);
+            if (this.queue.isEmpty()) {
+                // something flushed async, dump tasks now
+                Runnable r;
+                while ((r = this.pendingTasks.poll()) != null) {
+                    this.channel.eventLoop().execute(r);
+                }
+            }
+        }
+    }
+    // Paper end - add pending task queue
 
     // Paper start - allow controlled flushing
     volatile boolean canFlush = true;
@@ -399,6 +421,7 @@ public class Connection extends SimpleChannelInboundHandler<Packet<?>> {
         return false;
     }
     private boolean processQueue() {
+        try { // Paper - add pending task queue
         if (this.queue.isEmpty()) return true;
         // Paper start - make only one flush call per sendPacketQueue() call
         final boolean needsFlush = this.canFlush;
@@ -430,6 +453,12 @@ public class Connection extends SimpleChannelInboundHandler<Packet<?>> {
             }
         }
         return true;
+        } finally { // Paper start - add pending task queue
+            Runnable r;
+            while ((r = this.pendingTasks.poll()) != null) {
+                this.channel.eventLoop().execute(r);
+            }
+        } // Paper end - add pending task queue
     }
     // Paper end
 
diff --git a/src/main/java/net/minecraft/server/MCUtil.java b/src/main/java/net/minecraft/server/MCUtil.java
index 82a233b413791eff4bc6b9140b5bbf99354ed671..15fb4ee2066df1c8ce341913a64f350fb8b9718c 100644
--- a/src/main/java/net/minecraft/server/MCUtil.java
+++ b/src/main/java/net/minecraft/server/MCUtil.java
@@ -642,7 +642,7 @@ public final class MCUtil {
 
             worldData.addProperty("name", world.getWorld().getName());
             worldData.addProperty("view-distance", world.getChunkSource().chunkMap.getEffectiveViewDistance());
-            worldData.addProperty("no-view-distance", world.getChunkSource().chunkMap.getRawNoTickViewDistance());
+            worldData.addProperty("no-view-distance", world.getChunkSource().chunkMap.playerChunkManager.getTargetNoTickViewDistance()); // Paper - replace old player chunk management
             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 a9267e64e54f451c896e35693f469b8563f578f9..326aecc38a7f93fe0d25fb9b772d06f78f99781d 100644
--- a/src/main/java/net/minecraft/server/level/ChunkHolder.java
+++ b/src/main/java/net/minecraft/server/level/ChunkHolder.java
@@ -491,7 +491,7 @@ public class ChunkHolder {
         // 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.PlayerAreaMap viewDistanceMap = this.chunkMap.playerChunkManager.broadcastMap; // Paper - replace old player chunk manager
         com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> players = viewDistanceMap.getObjectsInRange(this.pos);
         if (players == null) {
             return;
@@ -508,6 +508,7 @@ public class ChunkHolder {
 
                 int viewDistance = viewDistanceMap.getLastViewDistance(player);
                 long lastPosition = viewDistanceMap.getLastCoordinate(player);
+                if (!this.chunkMap.playerChunkManager.isChunkSent(player, this.pos.x, this.pos.z)) continue; // Paper - replace player chunk management
 
                 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);
@@ -524,6 +525,7 @@ public class ChunkHolder {
                     continue;
                 }
                 ServerPlayer player = (ServerPlayer)temp;
+                if (!this.chunkMap.playerChunkManager.isChunkSent(player, this.pos.x, this.pos.z)) continue; // Paper - replace player chunk management
                 player.connection.send(packet);
             }
         }
diff --git a/src/main/java/net/minecraft/server/level/ChunkMap.java b/src/main/java/net/minecraft/server/level/ChunkMap.java
index 85c97767cdaf45b24f5764a6a1ef3c56535bb37f..8e0762bc1d705b7df664b6270c4d536f77572b87 100644
--- a/src/main/java/net/minecraft/server/level/ChunkMap.java
+++ b/src/main/java/net/minecraft/server/level/ChunkMap.java
@@ -187,22 +187,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
     final CallbackExecutor chunkLoadConversionCallbackExecutor = new CallbackExecutor(); // Paper
     // Paper start - distance maps
     private final com.destroystokyo.paper.util.misc.PooledLinkedHashSets<ServerPlayer> 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
+    public final io.papermc.paper.chunk.PlayerChunkLoader playerChunkManager = new io.papermc.paper.chunk.PlayerChunkLoader(this, this.pooledLinkedPlayerHashSets); // Paper - replace chunk loader
     // Paper start - use distance map to optimise tracker
     public static boolean isLegacyTrackingEntity(Entity entity) {
         return entity.isLegacyTrackingEntity;
@@ -241,7 +226,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
             com.destroystokyo.paper.util.misc.PlayerAreaMap trackMap = this.playerEntityTrackerTrackMaps[i];
             int trackRange = this.entityTrackerTrackRanges[i];
 
-            trackMap.add(player, chunkX, chunkZ, Math.min(trackRange, this.getEffectiveViewDistance()));
+            trackMap.add(player, chunkX, chunkZ, Math.min(trackRange, player.getBukkitEntity().getViewDistance())); // Paper - per player view distances
         }
         // Paper end - use distance map to optimise entity tracker
         // Paper start - optimise PlayerChunkMap#isOutsideRange
@@ -250,19 +235,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         // Paper start - optimise PlayerChunkMap#isOutsideRange
         this.playerChunkTickRangeMap.add(player, chunkX, chunkZ, DistanceManager.MOB_SPAWN_RANGE);
         // Paper end - optimise PlayerChunkMap#isOutsideRange
-        // 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
+        this.playerChunkManager.addPlayer(player); // Paper - replace chunk loader
     }
 
     void removePlayerFromDistanceMaps(ServerPlayer player) {
@@ -275,11 +248,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         this.playerMobSpawnMap.remove(player);
         this.playerChunkTickRangeMap.remove(player);
         // Paper end - optimise PlayerChunkMap#isOutsideRange
-        // Paper start - no-tick view distance
-        this.playerViewDistanceBroadcastMap.remove(player);
-        this.playerViewDistanceTickMap.remove(player);
-        this.playerViewDistanceNoTickMap.remove(player);
-        // Paper end - no-tick view distance
+        this.playerChunkManager.removePlayer(player); // Paper - replace chunk loader
     }
 
     void updateMaps(ServerPlayer player) {
@@ -291,25 +260,13 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
             com.destroystokyo.paper.util.misc.PlayerAreaMap trackMap = this.playerEntityTrackerTrackMaps[i];
             int trackRange = this.entityTrackerTrackRanges[i];
 
-            trackMap.update(player, chunkX, chunkZ, Math.min(trackRange, this.getEffectiveViewDistance()));
+            trackMap.update(player, chunkX, chunkZ, Math.min(trackRange, player.getBukkitEntity().getViewDistance())); // Paper - per player view distances
         }
         // Paper end - use distance map to optimise entity tracker
         // Paper start - optimise PlayerChunkMap#isOutsideRange
         this.playerChunkTickRangeMap.update(player, chunkX, chunkZ, DistanceManager.MOB_SPAWN_RANGE);
         // Paper end - optimise PlayerChunkMap#isOutsideRange
-        // 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
+        this.playerChunkManager.updatePlayer(player); // Paper - replace chunk loader
     }
     // Paper end
     // Paper start
@@ -394,43 +351,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         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<ServerPlayer> 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<ServerPlayer> 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<ServerPlayer> 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<ServerPlayer> newState) -> {
-                ChunkMap.this.updateChunkTracking(player, new ChunkPos(rangeX, rangeZ), null, true, false); // unloaded, loaded
-            });
+        this.setNoTickViewDistance(this.level.paperConfig.noTickViewDistance); // Paper - replace chunk loading system
         // Paper end - no-tick view distance
         this.playerMobDistanceMap = this.level.paperConfig.perPlayerMobSpawns ? new com.destroystokyo.paper.util.PlayerMobDistanceMap() : null; // Paper
         // Paper start - use distance map to optimise entity tracker
@@ -537,6 +458,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
     }
 
     public void checkHighPriorityChunks(ServerPlayer player) {
+        if (true) return; // Paper - replace player chunk loader
         int currentTick = MinecraftServer.currentTick;
         if (currentTick - player.lastHighPriorityChecked < 20 || !player.isRealPlayer) { // weed out fake players
             return;
@@ -544,7 +466,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         player.lastHighPriorityChecked = currentTick;
         it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap priorities = new it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap();
 
-        int viewDistance = getEffectiveNoTickViewDistance();
+        int viewDistance = 10;//int viewDistance = getEffectiveNoTickViewDistance(); // Paper - replace player chunk loader
         net.minecraft.core.BlockPos.MutableBlockPos pos = new net.minecraft.core.BlockPos.MutableBlockPos();
 
         // Prioritize circular near
@@ -610,7 +532,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
     }
 
     private boolean shouldSkipPrioritization(ChunkPos coord) {
-        if (playerViewDistanceNoTickMap.getObjectsInRange(coord.toLong()) == null) return true;
+        if (true) return true; // Paper - replace player chunk loader - unused outside paper player loader logic
         ChunkHolder chunk = getUpdatingChunkIfPresent(coord.toLong());
         return chunk != null && (chunk.isFullChunkReady());
     }
@@ -1548,7 +1470,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
             int k = this.viewDistance;
 
             this.viewDistance = j;
-            this.setNoTickViewDistance(this.getRawNoTickViewDistance()); // Paper - no-tick view distance - propagate changes to no-tick, which does the actual chunk loading/sending
+            this.playerChunkManager.setTickDistance(Mth.clamp(watchDistance, 2, 32)); // Paper - replace player loader system
         }
 
     }
@@ -1556,26 +1478,11 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
     // Paper start - no-tick view distance
     public final void setNoTickViewDistance(int viewDistance) {
         viewDistance = viewDistance == -1 ? -1 : Mth.clamp(viewDistance, 2, 32);
-
-        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
-            }
-        }
+        this.playerChunkManager.setLoadDistance(viewDistance == -1 ? -1 : viewDistance + 1); // Paper - replace player loader system - add 1 here, we need an extra one to send to clients for chunks in this viewDistance to render
 
     }
 
-    protected void updateChunkTracking(ServerPlayer player, ChunkPos pos, Packet<?>[] packets, boolean withinMaxWatchDistance, boolean withinViewDistance) {
+    public void updateChunkTracking(ServerPlayer player, ChunkPos pos, Packet<?>[] packets, boolean withinMaxWatchDistance, boolean withinViewDistance) { // Paper - public
         if (player.level == this.level) {
             if (withinViewDistance && !withinMaxWatchDistance) {
                 ChunkHolder playerchunk = this.getVisibleChunkIfPresent(pos.toLong());
@@ -1904,6 +1811,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         */ // Paper end - replaced by distance map
 
         this.updateMaps(player); // Paper - distance maps
+        this.playerChunkManager.updatePlayer(player); // Paper - respond to movement immediately
 
     }
 
@@ -1912,7 +1820,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         // 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<ServerPlayer> inRange = this.playerViewDistanceBroadcastMap.getObjectsInRange(chunkPos);
+        com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> inRange = this.playerChunkManager.broadcastMap.getObjectsInRange(chunkPos); // Paper - replace player chunk loader system
 
         if (inRange == null) {
             return Stream.empty();
@@ -1928,8 +1836,9 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
                     continue;
                 }
                 ServerPlayer player = (ServerPlayer)temp;
-                int viewDistance = this.playerViewDistanceBroadcastMap.getLastViewDistance(player);
-                long lastPosition = this.playerViewDistanceBroadcastMap.getLastCoordinate(player);
+                if (!this.playerChunkManager.isChunkSent(player, chunkPos.x, chunkPos.z)) continue; // Paper - replace player chunk management
+                int viewDistance = this.playerChunkManager.broadcastMap.getLastViewDistance(player); // Paper - replace player chunk loader system
+                long lastPosition = this.playerChunkManager.broadcastMap.getLastCoordinate(player); // Paper - replace player chunk loader system
 
                 int distX = Math.abs(MCUtil.getCoordinateX(lastPosition) - chunkPos.x);
                 int distZ = Math.abs(MCUtil.getCoordinateZ(lastPosition) - chunkPos.z);
@@ -1944,6 +1853,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
                     continue;
                 }
                 ServerPlayer player = (ServerPlayer)temp;
+                if (!this.playerChunkManager.isChunkSent(player, chunkPos.x, chunkPos.z)) continue; // Paper - replace player chunk management
                 players.add(player);
             }
         }
@@ -2357,7 +2267,7 @@ Sections go from 0..16. Now whenever a section is not empty, it can potentially
                 double vec3d_dy = player.getY() - this.entity.getY();
                 double vec3d_dz = player.getZ() - this.entity.getZ();
                 // Paper end - remove allocation of Vec3D here
-                int i = Math.min(this.getEffectiveRange(), (ChunkMap.this.viewDistance - 1) * 16);
+                int i = Math.min(this.getEffectiveRange(), player.getBukkitEntity().getViewDistance() * 16); // Paper - per player view distance
                 boolean flag = vec3d_dx >= (double) (-i) && vec3d_dx <= (double) i && vec3d_dz >= (double) (-i) && vec3d_dz <= (double) i && this.entity.broadcastToPlayer(player); // Paper - remove allocation of Vec3D here
 
                 // CraftBukkit start - respect vanish API
diff --git a/src/main/java/net/minecraft/server/level/DistanceManager.java b/src/main/java/net/minecraft/server/level/DistanceManager.java
index 1cc4e0a1f3d8235ef88b48e01ca8b78a263d2676..0b34536cdffab31a717b613042d7098109846586 100644
--- a/src/main/java/net/minecraft/server/level/DistanceManager.java
+++ b/src/main/java/net/minecraft/server/level/DistanceManager.java
@@ -46,7 +46,7 @@ public abstract class DistanceManager {
     public final Long2ObjectOpenHashMap<SortedArraySet<Ticket<?>>> tickets = new Long2ObjectOpenHashMap();
     private final DistanceManager.ChunkTicketTracker ticketTracker = new DistanceManager.ChunkTicketTracker();
     public static final int MOB_SPAWN_RANGE = 8; // private final ChunkMapDistance.b f = new ChunkMapDistance.b(8); // Paper - no longer used
-    private final DistanceManager.PlayerTicketTracker playerTicketManager = new DistanceManager.PlayerTicketTracker(33);
+    //private final DistanceManager.PlayerTicketTracker playerTicketManager = new DistanceManager.PlayerTicketTracker(33); // Paper - no longer used
     // Paper start use a queue, but still keep unique requirement
     public final java.util.Queue<ChunkHolder> pendingChunkUpdates = new java.util.ArrayDeque<ChunkHolder>() {
         @Override
@@ -113,7 +113,7 @@ public abstract class DistanceManager {
     public boolean runAllUpdates(ChunkMap playerchunkmap) {
         //this.f.a(); // Paper - no longer used
         org.spigotmc.AsyncCatcher.catchOp("DistanceManagerTick"); // Paper
-        this.playerTicketManager.runAllUpdates();
+        //this.playerTicketManager.runAllUpdates(); // Paper - no longer used
         int i = Integer.MAX_VALUE - this.ticketTracker.runDistanceUpdates(Integer.MAX_VALUE);
         boolean flag = i != 0;
 
@@ -313,7 +313,7 @@ public abstract class DistanceManager {
         org.spigotmc.AsyncCatcher.catchOp("ChunkMapDistance::addPriorityTicket");
         long pair = coords.toLong();
         ChunkHolder chunk = chunkMap.getUpdatingChunkIfPresent(pair);
-        boolean needsTicket = chunkMap.playerViewDistanceNoTickMap.getObjectsInRange(pair) != null && !hasPlayerTicket(coords, 33);
+        boolean needsTicket = false; // Paper - replace old loader system
 
         if (needsTicket) {
             Ticket<?> ticket = new Ticket<>(TicketType.PLAYER, 33, coords);
@@ -411,7 +411,7 @@ public abstract class DistanceManager {
             return new ObjectOpenHashSet();
         })).add(player);
         //this.f.update(i, 0, true); // Paper - no longer used
-        this.playerTicketManager.update(i, 0, true);
+        //this.playerTicketManager.update(i, 0, true); // Paper - no longer used
     }
 
     public void removePlayer(SectionPos pos, ServerPlayer player) {
@@ -423,7 +423,7 @@ public abstract class DistanceManager {
         if (objectset == null || objectset.isEmpty()) { // Paper
             this.playersPerChunk.remove(i);
             //this.f.update(i, Integer.MAX_VALUE, false); // Paper - no longer used
-            this.playerTicketManager.update(i, Integer.MAX_VALUE, false);
+            //this.playerTicketManager.update(i, Integer.MAX_VALUE, false); // Paper - no longer used
         }
 
     }
@@ -442,7 +442,7 @@ public abstract class DistanceManager {
     }
 
     protected void setNoTickViewDistance(int i) { // Paper - force abi breakage on usage change
-        this.playerTicketManager.updateViewDistance(i);
+        throw new UnsupportedOperationException("use world api"); // Paper - no longer relevant
     }
 
     public int getNaturalSpawnChunkCount() {
@@ -563,6 +563,7 @@ public abstract class DistanceManager {
         }
     }
 
+    /* Paper - replace old loader system
     private class FixedPlayerDistanceChunkTracker extends ChunkTracker {
 
         protected final Long2ByteMap chunks = new Long2ByteOpenHashMap();
@@ -858,4 +859,5 @@ public abstract class DistanceManager {
         }
         // Paper end
     }
+     */ // Paper - replace old loader system
 }
diff --git a/src/main/java/net/minecraft/server/level/ServerChunkCache.java b/src/main/java/net/minecraft/server/level/ServerChunkCache.java
index 39840403da99252c5d634e99e1da19f6066dee7c..6db8c95693772296d947fbc051b97937fd184685 100644
--- a/src/main/java/net/minecraft/server/level/ServerChunkCache.java
+++ b/src/main/java/net/minecraft/server/level/ServerChunkCache.java
@@ -929,6 +929,7 @@ public class ServerChunkCache extends ChunkSource {
         this.level.timings.doChunkMap.stopTiming(); // Spigot
         this.level.getProfiler().popPush("chunks");
         this.level.timings.chunks.startTiming(); // Paper - timings
+        this.chunkMap.playerChunkManager.tick(); // Paper - this is mostly is to account for view distance changes
         this.tickChunks();
         this.level.timings.chunks.stopTiming(); // Paper - timings
         this.level.timings.doChunkUnload.startTiming(); // Spigot
@@ -1219,6 +1220,7 @@ public class ServerChunkCache extends ChunkSource {
         public boolean pollTask() {
         try {
             boolean execChunkTask = com.destroystokyo.paper.io.chunk.ChunkTaskManager.pollChunkWaitQueue() || ServerChunkCache.this.level.asyncChunkTaskManager.pollNextChunkTask(); // Paper
+            ServerChunkCache.this.chunkMap.playerChunkManager.tickMidTick(); // Paper
             if (ServerChunkCache.this.runDistanceManagerUpdates()) {
                 return true;
             } else {
diff --git a/src/main/java/net/minecraft/server/level/ServerPlayer.java b/src/main/java/net/minecraft/server/level/ServerPlayer.java
index d0a6da33bb9152b6fafe6b3a788817d523c1fe49..6614954dd30efdd6a53d561fcb3cbfba8b168805 100644
--- a/src/main/java/net/minecraft/server/level/ServerPlayer.java
+++ b/src/main/java/net/minecraft/server/level/ServerPlayer.java
@@ -261,7 +261,7 @@ public class ServerPlayer extends Player {
 
     public double lastEntitySpawnRadiusSquared; // Paper - optimise isOutsideRange, this field is in blocks
     public final com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> cachedSingleHashSet; // Paper
-    boolean needsChunkCenterUpdate; // Paper - no-tick view distance
+    public boolean needsChunkCenterUpdate; // Paper - no-tick view distance // Paper - public
     public org.bukkit.event.player.PlayerQuitEvent.QuitReason quitReason = null; // Paper - there are a lot of changes to do if we change all methods leading to the event
 
     public ServerPlayer(MinecraftServer server, ServerLevel world, GameProfile profile) {
diff --git a/src/main/java/net/minecraft/server/players/PlayerList.java b/src/main/java/net/minecraft/server/players/PlayerList.java
index 9b6770a41d272eea4b0a1d2076c936af3eaf5c2c..99aa8f2ba2f10578f37de621d1a5a8e222cd70b1 100644
--- a/src/main/java/net/minecraft/server/players/PlayerList.java
+++ b/src/main/java/net/minecraft/server/players/PlayerList.java
@@ -267,7 +267,7 @@ 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.getChunkSource().chunkMap.getLoadViewDistance(), flag1, !flag, worldserver1.isDebug(), worldserver1.isFlat())); // Paper - no-tick 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.getChunkSource().chunkMap.playerChunkManager.getLoadDistance(), flag1, !flag, worldserver1.isDebug(), worldserver1.isFlat())); // Paper - no-tick view distance // Paper - replace old player chunk management
         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()));
@@ -941,7 +941,7 @@ 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.getChunkSource().chunkMap.getLoadViewDistance())); // Spigot // Paper - no-tick view distance
+        entityplayer1.connection.send(new ClientboundSetChunkCacheRadiusPacket(worldserver1.getChunkSource().chunkMap.playerChunkManager.getLoadDistance())); // Spigot // Paper - no-tick view distance// Paper - replace old player chunk management
         entityplayer1.setLevel(worldserver1);
         entityplayer1.unsetRemoved();
         entityplayer1.connection.teleport(new Location(worldserver1.getWorld(), entityplayer1.getX(), entityplayer1.getY(), entityplayer1.getZ(), entityplayer1.getYRot(), entityplayer1.getXRot()));
@@ -1216,7 +1216,7 @@ public abstract class PlayerList {
             // Really shouldn't happen...
             backingSet = world != null ? world.players.toArray() : players.toArray();
         } else {
-            com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> nearbyPlayers = chunkMap.playerViewDistanceBroadcastMap.getObjectsInRange(MCUtil.fastFloor(x) >> 4, MCUtil.fastFloor(z) >> 4);
+            com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> nearbyPlayers = chunkMap.playerChunkManager.broadcastMap.getObjectsInRange(MCUtil.fastFloor(x) >> 4, MCUtil.fastFloor(z) >> 4); // Paper - replace old player chunk management
             if (nearbyPlayers == null) {
                 return;
             }
diff --git a/src/main/java/net/minecraft/world/item/EnderEyeItem.java b/src/main/java/net/minecraft/world/item/EnderEyeItem.java
index 7ccfe737fdf7f07b731ea0ff82e897564350705c..fe709bee0e657ff9bfc6deb6d4bd8ce4eccfcf06 100644
--- a/src/main/java/net/minecraft/world/item/EnderEyeItem.java
+++ b/src/main/java/net/minecraft/world/item/EnderEyeItem.java
@@ -60,9 +60,10 @@ public class EnderEyeItem extends Item {
 
                     // CraftBukkit start - Use relative location for far away sounds
                     // world.b(1038, blockposition1.c(1, 0, 1), 0);
-                    int viewDistance = world.getCraftServer().getViewDistance() * 16;
+                    //int viewDistance = world.getCraftServer().getViewDistance() * 16; // Paper - apply view distance patch
                     BlockPos soundPos = blockposition1.offset(1, 0, 1);
                     for (ServerPlayer player : world.getServer().getPlayerList().players) {
+                        final int viewDistance = player.getBukkitEntity().getViewDistance(); // Paper - apply view distance patch
                         double deltaX = soundPos.getX() - player.getX();
                         double deltaZ = soundPos.getZ() - player.getZ();
                         double distanceSquared = deltaX * deltaX + deltaZ * deltaZ;
diff --git a/src/main/java/net/minecraft/world/level/Level.java b/src/main/java/net/minecraft/world/level/Level.java
index 3a6f79233cec7aee87be20787b6deae4b313f0ac..41be326b8ea5b7419dc09578e48c7c7f378e22cc 100644
--- a/src/main/java/net/minecraft/world/level/Level.java
+++ b/src/main/java/net/minecraft/world/level/Level.java
@@ -588,7 +588,7 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
                 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)) {
+            } else if ((i & 2) != 0 && (!this.isClientSide || (i & 4) == 0) && (this.isClientSide || chunk == null || ((ServerLevel)this).getChunkSource().chunkMap.playerChunkManager.broadcastMap.getObjectsInRange(MCUtil.getCoordinateKey(blockposition)) != null)) { // Paper - replace old player chunk management
                 ((ServerLevel)this).getChunkSource().blockChanged(blockposition);
                 // Paper end - per player view distance
             }
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 f0c43f9f636a5dd1f0dfbae604dfa1f4ff9ebd4e..9e75ee7f43722f05dd5df4ef00f7d3e271f4c6e5 100644
--- a/src/main/java/net/minecraft/world/level/chunk/LevelChunk.java
+++ b/src/main/java/net/minecraft/world/level/chunk/LevelChunk.java
@@ -293,11 +293,12 @@ public class LevelChunk implements ChunkAccess {
         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) {
+            if (chunkMap.playerChunkManager.tickMap.getObjectsInRange(this.coordinateKey) != null) { // Paper - replace old player chunk loading system
                 // 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) {
+                    if (LevelChunk.this.areNeighboursLoaded(2) && chunkMap.playerChunkManager.tickMap.getObjectsInRange(LevelChunk.this.coordinateKey) != null) { // Paper - replace old player chunk loading system
+                        chunkMap.playerChunkManager.onChunkPlayerTickReady(this.chunkPos.x, this.chunkPos.z); // Paper - replace old player chunk
                         chunkProviderServer.addTicketAtLevel(net.minecraft.server.level.TicketType.PLAYER, LevelChunk.this.chunkPos, 31, LevelChunk.this.chunkPos); // 31 -> entity ticking, TODO check on update
                     }
                 });
@@ -306,31 +307,18 @@ public class LevelChunk implements ChunkAccess {
 
         // 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<net.minecraft.server.level.ServerPlayer> 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 start - replace old player chunk loading system
+            chunkProviderServer.mainThreadProcessor.execute(() -> {
+                if (!LevelChunk.this.areNeighboursLoaded(1)) {
+                    return;
+                }
+                LevelChunk.this.postProcessGeneration();
+                if (!LevelChunk.this.areNeighboursLoaded(1)) {
+                    return;
+                }
+                chunkMap.playerChunkManager.onChunkSendReady(this.chunkPos.x, this.chunkPos.z);
+            });
+            // Paper end - replace old player chunk loading system
         }
         // Paper end - no-tick view distance
     }
@@ -871,6 +859,7 @@ public class LevelChunk implements ChunkAccess {
         // Paper end - neighbour cache
         org.bukkit.Server server = this.level.getCraftServer();
         this.level.getChunkSource().addLoadedChunk(this); // Paper
+        ((ServerLevel)this.level).getChunkSource().chunkMap.playerChunkManager.onChunkLoad(this.chunkPos.x, this.chunkPos.z); // Paper - rewrite player chunk management
         if (server != null) {
             /*
              * If it's a new world, the first few chunks are generated inside
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
index b4cf0d44bda13625cfa8264043a49c1a0daf1054..e5e23c907d49ee64218f3302e2a2323d6937a8a1 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
@@ -2067,14 +2067,14 @@ public class CraftWorld extends CraftRegionAccessor implements World {
             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()) {
+        if (true) { // Paper - replace old player chunk management
             chunkMap.setViewDistance(viewDistance);
         }
     }
 
     @Override
     public int getNoTickViewDistance() {
-        return getHandle().getChunkSource().chunkMap.getEffectiveNoTickViewDistance();
+        return getHandle().getChunkSource().chunkMap.playerChunkManager.getTargetNoTickViewDistance(); // Paper - replace old player chunk management
     }
 
     @Override
@@ -2083,11 +2083,22 @@ public class CraftWorld extends CraftRegionAccessor implements World {
             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()) {
+        if (true) { // Paper - replace old player chunk management
             chunkMap.setNoTickViewDistance(viewDistance);
         }
     }
     // Paper end - per player view distance
+    // Paper start - add view distances
+    @Override
+    public int getSendViewDistance() {
+        return getHandle().getChunkSource().chunkMap.playerChunkManager.getTargetSendDistance();
+    }
+
+    @Override
+    public void setSendViewDistance(int viewDistance) {
+        getHandle().getChunkSource().chunkMap.playerChunkManager.setTargetSendDistance(viewDistance);
+    }
+    // Paper end - add view distances
 
     // Spigot start
     private final org.bukkit.World.Spigot spigot = new org.bukkit.World.Spigot()
diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
index b3ffda6f177e4a45f25772483e935a36b3f5f72a..4ff4143f3a7cd89ef92f4b8882fa3e5addfe0f06 100644
--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
+++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
@@ -517,15 +517,70 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
         }
     }
 
+    // Paper start - implement view distances
+    @Override
+    public int getSendViewDistance() {
+        net.minecraft.server.level.ChunkMap chunkMap = this.getHandle().getLevel().getChunkSource().chunkMap;
+        io.papermc.paper.chunk.PlayerChunkLoader.PlayerLoaderData data = chunkMap.playerChunkManager.getData(this.getHandle());
+        if (data == null) {
+            return chunkMap.playerChunkManager.getTargetSendDistance();
+        }
+        return data.getTargetSendViewDistance();
+    }
+
+    @Override
+    public void setSendViewDistance(int viewDistance) {
+        net.minecraft.server.level.ChunkMap chunkMap = this.getHandle().getLevel().getChunkSource().chunkMap;
+        io.papermc.paper.chunk.PlayerChunkLoader.PlayerLoaderData data = chunkMap.playerChunkManager.getData(this.getHandle());
+        if (data == null) {
+            throw new IllegalStateException("Player is not attached to world");
+        }
+
+        data.setTargetSendViewDistance(viewDistance);
+    }
+
+    @Override
+    public int getNoTickViewDistance() {
+        net.minecraft.server.level.ChunkMap chunkMap = this.getHandle().getLevel().getChunkSource().chunkMap;
+        io.papermc.paper.chunk.PlayerChunkLoader.PlayerLoaderData data = chunkMap.playerChunkManager.getData(this.getHandle());
+        if (data == null) {
+            return chunkMap.playerChunkManager.getTargetNoTickViewDistance();
+        }
+        return data.getTargetNoTickViewDistance();
+    }
+
+    @Override
+    public void setNoTickViewDistance(int viewDistance) {
+        net.minecraft.server.level.ChunkMap chunkMap = this.getHandle().getLevel().getChunkSource().chunkMap;
+        io.papermc.paper.chunk.PlayerChunkLoader.PlayerLoaderData data = chunkMap.playerChunkManager.getData(this.getHandle());
+        if (data == null) {
+            throw new IllegalStateException("Player is not attached to world");
+        }
+
+        data.setTargetNoTickViewDistance(viewDistance);
+    }
+
     @Override
     public int getViewDistance() {
-        throw new NotImplementedException("Per-Player View Distance APIs need further understanding to properly implement (There are per world view distances though!)"); // TODO
+        net.minecraft.server.level.ChunkMap chunkMap = this.getHandle().getLevel().getChunkSource().chunkMap;
+        io.papermc.paper.chunk.PlayerChunkLoader.PlayerLoaderData data = chunkMap.playerChunkManager.getData(this.getHandle());
+        if (data == null) {
+            return chunkMap.playerChunkManager.getTargetViewDistance();
+        }
+        return data.getTargetTickViewDistance();
     }
 
     @Override
     public void setViewDistance(int viewDistance) {
-        throw new NotImplementedException("Per-Player View Distance APIs need further understanding to properly implement (There are per world view distances though!)"); // TODO
+        net.minecraft.server.level.ChunkMap chunkMap = this.getHandle().getLevel().getChunkSource().chunkMap;
+        io.papermc.paper.chunk.PlayerChunkLoader.PlayerLoaderData data = chunkMap.playerChunkManager.getData(this.getHandle());
+        if (data == null) {
+            throw new IllegalStateException("Player is not attached to world");
+        }
+
+        data.setTargetTickViewDistance(viewDistance);
     }
+    // Paper end - implement view distances
 
     @Override
     public <T> T getClientOption(com.destroystokyo.paper.ClientOption<T> type) {