-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathWorld.php
3554 lines (3075 loc) · 117 KB
/
World.php
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
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
/**
* All World related classes are here, like Generators, Populators, Noise, ...
*/
namespace pocketmine\world;
use pocketmine\block\Air;
use pocketmine\block\Block;
use pocketmine\block\BlockTypeIds;
use pocketmine\block\RuntimeBlockStateRegistry;
use pocketmine\block\tile\Spawnable;
use pocketmine\block\tile\Tile;
use pocketmine\block\tile\TileFactory;
use pocketmine\block\UnknownBlock;
use pocketmine\block\VanillaBlocks;
use pocketmine\data\bedrock\BiomeIds;
use pocketmine\data\bedrock\block\BlockStateData;
use pocketmine\data\bedrock\block\BlockStateDeserializeException;
use pocketmine\data\SavedDataLoadingException;
use pocketmine\entity\Entity;
use pocketmine\entity\EntityFactory;
use pocketmine\entity\Location;
use pocketmine\entity\object\ExperienceOrb;
use pocketmine\entity\object\ItemEntity;
use pocketmine\event\block\BlockBreakEvent;
use pocketmine\event\block\BlockPlaceEvent;
use pocketmine\event\block\BlockUpdateEvent;
use pocketmine\event\player\PlayerInteractEvent;
use pocketmine\event\world\ChunkLoadEvent;
use pocketmine\event\world\ChunkPopulateEvent;
use pocketmine\event\world\ChunkUnloadEvent;
use pocketmine\event\world\SpawnChangeEvent;
use pocketmine\event\world\WorldDifficultyChangeEvent;
use pocketmine\event\world\WorldDisplayNameChangeEvent;
use pocketmine\event\world\WorldParticleEvent;
use pocketmine\event\world\WorldSaveEvent;
use pocketmine\event\world\WorldSoundEvent;
use pocketmine\item\Item;
use pocketmine\item\ItemUseResult;
use pocketmine\item\LegacyStringToItemParser;
use pocketmine\item\StringToItemParser;
use pocketmine\item\VanillaItems;
use pocketmine\lang\KnownTranslationFactory;
use pocketmine\math\AxisAlignedBB;
use pocketmine\math\Facing;
use pocketmine\math\Vector3;
use pocketmine\nbt\tag\IntTag;
use pocketmine\nbt\tag\StringTag;
use pocketmine\network\mcpe\convert\TypeConverter;
use pocketmine\network\mcpe\NetworkBroadcastUtils;
use pocketmine\network\mcpe\protocol\BlockActorDataPacket;
use pocketmine\network\mcpe\protocol\ClientboundPacket;
use pocketmine\network\mcpe\protocol\types\BlockPosition;
use pocketmine\network\mcpe\protocol\UpdateBlockPacket;
use pocketmine\player\Player;
use pocketmine\promise\Promise;
use pocketmine\promise\PromiseResolver;
use pocketmine\scheduler\AsyncPool;
use pocketmine\Server;
use pocketmine\ServerConfigGroup;
use pocketmine\utils\AssumptionFailedError;
use pocketmine\utils\Limits;
use pocketmine\utils\ReversePriorityQueue;
use pocketmine\utils\Utils;
use pocketmine\world\biome\Biome;
use pocketmine\world\biome\BiomeRegistry;
use pocketmine\world\format\Chunk;
use pocketmine\world\format\io\ChunkData;
use pocketmine\world\format\io\exception\CorruptedChunkException;
use pocketmine\world\format\io\GlobalBlockStateHandlers;
use pocketmine\world\format\io\WritableWorldProvider;
use pocketmine\world\format\LightArray;
use pocketmine\world\format\SubChunk;
use pocketmine\world\generator\GeneratorManager;
use pocketmine\world\generator\GeneratorRegisterTask;
use pocketmine\world\generator\GeneratorUnregisterTask;
use pocketmine\world\generator\PopulationTask;
use pocketmine\world\light\BlockLightUpdate;
use pocketmine\world\light\LightPopulationTask;
use pocketmine\world\light\SkyLightUpdate;
use pocketmine\world\particle\BlockBreakParticle;
use pocketmine\world\particle\Particle;
use pocketmine\world\sound\BlockPlaceSound;
use pocketmine\world\sound\Sound;
use pocketmine\world\utils\SubChunkExplorer;
use pocketmine\YmlServerProperties;
use function abs;
use function array_filter;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function array_sum;
use function array_values;
use function assert;
use function cos;
use function count;
use function floor;
use function get_class;
use function gettype;
use function is_a;
use function is_object;
use function max;
use function microtime;
use function min;
use function morton2d_decode;
use function morton2d_encode;
use function morton3d_decode;
use function morton3d_encode;
use function mt_rand;
use function preg_match;
use function spl_object_id;
use function strtolower;
use function trim;
use const M_PI;
use const PHP_INT_MAX;
use const PHP_INT_MIN;
#include <rules/World.h>
/**
* @phpstan-type ChunkPosHash int
* @phpstan-type BlockPosHash int
* @phpstan-type ChunkBlockPosHash int
*/
class World implements ChunkManager{
private static int $worldIdCounter = 1;
public const Y_MAX = 320;
public const Y_MIN = -64;
public const TIME_DAY = 1000;
public const TIME_NOON = 6000;
public const TIME_SUNSET = 12000;
public const TIME_NIGHT = 13000;
public const TIME_MIDNIGHT = 18000;
public const TIME_SUNRISE = 23000;
public const TIME_FULL = 24000;
public const DIFFICULTY_PEACEFUL = 0;
public const DIFFICULTY_EASY = 1;
public const DIFFICULTY_NORMAL = 2;
public const DIFFICULTY_HARD = 3;
public const DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK = 3;
//TODO: this could probably do with being a lot bigger
private const BLOCK_CACHE_SIZE_CAP = 2048;
/**
* @var Player[] entity runtime ID => Player
* @phpstan-var array<int, Player>
*/
private array $players = [];
/**
* @var Entity[] entity runtime ID => Entity
* @phpstan-var array<int, Entity>
*/
private array $entities = [];
/**
* @var Vector3[] entity runtime ID => Vector3
* @phpstan-var array<int, Vector3>
*/
private array $entityLastKnownPositions = [];
/**
* @var Entity[][] chunkHash => [entity runtime ID => Entity]
* @phpstan-var array<ChunkPosHash, array<int, Entity>>
*/
private array $entitiesByChunk = [];
/**
* @var Entity[] entity runtime ID => Entity
* @phpstan-var array<int, Entity>
*/
public array $updateEntities = [];
private bool $inDynamicStateRecalculation = false;
/**
* @var Block[][] chunkHash => [relativeBlockHash => Block]
* @phpstan-var array<ChunkPosHash, array<ChunkBlockPosHash, Block>>
*/
private array $blockCache = [];
private int $blockCacheSize = 0;
/**
* @var AxisAlignedBB[][][] chunkHash => [relativeBlockHash => AxisAlignedBB[]]
* @phpstan-var array<ChunkPosHash, array<ChunkBlockPosHash, list<AxisAlignedBB>>>
*/
private array $blockCollisionBoxCache = [];
private int $sendTimeTicker = 0;
private int $worldId;
private int $providerGarbageCollectionTicker = 0;
private int $minY;
private int $maxY;
/**
* @var ChunkTicker[][] chunkHash => [spl_object_id => ChunkTicker]
* @phpstan-var array<ChunkPosHash, array<int, ChunkTicker>>
*/
private array $registeredTickingChunks = [];
/**
* Set of chunks which are definitely ready for ticking.
*
* @var int[]
* @phpstan-var array<ChunkPosHash, ChunkPosHash>
*/
private array $validTickingChunks = [];
/**
* Set of chunks which might be ready for ticking. These will be checked at the next tick.
* @var int[]
* @phpstan-var array<ChunkPosHash, ChunkPosHash>
*/
private array $recheckTickingChunks = [];
/**
* @var ChunkLoader[][] chunkHash => [spl_object_id => ChunkLoader]
* @phpstan-var array<ChunkPosHash, array<int, ChunkLoader>>
*/
private array $chunkLoaders = [];
/**
* @var ChunkListener[][] chunkHash => [spl_object_id => ChunkListener]
* @phpstan-var array<ChunkPosHash, array<int, ChunkListener>>
*/
private array $chunkListeners = [];
/**
* @var Player[][] chunkHash => [spl_object_id => Player]
* @phpstan-var array<ChunkPosHash, array<int, Player>>
*/
private array $playerChunkListeners = [];
/**
* @var ClientboundPacket[][]
* @phpstan-var array<ChunkPosHash, list<ClientboundPacket>>
*/
private array $packetBuffersByChunk = [];
/**
* @var float[] chunkHash => timestamp of request
* @phpstan-var array<ChunkPosHash, float>
*/
private array $unloadQueue = [];
private int $time;
public bool $stopTime = false;
private float $sunAnglePercentage = 0.0;
private int $skyLightReduction = 0;
private string $folderName;
private string $displayName;
/**
* @var Chunk[]
* @phpstan-var array<ChunkPosHash, Chunk>
*/
private array $chunks = [];
/**
* @var Vector3[][] chunkHash => [relativeBlockHash => Vector3]
* @phpstan-var array<ChunkPosHash, array<ChunkBlockPosHash, Vector3>>
*/
private array $changedBlocks = [];
/** @phpstan-var ReversePriorityQueue<int, Vector3> */
private ReversePriorityQueue $scheduledBlockUpdateQueue;
/**
* @var int[] blockHash => tick delay
* @phpstan-var array<BlockPosHash, int>
*/
private array $scheduledBlockUpdateQueueIndex = [];
/** @phpstan-var \SplQueue<int> */
private \SplQueue $neighbourBlockUpdateQueue;
/**
* @var true[] blockhash => dummy
* @phpstan-var array<BlockPosHash, true>
*/
private array $neighbourBlockUpdateQueueIndex = [];
/**
* @var bool[] chunkHash => isValid
* @phpstan-var array<ChunkPosHash, bool>
*/
private array $activeChunkPopulationTasks = [];
/**
* @var ChunkLockId[]
* @phpstan-var array<ChunkPosHash, ChunkLockId>
*/
private array $chunkLock = [];
private int $maxConcurrentChunkPopulationTasks = 2;
/**
* @var PromiseResolver[] chunkHash => promise
* @phpstan-var array<ChunkPosHash, PromiseResolver<Chunk>>
*/
private array $chunkPopulationRequestMap = [];
/**
* @var \SplQueue (queue of chunkHashes)
* @phpstan-var \SplQueue<ChunkPosHash>
*/
private \SplQueue $chunkPopulationRequestQueue;
/**
* @var true[] chunkHash => dummy
* @phpstan-var array<ChunkPosHash, true>
*/
private array $chunkPopulationRequestQueueIndex = [];
/**
* @var true[]
* @phpstan-var array<int, true>
*/
private array $generatorRegisteredWorkers = [];
private bool $autoSave = true;
private int $sleepTicks = 0;
private int $chunkTickRadius;
private int $tickedBlocksPerSubchunkPerTick = self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK;
/**
* @var true[]
* @phpstan-var array<int, true>
*/
private array $randomTickBlocks = [];
public WorldTimings $timings;
public float $tickRateTime = 0;
private bool $doingTick = false;
/** @phpstan-var class-string<\pocketmine\world\generator\Generator> */
private string $generator;
private bool $unloaded = false;
/**
* @var \Closure[]
* @phpstan-var array<int, \Closure() : void>
*/
private array $unloadCallbacks = [];
private ?BlockLightUpdate $blockLightUpdate = null;
private ?SkyLightUpdate $skyLightUpdate = null;
private \Logger $logger;
/**
* @phpstan-return ChunkPosHash
*/
public static function chunkHash(int $x, int $z) : int{
return morton2d_encode($x, $z);
}
private const MORTON3D_BIT_SIZE = 21;
private const BLOCKHASH_Y_BITS = 9;
private const BLOCKHASH_Y_PADDING = 64; //size (in blocks) of padding after both boundaries of the Y axis
private const BLOCKHASH_Y_OFFSET = self::BLOCKHASH_Y_PADDING - self::Y_MIN;
private const BLOCKHASH_Y_MASK = (1 << self::BLOCKHASH_Y_BITS) - 1;
private const BLOCKHASH_XZ_MASK = (1 << self::MORTON3D_BIT_SIZE) - 1;
private const BLOCKHASH_XZ_EXTRA_BITS = (self::MORTON3D_BIT_SIZE - self::BLOCKHASH_Y_BITS) >> 1;
private const BLOCKHASH_XZ_EXTRA_MASK = (1 << self::BLOCKHASH_XZ_EXTRA_BITS) - 1;
private const BLOCKHASH_XZ_SIGN_SHIFT = 64 - self::MORTON3D_BIT_SIZE - self::BLOCKHASH_XZ_EXTRA_BITS;
private const BLOCKHASH_X_SHIFT = self::BLOCKHASH_Y_BITS;
private const BLOCKHASH_Z_SHIFT = self::BLOCKHASH_X_SHIFT + self::BLOCKHASH_XZ_EXTRA_BITS;
/**
* @phpstan-return BlockPosHash
*/
public static function blockHash(int $x, int $y, int $z) : int{
$shiftedY = $y + self::BLOCKHASH_Y_OFFSET;
if(($shiftedY & (~0 << self::BLOCKHASH_Y_BITS)) !== 0){
throw new \InvalidArgumentException("Y coordinate $y is out of range!");
}
//morton3d gives us 21 bits on each axis, but the Y axis only requires 9
//so we use the extra space on Y (12 bits) and add 6 extra bits from X and Z instead.
//if we ever need more space for Y (e.g. due to expansion), take bits from X/Z to compensate.
return morton3d_encode(
$x & self::BLOCKHASH_XZ_MASK,
($shiftedY /* & self::BLOCKHASH_Y_MASK */) |
((($x >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_X_SHIFT) |
((($z >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_Z_SHIFT),
$z & self::BLOCKHASH_XZ_MASK
);
}
/**
* Computes a small index relative to chunk base from the given coordinates.
*/
public static function chunkBlockHash(int $x, int $y, int $z) : int{
return morton3d_encode($x, $y, $z);
}
/**
* @phpstan-param BlockPosHash $hash
* @phpstan-param-out int $x
* @phpstan-param-out int $y
* @phpstan-param-out int $z
*/
public static function getBlockXYZ(int $hash, ?int &$x, ?int &$y, ?int &$z) : void{
[$baseX, $baseY, $baseZ] = morton3d_decode($hash);
$extraX = ((($baseY >> self::BLOCKHASH_X_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
$extraZ = ((($baseY >> self::BLOCKHASH_Z_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
$x = (($baseX & self::BLOCKHASH_XZ_MASK) | $extraX) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
$y = ($baseY & self::BLOCKHASH_Y_MASK) - self::BLOCKHASH_Y_OFFSET;
$z = (($baseZ & self::BLOCKHASH_XZ_MASK) | $extraZ) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
}
/**
* @phpstan-param ChunkPosHash $hash
* @phpstan-param-out int $x
* @phpstan-param-out int $z
*/
public static function getXZ(int $hash, ?int &$x, ?int &$z) : void{
[$x, $z] = morton2d_decode($hash);
}
public static function getDifficultyFromString(string $str) : int{
switch(strtolower(trim($str))){
case "0":
case "peaceful":
case "p":
return World::DIFFICULTY_PEACEFUL;
case "1":
case "easy":
case "e":
return World::DIFFICULTY_EASY;
case "2":
case "normal":
case "n":
return World::DIFFICULTY_NORMAL;
case "3":
case "hard":
case "h":
return World::DIFFICULTY_HARD;
}
return -1;
}
/**
* Init the default world data
*/
public function __construct(
private Server $server,
string $name, //TODO: this should be folderName (named arguments BC break)
private WritableWorldProvider $provider,
private AsyncPool $workerPool
){
$this->folderName = $name;
$this->worldId = self::$worldIdCounter++;
$this->displayName = $this->provider->getWorldData()->getName();
$this->logger = new \PrefixedLogger($server->getLogger(), "World: $this->displayName");
$this->minY = $this->provider->getWorldMinY();
$this->maxY = $this->provider->getWorldMaxY();
$this->server->getLogger()->info($this->server->getLanguage()->translate(KnownTranslationFactory::pocketmine_level_preparing($this->displayName)));
$generator = GeneratorManager::getInstance()->getGenerator($this->provider->getWorldData()->getGenerator()) ??
throw new AssumptionFailedError("WorldManager should already have checked that the generator exists");
$generator->validateGeneratorOptions($this->provider->getWorldData()->getGeneratorOptions());
$this->generator = $generator->getGeneratorClass();
$this->chunkPopulationRequestQueue = new \SplQueue();
$this->addOnUnloadCallback(function() : void{
$this->logger->debug("Cancelling unfulfilled generation requests");
foreach($this->chunkPopulationRequestMap as $chunkHash => $promise){
$promise->reject();
unset($this->chunkPopulationRequestMap[$chunkHash]);
}
if(count($this->chunkPopulationRequestMap) !== 0){
//TODO: this might actually get hit because generation rejection callbacks might try to schedule new
//requests, and we can't prevent that right now because there's no way to detect "unloading" state
throw new AssumptionFailedError("New generation requests scheduled during unload");
}
});
$this->scheduledBlockUpdateQueue = new ReversePriorityQueue();
$this->scheduledBlockUpdateQueue->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
$this->neighbourBlockUpdateQueue = new \SplQueue();
$this->time = $this->provider->getWorldData()->getTime();
$cfg = $this->server->getConfigGroup();
$this->chunkTickRadius = min($this->server->getViewDistance(), max(0, $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_TICK_RADIUS, 4)));
if($cfg->getPropertyInt("chunk-ticking.per-tick", 40) <= 0){
//TODO: this needs l10n
$this->logger->warning("\"chunk-ticking.per-tick\" setting is deprecated, but you've used it to disable chunk ticking. Set \"chunk-ticking.tick-radius\" to 0 in \"pocketmine.yml\" instead.");
$this->chunkTickRadius = 0;
}
$this->tickedBlocksPerSubchunkPerTick = $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_BLOCKS_PER_SUBCHUNK_PER_TICK, self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK);
$this->maxConcurrentChunkPopulationTasks = $cfg->getPropertyInt(YmlServerProperties::CHUNK_GENERATION_POPULATION_QUEUE_SIZE, 2);
$this->initRandomTickBlocksFromConfig($cfg);
$this->timings = new WorldTimings($this);
$this->workerPool->addWorkerStartHook($workerStartHook = function(int $workerId) : void{
if(array_key_exists($workerId, $this->generatorRegisteredWorkers)){
$this->logger->debug("Worker $workerId with previously registered generator restarted, flagging as unregistered");
unset($this->generatorRegisteredWorkers[$workerId]);
}
});
$workerPool = $this->workerPool;
$this->addOnUnloadCallback(static function() use ($workerPool, $workerStartHook) : void{
$workerPool->removeWorkerStartHook($workerStartHook);
});
}
private function initRandomTickBlocksFromConfig(ServerConfigGroup $cfg) : void{
$dontTickBlocks = [];
$parser = StringToItemParser::getInstance();
foreach($cfg->getProperty(YmlServerProperties::CHUNK_TICKING_DISABLE_BLOCK_TICKING, []) as $name){
$name = (string) $name;
$item = $parser->parse($name);
if($item !== null){
$block = $item->getBlock();
}elseif(preg_match("/^-?\d+$/", $name) === 1){
//TODO: this is a really sketchy hack - remove this as soon as possible
try{
$blockStateData = GlobalBlockStateHandlers::getUpgrader()->upgradeIntIdMeta((int) $name, 0);
}catch(BlockStateDeserializeException){
continue;
}
$block = RuntimeBlockStateRegistry::getInstance()->fromStateId(GlobalBlockStateHandlers::getDeserializer()->deserialize($blockStateData));
}else{
//TODO: we probably ought to log an error here
continue;
}
if($block->getTypeId() !== BlockTypeIds::AIR){
$dontTickBlocks[$block->getTypeId()] = $name;
}
}
foreach(RuntimeBlockStateRegistry::getInstance()->getAllKnownStates() as $state){
$dontTickName = $dontTickBlocks[$state->getTypeId()] ?? null;
if($dontTickName === null && $state->ticksRandomly()){
$this->randomTickBlocks[$state->getStateId()] = true;
}
}
}
public function getTickRateTime() : float{
return $this->tickRateTime;
}
public function registerGeneratorToWorker(int $worker) : void{
$this->logger->debug("Registering generator on worker $worker");
$this->workerPool->submitTaskToWorker(new GeneratorRegisterTask($this, $this->generator, $this->provider->getWorldData()->getGeneratorOptions()), $worker);
$this->generatorRegisteredWorkers[$worker] = true;
}
public function unregisterGenerator() : void{
foreach($this->workerPool->getRunningWorkers() as $i){
if(isset($this->generatorRegisteredWorkers[$i])){
$this->workerPool->submitTaskToWorker(new GeneratorUnregisterTask($this), $i);
}
}
$this->generatorRegisteredWorkers = [];
}
public function getServer() : Server{
return $this->server;
}
public function getLogger() : \Logger{
return $this->logger;
}
final public function getProvider() : WritableWorldProvider{
return $this->provider;
}
/**
* Returns the unique world identifier
*/
final public function getId() : int{
return $this->worldId;
}
public function isLoaded() : bool{
return !$this->unloaded;
}
/**
* @internal
*/
public function onUnload() : void{
if($this->unloaded){
throw new \LogicException("Tried to close a world which is already closed");
}
foreach($this->unloadCallbacks as $callback){
$callback();
}
$this->unloadCallbacks = [];
foreach($this->chunks as $chunkHash => $chunk){
self::getXZ($chunkHash, $chunkX, $chunkZ);
$this->unloadChunk($chunkX, $chunkZ, false);
}
foreach($this->entitiesByChunk as $chunkHash => $entities){
self::getXZ($chunkHash, $chunkX, $chunkZ);
$leakedEntities = 0;
foreach($entities as $entity){
if(!$entity->isFlaggedForDespawn()){
$leakedEntities++;
}
$entity->close();
}
if($leakedEntities !== 0){
$this->logger->warning("$leakedEntities leaked entities found in ungenerated chunk $chunkX $chunkZ during unload, they won't be saved!");
}
}
$this->save();
$this->unregisterGenerator();
$this->provider->close();
$this->blockCache = [];
$this->blockCacheSize = 0;
$this->blockCollisionBoxCache = [];
$this->unloaded = true;
}
/** @phpstan-param \Closure() : void $callback */
public function addOnUnloadCallback(\Closure $callback) : void{
$this->unloadCallbacks[spl_object_id($callback)] = $callback;
}
/** @phpstan-param \Closure() : void $callback */
public function removeOnUnloadCallback(\Closure $callback) : void{
unset($this->unloadCallbacks[spl_object_id($callback)]);
}
/**
* Returns a list of players who are in the given filter and also using the chunk containing the target position.
* Used for broadcasting sounds and particles with specific targets.
*
* @param Player[] $allowed
*
* @return array<int, Player>
*/
private function filterViewersForPosition(Vector3 $pos, array $allowed) : array{
$candidates = $this->getViewersForPosition($pos);
$filtered = [];
foreach($allowed as $player){
$k = spl_object_id($player);
if(isset($candidates[$k])){
$filtered[$k] = $candidates[$k];
}
}
return $filtered;
}
/**
* @param Player[]|null $players
*/
public function addSound(Vector3 $pos, Sound $sound, ?array $players = null) : void{
$players ??= $this->getViewersForPosition($pos);
if(WorldSoundEvent::hasHandlers()){
$ev = new WorldSoundEvent($this, $sound, $pos, $players);
$ev->call();
if($ev->isCancelled()){
return;
}
$sound = $ev->getSound();
$players = $ev->getRecipients();
}
$pk = $sound->encode($pos);
if(count($pk) > 0){
if($players === $this->getViewersForPosition($pos)){
foreach($pk as $e){
$this->broadcastPacketToViewers($pos, $e);
}
}else{
NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
}
}
}
/**
* @param Player[]|null $players
*/
public function addParticle(Vector3 $pos, Particle $particle, ?array $players = null) : void{
$players ??= $this->getViewersForPosition($pos);
if(WorldParticleEvent::hasHandlers()){
$ev = new WorldParticleEvent($this, $particle, $pos, $players);
$ev->call();
if($ev->isCancelled()){
return;
}
$particle = $ev->getParticle();
$players = $ev->getRecipients();
}
$pk = $particle->encode($pos);
if(count($pk) > 0){
if($players === $this->getViewersForPosition($pos)){
foreach($pk as $e){
$this->broadcastPacketToViewers($pos, $e);
}
}else{
NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
}
}
}
public function getAutoSave() : bool{
return $this->autoSave;
}
public function setAutoSave(bool $value) : void{
$this->autoSave = $value;
}
/**
* @deprecated WARNING: This function has a misleading name. Contrary to what the name might imply, this function
* DOES NOT return players who are IN a chunk, rather, it returns players who can SEE the chunk.
*
* Returns a list of players who have the target chunk within their view distance.
*
* @return Player[] spl_object_id => Player
* @phpstan-return array<int, Player>
*/
public function getChunkPlayers(int $chunkX, int $chunkZ) : array{
return $this->playerChunkListeners[World::chunkHash($chunkX, $chunkZ)] ?? [];
}
/**
* Gets the chunk loaders being used in a specific chunk
*
* @return ChunkLoader[]
* @phpstan-return array<int, ChunkLoader>
*/
public function getChunkLoaders(int $chunkX, int $chunkZ) : array{
return $this->chunkLoaders[World::chunkHash($chunkX, $chunkZ)] ?? [];
}
/**
* Returns an array of players who have the target position within their view distance.
*
* @return Player[] spl_object_id => Player
* @phpstan-return array<int, Player>
*/
public function getViewersForPosition(Vector3 $pos) : array{
return $this->getChunkPlayers($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
}
/**
* Broadcasts a packet to every player who has the target position within their view distance.
*/
public function broadcastPacketToViewers(Vector3 $pos, ClientboundPacket $packet) : void{
$this->broadcastPacketToPlayersUsingChunk($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE, $packet);
}
private function broadcastPacketToPlayersUsingChunk(int $chunkX, int $chunkZ, ClientboundPacket $packet) : void{
if(!isset($this->packetBuffersByChunk[$index = World::chunkHash($chunkX, $chunkZ)])){
$this->packetBuffersByChunk[$index] = [$packet];
}else{
$this->packetBuffersByChunk[$index][] = $packet;
}
}
public function registerChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ, bool $autoLoad = true) : void{
$loaderId = spl_object_id($loader);
if(!isset($this->chunkLoaders[$chunkHash = World::chunkHash($chunkX, $chunkZ)])){
$this->chunkLoaders[$chunkHash] = [];
}elseif(isset($this->chunkLoaders[$chunkHash][$loaderId])){
return;
}
$this->chunkLoaders[$chunkHash][$loaderId] = $loader;
$this->cancelUnloadChunkRequest($chunkX, $chunkZ);
if($autoLoad){
$this->loadChunk($chunkX, $chunkZ);
}
}
public function unregisterChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ) : void{
$chunkHash = World::chunkHash($chunkX, $chunkZ);
$loaderId = spl_object_id($loader);
if(isset($this->chunkLoaders[$chunkHash][$loaderId])){
if(count($this->chunkLoaders[$chunkHash]) === 1){
unset($this->chunkLoaders[$chunkHash]);
$this->unloadChunkRequest($chunkX, $chunkZ, true);
if(isset($this->chunkPopulationRequestMap[$chunkHash]) && !isset($this->activeChunkPopulationTasks[$chunkHash])){
$this->chunkPopulationRequestMap[$chunkHash]->reject();
unset($this->chunkPopulationRequestMap[$chunkHash]);
}
}else{
unset($this->chunkLoaders[$chunkHash][$loaderId]);
}
}
}
/**
* Registers a listener to receive events on a chunk.
*/
public function registerChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ) : void{
$hash = World::chunkHash($chunkX, $chunkZ);
if(isset($this->chunkListeners[$hash])){
$this->chunkListeners[$hash][spl_object_id($listener)] = $listener;
}else{
$this->chunkListeners[$hash] = [spl_object_id($listener) => $listener];
}
if($listener instanceof Player){
$this->playerChunkListeners[$hash][spl_object_id($listener)] = $listener;
}
}
/**
* Unregisters a chunk listener previously registered.
*
* @see World::registerChunkListener()
*/
public function unregisterChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ) : void{
$hash = World::chunkHash($chunkX, $chunkZ);
if(isset($this->chunkListeners[$hash])){
if(count($this->chunkListeners[$hash]) === 1){
unset($this->chunkListeners[$hash]);
unset($this->playerChunkListeners[$hash]);
}else{
unset($this->chunkListeners[$hash][spl_object_id($listener)]);
unset($this->playerChunkListeners[$hash][spl_object_id($listener)]);
}
}
}
/**
* Unregisters a chunk listener from all chunks it is listening on in this World.
*/
public function unregisterChunkListenerFromAll(ChunkListener $listener) : void{
foreach($this->chunkListeners as $hash => $listeners){
World::getXZ($hash, $chunkX, $chunkZ);
$this->unregisterChunkListener($listener, $chunkX, $chunkZ);
}
}
/**
* Returns all the listeners attached to this chunk.
*
* @return ChunkListener[]
* @phpstan-return array<int, ChunkListener>
*/
public function getChunkListeners(int $chunkX, int $chunkZ) : array{
return $this->chunkListeners[World::chunkHash($chunkX, $chunkZ)] ?? [];
}
/**
* @internal
*/
public function sendTime(Player ...$targets) : void{
if(count($targets) === 0){
$targets = $this->players;
}
foreach($targets as $player){
$player->getNetworkSession()->syncWorldTime($this->time);
}
}
public function isDoingTick() : bool{
return $this->doingTick;
}
/**
* @internal
*/
public function doTick(int $currentTick) : void{
if($this->unloaded){
throw new \LogicException("Attempted to tick a world which has been closed");
}
$this->timings->doTick->startTiming();
$this->doingTick = true;
try{
$this->actuallyDoTick($currentTick);
}finally{
$this->doingTick = false;
$this->timings->doTick->stopTiming();
}
}
protected function actuallyDoTick(int $currentTick) : void{
if(!$this->stopTime){
//this simulates an overflow, as would happen in any language which doesn't do stupid things to var types
if($this->time === PHP_INT_MAX){
$this->time = PHP_INT_MIN;
}else{
$this->time++;
}
}
$this->sunAnglePercentage = $this->computeSunAnglePercentage(); //Sun angle depends on the current time
$this->skyLightReduction = $this->computeSkyLightReduction(); //Sky light reduction depends on the sun angle
if(++$this->sendTimeTicker === 200){
$this->sendTime();
$this->sendTimeTicker = 0;
}
$this->unloadChunks();
if(++$this->providerGarbageCollectionTicker >= 6000){
$this->provider->doGarbageCollection();
$this->providerGarbageCollectionTicker = 0;
}
$this->timings->scheduledBlockUpdates->startTiming();
//Delayed updates
while($this->scheduledBlockUpdateQueue->count() > 0 && $this->scheduledBlockUpdateQueue->current()["priority"] <= $currentTick){
/** @var Vector3 $vec */
$vec = $this->scheduledBlockUpdateQueue->extract()["data"];
unset($this->scheduledBlockUpdateQueueIndex[World::blockHash($vec->x, $vec->y, $vec->z)]);
if(!$this->isInLoadedTerrain($vec)){
continue;
}
$block = $this->getBlock($vec);
$block->onScheduledUpdate();
}
$this->timings->scheduledBlockUpdates->stopTiming();
$this->timings->neighbourBlockUpdates->startTiming();
//Normal updates
while($this->neighbourBlockUpdateQueue->count() > 0){
$index = $this->neighbourBlockUpdateQueue->dequeue();
unset($this->neighbourBlockUpdateQueueIndex[$index]);
World::getBlockXYZ($index, $x, $y, $z);
if(!$this->isChunkLoaded($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)){
continue;
}
$block = $this->getBlockAt($x, $y, $z);
if(BlockUpdateEvent::hasHandlers()){
$ev = new BlockUpdateEvent($block);
$ev->call();
if($ev->isCancelled()){
continue;
}
}
foreach($this->getNearbyEntities(AxisAlignedBB::one()->offset($x, $y, $z)) as $entity){
$entity->onNearbyBlockChange();
}
$block->onNearbyBlockChange();
}
$this->timings->neighbourBlockUpdates->stopTiming();
$this->timings->entityTick->startTiming();
//Update entities that need update