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