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