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