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