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