PocketMine-MP 5.33.2 git-919492bdcad8510eb6606439eb77e1c604f1d1ea
Loading...
Searching...
No Matches
World.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
27namespace pocketmine\world;
28
61use pocketmine\item\ItemUseResult;
94use pocketmine\world\format\LightArray;
111use function abs;
112use function array_filter;
113use function array_key_exists;
114use function array_keys;
115use function array_map;
116use function array_merge;
117use function array_sum;
118use function array_values;
119use function assert;
120use function cos;
121use function count;
122use function floor;
123use function get_class;
124use function gettype;
125use function is_a;
126use function is_object;
127use function max;
128use function microtime;
129use function min;
130use function morton2d_decode;
131use function morton2d_encode;
132use function morton3d_decode;
133use function morton3d_encode;
134use function mt_rand;
135use function preg_match;
136use function spl_object_id;
137use function strtolower;
138use function trim;
139use const M_PI;
140use const PHP_INT_MAX;
141use const PHP_INT_MIN;
142
143#include <rules/World.h>
144
150class World implements ChunkManager{
151
152 private static int $worldIdCounter = 1;
153
154 public const Y_MAX = 320;
155 public const Y_MIN = -64;
156
157 public const TIME_DAY = 1000;
158 public const TIME_NOON = 6000;
159 public const TIME_SUNSET = 12000;
160 public const TIME_NIGHT = 13000;
161 public const TIME_MIDNIGHT = 18000;
162 public const TIME_SUNRISE = 23000;
163
164 public const TIME_FULL = 24000;
165
166 public const DIFFICULTY_PEACEFUL = 0;
167 public const DIFFICULTY_EASY = 1;
168 public const DIFFICULTY_NORMAL = 2;
169 public const DIFFICULTY_HARD = 3;
170
171 public const DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK = 3;
172
173 //TODO: this could probably do with being a lot bigger
174 private const BLOCK_CACHE_SIZE_CAP = 2048;
175
180 private array $players = [];
181
186 private array $entities = [];
191 private array $entityLastKnownPositions = [];
192
197 private array $entitiesByChunk = [];
198
203 public array $updateEntities = [];
204
205 private bool $inDynamicStateRecalculation = false;
210 private array $blockCache = [];
211 private int $blockCacheSize = 0;
216 private array $blockCollisionBoxCache = [];
217
218 private int $sendTimeTicker = 0;
219
220 private int $worldId;
221
222 private int $providerGarbageCollectionTicker = 0;
223
224 private int $minY;
225 private int $maxY;
226
231 private array $registeredTickingChunks = [];
232
239 private array $validTickingChunks = [];
240
246 private array $recheckTickingChunks = [];
247
252 private array $chunkLoaders = [];
253
258 private array $chunkListeners = [];
263 private array $playerChunkListeners = [];
264
269 private array $packetBuffersByChunk = [];
270
275 private array $unloadQueue = [];
276
277 private int $time;
278 public bool $stopTime = false;
279
280 private float $sunAnglePercentage = 0.0;
281 private int $skyLightReduction = 0;
282
283 private string $folderName;
284 private string $displayName;
285
290 private array $chunks = [];
291
296 private array $knownUngeneratedChunks = [];
297
302 private array $changedBlocks = [];
303
305 private ReversePriorityQueue $scheduledBlockUpdateQueue;
310 private array $scheduledBlockUpdateQueueIndex = [];
311
313 private \SplQueue $neighbourBlockUpdateQueue;
318 private array $neighbourBlockUpdateQueueIndex = [];
319
324 private array $activeChunkPopulationTasks = [];
329 private array $chunkLock = [];
330 private int $maxConcurrentChunkPopulationTasks = 2;
335 private array $chunkPopulationRequestMap = [];
340 private \SplQueue $chunkPopulationRequestQueue;
345 private array $chunkPopulationRequestQueueIndex = [];
346
347 private readonly GeneratorExecutor $generatorExecutor;
348
349 private bool $autoSave = true;
350
351 private int $sleepTicks = 0;
352
353 private int $chunkTickRadius;
354 private int $tickedBlocksPerSubchunkPerTick = self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK;
359 private array $randomTickBlocks = [];
360
361 public WorldTimings $timings;
362
363 public float $tickRateTime = 0;
364
365 private bool $doingTick = false;
366
367 private bool $unloaded = false;
372 private array $unloadCallbacks = [];
373
374 private ?BlockLightUpdate $blockLightUpdate = null;
375 private ?SkyLightUpdate $skyLightUpdate = null;
376
377 private \Logger $logger;
378
379 private RuntimeBlockStateRegistry $blockStateRegistry;
380
384 public static function chunkHash(int $x, int $z) : int{
385 return morton2d_encode($x, $z);
386 }
387
388 private const MORTON3D_BIT_SIZE = 21;
389 private const BLOCKHASH_Y_BITS = 9;
390 private const BLOCKHASH_Y_PADDING = 64; //size (in blocks) of padding after both boundaries of the Y axis
391 private const BLOCKHASH_Y_OFFSET = self::BLOCKHASH_Y_PADDING - self::Y_MIN;
392 private const BLOCKHASH_Y_MASK = (1 << self::BLOCKHASH_Y_BITS) - 1;
393 private const BLOCKHASH_XZ_MASK = (1 << self::MORTON3D_BIT_SIZE) - 1;
394 private const BLOCKHASH_XZ_EXTRA_BITS = (self::MORTON3D_BIT_SIZE - self::BLOCKHASH_Y_BITS) >> 1;
395 private const BLOCKHASH_XZ_EXTRA_MASK = (1 << self::BLOCKHASH_XZ_EXTRA_BITS) - 1;
396 private const BLOCKHASH_XZ_SIGN_SHIFT = 64 - self::MORTON3D_BIT_SIZE - self::BLOCKHASH_XZ_EXTRA_BITS;
397 private const BLOCKHASH_X_SHIFT = self::BLOCKHASH_Y_BITS;
398 private const BLOCKHASH_Z_SHIFT = self::BLOCKHASH_X_SHIFT + self::BLOCKHASH_XZ_EXTRA_BITS;
399
403 public static function blockHash(int $x, int $y, int $z) : int{
404 $shiftedY = $y + self::BLOCKHASH_Y_OFFSET;
405 if(($shiftedY & (~0 << self::BLOCKHASH_Y_BITS)) !== 0){
406 throw new \InvalidArgumentException("Y coordinate $y is out of range!");
407 }
408 //morton3d gives us 21 bits on each axis, but the Y axis only requires 9
409 //so we use the extra space on Y (12 bits) and add 6 extra bits from X and Z instead.
410 //if we ever need more space for Y (e.g. due to expansion), take bits from X/Z to compensate.
411 return morton3d_encode(
412 $x & self::BLOCKHASH_XZ_MASK,
413 ($shiftedY /* & self::BLOCKHASH_Y_MASK */) |
414 ((($x >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_X_SHIFT) |
415 ((($z >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_Z_SHIFT),
416 $z & self::BLOCKHASH_XZ_MASK
417 );
418 }
419
423 public static function chunkBlockHash(int $x, int $y, int $z) : int{
424 return morton3d_encode($x, $y, $z);
425 }
426
433 public static function getBlockXYZ(int $hash, ?int &$x, ?int &$y, ?int &$z) : void{
434 [$baseX, $baseY, $baseZ] = morton3d_decode($hash);
435
436 $extraX = ((($baseY >> self::BLOCKHASH_X_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
437 $extraZ = ((($baseY >> self::BLOCKHASH_Z_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
438
439 $x = (($baseX & self::BLOCKHASH_XZ_MASK) | $extraX) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
440 $y = ($baseY & self::BLOCKHASH_Y_MASK) - self::BLOCKHASH_Y_OFFSET;
441 $z = (($baseZ & self::BLOCKHASH_XZ_MASK) | $extraZ) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
442 }
443
449 public static function getXZ(int $hash, ?int &$x, ?int &$z) : void{
450 [$x, $z] = morton2d_decode($hash);
451 }
452
453 public static function getDifficultyFromString(string $str) : int{
454 switch(strtolower(trim($str))){
455 case "0":
456 case "peaceful":
457 case "p":
458 return World::DIFFICULTY_PEACEFUL;
459
460 case "1":
461 case "easy":
462 case "e":
463 return World::DIFFICULTY_EASY;
464
465 case "2":
466 case "normal":
467 case "n":
468 return World::DIFFICULTY_NORMAL;
469
470 case "3":
471 case "hard":
472 case "h":
473 return World::DIFFICULTY_HARD;
474 }
475
476 return -1;
477 }
478
482 public function __construct(
483 private Server $server,
484 string $name, //TODO: this should be folderName (named arguments BC break)
485 private WritableWorldProvider $provider,
486 private AsyncPool $workerPool
487 ){
488 $this->folderName = $name;
489 $this->worldId = self::$worldIdCounter++;
490
491 $this->displayName = $this->provider->getWorldData()->getName();
492 $this->logger = new \PrefixedLogger($server->getLogger(), "World: $this->displayName");
493
494 $this->blockStateRegistry = RuntimeBlockStateRegistry::getInstance();
495 $this->minY = $this->provider->getWorldMinY();
496 $this->maxY = $this->provider->getWorldMaxY();
497
498 $this->server->getLogger()->info($this->server->getLanguage()->translate(KnownTranslationFactory::pocketmine_level_preparing($this->displayName)));
499 $generator = GeneratorManager::getInstance()->getGenerator($this->provider->getWorldData()->getGenerator()) ??
500 throw new AssumptionFailedError("WorldManager should already have checked that the generator exists");
501 $generator->validateGeneratorOptions($this->provider->getWorldData()->getGeneratorOptions());
502
503 $executorSetupParameters = new GeneratorExecutorSetupParameters(
504 worldMinY: $this->minY,
505 worldMaxY: $this->maxY,
506 generatorSeed: $this->getSeed(),
507 generatorClass: $generator->getGeneratorClass(),
508 generatorSettings: $this->provider->getWorldData()->getGeneratorOptions()
509 );
510 $this->generatorExecutor = $generator->isFast() ?
511 new SyncGeneratorExecutor($executorSetupParameters) :
513 $this->logger,
514 $this->workerPool,
515 $executorSetupParameters,
516 $this->worldId
517 );
518
519 $this->chunkPopulationRequestQueue = new \SplQueue();
520 $this->addOnUnloadCallback(function() : void{
521 $this->logger->debug("Cancelling unfulfilled generation requests");
522
523 foreach($this->chunkPopulationRequestMap as $chunkHash => $promise){
524 $promise->reject();
525 unset($this->chunkPopulationRequestMap[$chunkHash]);
526 }
527 if(count($this->chunkPopulationRequestMap) !== 0){
528 //TODO: this might actually get hit because generation rejection callbacks might try to schedule new
529 //requests, and we can't prevent that right now because there's no way to detect "unloading" state
530 throw new AssumptionFailedError("New generation requests scheduled during unload");
531 }
532 });
533
534 $this->scheduledBlockUpdateQueue = new ReversePriorityQueue();
535 $this->scheduledBlockUpdateQueue->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
536
537 $this->neighbourBlockUpdateQueue = new \SplQueue();
538
539 $this->time = $this->provider->getWorldData()->getTime();
540
541 $cfg = $this->server->getConfigGroup();
542 $this->chunkTickRadius = min($this->server->getViewDistance(), max(0, $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_TICK_RADIUS, 4)));
543 if($cfg->getPropertyInt("chunk-ticking.per-tick", 40) <= 0){
544 //TODO: this needs l10n
545 $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.");
546 $this->chunkTickRadius = 0;
547 }
548 $this->tickedBlocksPerSubchunkPerTick = $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_BLOCKS_PER_SUBCHUNK_PER_TICK, self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK);
549 $this->maxConcurrentChunkPopulationTasks = $cfg->getPropertyInt(YmlServerProperties::CHUNK_GENERATION_POPULATION_QUEUE_SIZE, 2);
550
551 $this->initRandomTickBlocksFromConfig($cfg);
552
553 $this->timings = new WorldTimings($this);
554 }
555
556 private function initRandomTickBlocksFromConfig(ServerConfigGroup $cfg) : void{
557 $dontTickBlocks = [];
558 $parser = StringToItemParser::getInstance();
559 foreach($cfg->getProperty(YmlServerProperties::CHUNK_TICKING_DISABLE_BLOCK_TICKING, []) as $name){
560 $name = (string) $name;
561 $item = $parser->parse($name);
562 if($item !== null){
563 $block = $item->getBlock();
564 }elseif(preg_match("/^-?\d+$/", $name) === 1){
565 //TODO: this is a really sketchy hack - remove this as soon as possible
566 try{
567 $blockStateData = GlobalBlockStateHandlers::getUpgrader()->upgradeIntIdMeta((int) $name, 0);
568 }catch(BlockStateDeserializeException){
569 continue;
570 }
571 $block = $this->blockStateRegistry->fromStateId(GlobalBlockStateHandlers::getDeserializer()->deserialize($blockStateData));
572 }else{
573 //TODO: we probably ought to log an error here
574 continue;
575 }
576
577 if($block->getTypeId() !== BlockTypeIds::AIR){
578 $dontTickBlocks[$block->getTypeId()] = $name;
579 }
580 }
581
582 foreach($this->blockStateRegistry->getAllKnownStates() as $state){
583 $dontTickName = $dontTickBlocks[$state->getTypeId()] ?? null;
584 if($dontTickName === null && $state->ticksRandomly()){
585 $this->randomTickBlocks[$state->getStateId()] = true;
586 }
587 }
588 }
589
590 public function getTickRateTime() : float{
591 return $this->tickRateTime;
592 }
593
594 public function getServer() : Server{
595 return $this->server;
596 }
597
598 public function getLogger() : \Logger{
599 return $this->logger;
600 }
601
602 final public function getProvider() : WritableWorldProvider{
603 return $this->provider;
604 }
605
609 final public function getId() : int{
610 return $this->worldId;
611 }
612
613 public function isLoaded() : bool{
614 return !$this->unloaded;
615 }
616
620 public function onUnload() : void{
621 if($this->unloaded){
622 throw new \LogicException("Tried to close a world which is already closed");
623 }
624
625 foreach($this->unloadCallbacks as $callback){
626 $callback();
627 }
628 $this->unloadCallbacks = [];
629
630 foreach($this->chunks as $chunkHash => $chunk){
631 self::getXZ($chunkHash, $chunkX, $chunkZ);
632 $this->unloadChunk($chunkX, $chunkZ, false);
633 }
634 $this->knownUngeneratedChunks = [];
635 foreach($this->entitiesByChunk as $chunkHash => $entities){
636 self::getXZ($chunkHash, $chunkX, $chunkZ);
637
638 $leakedEntities = 0;
639 foreach($entities as $entity){
640 if(!$entity->isFlaggedForDespawn()){
641 $leakedEntities++;
642 }
643 $entity->close();
644 }
645 if($leakedEntities !== 0){
646 $this->logger->warning("$leakedEntities leaked entities found in ungenerated chunk $chunkX $chunkZ during unload, they won't be saved!");
647 }
648 }
649
650 $this->save();
651
652 $this->generatorExecutor->shutdown();
653
654 $this->provider->close();
655 $this->blockCache = [];
656 $this->blockCacheSize = 0;
657 $this->blockCollisionBoxCache = [];
658
659 $this->unloaded = true;
660 }
661
663 public function addOnUnloadCallback(\Closure $callback) : void{
664 $this->unloadCallbacks[spl_object_id($callback)] = $callback;
665 }
666
668 public function removeOnUnloadCallback(\Closure $callback) : void{
669 unset($this->unloadCallbacks[spl_object_id($callback)]);
670 }
671
680 private function filterViewersForPosition(Vector3 $pos, array $allowed) : array{
681 $candidates = $this->getViewersForPosition($pos);
682 $filtered = [];
683 foreach($allowed as $player){
684 $k = spl_object_id($player);
685 if(isset($candidates[$k])){
686 $filtered[$k] = $candidates[$k];
687 }
688 }
689
690 return $filtered;
691 }
692
696 public function addSound(Vector3 $pos, Sound $sound, ?array $players = null) : void{
697 $players ??= $this->getViewersForPosition($pos);
698
699 if(WorldSoundEvent::hasHandlers()){
700 $ev = new WorldSoundEvent($this, $sound, $pos, $players);
701 $ev->call();
702 if($ev->isCancelled()){
703 return;
704 }
705
706 $sound = $ev->getSound();
707 $players = $ev->getRecipients();
708 }
709
710 $pk = $sound->encode($pos);
711 if(count($pk) > 0){
712 if($players === $this->getViewersForPosition($pos)){
713 foreach($pk as $e){
714 $this->broadcastPacketToViewers($pos, $e);
715 }
716 }else{
717 NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
718 }
719 }
720 }
721
725 public function addParticle(Vector3 $pos, Particle $particle, ?array $players = null) : void{
726 $players ??= $this->getViewersForPosition($pos);
727
728 if(WorldParticleEvent::hasHandlers()){
729 $ev = new WorldParticleEvent($this, $particle, $pos, $players);
730 $ev->call();
731 if($ev->isCancelled()){
732 return;
733 }
734
735 $particle = $ev->getParticle();
736 $players = $ev->getRecipients();
737 }
738
739 $pk = $particle->encode($pos);
740 if(count($pk) > 0){
741 if($players === $this->getViewersForPosition($pos)){
742 foreach($pk as $e){
743 $this->broadcastPacketToViewers($pos, $e);
744 }
745 }else{
746 NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
747 }
748 }
749 }
750
751 public function getAutoSave() : bool{
752 return $this->autoSave;
753 }
754
755 public function setAutoSave(bool $value) : void{
756 $this->autoSave = $value;
757 }
758
768 public function getChunkPlayers(int $chunkX, int $chunkZ) : array{
769 return $this->playerChunkListeners[World::chunkHash($chunkX, $chunkZ)] ?? [];
770 }
771
778 public function getChunkLoaders(int $chunkX, int $chunkZ) : array{
779 return $this->chunkLoaders[World::chunkHash($chunkX, $chunkZ)] ?? [];
780 }
781
788 public function getViewersForPosition(Vector3 $pos) : array{
789 return $this->getChunkPlayers($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
790 }
791
795 public function broadcastPacketToViewers(Vector3 $pos, ClientboundPacket $packet) : void{
796 $this->broadcastPacketToPlayersUsingChunk($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE, $packet);
797 }
798
799 private function broadcastPacketToPlayersUsingChunk(int $chunkX, int $chunkZ, ClientboundPacket $packet) : void{
800 if(!isset($this->packetBuffersByChunk[$index = World::chunkHash($chunkX, $chunkZ)])){
801 $this->packetBuffersByChunk[$index] = [$packet];
802 }else{
803 $this->packetBuffersByChunk[$index][] = $packet;
804 }
805 }
806
807 public function registerChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ, bool $autoLoad = true) : void{
808 $loaderId = spl_object_id($loader);
809
810 if(!isset($this->chunkLoaders[$chunkHash = World::chunkHash($chunkX, $chunkZ)])){
811 $this->chunkLoaders[$chunkHash] = [];
812 }elseif(isset($this->chunkLoaders[$chunkHash][$loaderId])){
813 return;
814 }
815
816 $this->chunkLoaders[$chunkHash][$loaderId] = $loader;
817
818 $this->cancelUnloadChunkRequest($chunkX, $chunkZ);
819
820 if($autoLoad){
821 $this->loadChunk($chunkX, $chunkZ);
822 }
823 }
824
825 public function unregisterChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ) : void{
826 $chunkHash = World::chunkHash($chunkX, $chunkZ);
827 $loaderId = spl_object_id($loader);
828 if(isset($this->chunkLoaders[$chunkHash][$loaderId])){
829 if(count($this->chunkLoaders[$chunkHash]) === 1){
830 unset($this->chunkLoaders[$chunkHash]);
831 $this->unloadChunkRequest($chunkX, $chunkZ, true);
832 if(isset($this->chunkPopulationRequestMap[$chunkHash]) && !isset($this->activeChunkPopulationTasks[$chunkHash])){
833 $this->chunkPopulationRequestMap[$chunkHash]->reject();
834 unset($this->chunkPopulationRequestMap[$chunkHash]);
835 }
836 }else{
837 unset($this->chunkLoaders[$chunkHash][$loaderId]);
838 }
839 }
840 }
841
845 public function registerChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ) : void{
846 $hash = World::chunkHash($chunkX, $chunkZ);
847 if(isset($this->chunkListeners[$hash])){
848 $this->chunkListeners[$hash][spl_object_id($listener)] = $listener;
849 }else{
850 $this->chunkListeners[$hash] = [spl_object_id($listener) => $listener];
851 }
852 if($listener instanceof Player){
853 $this->playerChunkListeners[$hash][spl_object_id($listener)] = $listener;
854 }
855 }
856
862 public function unregisterChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ) : void{
863 $hash = World::chunkHash($chunkX, $chunkZ);
864 if(isset($this->chunkListeners[$hash])){
865 if(count($this->chunkListeners[$hash]) === 1){
866 unset($this->chunkListeners[$hash]);
867 unset($this->playerChunkListeners[$hash]);
868 }else{
869 unset($this->chunkListeners[$hash][spl_object_id($listener)]);
870 unset($this->playerChunkListeners[$hash][spl_object_id($listener)]);
871 }
872 }
873 }
874
878 public function unregisterChunkListenerFromAll(ChunkListener $listener) : void{
879 foreach($this->chunkListeners as $hash => $listeners){
880 World::getXZ($hash, $chunkX, $chunkZ);
881 $this->unregisterChunkListener($listener, $chunkX, $chunkZ);
882 }
883 }
884
891 public function getChunkListeners(int $chunkX, int $chunkZ) : array{
892 return $this->chunkListeners[World::chunkHash($chunkX, $chunkZ)] ?? [];
893 }
894
898 public function sendTime(Player ...$targets) : void{
899 if(count($targets) === 0){
900 $targets = $this->players;
901 }
902 foreach($targets as $player){
903 $player->getNetworkSession()->syncWorldTime($this->time);
904 }
905 }
906
907 public function isDoingTick() : bool{
908 return $this->doingTick;
909 }
910
914 public function doTick(int $currentTick) : void{
915 if($this->unloaded){
916 throw new \LogicException("Attempted to tick a world which has been closed");
917 }
918
919 $this->timings->doTick->startTiming();
920 $this->doingTick = true;
921 try{
922 $this->actuallyDoTick($currentTick);
923 }finally{
924 $this->doingTick = false;
925 $this->timings->doTick->stopTiming();
926 }
927 }
928
929 protected function actuallyDoTick(int $currentTick) : void{
930 if(!$this->stopTime){
931 //this simulates an overflow, as would happen in any language which doesn't do stupid things to var types
932 if($this->time === PHP_INT_MAX){
933 $this->time = PHP_INT_MIN;
934 }else{
935 $this->time++;
936 }
937 }
938
939 $this->sunAnglePercentage = $this->computeSunAnglePercentage(); //Sun angle depends on the current time
940 $this->skyLightReduction = $this->computeSkyLightReduction(); //Sky light reduction depends on the sun angle
941
942 if(++$this->sendTimeTicker === 200){
943 $this->sendTime();
944 $this->sendTimeTicker = 0;
945 }
946
947 $this->unloadChunks();
948 if(++$this->providerGarbageCollectionTicker >= 6000){
949 $this->provider->doGarbageCollection();
950 $this->providerGarbageCollectionTicker = 0;
951 }
952
953 $this->timings->scheduledBlockUpdates->startTiming();
954 //Delayed updates
955 while($this->scheduledBlockUpdateQueue->count() > 0 && $this->scheduledBlockUpdateQueue->current()["priority"] <= $currentTick){
957 $vec = $this->scheduledBlockUpdateQueue->extract()["data"];
958 unset($this->scheduledBlockUpdateQueueIndex[World::blockHash($vec->x, $vec->y, $vec->z)]);
959 if(!$this->isInLoadedTerrain($vec)){
960 continue;
961 }
962 $block = $this->getBlock($vec);
963 $block->onScheduledUpdate();
964 }
965 $this->timings->scheduledBlockUpdates->stopTiming();
966
967 $this->timings->neighbourBlockUpdates->startTiming();
968 //Normal updates
969 while($this->neighbourBlockUpdateQueue->count() > 0){
970 $index = $this->neighbourBlockUpdateQueue->dequeue();
971 unset($this->neighbourBlockUpdateQueueIndex[$index]);
972 World::getBlockXYZ($index, $x, $y, $z);
973 if(!$this->isChunkLoaded($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)){
974 continue;
975 }
976
977 $block = $this->getBlockAt($x, $y, $z);
978
979 if(BlockUpdateEvent::hasHandlers()){
980 $ev = new BlockUpdateEvent($block);
981 $ev->call();
982 if($ev->isCancelled()){
983 continue;
984 }
985 }
986 foreach($this->getNearbyEntities(AxisAlignedBB::one()->offsetCopy($x, $y, $z)) as $entity){
987 $entity->onNearbyBlockChange();
988 }
989 $block->onNearbyBlockChange();
990 }
991
992 $this->timings->neighbourBlockUpdates->stopTiming();
993
994 $this->timings->entityTick->startTiming();
995 //Update entities that need update
996 foreach($this->updateEntities as $id => $entity){
997 if($entity->isClosed() || $entity->isFlaggedForDespawn() || !$entity->onUpdate($currentTick)){
998 unset($this->updateEntities[$id]);
999 }
1000 if($entity->isFlaggedForDespawn()){
1001 $entity->close();
1002 }
1003 }
1004 $this->timings->entityTick->stopTiming();
1005
1006 $this->timings->randomChunkUpdates->startTiming();
1007 $this->tickChunks();
1008 $this->timings->randomChunkUpdates->stopTiming();
1009
1010 $this->executeQueuedLightUpdates();
1011
1012 if(count($this->changedBlocks) > 0){
1013 if(count($this->players) > 0){
1014 foreach($this->changedBlocks as $index => $blocks){
1015 if(count($blocks) === 0){ //blocks can be set normally and then later re-set with direct send
1016 continue;
1017 }
1018 World::getXZ($index, $chunkX, $chunkZ);
1019 if(!$this->isChunkLoaded($chunkX, $chunkZ)){
1020 //a previous chunk may have caused this one to be unloaded by a ChunkListener
1021 continue;
1022 }
1023 if(count($blocks) > 512){
1024 $chunk = $this->getChunk($chunkX, $chunkZ) ?? throw new AssumptionFailedError("We already checked that the chunk is loaded");
1025 foreach($this->getChunkPlayers($chunkX, $chunkZ) as $p){
1026 $p->onChunkChanged($chunkX, $chunkZ, $chunk);
1027 }
1028 }else{
1029 foreach($this->createBlockUpdatePackets($blocks) as $packet){
1030 $this->broadcastPacketToPlayersUsingChunk($chunkX, $chunkZ, $packet);
1031 }
1032 }
1033 }
1034 }
1035
1036 $this->changedBlocks = [];
1037
1038 }
1039
1040 if($this->sleepTicks > 0 && --$this->sleepTicks <= 0){
1041 $this->checkSleep();
1042 }
1043
1044 foreach($this->packetBuffersByChunk as $index => $entries){
1045 World::getXZ($index, $chunkX, $chunkZ);
1046 $chunkPlayers = $this->getChunkPlayers($chunkX, $chunkZ);
1047 if(count($chunkPlayers) > 0){
1048 NetworkBroadcastUtils::broadcastPackets($chunkPlayers, $entries);
1049 }
1050 }
1051
1052 $this->packetBuffersByChunk = [];
1053 }
1054
1055 public function checkSleep() : void{
1056 if(count($this->players) === 0){
1057 return;
1058 }
1059
1060 $resetTime = true;
1061 foreach($this->getPlayers() as $p){
1062 if(!$p->isSleeping()){
1063 $resetTime = false;
1064 break;
1065 }
1066 }
1067
1068 if($resetTime){
1069 $time = $this->getTimeOfDay();
1070
1071 if($time >= World::TIME_NIGHT && $time < World::TIME_SUNRISE){
1072 $this->setTime($this->getTime() + World::TIME_FULL - $time);
1073
1074 foreach($this->getPlayers() as $p){
1075 $p->stopSleep();
1076 }
1077 }
1078 }
1079 }
1080
1081 public function setSleepTicks(int $ticks) : void{
1082 $this->sleepTicks = $ticks;
1083 }
1084
1091 public function createBlockUpdatePackets(array $blocks) : array{
1092 $packets = [];
1093
1094 $blockTranslator = TypeConverter::getInstance()->getBlockTranslator();
1095
1096 foreach($blocks as $b){
1097 if(!($b instanceof Vector3)){
1098 throw new \TypeError("Expected Vector3 in blocks array, got " . (is_object($b) ? get_class($b) : gettype($b)));
1099 }
1100
1101 $fullBlock = $this->getBlockAt($b->x, $b->y, $b->z);
1102 $blockPosition = BlockPosition::fromVector3($b);
1103
1104 $tile = $this->getTileAt($b->x, $b->y, $b->z);
1105 if($tile instanceof Spawnable){
1106 $expectedClass = $fullBlock->getIdInfo()->getTileClass();
1107 if($expectedClass !== null && $tile instanceof $expectedClass && count($fakeStateProperties = $tile->getRenderUpdateBugWorkaroundStateProperties($fullBlock)) > 0){
1108 $originalStateData = $blockTranslator->internalIdToNetworkStateData($fullBlock->getStateId());
1109 $fakeStateData = new BlockStateData(
1110 $originalStateData->getName(),
1111 array_merge($originalStateData->getStates(), $fakeStateProperties),
1112 $originalStateData->getVersion()
1113 );
1114 $packets[] = UpdateBlockPacket::create(
1115 $blockPosition,
1116 $blockTranslator->getBlockStateDictionary()->lookupStateIdFromData($fakeStateData) ?? throw new AssumptionFailedError("Unmapped fake blockstate data: " . $fakeStateData->toNbt()),
1117 UpdateBlockPacket::FLAG_NETWORK,
1118 UpdateBlockPacket::DATA_LAYER_NORMAL
1119 );
1120 }
1121 }
1122 $packets[] = UpdateBlockPacket::create(
1123 $blockPosition,
1124 $blockTranslator->internalIdToNetworkId($fullBlock->getStateId()),
1125 UpdateBlockPacket::FLAG_NETWORK,
1126 UpdateBlockPacket::DATA_LAYER_NORMAL
1127 );
1128
1129 if($tile instanceof Spawnable){
1130 $packets[] = BlockActorDataPacket::create($blockPosition, $tile->getSerializedSpawnCompound());
1131 }
1132 }
1133
1134 return $packets;
1135 }
1136
1137 public function clearCache(bool $force = false) : void{
1138 if($force){
1139 $this->blockCache = [];
1140 $this->blockCacheSize = 0;
1141 $this->blockCollisionBoxCache = [];
1142 }else{
1143 //Recalculate this when we're asked - blockCacheSize may be higher than the real size
1144 $this->blockCacheSize = 0;
1145 foreach($this->blockCache as $list){
1146 $this->blockCacheSize += count($list);
1147 if($this->blockCacheSize > self::BLOCK_CACHE_SIZE_CAP){
1148 $this->blockCache = [];
1149 $this->blockCacheSize = 0;
1150 break;
1151 }
1152 }
1153
1154 $count = 0;
1155 foreach($this->blockCollisionBoxCache as $list){
1156 $count += count($list);
1157 if($count > self::BLOCK_CACHE_SIZE_CAP){
1158 //TODO: Is this really the best logic?
1159 $this->blockCollisionBoxCache = [];
1160 break;
1161 }
1162 }
1163 }
1164 }
1165
1166 private function trimBlockCache() : void{
1167 $before = $this->blockCacheSize;
1168 //Since PHP maintains key order, earliest in foreach should be the oldest entries
1169 //Older entries are less likely to be hot, so destroying these should usually have the lowest impact on performance
1170 foreach($this->blockCache as $chunkHash => $blocks){
1171 unset($this->blockCache[$chunkHash]);
1172 $this->blockCacheSize -= count($blocks);
1173 if($this->blockCacheSize < self::BLOCK_CACHE_SIZE_CAP){
1174 break;
1175 }
1176 }
1177 }
1178
1183 public function getRandomTickedBlocks() : array{
1184 return $this->randomTickBlocks;
1185 }
1186
1187 public function addRandomTickedBlock(Block $block) : void{
1188 if($block instanceof UnknownBlock){
1189 throw new \InvalidArgumentException("Cannot do random-tick on unknown block");
1190 }
1191 $this->randomTickBlocks[$block->getStateId()] = true;
1192 }
1193
1194 public function removeRandomTickedBlock(Block $block) : void{
1195 unset($this->randomTickBlocks[$block->getStateId()]);
1196 }
1197
1202 public function getChunkTickRadius() : int{
1203 return $this->chunkTickRadius;
1204 }
1205
1210 public function setChunkTickRadius(int $radius) : void{
1211 $this->chunkTickRadius = $radius;
1212 }
1213
1221 public function getTickingChunks() : array{
1222 return array_keys($this->validTickingChunks);
1223 }
1224
1229 public function registerTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ) : void{
1230 $chunkPosHash = World::chunkHash($chunkX, $chunkZ);
1231 $this->registeredTickingChunks[$chunkPosHash][spl_object_id($ticker)] = $ticker;
1232 $this->recheckTickingChunks[$chunkPosHash] = $chunkPosHash;
1233 }
1234
1239 public function unregisterTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ) : void{
1240 $chunkHash = World::chunkHash($chunkX, $chunkZ);
1241 $tickerId = spl_object_id($ticker);
1242 if(isset($this->registeredTickingChunks[$chunkHash][$tickerId])){
1243 if(count($this->registeredTickingChunks[$chunkHash]) === 1){
1244 unset(
1245 $this->registeredTickingChunks[$chunkHash],
1246 $this->recheckTickingChunks[$chunkHash],
1247 $this->validTickingChunks[$chunkHash]
1248 );
1249 }else{
1250 unset($this->registeredTickingChunks[$chunkHash][$tickerId]);
1251 }
1252 }
1253 }
1254
1255 private function tickChunks() : void{
1256 if($this->chunkTickRadius <= 0 || count($this->registeredTickingChunks) === 0){
1257 return;
1258 }
1259
1260 if(count($this->recheckTickingChunks) > 0){
1261 $this->timings->randomChunkUpdatesChunkSelection->startTiming();
1262
1263 $chunkTickableCache = [];
1264
1265 foreach($this->recheckTickingChunks as $hash => $_){
1266 World::getXZ($hash, $chunkX, $chunkZ);
1267 if($this->isChunkTickable($chunkX, $chunkZ, $chunkTickableCache)){
1268 $this->validTickingChunks[$hash] = $hash;
1269 }
1270 }
1271 $this->recheckTickingChunks = [];
1272
1273 $this->timings->randomChunkUpdatesChunkSelection->stopTiming();
1274 }
1275
1276 foreach($this->validTickingChunks as $index => $_){
1277 World::getXZ($index, $chunkX, $chunkZ);
1278
1279 $this->tickChunk($chunkX, $chunkZ);
1280 }
1281 }
1282
1289 private function isChunkTickable(int $chunkX, int $chunkZ, array &$cache) : bool{
1290 for($cx = -1; $cx <= 1; ++$cx){
1291 for($cz = -1; $cz <= 1; ++$cz){
1292 $chunkHash = World::chunkHash($chunkX + $cx, $chunkZ + $cz);
1293 if(isset($cache[$chunkHash])){
1294 if(!$cache[$chunkHash]){
1295 return false;
1296 }
1297 continue;
1298 }
1299 if($this->isChunkLocked($chunkX + $cx, $chunkZ + $cz)){
1300 $cache[$chunkHash] = false;
1301 return false;
1302 }
1303 $adjacentChunk = $this->getChunk($chunkX + $cx, $chunkZ + $cz);
1304 if($adjacentChunk === null || !$adjacentChunk->isPopulated()){
1305 $cache[$chunkHash] = false;
1306 return false;
1307 }
1308 $lightPopulatedState = $adjacentChunk->isLightPopulated();
1309 if($lightPopulatedState !== true){
1310 if($lightPopulatedState === false){
1311 $this->orderLightPopulation($chunkX + $cx, $chunkZ + $cz);
1312 }
1313 $cache[$chunkHash] = false;
1314 return false;
1315 }
1316
1317 $cache[$chunkHash] = true;
1318 }
1319 }
1320
1321 return true;
1322 }
1323
1333 private function markTickingChunkForRecheck(int $chunkX, int $chunkZ) : void{
1334 for($cx = -1; $cx <= 1; ++$cx){
1335 for($cz = -1; $cz <= 1; ++$cz){
1336 $chunkHash = World::chunkHash($chunkX + $cx, $chunkZ + $cz);
1337 unset($this->validTickingChunks[$chunkHash]);
1338 if(isset($this->registeredTickingChunks[$chunkHash])){
1339 $this->recheckTickingChunks[$chunkHash] = $chunkHash;
1340 }else{
1341 unset($this->recheckTickingChunks[$chunkHash]);
1342 }
1343 }
1344 }
1345 }
1346
1347 private function orderLightPopulation(int $chunkX, int $chunkZ) : void{
1348 $chunkHash = World::chunkHash($chunkX, $chunkZ);
1349 $lightPopulatedState = $this->chunks[$chunkHash]->isLightPopulated();
1350 if($lightPopulatedState === false){
1351 $this->chunks[$chunkHash]->setLightPopulated(null);
1352 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
1353
1354 $this->workerPool->submitTask(new LightPopulationTask(
1355 $this->chunks[$chunkHash],
1356 function(array $blockLight, array $skyLight, array $heightMap) use ($chunkX, $chunkZ) : void{
1363 if($this->unloaded || ($chunk = $this->getChunk($chunkX, $chunkZ)) === null || $chunk->isLightPopulated() === true){
1364 return;
1365 }
1366 //TODO: calculated light information might not be valid if the terrain changed during light calculation
1367
1368 $chunk->setHeightMapArray($heightMap);
1369 foreach($blockLight as $y => $lightArray){
1370 $chunk->getSubChunk($y)->setBlockLightArray($lightArray);
1371 }
1372 foreach($skyLight as $y => $lightArray){
1373 $chunk->getSubChunk($y)->setBlockSkyLightArray($lightArray);
1374 }
1375 $chunk->setLightPopulated(true);
1376 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
1377 }
1378 ));
1379 }
1380 }
1381
1382 private function tickChunk(int $chunkX, int $chunkZ) : void{
1383 $chunk = $this->getChunk($chunkX, $chunkZ);
1384 if($chunk === null){
1385 //the chunk may have been unloaded during a previous chunk's update (e.g. during BlockGrowEvent)
1386 return;
1387 }
1388 foreach($this->getChunkEntities($chunkX, $chunkZ) as $entity){
1389 $entity->onRandomUpdate();
1390 }
1391
1392 $blockFactory = $this->blockStateRegistry;
1393 foreach($chunk->getSubChunks() as $Y => $subChunk){
1394 if(!$subChunk->isEmptyFast()){
1395 $k = 0;
1396 for($i = 0; $i < $this->tickedBlocksPerSubchunkPerTick; ++$i){
1397 if(($i % 5) === 0){
1398 //60 bits will be used by 5 blocks (12 bits each)
1399 $k = mt_rand(0, (1 << 60) - 1);
1400 }
1401 $x = $k & SubChunk::COORD_MASK;
1402 $y = ($k >> SubChunk::COORD_BIT_SIZE) & SubChunk::COORD_MASK;
1403 $z = ($k >> (SubChunk::COORD_BIT_SIZE * 2)) & SubChunk::COORD_MASK;
1404 $k >>= (SubChunk::COORD_BIT_SIZE * 3);
1405
1406 $state = $subChunk->getBlockStateId($x, $y, $z);
1407
1408 if(isset($this->randomTickBlocks[$state])){
1409 $block = $blockFactory->fromStateId($state);
1410 $block->position($this, $chunkX * Chunk::EDGE_LENGTH + $x, ($Y << SubChunk::COORD_BIT_SIZE) + $y, $chunkZ * Chunk::EDGE_LENGTH + $z);
1411 $block->onRandomTick();
1412 }
1413 }
1414 }
1415 }
1416 }
1417
1421 public function __debugInfo() : array{
1422 return [];
1423 }
1424
1425 public function save(bool $force = false) : bool{
1426
1427 if(!$this->getAutoSave() && !$force){
1428 return false;
1429 }
1430
1431 (new WorldSaveEvent($this))->call();
1432
1433 $timings = $this->timings->syncDataSave;
1434 $timings->startTiming();
1435
1436 $this->provider->getWorldData()->setTime($this->time);
1437 $this->saveChunks();
1438 $this->provider->getWorldData()->save();
1439
1440 $timings->stopTiming();
1441
1442 return true;
1443 }
1444
1445 public function saveChunks() : void{
1446 $this->timings->syncChunkSave->startTiming();
1447 try{
1448 foreach($this->chunks as $chunkHash => $chunk){
1449 self::getXZ($chunkHash, $chunkX, $chunkZ);
1450 $this->provider->saveChunk($chunkX, $chunkZ, new ChunkData(
1451 $chunk->getSubChunks(),
1452 $chunk->isPopulated(),
1453 array_map(fn(Entity $e) => $e->saveNBT(), array_values(array_filter($this->getChunkEntities($chunkX, $chunkZ), fn(Entity $e) => $e->canSaveWithChunk()))),
1454 array_map(fn(Tile $t) => $t->saveNBT(), array_values($chunk->getTiles())),
1455 ), $chunk->getTerrainDirtyFlags());
1456 $chunk->clearTerrainDirtyFlags();
1457 }
1458 }finally{
1459 $this->timings->syncChunkSave->stopTiming();
1460 }
1461 }
1462
1467 public function scheduleDelayedBlockUpdate(Vector3 $pos, int $delay) : void{
1468 if(
1469 !$this->isInWorld($pos->x, $pos->y, $pos->z) ||
1470 (isset($this->scheduledBlockUpdateQueueIndex[$index = World::blockHash($pos->x, $pos->y, $pos->z)]) && $this->scheduledBlockUpdateQueueIndex[$index] <= $delay)
1471 ){
1472 return;
1473 }
1474 $this->scheduledBlockUpdateQueueIndex[$index] = $delay;
1475 $this->scheduledBlockUpdateQueue->insert(new Vector3((int) $pos->x, (int) $pos->y, (int) $pos->z), $delay + $this->server->getTick());
1476 }
1477
1478 private function tryAddToNeighbourUpdateQueue(int $x, int $y, int $z) : void{
1479 if($this->isInWorld($x, $y, $z)){
1480 $hash = World::blockHash($x, $y, $z);
1481 if(!isset($this->neighbourBlockUpdateQueueIndex[$hash])){
1482 $this->neighbourBlockUpdateQueue->enqueue($hash);
1483 $this->neighbourBlockUpdateQueueIndex[$hash] = true;
1484 }
1485 }
1486 }
1487
1494 private function internalNotifyNeighbourBlockUpdate(int $x, int $y, int $z) : void{
1495 $this->tryAddToNeighbourUpdateQueue($x, $y, $z);
1496 foreach(Facing::OFFSET as [$dx, $dy, $dz]){
1497 $this->tryAddToNeighbourUpdateQueue($x + $dx, $y + $dy, $z + $dz);
1498 }
1499 }
1500
1508 public function notifyNeighbourBlockUpdate(Vector3 $pos) : void{
1509 $this->internalNotifyNeighbourBlockUpdate($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ());
1510 }
1511
1516 public function getCollisionBlocks(AxisAlignedBB $bb, bool $targetFirst = false) : array{
1517 $minX = (int) floor($bb->minX - 1);
1518 $minY = (int) floor($bb->minY - 1);
1519 $minZ = (int) floor($bb->minZ - 1);
1520 $maxX = (int) floor($bb->maxX + 1);
1521 $maxY = (int) floor($bb->maxY + 1);
1522 $maxZ = (int) floor($bb->maxZ + 1);
1523
1524 $collides = [];
1525
1526 $collisionInfo = $this->blockStateRegistry->collisionInfo;
1527 if($targetFirst){
1528 for($z = $minZ; $z <= $maxZ; ++$z){
1529 $zOverflow = $z === $minZ || $z === $maxZ;
1530 for($x = $minX; $x <= $maxX; ++$x){
1531 $zxOverflow = $zOverflow || $x === $minX || $x === $maxX;
1532 for($y = $minY; $y <= $maxY; ++$y){
1533 $overflow = $zxOverflow || $y === $minY || $y === $maxY;
1534
1535 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1536 if($overflow ?
1537 $stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW && $this->getBlockAt($x, $y, $z)->collidesWithBB($bb) :
1538 match ($stateCollisionInfo) {
1539 RuntimeBlockStateRegistry::COLLISION_CUBE => true,
1540 RuntimeBlockStateRegistry::COLLISION_NONE => false,
1541 default => $this->getBlockAt($x, $y, $z)->collidesWithBB($bb)
1542 }
1543 ){
1544 return [$this->getBlockAt($x, $y, $z)];
1545 }
1546 }
1547 }
1548 }
1549 }else{
1550 //TODO: duplicated code :( this way is better for performance though
1551 for($z = $minZ; $z <= $maxZ; ++$z){
1552 $zOverflow = $z === $minZ || $z === $maxZ;
1553 for($x = $minX; $x <= $maxX; ++$x){
1554 $zxOverflow = $zOverflow || $x === $minX || $x === $maxX;
1555 for($y = $minY; $y <= $maxY; ++$y){
1556 $overflow = $zxOverflow || $y === $minY || $y === $maxY;
1557
1558 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1559 if($overflow ?
1560 $stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW && $this->getBlockAt($x, $y, $z)->collidesWithBB($bb) :
1561 match ($stateCollisionInfo) {
1562 RuntimeBlockStateRegistry::COLLISION_CUBE => true,
1563 RuntimeBlockStateRegistry::COLLISION_NONE => false,
1564 default => $this->getBlockAt($x, $y, $z)->collidesWithBB($bb)
1565 }
1566 ){
1567 $collides[] = $this->getBlockAt($x, $y, $z);
1568 }
1569 }
1570 }
1571 }
1572 }
1573
1574 return $collides;
1575 }
1576
1581 private function getBlockCollisionInfo(int $x, int $y, int $z, array $collisionInfo) : int{
1582 if(!$this->isInWorld($x, $y, $z)){
1583 return RuntimeBlockStateRegistry::COLLISION_NONE;
1584 }
1585 $chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1586 if($chunk === null){
1587 return RuntimeBlockStateRegistry::COLLISION_NONE;
1588 }
1589 $stateId = $chunk
1590 ->getSubChunk($y >> SubChunk::COORD_BIT_SIZE)
1591 ->getBlockStateId(
1592 $x & SubChunk::COORD_MASK,
1593 $y & SubChunk::COORD_MASK,
1594 $z & SubChunk::COORD_MASK
1595 );
1596 return $collisionInfo[$stateId];
1597 }
1598
1610 private function getBlockCollisionBoxesForCell(int $x, int $y, int $z, array $collisionInfo) : array{
1611 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1612 $boxes = match($stateCollisionInfo){
1613 RuntimeBlockStateRegistry::COLLISION_NONE => [],
1614 RuntimeBlockStateRegistry::COLLISION_CUBE => [AxisAlignedBB::one()->offsetCopy($x, $y, $z)],
1615 default => $this->getBlockAt($x, $y, $z)->getCollisionBoxes()
1616 };
1617
1618 //overlapping AABBs can't make any difference if this is a cube, so we can save some CPU cycles in this common case
1619 if($stateCollisionInfo !== RuntimeBlockStateRegistry::COLLISION_CUBE){
1620 $cellBB = null;
1621 foreach(Facing::OFFSET as [$dx, $dy, $dz]){
1622 $offsetX = $x + $dx;
1623 $offsetY = $y + $dy;
1624 $offsetZ = $z + $dz;
1625 $stateCollisionInfo = $this->getBlockCollisionInfo($offsetX, $offsetY, $offsetZ, $collisionInfo);
1626 if($stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW){
1627 //avoid allocating this unless it's needed
1628 $cellBB ??= AxisAlignedBB::one()->offsetCopy($x, $y, $z);
1629 $extraBoxes = $this->getBlockAt($offsetX, $offsetY, $offsetZ)->getCollisionBoxes();
1630 foreach($extraBoxes as $extraBox){
1631 if($extraBox->intersectsWith($cellBB)){
1632 $boxes[] = $extraBox;
1633 }
1634 }
1635 }
1636 }
1637 }
1638
1639 return $boxes;
1640 }
1641
1646 public function getBlockCollisionBoxes(AxisAlignedBB $bb) : array{
1647 $minX = (int) floor($bb->minX);
1648 $minY = (int) floor($bb->minY);
1649 $minZ = (int) floor($bb->minZ);
1650 $maxX = (int) floor($bb->maxX);
1651 $maxY = (int) floor($bb->maxY);
1652 $maxZ = (int) floor($bb->maxZ);
1653
1654 $collides = [];
1655
1656 $collisionInfo = $this->blockStateRegistry->collisionInfo;
1657
1658 for($z = $minZ; $z <= $maxZ; ++$z){
1659 for($x = $minX; $x <= $maxX; ++$x){
1660 $chunkPosHash = World::chunkHash($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1661 for($y = $minY; $y <= $maxY; ++$y){
1662 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
1663
1664 $boxes = $this->blockCollisionBoxCache[$chunkPosHash][$relativeBlockHash] ??= $this->getBlockCollisionBoxesForCell($x, $y, $z, $collisionInfo);
1665
1666 foreach($boxes as $blockBB){
1667 if($blockBB->intersectsWith($bb)){
1668 $collides[] = $blockBB;
1669 }
1670 }
1671 }
1672 }
1673 }
1674
1675 return $collides;
1676 }
1677
1682 public function computeSunAnglePercentage() : float{
1683 $timeProgress = ($this->time % self::TIME_FULL) / self::TIME_FULL;
1684
1685 //0.0 needs to be high noon, not dusk
1686 $sunProgress = $timeProgress + ($timeProgress < 0.25 ? 0.75 : -0.25);
1687
1688 //Offset the sun progress to be above the horizon longer at dusk and dawn
1689 //this is roughly an inverted sine curve, which pushes the sun progress back at dusk and forwards at dawn
1690 $diff = (((1 - ((cos($sunProgress * M_PI) + 1) / 2)) - $sunProgress) / 3);
1691
1692 return $sunProgress + $diff;
1693 }
1694
1698 public function getSunAnglePercentage() : float{
1699 return $this->sunAnglePercentage;
1700 }
1701
1705 public function getSunAngleRadians() : float{
1706 return $this->sunAnglePercentage * 2 * M_PI;
1707 }
1708
1712 public function getSunAngleDegrees() : float{
1713 return $this->sunAnglePercentage * 360.0;
1714 }
1715
1720 public function computeSkyLightReduction() : int{
1721 $percentage = max(0, min(1, -(cos($this->getSunAngleRadians()) * 2 - 0.5)));
1722
1723 //TODO: check rain and thunder level
1724
1725 return (int) ($percentage * 11);
1726 }
1727
1731 public function getSkyLightReduction() : int{
1732 return $this->skyLightReduction;
1733 }
1734
1739 public function getFullLight(Vector3 $pos) : int{
1740 $floorX = $pos->getFloorX();
1741 $floorY = $pos->getFloorY();
1742 $floorZ = $pos->getFloorZ();
1743 return $this->getFullLightAt($floorX, $floorY, $floorZ);
1744 }
1745
1750 public function getFullLightAt(int $x, int $y, int $z) : int{
1751 $skyLight = $this->getRealBlockSkyLightAt($x, $y, $z);
1752 if($skyLight < 15){
1753 return max($skyLight, $this->getBlockLightAt($x, $y, $z));
1754 }else{
1755 return $skyLight;
1756 }
1757 }
1758
1763 public function getHighestAdjacentFullLightAt(int $x, int $y, int $z) : int{
1764 return $this->getHighestAdjacentLight($x, $y, $z, $this->getFullLightAt(...));
1765 }
1766
1771 public function getPotentialLight(Vector3 $pos) : int{
1772 $floorX = $pos->getFloorX();
1773 $floorY = $pos->getFloorY();
1774 $floorZ = $pos->getFloorZ();
1775 return $this->getPotentialLightAt($floorX, $floorY, $floorZ);
1776 }
1777
1782 public function getPotentialLightAt(int $x, int $y, int $z) : int{
1783 return max($this->getPotentialBlockSkyLightAt($x, $y, $z), $this->getBlockLightAt($x, $y, $z));
1784 }
1785
1790 public function getHighestAdjacentPotentialLightAt(int $x, int $y, int $z) : int{
1791 return $this->getHighestAdjacentLight($x, $y, $z, $this->getPotentialLightAt(...));
1792 }
1793
1800 public function getPotentialBlockSkyLightAt(int $x, int $y, int $z) : int{
1801 if(!$this->isInWorld($x, $y, $z)){
1802 return $y >= self::Y_MAX ? 15 : 0;
1803 }
1804 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null && $chunk->isLightPopulated() === true){
1805 return $chunk->getSubChunk($y >> Chunk::COORD_BIT_SIZE)->getBlockSkyLightArray()->get($x & SubChunk::COORD_MASK, $y & SubChunk::COORD_MASK, $z & SubChunk::COORD_MASK);
1806 }
1807 return 0; //TODO: this should probably throw instead (light not calculated yet)
1808 }
1809
1815 public function getRealBlockSkyLightAt(int $x, int $y, int $z) : int{
1816 $light = $this->getPotentialBlockSkyLightAt($x, $y, $z) - $this->skyLightReduction;
1817 return $light < 0 ? 0 : $light;
1818 }
1819
1825 public function getBlockLightAt(int $x, int $y, int $z) : int{
1826 if(!$this->isInWorld($x, $y, $z)){
1827 return 0;
1828 }
1829 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null && $chunk->isLightPopulated() === true){
1830 return $chunk->getSubChunk($y >> Chunk::COORD_BIT_SIZE)->getBlockLightArray()->get($x & SubChunk::COORD_MASK, $y & SubChunk::COORD_MASK, $z & SubChunk::COORD_MASK);
1831 }
1832 return 0; //TODO: this should probably throw instead (light not calculated yet)
1833 }
1834
1835 public function updateAllLight(int $x, int $y, int $z) : void{
1836 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) === null || $chunk->isLightPopulated() !== true){
1837 return;
1838 }
1839
1840 $blockFactory = $this->blockStateRegistry;
1841 $this->timings->doBlockSkyLightUpdates->startTiming();
1842 if($this->skyLightUpdate === null){
1843 $this->skyLightUpdate = new SkyLightUpdate(new SubChunkExplorer($this), $blockFactory->lightFilter, $blockFactory->blocksDirectSkyLight);
1844 }
1845 $this->skyLightUpdate->recalculateNode($x, $y, $z);
1846 $this->timings->doBlockSkyLightUpdates->stopTiming();
1847
1848 $this->timings->doBlockLightUpdates->startTiming();
1849 if($this->blockLightUpdate === null){
1850 $this->blockLightUpdate = new BlockLightUpdate(new SubChunkExplorer($this), $blockFactory->lightFilter, $blockFactory->light);
1851 }
1852 $this->blockLightUpdate->recalculateNode($x, $y, $z);
1853 $this->timings->doBlockLightUpdates->stopTiming();
1854 }
1855
1859 private function getHighestAdjacentLight(int $x, int $y, int $z, \Closure $lightGetter) : int{
1860 $max = 0;
1861 foreach(Facing::OFFSET as [$offsetX, $offsetY, $offsetZ]){
1862 $x1 = $x + $offsetX;
1863 $y1 = $y + $offsetY;
1864 $z1 = $z + $offsetZ;
1865 if(
1866 !$this->isInWorld($x1, $y1, $z1) ||
1867 ($chunk = $this->getChunk($x1 >> Chunk::COORD_BIT_SIZE, $z1 >> Chunk::COORD_BIT_SIZE)) === null ||
1868 $chunk->isLightPopulated() !== true
1869 ){
1870 continue;
1871 }
1872 $max = max($max, $lightGetter($x1, $y1, $z1));
1873 }
1874 return $max;
1875 }
1876
1880 public function getHighestAdjacentPotentialBlockSkyLight(int $x, int $y, int $z) : int{
1881 return $this->getHighestAdjacentLight($x, $y, $z, $this->getPotentialBlockSkyLightAt(...));
1882 }
1883
1888 public function getHighestAdjacentRealBlockSkyLight(int $x, int $y, int $z) : int{
1889 return $this->getHighestAdjacentPotentialBlockSkyLight($x, $y, $z) - $this->skyLightReduction;
1890 }
1891
1895 public function getHighestAdjacentBlockLight(int $x, int $y, int $z) : int{
1896 return $this->getHighestAdjacentLight($x, $y, $z, $this->getBlockLightAt(...));
1897 }
1898
1899 private function executeQueuedLightUpdates() : void{
1900 if($this->blockLightUpdate !== null){
1901 $this->timings->doBlockLightUpdates->startTiming();
1902 $this->blockLightUpdate->execute();
1903 $this->blockLightUpdate = null;
1904 $this->timings->doBlockLightUpdates->stopTiming();
1905 }
1906
1907 if($this->skyLightUpdate !== null){
1908 $this->timings->doBlockSkyLightUpdates->startTiming();
1909 $this->skyLightUpdate->execute();
1910 $this->skyLightUpdate = null;
1911 $this->timings->doBlockSkyLightUpdates->stopTiming();
1912 }
1913 }
1914
1915 public function isInWorld(int $x, int $y, int $z) : bool{
1916 return (
1917 $x <= Limits::INT32_MAX && $x >= Limits::INT32_MIN &&
1918 $y < $this->maxY && $y >= $this->minY &&
1919 $z <= Limits::INT32_MAX && $z >= Limits::INT32_MIN
1920 );
1921 }
1922
1933 public function getBlock(Vector3 $pos, bool $cached = true, bool $addToCache = true) : Block{
1934 return $this->getBlockAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z), $cached, $addToCache);
1935 }
1936
1946 public function getBlockAt(int $x, int $y, int $z, bool $cached = true, bool $addToCache = true) : Block{
1947 $relativeBlockHash = null;
1948 $chunkHash = World::chunkHash($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1949
1950 if($this->isInWorld($x, $y, $z)){
1951 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
1952
1953 if($cached && isset($this->blockCache[$chunkHash][$relativeBlockHash])){
1954 return $this->blockCache[$chunkHash][$relativeBlockHash];
1955 }
1956
1957 $chunk = $this->chunks[$chunkHash] ?? null;
1958 if($chunk !== null){
1959 $block = $this->blockStateRegistry->fromStateId($chunk->getBlockStateId($x & Chunk::COORD_MASK, $y, $z & Chunk::COORD_MASK));
1960 }else{
1961 $addToCache = false;
1962 $block = VanillaBlocks::AIR();
1963 }
1964 }else{
1965 $block = VanillaBlocks::AIR();
1966 }
1967
1968 $block->position($this, $x, $y, $z);
1969
1970 if($this->inDynamicStateRecalculation){
1971 //this call was generated by a parent getBlock() call calculating dynamic stateinfo
1972 //don't calculate dynamic state and don't add to block cache (since it won't have dynamic state calculated).
1973 //this ensures that it's impossible for dynamic state properties to recursively depend on each other.
1974 $addToCache = false;
1975 }else{
1976 $this->inDynamicStateRecalculation = true;
1977 $replacement = $block->readStateFromWorld();
1978 if($replacement !== $block){
1979 $replacement->position($this, $x, $y, $z);
1980 $block = $replacement;
1981 }
1982 $this->inDynamicStateRecalculation = false;
1983 }
1984
1985 if($addToCache && $relativeBlockHash !== null){
1986 $this->blockCache[$chunkHash][$relativeBlockHash] = $block;
1987
1988 if(++$this->blockCacheSize >= self::BLOCK_CACHE_SIZE_CAP){
1989 $this->trimBlockCache();
1990 }
1991 }
1992
1993 return $block;
1994 }
1995
2001 public function setBlock(Vector3 $pos, Block $block, bool $update = true) : void{
2002 $this->setBlockAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z), $block, $update);
2003 }
2004
2013 public function setBlockAt(int $x, int $y, int $z, Block $block, bool $update = true) : void{
2014 if(!$this->isInWorld($x, $y, $z)){
2015 throw new \InvalidArgumentException("Pos x=$x,y=$y,z=$z is outside of the world bounds");
2016 }
2017 $chunkX = $x >> Chunk::COORD_BIT_SIZE;
2018 $chunkZ = $z >> Chunk::COORD_BIT_SIZE;
2019 if($this->loadChunk($chunkX, $chunkZ) === null){ //current expected behaviour is to try to load the terrain synchronously
2020 throw new WorldException("Cannot set a block in un-generated terrain");
2021 }
2022
2023 //TODO: this computes state ID twice (we do it again in writeStateToWorld()). Not great for performance :(
2024 $stateId = $block->getStateId();
2025 if(!$this->blockStateRegistry->hasStateId($stateId)){
2026 throw new \LogicException("Block state ID not known to RuntimeBlockStateRegistry (probably not registered)");
2027 }
2028 if(!GlobalBlockStateHandlers::getSerializer()->isRegistered($block)){
2029 throw new \LogicException("Block not registered with GlobalBlockStateHandlers serializer");
2030 }
2031
2032 $this->timings->setBlock->startTiming();
2033
2034 $this->unlockChunk($chunkX, $chunkZ, null);
2035
2036 $block = clone $block;
2037
2038 $block->position($this, $x, $y, $z);
2039 $block->writeStateToWorld();
2040 $pos = new Vector3($x, $y, $z);
2041
2042 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2043 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
2044
2045 unset($this->blockCache[$chunkHash][$relativeBlockHash]);
2046 $this->blockCacheSize--;
2047 unset($this->blockCollisionBoxCache[$chunkHash][$relativeBlockHash]);
2048 //blocks like fences have collision boxes that reach into neighbouring blocks, so we need to invalidate the
2049 //caches for those blocks as well
2050 foreach(Facing::OFFSET as [$offsetX, $offsetY, $offsetZ]){
2051 $sideChunkPosHash = World::chunkHash(($x + $offsetX) >> Chunk::COORD_BIT_SIZE, ($z + $offsetZ) >> Chunk::COORD_BIT_SIZE);
2052 $sideChunkBlockHash = World::chunkBlockHash($x + $offsetX, $y + $offsetY, $z + $offsetZ);
2053 unset($this->blockCollisionBoxCache[$sideChunkPosHash][$sideChunkBlockHash]);
2054 }
2055
2056 if(!isset($this->changedBlocks[$chunkHash])){
2057 $this->changedBlocks[$chunkHash] = [];
2058 }
2059 $this->changedBlocks[$chunkHash][$relativeBlockHash] = $pos;
2060
2061 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2062 $listener->onBlockChanged($pos);
2063 }
2064
2065 if($update){
2066 $this->updateAllLight($x, $y, $z);
2067 $this->internalNotifyNeighbourBlockUpdate($x, $y, $z);
2068 }
2069
2070 $this->timings->setBlock->stopTiming();
2071 }
2072
2073 public function dropItem(Vector3 $source, Item $item, ?Vector3 $motion = null, int $delay = 10) : ?ItemEntity{
2074 if($item->isNull()){
2075 return null;
2076 }
2077
2078 $itemEntity = new ItemEntity(Location::fromObject($source, $this, Utils::getRandomFloat() * 360, 0), $item);
2079
2080 $itemEntity->setPickupDelay($delay);
2081 $itemEntity->setMotion($motion ?? new Vector3(Utils::getRandomFloat() * 0.2 - 0.1, 0.2, Utils::getRandomFloat() * 0.2 - 0.1));
2082 $itemEntity->spawnToAll();
2083
2084 return $itemEntity;
2085 }
2086
2093 public function dropExperience(Vector3 $pos, int $amount) : array{
2094 $orbs = [];
2095
2096 foreach(ExperienceOrb::splitIntoOrbSizes($amount) as $split){
2097 $orb = new ExperienceOrb(Location::fromObject($pos, $this, Utils::getRandomFloat() * 360, 0), $split);
2098
2099 $orb->setMotion(new Vector3((Utils::getRandomFloat() * 0.2 - 0.1) * 2, Utils::getRandomFloat() * 0.4, (Utils::getRandomFloat() * 0.2 - 0.1) * 2));
2100 $orb->spawnToAll();
2101
2102 $orbs[] = $orb;
2103 }
2104
2105 return $orbs;
2106 }
2107
2116 public function useBreakOn(Vector3 $vector, ?Item &$item = null, ?Player $player = null, bool $createParticles = false, array &$returnedItems = []) : bool{
2117 $vector = $vector->floor();
2118
2119 $chunkX = $vector->getFloorX() >> Chunk::COORD_BIT_SIZE;
2120 $chunkZ = $vector->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2121 if(!$this->isChunkLoaded($chunkX, $chunkZ) || $this->isChunkLocked($chunkX, $chunkZ)){
2122 return false;
2123 }
2124
2125 $target = $this->getBlock($vector);
2126 $affectedBlocks = $target->getAffectedBlocks();
2127
2128 if($item === null){
2129 $item = VanillaItems::AIR();
2130 }
2131
2132 $drops = [];
2133 if($player === null || $player->hasFiniteResources()){
2134 $drops = array_merge(...array_map(fn(Block $block) => $block->getDrops($item), $affectedBlocks));
2135 }
2136
2137 $xpDrop = 0;
2138 if($player !== null && $player->hasFiniteResources()){
2139 $xpDrop = array_sum(array_map(fn(Block $block) => $block->getXpDropForTool($item), $affectedBlocks));
2140 }
2141
2142 if($player !== null){
2143 $ev = new BlockBreakEvent($player, $target, $item, $player->isCreative(), $drops, $xpDrop);
2144
2145 if($target instanceof Air || ($player->isSurvival() && !$target->getBreakInfo()->isBreakable()) || $player->isSpectator()){
2146 $ev->cancel();
2147 }
2148
2149 if($player->isAdventure(true) && !$ev->isCancelled()){
2150 $canBreak = false;
2151 $itemParser = LegacyStringToItemParser::getInstance();
2152 foreach($item->getCanDestroy() as $v){
2153 $entry = $itemParser->parse($v);
2154 if($entry->getBlock()->hasSameTypeId($target)){
2155 $canBreak = true;
2156 break;
2157 }
2158 }
2159
2160 if(!$canBreak){
2161 $ev->cancel();
2162 }
2163 }
2164
2165 $ev->call();
2166 if($ev->isCancelled()){
2167 return false;
2168 }
2169
2170 $drops = $ev->getDrops();
2171 $xpDrop = $ev->getXpDropAmount();
2172
2173 }elseif(!$target->getBreakInfo()->isBreakable()){
2174 return false;
2175 }
2176
2177 foreach($affectedBlocks as $t){
2178 $this->destroyBlockInternal($t, $item, $player, $createParticles, $returnedItems);
2179 }
2180
2181 $item->onDestroyBlock($target, $returnedItems);
2182
2183 if(count($drops) > 0){
2184 $dropPos = $vector->add(0.5, 0.5, 0.5);
2185 foreach($drops as $drop){
2186 if(!$drop->isNull()){
2187 $this->dropItem($dropPos, $drop);
2188 }
2189 }
2190 }
2191
2192 if($xpDrop > 0){
2193 $this->dropExperience($vector->add(0.5, 0.5, 0.5), $xpDrop);
2194 }
2195
2196 return true;
2197 }
2198
2202 private function destroyBlockInternal(Block $target, Item $item, ?Player $player, bool $createParticles, array &$returnedItems) : void{
2203 if($createParticles){
2204 $this->addParticle($target->getPosition()->add(0.5, 0.5, 0.5), new BlockBreakParticle($target));
2205 }
2206
2207 $target->onBreak($item, $player, $returnedItems);
2208
2209 $tile = $this->getTile($target->getPosition());
2210 if($tile !== null){
2211 $tile->onBlockDestroyed();
2212 }
2213 }
2214
2222 public function useItemOn(Vector3 $vector, Item &$item, Facing $face, ?Vector3 $clickVector = null, ?Player $player = null, bool $playSound = false, array &$returnedItems = []) : bool{
2223 $blockClicked = $this->getBlock($vector);
2224 $blockReplace = $blockClicked->getSide($face);
2225
2226 if($clickVector === null){
2227 $clickVector = new Vector3(0.0, 0.0, 0.0);
2228 }else{
2229 $clickVector = new Vector3(
2230 min(1.0, max(0.0, $clickVector->x)),
2231 min(1.0, max(0.0, $clickVector->y)),
2232 min(1.0, max(0.0, $clickVector->z))
2233 );
2234 }
2235
2236 if(!$this->isInWorld($blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z)){
2237 //TODO: build height limit messages for custom world heights and mcregion cap
2238 return false;
2239 }
2240 $chunkX = $blockReplace->getPosition()->getFloorX() >> Chunk::COORD_BIT_SIZE;
2241 $chunkZ = $blockReplace->getPosition()->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2242 if(!$this->isChunkLoaded($chunkX, $chunkZ) || $this->isChunkLocked($chunkX, $chunkZ)){
2243 return false;
2244 }
2245
2246 if($blockClicked->getTypeId() === BlockTypeIds::AIR){
2247 return false;
2248 }
2249
2250 if($player !== null){
2251 $ev = new PlayerInteractEvent($player, $item, $blockClicked, $clickVector, $face, PlayerInteractEvent::RIGHT_CLICK_BLOCK);
2252 if($player->isSneaking()){
2253 $ev->setUseItem(false);
2254 $ev->setUseBlock($item->isNull()); //opening doors is still possible when sneaking if using an empty hand
2255 }
2256 if($player->isSpectator()){
2257 $ev->cancel(); //set it to cancelled so plugins can bypass this
2258 }
2259
2260 $ev->call();
2261 if(!$ev->isCancelled()){
2262 if($ev->useBlock() && $blockClicked->onInteract($item, $face, $clickVector, $player, $returnedItems)){
2263 return true;
2264 }
2265
2266 if($ev->useItem()){
2267 $result = $item->onInteractBlock($player, $blockReplace, $blockClicked, $face, $clickVector, $returnedItems);
2268 if($result !== ItemUseResult::NONE){
2269 return $result === ItemUseResult::SUCCESS;
2270 }
2271 }
2272 }else{
2273 return false;
2274 }
2275 }elseif($blockClicked->onInteract($item, $face, $clickVector, $player, $returnedItems)){
2276 return true;
2277 }
2278
2279 if($item->isNull() || !$item->canBePlaced()){
2280 return false;
2281 }
2282
2283 //TODO: while passing Facing::UP mimics the vanilla behaviour with replaceable blocks, we should really pass
2284 //some other value like NULL and let place() deal with it. This will look like a bug to anyone who doesn't know
2285 //about the vanilla behaviour.
2286 $tx =
2287 $item->getPlacementTransaction($blockClicked, $blockClicked, Facing::UP, $clickVector, $player) ??
2288 $item->getPlacementTransaction($blockReplace, $blockClicked, $face, $clickVector, $player);
2289 if($tx === null){
2290 //no placement options available
2291 return false;
2292 }
2293
2294 foreach($tx->getBlocks() as [$x, $y, $z, $block]){
2295 $block->position($this, $x, $y, $z);
2296 foreach($block->getCollisionBoxes() as $collisionBox){
2297 if(count($this->getCollidingEntities($collisionBox)) > 0){
2298 return false; //Entity in block
2299 }
2300 }
2301 }
2302
2303 if($player !== null){
2304 $ev = new BlockPlaceEvent($player, $tx, $blockClicked, $item);
2305 if($player->isSpectator()){
2306 $ev->cancel();
2307 }
2308
2309 if($player->isAdventure(true) && !$ev->isCancelled()){
2310 $canPlace = false;
2311 $itemParser = LegacyStringToItemParser::getInstance();
2312 foreach($item->getCanPlaceOn() as $v){
2313 $entry = $itemParser->parse($v);
2314 if($entry->getBlock()->hasSameTypeId($blockClicked)){
2315 $canPlace = true;
2316 break;
2317 }
2318 }
2319
2320 if(!$canPlace){
2321 $ev->cancel();
2322 }
2323 }
2324
2325 $ev->call();
2326 if($ev->isCancelled()){
2327 return false;
2328 }
2329 }
2330
2331 if(!$tx->apply()){
2332 return false;
2333 }
2334 $first = true;
2335 foreach($tx->getBlocks() as [$x, $y, $z, $_]){
2336 $tile = $this->getTileAt($x, $y, $z);
2337 if($tile !== null){
2338 //TODO: seal this up inside block placement
2339 $tile->copyDataFromItem($item);
2340 }
2341
2342 $placed = $this->getBlockAt($x, $y, $z);
2343 $placed->onPostPlace();
2344 if($first && $playSound){
2345 $this->addSound($placed->getPosition(), new BlockPlaceSound($placed));
2346 }
2347 $first = false;
2348 }
2349
2350 $item->pop();
2351
2352 return true;
2353 }
2354
2355 public function getEntity(int $entityId) : ?Entity{
2356 return $this->entities[$entityId] ?? null;
2357 }
2358
2365 public function getEntities() : array{
2366 return $this->entities;
2367 }
2368
2379 public function getCollidingEntities(AxisAlignedBB $bb, ?Entity $entity = null) : array{
2380 $nearby = [];
2381
2382 foreach($this->getNearbyEntities($bb, $entity) as $ent){
2383 if($ent->canBeCollidedWith() && ($entity === null || $entity->canCollideWith($ent))){
2384 $nearby[] = $ent;
2385 }
2386 }
2387
2388 return $nearby;
2389 }
2390
2397 public function getNearbyEntities(AxisAlignedBB $bb, ?Entity $entity = null) : array{
2398 $nearby = [];
2399
2400 $minX = ((int) floor($bb->minX - 2)) >> Chunk::COORD_BIT_SIZE;
2401 $maxX = ((int) floor($bb->maxX + 2)) >> Chunk::COORD_BIT_SIZE;
2402 $minZ = ((int) floor($bb->minZ - 2)) >> Chunk::COORD_BIT_SIZE;
2403 $maxZ = ((int) floor($bb->maxZ + 2)) >> Chunk::COORD_BIT_SIZE;
2404
2405 for($x = $minX; $x <= $maxX; ++$x){
2406 for($z = $minZ; $z <= $maxZ; ++$z){
2407 foreach($this->getChunkEntities($x, $z) as $ent){
2408 if($ent !== $entity && $ent->boundingBox->intersectsWith($bb)){
2409 $nearby[] = $ent;
2410 }
2411 }
2412 }
2413 }
2414
2415 return $nearby;
2416 }
2417
2429 public function getNearestEntity(Vector3 $pos, float $maxDistance, string $entityType = Entity::class, bool $includeDead = false) : ?Entity{
2430 assert(is_a($entityType, Entity::class, true));
2431
2432 $minX = ((int) floor($pos->x - $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2433 $maxX = ((int) floor($pos->x + $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2434 $minZ = ((int) floor($pos->z - $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2435 $maxZ = ((int) floor($pos->z + $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2436
2437 $currentTargetDistSq = $maxDistance ** 2;
2438
2443 $currentTarget = null;
2444
2445 for($x = $minX; $x <= $maxX; ++$x){
2446 for($z = $minZ; $z <= $maxZ; ++$z){
2447 foreach($this->getChunkEntities($x, $z) as $entity){
2448 if(!($entity instanceof $entityType) || $entity->isFlaggedForDespawn() || (!$includeDead && !$entity->isAlive())){
2449 continue;
2450 }
2451 $distSq = $entity->getPosition()->distanceSquared($pos);
2452 if($distSq < $currentTargetDistSq){
2453 $currentTargetDistSq = $distSq;
2454 $currentTarget = $entity;
2455 }
2456 }
2457 }
2458 }
2459
2460 return $currentTarget;
2461 }
2462
2469 public function getPlayers() : array{
2470 return $this->players;
2471 }
2472
2479 public function getTile(Vector3 $pos) : ?Tile{
2480 return $this->getTileAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z));
2481 }
2482
2486 public function getTileAt(int $x, int $y, int $z) : ?Tile{
2487 return ($chunk = $this->loadChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null ? $chunk->getTile($x & Chunk::COORD_MASK, $y, $z & Chunk::COORD_MASK) : null;
2488 }
2489
2490 public function getBiomeId(int $x, int $y, int $z) : int{
2491 if(($chunk = $this->loadChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null){
2492 return $chunk->getBiomeId($x & Chunk::COORD_MASK, $y & Chunk::COORD_MASK, $z & Chunk::COORD_MASK);
2493 }
2494 return BiomeIds::OCEAN; //TODO: this should probably throw instead (terrain not generated yet)
2495 }
2496
2497 public function getBiome(int $x, int $y, int $z) : Biome{
2498 return BiomeRegistry::getInstance()->getBiome($this->getBiomeId($x, $y, $z));
2499 }
2500
2501 public function setBiomeId(int $x, int $y, int $z, int $biomeId) : void{
2502 $chunkX = $x >> Chunk::COORD_BIT_SIZE;
2503 $chunkZ = $z >> Chunk::COORD_BIT_SIZE;
2504 $this->unlockChunk($chunkX, $chunkZ, null);
2505 if(($chunk = $this->loadChunk($chunkX, $chunkZ)) !== null){
2506 $chunk->setBiomeId($x & Chunk::COORD_MASK, $y & Chunk::COORD_MASK, $z & Chunk::COORD_MASK, $biomeId);
2507 }else{
2508 //if we allowed this, the modifications would be lost when the chunk is created
2509 throw new WorldException("Cannot set biome in a non-generated chunk");
2510 }
2511 }
2512
2517 public function getLoadedChunks() : array{
2518 return $this->chunks;
2519 }
2520
2521 public function getChunk(int $chunkX, int $chunkZ) : ?Chunk{
2522 return $this->chunks[World::chunkHash($chunkX, $chunkZ)] ?? null;
2523 }
2524
2529 public function getChunkEntities(int $chunkX, int $chunkZ) : array{
2530 return $this->entitiesByChunk[World::chunkHash($chunkX, $chunkZ)] ?? [];
2531 }
2532
2536 public function getOrLoadChunkAtPosition(Vector3 $pos) : ?Chunk{
2537 return $this->loadChunk($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2538 }
2539
2546 public function getAdjacentChunks(int $x, int $z) : array{
2547 $result = [];
2548 for($xx = -1; $xx <= 1; ++$xx){
2549 for($zz = -1; $zz <= 1; ++$zz){
2550 if($xx === 0 && $zz === 0){
2551 continue; //center chunk
2552 }
2553 $result[World::chunkHash($xx, $zz)] = $this->loadChunk($x + $xx, $z + $zz);
2554 }
2555 }
2556
2557 return $result;
2558 }
2559
2574 public function lockChunk(int $chunkX, int $chunkZ, ChunkLockId $lockId) : void{
2575 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2576 if(isset($this->chunkLock[$chunkHash])){
2577 throw new \InvalidArgumentException("Chunk $chunkX $chunkZ is already locked");
2578 }
2579 $this->chunkLock[$chunkHash] = $lockId;
2580 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
2581 }
2582
2591 public function unlockChunk(int $chunkX, int $chunkZ, ?ChunkLockId $lockId) : bool{
2592 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2593 if(isset($this->chunkLock[$chunkHash]) && ($lockId === null || $this->chunkLock[$chunkHash] === $lockId)){
2594 unset($this->chunkLock[$chunkHash]);
2595 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
2596 return true;
2597 }
2598 return false;
2599 }
2600
2606 public function isChunkLocked(int $chunkX, int $chunkZ) : bool{
2607 return isset($this->chunkLock[World::chunkHash($chunkX, $chunkZ)]);
2608 }
2609
2610 public function setChunk(int $chunkX, int $chunkZ, Chunk $chunk) : void{
2611 foreach($chunk->getSubChunks() as $subChunk){
2612 foreach($subChunk->getBlockLayers() as $blockLayer){
2613 foreach($blockLayer->getPalette() as $blockStateId){
2614 if(!$this->blockStateRegistry->hasStateId($blockStateId)){
2615 throw new \InvalidArgumentException("Provided chunk contains unknown/unregistered blocks (found unknown state ID $blockStateId)");
2616 }
2617 }
2618 }
2619 }
2620
2621 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2622 $oldChunk = $this->loadChunk($chunkX, $chunkZ);
2623 if($oldChunk !== null && $oldChunk !== $chunk){
2624 $deletedTiles = 0;
2625 $transferredTiles = 0;
2626 foreach($oldChunk->getTiles() as $oldTile){
2627 $tilePosition = $oldTile->getPosition();
2628 $localX = $tilePosition->getFloorX() & Chunk::COORD_MASK;
2629 $localY = $tilePosition->getFloorY();
2630 $localZ = $tilePosition->getFloorZ() & Chunk::COORD_MASK;
2631
2632 $newBlock = $this->blockStateRegistry->fromStateId($chunk->getBlockStateId($localX, $localY, $localZ));
2633 $expectedTileClass = $newBlock->getIdInfo()->getTileClass();
2634 if(
2635 $expectedTileClass === null || //new block doesn't expect a tile
2636 !($oldTile instanceof $expectedTileClass) || //new block expects a different tile
2637 (($newTile = $chunk->getTile($localX, $localY, $localZ)) !== null && $newTile !== $oldTile) //new chunk already has a different tile
2638 ){
2639 $oldTile->close();
2640 $deletedTiles++;
2641 }else{
2642 $transferredTiles++;
2643 $chunk->addTile($oldTile);
2644 $oldChunk->removeTile($oldTile);
2645 }
2646 }
2647 if($deletedTiles > 0 || $transferredTiles > 0){
2648 $this->logger->debug("Replacement of chunk $chunkX $chunkZ caused deletion of $deletedTiles obsolete/conflicted tiles, and transfer of $transferredTiles");
2649 }
2650 }
2651
2652 $this->chunks[$chunkHash] = $chunk;
2653 unset($this->knownUngeneratedChunks[$chunkHash]);
2654
2655 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
2656 unset($this->blockCache[$chunkHash]);
2657 unset($this->blockCollisionBoxCache[$chunkHash]);
2658 unset($this->changedBlocks[$chunkHash]);
2659 $chunk->setTerrainDirty();
2660 $this->markTickingChunkForRecheck($chunkX, $chunkZ); //this replacement chunk may not meet the conditions for ticking
2661
2662 if(!$this->isChunkInUse($chunkX, $chunkZ)){
2663 $this->unloadChunkRequest($chunkX, $chunkZ);
2664 }
2665
2666 if($oldChunk === null){
2667 if(ChunkLoadEvent::hasHandlers()){
2668 (new ChunkLoadEvent($this, $chunkX, $chunkZ, $chunk, true))->call();
2669 }
2670
2671 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2672 $listener->onChunkLoaded($chunkX, $chunkZ, $chunk);
2673 }
2674 }else{
2675 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2676 $listener->onChunkChanged($chunkX, $chunkZ, $chunk);
2677 }
2678 }
2679
2680 for($cX = -1; $cX <= 1; ++$cX){
2681 for($cZ = -1; $cZ <= 1; ++$cZ){
2682 foreach($this->getChunkEntities($chunkX + $cX, $chunkZ + $cZ) as $entity){
2683 $entity->onNearbyBlockChange();
2684 }
2685 }
2686 }
2687 }
2688
2695 public function getHighestBlockAt(int $x, int $z) : ?int{
2696 if(($chunk = $this->loadChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null){
2697 return $chunk->getHighestBlockAt($x & Chunk::COORD_MASK, $z & Chunk::COORD_MASK);
2698 }
2699 throw new WorldException("Cannot get highest block in an ungenerated chunk");
2700 }
2701
2705 public function isInLoadedTerrain(Vector3 $pos) : bool{
2706 return $this->isChunkLoaded($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2707 }
2708
2709 public function isChunkLoaded(int $x, int $z) : bool{
2710 return isset($this->chunks[World::chunkHash($x, $z)]);
2711 }
2712
2713 public function isChunkGenerated(int $x, int $z) : bool{
2714 return $this->loadChunk($x, $z) !== null;
2715 }
2716
2717 public function isChunkPopulated(int $x, int $z) : bool{
2718 $chunk = $this->loadChunk($x, $z);
2719 return $chunk !== null && $chunk->isPopulated();
2720 }
2721
2725 public function getSpawnLocation() : Position{
2726 return Position::fromObject($this->provider->getWorldData()->getSpawn(), $this);
2727 }
2728
2732 public function setSpawnLocation(Vector3 $pos) : void{
2733 $previousSpawn = $this->getSpawnLocation();
2734 $this->provider->getWorldData()->setSpawn($pos);
2735 (new SpawnChangeEvent($this, $previousSpawn))->call();
2736
2737 $location = Position::fromObject($pos, $this);
2738 foreach($this->players as $player){
2739 $player->getNetworkSession()->syncWorldSpawnPoint($location);
2740 }
2741 }
2742
2746 public function addEntity(Entity $entity) : void{
2747 if($entity->isClosed()){
2748 throw new \InvalidArgumentException("Attempted to add a garbage closed Entity to world");
2749 }
2750 if($entity->getWorld() !== $this){
2751 throw new \InvalidArgumentException("Invalid Entity world");
2752 }
2753 if(array_key_exists($entity->getId(), $this->entities)){
2754 if($this->entities[$entity->getId()] === $entity){
2755 throw new \InvalidArgumentException("Entity " . $entity->getId() . " has already been added to this world");
2756 }else{
2757 throw new AssumptionFailedError("Found two different entities sharing entity ID " . $entity->getId());
2758 }
2759 }
2760 if(!EntityFactory::getInstance()->isRegistered($entity::class) && !$entity instanceof Player){
2761 //canSaveWithChunk is mutable, so that means it could be toggled after adding the entity and cause a crash
2762 //later on. Better we just force all entities to have a save ID, even if it might not be needed.
2763 throw new \LogicException("Entity " . $entity::class . " is not registered for a save ID in EntityFactory");
2764 }
2765 $pos = $entity->getPosition()->asVector3();
2766 $this->entitiesByChunk[World::chunkHash($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE)][$entity->getId()] = $entity;
2767 $this->entityLastKnownPositions[$entity->getId()] = $pos;
2768
2769 if($entity instanceof Player){
2770 $this->players[$entity->getId()] = $entity;
2771 }
2772 $this->entities[$entity->getId()] = $entity;
2773 }
2774
2780 public function removeEntity(Entity $entity) : void{
2781 if($entity->getWorld() !== $this){
2782 throw new \InvalidArgumentException("Invalid Entity world");
2783 }
2784 if(!array_key_exists($entity->getId(), $this->entities)){
2785 throw new \InvalidArgumentException("Entity is not tracked by this world (possibly already removed?)");
2786 }
2787 $pos = $this->entityLastKnownPositions[$entity->getId()];
2788 $chunkHash = World::chunkHash($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2789 if(isset($this->entitiesByChunk[$chunkHash][$entity->getId()])){
2790 if(count($this->entitiesByChunk[$chunkHash]) === 1){
2791 unset($this->entitiesByChunk[$chunkHash]);
2792 }else{
2793 unset($this->entitiesByChunk[$chunkHash][$entity->getId()]);
2794 }
2795 }
2796 unset($this->entityLastKnownPositions[$entity->getId()]);
2797
2798 if($entity instanceof Player){
2799 unset($this->players[$entity->getId()]);
2800 $this->checkSleep();
2801 }
2802
2803 unset($this->entities[$entity->getId()]);
2804 unset($this->updateEntities[$entity->getId()]);
2805 }
2806
2810 public function onEntityMoved(Entity $entity) : void{
2811 if(!array_key_exists($entity->getId(), $this->entityLastKnownPositions)){
2812 //this can happen if the entity was teleported before addEntity() was called
2813 return;
2814 }
2815 $oldPosition = $this->entityLastKnownPositions[$entity->getId()];
2816 $newPosition = $entity->getPosition();
2817
2818 $oldChunkX = $oldPosition->getFloorX() >> Chunk::COORD_BIT_SIZE;
2819 $oldChunkZ = $oldPosition->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2820 $newChunkX = $newPosition->getFloorX() >> Chunk::COORD_BIT_SIZE;
2821 $newChunkZ = $newPosition->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2822
2823 if($oldChunkX !== $newChunkX || $oldChunkZ !== $newChunkZ){
2824 $oldChunkHash = World::chunkHash($oldChunkX, $oldChunkZ);
2825 if(isset($this->entitiesByChunk[$oldChunkHash][$entity->getId()])){
2826 if(count($this->entitiesByChunk[$oldChunkHash]) === 1){
2827 unset($this->entitiesByChunk[$oldChunkHash]);
2828 }else{
2829 unset($this->entitiesByChunk[$oldChunkHash][$entity->getId()]);
2830 }
2831 }
2832
2833 $newViewers = $this->getViewersForPosition($newPosition);
2834 foreach($entity->getViewers() as $player){
2835 if(!isset($newViewers[spl_object_id($player)])){
2836 $entity->despawnFrom($player);
2837 }else{
2838 unset($newViewers[spl_object_id($player)]);
2839 }
2840 }
2841 foreach($newViewers as $player){
2842 $entity->spawnTo($player);
2843 }
2844
2845 $newChunkHash = World::chunkHash($newChunkX, $newChunkZ);
2846 $this->entitiesByChunk[$newChunkHash][$entity->getId()] = $entity;
2847 }
2848 $this->entityLastKnownPositions[$entity->getId()] = $newPosition->asVector3();
2849 }
2850
2855 public function addTile(Tile $tile) : void{
2856 if($tile->isClosed()){
2857 throw new \InvalidArgumentException("Attempted to add a garbage closed Tile to world");
2858 }
2859 $pos = $tile->getPosition();
2860 if(!$pos->isValid() || $pos->getWorld() !== $this){
2861 throw new \InvalidArgumentException("Invalid Tile world");
2862 }
2863 if(!$this->isInWorld($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ())){
2864 throw new \InvalidArgumentException("Tile position is outside the world bounds");
2865 }
2866 if(!TileFactory::getInstance()->isRegistered($tile::class)){
2867 throw new \LogicException("Tile " . $tile::class . " is not registered for a save ID in TileFactory");
2868 }
2869
2870 $chunkX = $pos->getFloorX() >> Chunk::COORD_BIT_SIZE;
2871 $chunkZ = $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2872
2873 if(isset($this->chunks[$hash = World::chunkHash($chunkX, $chunkZ)])){
2874 $this->chunks[$hash]->addTile($tile);
2875 }else{
2876 throw new \InvalidArgumentException("Attempted to create tile " . get_class($tile) . " in unloaded chunk $chunkX $chunkZ");
2877 }
2878
2879 //delegate tile ticking to the corresponding block
2880 $this->scheduleDelayedBlockUpdate($pos->asVector3(), 1);
2881 }
2882
2887 public function removeTile(Tile $tile) : void{
2888 $pos = $tile->getPosition();
2889 if(!$pos->isValid() || $pos->getWorld() !== $this){
2890 throw new \InvalidArgumentException("Invalid Tile world");
2891 }
2892
2893 $chunkX = $pos->getFloorX() >> Chunk::COORD_BIT_SIZE;
2894 $chunkZ = $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2895
2896 if(isset($this->chunks[$hash = World::chunkHash($chunkX, $chunkZ)])){
2897 $this->chunks[$hash]->removeTile($tile);
2898 }
2899 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2900 $listener->onBlockChanged($pos->asVector3());
2901 }
2902 }
2903
2904 public function isChunkInUse(int $x, int $z) : bool{
2905 return isset($this->chunkLoaders[$index = World::chunkHash($x, $z)]) && count($this->chunkLoaders[$index]) > 0;
2906 }
2907
2914 public function loadChunk(int $x, int $z) : ?Chunk{
2915 if(isset($this->chunks[$chunkHash = World::chunkHash($x, $z)])){
2916 return $this->chunks[$chunkHash];
2917 }
2918 if(isset($this->knownUngeneratedChunks[$chunkHash])){
2919 return null;
2920 }
2921
2922 $this->timings->syncChunkLoad->startTiming();
2923
2924 $this->cancelUnloadChunkRequest($x, $z);
2925
2926 $this->timings->syncChunkLoadData->startTiming();
2927
2928 $loadedChunkData = null;
2929
2930 try{
2931 $loadedChunkData = $this->provider->loadChunk($x, $z);
2932 }catch(CorruptedChunkException $e){
2933 $this->logger->critical("Failed to load chunk x=$x z=$z: " . $e->getMessage());
2934 }
2935
2936 $this->timings->syncChunkLoadData->stopTiming();
2937
2938 if($loadedChunkData === null){
2939 $this->timings->syncChunkLoad->stopTiming();
2940 $this->knownUngeneratedChunks[$chunkHash] = true;
2941 return null;
2942 }
2943
2944 $chunkData = $loadedChunkData->getData();
2945 $chunk = new Chunk($chunkData->getSubChunks(), $chunkData->isPopulated());
2946 if(!$loadedChunkData->isUpgraded()){
2947 $chunk->clearTerrainDirtyFlags();
2948 }else{
2949 $this->logger->debug("Chunk $x $z has been upgraded, will be saved at the next autosave opportunity");
2950 }
2951 $this->chunks[$chunkHash] = $chunk;
2952
2953 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
2954 unset($this->blockCache[$chunkHash]);
2955 unset($this->blockCollisionBoxCache[$chunkHash]);
2956
2957 $this->initChunk($x, $z, $chunkData, $chunk);
2958
2959 if(ChunkLoadEvent::hasHandlers()){
2960 (new ChunkLoadEvent($this, $x, $z, $this->chunks[$chunkHash], false))->call();
2961 }
2962
2963 if(!$this->isChunkInUse($x, $z)){
2964 $this->logger->debug("Newly loaded chunk $x $z has no loaders registered, will be unloaded at next available opportunity");
2965 $this->unloadChunkRequest($x, $z);
2966 }
2967 foreach($this->getChunkListeners($x, $z) as $listener){
2968 $listener->onChunkLoaded($x, $z, $this->chunks[$chunkHash]);
2969 }
2970 $this->markTickingChunkForRecheck($x, $z); //tickers may have been registered before the chunk was loaded
2971
2972 $this->timings->syncChunkLoad->stopTiming();
2973
2974 return $this->chunks[$chunkHash];
2975 }
2976
2977 private function initChunk(int $chunkX, int $chunkZ, ChunkData $chunkData, Chunk $chunk) : void{
2978 $logger = new \PrefixedLogger($this->logger, "Loading chunk $chunkX $chunkZ");
2979
2980 if(count($chunkData->getEntityNBT()) !== 0){
2981 $this->timings->syncChunkLoadEntities->startTiming();
2982 $entityFactory = EntityFactory::getInstance();
2983
2984 $deletedEntities = [];
2985 foreach($chunkData->getEntityNBT() as $k => $nbt){
2986 try{
2987 $entity = $entityFactory->createFromData($this, $nbt);
2988 }catch(SavedDataLoadingException $e){
2989 $logger->error("Bad entity data at list position $k: " . $e->getMessage());
2990 $logger->logException($e);
2991 continue;
2992 }
2993 if($entity === null){
2994 $saveIdTag = $nbt->getTag("identifier") ?? $nbt->getTag("id");
2995 $saveId = "<unknown>";
2996 if($saveIdTag instanceof StringTag){
2997 $saveId = $saveIdTag->getValue();
2998 }elseif($saveIdTag instanceof IntTag){ //legacy MCPE format
2999 $saveId = "legacy(" . $saveIdTag->getValue() . ")";
3000 }
3001 $deletedEntities[$saveId] = ($deletedEntities[$saveId] ?? 0) + 1;
3002 }
3003 //TODO: we can't prevent entities getting added to unloaded chunks if they were saved in the wrong place
3004 //here, because entities currently add themselves to the world
3005 }
3006
3007 foreach(Utils::promoteKeys($deletedEntities) as $saveId => $count){
3008 $logger->warning("Deleted unknown entity type $saveId x$count");
3009 }
3010 $this->timings->syncChunkLoadEntities->stopTiming();
3011 }
3012
3013 if(count($chunkData->getTileNBT()) !== 0){
3014 $this->timings->syncChunkLoadTileEntities->startTiming();
3015 $tileFactory = TileFactory::getInstance();
3016
3017 $deletedTiles = [];
3018 foreach($chunkData->getTileNBT() as $k => $nbt){
3019 try{
3020 $tile = $tileFactory->createFromData($this, $nbt);
3021 }catch(SavedDataLoadingException $e){
3022 $logger->error("Bad tile entity data at list position $k: " . $e->getMessage());
3023 $logger->logException($e);
3024 continue;
3025 }
3026 if($tile === null){
3027 $saveId = $nbt->getString("id", "<unknown>");
3028 $deletedTiles[$saveId] = ($deletedTiles[$saveId] ?? 0) + 1;
3029 continue;
3030 }
3031
3032 $tilePosition = $tile->getPosition();
3033 if(!$this->isChunkLoaded($tilePosition->getFloorX() >> Chunk::COORD_BIT_SIZE, $tilePosition->getFloorZ() >> Chunk::COORD_BIT_SIZE)){
3034 $logger->error("Found tile saved on wrong chunk - unable to fix due to correct chunk not loaded");
3035 }elseif(!$this->isInWorld($tilePosition->getFloorX(), $tilePosition->getFloorY(), $tilePosition->getFloorZ())){
3036 $logger->error("Cannot add tile with position outside the world bounds: x=$tilePosition->x,y=$tilePosition->y,z=$tilePosition->z");
3037 }elseif($this->getTile($tilePosition) !== null){
3038 $logger->error("Cannot add tile at x=$tilePosition->x,y=$tilePosition->y,z=$tilePosition->z: Another tile is already at that position");
3039 }else{
3040 $this->addTile($tile);
3041 }
3042 $expectedStateId = $chunk->getBlockStateId($tilePosition->getFloorX() & Chunk::COORD_MASK, $tilePosition->getFloorY(), $tilePosition->getFloorZ() & Chunk::COORD_MASK);
3043 $actualStateId = $this->getBlock($tilePosition)->getStateId();
3044 if($expectedStateId !== $actualStateId){
3045 //state ID was updated by readStateFromWorld - typically because the block pulled some data from the tile
3046 //make sure this is synced to the chunk
3047 //TODO: in the future we should pull tile reading logic out of readStateFromWorld() and do it only
3048 //when the tile is loaded - this would be cleaner and faster
3049 $chunk->setBlockStateId($tilePosition->getFloorX() & Chunk::COORD_MASK, $tilePosition->getFloorY(), $tilePosition->getFloorZ() & Chunk::COORD_MASK, $actualStateId);
3050 $this->logger->debug("Tile " . $tile::class . " at x=$tilePosition->x,y=$tilePosition->y,z=$tilePosition->z updated block state ID from $expectedStateId to $actualStateId");
3051 }
3052 }
3053
3054 foreach(Utils::promoteKeys($deletedTiles) as $saveId => $count){
3055 $logger->warning("Deleted unknown tile entity type $saveId x$count");
3056 }
3057
3058 $this->timings->syncChunkLoadTileEntities->stopTiming();
3059 }
3060 }
3061
3062 private function queueUnloadChunk(int $x, int $z) : void{
3063 $this->unloadQueue[World::chunkHash($x, $z)] = microtime(true);
3064 }
3065
3066 public function unloadChunkRequest(int $x, int $z, bool $safe = true) : bool{
3067 if(($safe && $this->isChunkInUse($x, $z)) || $this->isSpawnChunk($x, $z)){
3068 return false;
3069 }
3070
3071 $this->queueUnloadChunk($x, $z);
3072
3073 return true;
3074 }
3075
3076 public function cancelUnloadChunkRequest(int $x, int $z) : void{
3077 unset($this->unloadQueue[World::chunkHash($x, $z)]);
3078 }
3079
3080 public function unloadChunk(int $x, int $z, bool $safe = true, bool $trySave = true) : bool{
3081 if($safe && $this->isChunkInUse($x, $z)){
3082 return false;
3083 }
3084
3085 if(!$this->isChunkLoaded($x, $z)){
3086 return true;
3087 }
3088
3089 $this->timings->doChunkUnload->startTiming();
3090
3091 $chunkHash = World::chunkHash($x, $z);
3092
3093 $chunk = $this->chunks[$chunkHash] ?? null;
3094
3095 if($chunk !== null){
3096 if(ChunkUnloadEvent::hasHandlers()){
3097 $ev = new ChunkUnloadEvent($this, $x, $z, $chunk);
3098 $ev->call();
3099 if($ev->isCancelled()){
3100 $this->timings->doChunkUnload->stopTiming();
3101
3102 return false;
3103 }
3104 }
3105
3106 if($trySave && $this->getAutoSave()){
3107 $this->timings->syncChunkSave->startTiming();
3108 try{
3109 $this->provider->saveChunk($x, $z, new ChunkData(
3110 $chunk->getSubChunks(),
3111 $chunk->isPopulated(),
3112 array_map(fn(Entity $e) => $e->saveNBT(), array_values(array_filter($this->getChunkEntities($x, $z), fn(Entity $e) => $e->canSaveWithChunk()))),
3113 array_map(fn(Tile $t) => $t->saveNBT(), array_values($chunk->getTiles())),
3114 ), $chunk->getTerrainDirtyFlags());
3115 }finally{
3116 $this->timings->syncChunkSave->stopTiming();
3117 }
3118 }
3119
3120 foreach($this->getChunkListeners($x, $z) as $listener){
3121 $listener->onChunkUnloaded($x, $z, $chunk);
3122 }
3123
3124 foreach($this->getChunkEntities($x, $z) as $entity){
3125 if($entity instanceof Player){
3126 continue;
3127 }
3128 $entity->close();
3129 }
3130
3131 $chunk->onUnload();
3132 }
3133
3134 unset($this->chunks[$chunkHash]);
3135 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
3136 unset($this->blockCache[$chunkHash]);
3137 unset($this->blockCollisionBoxCache[$chunkHash]);
3138 unset($this->changedBlocks[$chunkHash]);
3139 unset($this->registeredTickingChunks[$chunkHash]);
3140 $this->markTickingChunkForRecheck($x, $z);
3141
3142 if(array_key_exists($chunkHash, $this->chunkPopulationRequestMap)){
3143 $this->logger->debug("Rejecting population promise for chunk $x $z");
3144 $this->chunkPopulationRequestMap[$chunkHash]->reject();
3145 unset($this->chunkPopulationRequestMap[$chunkHash]);
3146 if(isset($this->activeChunkPopulationTasks[$chunkHash])){
3147 $this->logger->debug("Marking population task for chunk $x $z as orphaned");
3148 $this->activeChunkPopulationTasks[$chunkHash] = false;
3149 }
3150 }
3151
3152 $this->timings->doChunkUnload->stopTiming();
3153
3154 return true;
3155 }
3156
3160 public function isSpawnChunk(int $X, int $Z) : bool{
3161 $spawn = $this->getSpawnLocation();
3162 $spawnX = $spawn->x >> Chunk::COORD_BIT_SIZE;
3163 $spawnZ = $spawn->z >> Chunk::COORD_BIT_SIZE;
3164
3165 return abs($X - $spawnX) <= 1 && abs($Z - $spawnZ) <= 1;
3166 }
3167
3175 public function requestSafeSpawn(?Vector3 $spawn = null) : Promise{
3177 $resolver = new PromiseResolver();
3178 $spawn ??= $this->getSpawnLocation();
3179 /*
3180 * TODO: this relies on the assumption that getSafeSpawn() will only alter the Y coordinate of the provided
3181 * position, which is currently OK, but might be a problem in the future.
3182 */
3183 $this->requestChunkPopulation($spawn->getFloorX() >> Chunk::COORD_BIT_SIZE, $spawn->getFloorZ() >> Chunk::COORD_BIT_SIZE, null)->onCompletion(
3184 function() use ($spawn, $resolver) : void{
3185 $spawn = $this->getSafeSpawn($spawn);
3186 $resolver->resolve($spawn);
3187 },
3188 function() use ($resolver) : void{
3189 $resolver->reject();
3190 }
3191 );
3192
3193 return $resolver->getPromise();
3194 }
3195
3202 public function getSafeSpawn(?Vector3 $spawn = null) : Position{
3203 if(!($spawn instanceof Vector3) || $spawn->y <= $this->minY){
3204 $spawn = $this->getSpawnLocation();
3205 }
3206
3207 $max = $this->maxY;
3208 $v = $spawn->floor();
3209 $chunk = $this->getOrLoadChunkAtPosition($v);
3210 if($chunk === null){
3211 throw new WorldException("Cannot find a safe spawn point in non-generated terrain");
3212 }
3213 $x = (int) $v->x;
3214 $z = (int) $v->z;
3215 $y = (int) min($max - 2, $v->y);
3216 $wasAir = $this->getBlockAt($x, $y - 1, $z)->getTypeId() === BlockTypeIds::AIR; //TODO: bad hack, clean up
3217 for(; $y > $this->minY; --$y){
3218 if($this->getBlockAt($x, $y, $z)->isFullCube()){
3219 if($wasAir){
3220 $y++;
3221 }
3222 break;
3223 }else{
3224 $wasAir = true;
3225 }
3226 }
3227
3228 for(; $y >= $this->minY && $y < $max; ++$y){
3229 if(!$this->getBlockAt($x, $y + 1, $z)->isFullCube()){
3230 if(!$this->getBlockAt($x, $y, $z)->isFullCube()){
3231 return new Position($spawn->x, $y === (int) $spawn->y ? $spawn->y : $y, $spawn->z, $this);
3232 }
3233 }else{
3234 ++$y;
3235 }
3236 }
3237
3238 return new Position($spawn->x, $y, $spawn->z, $this);
3239 }
3240
3244 public function getTime() : int{
3245 return $this->time;
3246 }
3247
3251 public function getTimeOfDay() : int{
3252 return $this->time % self::TIME_FULL;
3253 }
3254
3259 public function getDisplayName() : string{
3260 return $this->displayName;
3261 }
3262
3266 public function setDisplayName(string $name) : void{
3267 (new WorldDisplayNameChangeEvent($this, $this->displayName, $name))->call();
3268
3269 $this->displayName = $name;
3270 $this->provider->getWorldData()->setName($name);
3271 }
3272
3276 public function getFolderName() : string{
3277 return $this->folderName;
3278 }
3279
3283 public function setTime(int $time) : void{
3284 $this->time = $time;
3285 $this->sendTime();
3286 }
3287
3291 public function stopTime() : void{
3292 $this->stopTime = true;
3293 $this->sendTime();
3294 }
3295
3299 public function startTime() : void{
3300 $this->stopTime = false;
3301 $this->sendTime();
3302 }
3303
3307 public function getSeed() : int{
3308 return $this->provider->getWorldData()->getSeed();
3309 }
3310
3311 public function getMinY() : int{
3312 return $this->minY;
3313 }
3314
3315 public function getMaxY() : int{
3316 return $this->maxY;
3317 }
3318
3319 public function getDifficulty() : int{
3320 return $this->provider->getWorldData()->getDifficulty();
3321 }
3322
3323 public function setDifficulty(int $difficulty) : void{
3324 if($difficulty < 0 || $difficulty > 3){
3325 throw new \InvalidArgumentException("Invalid difficulty level $difficulty");
3326 }
3327 (new WorldDifficultyChangeEvent($this, $this->getDifficulty(), $difficulty))->call();
3328 $this->provider->getWorldData()->setDifficulty($difficulty);
3329
3330 foreach($this->players as $player){
3331 $player->getNetworkSession()->syncWorldDifficulty($this->getDifficulty());
3332 }
3333 }
3334
3335 private function addChunkHashToPopulationRequestQueue(int $chunkHash) : void{
3336 if(!isset($this->chunkPopulationRequestQueueIndex[$chunkHash])){
3337 $this->chunkPopulationRequestQueue->enqueue($chunkHash);
3338 $this->chunkPopulationRequestQueueIndex[$chunkHash] = true;
3339 }
3340 }
3341
3345 private function enqueuePopulationRequest(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3346 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3347 $this->addChunkHashToPopulationRequestQueue($chunkHash);
3349 $resolver = $this->chunkPopulationRequestMap[$chunkHash] = new PromiseResolver();
3350 if($associatedChunkLoader === null){
3351 $temporaryLoader = new ChunkLoader();
3352 $this->registerChunkLoader($temporaryLoader, $chunkX, $chunkZ);
3353 $resolver->getPromise()->onCompletion(
3354 fn() => $this->unregisterChunkLoader($temporaryLoader, $chunkX, $chunkZ),
3355 static function() : void{}
3356 );
3357 }
3358 return $resolver->getPromise();
3359 }
3360
3361 private function drainPopulationRequestQueue() : void{
3362 $failed = [];
3363 while(count($this->activeChunkPopulationTasks) < $this->maxConcurrentChunkPopulationTasks && !$this->chunkPopulationRequestQueue->isEmpty()){
3364 $nextChunkHash = $this->chunkPopulationRequestQueue->dequeue();
3365 unset($this->chunkPopulationRequestQueueIndex[$nextChunkHash]);
3366 World::getXZ($nextChunkHash, $nextChunkX, $nextChunkZ);
3367 if(isset($this->chunkPopulationRequestMap[$nextChunkHash])){
3368 assert(!($this->activeChunkPopulationTasks[$nextChunkHash] ?? false), "Population for chunk $nextChunkX $nextChunkZ already running");
3369 if(
3370 !$this->orderChunkPopulation($nextChunkX, $nextChunkZ, null)->isResolved() &&
3371 !isset($this->activeChunkPopulationTasks[$nextChunkHash])
3372 ){
3373 $failed[] = $nextChunkHash;
3374 }
3375 }
3376 }
3377
3378 //these requests failed even though they weren't rate limited; we can't directly re-add them to the back of the
3379 //queue because it would result in an infinite loop
3380 foreach($failed as $hash){
3381 $this->addChunkHashToPopulationRequestQueue($hash);
3382 }
3383 }
3384
3390 private function checkChunkPopulationPreconditions(int $chunkX, int $chunkZ) : array{
3391 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3392 $resolver = $this->chunkPopulationRequestMap[$chunkHash] ?? null;
3393 if($resolver !== null && isset($this->activeChunkPopulationTasks[$chunkHash])){
3394 //generation is already running
3395 return [$resolver, false];
3396 }
3397
3398 $temporaryChunkLoader = new ChunkLoader();
3399 $this->registerChunkLoader($temporaryChunkLoader, $chunkX, $chunkZ);
3400 $chunk = $this->loadChunk($chunkX, $chunkZ);
3401 $this->unregisterChunkLoader($temporaryChunkLoader, $chunkX, $chunkZ);
3402 if($chunk !== null && $chunk->isPopulated()){
3403 //chunk is already populated; return a pre-resolved promise that will directly fire callbacks assigned
3404 $resolver ??= new PromiseResolver();
3405 unset($this->chunkPopulationRequestMap[$chunkHash]);
3406 $resolver->resolve($chunk);
3407 return [$resolver, false];
3408 }
3409 return [$resolver, true];
3410 }
3411
3423 public function requestChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3424 [$resolver, $proceedWithPopulation] = $this->checkChunkPopulationPreconditions($chunkX, $chunkZ);
3425 if(!$proceedWithPopulation){
3426 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3427 }
3428
3429 if(count($this->activeChunkPopulationTasks) >= $this->maxConcurrentChunkPopulationTasks){
3430 //too many chunks are already generating; delay resolution of the request until later
3431 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3432 }
3433 return $this->internalOrderChunkPopulation($chunkX, $chunkZ, $associatedChunkLoader, $resolver);
3434 }
3435
3446 public function orderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3447 [$resolver, $proceedWithPopulation] = $this->checkChunkPopulationPreconditions($chunkX, $chunkZ);
3448 if(!$proceedWithPopulation){
3449 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3450 }
3451
3452 return $this->internalOrderChunkPopulation($chunkX, $chunkZ, $associatedChunkLoader, $resolver);
3453 }
3454
3459 private function internalOrderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader, ?PromiseResolver $resolver) : Promise{
3460 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3461
3462 $timings = $this->timings->chunkPopulationOrder;
3463 $timings->startTiming();
3464
3465 try{
3466 for($xx = -1; $xx <= 1; ++$xx){
3467 for($zz = -1; $zz <= 1; ++$zz){
3468 if($this->isChunkLocked($chunkX + $xx, $chunkZ + $zz)){
3469 //chunk is already in use by another generation request; queue the request for later
3470 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3471 }
3472 }
3473 }
3474
3475 $this->activeChunkPopulationTasks[$chunkHash] = true;
3476 if($resolver === null){
3477 $resolver = new PromiseResolver();
3478 $this->chunkPopulationRequestMap[$chunkHash] = $resolver;
3479 }
3480
3481 $chunkPopulationLockId = new ChunkLockId();
3482
3483 $temporaryChunkLoader = new ChunkLoader();
3484 for($xx = -1; $xx <= 1; ++$xx){
3485 for($zz = -1; $zz <= 1; ++$zz){
3486 $this->lockChunk($chunkX + $xx, $chunkZ + $zz, $chunkPopulationLockId);
3487 $this->registerChunkLoader($temporaryChunkLoader, $chunkX + $xx, $chunkZ + $zz);
3488 }
3489 }
3490
3491 $centerChunk = $this->loadChunk($chunkX, $chunkZ);
3492 $adjacentChunks = $this->getAdjacentChunks($chunkX, $chunkZ);
3493
3494 $this->generatorExecutor->populate(
3495 $chunkX,
3496 $chunkZ,
3497 $centerChunk,
3498 $adjacentChunks,
3499 function(Chunk $centerChunk, array $adjacentChunks) use ($chunkPopulationLockId, $chunkX, $chunkZ, $temporaryChunkLoader) : void{
3500 if(!$this->isLoaded()){
3501 return;
3502 }
3503
3504 $this->generateChunkCallback($chunkPopulationLockId, $chunkX, $chunkZ, $centerChunk, $adjacentChunks, $temporaryChunkLoader);
3505 }
3506 );
3507
3508 return $resolver->getPromise();
3509 }finally{
3510 $timings->stopTiming();
3511 }
3512 }
3513
3518 private function generateChunkCallback(ChunkLockId $chunkLockId, int $x, int $z, Chunk $chunk, array $adjacentChunks, ChunkLoader $temporaryChunkLoader) : void{
3519 $timings = $this->timings->chunkPopulationCompletion;
3520 $timings->startTiming();
3521
3522 $dirtyChunks = 0;
3523 for($xx = -1; $xx <= 1; ++$xx){
3524 for($zz = -1; $zz <= 1; ++$zz){
3525 $this->unregisterChunkLoader($temporaryChunkLoader, $x + $xx, $z + $zz);
3526 if(!$this->unlockChunk($x + $xx, $z + $zz, $chunkLockId)){
3527 $dirtyChunks++;
3528 }
3529 }
3530 }
3531
3532 $index = World::chunkHash($x, $z);
3533 if(!isset($this->activeChunkPopulationTasks[$index])){
3534 throw new AssumptionFailedError("This should always be set, regardless of whether the task was orphaned or not");
3535 }
3536 if(!$this->activeChunkPopulationTasks[$index]){
3537 $this->logger->debug("Discarding orphaned population result for chunk x=$x,z=$z");
3538 unset($this->activeChunkPopulationTasks[$index]);
3539 }else{
3540 if($dirtyChunks === 0){
3541 $oldChunk = $this->loadChunk($x, $z);
3542 $this->setChunk($x, $z, $chunk);
3543
3544 foreach($adjacentChunks as $relativeChunkHash => $adjacentChunk){
3545 World::getXZ($relativeChunkHash, $relativeX, $relativeZ);
3546 if($relativeX < -1 || $relativeX > 1 || $relativeZ < -1 || $relativeZ > 1){
3547 throw new AssumptionFailedError("Adjacent chunks should be in range -1 ... +1 coordinates");
3548 }
3549 $this->setChunk($x + $relativeX, $z + $relativeZ, $adjacentChunk);
3550 }
3551
3552 if(($oldChunk === null || !$oldChunk->isPopulated()) && $chunk->isPopulated()){
3553 if(ChunkPopulateEvent::hasHandlers()){
3554 (new ChunkPopulateEvent($this, $x, $z, $chunk))->call();
3555 }
3556
3557 foreach($this->getChunkListeners($x, $z) as $listener){
3558 $listener->onChunkPopulated($x, $z, $chunk);
3559 }
3560 }
3561 }else{
3562 $this->logger->debug("Discarding population result for chunk x=$x,z=$z - terrain was modified on the main thread before async population completed");
3563 }
3564
3565 //This needs to be in this specific spot because user code might call back to orderChunkPopulation().
3566 //If it does, and finds the promise, and doesn't find an active task associated with it, it will schedule
3567 //another PopulationTask. We don't want that because we're here processing the results.
3568 //We can't remove the promise from the array before setting the chunks in the world because that would lead
3569 //to the same problem. Therefore, it's necessary that this code be split into two if/else, with this in the
3570 //middle.
3571 unset($this->activeChunkPopulationTasks[$index]);
3572
3573 if($dirtyChunks === 0){
3574 $promise = $this->chunkPopulationRequestMap[$index] ?? null;
3575 if($promise !== null){
3576 unset($this->chunkPopulationRequestMap[$index]);
3577 $promise->resolve($chunk);
3578 }else{
3579 //Handlers of ChunkPopulateEvent, ChunkLoadEvent, or just ChunkListeners can cause this
3580 $this->logger->debug("Unable to resolve population promise for chunk x=$x,z=$z - populated chunk was forcibly unloaded while setting modified chunks");
3581 }
3582 }else{
3583 //request failed, stick it back on the queue
3584 //we didn't resolve the promise or touch it in any way, so any fake chunk loaders are still valid and
3585 //don't need to be added a second time.
3586 $this->addChunkHashToPopulationRequestQueue($index);
3587 }
3588
3589 $this->drainPopulationRequestQueue();
3590 }
3591 $timings->stopTiming();
3592 }
3593
3594 public function doChunkGarbageCollection() : void{
3595 $this->timings->doChunkGC->startTiming();
3596
3597 foreach($this->chunks as $index => $chunk){
3598 if(!isset($this->unloadQueue[$index])){
3599 World::getXZ($index, $X, $Z);
3600 if(!$this->isSpawnChunk($X, $Z)){
3601 $this->unloadChunkRequest($X, $Z, true);
3602 }
3603 }
3604 $chunk->collectGarbage();
3605 }
3606
3607 $this->provider->doGarbageCollection();
3608
3609 $this->timings->doChunkGC->stopTiming();
3610 }
3611
3612 public function unloadChunks(bool $force = false) : void{
3613 if(count($this->unloadQueue) > 0){
3614 $maxUnload = 96;
3615 $now = microtime(true);
3616 foreach($this->unloadQueue as $index => $time){
3617 World::getXZ($index, $X, $Z);
3618
3619 if(!$force){
3620 if($maxUnload <= 0){
3621 break;
3622 }elseif($time > ($now - 30)){
3623 continue;
3624 }
3625 }
3626
3627 //If the chunk can't be unloaded, it stays on the queue
3628 if($this->unloadChunk($X, $Z, true)){
3629 unset($this->unloadQueue[$index]);
3630 --$maxUnload;
3631 }
3632 }
3633 }
3634 }
3635}
pop(int $count=1)
Definition Item.php:435
getChunkListeners(int $chunkX, int $chunkZ)
Definition World.php:891
removeEntity(Entity $entity)
Definition World.php:2780
notifyNeighbourBlockUpdate(Vector3 $pos)
Definition World.php:1508
getCollisionBlocks(AxisAlignedBB $bb, bool $targetFirst=false)
Definition World.php:1516
getHighestAdjacentBlockLight(int $x, int $y, int $z)
Definition World.php:1895
setDisplayName(string $name)
Definition World.php:3266
getPotentialBlockSkyLightAt(int $x, int $y, int $z)
Definition World.php:1800
removeOnUnloadCallback(\Closure $callback)
Definition World.php:668
isChunkLocked(int $chunkX, int $chunkZ)
Definition World.php:2606
setSpawnLocation(Vector3 $pos)
Definition World.php:2732
getPotentialLightAt(int $x, int $y, int $z)
Definition World.php:1782
createBlockUpdatePackets(array $blocks)
Definition World.php:1091
getSafeSpawn(?Vector3 $spawn=null)
Definition World.php:3202
registerChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ)
Definition World.php:845
getBlockAt(int $x, int $y, int $z, bool $cached=true, bool $addToCache=true)
Definition World.php:1946
getChunkEntities(int $chunkX, int $chunkZ)
Definition World.php:2529
addEntity(Entity $entity)
Definition World.php:2746
getBlockLightAt(int $x, int $y, int $z)
Definition World.php:1825
getBlock(Vector3 $pos, bool $cached=true, bool $addToCache=true)
Definition World.php:1933
static chunkHash(int $x, int $z)
Definition World.php:384
broadcastPacketToViewers(Vector3 $pos, ClientboundPacket $packet)
Definition World.php:795
getOrLoadChunkAtPosition(Vector3 $pos)
Definition World.php:2536
static chunkBlockHash(int $x, int $y, int $z)
Definition World.php:423
getHighestAdjacentPotentialBlockSkyLight(int $x, int $y, int $z)
Definition World.php:1880
getFullLight(Vector3 $pos)
Definition World.php:1739
isInWorld(int $x, int $y, int $z)
Definition World.php:1915
unlockChunk(int $chunkX, int $chunkZ, ?ChunkLockId $lockId)
Definition World.php:2591
getChunkLoaders(int $chunkX, int $chunkZ)
Definition World.php:778
getAdjacentChunks(int $x, int $z)
Definition World.php:2546
getChunkPlayers(int $chunkX, int $chunkZ)
Definition World.php:768
getTileAt(int $x, int $y, int $z)
Definition World.php:2486
getHighestAdjacentFullLightAt(int $x, int $y, int $z)
Definition World.php:1763
setChunkTickRadius(int $radius)
Definition World.php:1210
getViewersForPosition(Vector3 $pos)
Definition World.php:788
getNearestEntity(Vector3 $pos, float $maxDistance, string $entityType=Entity::class, bool $includeDead=false)
Definition World.php:2429
__construct(private Server $server, string $name, private WritableWorldProvider $provider, private AsyncPool $workerPool)
Definition World.php:482
requestChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader)
Definition World.php:3423
addSound(Vector3 $pos, Sound $sound, ?array $players=null)
Definition World.php:696
registerTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ)
Definition World.php:1229
setBlock(Vector3 $pos, Block $block, bool $update=true)
Definition World.php:2001
getNearbyEntities(AxisAlignedBB $bb, ?Entity $entity=null)
Definition World.php:2397
static getXZ(int $hash, ?int &$x, ?int &$z)
Definition World.php:449
getBlockCollisionBoxes(AxisAlignedBB $bb)
Definition World.php:1646
getCollidingEntities(AxisAlignedBB $bb, ?Entity $entity=null)
Definition World.php:2379
isSpawnChunk(int $X, int $Z)
Definition World.php:3160
useBreakOn(Vector3 $vector, ?Item &$item=null, ?Player $player=null, bool $createParticles=false, array &$returnedItems=[])
Definition World.php:2116
getPotentialLight(Vector3 $pos)
Definition World.php:1771
addParticle(Vector3 $pos, Particle $particle, ?array $players=null)
Definition World.php:725
unregisterChunkListenerFromAll(ChunkListener $listener)
Definition World.php:878
loadChunk(int $x, int $z)
Definition World.php:2914
getHighestAdjacentPotentialLightAt(int $x, int $y, int $z)
Definition World.php:1790
setBlockAt(int $x, int $y, int $z, Block $block, bool $update=true)
Definition World.php:2013
useItemOn(Vector3 $vector, Item &$item, Facing $face, ?Vector3 $clickVector=null, ?Player $player=null, bool $playSound=false, array &$returnedItems=[])
Definition World.php:2222
unregisterTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ)
Definition World.php:1239
getRealBlockSkyLightAt(int $x, int $y, int $z)
Definition World.php:1815
static blockHash(int $x, int $y, int $z)
Definition World.php:403
getTile(Vector3 $pos)
Definition World.php:2479
getFullLightAt(int $x, int $y, int $z)
Definition World.php:1750
getHighestAdjacentRealBlockSkyLight(int $x, int $y, int $z)
Definition World.php:1888
orderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader)
Definition World.php:3446
dropExperience(Vector3 $pos, int $amount)
Definition World.php:2093
isInLoadedTerrain(Vector3 $pos)
Definition World.php:2705
lockChunk(int $chunkX, int $chunkZ, ChunkLockId $lockId)
Definition World.php:2574
getHighestBlockAt(int $x, int $z)
Definition World.php:2695
scheduleDelayedBlockUpdate(Vector3 $pos, int $delay)
Definition World.php:1467
static getBlockXYZ(int $hash, ?int &$x, ?int &$y, ?int &$z)
Definition World.php:433
addOnUnloadCallback(\Closure $callback)
Definition World.php:663
requestSafeSpawn(?Vector3 $spawn=null)
Definition World.php:3175
unregisterChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ)
Definition World.php:862