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