PocketMine-MP 5.27.1 git-9af3cde03fabbe4129c79e46dc87ffa0fff446e6
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;
109use function abs;
110use function array_filter;
111use function array_key_exists;
112use function array_keys;
113use function array_map;
114use function array_merge;
115use function array_sum;
116use function array_values;
117use function assert;
118use function cos;
119use function count;
120use function floor;
121use function get_class;
122use function gettype;
123use function is_a;
124use function is_object;
125use function max;
126use function microtime;
127use function min;
128use function morton2d_decode;
129use function morton2d_encode;
130use function morton3d_decode;
131use function morton3d_encode;
132use function mt_rand;
133use function preg_match;
134use function spl_object_id;
135use function strtolower;
136use function trim;
137use const M_PI;
138use const PHP_INT_MAX;
139use const PHP_INT_MIN;
140
141#include <rules/World.h>
142
148class World implements ChunkManager{
149
150 private static int $worldIdCounter = 1;
151
152 public const Y_MAX = 320;
153 public const Y_MIN = -64;
154
155 public const TIME_DAY = 1000;
156 public const TIME_NOON = 6000;
157 public const TIME_SUNSET = 12000;
158 public const TIME_NIGHT = 13000;
159 public const TIME_MIDNIGHT = 18000;
160 public const TIME_SUNRISE = 23000;
161
162 public const TIME_FULL = 24000;
163
164 public const DIFFICULTY_PEACEFUL = 0;
165 public const DIFFICULTY_EASY = 1;
166 public const DIFFICULTY_NORMAL = 2;
167 public const DIFFICULTY_HARD = 3;
168
169 public const DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK = 3;
170
171 //TODO: this could probably do with being a lot bigger
172 private const BLOCK_CACHE_SIZE_CAP = 2048;
173
178 private array $players = [];
179
184 private array $entities = [];
189 private array $entityLastKnownPositions = [];
190
195 private array $entitiesByChunk = [];
196
201 public array $updateEntities = [];
202
203 private bool $inDynamicStateRecalculation = false;
208 private array $blockCache = [];
209 private int $blockCacheSize = 0;
214 private array $blockCollisionBoxCache = [];
215
216 private int $sendTimeTicker = 0;
217
218 private int $worldId;
219
220 private int $providerGarbageCollectionTicker = 0;
221
222 private int $minY;
223 private int $maxY;
224
229 private array $registeredTickingChunks = [];
230
237 private array $validTickingChunks = [];
238
244 private array $recheckTickingChunks = [];
245
250 private array $chunkLoaders = [];
251
256 private array $chunkListeners = [];
261 private array $playerChunkListeners = [];
262
267 private array $packetBuffersByChunk = [];
268
273 private array $unloadQueue = [];
274
275 private int $time;
276 public bool $stopTime = false;
277
278 private float $sunAnglePercentage = 0.0;
279 private int $skyLightReduction = 0;
280
281 private string $folderName;
282 private string $displayName;
283
288 private array $chunks = [];
289
294 private array $changedBlocks = [];
295
297 private ReversePriorityQueue $scheduledBlockUpdateQueue;
302 private array $scheduledBlockUpdateQueueIndex = [];
303
305 private \SplQueue $neighbourBlockUpdateQueue;
310 private array $neighbourBlockUpdateQueueIndex = [];
311
316 private array $activeChunkPopulationTasks = [];
321 private array $chunkLock = [];
322 private int $maxConcurrentChunkPopulationTasks = 2;
327 private array $chunkPopulationRequestMap = [];
332 private \SplQueue $chunkPopulationRequestQueue;
337 private array $chunkPopulationRequestQueueIndex = [];
338
343 private array $generatorRegisteredWorkers = [];
344
345 private bool $autoSave = true;
346
347 private int $sleepTicks = 0;
348
349 private int $chunkTickRadius;
350 private int $tickedBlocksPerSubchunkPerTick = self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK;
355 private array $randomTickBlocks = [];
356
357 public WorldTimings $timings;
358
359 public float $tickRateTime = 0;
360
361 private bool $doingTick = false;
362
364 private string $generator;
365
366 private bool $unloaded = false;
371 private array $unloadCallbacks = [];
372
373 private ?BlockLightUpdate $blockLightUpdate = null;
374 private ?SkyLightUpdate $skyLightUpdate = null;
375
376 private \Logger $logger;
377
378 private RuntimeBlockStateRegistry $blockStateRegistry;
379
383 public static function chunkHash(int $x, int $z) : int{
384 return morton2d_encode($x, $z);
385 }
386
387 private const MORTON3D_BIT_SIZE = 21;
388 private const BLOCKHASH_Y_BITS = 9;
389 private const BLOCKHASH_Y_PADDING = 64; //size (in blocks) of padding after both boundaries of the Y axis
390 private const BLOCKHASH_Y_OFFSET = self::BLOCKHASH_Y_PADDING - self::Y_MIN;
391 private const BLOCKHASH_Y_MASK = (1 << self::BLOCKHASH_Y_BITS) - 1;
392 private const BLOCKHASH_XZ_MASK = (1 << self::MORTON3D_BIT_SIZE) - 1;
393 private const BLOCKHASH_XZ_EXTRA_BITS = (self::MORTON3D_BIT_SIZE - self::BLOCKHASH_Y_BITS) >> 1;
394 private const BLOCKHASH_XZ_EXTRA_MASK = (1 << self::BLOCKHASH_XZ_EXTRA_BITS) - 1;
395 private const BLOCKHASH_XZ_SIGN_SHIFT = 64 - self::MORTON3D_BIT_SIZE - self::BLOCKHASH_XZ_EXTRA_BITS;
396 private const BLOCKHASH_X_SHIFT = self::BLOCKHASH_Y_BITS;
397 private const BLOCKHASH_Z_SHIFT = self::BLOCKHASH_X_SHIFT + self::BLOCKHASH_XZ_EXTRA_BITS;
398
402 public static function blockHash(int $x, int $y, int $z) : int{
403 $shiftedY = $y + self::BLOCKHASH_Y_OFFSET;
404 if(($shiftedY & (~0 << self::BLOCKHASH_Y_BITS)) !== 0){
405 throw new \InvalidArgumentException("Y coordinate $y is out of range!");
406 }
407 //morton3d gives us 21 bits on each axis, but the Y axis only requires 9
408 //so we use the extra space on Y (12 bits) and add 6 extra bits from X and Z instead.
409 //if we ever need more space for Y (e.g. due to expansion), take bits from X/Z to compensate.
410 return morton3d_encode(
411 $x & self::BLOCKHASH_XZ_MASK,
412 ($shiftedY /* & self::BLOCKHASH_Y_MASK */) |
413 ((($x >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_X_SHIFT) |
414 ((($z >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_Z_SHIFT),
415 $z & self::BLOCKHASH_XZ_MASK
416 );
417 }
418
422 public static function chunkBlockHash(int $x, int $y, int $z) : int{
423 return morton3d_encode($x, $y, $z);
424 }
425
432 public static function getBlockXYZ(int $hash, ?int &$x, ?int &$y, ?int &$z) : void{
433 [$baseX, $baseY, $baseZ] = morton3d_decode($hash);
434
435 $extraX = ((($baseY >> self::BLOCKHASH_X_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
436 $extraZ = ((($baseY >> self::BLOCKHASH_Z_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
437
438 $x = (($baseX & self::BLOCKHASH_XZ_MASK) | $extraX) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
439 $y = ($baseY & self::BLOCKHASH_Y_MASK) - self::BLOCKHASH_Y_OFFSET;
440 $z = (($baseZ & self::BLOCKHASH_XZ_MASK) | $extraZ) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
441 }
442
448 public static function getXZ(int $hash, ?int &$x, ?int &$z) : void{
449 [$x, $z] = morton2d_decode($hash);
450 }
451
452 public static function getDifficultyFromString(string $str) : int{
453 switch(strtolower(trim($str))){
454 case "0":
455 case "peaceful":
456 case "p":
457 return World::DIFFICULTY_PEACEFUL;
458
459 case "1":
460 case "easy":
461 case "e":
462 return World::DIFFICULTY_EASY;
463
464 case "2":
465 case "normal":
466 case "n":
467 return World::DIFFICULTY_NORMAL;
468
469 case "3":
470 case "hard":
471 case "h":
472 return World::DIFFICULTY_HARD;
473 }
474
475 return -1;
476 }
477
481 public function __construct(
482 private Server $server,
483 string $name, //TODO: this should be folderName (named arguments BC break)
484 private WritableWorldProvider $provider,
485 private AsyncPool $workerPool
486 ){
487 $this->folderName = $name;
488 $this->worldId = self::$worldIdCounter++;
489
490 $this->displayName = $this->provider->getWorldData()->getName();
491 $this->logger = new \PrefixedLogger($server->getLogger(), "World: $this->displayName");
492
493 $this->blockStateRegistry = RuntimeBlockStateRegistry::getInstance();
494 $this->minY = $this->provider->getWorldMinY();
495 $this->maxY = $this->provider->getWorldMaxY();
496
497 $this->server->getLogger()->info($this->server->getLanguage()->translate(KnownTranslationFactory::pocketmine_level_preparing($this->displayName)));
498 $generator = GeneratorManager::getInstance()->getGenerator($this->provider->getWorldData()->getGenerator()) ??
499 throw new AssumptionFailedError("WorldManager should already have checked that the generator exists");
500 $generator->validateGeneratorOptions($this->provider->getWorldData()->getGeneratorOptions());
501 $this->generator = $generator->getGeneratorClass();
502 $this->chunkPopulationRequestQueue = new \SplQueue();
503 $this->addOnUnloadCallback(function() : void{
504 $this->logger->debug("Cancelling unfulfilled generation requests");
505
506 foreach($this->chunkPopulationRequestMap as $chunkHash => $promise){
507 $promise->reject();
508 unset($this->chunkPopulationRequestMap[$chunkHash]);
509 }
510 if(count($this->chunkPopulationRequestMap) !== 0){
511 //TODO: this might actually get hit because generation rejection callbacks might try to schedule new
512 //requests, and we can't prevent that right now because there's no way to detect "unloading" state
513 throw new AssumptionFailedError("New generation requests scheduled during unload");
514 }
515 });
516
517 $this->scheduledBlockUpdateQueue = new ReversePriorityQueue();
518 $this->scheduledBlockUpdateQueue->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
519
520 $this->neighbourBlockUpdateQueue = new \SplQueue();
521
522 $this->time = $this->provider->getWorldData()->getTime();
523
524 $cfg = $this->server->getConfigGroup();
525 $this->chunkTickRadius = min($this->server->getViewDistance(), max(0, $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_TICK_RADIUS, 4)));
526 if($cfg->getPropertyInt("chunk-ticking.per-tick", 40) <= 0){
527 //TODO: this needs l10n
528 $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.");
529 $this->chunkTickRadius = 0;
530 }
531 $this->tickedBlocksPerSubchunkPerTick = $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_BLOCKS_PER_SUBCHUNK_PER_TICK, self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK);
532 $this->maxConcurrentChunkPopulationTasks = $cfg->getPropertyInt(YmlServerProperties::CHUNK_GENERATION_POPULATION_QUEUE_SIZE, 2);
533
534 $this->initRandomTickBlocksFromConfig($cfg);
535
536 $this->timings = new WorldTimings($this);
537
538 $this->workerPool->addWorkerStartHook($workerStartHook = function(int $workerId) : void{
539 if(array_key_exists($workerId, $this->generatorRegisteredWorkers)){
540 $this->logger->debug("Worker $workerId with previously registered generator restarted, flagging as unregistered");
541 unset($this->generatorRegisteredWorkers[$workerId]);
542 }
543 });
544 $workerPool = $this->workerPool;
545 $this->addOnUnloadCallback(static function() use ($workerPool, $workerStartHook) : void{
546 $workerPool->removeWorkerStartHook($workerStartHook);
547 });
548 }
549
550 private function initRandomTickBlocksFromConfig(ServerConfigGroup $cfg) : void{
551 $dontTickBlocks = [];
552 $parser = StringToItemParser::getInstance();
553 foreach($cfg->getProperty(YmlServerProperties::CHUNK_TICKING_DISABLE_BLOCK_TICKING, []) as $name){
554 $name = (string) $name;
555 $item = $parser->parse($name);
556 if($item !== null){
557 $block = $item->getBlock();
558 }elseif(preg_match("/^-?\d+$/", $name) === 1){
559 //TODO: this is a really sketchy hack - remove this as soon as possible
560 try{
561 $blockStateData = GlobalBlockStateHandlers::getUpgrader()->upgradeIntIdMeta((int) $name, 0);
562 }catch(BlockStateDeserializeException){
563 continue;
564 }
565 $block = $this->blockStateRegistry->fromStateId(GlobalBlockStateHandlers::getDeserializer()->deserialize($blockStateData));
566 }else{
567 //TODO: we probably ought to log an error here
568 continue;
569 }
570
571 if($block->getTypeId() !== BlockTypeIds::AIR){
572 $dontTickBlocks[$block->getTypeId()] = $name;
573 }
574 }
575
576 foreach($this->blockStateRegistry->getAllKnownStates() as $state){
577 $dontTickName = $dontTickBlocks[$state->getTypeId()] ?? null;
578 if($dontTickName === null && $state->ticksRandomly()){
579 $this->randomTickBlocks[$state->getStateId()] = true;
580 }
581 }
582 }
583
584 public function getTickRateTime() : float{
585 return $this->tickRateTime;
586 }
587
588 public function registerGeneratorToWorker(int $worker) : void{
589 $this->logger->debug("Registering generator on worker $worker");
590 $this->workerPool->submitTaskToWorker(new GeneratorRegisterTask($this, $this->generator, $this->provider->getWorldData()->getGeneratorOptions()), $worker);
591 $this->generatorRegisteredWorkers[$worker] = true;
592 }
593
594 public function unregisterGenerator() : void{
595 foreach($this->workerPool->getRunningWorkers() as $i){
596 if(isset($this->generatorRegisteredWorkers[$i])){
597 $this->workerPool->submitTaskToWorker(new GeneratorUnregisterTask($this), $i);
598 }
599 }
600 $this->generatorRegisteredWorkers = [];
601 }
602
603 public function getServer() : Server{
604 return $this->server;
605 }
606
607 public function getLogger() : \Logger{
608 return $this->logger;
609 }
610
611 final public function getProvider() : WritableWorldProvider{
612 return $this->provider;
613 }
614
618 final public function getId() : int{
619 return $this->worldId;
620 }
621
622 public function isLoaded() : bool{
623 return !$this->unloaded;
624 }
625
629 public function onUnload() : void{
630 if($this->unloaded){
631 throw new \LogicException("Tried to close a world which is already closed");
632 }
633
634 foreach($this->unloadCallbacks as $callback){
635 $callback();
636 }
637 $this->unloadCallbacks = [];
638
639 foreach($this->chunks as $chunkHash => $chunk){
640 self::getXZ($chunkHash, $chunkX, $chunkZ);
641 $this->unloadChunk($chunkX, $chunkZ, false);
642 }
643 foreach($this->entitiesByChunk as $chunkHash => $entities){
644 self::getXZ($chunkHash, $chunkX, $chunkZ);
645
646 $leakedEntities = 0;
647 foreach($entities as $entity){
648 if(!$entity->isFlaggedForDespawn()){
649 $leakedEntities++;
650 }
651 $entity->close();
652 }
653 if($leakedEntities !== 0){
654 $this->logger->warning("$leakedEntities leaked entities found in ungenerated chunk $chunkX $chunkZ during unload, they won't be saved!");
655 }
656 }
657
658 $this->save();
659
660 $this->unregisterGenerator();
661
662 $this->provider->close();
663 $this->blockCache = [];
664 $this->blockCacheSize = 0;
665 $this->blockCollisionBoxCache = [];
666
667 $this->unloaded = true;
668 }
669
671 public function addOnUnloadCallback(\Closure $callback) : void{
672 $this->unloadCallbacks[spl_object_id($callback)] = $callback;
673 }
674
676 public function removeOnUnloadCallback(\Closure $callback) : void{
677 unset($this->unloadCallbacks[spl_object_id($callback)]);
678 }
679
688 private function filterViewersForPosition(Vector3 $pos, array $allowed) : array{
689 $candidates = $this->getViewersForPosition($pos);
690 $filtered = [];
691 foreach($allowed as $player){
692 $k = spl_object_id($player);
693 if(isset($candidates[$k])){
694 $filtered[$k] = $candidates[$k];
695 }
696 }
697
698 return $filtered;
699 }
700
704 public function addSound(Vector3 $pos, Sound $sound, ?array $players = null) : void{
705 $players ??= $this->getViewersForPosition($pos);
706
707 if(WorldSoundEvent::hasHandlers()){
708 $ev = new WorldSoundEvent($this, $sound, $pos, $players);
709 $ev->call();
710 if($ev->isCancelled()){
711 return;
712 }
713
714 $sound = $ev->getSound();
715 $players = $ev->getRecipients();
716 }
717
718 $pk = $sound->encode($pos);
719 if(count($pk) > 0){
720 if($players === $this->getViewersForPosition($pos)){
721 foreach($pk as $e){
722 $this->broadcastPacketToViewers($pos, $e);
723 }
724 }else{
725 NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
726 }
727 }
728 }
729
733 public function addParticle(Vector3 $pos, Particle $particle, ?array $players = null) : void{
734 $players ??= $this->getViewersForPosition($pos);
735
736 if(WorldParticleEvent::hasHandlers()){
737 $ev = new WorldParticleEvent($this, $particle, $pos, $players);
738 $ev->call();
739 if($ev->isCancelled()){
740 return;
741 }
742
743 $particle = $ev->getParticle();
744 $players = $ev->getRecipients();
745 }
746
747 $pk = $particle->encode($pos);
748 if(count($pk) > 0){
749 if($players === $this->getViewersForPosition($pos)){
750 foreach($pk as $e){
751 $this->broadcastPacketToViewers($pos, $e);
752 }
753 }else{
754 NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
755 }
756 }
757 }
758
759 public function getAutoSave() : bool{
760 return $this->autoSave;
761 }
762
763 public function setAutoSave(bool $value) : void{
764 $this->autoSave = $value;
765 }
766
776 public function getChunkPlayers(int $chunkX, int $chunkZ) : array{
777 return $this->playerChunkListeners[World::chunkHash($chunkX, $chunkZ)] ?? [];
778 }
779
786 public function getChunkLoaders(int $chunkX, int $chunkZ) : array{
787 return $this->chunkLoaders[World::chunkHash($chunkX, $chunkZ)] ?? [];
788 }
789
796 public function getViewersForPosition(Vector3 $pos) : array{
797 return $this->getChunkPlayers($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
798 }
799
803 public function broadcastPacketToViewers(Vector3 $pos, ClientboundPacket $packet) : void{
804 $this->broadcastPacketToPlayersUsingChunk($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE, $packet);
805 }
806
807 private function broadcastPacketToPlayersUsingChunk(int $chunkX, int $chunkZ, ClientboundPacket $packet) : void{
808 if(!isset($this->packetBuffersByChunk[$index = World::chunkHash($chunkX, $chunkZ)])){
809 $this->packetBuffersByChunk[$index] = [$packet];
810 }else{
811 $this->packetBuffersByChunk[$index][] = $packet;
812 }
813 }
814
815 public function registerChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ, bool $autoLoad = true) : void{
816 $loaderId = spl_object_id($loader);
817
818 if(!isset($this->chunkLoaders[$chunkHash = World::chunkHash($chunkX, $chunkZ)])){
819 $this->chunkLoaders[$chunkHash] = [];
820 }elseif(isset($this->chunkLoaders[$chunkHash][$loaderId])){
821 return;
822 }
823
824 $this->chunkLoaders[$chunkHash][$loaderId] = $loader;
825
826 $this->cancelUnloadChunkRequest($chunkX, $chunkZ);
827
828 if($autoLoad){
829 $this->loadChunk($chunkX, $chunkZ);
830 }
831 }
832
833 public function unregisterChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ) : void{
834 $chunkHash = World::chunkHash($chunkX, $chunkZ);
835 $loaderId = spl_object_id($loader);
836 if(isset($this->chunkLoaders[$chunkHash][$loaderId])){
837 if(count($this->chunkLoaders[$chunkHash]) === 1){
838 unset($this->chunkLoaders[$chunkHash]);
839 $this->unloadChunkRequest($chunkX, $chunkZ, true);
840 if(isset($this->chunkPopulationRequestMap[$chunkHash]) && !isset($this->activeChunkPopulationTasks[$chunkHash])){
841 $this->chunkPopulationRequestMap[$chunkHash]->reject();
842 unset($this->chunkPopulationRequestMap[$chunkHash]);
843 }
844 }else{
845 unset($this->chunkLoaders[$chunkHash][$loaderId]);
846 }
847 }
848 }
849
853 public function registerChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ) : void{
854 $hash = World::chunkHash($chunkX, $chunkZ);
855 if(isset($this->chunkListeners[$hash])){
856 $this->chunkListeners[$hash][spl_object_id($listener)] = $listener;
857 }else{
858 $this->chunkListeners[$hash] = [spl_object_id($listener) => $listener];
859 }
860 if($listener instanceof Player){
861 $this->playerChunkListeners[$hash][spl_object_id($listener)] = $listener;
862 }
863 }
864
870 public function unregisterChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ) : void{
871 $hash = World::chunkHash($chunkX, $chunkZ);
872 if(isset($this->chunkListeners[$hash])){
873 if(count($this->chunkListeners[$hash]) === 1){
874 unset($this->chunkListeners[$hash]);
875 unset($this->playerChunkListeners[$hash]);
876 }else{
877 unset($this->chunkListeners[$hash][spl_object_id($listener)]);
878 unset($this->playerChunkListeners[$hash][spl_object_id($listener)]);
879 }
880 }
881 }
882
886 public function unregisterChunkListenerFromAll(ChunkListener $listener) : void{
887 foreach($this->chunkListeners as $hash => $listeners){
888 World::getXZ($hash, $chunkX, $chunkZ);
889 $this->unregisterChunkListener($listener, $chunkX, $chunkZ);
890 }
891 }
892
899 public function getChunkListeners(int $chunkX, int $chunkZ) : array{
900 return $this->chunkListeners[World::chunkHash($chunkX, $chunkZ)] ?? [];
901 }
902
906 public function sendTime(Player ...$targets) : void{
907 if(count($targets) === 0){
908 $targets = $this->players;
909 }
910 foreach($targets as $player){
911 $player->getNetworkSession()->syncWorldTime($this->time);
912 }
913 }
914
915 public function isDoingTick() : bool{
916 return $this->doingTick;
917 }
918
922 public function doTick(int $currentTick) : void{
923 if($this->unloaded){
924 throw new \LogicException("Attempted to tick a world which has been closed");
925 }
926
927 $this->timings->doTick->startTiming();
928 $this->doingTick = true;
929 try{
930 $this->actuallyDoTick($currentTick);
931 }finally{
932 $this->doingTick = false;
933 $this->timings->doTick->stopTiming();
934 }
935 }
936
937 protected function actuallyDoTick(int $currentTick) : void{
938 if(!$this->stopTime){
939 //this simulates an overflow, as would happen in any language which doesn't do stupid things to var types
940 if($this->time === PHP_INT_MAX){
941 $this->time = PHP_INT_MIN;
942 }else{
943 $this->time++;
944 }
945 }
946
947 $this->sunAnglePercentage = $this->computeSunAnglePercentage(); //Sun angle depends on the current time
948 $this->skyLightReduction = $this->computeSkyLightReduction(); //Sky light reduction depends on the sun angle
949
950 if(++$this->sendTimeTicker === 200){
951 $this->sendTime();
952 $this->sendTimeTicker = 0;
953 }
954
955 $this->unloadChunks();
956 if(++$this->providerGarbageCollectionTicker >= 6000){
957 $this->provider->doGarbageCollection();
958 $this->providerGarbageCollectionTicker = 0;
959 }
960
961 $this->timings->scheduledBlockUpdates->startTiming();
962 //Delayed updates
963 while($this->scheduledBlockUpdateQueue->count() > 0 && $this->scheduledBlockUpdateQueue->current()["priority"] <= $currentTick){
965 $vec = $this->scheduledBlockUpdateQueue->extract()["data"];
966 unset($this->scheduledBlockUpdateQueueIndex[World::blockHash($vec->x, $vec->y, $vec->z)]);
967 if(!$this->isInLoadedTerrain($vec)){
968 continue;
969 }
970 $block = $this->getBlock($vec);
971 $block->onScheduledUpdate();
972 }
973 $this->timings->scheduledBlockUpdates->stopTiming();
974
975 $this->timings->neighbourBlockUpdates->startTiming();
976 //Normal updates
977 while($this->neighbourBlockUpdateQueue->count() > 0){
978 $index = $this->neighbourBlockUpdateQueue->dequeue();
979 unset($this->neighbourBlockUpdateQueueIndex[$index]);
980 World::getBlockXYZ($index, $x, $y, $z);
981 if(!$this->isChunkLoaded($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)){
982 continue;
983 }
984
985 $block = $this->getBlockAt($x, $y, $z);
986
987 if(BlockUpdateEvent::hasHandlers()){
988 $ev = new BlockUpdateEvent($block);
989 $ev->call();
990 if($ev->isCancelled()){
991 continue;
992 }
993 }
994 foreach($this->getNearbyEntities(AxisAlignedBB::one()->offset($x, $y, $z)) as $entity){
995 $entity->onNearbyBlockChange();
996 }
997 $block->onNearbyBlockChange();
998 }
999
1000 $this->timings->neighbourBlockUpdates->stopTiming();
1001
1002 $this->timings->entityTick->startTiming();
1003 //Update entities that need update
1004 foreach($this->updateEntities as $id => $entity){
1005 if($entity->isClosed() || $entity->isFlaggedForDespawn() || !$entity->onUpdate($currentTick)){
1006 unset($this->updateEntities[$id]);
1007 }
1008 if($entity->isFlaggedForDespawn()){
1009 $entity->close();
1010 }
1011 }
1012 $this->timings->entityTick->stopTiming();
1013
1014 $this->timings->randomChunkUpdates->startTiming();
1015 $this->tickChunks();
1016 $this->timings->randomChunkUpdates->stopTiming();
1017
1018 $this->executeQueuedLightUpdates();
1019
1020 if(count($this->changedBlocks) > 0){
1021 if(count($this->players) > 0){
1022 foreach($this->changedBlocks as $index => $blocks){
1023 if(count($blocks) === 0){ //blocks can be set normally and then later re-set with direct send
1024 continue;
1025 }
1026 World::getXZ($index, $chunkX, $chunkZ);
1027 if(!$this->isChunkLoaded($chunkX, $chunkZ)){
1028 //a previous chunk may have caused this one to be unloaded by a ChunkListener
1029 continue;
1030 }
1031 if(count($blocks) > 512){
1032 $chunk = $this->getChunk($chunkX, $chunkZ) ?? throw new AssumptionFailedError("We already checked that the chunk is loaded");
1033 foreach($this->getChunkPlayers($chunkX, $chunkZ) as $p){
1034 $p->onChunkChanged($chunkX, $chunkZ, $chunk);
1035 }
1036 }else{
1037 foreach($this->createBlockUpdatePackets($blocks) as $packet){
1038 $this->broadcastPacketToPlayersUsingChunk($chunkX, $chunkZ, $packet);
1039 }
1040 }
1041 }
1042 }
1043
1044 $this->changedBlocks = [];
1045
1046 }
1047
1048 if($this->sleepTicks > 0 && --$this->sleepTicks <= 0){
1049 $this->checkSleep();
1050 }
1051
1052 foreach($this->packetBuffersByChunk as $index => $entries){
1053 World::getXZ($index, $chunkX, $chunkZ);
1054 $chunkPlayers = $this->getChunkPlayers($chunkX, $chunkZ);
1055 if(count($chunkPlayers) > 0){
1056 NetworkBroadcastUtils::broadcastPackets($chunkPlayers, $entries);
1057 }
1058 }
1059
1060 $this->packetBuffersByChunk = [];
1061 }
1062
1063 public function checkSleep() : void{
1064 if(count($this->players) === 0){
1065 return;
1066 }
1067
1068 $resetTime = true;
1069 foreach($this->getPlayers() as $p){
1070 if(!$p->isSleeping()){
1071 $resetTime = false;
1072 break;
1073 }
1074 }
1075
1076 if($resetTime){
1077 $time = $this->getTimeOfDay();
1078
1079 if($time >= World::TIME_NIGHT && $time < World::TIME_SUNRISE){
1080 $this->setTime($this->getTime() + World::TIME_FULL - $time);
1081
1082 foreach($this->getPlayers() as $p){
1083 $p->stopSleep();
1084 }
1085 }
1086 }
1087 }
1088
1089 public function setSleepTicks(int $ticks) : void{
1090 $this->sleepTicks = $ticks;
1091 }
1092
1099 public function createBlockUpdatePackets(array $blocks) : array{
1100 $packets = [];
1101
1102 $blockTranslator = TypeConverter::getInstance()->getBlockTranslator();
1103
1104 foreach($blocks as $b){
1105 if(!($b instanceof Vector3)){
1106 throw new \TypeError("Expected Vector3 in blocks array, got " . (is_object($b) ? get_class($b) : gettype($b)));
1107 }
1108
1109 $fullBlock = $this->getBlockAt($b->x, $b->y, $b->z);
1110 $blockPosition = BlockPosition::fromVector3($b);
1111
1112 $tile = $this->getTileAt($b->x, $b->y, $b->z);
1113 if($tile instanceof Spawnable){
1114 $expectedClass = $fullBlock->getIdInfo()->getTileClass();
1115 if($expectedClass !== null && $tile instanceof $expectedClass && count($fakeStateProperties = $tile->getRenderUpdateBugWorkaroundStateProperties($fullBlock)) > 0){
1116 $originalStateData = $blockTranslator->internalIdToNetworkStateData($fullBlock->getStateId());
1117 $fakeStateData = new BlockStateData(
1118 $originalStateData->getName(),
1119 array_merge($originalStateData->getStates(), $fakeStateProperties),
1120 $originalStateData->getVersion()
1121 );
1122 $packets[] = UpdateBlockPacket::create(
1123 $blockPosition,
1124 $blockTranslator->getBlockStateDictionary()->lookupStateIdFromData($fakeStateData) ?? throw new AssumptionFailedError("Unmapped fake blockstate data: " . $fakeStateData->toNbt()),
1125 UpdateBlockPacket::FLAG_NETWORK,
1126 UpdateBlockPacket::DATA_LAYER_NORMAL
1127 );
1128 }
1129 }
1130 $packets[] = UpdateBlockPacket::create(
1131 $blockPosition,
1132 $blockTranslator->internalIdToNetworkId($fullBlock->getStateId()),
1133 UpdateBlockPacket::FLAG_NETWORK,
1134 UpdateBlockPacket::DATA_LAYER_NORMAL
1135 );
1136
1137 if($tile instanceof Spawnable){
1138 $packets[] = BlockActorDataPacket::create($blockPosition, $tile->getSerializedSpawnCompound());
1139 }
1140 }
1141
1142 return $packets;
1143 }
1144
1145 public function clearCache(bool $force = false) : void{
1146 if($force){
1147 $this->blockCache = [];
1148 $this->blockCacheSize = 0;
1149 $this->blockCollisionBoxCache = [];
1150 }else{
1151 //Recalculate this when we're asked - blockCacheSize may be higher than the real size
1152 $this->blockCacheSize = 0;
1153 foreach($this->blockCache as $list){
1154 $this->blockCacheSize += count($list);
1155 if($this->blockCacheSize > self::BLOCK_CACHE_SIZE_CAP){
1156 $this->blockCache = [];
1157 $this->blockCacheSize = 0;
1158 break;
1159 }
1160 }
1161
1162 $count = 0;
1163 foreach($this->blockCollisionBoxCache as $list){
1164 $count += count($list);
1165 if($count > self::BLOCK_CACHE_SIZE_CAP){
1166 //TODO: Is this really the best logic?
1167 $this->blockCollisionBoxCache = [];
1168 break;
1169 }
1170 }
1171 }
1172 }
1173
1174 private function trimBlockCache() : void{
1175 $before = $this->blockCacheSize;
1176 //Since PHP maintains key order, earliest in foreach should be the oldest entries
1177 //Older entries are less likely to be hot, so destroying these should usually have the lowest impact on performance
1178 foreach($this->blockCache as $chunkHash => $blocks){
1179 unset($this->blockCache[$chunkHash]);
1180 $this->blockCacheSize -= count($blocks);
1181 if($this->blockCacheSize < self::BLOCK_CACHE_SIZE_CAP){
1182 break;
1183 }
1184 }
1185 }
1186
1191 public function getRandomTickedBlocks() : array{
1192 return $this->randomTickBlocks;
1193 }
1194
1195 public function addRandomTickedBlock(Block $block) : void{
1196 if($block instanceof UnknownBlock){
1197 throw new \InvalidArgumentException("Cannot do random-tick on unknown block");
1198 }
1199 $this->randomTickBlocks[$block->getStateId()] = true;
1200 }
1201
1202 public function removeRandomTickedBlock(Block $block) : void{
1203 unset($this->randomTickBlocks[$block->getStateId()]);
1204 }
1205
1210 public function getChunkTickRadius() : int{
1211 return $this->chunkTickRadius;
1212 }
1213
1218 public function setChunkTickRadius(int $radius) : void{
1219 $this->chunkTickRadius = $radius;
1220 }
1221
1229 public function getTickingChunks() : array{
1230 return array_keys($this->validTickingChunks);
1231 }
1232
1237 public function registerTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ) : void{
1238 $chunkPosHash = World::chunkHash($chunkX, $chunkZ);
1239 $this->registeredTickingChunks[$chunkPosHash][spl_object_id($ticker)] = $ticker;
1240 $this->recheckTickingChunks[$chunkPosHash] = $chunkPosHash;
1241 }
1242
1247 public function unregisterTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ) : void{
1248 $chunkHash = World::chunkHash($chunkX, $chunkZ);
1249 $tickerId = spl_object_id($ticker);
1250 if(isset($this->registeredTickingChunks[$chunkHash][$tickerId])){
1251 if(count($this->registeredTickingChunks[$chunkHash]) === 1){
1252 unset(
1253 $this->registeredTickingChunks[$chunkHash],
1254 $this->recheckTickingChunks[$chunkHash],
1255 $this->validTickingChunks[$chunkHash]
1256 );
1257 }else{
1258 unset($this->registeredTickingChunks[$chunkHash][$tickerId]);
1259 }
1260 }
1261 }
1262
1263 private function tickChunks() : void{
1264 if($this->chunkTickRadius <= 0 || count($this->registeredTickingChunks) === 0){
1265 return;
1266 }
1267
1268 if(count($this->recheckTickingChunks) > 0){
1269 $this->timings->randomChunkUpdatesChunkSelection->startTiming();
1270
1271 $chunkTickableCache = [];
1272
1273 foreach($this->recheckTickingChunks as $hash => $_){
1274 World::getXZ($hash, $chunkX, $chunkZ);
1275 if($this->isChunkTickable($chunkX, $chunkZ, $chunkTickableCache)){
1276 $this->validTickingChunks[$hash] = $hash;
1277 }
1278 }
1279 $this->recheckTickingChunks = [];
1280
1281 $this->timings->randomChunkUpdatesChunkSelection->stopTiming();
1282 }
1283
1284 foreach($this->validTickingChunks as $index => $_){
1285 World::getXZ($index, $chunkX, $chunkZ);
1286
1287 $this->tickChunk($chunkX, $chunkZ);
1288 }
1289 }
1290
1297 private function isChunkTickable(int $chunkX, int $chunkZ, array &$cache) : bool{
1298 for($cx = -1; $cx <= 1; ++$cx){
1299 for($cz = -1; $cz <= 1; ++$cz){
1300 $chunkHash = World::chunkHash($chunkX + $cx, $chunkZ + $cz);
1301 if(isset($cache[$chunkHash])){
1302 if(!$cache[$chunkHash]){
1303 return false;
1304 }
1305 continue;
1306 }
1307 if($this->isChunkLocked($chunkX + $cx, $chunkZ + $cz)){
1308 $cache[$chunkHash] = false;
1309 return false;
1310 }
1311 $adjacentChunk = $this->getChunk($chunkX + $cx, $chunkZ + $cz);
1312 if($adjacentChunk === null || !$adjacentChunk->isPopulated()){
1313 $cache[$chunkHash] = false;
1314 return false;
1315 }
1316 $lightPopulatedState = $adjacentChunk->isLightPopulated();
1317 if($lightPopulatedState !== true){
1318 if($lightPopulatedState === false){
1319 $this->orderLightPopulation($chunkX + $cx, $chunkZ + $cz);
1320 }
1321 $cache[$chunkHash] = false;
1322 return false;
1323 }
1324
1325 $cache[$chunkHash] = true;
1326 }
1327 }
1328
1329 return true;
1330 }
1331
1341 private function markTickingChunkForRecheck(int $chunkX, int $chunkZ) : void{
1342 for($cx = -1; $cx <= 1; ++$cx){
1343 for($cz = -1; $cz <= 1; ++$cz){
1344 $chunkHash = World::chunkHash($chunkX + $cx, $chunkZ + $cz);
1345 unset($this->validTickingChunks[$chunkHash]);
1346 if(isset($this->registeredTickingChunks[$chunkHash])){
1347 $this->recheckTickingChunks[$chunkHash] = $chunkHash;
1348 }else{
1349 unset($this->recheckTickingChunks[$chunkHash]);
1350 }
1351 }
1352 }
1353 }
1354
1355 private function orderLightPopulation(int $chunkX, int $chunkZ) : void{
1356 $chunkHash = World::chunkHash($chunkX, $chunkZ);
1357 $lightPopulatedState = $this->chunks[$chunkHash]->isLightPopulated();
1358 if($lightPopulatedState === false){
1359 $this->chunks[$chunkHash]->setLightPopulated(null);
1360 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
1361
1362 $this->workerPool->submitTask(new LightPopulationTask(
1363 $this->chunks[$chunkHash],
1364 function(array $blockLight, array $skyLight, array $heightMap) use ($chunkX, $chunkZ) : void{
1371 if($this->unloaded || ($chunk = $this->getChunk($chunkX, $chunkZ)) === null || $chunk->isLightPopulated() === true){
1372 return;
1373 }
1374 //TODO: calculated light information might not be valid if the terrain changed during light calculation
1375
1376 $chunk->setHeightMapArray($heightMap);
1377 foreach($blockLight as $y => $lightArray){
1378 $chunk->getSubChunk($y)->setBlockLightArray($lightArray);
1379 }
1380 foreach($skyLight as $y => $lightArray){
1381 $chunk->getSubChunk($y)->setBlockSkyLightArray($lightArray);
1382 }
1383 $chunk->setLightPopulated(true);
1384 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
1385 }
1386 ));
1387 }
1388 }
1389
1390 private function tickChunk(int $chunkX, int $chunkZ) : void{
1391 $chunk = $this->getChunk($chunkX, $chunkZ);
1392 if($chunk === null){
1393 //the chunk may have been unloaded during a previous chunk's update (e.g. during BlockGrowEvent)
1394 return;
1395 }
1396 foreach($this->getChunkEntities($chunkX, $chunkZ) as $entity){
1397 $entity->onRandomUpdate();
1398 }
1399
1400 $blockFactory = $this->blockStateRegistry;
1401 foreach($chunk->getSubChunks() as $Y => $subChunk){
1402 if(!$subChunk->isEmptyFast()){
1403 $k = 0;
1404 for($i = 0; $i < $this->tickedBlocksPerSubchunkPerTick; ++$i){
1405 if(($i % 5) === 0){
1406 //60 bits will be used by 5 blocks (12 bits each)
1407 $k = mt_rand(0, (1 << 60) - 1);
1408 }
1409 $x = $k & SubChunk::COORD_MASK;
1410 $y = ($k >> SubChunk::COORD_BIT_SIZE) & SubChunk::COORD_MASK;
1411 $z = ($k >> (SubChunk::COORD_BIT_SIZE * 2)) & SubChunk::COORD_MASK;
1412 $k >>= (SubChunk::COORD_BIT_SIZE * 3);
1413
1414 $state = $subChunk->getBlockStateId($x, $y, $z);
1415
1416 if(isset($this->randomTickBlocks[$state])){
1417 $block = $blockFactory->fromStateId($state);
1418 $block->position($this, $chunkX * Chunk::EDGE_LENGTH + $x, ($Y << SubChunk::COORD_BIT_SIZE) + $y, $chunkZ * Chunk::EDGE_LENGTH + $z);
1419 $block->onRandomTick();
1420 }
1421 }
1422 }
1423 }
1424 }
1425
1429 public function __debugInfo() : array{
1430 return [];
1431 }
1432
1433 public function save(bool $force = false) : bool{
1434
1435 if(!$this->getAutoSave() && !$force){
1436 return false;
1437 }
1438
1439 (new WorldSaveEvent($this))->call();
1440
1441 $timings = $this->timings->syncDataSave;
1442 $timings->startTiming();
1443
1444 $this->provider->getWorldData()->setTime($this->time);
1445 $this->saveChunks();
1446 $this->provider->getWorldData()->save();
1447
1448 $timings->stopTiming();
1449
1450 return true;
1451 }
1452
1453 public function saveChunks() : void{
1454 $this->timings->syncChunkSave->startTiming();
1455 try{
1456 foreach($this->chunks as $chunkHash => $chunk){
1457 self::getXZ($chunkHash, $chunkX, $chunkZ);
1458 $this->provider->saveChunk($chunkX, $chunkZ, new ChunkData(
1459 $chunk->getSubChunks(),
1460 $chunk->isPopulated(),
1461 array_map(fn(Entity $e) => $e->saveNBT(), array_values(array_filter($this->getChunkEntities($chunkX, $chunkZ), fn(Entity $e) => $e->canSaveWithChunk()))),
1462 array_map(fn(Tile $t) => $t->saveNBT(), array_values($chunk->getTiles())),
1463 ), $chunk->getTerrainDirtyFlags());
1464 $chunk->clearTerrainDirtyFlags();
1465 }
1466 }finally{
1467 $this->timings->syncChunkSave->stopTiming();
1468 }
1469 }
1470
1475 public function scheduleDelayedBlockUpdate(Vector3 $pos, int $delay) : void{
1476 if(
1477 !$this->isInWorld($pos->x, $pos->y, $pos->z) ||
1478 (isset($this->scheduledBlockUpdateQueueIndex[$index = World::blockHash($pos->x, $pos->y, $pos->z)]) && $this->scheduledBlockUpdateQueueIndex[$index] <= $delay)
1479 ){
1480 return;
1481 }
1482 $this->scheduledBlockUpdateQueueIndex[$index] = $delay;
1483 $this->scheduledBlockUpdateQueue->insert(new Vector3((int) $pos->x, (int) $pos->y, (int) $pos->z), $delay + $this->server->getTick());
1484 }
1485
1486 private function tryAddToNeighbourUpdateQueue(int $x, int $y, int $z) : void{
1487 if($this->isInWorld($x, $y, $z)){
1488 $hash = World::blockHash($x, $y, $z);
1489 if(!isset($this->neighbourBlockUpdateQueueIndex[$hash])){
1490 $this->neighbourBlockUpdateQueue->enqueue($hash);
1491 $this->neighbourBlockUpdateQueueIndex[$hash] = true;
1492 }
1493 }
1494 }
1495
1502 private function internalNotifyNeighbourBlockUpdate(int $x, int $y, int $z) : void{
1503 $this->tryAddToNeighbourUpdateQueue($x, $y, $z);
1504 foreach(Facing::OFFSET as [$dx, $dy, $dz]){
1505 $this->tryAddToNeighbourUpdateQueue($x + $dx, $y + $dy, $z + $dz);
1506 }
1507 }
1508
1516 public function notifyNeighbourBlockUpdate(Vector3 $pos) : void{
1517 $this->internalNotifyNeighbourBlockUpdate($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ());
1518 }
1519
1524 public function getCollisionBlocks(AxisAlignedBB $bb, bool $targetFirst = false) : array{
1525 $minX = (int) floor($bb->minX - 1);
1526 $minY = (int) floor($bb->minY - 1);
1527 $minZ = (int) floor($bb->minZ - 1);
1528 $maxX = (int) floor($bb->maxX + 1);
1529 $maxY = (int) floor($bb->maxY + 1);
1530 $maxZ = (int) floor($bb->maxZ + 1);
1531
1532 $collides = [];
1533
1534 $collisionInfo = $this->blockStateRegistry->collisionInfo;
1535 if($targetFirst){
1536 for($z = $minZ; $z <= $maxZ; ++$z){
1537 $zOverflow = $z === $minZ || $z === $maxZ;
1538 for($x = $minX; $x <= $maxX; ++$x){
1539 $zxOverflow = $zOverflow || $x === $minX || $x === $maxX;
1540 for($y = $minY; $y <= $maxY; ++$y){
1541 $overflow = $zxOverflow || $y === $minY || $y === $maxY;
1542
1543 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1544 if($overflow ?
1545 $stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW && $this->getBlockAt($x, $y, $z)->collidesWithBB($bb) :
1546 match ($stateCollisionInfo) {
1547 RuntimeBlockStateRegistry::COLLISION_CUBE => true,
1548 RuntimeBlockStateRegistry::COLLISION_NONE => false,
1549 default => $this->getBlockAt($x, $y, $z)->collidesWithBB($bb)
1550 }
1551 ){
1552 return [$this->getBlockAt($x, $y, $z)];
1553 }
1554 }
1555 }
1556 }
1557 }else{
1558 //TODO: duplicated code :( this way is better for performance though
1559 for($z = $minZ; $z <= $maxZ; ++$z){
1560 $zOverflow = $z === $minZ || $z === $maxZ;
1561 for($x = $minX; $x <= $maxX; ++$x){
1562 $zxOverflow = $zOverflow || $x === $minX || $x === $maxX;
1563 for($y = $minY; $y <= $maxY; ++$y){
1564 $overflow = $zxOverflow || $y === $minY || $y === $maxY;
1565
1566 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1567 if($overflow ?
1568 $stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW && $this->getBlockAt($x, $y, $z)->collidesWithBB($bb) :
1569 match ($stateCollisionInfo) {
1570 RuntimeBlockStateRegistry::COLLISION_CUBE => true,
1571 RuntimeBlockStateRegistry::COLLISION_NONE => false,
1572 default => $this->getBlockAt($x, $y, $z)->collidesWithBB($bb)
1573 }
1574 ){
1575 $collides[] = $this->getBlockAt($x, $y, $z);
1576 }
1577 }
1578 }
1579 }
1580 }
1581
1582 return $collides;
1583 }
1584
1589 private function getBlockCollisionInfo(int $x, int $y, int $z, array $collisionInfo) : int{
1590 if(!$this->isInWorld($x, $y, $z)){
1591 return RuntimeBlockStateRegistry::COLLISION_NONE;
1592 }
1593 $chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1594 if($chunk === null){
1595 return RuntimeBlockStateRegistry::COLLISION_NONE;
1596 }
1597 $stateId = $chunk
1598 ->getSubChunk($y >> SubChunk::COORD_BIT_SIZE)
1599 ->getBlockStateId(
1600 $x & SubChunk::COORD_MASK,
1601 $y & SubChunk::COORD_MASK,
1602 $z & SubChunk::COORD_MASK
1603 );
1604 return $collisionInfo[$stateId];
1605 }
1606
1618 private function getBlockCollisionBoxesForCell(int $x, int $y, int $z, array $collisionInfo) : array{
1619 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1620 $boxes = match($stateCollisionInfo){
1621 RuntimeBlockStateRegistry::COLLISION_NONE => [],
1622 RuntimeBlockStateRegistry::COLLISION_CUBE => [AxisAlignedBB::one()->offset($x, $y, $z)],
1623 default => $this->getBlockAt($x, $y, $z)->getCollisionBoxes()
1624 };
1625
1626 //overlapping AABBs can't make any difference if this is a cube, so we can save some CPU cycles in this common case
1627 if($stateCollisionInfo !== RuntimeBlockStateRegistry::COLLISION_CUBE){
1628 $cellBB = null;
1629 foreach(Facing::OFFSET as [$dx, $dy, $dz]){
1630 $offsetX = $x + $dx;
1631 $offsetY = $y + $dy;
1632 $offsetZ = $z + $dz;
1633 $stateCollisionInfo = $this->getBlockCollisionInfo($offsetX, $offsetY, $offsetZ, $collisionInfo);
1634 if($stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW){
1635 //avoid allocating this unless it's needed
1636 $cellBB ??= AxisAlignedBB::one()->offset($x, $y, $z);
1637 $extraBoxes = $this->getBlockAt($offsetX, $offsetY, $offsetZ)->getCollisionBoxes();
1638 foreach($extraBoxes as $extraBox){
1639 if($extraBox->intersectsWith($cellBB)){
1640 $boxes[] = $extraBox;
1641 }
1642 }
1643 }
1644 }
1645 }
1646
1647 return $boxes;
1648 }
1649
1654 public function getBlockCollisionBoxes(AxisAlignedBB $bb) : array{
1655 $minX = (int) floor($bb->minX);
1656 $minY = (int) floor($bb->minY);
1657 $minZ = (int) floor($bb->minZ);
1658 $maxX = (int) floor($bb->maxX);
1659 $maxY = (int) floor($bb->maxY);
1660 $maxZ = (int) floor($bb->maxZ);
1661
1662 $collides = [];
1663
1664 $collisionInfo = $this->blockStateRegistry->collisionInfo;
1665
1666 for($z = $minZ; $z <= $maxZ; ++$z){
1667 for($x = $minX; $x <= $maxX; ++$x){
1668 $chunkPosHash = World::chunkHash($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1669 for($y = $minY; $y <= $maxY; ++$y){
1670 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
1671
1672 $boxes = $this->blockCollisionBoxCache[$chunkPosHash][$relativeBlockHash] ??= $this->getBlockCollisionBoxesForCell($x, $y, $z, $collisionInfo);
1673
1674 foreach($boxes as $blockBB){
1675 if($blockBB->intersectsWith($bb)){
1676 $collides[] = $blockBB;
1677 }
1678 }
1679 }
1680 }
1681 }
1682
1683 return $collides;
1684 }
1685
1690 public function computeSunAnglePercentage() : float{
1691 $timeProgress = ($this->time % self::TIME_FULL) / self::TIME_FULL;
1692
1693 //0.0 needs to be high noon, not dusk
1694 $sunProgress = $timeProgress + ($timeProgress < 0.25 ? 0.75 : -0.25);
1695
1696 //Offset the sun progress to be above the horizon longer at dusk and dawn
1697 //this is roughly an inverted sine curve, which pushes the sun progress back at dusk and forwards at dawn
1698 $diff = (((1 - ((cos($sunProgress * M_PI) + 1) / 2)) - $sunProgress) / 3);
1699
1700 return $sunProgress + $diff;
1701 }
1702
1706 public function getSunAnglePercentage() : float{
1707 return $this->sunAnglePercentage;
1708 }
1709
1713 public function getSunAngleRadians() : float{
1714 return $this->sunAnglePercentage * 2 * M_PI;
1715 }
1716
1720 public function getSunAngleDegrees() : float{
1721 return $this->sunAnglePercentage * 360.0;
1722 }
1723
1728 public function computeSkyLightReduction() : int{
1729 $percentage = max(0, min(1, -(cos($this->getSunAngleRadians()) * 2 - 0.5)));
1730
1731 //TODO: check rain and thunder level
1732
1733 return (int) ($percentage * 11);
1734 }
1735
1739 public function getSkyLightReduction() : int{
1740 return $this->skyLightReduction;
1741 }
1742
1747 public function getFullLight(Vector3 $pos) : int{
1748 $floorX = $pos->getFloorX();
1749 $floorY = $pos->getFloorY();
1750 $floorZ = $pos->getFloorZ();
1751 return $this->getFullLightAt($floorX, $floorY, $floorZ);
1752 }
1753
1758 public function getFullLightAt(int $x, int $y, int $z) : int{
1759 $skyLight = $this->getRealBlockSkyLightAt($x, $y, $z);
1760 if($skyLight < 15){
1761 return max($skyLight, $this->getBlockLightAt($x, $y, $z));
1762 }else{
1763 return $skyLight;
1764 }
1765 }
1766
1771 public function getHighestAdjacentFullLightAt(int $x, int $y, int $z) : int{
1772 return $this->getHighestAdjacentLight($x, $y, $z, $this->getFullLightAt(...));
1773 }
1774
1779 public function getPotentialLight(Vector3 $pos) : int{
1780 $floorX = $pos->getFloorX();
1781 $floorY = $pos->getFloorY();
1782 $floorZ = $pos->getFloorZ();
1783 return $this->getPotentialLightAt($floorX, $floorY, $floorZ);
1784 }
1785
1790 public function getPotentialLightAt(int $x, int $y, int $z) : int{
1791 return max($this->getPotentialBlockSkyLightAt($x, $y, $z), $this->getBlockLightAt($x, $y, $z));
1792 }
1793
1798 public function getHighestAdjacentPotentialLightAt(int $x, int $y, int $z) : int{
1799 return $this->getHighestAdjacentLight($x, $y, $z, $this->getPotentialLightAt(...));
1800 }
1801
1808 public function getPotentialBlockSkyLightAt(int $x, int $y, int $z) : int{
1809 if(!$this->isInWorld($x, $y, $z)){
1810 return $y >= self::Y_MAX ? 15 : 0;
1811 }
1812 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null && $chunk->isLightPopulated() === true){
1813 return $chunk->getSubChunk($y >> Chunk::COORD_BIT_SIZE)->getBlockSkyLightArray()->get($x & SubChunk::COORD_MASK, $y & SubChunk::COORD_MASK, $z & SubChunk::COORD_MASK);
1814 }
1815 return 0; //TODO: this should probably throw instead (light not calculated yet)
1816 }
1817
1823 public function getRealBlockSkyLightAt(int $x, int $y, int $z) : int{
1824 $light = $this->getPotentialBlockSkyLightAt($x, $y, $z) - $this->skyLightReduction;
1825 return $light < 0 ? 0 : $light;
1826 }
1827
1833 public function getBlockLightAt(int $x, int $y, int $z) : int{
1834 if(!$this->isInWorld($x, $y, $z)){
1835 return 0;
1836 }
1837 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null && $chunk->isLightPopulated() === true){
1838 return $chunk->getSubChunk($y >> Chunk::COORD_BIT_SIZE)->getBlockLightArray()->get($x & SubChunk::COORD_MASK, $y & SubChunk::COORD_MASK, $z & SubChunk::COORD_MASK);
1839 }
1840 return 0; //TODO: this should probably throw instead (light not calculated yet)
1841 }
1842
1843 public function updateAllLight(int $x, int $y, int $z) : void{
1844 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) === null || $chunk->isLightPopulated() !== true){
1845 return;
1846 }
1847
1848 $blockFactory = $this->blockStateRegistry;
1849 $this->timings->doBlockSkyLightUpdates->startTiming();
1850 if($this->skyLightUpdate === null){
1851 $this->skyLightUpdate = new SkyLightUpdate(new SubChunkExplorer($this), $blockFactory->lightFilter, $blockFactory->blocksDirectSkyLight);
1852 }
1853 $this->skyLightUpdate->recalculateNode($x, $y, $z);
1854 $this->timings->doBlockSkyLightUpdates->stopTiming();
1855
1856 $this->timings->doBlockLightUpdates->startTiming();
1857 if($this->blockLightUpdate === null){
1858 $this->blockLightUpdate = new BlockLightUpdate(new SubChunkExplorer($this), $blockFactory->lightFilter, $blockFactory->light);
1859 }
1860 $this->blockLightUpdate->recalculateNode($x, $y, $z);
1861 $this->timings->doBlockLightUpdates->stopTiming();
1862 }
1863
1867 private function getHighestAdjacentLight(int $x, int $y, int $z, \Closure $lightGetter) : int{
1868 $max = 0;
1869 foreach(Facing::OFFSET as [$offsetX, $offsetY, $offsetZ]){
1870 $x1 = $x + $offsetX;
1871 $y1 = $y + $offsetY;
1872 $z1 = $z + $offsetZ;
1873 if(
1874 !$this->isInWorld($x1, $y1, $z1) ||
1875 ($chunk = $this->getChunk($x1 >> Chunk::COORD_BIT_SIZE, $z1 >> Chunk::COORD_BIT_SIZE)) === null ||
1876 $chunk->isLightPopulated() !== true
1877 ){
1878 continue;
1879 }
1880 $max = max($max, $lightGetter($x1, $y1, $z1));
1881 }
1882 return $max;
1883 }
1884
1888 public function getHighestAdjacentPotentialBlockSkyLight(int $x, int $y, int $z) : int{
1889 return $this->getHighestAdjacentLight($x, $y, $z, $this->getPotentialBlockSkyLightAt(...));
1890 }
1891
1896 public function getHighestAdjacentRealBlockSkyLight(int $x, int $y, int $z) : int{
1897 return $this->getHighestAdjacentPotentialBlockSkyLight($x, $y, $z) - $this->skyLightReduction;
1898 }
1899
1903 public function getHighestAdjacentBlockLight(int $x, int $y, int $z) : int{
1904 return $this->getHighestAdjacentLight($x, $y, $z, $this->getBlockLightAt(...));
1905 }
1906
1907 private function executeQueuedLightUpdates() : void{
1908 if($this->blockLightUpdate !== null){
1909 $this->timings->doBlockLightUpdates->startTiming();
1910 $this->blockLightUpdate->execute();
1911 $this->blockLightUpdate = null;
1912 $this->timings->doBlockLightUpdates->stopTiming();
1913 }
1914
1915 if($this->skyLightUpdate !== null){
1916 $this->timings->doBlockSkyLightUpdates->startTiming();
1917 $this->skyLightUpdate->execute();
1918 $this->skyLightUpdate = null;
1919 $this->timings->doBlockSkyLightUpdates->stopTiming();
1920 }
1921 }
1922
1923 public function isInWorld(int $x, int $y, int $z) : bool{
1924 return (
1925 $x <= Limits::INT32_MAX && $x >= Limits::INT32_MIN &&
1926 $y < $this->maxY && $y >= $this->minY &&
1927 $z <= Limits::INT32_MAX && $z >= Limits::INT32_MIN
1928 );
1929 }
1930
1941 public function getBlock(Vector3 $pos, bool $cached = true, bool $addToCache = true) : Block{
1942 return $this->getBlockAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z), $cached, $addToCache);
1943 }
1944
1954 public function getBlockAt(int $x, int $y, int $z, bool $cached = true, bool $addToCache = true) : Block{
1955 $relativeBlockHash = null;
1956 $chunkHash = World::chunkHash($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1957
1958 if($this->isInWorld($x, $y, $z)){
1959 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
1960
1961 if($cached && isset($this->blockCache[$chunkHash][$relativeBlockHash])){
1962 return $this->blockCache[$chunkHash][$relativeBlockHash];
1963 }
1964
1965 $chunk = $this->chunks[$chunkHash] ?? null;
1966 if($chunk !== null){
1967 $block = $this->blockStateRegistry->fromStateId($chunk->getBlockStateId($x & Chunk::COORD_MASK, $y, $z & Chunk::COORD_MASK));
1968 }else{
1969 $addToCache = false;
1970 $block = VanillaBlocks::AIR();
1971 }
1972 }else{
1973 $block = VanillaBlocks::AIR();
1974 }
1975
1976 $block->position($this, $x, $y, $z);
1977
1978 if($this->inDynamicStateRecalculation){
1979 //this call was generated by a parent getBlock() call calculating dynamic stateinfo
1980 //don't calculate dynamic state and don't add to block cache (since it won't have dynamic state calculated).
1981 //this ensures that it's impossible for dynamic state properties to recursively depend on each other.
1982 $addToCache = false;
1983 }else{
1984 $this->inDynamicStateRecalculation = true;
1985 $replacement = $block->readStateFromWorld();
1986 if($replacement !== $block){
1987 $replacement->position($this, $x, $y, $z);
1988 $block = $replacement;
1989 }
1990 $this->inDynamicStateRecalculation = false;
1991 }
1992
1993 if($addToCache && $relativeBlockHash !== null){
1994 $this->blockCache[$chunkHash][$relativeBlockHash] = $block;
1995
1996 if(++$this->blockCacheSize >= self::BLOCK_CACHE_SIZE_CAP){
1997 $this->trimBlockCache();
1998 }
1999 }
2000
2001 return $block;
2002 }
2003
2009 public function setBlock(Vector3 $pos, Block $block, bool $update = true) : void{
2010 $this->setBlockAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z), $block, $update);
2011 }
2012
2021 public function setBlockAt(int $x, int $y, int $z, Block $block, bool $update = true) : void{
2022 if(!$this->isInWorld($x, $y, $z)){
2023 throw new \InvalidArgumentException("Pos x=$x,y=$y,z=$z is outside of the world bounds");
2024 }
2025 $chunkX = $x >> Chunk::COORD_BIT_SIZE;
2026 $chunkZ = $z >> Chunk::COORD_BIT_SIZE;
2027 if($this->loadChunk($chunkX, $chunkZ) === null){ //current expected behaviour is to try to load the terrain synchronously
2028 throw new WorldException("Cannot set a block in un-generated terrain");
2029 }
2030
2031 $this->timings->setBlock->startTiming();
2032
2033 $this->unlockChunk($chunkX, $chunkZ, null);
2034
2035 $block = clone $block;
2036
2037 $block->position($this, $x, $y, $z);
2038 $block->writeStateToWorld();
2039 $pos = new Vector3($x, $y, $z);
2040
2041 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2042 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
2043
2044 unset($this->blockCache[$chunkHash][$relativeBlockHash]);
2045 $this->blockCacheSize--;
2046 unset($this->blockCollisionBoxCache[$chunkHash][$relativeBlockHash]);
2047 //blocks like fences have collision boxes that reach into neighbouring blocks, so we need to invalidate the
2048 //caches for those blocks as well
2049 foreach(Facing::OFFSET as [$offsetX, $offsetY, $offsetZ]){
2050 $sideChunkPosHash = World::chunkHash(($x + $offsetX) >> Chunk::COORD_BIT_SIZE, ($z + $offsetZ) >> Chunk::COORD_BIT_SIZE);
2051 $sideChunkBlockHash = World::chunkBlockHash($x + $offsetX, $y + $offsetY, $z + $offsetZ);
2052 unset($this->blockCollisionBoxCache[$sideChunkPosHash][$sideChunkBlockHash]);
2053 }
2054
2055 if(!isset($this->changedBlocks[$chunkHash])){
2056 $this->changedBlocks[$chunkHash] = [];
2057 }
2058 $this->changedBlocks[$chunkHash][$relativeBlockHash] = $pos;
2059
2060 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2061 $listener->onBlockChanged($pos);
2062 }
2063
2064 if($update){
2065 $this->updateAllLight($x, $y, $z);
2066 $this->internalNotifyNeighbourBlockUpdate($x, $y, $z);
2067 }
2068
2069 $this->timings->setBlock->stopTiming();
2070 }
2071
2072 public function dropItem(Vector3 $source, Item $item, ?Vector3 $motion = null, int $delay = 10) : ?ItemEntity{
2073 if($item->isNull()){
2074 return null;
2075 }
2076
2077 $itemEntity = new ItemEntity(Location::fromObject($source, $this, Utils::getRandomFloat() * 360, 0), $item);
2078
2079 $itemEntity->setPickupDelay($delay);
2080 $itemEntity->setMotion($motion ?? new Vector3(Utils::getRandomFloat() * 0.2 - 0.1, 0.2, Utils::getRandomFloat() * 0.2 - 0.1));
2081 $itemEntity->spawnToAll();
2082
2083 return $itemEntity;
2084 }
2085
2092 public function dropExperience(Vector3 $pos, int $amount) : array{
2093 $orbs = [];
2094
2095 foreach(ExperienceOrb::splitIntoOrbSizes($amount) as $split){
2096 $orb = new ExperienceOrb(Location::fromObject($pos, $this, Utils::getRandomFloat() * 360, 0), $split);
2097
2098 $orb->setMotion(new Vector3((Utils::getRandomFloat() * 0.2 - 0.1) * 2, Utils::getRandomFloat() * 0.4, (Utils::getRandomFloat() * 0.2 - 0.1) * 2));
2099 $orb->spawnToAll();
2100
2101 $orbs[] = $orb;
2102 }
2103
2104 return $orbs;
2105 }
2106
2115 public function useBreakOn(Vector3 $vector, ?Item &$item = null, ?Player $player = null, bool $createParticles = false, array &$returnedItems = []) : bool{
2116 $vector = $vector->floor();
2117
2118 $chunkX = $vector->getFloorX() >> Chunk::COORD_BIT_SIZE;
2119 $chunkZ = $vector->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2120 if(!$this->isChunkLoaded($chunkX, $chunkZ) || $this->isChunkLocked($chunkX, $chunkZ)){
2121 return false;
2122 }
2123
2124 $target = $this->getBlock($vector);
2125 $affectedBlocks = $target->getAffectedBlocks();
2126
2127 if($item === null){
2128 $item = VanillaItems::AIR();
2129 }
2130
2131 $drops = [];
2132 if($player === null || $player->hasFiniteResources()){
2133 $drops = array_merge(...array_map(fn(Block $block) => $block->getDrops($item), $affectedBlocks));
2134 }
2135
2136 $xpDrop = 0;
2137 if($player !== null && $player->hasFiniteResources()){
2138 $xpDrop = array_sum(array_map(fn(Block $block) => $block->getXpDropForTool($item), $affectedBlocks));
2139 }
2140
2141 if($player !== null){
2142 $ev = new BlockBreakEvent($player, $target, $item, $player->isCreative(), $drops, $xpDrop);
2143
2144 if($target instanceof Air || ($player->isSurvival() && !$target->getBreakInfo()->isBreakable()) || $player->isSpectator()){
2145 $ev->cancel();
2146 }
2147
2148 if($player->isAdventure(true) && !$ev->isCancelled()){
2149 $canBreak = false;
2150 $itemParser = LegacyStringToItemParser::getInstance();
2151 foreach($item->getCanDestroy() as $v){
2152 $entry = $itemParser->parse($v);
2153 if($entry->getBlock()->hasSameTypeId($target)){
2154 $canBreak = true;
2155 break;
2156 }
2157 }
2158
2159 if(!$canBreak){
2160 $ev->cancel();
2161 }
2162 }
2163
2164 $ev->call();
2165 if($ev->isCancelled()){
2166 return false;
2167 }
2168
2169 $drops = $ev->getDrops();
2170 $xpDrop = $ev->getXpDropAmount();
2171
2172 }elseif(!$target->getBreakInfo()->isBreakable()){
2173 return false;
2174 }
2175
2176 foreach($affectedBlocks as $t){
2177 $this->destroyBlockInternal($t, $item, $player, $createParticles, $returnedItems);
2178 }
2179
2180 $item->onDestroyBlock($target, $returnedItems);
2181
2182 if(count($drops) > 0){
2183 $dropPos = $vector->add(0.5, 0.5, 0.5);
2184 foreach($drops as $drop){
2185 if(!$drop->isNull()){
2186 $this->dropItem($dropPos, $drop);
2187 }
2188 }
2189 }
2190
2191 if($xpDrop > 0){
2192 $this->dropExperience($vector->add(0.5, 0.5, 0.5), $xpDrop);
2193 }
2194
2195 return true;
2196 }
2197
2201 private function destroyBlockInternal(Block $target, Item $item, ?Player $player, bool $createParticles, array &$returnedItems) : void{
2202 if($createParticles){
2203 $this->addParticle($target->getPosition()->add(0.5, 0.5, 0.5), new BlockBreakParticle($target));
2204 }
2205
2206 $target->onBreak($item, $player, $returnedItems);
2207
2208 $tile = $this->getTile($target->getPosition());
2209 if($tile !== null){
2210 $tile->onBlockDestroyed();
2211 }
2212 }
2213
2221 public function useItemOn(Vector3 $vector, Item &$item, int $face, ?Vector3 $clickVector = null, ?Player $player = null, bool $playSound = false, array &$returnedItems = []) : bool{
2222 $blockClicked = $this->getBlock($vector);
2223 $blockReplace = $blockClicked->getSide($face);
2224
2225 if($clickVector === null){
2226 $clickVector = new Vector3(0.0, 0.0, 0.0);
2227 }else{
2228 $clickVector = new Vector3(
2229 min(1.0, max(0.0, $clickVector->x)),
2230 min(1.0, max(0.0, $clickVector->y)),
2231 min(1.0, max(0.0, $clickVector->z))
2232 );
2233 }
2234
2235 if(!$this->isInWorld($blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z)){
2236 //TODO: build height limit messages for custom world heights and mcregion cap
2237 return false;
2238 }
2239 $chunkX = $blockReplace->getPosition()->getFloorX() >> Chunk::COORD_BIT_SIZE;
2240 $chunkZ = $blockReplace->getPosition()->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2241 if(!$this->isChunkLoaded($chunkX, $chunkZ) || $this->isChunkLocked($chunkX, $chunkZ)){
2242 return false;
2243 }
2244
2245 if($blockClicked->getTypeId() === BlockTypeIds::AIR){
2246 return false;
2247 }
2248
2249 if($player !== null){
2250 $ev = new PlayerInteractEvent($player, $item, $blockClicked, $clickVector, $face, PlayerInteractEvent::RIGHT_CLICK_BLOCK);
2251 if($player->isSneaking()){
2252 $ev->setUseItem(false);
2253 $ev->setUseBlock($item->isNull()); //opening doors is still possible when sneaking if using an empty hand
2254 }
2255 if($player->isSpectator()){
2256 $ev->cancel(); //set it to cancelled so plugins can bypass this
2257 }
2258
2259 $ev->call();
2260 if(!$ev->isCancelled()){
2261 if($ev->useBlock() && $blockClicked->onInteract($item, $face, $clickVector, $player, $returnedItems)){
2262 return true;
2263 }
2264
2265 if($ev->useItem()){
2266 $result = $item->onInteractBlock($player, $blockReplace, $blockClicked, $face, $clickVector, $returnedItems);
2267 if($result !== ItemUseResult::NONE){
2268 return $result === ItemUseResult::SUCCESS;
2269 }
2270 }
2271 }else{
2272 return false;
2273 }
2274 }elseif($blockClicked->onInteract($item, $face, $clickVector, $player, $returnedItems)){
2275 return true;
2276 }
2277
2278 if($item->isNull() || !$item->canBePlaced()){
2279 return false;
2280 }
2281 $hand = $item->getBlock($face);
2282 $hand->position($this, $blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z);
2283
2284 if($hand->canBePlacedAt($blockClicked, $clickVector, $face, true)){
2285 $blockReplace = $blockClicked;
2286 //TODO: while this mimics the vanilla behaviour with replaceable blocks, we should really pass some other
2287 //value like NULL and let place() deal with it. This will look like a bug to anyone who doesn't know about
2288 //the vanilla behaviour.
2289 $face = Facing::UP;
2290 $hand->position($this, $blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z);
2291 }elseif(!$hand->canBePlacedAt($blockReplace, $clickVector, $face, false)){
2292 return false;
2293 }
2294
2295 $tx = new BlockTransaction($this);
2296 if(!$hand->place($tx, $item, $blockReplace, $blockClicked, $face, $clickVector, $player)){
2297 return false;
2298 }
2299
2300 foreach($tx->getBlocks() as [$x, $y, $z, $block]){
2301 $block->position($this, $x, $y, $z);
2302 foreach($block->getCollisionBoxes() as $collisionBox){
2303 if(count($this->getCollidingEntities($collisionBox)) > 0){
2304 return false; //Entity in block
2305 }
2306 }
2307 }
2308
2309 if($player !== null){
2310 $ev = new BlockPlaceEvent($player, $tx, $blockClicked, $item);
2311 if($player->isSpectator()){
2312 $ev->cancel();
2313 }
2314
2315 if($player->isAdventure(true) && !$ev->isCancelled()){
2316 $canPlace = false;
2317 $itemParser = LegacyStringToItemParser::getInstance();
2318 foreach($item->getCanPlaceOn() as $v){
2319 $entry = $itemParser->parse($v);
2320 if($entry->getBlock()->hasSameTypeId($blockClicked)){
2321 $canPlace = true;
2322 break;
2323 }
2324 }
2325
2326 if(!$canPlace){
2327 $ev->cancel();
2328 }
2329 }
2330
2331 $ev->call();
2332 if($ev->isCancelled()){
2333 return false;
2334 }
2335 }
2336
2337 if(!$tx->apply()){
2338 return false;
2339 }
2340 foreach($tx->getBlocks() as [$x, $y, $z, $_]){
2341 $tile = $this->getTileAt($x, $y, $z);
2342 if($tile !== null){
2343 //TODO: seal this up inside block placement
2344 $tile->copyDataFromItem($item);
2345 }
2346
2347 $this->getBlockAt($x, $y, $z)->onPostPlace();
2348 }
2349
2350 if($playSound){
2351 $this->addSound($hand->getPosition(), new BlockPlaceSound($hand));
2352 }
2353
2354 $item->pop();
2355
2356 return true;
2357 }
2358
2359 public function getEntity(int $entityId) : ?Entity{
2360 return $this->entities[$entityId] ?? null;
2361 }
2362
2369 public function getEntities() : array{
2370 return $this->entities;
2371 }
2372
2383 public function getCollidingEntities(AxisAlignedBB $bb, ?Entity $entity = null) : array{
2384 $nearby = [];
2385
2386 foreach($this->getNearbyEntities($bb, $entity) as $ent){
2387 if($ent->canBeCollidedWith() && ($entity === null || $entity->canCollideWith($ent))){
2388 $nearby[] = $ent;
2389 }
2390 }
2391
2392 return $nearby;
2393 }
2394
2401 public function getNearbyEntities(AxisAlignedBB $bb, ?Entity $entity = null) : array{
2402 $nearby = [];
2403
2404 $minX = ((int) floor($bb->minX - 2)) >> Chunk::COORD_BIT_SIZE;
2405 $maxX = ((int) floor($bb->maxX + 2)) >> Chunk::COORD_BIT_SIZE;
2406 $minZ = ((int) floor($bb->minZ - 2)) >> Chunk::COORD_BIT_SIZE;
2407 $maxZ = ((int) floor($bb->maxZ + 2)) >> Chunk::COORD_BIT_SIZE;
2408
2409 for($x = $minX; $x <= $maxX; ++$x){
2410 for($z = $minZ; $z <= $maxZ; ++$z){
2411 foreach($this->getChunkEntities($x, $z) as $ent){
2412 if($ent !== $entity && $ent->boundingBox->intersectsWith($bb)){
2413 $nearby[] = $ent;
2414 }
2415 }
2416 }
2417 }
2418
2419 return $nearby;
2420 }
2421
2433 public function getNearestEntity(Vector3 $pos, float $maxDistance, string $entityType = Entity::class, bool $includeDead = false) : ?Entity{
2434 assert(is_a($entityType, Entity::class, true));
2435
2436 $minX = ((int) floor($pos->x - $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2437 $maxX = ((int) floor($pos->x + $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2438 $minZ = ((int) floor($pos->z - $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2439 $maxZ = ((int) floor($pos->z + $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2440
2441 $currentTargetDistSq = $maxDistance ** 2;
2442
2447 $currentTarget = null;
2448
2449 for($x = $minX; $x <= $maxX; ++$x){
2450 for($z = $minZ; $z <= $maxZ; ++$z){
2451 foreach($this->getChunkEntities($x, $z) as $entity){
2452 if(!($entity instanceof $entityType) || $entity->isFlaggedForDespawn() || (!$includeDead && !$entity->isAlive())){
2453 continue;
2454 }
2455 $distSq = $entity->getPosition()->distanceSquared($pos);
2456 if($distSq < $currentTargetDistSq){
2457 $currentTargetDistSq = $distSq;
2458 $currentTarget = $entity;
2459 }
2460 }
2461 }
2462 }
2463
2464 return $currentTarget;
2465 }
2466
2473 public function getPlayers() : array{
2474 return $this->players;
2475 }
2476
2483 public function getTile(Vector3 $pos) : ?Tile{
2484 return $this->getTileAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z));
2485 }
2486
2490 public function getTileAt(int $x, int $y, int $z) : ?Tile{
2491 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;
2492 }
2493
2494 public function getBiomeId(int $x, int $y, int $z) : int{
2495 if(($chunk = $this->loadChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null){
2496 return $chunk->getBiomeId($x & Chunk::COORD_MASK, $y & Chunk::COORD_MASK, $z & Chunk::COORD_MASK);
2497 }
2498 return BiomeIds::OCEAN; //TODO: this should probably throw instead (terrain not generated yet)
2499 }
2500
2501 public function getBiome(int $x, int $y, int $z) : Biome{
2502 return BiomeRegistry::getInstance()->getBiome($this->getBiomeId($x, $y, $z));
2503 }
2504
2505 public function setBiomeId(int $x, int $y, int $z, int $biomeId) : void{
2506 $chunkX = $x >> Chunk::COORD_BIT_SIZE;
2507 $chunkZ = $z >> Chunk::COORD_BIT_SIZE;
2508 $this->unlockChunk($chunkX, $chunkZ, null);
2509 if(($chunk = $this->loadChunk($chunkX, $chunkZ)) !== null){
2510 $chunk->setBiomeId($x & Chunk::COORD_MASK, $y & Chunk::COORD_MASK, $z & Chunk::COORD_MASK, $biomeId);
2511 }else{
2512 //if we allowed this, the modifications would be lost when the chunk is created
2513 throw new WorldException("Cannot set biome in a non-generated chunk");
2514 }
2515 }
2516
2521 public function getLoadedChunks() : array{
2522 return $this->chunks;
2523 }
2524
2525 public function getChunk(int $chunkX, int $chunkZ) : ?Chunk{
2526 return $this->chunks[World::chunkHash($chunkX, $chunkZ)] ?? null;
2527 }
2528
2533 public function getChunkEntities(int $chunkX, int $chunkZ) : array{
2534 return $this->entitiesByChunk[World::chunkHash($chunkX, $chunkZ)] ?? [];
2535 }
2536
2540 public function getOrLoadChunkAtPosition(Vector3 $pos) : ?Chunk{
2541 return $this->loadChunk($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2542 }
2543
2550 public function getAdjacentChunks(int $x, int $z) : array{
2551 $result = [];
2552 for($xx = -1; $xx <= 1; ++$xx){
2553 for($zz = -1; $zz <= 1; ++$zz){
2554 if($xx === 0 && $zz === 0){
2555 continue; //center chunk
2556 }
2557 $result[World::chunkHash($xx, $zz)] = $this->loadChunk($x + $xx, $z + $zz);
2558 }
2559 }
2560
2561 return $result;
2562 }
2563
2578 public function lockChunk(int $chunkX, int $chunkZ, ChunkLockId $lockId) : void{
2579 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2580 if(isset($this->chunkLock[$chunkHash])){
2581 throw new \InvalidArgumentException("Chunk $chunkX $chunkZ is already locked");
2582 }
2583 $this->chunkLock[$chunkHash] = $lockId;
2584 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
2585 }
2586
2595 public function unlockChunk(int $chunkX, int $chunkZ, ?ChunkLockId $lockId) : bool{
2596 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2597 if(isset($this->chunkLock[$chunkHash]) && ($lockId === null || $this->chunkLock[$chunkHash] === $lockId)){
2598 unset($this->chunkLock[$chunkHash]);
2599 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
2600 return true;
2601 }
2602 return false;
2603 }
2604
2610 public function isChunkLocked(int $chunkX, int $chunkZ) : bool{
2611 return isset($this->chunkLock[World::chunkHash($chunkX, $chunkZ)]);
2612 }
2613
2614 public function setChunk(int $chunkX, int $chunkZ, Chunk $chunk) : void{
2615 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2616 $oldChunk = $this->loadChunk($chunkX, $chunkZ);
2617 if($oldChunk !== null && $oldChunk !== $chunk){
2618 $deletedTiles = 0;
2619 $transferredTiles = 0;
2620 foreach($oldChunk->getTiles() as $oldTile){
2621 $tilePosition = $oldTile->getPosition();
2622 $localX = $tilePosition->getFloorX() & Chunk::COORD_MASK;
2623 $localY = $tilePosition->getFloorY();
2624 $localZ = $tilePosition->getFloorZ() & Chunk::COORD_MASK;
2625
2626 $newBlock = $this->blockStateRegistry->fromStateId($chunk->getBlockStateId($localX, $localY, $localZ));
2627 $expectedTileClass = $newBlock->getIdInfo()->getTileClass();
2628 if(
2629 $expectedTileClass === null || //new block doesn't expect a tile
2630 !($oldTile instanceof $expectedTileClass) || //new block expects a different tile
2631 (($newTile = $chunk->getTile($localX, $localY, $localZ)) !== null && $newTile !== $oldTile) //new chunk already has a different tile
2632 ){
2633 $oldTile->close();
2634 $deletedTiles++;
2635 }else{
2636 $transferredTiles++;
2637 $chunk->addTile($oldTile);
2638 $oldChunk->removeTile($oldTile);
2639 }
2640 }
2641 if($deletedTiles > 0 || $transferredTiles > 0){
2642 $this->logger->debug("Replacement of chunk $chunkX $chunkZ caused deletion of $deletedTiles obsolete/conflicted tiles, and transfer of $transferredTiles");
2643 }
2644 }
2645
2646 $this->chunks[$chunkHash] = $chunk;
2647
2648 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
2649 unset($this->blockCache[$chunkHash]);
2650 unset($this->blockCollisionBoxCache[$chunkHash]);
2651 unset($this->changedBlocks[$chunkHash]);
2652 $chunk->setTerrainDirty();
2653 $this->markTickingChunkForRecheck($chunkX, $chunkZ); //this replacement chunk may not meet the conditions for ticking
2654
2655 if(!$this->isChunkInUse($chunkX, $chunkZ)){
2656 $this->unloadChunkRequest($chunkX, $chunkZ);
2657 }
2658
2659 if($oldChunk === null){
2660 if(ChunkLoadEvent::hasHandlers()){
2661 (new ChunkLoadEvent($this, $chunkX, $chunkZ, $chunk, true))->call();
2662 }
2663
2664 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2665 $listener->onChunkLoaded($chunkX, $chunkZ, $chunk);
2666 }
2667 }else{
2668 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2669 $listener->onChunkChanged($chunkX, $chunkZ, $chunk);
2670 }
2671 }
2672
2673 for($cX = -1; $cX <= 1; ++$cX){
2674 for($cZ = -1; $cZ <= 1; ++$cZ){
2675 foreach($this->getChunkEntities($chunkX + $cX, $chunkZ + $cZ) as $entity){
2676 $entity->onNearbyBlockChange();
2677 }
2678 }
2679 }
2680 }
2681
2688 public function getHighestBlockAt(int $x, int $z) : ?int{
2689 if(($chunk = $this->loadChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null){
2690 return $chunk->getHighestBlockAt($x & Chunk::COORD_MASK, $z & Chunk::COORD_MASK);
2691 }
2692 throw new WorldException("Cannot get highest block in an ungenerated chunk");
2693 }
2694
2698 public function isInLoadedTerrain(Vector3 $pos) : bool{
2699 return $this->isChunkLoaded($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2700 }
2701
2702 public function isChunkLoaded(int $x, int $z) : bool{
2703 return isset($this->chunks[World::chunkHash($x, $z)]);
2704 }
2705
2706 public function isChunkGenerated(int $x, int $z) : bool{
2707 return $this->loadChunk($x, $z) !== null;
2708 }
2709
2710 public function isChunkPopulated(int $x, int $z) : bool{
2711 $chunk = $this->loadChunk($x, $z);
2712 return $chunk !== null && $chunk->isPopulated();
2713 }
2714
2718 public function getSpawnLocation() : Position{
2719 return Position::fromObject($this->provider->getWorldData()->getSpawn(), $this);
2720 }
2721
2725 public function setSpawnLocation(Vector3 $pos) : void{
2726 $previousSpawn = $this->getSpawnLocation();
2727 $this->provider->getWorldData()->setSpawn($pos);
2728 (new SpawnChangeEvent($this, $previousSpawn))->call();
2729
2730 $location = Position::fromObject($pos, $this);
2731 foreach($this->players as $player){
2732 $player->getNetworkSession()->syncWorldSpawnPoint($location);
2733 }
2734 }
2735
2739 public function addEntity(Entity $entity) : void{
2740 if($entity->isClosed()){
2741 throw new \InvalidArgumentException("Attempted to add a garbage closed Entity to world");
2742 }
2743 if($entity->getWorld() !== $this){
2744 throw new \InvalidArgumentException("Invalid Entity world");
2745 }
2746 if(array_key_exists($entity->getId(), $this->entities)){
2747 if($this->entities[$entity->getId()] === $entity){
2748 throw new \InvalidArgumentException("Entity " . $entity->getId() . " has already been added to this world");
2749 }else{
2750 throw new AssumptionFailedError("Found two different entities sharing entity ID " . $entity->getId());
2751 }
2752 }
2753 $pos = $entity->getPosition()->asVector3();
2754 $this->entitiesByChunk[World::chunkHash($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE)][$entity->getId()] = $entity;
2755 $this->entityLastKnownPositions[$entity->getId()] = $pos;
2756
2757 if($entity instanceof Player){
2758 $this->players[$entity->getId()] = $entity;
2759 }
2760 $this->entities[$entity->getId()] = $entity;
2761 }
2762
2768 public function removeEntity(Entity $entity) : void{
2769 if($entity->getWorld() !== $this){
2770 throw new \InvalidArgumentException("Invalid Entity world");
2771 }
2772 if(!array_key_exists($entity->getId(), $this->entities)){
2773 throw new \InvalidArgumentException("Entity is not tracked by this world (possibly already removed?)");
2774 }
2775 $pos = $this->entityLastKnownPositions[$entity->getId()];
2776 $chunkHash = World::chunkHash($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2777 if(isset($this->entitiesByChunk[$chunkHash][$entity->getId()])){
2778 if(count($this->entitiesByChunk[$chunkHash]) === 1){
2779 unset($this->entitiesByChunk[$chunkHash]);
2780 }else{
2781 unset($this->entitiesByChunk[$chunkHash][$entity->getId()]);
2782 }
2783 }
2784 unset($this->entityLastKnownPositions[$entity->getId()]);
2785
2786 if($entity instanceof Player){
2787 unset($this->players[$entity->getId()]);
2788 $this->checkSleep();
2789 }
2790
2791 unset($this->entities[$entity->getId()]);
2792 unset($this->updateEntities[$entity->getId()]);
2793 }
2794
2798 public function onEntityMoved(Entity $entity) : void{
2799 if(!array_key_exists($entity->getId(), $this->entityLastKnownPositions)){
2800 //this can happen if the entity was teleported before addEntity() was called
2801 return;
2802 }
2803 $oldPosition = $this->entityLastKnownPositions[$entity->getId()];
2804 $newPosition = $entity->getPosition();
2805
2806 $oldChunkX = $oldPosition->getFloorX() >> Chunk::COORD_BIT_SIZE;
2807 $oldChunkZ = $oldPosition->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2808 $newChunkX = $newPosition->getFloorX() >> Chunk::COORD_BIT_SIZE;
2809 $newChunkZ = $newPosition->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2810
2811 if($oldChunkX !== $newChunkX || $oldChunkZ !== $newChunkZ){
2812 $oldChunkHash = World::chunkHash($oldChunkX, $oldChunkZ);
2813 if(isset($this->entitiesByChunk[$oldChunkHash][$entity->getId()])){
2814 if(count($this->entitiesByChunk[$oldChunkHash]) === 1){
2815 unset($this->entitiesByChunk[$oldChunkHash]);
2816 }else{
2817 unset($this->entitiesByChunk[$oldChunkHash][$entity->getId()]);
2818 }
2819 }
2820
2821 $newViewers = $this->getViewersForPosition($newPosition);
2822 foreach($entity->getViewers() as $player){
2823 if(!isset($newViewers[spl_object_id($player)])){
2824 $entity->despawnFrom($player);
2825 }else{
2826 unset($newViewers[spl_object_id($player)]);
2827 }
2828 }
2829 foreach($newViewers as $player){
2830 $entity->spawnTo($player);
2831 }
2832
2833 $newChunkHash = World::chunkHash($newChunkX, $newChunkZ);
2834 $this->entitiesByChunk[$newChunkHash][$entity->getId()] = $entity;
2835 }
2836 $this->entityLastKnownPositions[$entity->getId()] = $newPosition->asVector3();
2837 }
2838
2843 public function addTile(Tile $tile) : void{
2844 if($tile->isClosed()){
2845 throw new \InvalidArgumentException("Attempted to add a garbage closed Tile to world");
2846 }
2847 $pos = $tile->getPosition();
2848 if(!$pos->isValid() || $pos->getWorld() !== $this){
2849 throw new \InvalidArgumentException("Invalid Tile world");
2850 }
2851 if(!$this->isInWorld($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ())){
2852 throw new \InvalidArgumentException("Tile position is outside the world bounds");
2853 }
2854
2855 $chunkX = $pos->getFloorX() >> Chunk::COORD_BIT_SIZE;
2856 $chunkZ = $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2857
2858 if(isset($this->chunks[$hash = World::chunkHash($chunkX, $chunkZ)])){
2859 $this->chunks[$hash]->addTile($tile);
2860 }else{
2861 throw new \InvalidArgumentException("Attempted to create tile " . get_class($tile) . " in unloaded chunk $chunkX $chunkZ");
2862 }
2863
2864 //delegate tile ticking to the corresponding block
2865 $this->scheduleDelayedBlockUpdate($pos->asVector3(), 1);
2866 }
2867
2872 public function removeTile(Tile $tile) : void{
2873 $pos = $tile->getPosition();
2874 if(!$pos->isValid() || $pos->getWorld() !== $this){
2875 throw new \InvalidArgumentException("Invalid Tile world");
2876 }
2877
2878 $chunkX = $pos->getFloorX() >> Chunk::COORD_BIT_SIZE;
2879 $chunkZ = $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2880
2881 if(isset($this->chunks[$hash = World::chunkHash($chunkX, $chunkZ)])){
2882 $this->chunks[$hash]->removeTile($tile);
2883 }
2884 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2885 $listener->onBlockChanged($pos->asVector3());
2886 }
2887 }
2888
2889 public function isChunkInUse(int $x, int $z) : bool{
2890 return isset($this->chunkLoaders[$index = World::chunkHash($x, $z)]) && count($this->chunkLoaders[$index]) > 0;
2891 }
2892
2899 public function loadChunk(int $x, int $z) : ?Chunk{
2900 if(isset($this->chunks[$chunkHash = World::chunkHash($x, $z)])){
2901 return $this->chunks[$chunkHash];
2902 }
2903
2904 $this->timings->syncChunkLoad->startTiming();
2905
2906 $this->cancelUnloadChunkRequest($x, $z);
2907
2908 $this->timings->syncChunkLoadData->startTiming();
2909
2910 $loadedChunkData = null;
2911
2912 try{
2913 $loadedChunkData = $this->provider->loadChunk($x, $z);
2914 }catch(CorruptedChunkException $e){
2915 $this->logger->critical("Failed to load chunk x=$x z=$z: " . $e->getMessage());
2916 }
2917
2918 $this->timings->syncChunkLoadData->stopTiming();
2919
2920 if($loadedChunkData === null){
2921 $this->timings->syncChunkLoad->stopTiming();
2922 return null;
2923 }
2924
2925 $chunkData = $loadedChunkData->getData();
2926 $chunk = new Chunk($chunkData->getSubChunks(), $chunkData->isPopulated());
2927 if(!$loadedChunkData->isUpgraded()){
2928 $chunk->clearTerrainDirtyFlags();
2929 }else{
2930 $this->logger->debug("Chunk $x $z has been upgraded, will be saved at the next autosave opportunity");
2931 }
2932 $this->chunks[$chunkHash] = $chunk;
2933
2934 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
2935 unset($this->blockCache[$chunkHash]);
2936 unset($this->blockCollisionBoxCache[$chunkHash]);
2937
2938 $this->initChunk($x, $z, $chunkData);
2939
2940 if(ChunkLoadEvent::hasHandlers()){
2941 (new ChunkLoadEvent($this, $x, $z, $this->chunks[$chunkHash], false))->call();
2942 }
2943
2944 if(!$this->isChunkInUse($x, $z)){
2945 $this->logger->debug("Newly loaded chunk $x $z has no loaders registered, will be unloaded at next available opportunity");
2946 $this->unloadChunkRequest($x, $z);
2947 }
2948 foreach($this->getChunkListeners($x, $z) as $listener){
2949 $listener->onChunkLoaded($x, $z, $this->chunks[$chunkHash]);
2950 }
2951 $this->markTickingChunkForRecheck($x, $z); //tickers may have been registered before the chunk was loaded
2952
2953 $this->timings->syncChunkLoad->stopTiming();
2954
2955 return $this->chunks[$chunkHash];
2956 }
2957
2958 private function initChunk(int $chunkX, int $chunkZ, ChunkData $chunkData) : void{
2959 $logger = new \PrefixedLogger($this->logger, "Loading chunk $chunkX $chunkZ");
2960
2961 if(count($chunkData->getEntityNBT()) !== 0){
2962 $this->timings->syncChunkLoadEntities->startTiming();
2963 $entityFactory = EntityFactory::getInstance();
2964 foreach($chunkData->getEntityNBT() as $k => $nbt){
2965 try{
2966 $entity = $entityFactory->createFromData($this, $nbt);
2967 }catch(SavedDataLoadingException $e){
2968 $logger->error("Bad entity data at list position $k: " . $e->getMessage());
2969 $logger->logException($e);
2970 continue;
2971 }
2972 if($entity === null){
2973 $saveIdTag = $nbt->getTag("identifier") ?? $nbt->getTag("id");
2974 $saveId = "<unknown>";
2975 if($saveIdTag instanceof StringTag){
2976 $saveId = $saveIdTag->getValue();
2977 }elseif($saveIdTag instanceof IntTag){ //legacy MCPE format
2978 $saveId = "legacy(" . $saveIdTag->getValue() . ")";
2979 }
2980 $logger->warning("Deleted unknown entity type $saveId");
2981 }
2982 //TODO: we can't prevent entities getting added to unloaded chunks if they were saved in the wrong place
2983 //here, because entities currently add themselves to the world
2984 }
2985
2986 $this->timings->syncChunkLoadEntities->stopTiming();
2987 }
2988
2989 if(count($chunkData->getTileNBT()) !== 0){
2990 $this->timings->syncChunkLoadTileEntities->startTiming();
2991 $tileFactory = TileFactory::getInstance();
2992 foreach($chunkData->getTileNBT() as $k => $nbt){
2993 try{
2994 $tile = $tileFactory->createFromData($this, $nbt);
2995 }catch(SavedDataLoadingException $e){
2996 $logger->error("Bad tile entity data at list position $k: " . $e->getMessage());
2997 $logger->logException($e);
2998 continue;
2999 }
3000 if($tile === null){
3001 $logger->warning("Deleted unknown tile entity type " . $nbt->getString("id", "<unknown>"));
3002 continue;
3003 }
3004
3005 $tilePosition = $tile->getPosition();
3006 if(!$this->isChunkLoaded($tilePosition->getFloorX() >> Chunk::COORD_BIT_SIZE, $tilePosition->getFloorZ() >> Chunk::COORD_BIT_SIZE)){
3007 $logger->error("Found tile saved on wrong chunk - unable to fix due to correct chunk not loaded");
3008 }elseif(!$this->isInWorld($tilePosition->getFloorX(), $tilePosition->getFloorY(), $tilePosition->getFloorZ())){
3009 $logger->error("Cannot add tile with position outside the world bounds: x=$tilePosition->x,y=$tilePosition->y,z=$tilePosition->z");
3010 }elseif($this->getTile($tilePosition) !== null){
3011 $logger->error("Cannot add tile at x=$tilePosition->x,y=$tilePosition->y,z=$tilePosition->z: Another tile is already at that position");
3012 }else{
3013 $this->addTile($tile);
3014 }
3015 }
3016
3017 $this->timings->syncChunkLoadTileEntities->stopTiming();
3018 }
3019 }
3020
3021 private function queueUnloadChunk(int $x, int $z) : void{
3022 $this->unloadQueue[World::chunkHash($x, $z)] = microtime(true);
3023 }
3024
3025 public function unloadChunkRequest(int $x, int $z, bool $safe = true) : bool{
3026 if(($safe && $this->isChunkInUse($x, $z)) || $this->isSpawnChunk($x, $z)){
3027 return false;
3028 }
3029
3030 $this->queueUnloadChunk($x, $z);
3031
3032 return true;
3033 }
3034
3035 public function cancelUnloadChunkRequest(int $x, int $z) : void{
3036 unset($this->unloadQueue[World::chunkHash($x, $z)]);
3037 }
3038
3039 public function unloadChunk(int $x, int $z, bool $safe = true, bool $trySave = true) : bool{
3040 if($safe && $this->isChunkInUse($x, $z)){
3041 return false;
3042 }
3043
3044 if(!$this->isChunkLoaded($x, $z)){
3045 return true;
3046 }
3047
3048 $this->timings->doChunkUnload->startTiming();
3049
3050 $chunkHash = World::chunkHash($x, $z);
3051
3052 $chunk = $this->chunks[$chunkHash] ?? null;
3053
3054 if($chunk !== null){
3055 if(ChunkUnloadEvent::hasHandlers()){
3056 $ev = new ChunkUnloadEvent($this, $x, $z, $chunk);
3057 $ev->call();
3058 if($ev->isCancelled()){
3059 $this->timings->doChunkUnload->stopTiming();
3060
3061 return false;
3062 }
3063 }
3064
3065 if($trySave && $this->getAutoSave()){
3066 $this->timings->syncChunkSave->startTiming();
3067 try{
3068 $this->provider->saveChunk($x, $z, new ChunkData(
3069 $chunk->getSubChunks(),
3070 $chunk->isPopulated(),
3071 array_map(fn(Entity $e) => $e->saveNBT(), array_values(array_filter($this->getChunkEntities($x, $z), fn(Entity $e) => $e->canSaveWithChunk()))),
3072 array_map(fn(Tile $t) => $t->saveNBT(), array_values($chunk->getTiles())),
3073 ), $chunk->getTerrainDirtyFlags());
3074 }finally{
3075 $this->timings->syncChunkSave->stopTiming();
3076 }
3077 }
3078
3079 foreach($this->getChunkListeners($x, $z) as $listener){
3080 $listener->onChunkUnloaded($x, $z, $chunk);
3081 }
3082
3083 foreach($this->getChunkEntities($x, $z) as $entity){
3084 if($entity instanceof Player){
3085 continue;
3086 }
3087 $entity->close();
3088 }
3089
3090 $chunk->onUnload();
3091 }
3092
3093 unset($this->chunks[$chunkHash]);
3094 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
3095 unset($this->blockCache[$chunkHash]);
3096 unset($this->blockCollisionBoxCache[$chunkHash]);
3097 unset($this->changedBlocks[$chunkHash]);
3098 unset($this->registeredTickingChunks[$chunkHash]);
3099 $this->markTickingChunkForRecheck($x, $z);
3100
3101 if(array_key_exists($chunkHash, $this->chunkPopulationRequestMap)){
3102 $this->logger->debug("Rejecting population promise for chunk $x $z");
3103 $this->chunkPopulationRequestMap[$chunkHash]->reject();
3104 unset($this->chunkPopulationRequestMap[$chunkHash]);
3105 if(isset($this->activeChunkPopulationTasks[$chunkHash])){
3106 $this->logger->debug("Marking population task for chunk $x $z as orphaned");
3107 $this->activeChunkPopulationTasks[$chunkHash] = false;
3108 }
3109 }
3110
3111 $this->timings->doChunkUnload->stopTiming();
3112
3113 return true;
3114 }
3115
3119 public function isSpawnChunk(int $X, int $Z) : bool{
3120 $spawn = $this->getSpawnLocation();
3121 $spawnX = $spawn->x >> Chunk::COORD_BIT_SIZE;
3122 $spawnZ = $spawn->z >> Chunk::COORD_BIT_SIZE;
3123
3124 return abs($X - $spawnX) <= 1 && abs($Z - $spawnZ) <= 1;
3125 }
3126
3134 public function requestSafeSpawn(?Vector3 $spawn = null) : Promise{
3136 $resolver = new PromiseResolver();
3137 $spawn ??= $this->getSpawnLocation();
3138 /*
3139 * TODO: this relies on the assumption that getSafeSpawn() will only alter the Y coordinate of the provided
3140 * position, which is currently OK, but might be a problem in the future.
3141 */
3142 $this->requestChunkPopulation($spawn->getFloorX() >> Chunk::COORD_BIT_SIZE, $spawn->getFloorZ() >> Chunk::COORD_BIT_SIZE, null)->onCompletion(
3143 function() use ($spawn, $resolver) : void{
3144 $spawn = $this->getSafeSpawn($spawn);
3145 $resolver->resolve($spawn);
3146 },
3147 function() use ($resolver) : void{
3148 $resolver->reject();
3149 }
3150 );
3151
3152 return $resolver->getPromise();
3153 }
3154
3161 public function getSafeSpawn(?Vector3 $spawn = null) : Position{
3162 if(!($spawn instanceof Vector3) || $spawn->y <= $this->minY){
3163 $spawn = $this->getSpawnLocation();
3164 }
3165
3166 $max = $this->maxY;
3167 $v = $spawn->floor();
3168 $chunk = $this->getOrLoadChunkAtPosition($v);
3169 if($chunk === null){
3170 throw new WorldException("Cannot find a safe spawn point in non-generated terrain");
3171 }
3172 $x = (int) $v->x;
3173 $z = (int) $v->z;
3174 $y = (int) min($max - 2, $v->y);
3175 $wasAir = $this->getBlockAt($x, $y - 1, $z)->getTypeId() === BlockTypeIds::AIR; //TODO: bad hack, clean up
3176 for(; $y > $this->minY; --$y){
3177 if($this->getBlockAt($x, $y, $z)->isFullCube()){
3178 if($wasAir){
3179 $y++;
3180 }
3181 break;
3182 }else{
3183 $wasAir = true;
3184 }
3185 }
3186
3187 for(; $y >= $this->minY && $y < $max; ++$y){
3188 if(!$this->getBlockAt($x, $y + 1, $z)->isFullCube()){
3189 if(!$this->getBlockAt($x, $y, $z)->isFullCube()){
3190 return new Position($spawn->x, $y === (int) $spawn->y ? $spawn->y : $y, $spawn->z, $this);
3191 }
3192 }else{
3193 ++$y;
3194 }
3195 }
3196
3197 return new Position($spawn->x, $y, $spawn->z, $this);
3198 }
3199
3203 public function getTime() : int{
3204 return $this->time;
3205 }
3206
3210 public function getTimeOfDay() : int{
3211 return $this->time % self::TIME_FULL;
3212 }
3213
3218 public function getDisplayName() : string{
3219 return $this->displayName;
3220 }
3221
3225 public function setDisplayName(string $name) : void{
3226 (new WorldDisplayNameChangeEvent($this, $this->displayName, $name))->call();
3227
3228 $this->displayName = $name;
3229 $this->provider->getWorldData()->setName($name);
3230 }
3231
3235 public function getFolderName() : string{
3236 return $this->folderName;
3237 }
3238
3242 public function setTime(int $time) : void{
3243 $this->time = $time;
3244 $this->sendTime();
3245 }
3246
3250 public function stopTime() : void{
3251 $this->stopTime = true;
3252 $this->sendTime();
3253 }
3254
3258 public function startTime() : void{
3259 $this->stopTime = false;
3260 $this->sendTime();
3261 }
3262
3266 public function getSeed() : int{
3267 return $this->provider->getWorldData()->getSeed();
3268 }
3269
3270 public function getMinY() : int{
3271 return $this->minY;
3272 }
3273
3274 public function getMaxY() : int{
3275 return $this->maxY;
3276 }
3277
3278 public function getDifficulty() : int{
3279 return $this->provider->getWorldData()->getDifficulty();
3280 }
3281
3282 public function setDifficulty(int $difficulty) : void{
3283 if($difficulty < 0 || $difficulty > 3){
3284 throw new \InvalidArgumentException("Invalid difficulty level $difficulty");
3285 }
3286 (new WorldDifficultyChangeEvent($this, $this->getDifficulty(), $difficulty))->call();
3287 $this->provider->getWorldData()->setDifficulty($difficulty);
3288
3289 foreach($this->players as $player){
3290 $player->getNetworkSession()->syncWorldDifficulty($this->getDifficulty());
3291 }
3292 }
3293
3294 private function addChunkHashToPopulationRequestQueue(int $chunkHash) : void{
3295 if(!isset($this->chunkPopulationRequestQueueIndex[$chunkHash])){
3296 $this->chunkPopulationRequestQueue->enqueue($chunkHash);
3297 $this->chunkPopulationRequestQueueIndex[$chunkHash] = true;
3298 }
3299 }
3300
3304 private function enqueuePopulationRequest(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3305 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3306 $this->addChunkHashToPopulationRequestQueue($chunkHash);
3308 $resolver = $this->chunkPopulationRequestMap[$chunkHash] = new PromiseResolver();
3309 if($associatedChunkLoader === null){
3310 $temporaryLoader = new class implements ChunkLoader{};
3311 $this->registerChunkLoader($temporaryLoader, $chunkX, $chunkZ);
3312 $resolver->getPromise()->onCompletion(
3313 fn() => $this->unregisterChunkLoader($temporaryLoader, $chunkX, $chunkZ),
3314 static function() : void{}
3315 );
3316 }
3317 return $resolver->getPromise();
3318 }
3319
3320 private function drainPopulationRequestQueue() : void{
3321 $failed = [];
3322 while(count($this->activeChunkPopulationTasks) < $this->maxConcurrentChunkPopulationTasks && !$this->chunkPopulationRequestQueue->isEmpty()){
3323 $nextChunkHash = $this->chunkPopulationRequestQueue->dequeue();
3324 unset($this->chunkPopulationRequestQueueIndex[$nextChunkHash]);
3325 World::getXZ($nextChunkHash, $nextChunkX, $nextChunkZ);
3326 if(isset($this->chunkPopulationRequestMap[$nextChunkHash])){
3327 assert(!($this->activeChunkPopulationTasks[$nextChunkHash] ?? false), "Population for chunk $nextChunkX $nextChunkZ already running");
3328 if(
3329 !$this->orderChunkPopulation($nextChunkX, $nextChunkZ, null)->isResolved() &&
3330 !isset($this->activeChunkPopulationTasks[$nextChunkHash])
3331 ){
3332 $failed[] = $nextChunkHash;
3333 }
3334 }
3335 }
3336
3337 //these requests failed even though they weren't rate limited; we can't directly re-add them to the back of the
3338 //queue because it would result in an infinite loop
3339 foreach($failed as $hash){
3340 $this->addChunkHashToPopulationRequestQueue($hash);
3341 }
3342 }
3343
3349 private function checkChunkPopulationPreconditions(int $chunkX, int $chunkZ) : array{
3350 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3351 $resolver = $this->chunkPopulationRequestMap[$chunkHash] ?? null;
3352 if($resolver !== null && isset($this->activeChunkPopulationTasks[$chunkHash])){
3353 //generation is already running
3354 return [$resolver, false];
3355 }
3356
3357 $temporaryChunkLoader = new class implements ChunkLoader{};
3358 $this->registerChunkLoader($temporaryChunkLoader, $chunkX, $chunkZ);
3359 $chunk = $this->loadChunk($chunkX, $chunkZ);
3360 $this->unregisterChunkLoader($temporaryChunkLoader, $chunkX, $chunkZ);
3361 if($chunk !== null && $chunk->isPopulated()){
3362 //chunk is already populated; return a pre-resolved promise that will directly fire callbacks assigned
3363 $resolver ??= new PromiseResolver();
3364 unset($this->chunkPopulationRequestMap[$chunkHash]);
3365 $resolver->resolve($chunk);
3366 return [$resolver, false];
3367 }
3368 return [$resolver, true];
3369 }
3370
3382 public function requestChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3383 [$resolver, $proceedWithPopulation] = $this->checkChunkPopulationPreconditions($chunkX, $chunkZ);
3384 if(!$proceedWithPopulation){
3385 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3386 }
3387
3388 if(count($this->activeChunkPopulationTasks) >= $this->maxConcurrentChunkPopulationTasks){
3389 //too many chunks are already generating; delay resolution of the request until later
3390 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3391 }
3392 return $this->internalOrderChunkPopulation($chunkX, $chunkZ, $associatedChunkLoader, $resolver);
3393 }
3394
3405 public function orderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3406 [$resolver, $proceedWithPopulation] = $this->checkChunkPopulationPreconditions($chunkX, $chunkZ);
3407 if(!$proceedWithPopulation){
3408 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3409 }
3410
3411 return $this->internalOrderChunkPopulation($chunkX, $chunkZ, $associatedChunkLoader, $resolver);
3412 }
3413
3418 private function internalOrderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader, ?PromiseResolver $resolver) : Promise{
3419 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3420
3421 $timings = $this->timings->chunkPopulationOrder;
3422 $timings->startTiming();
3423
3424 try{
3425 for($xx = -1; $xx <= 1; ++$xx){
3426 for($zz = -1; $zz <= 1; ++$zz){
3427 if($this->isChunkLocked($chunkX + $xx, $chunkZ + $zz)){
3428 //chunk is already in use by another generation request; queue the request for later
3429 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3430 }
3431 }
3432 }
3433
3434 $this->activeChunkPopulationTasks[$chunkHash] = true;
3435 if($resolver === null){
3436 $resolver = new PromiseResolver();
3437 $this->chunkPopulationRequestMap[$chunkHash] = $resolver;
3438 }
3439
3440 $chunkPopulationLockId = new ChunkLockId();
3441
3442 $temporaryChunkLoader = new class implements ChunkLoader{
3443 };
3444 for($xx = -1; $xx <= 1; ++$xx){
3445 for($zz = -1; $zz <= 1; ++$zz){
3446 $this->lockChunk($chunkX + $xx, $chunkZ + $zz, $chunkPopulationLockId);
3447 $this->registerChunkLoader($temporaryChunkLoader, $chunkX + $xx, $chunkZ + $zz);
3448 }
3449 }
3450
3451 $centerChunk = $this->loadChunk($chunkX, $chunkZ);
3452 $adjacentChunks = $this->getAdjacentChunks($chunkX, $chunkZ);
3453 $task = new PopulationTask(
3454 $this->worldId,
3455 $chunkX,
3456 $chunkZ,
3457 $centerChunk,
3458 $adjacentChunks,
3459 function(Chunk $centerChunk, array $adjacentChunks) use ($chunkPopulationLockId, $chunkX, $chunkZ, $temporaryChunkLoader) : void{
3460 if(!$this->isLoaded()){
3461 return;
3462 }
3463
3464 $this->generateChunkCallback($chunkPopulationLockId, $chunkX, $chunkZ, $centerChunk, $adjacentChunks, $temporaryChunkLoader);
3465 }
3466 );
3467 $workerId = $this->workerPool->selectWorker();
3468 if(!isset($this->workerPool->getRunningWorkers()[$workerId]) && isset($this->generatorRegisteredWorkers[$workerId])){
3469 $this->logger->debug("Selected worker $workerId previously had generator registered, but is now offline");
3470 unset($this->generatorRegisteredWorkers[$workerId]);
3471 }
3472 if(!isset($this->generatorRegisteredWorkers[$workerId])){
3473 $this->registerGeneratorToWorker($workerId);
3474 }
3475 $this->workerPool->submitTaskToWorker($task, $workerId);
3476
3477 return $resolver->getPromise();
3478 }finally{
3479 $timings->stopTiming();
3480 }
3481 }
3482
3487 private function generateChunkCallback(ChunkLockId $chunkLockId, int $x, int $z, Chunk $chunk, array $adjacentChunks, ChunkLoader $temporaryChunkLoader) : void{
3488 $timings = $this->timings->chunkPopulationCompletion;
3489 $timings->startTiming();
3490
3491 $dirtyChunks = 0;
3492 for($xx = -1; $xx <= 1; ++$xx){
3493 for($zz = -1; $zz <= 1; ++$zz){
3494 $this->unregisterChunkLoader($temporaryChunkLoader, $x + $xx, $z + $zz);
3495 if(!$this->unlockChunk($x + $xx, $z + $zz, $chunkLockId)){
3496 $dirtyChunks++;
3497 }
3498 }
3499 }
3500
3501 $index = World::chunkHash($x, $z);
3502 if(!isset($this->activeChunkPopulationTasks[$index])){
3503 throw new AssumptionFailedError("This should always be set, regardless of whether the task was orphaned or not");
3504 }
3505 if(!$this->activeChunkPopulationTasks[$index]){
3506 $this->logger->debug("Discarding orphaned population result for chunk x=$x,z=$z");
3507 unset($this->activeChunkPopulationTasks[$index]);
3508 }else{
3509 if($dirtyChunks === 0){
3510 $oldChunk = $this->loadChunk($x, $z);
3511 $this->setChunk($x, $z, $chunk);
3512
3513 foreach($adjacentChunks as $relativeChunkHash => $adjacentChunk){
3514 World::getXZ($relativeChunkHash, $relativeX, $relativeZ);
3515 if($relativeX < -1 || $relativeX > 1 || $relativeZ < -1 || $relativeZ > 1){
3516 throw new AssumptionFailedError("Adjacent chunks should be in range -1 ... +1 coordinates");
3517 }
3518 $this->setChunk($x + $relativeX, $z + $relativeZ, $adjacentChunk);
3519 }
3520
3521 if(($oldChunk === null || !$oldChunk->isPopulated()) && $chunk->isPopulated()){
3522 if(ChunkPopulateEvent::hasHandlers()){
3523 (new ChunkPopulateEvent($this, $x, $z, $chunk))->call();
3524 }
3525
3526 foreach($this->getChunkListeners($x, $z) as $listener){
3527 $listener->onChunkPopulated($x, $z, $chunk);
3528 }
3529 }
3530 }else{
3531 $this->logger->debug("Discarding population result for chunk x=$x,z=$z - terrain was modified on the main thread before async population completed");
3532 }
3533
3534 //This needs to be in this specific spot because user code might call back to orderChunkPopulation().
3535 //If it does, and finds the promise, and doesn't find an active task associated with it, it will schedule
3536 //another PopulationTask. We don't want that because we're here processing the results.
3537 //We can't remove the promise from the array before setting the chunks in the world because that would lead
3538 //to the same problem. Therefore, it's necessary that this code be split into two if/else, with this in the
3539 //middle.
3540 unset($this->activeChunkPopulationTasks[$index]);
3541
3542 if($dirtyChunks === 0){
3543 $promise = $this->chunkPopulationRequestMap[$index] ?? null;
3544 if($promise !== null){
3545 unset($this->chunkPopulationRequestMap[$index]);
3546 $promise->resolve($chunk);
3547 }else{
3548 //Handlers of ChunkPopulateEvent, ChunkLoadEvent, or just ChunkListeners can cause this
3549 $this->logger->debug("Unable to resolve population promise for chunk x=$x,z=$z - populated chunk was forcibly unloaded while setting modified chunks");
3550 }
3551 }else{
3552 //request failed, stick it back on the queue
3553 //we didn't resolve the promise or touch it in any way, so any fake chunk loaders are still valid and
3554 //don't need to be added a second time.
3555 $this->addChunkHashToPopulationRequestQueue($index);
3556 }
3557
3558 $this->drainPopulationRequestQueue();
3559 }
3560 $timings->stopTiming();
3561 }
3562
3563 public function doChunkGarbageCollection() : void{
3564 $this->timings->doChunkGC->startTiming();
3565
3566 foreach($this->chunks as $index => $chunk){
3567 if(!isset($this->unloadQueue[$index])){
3568 World::getXZ($index, $X, $Z);
3569 if(!$this->isSpawnChunk($X, $Z)){
3570 $this->unloadChunkRequest($X, $Z, true);
3571 }
3572 }
3573 $chunk->collectGarbage();
3574 }
3575
3576 $this->provider->doGarbageCollection();
3577
3578 $this->timings->doChunkGC->stopTiming();
3579 }
3580
3581 public function unloadChunks(bool $force = false) : void{
3582 if(count($this->unloadQueue) > 0){
3583 $maxUnload = 96;
3584 $now = microtime(true);
3585 foreach($this->unloadQueue as $index => $time){
3586 World::getXZ($index, $X, $Z);
3587
3588 if(!$force){
3589 if($maxUnload <= 0){
3590 break;
3591 }elseif($time > ($now - 30)){
3592 continue;
3593 }
3594 }
3595
3596 //If the chunk can't be unloaded, it stays on the queue
3597 if($this->unloadChunk($X, $Z, true)){
3598 unset($this->unloadQueue[$index]);
3599 --$maxUnload;
3600 }
3601 }
3602 }
3603 }
3604}
getBlock(?int $clickedFace=null)
Definition Item.php:491
pop(int $count=1)
Definition Item.php:430
removeWorkerStartHook(\Closure $hook)
getChunkListeners(int $chunkX, int $chunkZ)
Definition World.php:899
removeEntity(Entity $entity)
Definition World.php:2768
notifyNeighbourBlockUpdate(Vector3 $pos)
Definition World.php:1516
getCollisionBlocks(AxisAlignedBB $bb, bool $targetFirst=false)
Definition World.php:1524
getHighestAdjacentBlockLight(int $x, int $y, int $z)
Definition World.php:1903
setDisplayName(string $name)
Definition World.php:3225
getPotentialBlockSkyLightAt(int $x, int $y, int $z)
Definition World.php:1808
removeOnUnloadCallback(\Closure $callback)
Definition World.php:676
isChunkLocked(int $chunkX, int $chunkZ)
Definition World.php:2610
setSpawnLocation(Vector3 $pos)
Definition World.php:2725
getPotentialLightAt(int $x, int $y, int $z)
Definition World.php:1790
createBlockUpdatePackets(array $blocks)
Definition World.php:1099
getSafeSpawn(?Vector3 $spawn=null)
Definition World.php:3161
registerChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ)
Definition World.php:853
getBlockAt(int $x, int $y, int $z, bool $cached=true, bool $addToCache=true)
Definition World.php:1954
getChunkEntities(int $chunkX, int $chunkZ)
Definition World.php:2533
addEntity(Entity $entity)
Definition World.php:2739
getBlockLightAt(int $x, int $y, int $z)
Definition World.php:1833
getBlock(Vector3 $pos, bool $cached=true, bool $addToCache=true)
Definition World.php:1941
static chunkHash(int $x, int $z)
Definition World.php:383
broadcastPacketToViewers(Vector3 $pos, ClientboundPacket $packet)
Definition World.php:803
getOrLoadChunkAtPosition(Vector3 $pos)
Definition World.php:2540
static chunkBlockHash(int $x, int $y, int $z)
Definition World.php:422
getHighestAdjacentPotentialBlockSkyLight(int $x, int $y, int $z)
Definition World.php:1888
getFullLight(Vector3 $pos)
Definition World.php:1747
isInWorld(int $x, int $y, int $z)
Definition World.php:1923
unlockChunk(int $chunkX, int $chunkZ, ?ChunkLockId $lockId)
Definition World.php:2595
getChunkLoaders(int $chunkX, int $chunkZ)
Definition World.php:786
getAdjacentChunks(int $x, int $z)
Definition World.php:2550
getChunkPlayers(int $chunkX, int $chunkZ)
Definition World.php:776
getTileAt(int $x, int $y, int $z)
Definition World.php:2490
getHighestAdjacentFullLightAt(int $x, int $y, int $z)
Definition World.php:1771
setChunkTickRadius(int $radius)
Definition World.php:1218
getViewersForPosition(Vector3 $pos)
Definition World.php:796
getNearestEntity(Vector3 $pos, float $maxDistance, string $entityType=Entity::class, bool $includeDead=false)
Definition World.php:2433
__construct(private Server $server, string $name, private WritableWorldProvider $provider, private AsyncPool $workerPool)
Definition World.php:481
requestChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader)
Definition World.php:3382
addSound(Vector3 $pos, Sound $sound, ?array $players=null)
Definition World.php:704
registerTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ)
Definition World.php:1237
setBlock(Vector3 $pos, Block $block, bool $update=true)
Definition World.php:2009
getNearbyEntities(AxisAlignedBB $bb, ?Entity $entity=null)
Definition World.php:2401
static getXZ(int $hash, ?int &$x, ?int &$z)
Definition World.php:448
getBlockCollisionBoxes(AxisAlignedBB $bb)
Definition World.php:1654
getCollidingEntities(AxisAlignedBB $bb, ?Entity $entity=null)
Definition World.php:2383
isSpawnChunk(int $X, int $Z)
Definition World.php:3119
useBreakOn(Vector3 $vector, ?Item &$item=null, ?Player $player=null, bool $createParticles=false, array &$returnedItems=[])
Definition World.php:2115
getPotentialLight(Vector3 $pos)
Definition World.php:1779
addParticle(Vector3 $pos, Particle $particle, ?array $players=null)
Definition World.php:733
unregisterChunkListenerFromAll(ChunkListener $listener)
Definition World.php:886
loadChunk(int $x, int $z)
Definition World.php:2899
useItemOn(Vector3 $vector, Item &$item, int $face, ?Vector3 $clickVector=null, ?Player $player=null, bool $playSound=false, array &$returnedItems=[])
Definition World.php:2221
getHighestAdjacentPotentialLightAt(int $x, int $y, int $z)
Definition World.php:1798
setBlockAt(int $x, int $y, int $z, Block $block, bool $update=true)
Definition World.php:2021
unregisterTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ)
Definition World.php:1247
getRealBlockSkyLightAt(int $x, int $y, int $z)
Definition World.php:1823
static blockHash(int $x, int $y, int $z)
Definition World.php:402
getTile(Vector3 $pos)
Definition World.php:2483
getFullLightAt(int $x, int $y, int $z)
Definition World.php:1758
getHighestAdjacentRealBlockSkyLight(int $x, int $y, int $z)
Definition World.php:1896
orderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader)
Definition World.php:3405
dropExperience(Vector3 $pos, int $amount)
Definition World.php:2092
isInLoadedTerrain(Vector3 $pos)
Definition World.php:2698
lockChunk(int $chunkX, int $chunkZ, ChunkLockId $lockId)
Definition World.php:2578
getHighestBlockAt(int $x, int $z)
Definition World.php:2688
scheduleDelayedBlockUpdate(Vector3 $pos, int $delay)
Definition World.php:1475
static getBlockXYZ(int $hash, ?int &$x, ?int &$y, ?int &$z)
Definition World.php:432
addOnUnloadCallback(\Closure $callback)
Definition World.php:671
requestSafeSpawn(?Vector3 $spawn=null)
Definition World.php:3134
unregisterChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ)
Definition World.php:870
getTile(int $x, int $y, int $z)
Definition Chunk.php:229
getHighestBlockAt(int $x, int $z)
Definition Chunk.php:121
getBlockStateId(int $x, int $y, int $z)
Definition Chunk.php:101