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