PocketMine-MP 5.37.1 git-da6732df2656426fbd1b7898ed06c8286969d2f1
Loading...
Searching...
No Matches
Player.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
24namespace pocketmine\player;
25
26use DateTimeImmutable;
103use pocketmine\item\ItemUseResult;
126use pocketmine\permission\PermissibleDelegateTrait;
134use pocketmine\world\ChunkListenerNoOpTrait;
147use Ramsey\Uuid\UuidInterface;
148use function abs;
149use function array_filter;
150use function array_shift;
151use function assert;
152use function count;
153use function explode;
154use function floor;
155use function get_class;
156use function max;
157use function mb_strlen;
158use function microtime;
159use function min;
160use function preg_match;
161use function spl_object_id;
162use function sqrt;
163use function str_starts_with;
164use function strlen;
165use function strtolower;
166use function substr;
167use function trim;
168use const M_PI;
169use const M_SQRT3;
170use const PHP_INT_MAX;
171
176 use PermissibleDelegateTrait;
177
178 private const MOVES_PER_TICK = 2;
179 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK; //100 ticks backlog (5 seconds)
180
182 private const MAX_CHAT_CHAR_LENGTH = 512;
188 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
189 private const MAX_REACH_DISTANCE_CREATIVE = 13;
190 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
191 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
192
193 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
194
195 public const TAG_FIRST_PLAYED = "firstPlayed"; //TAG_Long
196 public const TAG_LAST_PLAYED = "lastPlayed"; //TAG_Long
197 private const TAG_GAME_MODE = "playerGameType"; //TAG_Int
198 private const TAG_SPAWN_WORLD = "SpawnLevel"; //TAG_String
199 private const TAG_SPAWN_X = "SpawnX"; //TAG_Int
200 private const TAG_SPAWN_Y = "SpawnY"; //TAG_Int
201 private const TAG_SPAWN_Z = "SpawnZ"; //TAG_Int
202 private const TAG_DEATH_WORLD = "DeathLevel"; //TAG_String
203 private const TAG_DEATH_X = "DeathPositionX"; //TAG_Int
204 private const TAG_DEATH_Y = "DeathPositionY"; //TAG_Int
205 private const TAG_DEATH_Z = "DeathPositionZ"; //TAG_Int
206 public const TAG_LEVEL = "Level"; //TAG_String
207 public const TAG_LAST_KNOWN_XUID = "LastKnownXUID"; //TAG_String
208
212 public static function isValidUserName(?string $name) : bool{
213 if($name === null){
214 return false;
215 }
216
217 $lname = strtolower($name);
218 $len = strlen($name);
219 return $lname !== "rcon" && $lname !== "console" && $len >= 1 && $len <= 16 && preg_match("/[^A-Za-z0-9_ ]/", $name) === 0;
220 }
221
222 protected ?NetworkSession $networkSession;
223
224 public bool $spawned = false;
225
226 protected string $username;
227 protected string $displayName;
228 protected string $xuid = "";
229 protected bool $authenticated;
230 protected PlayerInfo $playerInfo;
231
232 protected ?InventoryWindow $currentWindow = null;
234 protected array $permanentWindows = [];
235 protected Inventory $cursorInventory;
236 protected CraftingGrid $craftingGrid;
237 protected CreativeInventory $creativeInventory;
238
239 protected int $messageCounter = 2;
240
241 protected DateTimeImmutable $firstPlayed;
242 protected DateTimeImmutable $lastPlayed;
243 protected GameMode $gamemode;
244
249 protected array $usedChunks = [];
254 private array $activeChunkGenerationRequests = [];
259 protected array $loadQueue = [];
260 protected int $nextChunkOrderRun = 5;
261
263 private array $tickingChunks = [];
264
265 protected int $viewDistance = -1;
266 protected int $spawnThreshold;
267 protected int $spawnChunkLoadCount = 0;
268 protected int $chunksPerTick;
269 protected ChunkSelector $chunkSelector;
270 protected ChunkLoader $chunkLoader;
271 protected ChunkTicker $chunkTicker;
272
274 protected array $hiddenPlayers = [];
275
276 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
277 protected ?float $lastMovementProcess = null;
278
279 protected int $inAirTicks = 0;
280
281 protected float $stepHeight = 0.6;
282
283 protected ?Vector3 $sleeping = null;
284 private ?Position $spawnPosition = null;
285
286 private bool $respawnLocked = false;
287
288 private ?Position $deathPosition = null;
289
290 //TODO: Abilities
291 protected bool $autoJump = true;
292 protected bool $allowFlight = false;
293 protected bool $blockCollision = true;
294 protected bool $flying = false;
295 protected bool $sneakPressed = false;
296
297 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
298
300 protected ?int $lineHeight = null;
301 private CommandAliasMap $commandAliasMap;
302
303 protected string $locale = "en_US";
304
305 protected int $startAction = -1;
306
311 protected array $usedItemsCooldown = [];
312
313 private int $lastEmoteTick = 0;
314
315 protected int $formIdCounter = 0;
317 protected array $forms = [];
318
319 protected \Logger $logger;
320
321 protected ?SurvivalBlockBreakHandler $blockBreakHandler = null;
322
323 public function __construct(Server $server, NetworkSession $session, PlayerInfo $playerInfo, bool $authenticated, Location $spawnLocation, ?CompoundTag $namedtag){
324 $username = TextFormat::clean($playerInfo->getUsername());
325 $this->logger = new \PrefixedLogger($server->getLogger(), "Player: $username");
326
327 $this->server = $server;
328 $this->networkSession = $session;
329 $this->playerInfo = $playerInfo;
330 $this->authenticated = $authenticated;
331
332 $this->username = $username;
333 $this->displayName = $this->username;
334 $this->locale = $this->playerInfo->getLocale();
335
336 $this->uuid = $this->playerInfo->getUuid();
337 $this->xuid = $this->playerInfo instanceof XboxLivePlayerInfo ? $this->playerInfo->getXuid() : "";
338
339 $this->creativeInventory = CreativeInventory::getInstance();
340
341 $rootPermissions = [DefaultPermissions::ROOT_USER => true];
342 if($this->server->isOp($this->username)){
343 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] = true;
344 }
345 $this->perm = new PermissibleBase($rootPermissions);
346 $this->commandAliasMap = new CommandAliasMap();
347
348 $this->chunksPerTick = $this->server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
349 $this->spawnThreshold = (int) (($this->server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
350 $this->chunkSelector = new ChunkSelector();
351
352 $this->chunkLoader = new ChunkLoader();
353 $this->chunkTicker = new ChunkTicker();
354 $world = $spawnLocation->getWorld();
355 //load the spawn chunk so we can see the terrain
356 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
357 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
358 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk, true);
359 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
360 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
361
362 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
363 }
364
365 protected function initHumanData(CompoundTag $nbt) : void{
366 $this->setNameTag($this->username);
367 }
368
369 private function callDummyItemHeldEvent() : void{
370 $slot = $this->hotbar->getSelectedIndex();
371
372 $event = new PlayerItemHeldEvent($this, $this->inventory->getItem($slot), $slot);
373 $event->call();
374 //TODO: this event is actually cancellable, but cancelling it here has no meaningful result, so we
375 //just ignore it. We fire this only because the content of the held slot changed, not because the
376 //held slot index changed. We can't prevent that from here, and nor would it be sensible to.
377 }
378
379 protected function initEntity(CompoundTag $nbt) : void{
380 parent::initEntity($nbt);
381 $this->addDefaultWindows();
382
383 $this->inventory->getListeners()->add(new CallbackInventoryListener(
384 function(Inventory $unused, int $slot) : void{
385 if($slot === $this->hotbar->getSelectedIndex()){
386 $this->setUsingItem(false);
387
388 $this->callDummyItemHeldEvent();
389 }
390 },
391 function() : void{
392 $this->setUsingItem(false);
393 $this->callDummyItemHeldEvent();
394 }
395 ));
396
397 $now = (int) (microtime(true) * 1000);
398 $createDateTimeImmutable = static function(string $tag) use ($nbt, $now) : DateTimeImmutable{
399 return new DateTimeImmutable('@' . $nbt->getLong($tag, $now) / 1000);
400 };
401 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
402 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
403
404 if(!$this->server->getForceGamemode() && ($gameModeTag = $nbt->getTag(self::TAG_GAME_MODE)) instanceof IntTag){
405 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL); //TODO: bad hack here to avoid crashes on corrupted data
406 }else{
407 $this->internalSetGameMode($this->server->getGamemode());
408 }
409
410 $this->keepMovement = true;
411
412 $this->setNameTagVisible();
413 $this->setNameTagAlwaysVisible();
414 $this->setCanClimb();
415
416 if(($world = $this->server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD, ""))) instanceof World){
417 $this->spawnPosition = new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
418 }
419 if(($world = $this->server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD, ""))) instanceof World){
420 $this->deathPosition = new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
421 }
422 }
423
424 public function getLeaveMessage() : Translatable|string{
425 if($this->spawned){
426 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
427 }
428
429 return "";
430 }
431
432 public function isAuthenticated() : bool{
433 return $this->authenticated;
434 }
435
440 public function getPlayerInfo() : PlayerInfo{ return $this->playerInfo; }
441
446 public function getXuid() : string{
447 return $this->xuid;
448 }
449
457 public function getUniqueId() : UuidInterface{
458 return parent::getUniqueId();
459 }
460
464 public function getFirstPlayed() : ?DateTimeImmutable{
465 return $this->firstPlayed;
466 }
467
471 public function getLastPlayed() : ?DateTimeImmutable{
472 return $this->lastPlayed;
473 }
474
475 public function hasPlayedBefore() : bool{
476 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format('%s')) > 1;
477 }
478
488 public function setAllowFlight(bool $value) : void{
489 if($this->allowFlight !== $value){
490 $this->allowFlight = $value;
491 $this->getNetworkSession()->syncAbilities($this);
492 }
493 }
494
501 public function getAllowFlight() : bool{
502 return $this->allowFlight;
503 }
504
513 public function setHasBlockCollision(bool $value) : void{
514 if($this->blockCollision !== $value){
515 $this->blockCollision = $value;
516 $this->getNetworkSession()->syncAbilities($this);
517 }
518 }
519
524 public function hasBlockCollision() : bool{
525 return $this->blockCollision;
526 }
527
528 public function setFlying(bool $value) : void{
529 if($this->flying !== $value){
530 $this->flying = $value;
531 $this->resetFallDistance();
532 $this->getNetworkSession()->syncAbilities($this);
533 }
534 }
535
536 public function isFlying() : bool{
537 return $this->flying;
538 }
539
553 public function setFlightSpeedMultiplier(float $flightSpeedMultiplier) : void{
554 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
555 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
556 $this->getNetworkSession()->syncAbilities($this);
557 }
558 }
559
571 public function getFlightSpeedMultiplier() : float{
572 return $this->flightSpeedMultiplier;
573 }
574
575 public function setAutoJump(bool $value) : void{
576 if($this->autoJump !== $value){
577 $this->autoJump = $value;
578 $this->getNetworkSession()->syncAdventureSettings();
579 }
580 }
581
582 public function hasAutoJump() : bool{
583 return $this->autoJump;
584 }
585
586 public function spawnTo(Player $player) : void{
587 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
588 parent::spawnTo($player);
589 }
590 }
591
592 public function getServer() : Server{
593 return $this->server;
594 }
595
596 public function getScreenLineHeight() : int{
597 return $this->lineHeight ?? 7;
598 }
599
600 public function setScreenLineHeight(?int $height) : void{
601 if($height !== null && $height < 1){
602 throw new \InvalidArgumentException("Line height must be at least 1");
603 }
604 $this->lineHeight = $height;
605 }
606
607 public function getCommandAliasMap() : CommandAliasMap{ return $this->commandAliasMap; }
608
609 public function canSee(Player $player) : bool{
610 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
611 }
612
613 public function hidePlayer(Player $player) : void{
614 if($player === $this){
615 return;
616 }
617 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] = true;
618 $player->despawnFrom($this);
619 }
620
621 public function showPlayer(Player $player) : void{
622 if($player === $this){
623 return;
624 }
625 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
626 if($player->isOnline()){
627 $player->spawnTo($this);
628 }
629 }
630
631 public function canCollideWith(Entity $entity) : bool{
632 return false;
633 }
634
635 public function canBeCollidedWith() : bool{
636 return !$this->isSpectator() && parent::canBeCollidedWith();
637 }
638
639 public function resetFallDistance() : void{
640 parent::resetFallDistance();
641 $this->inAirTicks = 0;
642 }
643
644 public function getViewDistance() : int{
645 return $this->viewDistance;
646 }
647
648 public function setViewDistance(int $distance) : void{
649 $newViewDistance = $this->server->getAllowedViewDistance($distance);
650
651 if($newViewDistance !== $this->viewDistance){
652 $ev = new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
653 $ev->call();
654 }
655
656 $this->viewDistance = $newViewDistance;
657
658 $this->spawnThreshold = (int) (min($this->viewDistance, $this->server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
659
660 $this->nextChunkOrderRun = 0;
661
662 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
663
664 $this->logger->debug("Setting view distance to " . $this->viewDistance . " (requested " . $distance . ")");
665 }
666
667 public function isOnline() : bool{
668 return $this->isConnected();
669 }
670
671 public function isConnected() : bool{
672 return $this->networkSession !== null && $this->networkSession->isConnected();
673 }
674
675 public function getNetworkSession() : NetworkSession{
676 if($this->networkSession === null){
677 throw new \LogicException("Player is not connected");
678 }
679 return $this->networkSession;
680 }
681
685 public function getName() : string{
686 return $this->username;
687 }
688
692 public function getDisplayName() : string{
693 return $this->displayName;
694 }
695
696 public function setDisplayName(string $name) : void{
697 $ev = new PlayerDisplayNameChangeEvent($this, $this->displayName, $name);
698 $ev->call();
699
700 $this->displayName = $ev->getNewName();
701 }
702
703 public function canBeRenamed() : bool{
704 return false;
705 }
706
710 public function getLocale() : string{
711 return $this->locale;
712 }
713
714 public function getLanguage() : Language{
715 return $this->server->getLanguage();
716 }
717
722 public function changeSkin(Skin $skin, string $newSkinName, string $oldSkinName) : bool{
723 $ev = new PlayerChangeSkinEvent($this, $this->getSkin(), $skin);
724 $ev->call();
725
726 if($ev->isCancelled()){
727 $this->sendSkin([$this]);
728 return true;
729 }
730
731 $this->setSkin($ev->getNewSkin());
732 $this->sendSkin($this->server->getOnlinePlayers());
733 return true;
734 }
735
741 public function sendSkin(?array $targets = null) : void{
742 parent::sendSkin($targets ?? $this->server->getOnlinePlayers());
743 }
744
748 public function isUsingItem() : bool{
749 return $this->startAction > -1;
750 }
751
752 public function setUsingItem(bool $value) : void{
753 $this->startAction = $value ? $this->server->getTick() : -1;
754 $this->networkPropertiesDirty = true;
755 }
756
761 public function getItemUseDuration() : int{
762 return $this->startAction === -1 ? -1 : ($this->server->getTick() - $this->startAction);
763 }
764
768 public function getItemCooldownExpiry(Item $item) : int{
769 $this->checkItemCooldowns();
770 return $this->usedItemsCooldown[$item->getCooldownTag() ?? $item->getStateId()] ?? 0;
771 }
772
776 public function hasItemCooldown(Item $item) : bool{
777 $this->checkItemCooldowns();
778 return isset($this->usedItemsCooldown[$item->getCooldownTag() ?? $item->getStateId()]);
779 }
780
784 public function resetItemCooldown(Item $item, ?int $ticks = null) : void{
785 $ticks = $ticks ?? $item->getCooldownTicks();
786 if($ticks > 0){
787 $this->usedItemsCooldown[$item->getCooldownTag() ?? $item->getStateId()] = $this->server->getTick() + $ticks;
788 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
789 }
790 }
791
792 protected function checkItemCooldowns() : void{
793 $serverTick = $this->server->getTick();
794 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
795 if($cooldownUntil <= $serverTick){
796 unset($this->usedItemsCooldown[$itemId]);
797 }
798 }
799 }
800
801 protected function setPosition(Vector3 $pos) : bool{
802 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
803 if(parent::setPosition($pos)){
804 $newWorld = $this->getWorld();
805 if($oldWorld !== $newWorld){
806 if($oldWorld !== null){
807 foreach($this->usedChunks as $index => $status){
808 World::getXZ($index, $X, $Z);
809 $this->unloadChunk($X, $Z, $oldWorld);
810 }
811 }
812
813 $this->usedChunks = [];
814 $this->loadQueue = [];
815 $this->getNetworkSession()->onEnterWorld();
816 }
817
818 return true;
819 }
820
821 return false;
822 }
823
824 protected function unloadChunk(int $x, int $z, ?World $world = null) : void{
825 $world = $world ?? $this->getWorld();
826 $index = World::chunkHash($x, $z);
827 if(isset($this->usedChunks[$index])){
828 foreach($world->getChunkEntities($x, $z) as $entity){
829 if($entity !== $this){
830 $entity->despawnFrom($this);
831 }
832 }
833 $this->getNetworkSession()->stopUsingChunk($x, $z);
834 unset($this->usedChunks[$index]);
835 unset($this->activeChunkGenerationRequests[$index]);
836 }
837 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
838 $world->unregisterChunkListener($this, $x, $z);
839 unset($this->loadQueue[$index]);
840 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
841 unset($this->tickingChunks[$index]);
842 }
843
844 protected function spawnEntitiesOnAllChunks() : void{
845 foreach($this->usedChunks as $chunkHash => $status){
846 if($status === UsedChunkStatus::SENT){
847 World::getXZ($chunkHash, $chunkX, $chunkZ);
848 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
849 }
850 }
851 }
852
853 protected function spawnEntitiesOnChunk(int $chunkX, int $chunkZ) : void{
854 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
855 if($entity !== $this && !$entity->isFlaggedForDespawn()){
856 $entity->spawnTo($this);
857 }
858 }
859 }
860
865 protected function requestChunks() : void{
866 if(!$this->isConnected()){
867 return;
868 }
869
870 Timings::$playerChunkSend->startTiming();
871
872 $count = 0;
873 $world = $this->getWorld();
874
875 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
876 foreach($this->loadQueue as $index => $distance){
877 if($count >= $limit){
878 break;
879 }
880
881 $X = null;
882 $Z = null;
883 World::getXZ($index, $X, $Z);
884
885 ++$count;
886
887 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
888 $this->activeChunkGenerationRequests[$index] = true;
889 unset($this->loadQueue[$index]);
890 $world->registerChunkLoader($this->chunkLoader, $X, $Z, true);
891 $world->registerChunkListener($this, $X, $Z);
892 if(isset($this->tickingChunks[$index])){
893 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
894 }
895
896 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
897 function() use ($X, $Z, $index, $world) : void{
898 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
899 return;
900 }
901 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
902 //We may have previously requested this, decided we didn't want it, and then decided we did want
903 //it again, all before the generation request got executed. In that case, the promise would have
904 //multiple callbacks for this player. In that case, only the first one matters.
905 return;
906 }
907 unset($this->activeChunkGenerationRequests[$index]);
908 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
909
910 $this->getNetworkSession()->startUsingChunk($X, $Z, function() use ($X, $Z, $index) : void{
911 $this->usedChunks[$index] = UsedChunkStatus::SENT;
912 if($this->spawnChunkLoadCount === -1){
913 $this->spawnEntitiesOnChunk($X, $Z);
914 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
915 $this->spawnChunkLoadCount = -1;
916
917 $this->spawnEntitiesOnAllChunks();
918
919 $this->getNetworkSession()->notifyTerrainReady();
920 }
921 (new PlayerPostChunkSendEvent($this, $X, $Z))->call();
922 });
923 },
924 static function() : void{
925 //NOOP: we'll re-request this if it fails anyway
926 }
927 );
928 }
929
930 Timings::$playerChunkSend->stopTiming();
931 }
932
933 private function recheckBroadcastPermissions() : void{
934 foreach([
935 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
936 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
937 ] as $permission => $channel){
938 if($this->hasPermission($permission)){
939 $this->server->subscribeToBroadcastChannel($channel, $this);
940 }else{
941 $this->server->unsubscribeFromBroadcastChannel($channel, $this);
942 }
943 }
944 }
945
950 public function doFirstSpawn() : void{
951 if($this->spawned){
952 return;
953 }
954 $this->spawned = true;
955 $this->recheckBroadcastPermissions();
956 $this->getPermissionRecalculationCallbacks()->add(function(array $changedPermissionsOldValues) : void{
957 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
958 $this->recheckBroadcastPermissions();
959 }
960 });
961
962 $ev = new PlayerJoinEvent($this,
963 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
964 );
965 $ev->call();
966 if($ev->getJoinMessage() !== ""){
967 $this->server->broadcastMessage($ev->getJoinMessage());
968 }
969
970 $this->noDamageTicks = 60;
971
972 $this->spawnToAll();
973
974 if($this->getHealth() <= 0){
975 $this->logger->debug("Quit while dead, forcing respawn");
976 $this->actuallyRespawn();
977 }
978 }
979
987 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
988 $world = $this->getWorld();
989 foreach($oldTickingChunks as $hash => $_){
990 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
991 //we are (probably) still using this chunk, but it's no longer within ticking range
992 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
993 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
994 }
995 }
996 foreach($newTickingChunks as $hash => $_){
997 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
998 //we were already using this chunk, but it is now within ticking range
999 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
1000 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
1001 }
1002 }
1003 }
1004
1009 protected function orderChunks() : void{
1010 if(!$this->isConnected() || $this->viewDistance === -1){
1011 return;
1012 }
1013
1014 Timings::$playerChunkOrder->startTiming();
1015
1016 $newOrder = [];
1017 $tickingChunks = [];
1018 $unloadChunks = $this->usedChunks;
1019
1020 $world = $this->getWorld();
1021 $tickingChunkRadius = $world->getChunkTickRadius();
1022
1023 foreach($this->chunkSelector->selectChunks(
1024 $this->server->getAllowedViewDistance($this->viewDistance),
1025 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1026 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1027 ) as $radius => $hash){
1028 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1029 $newOrder[$hash] = true;
1030 }
1031 if($radius < $tickingChunkRadius){
1032 $tickingChunks[$hash] = true;
1033 }
1034 unset($unloadChunks[$hash]);
1035 }
1036
1037 foreach($unloadChunks as $index => $status){
1038 World::getXZ($index, $X, $Z);
1039 $this->unloadChunk($X, $Z);
1040 }
1041
1042 $this->loadQueue = $newOrder;
1043
1044 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1045 $this->tickingChunks = $tickingChunks;
1046
1047 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1048 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1049 }
1050
1051 Timings::$playerChunkOrder->stopTiming();
1052 }
1053
1058 public function isUsingChunk(int $chunkX, int $chunkZ) : bool{
1059 return isset($this->usedChunks[World::chunkHash($chunkX, $chunkZ)]);
1060 }
1061
1066 public function getUsedChunks() : array{
1067 return $this->usedChunks;
1068 }
1069
1073 public function getUsedChunkStatus(int $chunkX, int $chunkZ) : ?UsedChunkStatus{
1074 return $this->usedChunks[World::chunkHash($chunkX, $chunkZ)] ?? null;
1075 }
1076
1080 public function hasReceivedChunk(int $chunkX, int $chunkZ) : bool{
1081 $status = $this->usedChunks[World::chunkHash($chunkX, $chunkZ)] ?? null;
1082 return $status === UsedChunkStatus::SENT;
1083 }
1084
1088 public function doChunkRequests() : void{
1089 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1090 $this->nextChunkOrderRun = PHP_INT_MAX;
1091 $this->orderChunks();
1092 }
1093
1094 if(count($this->loadQueue) > 0){
1095 $this->requestChunks();
1096 }
1097 }
1098
1099 public function getDeathPosition() : ?Position{
1100 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1101 $this->deathPosition = null;
1102 }
1103 return $this->deathPosition;
1104 }
1105
1109 public function setDeathPosition(?Vector3 $pos) : void{
1110 if($pos !== null){
1111 if($pos instanceof Position && $pos->world !== null){
1112 $world = $pos->world;
1113 }else{
1114 $world = $this->getWorld();
1115 }
1116 $this->deathPosition = new Position($pos->x, $pos->y, $pos->z, $world);
1117 }else{
1118 $this->deathPosition = null;
1119 }
1120 $this->networkPropertiesDirty = true;
1121 }
1122
1126 public function getSpawn(){
1127 if($this->hasValidCustomSpawn()){
1128 return $this->spawnPosition;
1129 }else{
1130 $world = $this->server->getWorldManager()->getDefaultWorld();
1131
1132 return $world->getSpawnLocation();
1133 }
1134 }
1135
1136 public function hasValidCustomSpawn() : bool{
1137 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1138 }
1139
1146 public function setSpawn(?Vector3 $pos) : void{
1147 if($pos !== null){
1148 if(!($pos instanceof Position)){
1149 $world = $this->getWorld();
1150 }else{
1151 $world = $pos->getWorld();
1152 }
1153 $this->spawnPosition = new Position($pos->x, $pos->y, $pos->z, $world);
1154 }else{
1155 $this->spawnPosition = null;
1156 }
1157 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1158 }
1159
1160 public function isSleeping() : bool{
1161 return $this->sleeping !== null;
1162 }
1163
1164 public function sleepOn(Vector3 $pos) : bool{
1165 $pos = $pos->floor();
1166 $b = $this->getWorld()->getBlock($pos);
1167
1168 $ev = new PlayerBedEnterEvent($this, $b);
1169 $ev->call();
1170 if($ev->isCancelled()){
1171 return false;
1172 }
1173
1174 if($b instanceof Bed){
1175 $b->setOccupied();
1176 $this->getWorld()->setBlock($pos, $b);
1177 }
1178
1179 $this->sleeping = $pos;
1180 $this->networkPropertiesDirty = true;
1181
1182 $this->setSpawn($pos);
1183
1184 $this->getWorld()->setSleepTicks(60);
1185
1186 return true;
1187 }
1188
1189 public function stopSleep() : void{
1190 if($this->sleeping instanceof Vector3){
1191 $b = $this->getWorld()->getBlock($this->sleeping);
1192 if($b instanceof Bed){
1193 $b->setOccupied(false);
1194 $this->getWorld()->setBlock($this->sleeping, $b);
1195 }
1196 (new PlayerBedLeaveEvent($this, $b))->call();
1197
1198 $this->sleeping = null;
1199 $this->networkPropertiesDirty = true;
1200
1201 $this->getWorld()->setSleepTicks(0);
1202
1203 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1204 }
1205 }
1206
1207 public function getGamemode() : GameMode{
1208 return $this->gamemode;
1209 }
1210
1211 protected function internalSetGameMode(GameMode $gameMode) : void{
1212 $this->gamemode = $gameMode;
1213
1214 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1215 $this->hungerManager->setEnabled($this->isSurvival());
1216
1217 if($this->isSpectator()){
1218 $this->setFlying(true);
1219 $this->setHasBlockCollision(false);
1220 $this->setSilent();
1221 $this->onGround = false;
1222
1223 //TODO: HACK! this syncs the onground flag with the client so that flying works properly
1224 //this is a yucky hack but we don't have any other options :(
1225 $this->sendPosition($this->location, null, null, MovePlayerPacket::MODE_TELEPORT);
1226 }else{
1227 if($this->isSurvival()){
1228 $this->setFlying(false);
1229 }
1230 $this->setHasBlockCollision(true);
1231 $this->setSilent(false);
1232 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1233 }
1234 }
1235
1239 public function setGamemode(GameMode $gm) : bool{
1240 if($this->gamemode === $gm){
1241 return false;
1242 }
1243
1244 $ev = new PlayerGameModeChangeEvent($this, $gm);
1245 $ev->call();
1246 if($ev->isCancelled()){
1247 return false;
1248 }
1249
1250 $this->internalSetGameMode($gm);
1251
1252 if($this->isSpectator()){
1253 $this->despawnFromAll();
1254 }else{
1255 $this->spawnToAll();
1256 }
1257
1258 $this->getNetworkSession()->syncGameMode($this->gamemode);
1259 return true;
1260 }
1261
1268 public function isSurvival(bool $literal = false) : bool{
1269 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1270 }
1271
1278 public function isCreative(bool $literal = false) : bool{
1279 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1280 }
1281
1288 public function isAdventure(bool $literal = false) : bool{
1289 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1290 }
1291
1292 public function isSpectator() : bool{
1293 return $this->gamemode === GameMode::SPECTATOR;
1294 }
1295
1296 public function setSneakPressed(bool $sneakPressed) : void{
1297 $this->sneakPressed = $sneakPressed;
1298 }
1299
1304 public function isSneakPressed() : bool{
1305 return $this->sneakPressed;
1306 }
1307
1311 public function hasFiniteResources() : bool{
1312 return $this->gamemode !== GameMode::CREATIVE;
1313 }
1314
1315 public function getDrops() : array{
1316 if($this->hasFiniteResources()){
1317 return parent::getDrops();
1318 }
1319
1320 return [];
1321 }
1322
1323 public function getXpDropAmount() : int{
1324 if($this->hasFiniteResources()){
1325 return parent::getXpDropAmount();
1326 }
1327
1328 return 0;
1329 }
1330
1331 protected function checkGroundState(float $wantedX, float $wantedY, float $wantedZ, float $dx, float $dy, float $dz) : void{
1332 if(!$this->blockCollision){
1333 $this->onGround = false;
1334 }else{
1335 //TODO: AxisAlignedBB::withComponents() would be nice here
1336 $bb = new AxisAlignedBB(
1337 $this->boundingBox->minX,
1338 $this->location->y - 0.2,
1339 $this->boundingBox->minZ,
1340 $this->boundingBox->maxX,
1341 $this->location->y + 0.2,
1342 $this->boundingBox->maxZ
1343 );
1344
1345 //we're already at the new position at this point; check if there are blocks we might have landed on between
1346 //the old and new positions (running down stairs necessitates this)
1347 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1348
1349 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb, true)) > 0;
1350 }
1351 }
1352
1353 public function canBeMovedByCurrents() : bool{
1354 return false; //currently has no server-side movement
1355 }
1356
1357 protected function checkNearEntities() : void{
1358 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1359 $entity->scheduleUpdate();
1360
1361 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1362 continue;
1363 }
1364
1365 $entity->onCollideWithPlayer($this);
1366 }
1367 }
1368
1369 public function getInAirTicks() : int{
1370 return $this->inAirTicks;
1371 }
1372
1381 public function handleMovement(Vector3 $newPos) : void{
1382 Timings::$playerMove->startTiming();
1383 try{
1384 $this->actuallyHandleMovement($newPos);
1385 }finally{
1386 Timings::$playerMove->stopTiming();
1387 }
1388 }
1389
1390 private function actuallyHandleMovement(Vector3 $newPos) : void{
1391 $this->moveRateLimit--;
1392 if($this->moveRateLimit < 0){
1393 return;
1394 }
1395
1396 $oldPos = $this->location;
1397 $distanceSquared = $newPos->distanceSquared($oldPos);
1398
1399 $revert = false;
1400
1401 if($distanceSquared > 225){ //15 blocks
1402 //TODO: this is probably too big if we process every movement
1403 /* !!! BEWARE YE WHO ENTER HERE !!!
1404 *
1405 * This is NOT an anti-cheat check. It is a safety check.
1406 * Without it hackers can teleport with freedom on their own and cause lots of undesirable behaviour, like
1407 * freezes, lag spikes and memory exhaustion due to sync chunk loading and collision checks across large distances.
1408 * Not only that, but high-latency players can trigger such behaviour innocently.
1409 *
1410 * If you must tamper with this code, be aware that this can cause very nasty results. Do not waste our time
1411 * asking for help if you suffer the consequences of messing with this.
1412 */
1413 $this->logger->debug("Moved too fast (" . sqrt($distanceSquared) . " blocks in 1 movement), reverting movement");
1414 $this->logger->debug("Old position: " . $oldPos->asVector3() . ", new position: " . $newPos);
1415 $revert = true;
1416 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1417 $revert = true;
1418 $this->nextChunkOrderRun = 0;
1419 }
1420
1421 if(!$revert && $distanceSquared !== 0.0){
1422 $dx = $newPos->x - $oldPos->x;
1423 $dy = $newPos->y - $oldPos->y;
1424 $dz = $newPos->z - $oldPos->z;
1425
1426 $this->move($dx, $dy, $dz);
1427 }
1428
1429 if($revert){
1430 $this->revertMovement($oldPos);
1431 }
1432 }
1433
1437 protected function processMostRecentMovements() : void{
1438 $now = microtime(true);
1439 $multiplier = $this->lastMovementProcess !== null ? ($now - $this->lastMovementProcess) * 20 : 1;
1440 $exceededRateLimit = $this->moveRateLimit < 0;
1441 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1442 $this->lastMovementProcess = $now;
1443
1444 $from = clone $this->lastLocation;
1445 $to = clone $this->location;
1446
1447 $delta = $to->distanceSquared($from);
1448 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1449
1450 if($delta > 0.0001 || $deltaAngle > 1.0){
1451 if(PlayerMoveEvent::hasHandlers()){
1452 $ev = new PlayerMoveEvent($this, $from, $to);
1453
1454 $ev->call();
1455
1456 if($ev->isCancelled()){
1457 $this->revertMovement($from);
1458 return;
1459 }
1460
1461 if($to->distanceSquared($ev->getTo()) > 0.01){ //If plugins modify the destination
1462 $this->teleport($ev->getTo());
1463 return;
1464 }
1465 }
1466
1467 $this->lastLocation = $to;
1468 $this->broadcastMovement();
1469
1470 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1471 if($horizontalDistanceTravelled > 0){
1472 //TODO: check for swimming
1473 if($this->isSprinting()){
1474 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, EntityExhaustEvent::CAUSE_SPRINTING);
1475 }else{
1476 $this->hungerManager->exhaust(0.0, EntityExhaustEvent::CAUSE_WALKING);
1477 }
1478
1479 if($this->nextChunkOrderRun > 20){
1480 $this->nextChunkOrderRun = 20;
1481 }
1482 }
1483 }
1484
1485 if($exceededRateLimit){ //client and server positions will be out of sync if this happens
1486 $this->logger->debug("Exceeded movement rate limit, forcing to last accepted position");
1487 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1488 }
1489 }
1490
1491 protected function revertMovement(Location $from) : void{
1492 $this->setPosition($from);
1493 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1494 }
1495
1496 protected function calculateFallDamage(float $fallDistance) : float{
1497 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1498 }
1499
1500 public function jump() : void{
1501 (new PlayerJumpEvent($this))->call();
1502 parent::jump();
1503 }
1504
1505 public function setMotion(Vector3 $motion) : bool{
1506 if(parent::setMotion($motion)){
1507 $this->broadcastMotion();
1508 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->id, $motion, tick: 0));
1509
1510 return true;
1511 }
1512 return false;
1513 }
1514
1515 protected function updateMovement(bool $teleport = false) : void{
1516
1517 }
1518
1519 protected function tryChangeMovement() : void{
1520
1521 }
1522
1523 public function onUpdate(int $currentTick) : bool{
1524 $tickDiff = $currentTick - $this->lastUpdate;
1525
1526 if($tickDiff <= 0){
1527 return true;
1528 }
1529
1530 $this->messageCounter = 2;
1531
1532 $this->lastUpdate = $currentTick;
1533
1534 if($this->justCreated){
1535 $this->onFirstUpdate($currentTick);
1536 }
1537
1538 if(!$this->isAlive() && $this->spawned){
1539 $this->onDeathUpdate($tickDiff);
1540 return true;
1541 }
1542
1543 $this->timings->startTiming();
1544
1545 if($this->spawned){
1546 Timings::$playerMove->startTiming();
1547 $this->processMostRecentMovements();
1548 $this->motion = Vector3::zero(); //TODO: HACK! (Fixes player knockback being messed up)
1549 if($this->onGround){
1550 $this->inAirTicks = 0;
1551 }else{
1552 $this->inAirTicks += $tickDiff;
1553 }
1554 Timings::$playerMove->stopTiming();
1555
1556 Timings::$entityBaseTick->startTiming();
1557 $this->entityBaseTick($tickDiff);
1558 Timings::$entityBaseTick->stopTiming();
1559
1560 if($this->isCreative() && $this->fireTicks > 1){
1561 $this->fireTicks = 1;
1562 }
1563
1564 if(!$this->isSpectator() && $this->isAlive()){
1565 Timings::$playerCheckNearEntities->startTiming();
1566 $this->checkNearEntities();
1567 Timings::$playerCheckNearEntities->stopTiming();
1568 }
1569
1570 if($this->blockBreakHandler !== null && !$this->blockBreakHandler->update()){
1571 $this->blockBreakHandler = null;
1572 }
1573 }
1574
1575 $this->timings->stopTiming();
1576
1577 return true;
1578 }
1579
1580 public function canEat() : bool{
1581 return $this->isCreative() || parent::canEat();
1582 }
1583
1584 public function canBreathe() : bool{
1585 return $this->isCreative() || parent::canBreathe();
1586 }
1587
1593 public function canInteract(Vector3 $pos, float $maxDistance, float $maxDiff = M_SQRT3 / 2) : bool{
1594 $eyePos = $this->getEyePos();
1595 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1596 return false;
1597 }
1598
1599 $dV = $this->getDirectionVector();
1600 $eyeDot = $dV->dot($eyePos);
1601 $targetDot = $dV->dot($pos);
1602 return ($targetDot - $eyeDot) >= -$maxDiff;
1603 }
1604
1609 public function chat(string $message) : bool{
1610 $this->removeCurrentWindow();
1611
1612 if($this->messageCounter <= 0){
1613 //the check below would take care of this (0 * (maxlen + 1) = 0), but it's better be explicit
1614 return false;
1615 }
1616
1617 //Fast length check, to make sure we don't get hung trying to explode MBs of string ...
1618 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1619 if(strlen($message) > $maxTotalLength){
1620 return false;
1621 }
1622
1623 $message = TextFormat::clean($message, false);
1624 foreach(explode("\n", $message, $this->messageCounter + 1) as $messagePart){
1625 if(trim($messagePart) !== "" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart, 'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1626 if(str_starts_with($messagePart, './')){
1627 $messagePart = substr($messagePart, 1);
1628 }
1629
1630 if(str_starts_with($messagePart, "/")){
1631 Timings::$playerCommand->startTiming();
1632 $this->server->dispatchCommand($this, substr($messagePart, 1));
1633 Timings::$playerCommand->stopTiming();
1634 }else{
1635 $ev = new PlayerChatEvent($this, $messagePart, $this->server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS), new StandardChatFormatter());
1636 $ev->call();
1637 if(!$ev->isCancelled()){
1638 $this->server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1639 }
1640 }
1641 }
1642 }
1643
1644 return true;
1645 }
1646
1647 public function selectHotbarSlot(int $hotbarSlot) : bool{
1648 if(!$this->hotbar->isHotbarSlot($hotbarSlot)){ //TODO: exception here?
1649 return false;
1650 }
1651 if($hotbarSlot === $this->hotbar->getSelectedIndex()){
1652 return true;
1653 }
1654
1655 $ev = new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1656 $ev->call();
1657 if($ev->isCancelled()){
1658 return false;
1659 }
1660
1661 $this->hotbar->setSelectedIndex($hotbarSlot);
1662 $this->setUsingItem(false);
1663
1664 return true;
1665 }
1666
1670 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1671 $heldItemChanged = false;
1672
1673 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->getMainHandItem())){
1674 //determine if the item was changed in some meaningful way, or just damaged/changed count
1675 //if it was really changed we always need to set it, whether we have finite resources or not
1676 $newReplica = clone $oldHeldItem;
1677 $newReplica->setCount($newHeldItem->getCount());
1678 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1679 $newDamage = $newHeldItem->getDamage();
1680 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1681 $newReplica->setDamage($newDamage);
1682 }
1683 }
1684 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1685
1686 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1687 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1688 $this->broadcastSound(new ItemBreakSound());
1689 }
1690 $this->setMainHandItem($newHeldItem);
1691 $heldItemChanged = true;
1692 }
1693 }
1694
1695 if(!$heldItemChanged){
1696 $newHeldItem = $oldHeldItem;
1697 }
1698
1699 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1700 $this->setMainHandItem(array_shift($extraReturnedItems));
1701 }
1702 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1703 //TODO: we can't generate a transaction for this since the items aren't coming from an inventory :(
1704 $ev = new PlayerDropItemEvent($this, $drop);
1705 if($this->isSpectator()){
1706 $ev->cancel();
1707 }
1708 $ev->call();
1709 if(!$ev->isCancelled()){
1710 $this->dropItem($drop);
1711 }
1712 }
1713 }
1714
1720 public function useHeldItem() : bool{
1721 $directionVector = $this->getDirectionVector();
1722 $item = $this->getMainHandItem();
1723 $oldItem = clone $item;
1724
1725 $ev = new PlayerItemUseEvent($this, $item, $directionVector);
1726 if($this->hasItemCooldown($item) || $this->isSpectator()){
1727 $ev->cancel();
1728 }
1729
1730 $ev->call();
1731
1732 if($ev->isCancelled()){
1733 return false;
1734 }
1735
1736 $returnedItems = [];
1737 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1738 if($result === ItemUseResult::FAIL){
1739 return false;
1740 }
1741
1742 $this->resetItemCooldown($oldItem);
1743 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1744
1745 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1746
1747 return true;
1748 }
1749
1755 public function consumeHeldItem() : bool{
1756 $slot = $this->getMainHandItem();
1757 if($slot instanceof ConsumableItem){
1758 $oldItem = clone $slot;
1759
1760 $ev = new PlayerItemConsumeEvent($this, $slot);
1761 if($this->hasItemCooldown($slot)){
1762 $ev->cancel();
1763 }
1764 $ev->call();
1765
1766 if($ev->isCancelled() || !$this->consumeObject($slot)){
1767 return false;
1768 }
1769
1770 $this->setUsingItem(false);
1771 $this->resetItemCooldown($oldItem);
1772
1773 $slot->pop();
1774 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1775
1776 return true;
1777 }
1778
1779 return false;
1780 }
1781
1787 public function releaseHeldItem() : bool{
1788 try{
1789 $item = $this->getMainHandItem();
1790 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1791 return false;
1792 }
1793
1794 $oldItem = clone $item;
1795
1796 $returnedItems = [];
1797 $result = $item->onReleaseUsing($this, $returnedItems);
1798 if($result === ItemUseResult::SUCCESS){
1799 $this->resetItemCooldown($oldItem);
1800 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1801 return true;
1802 }
1803
1804 return false;
1805 }finally{
1806 $this->setUsingItem(false);
1807 }
1808 }
1809
1810 public function pickBlock(Vector3 $pos, bool $addTileNBT) : bool{
1811 $block = $this->getWorld()->getBlock($pos);
1812 if($block instanceof UnknownBlock){
1813 return true;
1814 }
1815
1816 $item = $block->getPickedItem($addTileNBT);
1817
1818 $ev = new PlayerBlockPickEvent($this, $block, $item);
1819 $existingSlot = $this->inventory->first($item);
1820 if($existingSlot === -1 && $this->hasFiniteResources()){
1821 $ev->cancel();
1822 }
1823 $ev->call();
1824
1825 if(!$ev->isCancelled()){
1826 $this->equipOrAddPickedItem($existingSlot, $item);
1827 }
1828
1829 return true;
1830 }
1831
1832 public function pickEntity(int $entityId) : bool{
1833 $entity = $this->getWorld()->getEntity($entityId);
1834 if($entity === null){
1835 return true;
1836 }
1837
1838 $item = $entity->getPickedItem();
1839 if($item === null){
1840 return true;
1841 }
1842
1843 $ev = new PlayerEntityPickEvent($this, $entity, $item);
1844 $existingSlot = $this->inventory->first($item);
1845 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1846 $ev->cancel();
1847 }
1848 $ev->call();
1849
1850 if(!$ev->isCancelled()){
1851 $this->equipOrAddPickedItem($existingSlot, $item);
1852 }
1853
1854 return true;
1855 }
1856
1857 private function equipOrAddPickedItem(int $existingSlot, Item $item) : void{
1858 if($existingSlot !== -1){
1859 if($existingSlot < $this->hotbar->getSize()){
1860 $this->hotbar->setSelectedIndex($existingSlot);
1861 }else{
1862 $this->inventory->swap($this->hotbar->getSelectedIndex(), $existingSlot);
1863 }
1864 }else{
1865 $firstEmpty = $this->inventory->firstEmpty();
1866 if($firstEmpty === -1){ //full inventory
1867 $this->setMainHandItem($item);
1868 }elseif($firstEmpty < $this->hotbar->getSize()){
1869 $this->inventory->setItem($firstEmpty, $item);
1870 $this->hotbar->setSelectedIndex($firstEmpty);
1871 }else{
1872 $this->inventory->swap($this->hotbar->getSelectedIndex(), $firstEmpty);
1873 $this->setMainHandItem($item);
1874 }
1875 }
1876 }
1877
1883 public function attackBlock(Vector3 $pos, Facing $face) : bool{
1884 if($pos->distanceSquared($this->location) > 10000){
1885 return false; //TODO: maybe this should throw an exception instead?
1886 }
1887
1888 $target = $this->getWorld()->getBlock($pos);
1889
1890 $ev = new PlayerInteractEvent($this, $this->getMainHandItem(), $target, null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1891 if($this->isSpectator()){
1892 $ev->cancel();
1893 }
1894 $ev->call();
1895 if($ev->isCancelled()){
1896 return false;
1897 }
1898 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1899 if($target->onAttack($this->getMainHandItem(), $face, $this)){
1900 return true;
1901 }
1902
1903 $block = $target->getSide($face);
1904 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1905 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1906 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5), new FireExtinguishSound());
1907 return true;
1908 }
1909
1910 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1911 $this->blockBreakHandler = new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1912 }
1913
1914 return true;
1915 }
1916
1917 public function continueBreakBlock(Vector3 $pos, Facing $face) : void{
1918 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1919 $this->blockBreakHandler->setTargetedFace($face);
1920 }
1921 }
1922
1923 public function stopBreakBlock(Vector3 $pos) : void{
1924 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1925 $this->blockBreakHandler = null;
1926 }
1927 }
1928
1934 public function breakBlock(Vector3 $pos) : bool{
1935 $this->removeCurrentWindow();
1936
1937 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1938 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1939 $this->stopBreakBlock($pos);
1940 $item = $this->getMainHandItem();
1941 $oldItem = clone $item;
1942 $returnedItems = [];
1943 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1944 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1945 $this->hungerManager->exhaust(0.005, EntityExhaustEvent::CAUSE_MINING);
1946 return true;
1947 }
1948 }else{
1949 $this->logger->debug("Cancelled block break at $pos due to not currently being interactable");
1950 }
1951
1952 return false;
1953 }
1954
1960 public function interactBlock(Vector3 $pos, Facing $face, Vector3 $clickOffset) : bool{
1961 $this->setUsingItem(false);
1962
1963 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1964 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1965 $item = $this->getMainHandItem(); //this is a copy of the real item
1966 $oldItem = clone $item;
1967 $returnedItems = [];
1968 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1969 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1970 return true;
1971 }
1972 }else{
1973 $this->logger->debug("Cancelled interaction of block at $pos due to not currently being interactable");
1974 }
1975
1976 return false;
1977 }
1978
1985 public function attackEntity(Entity $entity) : bool{
1986 if(!$entity->isAlive()){
1987 return false;
1988 }
1989 if($entity instanceof ItemEntity || $entity instanceof Arrow){
1990 $this->logger->debug("Attempted to attack non-attackable entity " . get_class($entity));
1991 return false;
1992 }
1993
1994 $heldItem = $this->getMainHandItem();
1995 $oldItem = clone $heldItem;
1996
1997 $ev = new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1998 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1999 $this->logger->debug("Cancelled attack of entity " . $entity->getId() . " due to not currently being interactable");
2000 $ev->cancel();
2001 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
2002 $ev->cancel();
2003 }
2004
2005 $meleeEnchantmentDamage = 0;
2007 $meleeEnchantments = [];
2008 foreach($heldItem->getEnchantments() as $enchantment){
2009 $type = $enchantment->getType();
2010 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
2011 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
2012 $meleeEnchantments[] = $enchantment;
2013 }
2014 }
2015 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
2016
2017 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
2018 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
2019 }
2020
2021 $entity->attack($ev);
2022 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2023
2024 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
2025 if($ev->isCancelled()){
2026 $this->getWorld()->addSound($soundPos, new EntityAttackNoDamageSound());
2027 return false;
2028 }
2029 $this->getWorld()->addSound($soundPos, new EntityAttackSound());
2030
2031 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2032 $entity->broadcastAnimation(new CriticalHitAnimation($entity));
2033 }
2034
2035 foreach($meleeEnchantments as $enchantment){
2036 $type = $enchantment->getType();
2037 assert($type instanceof MeleeWeaponEnchantment);
2038 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2039 }
2040
2041 if($this->isAlive()){
2042 //reactive damage like thorns might cause us to be killed by attacking another mob, which
2043 //would mean we'd already have dropped the inventory by the time we reached here
2044 $returnedItems = [];
2045 $heldItem->onAttackEntity($entity, $returnedItems);
2046 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2047
2048 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_ATTACK);
2049 }
2050
2051 return true;
2052 }
2053
2058 public function missSwing() : void{
2059 $ev = new PlayerMissSwingEvent($this);
2060 $ev->call();
2061 if(!$ev->isCancelled()){
2062 $this->broadcastSound(new EntityAttackNoDamageSound());
2063 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2064 }
2065 }
2066
2070 public function interactEntity(Entity $entity, Vector3 $clickPos) : bool{
2071 $ev = new PlayerEntityInteractEvent($this, $entity, $clickPos);
2072
2073 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2074 $this->logger->debug("Cancelled interaction with entity " . $entity->getId() . " due to not currently being interactable");
2075 $ev->cancel();
2076 }
2077
2078 $ev->call();
2079
2080 $item = $this->getMainHandItem();
2081 $oldItem = clone $item;
2082 if(!$ev->isCancelled()){
2083 if($item->onInteractEntity($this, $entity, $clickPos)){
2084 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->getMainHandItem())){
2085 if($item instanceof Durable && $item->isBroken()){
2086 $this->broadcastSound(new ItemBreakSound());
2087 }
2088 $this->setMainHandItem($item);
2089 }
2090 }
2091 return $entity->onInteract($this, $clickPos);
2092 }
2093 return false;
2094 }
2095
2096 public function toggleSprint(bool $sprint) : bool{
2097 if($sprint === $this->sprinting){
2098 return true;
2099 }
2100 $ev = new PlayerToggleSprintEvent($this, $sprint);
2101 $ev->call();
2102 if($ev->isCancelled()){
2103 return false;
2104 }
2105 $this->setSprinting($sprint);
2106 return true;
2107 }
2108
2109 public function toggleSneak(bool $sneak, bool $sneakPressed = true) : bool{
2110 if($sneak === $this->sneaking && $sneakPressed === $this->sneakPressed){
2111 return true;
2112 }
2113 $this->setSneakPressed($sneakPressed);
2114
2115 $ev = new PlayerToggleSneakEvent($this, $sneak, $sneakPressed);
2116 if($sneak === $this->sneaking){
2117 $ev->cancel();
2118 }
2119 $ev->call();
2120
2121 if($ev->isCancelled()){
2122 return false;
2123 }
2124 $this->setSneaking($sneak);
2125 return true;
2126 }
2127
2128 public function toggleFlight(bool $fly) : bool{
2129 if($fly === $this->flying){
2130 return true;
2131 }
2132 $ev = new PlayerToggleFlightEvent($this, $fly);
2133 if(!$this->allowFlight){
2134 $ev->cancel();
2135 }
2136 $ev->call();
2137 if($ev->isCancelled()){
2138 return false;
2139 }
2140 $this->setFlying($fly);
2141 return true;
2142 }
2143
2144 public function toggleGlide(bool $glide) : bool{
2145 if($glide === $this->gliding){
2146 return true;
2147 }
2148 $ev = new PlayerToggleGlideEvent($this, $glide);
2149 $ev->call();
2150 if($ev->isCancelled()){
2151 return false;
2152 }
2153 $this->setGliding($glide);
2154 return true;
2155 }
2156
2157 public function toggleSwim(bool $swim) : bool{
2158 if($swim === $this->swimming){
2159 return true;
2160 }
2161 $ev = new PlayerToggleSwimEvent($this, $swim);
2162 $ev->call();
2163 if($ev->isCancelled()){
2164 return false;
2165 }
2166 $this->setSwimming($swim);
2167 return true;
2168 }
2169
2170 public function emote(string $emoteId) : void{
2171 $currentTick = $this->server->getTick();
2172 if($currentTick - $this->lastEmoteTick > 5){
2173 $this->lastEmoteTick = $currentTick;
2174 $event = new PlayerEmoteEvent($this, $emoteId);
2175 $event->call();
2176 if(!$event->isCancelled()){
2177 $emoteId = $event->getEmoteId();
2178 parent::emote($emoteId);
2179 }
2180 }
2181 }
2182
2186 public function dropItem(Item $item) : void{
2187 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2188 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2189 }
2190
2198 public function sendTitle(string $title, string $subtitle = "", int $fadeIn = -1, int $stay = -1, int $fadeOut = -1) : void{
2199 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2200 if($subtitle !== ""){
2201 $this->sendSubTitle($subtitle);
2202 }
2203 $this->getNetworkSession()->onTitle($title);
2204 }
2205
2209 public function sendSubTitle(string $subtitle) : void{
2210 $this->getNetworkSession()->onSubTitle($subtitle);
2211 }
2212
2216 public function sendActionBarMessage(string $message) : void{
2217 $this->getNetworkSession()->onActionBar($message);
2218 }
2219
2223 public function removeTitles() : void{
2224 $this->getNetworkSession()->onClearTitle();
2225 }
2226
2230 public function resetTitles() : void{
2231 $this->getNetworkSession()->onResetTitleOptions();
2232 }
2233
2241 public function setTitleDuration(int $fadeIn, int $stay, int $fadeOut) : void{
2242 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2243 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2244 }
2245 }
2246
2250 public function sendMessage(Translatable|string $message) : void{
2251 $this->getNetworkSession()->onChatMessage($message);
2252 }
2253
2254 public function sendJukeboxPopup(Translatable|string $message) : void{
2255 $this->getNetworkSession()->onJukeboxPopup($message);
2256 }
2257
2263 public function sendPopup(string $message) : void{
2264 $this->getNetworkSession()->onPopup($message);
2265 }
2266
2267 public function sendTip(string $message) : void{
2268 $this->getNetworkSession()->onTip($message);
2269 }
2270
2274 public function sendToastNotification(string $title, string $body) : void{
2275 $this->getNetworkSession()->onToastNotification($title, $body);
2276 }
2277
2283 public function sendForm(Form $form) : void{
2284 $id = $this->formIdCounter++;
2285 if($this->getNetworkSession()->onFormSent($id, $form)){
2286 $this->forms[$id] = $form;
2287 }
2288 }
2289
2290 public function onFormSubmit(int $formId, mixed $responseData) : bool{
2291 if(!isset($this->forms[$formId])){
2292 $this->logger->debug("Got unexpected response for form $formId");
2293 return false;
2294 }
2295
2296 try{
2297 $this->forms[$formId]->handleResponse($this, $responseData);
2298 }catch(FormValidationException $e){
2299 $this->logger->critical("Failed to validate form " . get_class($this->forms[$formId]) . ": " . $e->getMessage());
2300 $this->logger->logException($e);
2301 }finally{
2302 unset($this->forms[$formId]);
2303 }
2304
2305 return true;
2306 }
2307
2311 public function closeAllForms() : void{
2312 $this->getNetworkSession()->onCloseAllForms();
2313 }
2314
2324 public function transfer(string $address, int $port = 19132, Translatable|string|null $message = null) : bool{
2325 $ev = new PlayerTransferEvent($this, $address, $port, $message ?? KnownTranslationFactory::pocketmine_disconnect_transfer());
2326 $ev->call();
2327 if(!$ev->isCancelled()){
2328 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2329 return true;
2330 }
2331
2332 return false;
2333 }
2334
2342 public function kick(Translatable|string $reason = "", Translatable|string|null $quitMessage = null, Translatable|string|null $disconnectScreenMessage = null) : bool{
2343 $ev = new PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2344 $ev->call();
2345 if(!$ev->isCancelled()){
2346 $reason = $ev->getDisconnectReason();
2347 if($reason === ""){
2348 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2349 }
2350 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2351 if($disconnectScreenMessage === ""){
2352 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2353 }
2354 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2355
2356 return true;
2357 }
2358
2359 return false;
2360 }
2361
2375 public function disconnect(Translatable|string $reason, Translatable|string|null $quitMessage = null, Translatable|string|null $disconnectScreenMessage = null) : void{
2376 if(!$this->isConnected()){
2377 return;
2378 }
2379
2380 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2381 $this->onPostDisconnect($reason, $quitMessage);
2382 }
2383
2391 public function onPostDisconnect(Translatable|string $reason, Translatable|string|null $quitMessage) : void{
2392 if($this->isConnected()){
2393 throw new \LogicException("Player is still connected");
2394 }
2395
2396 //prevent the player receiving their own disconnect message
2397 $this->server->unsubscribeFromAllBroadcastChannels($this);
2398
2399 $this->removeCurrentWindow();
2400
2401 $ev = new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2402 $ev->call();
2403 if(($quitMessage = $ev->getQuitMessage()) !== ""){
2404 $this->server->broadcastMessage($quitMessage);
2405 }
2406 $this->save();
2407
2408 $this->spawned = false;
2409
2410 $this->stopSleep();
2411 $this->blockBreakHandler = null;
2412 $this->despawnFromAll();
2413
2414 $this->server->removeOnlinePlayer($this);
2415
2416 foreach($this->server->getOnlinePlayers() as $player){
2417 if(!$player->canSee($this)){
2418 $player->showPlayer($this);
2419 }
2420 }
2421 $this->hiddenPlayers = [];
2422
2423 if($this->location->isValid()){
2424 foreach($this->usedChunks as $index => $status){
2425 World::getXZ($index, $chunkX, $chunkZ);
2426 $this->unloadChunk($chunkX, $chunkZ);
2427 }
2428 }
2429 if(count($this->usedChunks) !== 0){
2430 throw new AssumptionFailedError("Previous loop should have cleared this array");
2431 }
2432 $this->loadQueue = [];
2433
2434 $this->removeCurrentWindow();
2435 $this->removePermanentWindows();
2436
2437 $this->perm->getPermissionRecalculationCallbacks()->clear();
2438
2439 $this->flagForDespawn();
2440 }
2441
2442 protected function onDispose() : void{
2443 $this->disconnect("Player destroyed");
2444 $this->cursorInventory->removeAllWindows();
2445 $this->craftingGrid->removeAllWindows();
2446 parent::onDispose();
2447 }
2448
2449 protected function destroyCycles() : void{
2450 $this->networkSession = null;
2451 $this->spawnPosition = null;
2452 $this->deathPosition = null;
2453 $this->blockBreakHandler = null;
2454 parent::destroyCycles();
2455 }
2456
2460 public function __debugInfo() : array{
2461 return [];
2462 }
2463
2464 public function __destruct(){
2465 parent::__destruct();
2466 $this->logger->debug("Destroyed by garbage collector");
2467 }
2468
2469 public function canSaveWithChunk() : bool{
2470 return false;
2471 }
2472
2473 public function setCanSaveWithChunk(bool $value) : void{
2474 throw new \BadMethodCallException("Players can't be saved with chunks");
2475 }
2476
2477 public function getSaveData() : CompoundTag{
2478 $nbt = $this->saveNBT();
2479
2480 $nbt->setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2481
2482 if($this->location->isValid()){
2483 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2484 }
2485
2486 if($this->hasValidCustomSpawn()){
2487 $spawn = $this->getSpawn();
2488 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2489 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2490 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2491 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2492 }
2493
2494 if($this->deathPosition !== null && $this->deathPosition->isValid()){
2495 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2496 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2497 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2498 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2499 }
2500
2501 $nbt->setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2502 $nbt->setLong(self::TAG_FIRST_PLAYED, (int) $this->firstPlayed->format('Uv'));
2503 $nbt->setLong(self::TAG_LAST_PLAYED, (int) floor(microtime(true) * 1000));
2504
2505 return $nbt;
2506 }
2507
2511 public function save() : void{
2512 $this->server->saveOfflinePlayerData($this->username, $this->getSaveData());
2513 }
2514
2515 protected function onDeath() : void{
2516 //Crafting grid must always be evacuated even if keep-inventory is true. This dumps the contents into the
2517 //main inventory and drops the rest on the ground.
2518 $this->removeCurrentWindow();
2519
2520 $this->setDeathPosition($this->getPosition());
2521
2522 $ev = new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(), null);
2523 $ev->call();
2524
2525 if(!$ev->getKeepInventory()){
2526 foreach($ev->getDrops() as $item){
2527 $this->getWorld()->dropItem($this->location, $item);
2528 }
2529
2530 $this->hotbar->setSelectedIndex(0);
2531 $clearInventory = fn(Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(Item $item) => $item->keepOnDeath()));
2532 $clearInventory($this->inventory);
2533 $clearInventory($this->armorInventory);
2534 $clearInventory($this->offHandInventory);
2535 }
2536
2537 if(!$ev->getKeepXp()){
2538 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2539 $this->xpManager->setXpAndProgress(0, 0.0);
2540 }
2541
2542 if($ev->getDeathMessage() !== ""){
2543 $this->server->broadcastMessage($ev->getDeathMessage());
2544 }
2545
2546 $this->startDeathAnimation();
2547
2548 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2549 }
2550
2551 protected function onDeathUpdate(int $tickDiff) : bool{
2552 parent::onDeathUpdate($tickDiff);
2553 return false; //never flag players for despawn
2554 }
2555
2556 public function respawn() : void{
2557 if($this->server->isHardcore()){
2558 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){ //this allows plugins to prevent the ban by cancelling PlayerKickEvent
2559 $this->server->getNameBans()->addBan($this->getName(), "Died in hardcore mode");
2560 }
2561 return;
2562 }
2563
2564 $this->actuallyRespawn();
2565 }
2566
2567 protected function actuallyRespawn() : void{
2568 if($this->respawnLocked){
2569 return;
2570 }
2571 $this->respawnLocked = true;
2572
2573 $this->logger->debug("Waiting for safe respawn position to be located");
2574 $spawn = $this->getSpawn();
2575 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2576 function(Position $safeSpawn) : void{
2577 if(!$this->isConnected()){
2578 return;
2579 }
2580 $this->logger->debug("Respawn position located, completing respawn");
2581 $ev = new PlayerRespawnEvent($this, $safeSpawn);
2582 $spawnPosition = $ev->getRespawnPosition();
2583 $spawnBlock = $spawnPosition->getWorld()->getBlock($spawnPosition);
2584 if($spawnBlock instanceof RespawnAnchor){
2585 if($spawnBlock->getCharges() > 0){
2586 $spawnPosition->getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2587 $spawnPosition->getWorld()->addSound($spawnPosition, new RespawnAnchorDepleteSound());
2588 }else{
2589 $defaultSpawn = $this->server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2590 if($defaultSpawn !== null){
2591 $this->setSpawn($defaultSpawn);
2592 $ev->setRespawnPosition($defaultSpawn);
2593 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2594 }
2595 }
2596 }
2597 $ev->call();
2598
2599 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2600 $this->teleport($realSpawn);
2601
2602 $this->setSprinting(false);
2603 $this->setSneaking(false);
2604 $this->setFlying(false);
2605
2606 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2607 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2608 $this->deadTicks = 0;
2609 $this->noDamageTicks = 60;
2610
2611 $this->effectManager->clear();
2612 $this->setHealth($this->getMaxHealth());
2613
2614 foreach($this->attributeMap->getAll() as $attr){
2615 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){ //we have already reset both of those if needed when the player died
2616 continue;
2617 }
2618 $attr->resetToDefault();
2619 }
2620
2621 $this->spawnToAll();
2622 $this->scheduleUpdate();
2623
2624 $this->getNetworkSession()->onServerRespawn();
2625 $this->respawnLocked = false;
2626 },
2627 function() : void{
2628 if($this->isConnected()){
2629 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2630 }
2631 }
2632 );
2633 }
2634
2635 protected function applyPostDamageEffects(EntityDamageEvent $source) : void{
2636 parent::applyPostDamageEffects($source);
2637
2638 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_DAMAGE);
2639 }
2640
2641 public function attack(EntityDamageEvent $source) : void{
2642 if(!$this->isAlive()){
2643 return;
2644 }
2645
2646 if($this->isCreative()
2647 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2648 ){
2649 $source->cancel();
2650 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2651 $source->cancel();
2652 }
2653
2654 parent::attack($source);
2655 }
2656
2657 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2658 parent::syncNetworkData($properties);
2659
2660 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2661 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2662
2663 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !== null);
2664 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !== null ? BlockPosition::fromVector3($this->sleeping) : new BlockPosition(0, 0, 0));
2665
2666 if($this->deathPosition !== null && $this->deathPosition->world === $this->location->world){
2667 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2668 //TODO: this should be updated when dimensions are implemented
2669 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2670 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2671 }else{
2672 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2673 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2674 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2675 }
2676 }
2677
2678 public function sendData(?array $targets, ?array $data = null) : void{
2679 if($targets === null){
2680 $targets = $this->getViewers();
2681 $targets[] = $this;
2682 }
2683 parent::sendData($targets, $data);
2684 }
2685
2686 public function broadcastAnimation(Animation $animation, ?array $targets = null) : void{
2687 if($this->spawned && $targets === null){
2688 $targets = $this->getViewers();
2689 $targets[] = $this;
2690 }
2691 parent::broadcastAnimation($animation, $targets);
2692 }
2693
2694 public function broadcastSound(Sound $sound, ?array $targets = null) : void{
2695 if($this->spawned && $targets === null){
2696 $targets = $this->getViewers();
2697 $targets[] = $this;
2698 }
2699 parent::broadcastSound($sound, $targets);
2700 }
2701
2705 protected function sendPosition(Vector3 $pos, ?float $yaw = null, ?float $pitch = null, int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2706 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2707
2708 $this->ySize = 0;
2709 }
2710
2711 public function teleport(Vector3 $pos, ?float $yaw = null, ?float $pitch = null) : bool{
2712 if(parent::teleport($pos, $yaw, $pitch)){
2713
2714 $this->removeCurrentWindow();
2715 $this->stopSleep();
2716
2717 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2718 $this->broadcastMovement(true);
2719
2720 $this->spawnToAll();
2721
2722 $this->resetFallDistance();
2723 $this->nextChunkOrderRun = 0;
2724 if($this->spawnChunkLoadCount !== -1){
2725 $this->spawnChunkLoadCount = 0;
2726 }
2727 $this->blockBreakHandler = null;
2728
2729 //TODO: workaround for player last pos not getting updated
2730 //Entity::updateMovement() normally handles this, but it's overridden with an empty function in Player
2731 $this->resetLastMovements();
2732
2733 return true;
2734 }
2735
2736 return false;
2737 }
2738
2739 protected function addDefaultWindows() : void{
2740 $this->cursorInventory = new SimpleInventory(1);
2741 $this->craftingGrid = new CraftingGrid(CraftingGrid::SIZE_SMALL);
2742
2743 $this->addPermanentWindows([
2744 new PlayerInventoryWindow($this, $this->inventory, PlayerInventoryWindow::TYPE_INVENTORY),
2745 new PlayerInventoryWindow($this, $this->armorInventory, PlayerInventoryWindow::TYPE_ARMOR),
2746 new PlayerInventoryWindow($this, $this->cursorInventory, PlayerInventoryWindow::TYPE_CURSOR),
2747 new PlayerInventoryWindow($this, $this->offHandInventory, PlayerInventoryWindow::TYPE_OFFHAND),
2748 new PlayerInventoryWindow($this, $this->craftingGrid, PlayerInventoryWindow::TYPE_CRAFTING),
2749 ]);
2750 }
2751
2752 public function getCursorInventory() : Inventory{
2753 return $this->cursorInventory;
2754 }
2755
2756 public function getCraftingGrid() : CraftingGrid{
2757 return $this->craftingGrid;
2758 }
2759
2765 return $this->creativeInventory;
2766 }
2767
2771 public function setCreativeInventory(CreativeInventory $inventory) : void{
2772 $this->creativeInventory = $inventory;
2773 if($this->spawned && $this->isConnected()){
2774 $this->getNetworkSession()->getInvManager()?->syncCreative();
2775 }
2776 }
2777
2782 private function doCloseInventory() : void{
2783 $windowsToClear = [];
2784 $mainInventoryWindow = null;
2785 foreach($this->permanentWindows as $window){
2786 if($window->getType() === PlayerInventoryWindow::TYPE_CRAFTING || $window->getType() === PlayerInventoryWindow::TYPE_CURSOR){
2787 $windowsToClear[] = $window;
2788 }elseif($window->getType() === PlayerInventoryWindow::TYPE_INVENTORY){
2789 $mainInventoryWindow = $window;
2790 }
2791 }
2792 if($mainInventoryWindow === null){
2793 //TODO: in the future this might not be the case, if we implement support for the player closing their
2794 //inventory window outside the protocol layer
2795 //in that case we'd have to create a new ephemeral window here
2796 throw new AssumptionFailedError("This should never be null");
2797 }
2798
2799 if($this->currentWindow instanceof TemporaryInventoryWindow){
2800 $windowsToClear[] = $this->currentWindow;
2801 }
2802
2803 $builder = new TransactionBuilder();
2804 foreach($windowsToClear as $window){
2805 $contents = $window->getInventory()->getContents();
2806
2807 if(count($contents) > 0){
2808 $drops = $builder->getActionBuilder($mainInventoryWindow)->addItem(...$contents);
2809 foreach($drops as $drop){
2810 $builder->addAction(new DropItemAction($drop));
2811 }
2812
2813 $builder->getActionBuilder($window)->clearAll();
2814 }
2815 }
2816
2817 $actions = $builder->generateActions();
2818 if(count($actions) !== 0){
2819 $transaction = new InventoryTransaction($this, $actions);
2820 try{
2821 $transaction->execute();
2822 $this->logger->debug("Successfully evacuated items from temporary inventories");
2823 }catch(TransactionCancelledException){
2824 $this->logger->debug("Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2825 foreach($windowsToClear as $window){
2826 $window->getInventory()->clearAll();
2827 }
2828 }catch(TransactionValidationException $e){
2829 throw new AssumptionFailedError("This server-generated transaction should never be invalid", 0, $e);
2830 }
2831 }
2832 }
2833
2837 public function getCurrentWindow() : ?InventoryWindow{
2838 return $this->currentWindow;
2839 }
2840
2844 public function setCurrentWindow(InventoryWindow $window) : bool{
2845 if($window === $this->currentWindow){
2846 return true;
2847 }
2848 if($window->getViewer() !== $this){
2849 throw new \InvalidArgumentException("Cannot reuse InventoryWindow instances, please create a new one for each player");
2850 }
2851 $ev = new InventoryOpenEvent($window, $this);
2852 $ev->call();
2853 if($ev->isCancelled()){
2854 return false;
2855 }
2856
2857 $this->removeCurrentWindow();
2858
2859 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) === null){
2860 throw new \InvalidArgumentException("Player cannot open inventories in this state");
2861 }
2862 $this->logger->debug("Opening inventory window " . get_class($window) . "#" . spl_object_id($window));
2863 $inventoryManager->onCurrentWindowChange($window);
2864 $window->onOpen();
2865 $this->currentWindow = $window;
2866 return true;
2867 }
2868
2869 public function removeCurrentWindow() : void{
2870 $this->doCloseInventory();
2871 if($this->currentWindow !== null){
2872 $currentWindow = $this->currentWindow;
2873 $this->logger->debug("Closing inventory window " . get_class($this->currentWindow) . "#" . spl_object_id($this->currentWindow));
2874 $this->currentWindow->onClose();
2875 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !== null){
2876 $inventoryManager->onCurrentWindowRemove();
2877 }
2878 $this->currentWindow = null;
2879 (new InventoryCloseEvent($currentWindow, $this))->call();
2880 }
2881 }
2882
2886 protected function addPermanentWindows(array $windows) : void{
2887 foreach($windows as $window){
2888 $window->onOpen();
2889 $this->permanentWindows[spl_object_id($window)] = $window;
2890 }
2891 }
2892
2893 protected function removePermanentWindows() : void{
2894 foreach($this->permanentWindows as $window){
2895 $window->onClose();
2896 }
2897 $this->permanentWindows = [];
2898 }
2899
2904 public function getPermanentWindows() : array{
2905 return $this->permanentWindows;
2906 }
2907
2911 public function openSignEditor(Vector3 $position, bool $frontFace = true) : void{
2912 $block = $this->getWorld()->getBlock($position);
2913 if($block instanceof BaseSign){
2914 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2915 $this->getNetworkSession()->onOpenSignEditor($position, $frontFace);
2916 }else{
2917 throw new \InvalidArgumentException("Block at this position is not a sign");
2918 }
2919 }
2920
2921 use ChunkListenerNoOpTrait {
2922 onChunkChanged as private;
2923 onChunkUnloaded as private;
2924 }
2925
2926 public function onChunkChanged(int $chunkX, int $chunkZ, Chunk $chunk) : void{
2927 $status = $this->usedChunks[$hash = World::chunkHash($chunkX, $chunkZ)] ?? null;
2928 if($status === UsedChunkStatus::SENT){
2929 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2930 $this->nextChunkOrderRun = 0;
2931 }
2932 }
2933
2934 public function onChunkUnloaded(int $chunkX, int $chunkZ, Chunk $chunk) : void{
2935 if($this->isUsingChunk($chunkX, $chunkZ)){
2936 $this->logger->debug("Detected forced unload of chunk " . $chunkX . " " . $chunkZ);
2937 $this->unloadChunk($chunkX, $chunkZ);
2938 }
2939 }
2940}
onInteract(Player $player, Vector3 $clickPos)
Definition Entity.php:1132
setString(string $name, string $value)
setInt(string $name, int $value)
setLong(string $name, int $value)
attackBlock(Vector3 $pos, Facing $face)
Definition Player.php:1883
setCreativeInventory(CreativeInventory $inventory)
Definition Player.php:2771
setCurrentWindow(InventoryWindow $window)
Definition Player.php:2844
hasItemCooldown(Item $item)
Definition Player.php:776
isUsingChunk(int $chunkX, int $chunkZ)
Definition Player.php:1058
setDeathPosition(?Vector3 $pos)
Definition Player.php:1109
setScreenLineHeight(?int $height)
Definition Player.php:600
setCanSaveWithChunk(bool $value)
Definition Player.php:2473
kick(Translatable|string $reason="", Translatable|string|null $quitMessage=null, Translatable|string|null $disconnectScreenMessage=null)
Definition Player.php:2342
openSignEditor(Vector3 $position, bool $frontFace=true)
Definition Player.php:2911
teleport(Vector3 $pos, ?float $yaw=null, ?float $pitch=null)
Definition Player.php:2711
applyPostDamageEffects(EntityDamageEvent $source)
Definition Player.php:2635
setAllowFlight(bool $value)
Definition Player.php:488
initHumanData(CompoundTag $nbt)
Definition Player.php:365
getItemCooldownExpiry(Item $item)
Definition Player.php:768
sendTitle(string $title, string $subtitle="", int $fadeIn=-1, int $stay=-1, int $fadeOut=-1)
Definition Player.php:2198
transfer(string $address, int $port=19132, Translatable|string|null $message=null)
Definition Player.php:2324
addPermanentWindows(array $windows)
Definition Player.php:2886
setFlightSpeedMultiplier(float $flightSpeedMultiplier)
Definition Player.php:553
changeSkin(Skin $skin, string $newSkinName, string $oldSkinName)
Definition Player.php:722
broadcastAnimation(Animation $animation, ?array $targets=null)
Definition Player.php:2686
sendMessage(Translatable|string $message)
Definition Player.php:2250
hasReceivedChunk(int $chunkX, int $chunkZ)
Definition Player.php:1080
static isValidUserName(?string $name)
Definition Player.php:212
attackEntity(Entity $entity)
Definition Player.php:1985
breakBlock(Vector3 $pos)
Definition Player.php:1934
onDeathUpdate(int $tickDiff)
Definition Player.php:2551
sendToastNotification(string $title, string $body)
Definition Player.php:2274
resetItemCooldown(Item $item, ?int $ticks=null)
Definition Player.php:784
setTitleDuration(int $fadeIn, int $stay, int $fadeOut)
Definition Player.php:2241
sendPosition(Vector3 $pos, ?float $yaw=null, ?float $pitch=null, int $mode=MovePlayerPacket::MODE_NORMAL)
Definition Player.php:2705
setSpawn(?Vector3 $pos)
Definition Player.php:1146
onChunkUnloaded as onChunkChanged(int $chunkX, int $chunkZ, Chunk $chunk)
Definition Player.php:2926
interactBlock(Vector3 $pos, Facing $face, Vector3 $clickOffset)
Definition Player.php:1960
sendData(?array $targets, ?array $data=null)
Definition Player.php:2678
isCreative(bool $literal=false)
Definition Player.php:1278
onChunkUnloaded(int $chunkX, int $chunkZ, Chunk $chunk)
Definition Player.php:2934
chat(string $message)
Definition Player.php:1609
sendActionBarMessage(string $message)
Definition Player.php:2216
sendPopup(string $message)
Definition Player.php:2263
isAdventure(bool $literal=false)
Definition Player.php:1288
canInteract(Vector3 $pos, float $maxDistance, float $maxDiff=M_SQRT3/2)
Definition Player.php:1593
broadcastSound(Sound $sound, ?array $targets=null)
Definition Player.php:2694
getUsedChunkStatus(int $chunkX, int $chunkZ)
Definition Player.php:1073
interactEntity(Entity $entity, Vector3 $clickPos)
Definition Player.php:2070
sendSkin(?array $targets=null)
Definition Player.php:741
isSurvival(bool $literal=false)
Definition Player.php:1268
disconnect(Translatable|string $reason, Translatable|string|null $quitMessage=null, Translatable|string|null $disconnectScreenMessage=null)
Definition Player.php:2375
handleMovement(Vector3 $newPos)
Definition Player.php:1381
setHasBlockCollision(bool $value)
Definition Player.php:513
setGamemode(GameMode $gm)
Definition Player.php:1239
sendSubTitle(string $subtitle)
Definition Player.php:2209