PocketMine-MP 5.25.3 git-463be36b72d4f519674ec472ca492773c197dbce
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 $newReplica->setDamage($newHeldItem->getDamage());
1645 }
1646 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1647
1648 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1649 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1650 $this->broadcastSound(new ItemBreakSound());
1651 }
1652 $this->inventory->setItemInHand($newHeldItem);
1653 $heldItemChanged = true;
1654 }
1655 }
1656
1657 if(!$heldItemChanged){
1658 $newHeldItem = $oldHeldItem;
1659 }
1660
1661 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1662 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1663 }
1664 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1665 //TODO: we can't generate a transaction for this since the items aren't coming from an inventory :(
1666 $ev = new PlayerDropItemEvent($this, $drop);
1667 if($this->isSpectator()){
1668 $ev->cancel();
1669 }
1670 $ev->call();
1671 if(!$ev->isCancelled()){
1672 $this->dropItem($drop);
1673 }
1674 }
1675 }
1676
1682 public function useHeldItem() : bool{
1683 $directionVector = $this->getDirectionVector();
1684 $item = $this->inventory->getItemInHand();
1685 $oldItem = clone $item;
1686
1687 $ev = new PlayerItemUseEvent($this, $item, $directionVector);
1688 if($this->hasItemCooldown($item) || $this->isSpectator()){
1689 $ev->cancel();
1690 }
1691
1692 $ev->call();
1693
1694 if($ev->isCancelled()){
1695 return false;
1696 }
1697
1698 $returnedItems = [];
1699 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1700 if($result === ItemUseResult::FAIL){
1701 return false;
1702 }
1703
1704 $this->resetItemCooldown($oldItem);
1705 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1706
1707 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1708
1709 return true;
1710 }
1711
1717 public function consumeHeldItem() : bool{
1718 $slot = $this->inventory->getItemInHand();
1719 if($slot instanceof ConsumableItem){
1720 $oldItem = clone $slot;
1721
1722 $ev = new PlayerItemConsumeEvent($this, $slot);
1723 if($this->hasItemCooldown($slot)){
1724 $ev->cancel();
1725 }
1726 $ev->call();
1727
1728 if($ev->isCancelled() || !$this->consumeObject($slot)){
1729 return false;
1730 }
1731
1732 $this->setUsingItem(false);
1733 $this->resetItemCooldown($oldItem);
1734
1735 $slot->pop();
1736 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1737
1738 return true;
1739 }
1740
1741 return false;
1742 }
1743
1749 public function releaseHeldItem() : bool{
1750 try{
1751 $item = $this->inventory->getItemInHand();
1752 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1753 return false;
1754 }
1755
1756 $oldItem = clone $item;
1757
1758 $returnedItems = [];
1759 $result = $item->onReleaseUsing($this, $returnedItems);
1760 if($result === ItemUseResult::SUCCESS){
1761 $this->resetItemCooldown($oldItem);
1762 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1763 return true;
1764 }
1765
1766 return false;
1767 }finally{
1768 $this->setUsingItem(false);
1769 }
1770 }
1771
1772 public function pickBlock(Vector3 $pos, bool $addTileNBT) : bool{
1773 $block = $this->getWorld()->getBlock($pos);
1774 if($block instanceof UnknownBlock){
1775 return true;
1776 }
1777
1778 $item = $block->getPickedItem($addTileNBT);
1779
1780 $ev = new PlayerBlockPickEvent($this, $block, $item);
1781 $existingSlot = $this->inventory->first($item);
1782 if($existingSlot === -1 && $this->hasFiniteResources()){
1783 $ev->cancel();
1784 }
1785 $ev->call();
1786
1787 if(!$ev->isCancelled()){
1788 $this->equipOrAddPickedItem($existingSlot, $item);
1789 }
1790
1791 return true;
1792 }
1793
1794 public function pickEntity(int $entityId) : bool{
1795 $entity = $this->getWorld()->getEntity($entityId);
1796 if($entity === null){
1797 return true;
1798 }
1799
1800 $item = $entity->getPickedItem();
1801 if($item === null){
1802 return true;
1803 }
1804
1805 $ev = new PlayerEntityPickEvent($this, $entity, $item);
1806 $existingSlot = $this->inventory->first($item);
1807 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1808 $ev->cancel();
1809 }
1810 $ev->call();
1811
1812 if(!$ev->isCancelled()){
1813 $this->equipOrAddPickedItem($existingSlot, $item);
1814 }
1815
1816 return true;
1817 }
1818
1819 private function equipOrAddPickedItem(int $existingSlot, Item $item) : void{
1820 if($existingSlot !== -1){
1821 if($existingSlot < $this->inventory->getHotbarSize()){
1822 $this->inventory->setHeldItemIndex($existingSlot);
1823 }else{
1824 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1825 }
1826 }else{
1827 $firstEmpty = $this->inventory->firstEmpty();
1828 if($firstEmpty === -1){ //full inventory
1829 $this->inventory->setItemInHand($item);
1830 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1831 $this->inventory->setItem($firstEmpty, $item);
1832 $this->inventory->setHeldItemIndex($firstEmpty);
1833 }else{
1834 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1835 $this->inventory->setItemInHand($item);
1836 }
1837 }
1838 }
1839
1845 public function attackBlock(Vector3 $pos, int $face) : bool{
1846 if($pos->distanceSquared($this->location) > 10000){
1847 return false; //TODO: maybe this should throw an exception instead?
1848 }
1849
1850 $target = $this->getWorld()->getBlock($pos);
1851
1852 $ev = new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target, null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1853 if($this->isSpectator()){
1854 $ev->cancel();
1855 }
1856 $ev->call();
1857 if($ev->isCancelled()){
1858 return false;
1859 }
1860 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1861 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1862 return true;
1863 }
1864
1865 $block = $target->getSide($face);
1866 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1867 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1868 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5), new FireExtinguishSound());
1869 return true;
1870 }
1871
1872 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1873 $this->blockBreakHandler = new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1874 }
1875
1876 return true;
1877 }
1878
1879 public function continueBreakBlock(Vector3 $pos, int $face) : void{
1880 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1881 $this->blockBreakHandler->setTargetedFace($face);
1882 }
1883 }
1884
1885 public function stopBreakBlock(Vector3 $pos) : void{
1886 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1887 $this->blockBreakHandler = null;
1888 }
1889 }
1890
1896 public function breakBlock(Vector3 $pos) : bool{
1897 $this->removeCurrentWindow();
1898
1899 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1900 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1901 $this->stopBreakBlock($pos);
1902 $item = $this->inventory->getItemInHand();
1903 $oldItem = clone $item;
1904 $returnedItems = [];
1905 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1906 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1907 $this->hungerManager->exhaust(0.005, PlayerExhaustEvent::CAUSE_MINING);
1908 return true;
1909 }
1910 }else{
1911 $this->logger->debug("Cancelled block break at $pos due to not currently being interactable");
1912 }
1913
1914 return false;
1915 }
1916
1922 public function interactBlock(Vector3 $pos, int $face, Vector3 $clickOffset) : bool{
1923 $this->setUsingItem(false);
1924
1925 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1926 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1927 $item = $this->inventory->getItemInHand(); //this is a copy of the real item
1928 $oldItem = clone $item;
1929 $returnedItems = [];
1930 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1931 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1932 return true;
1933 }
1934 }else{
1935 $this->logger->debug("Cancelled interaction of block at $pos due to not currently being interactable");
1936 }
1937
1938 return false;
1939 }
1940
1947 public function attackEntity(Entity $entity) : bool{
1948 if(!$entity->isAlive()){
1949 return false;
1950 }
1951 if($entity instanceof ItemEntity || $entity instanceof Arrow){
1952 $this->logger->debug("Attempted to attack non-attackable entity " . get_class($entity));
1953 return false;
1954 }
1955
1956 $heldItem = $this->inventory->getItemInHand();
1957 $oldItem = clone $heldItem;
1958
1959 $ev = new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1960 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1961 $this->logger->debug("Cancelled attack of entity " . $entity->getId() . " due to not currently being interactable");
1962 $ev->cancel();
1963 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1964 $ev->cancel();
1965 }
1966
1967 $meleeEnchantmentDamage = 0;
1969 $meleeEnchantments = [];
1970 foreach($heldItem->getEnchantments() as $enchantment){
1971 $type = $enchantment->getType();
1972 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1973 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1974 $meleeEnchantments[] = $enchantment;
1975 }
1976 }
1977 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1978
1979 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1980 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
1981 }
1982
1983 $entity->attack($ev);
1984 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1985
1986 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1987 if($ev->isCancelled()){
1988 $this->getWorld()->addSound($soundPos, new EntityAttackNoDamageSound());
1989 return false;
1990 }
1991 $this->getWorld()->addSound($soundPos, new EntityAttackSound());
1992
1993 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
1994 $entity->broadcastAnimation(new CriticalHitAnimation($entity));
1995 }
1996
1997 foreach($meleeEnchantments as $enchantment){
1998 $type = $enchantment->getType();
1999 assert($type instanceof MeleeWeaponEnchantment);
2000 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2001 }
2002
2003 if($this->isAlive()){
2004 //reactive damage like thorns might cause us to be killed by attacking another mob, which
2005 //would mean we'd already have dropped the inventory by the time we reached here
2006 $returnedItems = [];
2007 $heldItem->onAttackEntity($entity, $returnedItems);
2008 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2009
2010 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
2011 }
2012
2013 return true;
2014 }
2015
2020 public function missSwing() : void{
2021 $ev = new PlayerMissSwingEvent($this);
2022 $ev->call();
2023 if(!$ev->isCancelled()){
2024 $this->broadcastSound(new EntityAttackNoDamageSound());
2025 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2026 }
2027 }
2028
2032 public function interactEntity(Entity $entity, Vector3 $clickPos) : bool{
2033 $ev = new PlayerEntityInteractEvent($this, $entity, $clickPos);
2034
2035 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2036 $this->logger->debug("Cancelled interaction with entity " . $entity->getId() . " due to not currently being interactable");
2037 $ev->cancel();
2038 }
2039
2040 $ev->call();
2041
2042 $item = $this->inventory->getItemInHand();
2043 $oldItem = clone $item;
2044 if(!$ev->isCancelled()){
2045 if($item->onInteractEntity($this, $entity, $clickPos)){
2046 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
2047 if($item instanceof Durable && $item->isBroken()){
2048 $this->broadcastSound(new ItemBreakSound());
2049 }
2050 $this->inventory->setItemInHand($item);
2051 }
2052 }
2053 return $entity->onInteract($this, $clickPos);
2054 }
2055 return false;
2056 }
2057
2058 public function toggleSprint(bool $sprint) : bool{
2059 if($sprint === $this->sprinting){
2060 return true;
2061 }
2062 $ev = new PlayerToggleSprintEvent($this, $sprint);
2063 $ev->call();
2064 if($ev->isCancelled()){
2065 return false;
2066 }
2067 $this->setSprinting($sprint);
2068 return true;
2069 }
2070
2071 public function toggleSneak(bool $sneak) : bool{
2072 if($sneak === $this->sneaking){
2073 return true;
2074 }
2075 $ev = new PlayerToggleSneakEvent($this, $sneak);
2076 $ev->call();
2077 if($ev->isCancelled()){
2078 return false;
2079 }
2080 $this->setSneaking($sneak);
2081 return true;
2082 }
2083
2084 public function toggleFlight(bool $fly) : bool{
2085 if($fly === $this->flying){
2086 return true;
2087 }
2088 $ev = new PlayerToggleFlightEvent($this, $fly);
2089 if(!$this->allowFlight){
2090 $ev->cancel();
2091 }
2092 $ev->call();
2093 if($ev->isCancelled()){
2094 return false;
2095 }
2096 $this->setFlying($fly);
2097 return true;
2098 }
2099
2100 public function toggleGlide(bool $glide) : bool{
2101 if($glide === $this->gliding){
2102 return true;
2103 }
2104 $ev = new PlayerToggleGlideEvent($this, $glide);
2105 $ev->call();
2106 if($ev->isCancelled()){
2107 return false;
2108 }
2109 $this->setGliding($glide);
2110 return true;
2111 }
2112
2113 public function toggleSwim(bool $swim) : bool{
2114 if($swim === $this->swimming){
2115 return true;
2116 }
2117 $ev = new PlayerToggleSwimEvent($this, $swim);
2118 $ev->call();
2119 if($ev->isCancelled()){
2120 return false;
2121 }
2122 $this->setSwimming($swim);
2123 return true;
2124 }
2125
2126 public function emote(string $emoteId) : void{
2127 $currentTick = $this->server->getTick();
2128 if($currentTick - $this->lastEmoteTick > 5){
2129 $this->lastEmoteTick = $currentTick;
2130 $event = new PlayerEmoteEvent($this, $emoteId);
2131 $event->call();
2132 if(!$event->isCancelled()){
2133 $emoteId = $event->getEmoteId();
2134 parent::emote($emoteId);
2135 }
2136 }
2137 }
2138
2142 public function dropItem(Item $item) : void{
2143 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2144 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2145 }
2146
2154 public function sendTitle(string $title, string $subtitle = "", int $fadeIn = -1, int $stay = -1, int $fadeOut = -1) : void{
2155 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2156 if($subtitle !== ""){
2157 $this->sendSubTitle($subtitle);
2158 }
2159 $this->getNetworkSession()->onTitle($title);
2160 }
2161
2165 public function sendSubTitle(string $subtitle) : void{
2166 $this->getNetworkSession()->onSubTitle($subtitle);
2167 }
2168
2172 public function sendActionBarMessage(string $message) : void{
2173 $this->getNetworkSession()->onActionBar($message);
2174 }
2175
2179 public function removeTitles() : void{
2180 $this->getNetworkSession()->onClearTitle();
2181 }
2182
2186 public function resetTitles() : void{
2187 $this->getNetworkSession()->onResetTitleOptions();
2188 }
2189
2197 public function setTitleDuration(int $fadeIn, int $stay, int $fadeOut) : void{
2198 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2199 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2200 }
2201 }
2202
2206 public function sendMessage(Translatable|string $message) : void{
2207 $this->getNetworkSession()->onChatMessage($message);
2208 }
2209
2210 public function sendJukeboxPopup(Translatable|string $message) : void{
2211 $this->getNetworkSession()->onJukeboxPopup($message);
2212 }
2213
2219 public function sendPopup(string $message) : void{
2220 $this->getNetworkSession()->onPopup($message);
2221 }
2222
2223 public function sendTip(string $message) : void{
2224 $this->getNetworkSession()->onTip($message);
2225 }
2226
2230 public function sendToastNotification(string $title, string $body) : void{
2231 $this->getNetworkSession()->onToastNotification($title, $body);
2232 }
2233
2239 public function sendForm(Form $form) : void{
2240 $id = $this->formIdCounter++;
2241 if($this->getNetworkSession()->onFormSent($id, $form)){
2242 $this->forms[$id] = $form;
2243 }
2244 }
2245
2246 public function onFormSubmit(int $formId, mixed $responseData) : bool{
2247 if(!isset($this->forms[$formId])){
2248 $this->logger->debug("Got unexpected response for form $formId");
2249 return false;
2250 }
2251
2252 try{
2253 $this->forms[$formId]->handleResponse($this, $responseData);
2254 }catch(FormValidationException $e){
2255 $this->logger->critical("Failed to validate form " . get_class($this->forms[$formId]) . ": " . $e->getMessage());
2256 $this->logger->logException($e);
2257 }finally{
2258 unset($this->forms[$formId]);
2259 }
2260
2261 return true;
2262 }
2263
2267 public function closeAllForms() : void{
2268 $this->getNetworkSession()->onCloseAllForms();
2269 }
2270
2280 public function transfer(string $address, int $port = 19132, Translatable|string|null $message = null) : bool{
2281 $ev = new PlayerTransferEvent($this, $address, $port, $message ?? KnownTranslationFactory::pocketmine_disconnect_transfer());
2282 $ev->call();
2283 if(!$ev->isCancelled()){
2284 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2285 return true;
2286 }
2287
2288 return false;
2289 }
2290
2298 public function kick(Translatable|string $reason = "", Translatable|string|null $quitMessage = null, Translatable|string|null $disconnectScreenMessage = null) : bool{
2299 $ev = new PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2300 $ev->call();
2301 if(!$ev->isCancelled()){
2302 $reason = $ev->getDisconnectReason();
2303 if($reason === ""){
2304 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2305 }
2306 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2307 if($disconnectScreenMessage === ""){
2308 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2309 }
2310 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2311
2312 return true;
2313 }
2314
2315 return false;
2316 }
2317
2331 public function disconnect(Translatable|string $reason, Translatable|string|null $quitMessage = null, Translatable|string|null $disconnectScreenMessage = null) : void{
2332 if(!$this->isConnected()){
2333 return;
2334 }
2335
2336 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2337 $this->onPostDisconnect($reason, $quitMessage);
2338 }
2339
2347 public function onPostDisconnect(Translatable|string $reason, Translatable|string|null $quitMessage) : void{
2348 if($this->isConnected()){
2349 throw new \LogicException("Player is still connected");
2350 }
2351
2352 //prevent the player receiving their own disconnect message
2353 $this->server->unsubscribeFromAllBroadcastChannels($this);
2354
2355 $this->removeCurrentWindow();
2356
2357 $ev = new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2358 $ev->call();
2359 if(($quitMessage = $ev->getQuitMessage()) !== ""){
2360 $this->server->broadcastMessage($quitMessage);
2361 }
2362 $this->save();
2363
2364 $this->spawned = false;
2365
2366 $this->stopSleep();
2367 $this->blockBreakHandler = null;
2368 $this->despawnFromAll();
2369
2370 $this->server->removeOnlinePlayer($this);
2371
2372 foreach($this->server->getOnlinePlayers() as $player){
2373 if(!$player->canSee($this)){
2374 $player->showPlayer($this);
2375 }
2376 }
2377 $this->hiddenPlayers = [];
2378
2379 if($this->location->isValid()){
2380 foreach($this->usedChunks as $index => $status){
2381 World::getXZ($index, $chunkX, $chunkZ);
2382 $this->unloadChunk($chunkX, $chunkZ);
2383 }
2384 }
2385 if(count($this->usedChunks) !== 0){
2386 throw new AssumptionFailedError("Previous loop should have cleared this array");
2387 }
2388 $this->loadQueue = [];
2389
2390 $this->removeCurrentWindow();
2391 $this->removePermanentInventories();
2392
2393 $this->perm->getPermissionRecalculationCallbacks()->clear();
2394
2395 $this->flagForDespawn();
2396 }
2397
2398 protected function onDispose() : void{
2399 $this->disconnect("Player destroyed");
2400 $this->cursorInventory->removeAllViewers();
2401 $this->craftingGrid->removeAllViewers();
2402 parent::onDispose();
2403 }
2404
2405 protected function destroyCycles() : void{
2406 $this->networkSession = null;
2407 unset($this->cursorInventory);
2408 unset($this->craftingGrid);
2409 $this->spawnPosition = null;
2410 $this->deathPosition = null;
2411 $this->blockBreakHandler = null;
2412 parent::destroyCycles();
2413 }
2414
2418 public function __debugInfo() : array{
2419 return [];
2420 }
2421
2422 public function __destruct(){
2423 parent::__destruct();
2424 $this->logger->debug("Destroyed by garbage collector");
2425 }
2426
2427 public function canSaveWithChunk() : bool{
2428 return false;
2429 }
2430
2431 public function setCanSaveWithChunk(bool $value) : void{
2432 throw new \BadMethodCallException("Players can't be saved with chunks");
2433 }
2434
2435 public function getSaveData() : CompoundTag{
2436 $nbt = $this->saveNBT();
2437
2438 $nbt->setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2439
2440 if($this->location->isValid()){
2441 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2442 }
2443
2444 if($this->hasValidCustomSpawn()){
2445 $spawn = $this->getSpawn();
2446 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2447 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2448 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2449 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2450 }
2451
2452 if($this->deathPosition !== null && $this->deathPosition->isValid()){
2453 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2454 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2455 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2456 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2457 }
2458
2459 $nbt->setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2460 $nbt->setLong(self::TAG_FIRST_PLAYED, $this->firstPlayed);
2461 $nbt->setLong(self::TAG_LAST_PLAYED, (int) floor(microtime(true) * 1000));
2462
2463 return $nbt;
2464 }
2465
2469 public function save() : void{
2470 $this->server->saveOfflinePlayerData($this->username, $this->getSaveData());
2471 }
2472
2473 protected function onDeath() : void{
2474 //Crafting grid must always be evacuated even if keep-inventory is true. This dumps the contents into the
2475 //main inventory and drops the rest on the ground.
2476 $this->removeCurrentWindow();
2477
2478 $this->setDeathPosition($this->getPosition());
2479
2480 $ev = new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(), null);
2481 $ev->call();
2482
2483 if(!$ev->getKeepInventory()){
2484 foreach($ev->getDrops() as $item){
2485 $this->getWorld()->dropItem($this->location, $item);
2486 }
2487
2488 $clearInventory = fn(Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(Item $item) => $item->keepOnDeath()));
2489 $this->inventory->setHeldItemIndex(0);
2490 $clearInventory($this->inventory);
2491 $clearInventory($this->armorInventory);
2492 $clearInventory($this->offHandInventory);
2493 }
2494
2495 if(!$ev->getKeepXp()){
2496 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2497 $this->xpManager->setXpAndProgress(0, 0.0);
2498 }
2499
2500 if($ev->getDeathMessage() !== ""){
2501 $this->server->broadcastMessage($ev->getDeathMessage());
2502 }
2503
2504 $this->startDeathAnimation();
2505
2506 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2507 }
2508
2509 protected function onDeathUpdate(int $tickDiff) : bool{
2510 parent::onDeathUpdate($tickDiff);
2511 return false; //never flag players for despawn
2512 }
2513
2514 public function respawn() : void{
2515 if($this->server->isHardcore()){
2516 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){ //this allows plugins to prevent the ban by cancelling PlayerKickEvent
2517 $this->server->getNameBans()->addBan($this->getName(), "Died in hardcore mode");
2518 }
2519 return;
2520 }
2521
2522 $this->actuallyRespawn();
2523 }
2524
2525 protected function actuallyRespawn() : void{
2526 if($this->respawnLocked){
2527 return;
2528 }
2529 $this->respawnLocked = true;
2530
2531 $this->logger->debug("Waiting for safe respawn position to be located");
2532 $spawn = $this->getSpawn();
2533 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2534 function(Position $safeSpawn) : void{
2535 if(!$this->isConnected()){
2536 return;
2537 }
2538 $this->logger->debug("Respawn position located, completing respawn");
2539 $ev = new PlayerRespawnEvent($this, $safeSpawn);
2540 $ev->call();
2541
2542 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2543 $this->teleport($realSpawn);
2544
2545 $this->setSprinting(false);
2546 $this->setSneaking(false);
2547 $this->setFlying(false);
2548
2549 $this->extinguish();
2550 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2551 $this->deadTicks = 0;
2552 $this->noDamageTicks = 60;
2553
2554 $this->effectManager->clear();
2555 $this->setHealth($this->getMaxHealth());
2556
2557 foreach($this->attributeMap->getAll() as $attr){
2558 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){ //we have already reset both of those if needed when the player died
2559 continue;
2560 }
2561 $attr->resetToDefault();
2562 }
2563
2564 $this->spawnToAll();
2565 $this->scheduleUpdate();
2566
2567 $this->getNetworkSession()->onServerRespawn();
2568 $this->respawnLocked = false;
2569 },
2570 function() : void{
2571 if($this->isConnected()){
2572 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2573 }
2574 }
2575 );
2576 }
2577
2578 protected function applyPostDamageEffects(EntityDamageEvent $source) : void{
2579 parent::applyPostDamageEffects($source);
2580
2581 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2582 }
2583
2584 public function attack(EntityDamageEvent $source) : void{
2585 if(!$this->isAlive()){
2586 return;
2587 }
2588
2589 if($this->isCreative()
2590 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2591 ){
2592 $source->cancel();
2593 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2594 $source->cancel();
2595 }
2596
2597 parent::attack($source);
2598 }
2599
2600 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2601 parent::syncNetworkData($properties);
2602
2603 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2604 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2605
2606 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !== null);
2607 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !== null ? BlockPosition::fromVector3($this->sleeping) : new BlockPosition(0, 0, 0));
2608
2609 if($this->deathPosition !== null && $this->deathPosition->world === $this->location->world){
2610 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2611 //TODO: this should be updated when dimensions are implemented
2612 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2613 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2614 }else{
2615 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2616 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2617 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2618 }
2619 }
2620
2621 public function sendData(?array $targets, ?array $data = null) : void{
2622 if($targets === null){
2623 $targets = $this->getViewers();
2624 $targets[] = $this;
2625 }
2626 parent::sendData($targets, $data);
2627 }
2628
2629 public function broadcastAnimation(Animation $animation, ?array $targets = null) : void{
2630 if($this->spawned && $targets === null){
2631 $targets = $this->getViewers();
2632 $targets[] = $this;
2633 }
2634 parent::broadcastAnimation($animation, $targets);
2635 }
2636
2637 public function broadcastSound(Sound $sound, ?array $targets = null) : void{
2638 if($this->spawned && $targets === null){
2639 $targets = $this->getViewers();
2640 $targets[] = $this;
2641 }
2642 parent::broadcastSound($sound, $targets);
2643 }
2644
2648 protected function sendPosition(Vector3 $pos, ?float $yaw = null, ?float $pitch = null, int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2649 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2650
2651 $this->ySize = 0;
2652 }
2653
2654 public function teleport(Vector3 $pos, ?float $yaw = null, ?float $pitch = null) : bool{
2655 if(parent::teleport($pos, $yaw, $pitch)){
2656
2657 $this->removeCurrentWindow();
2658 $this->stopSleep();
2659
2660 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2661 $this->broadcastMovement(true);
2662
2663 $this->spawnToAll();
2664
2665 $this->resetFallDistance();
2666 $this->nextChunkOrderRun = 0;
2667 if($this->spawnChunkLoadCount !== -1){
2668 $this->spawnChunkLoadCount = 0;
2669 }
2670 $this->blockBreakHandler = null;
2671
2672 //TODO: workaround for player last pos not getting updated
2673 //Entity::updateMovement() normally handles this, but it's overridden with an empty function in Player
2674 $this->resetLastMovements();
2675
2676 return true;
2677 }
2678
2679 return false;
2680 }
2681
2682 protected function addDefaultWindows() : void{
2683 $this->cursorInventory = new PlayerCursorInventory($this);
2684 $this->craftingGrid = new PlayerCraftingInventory($this);
2685
2686 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2687
2688 //TODO: more windows
2689 }
2690
2691 public function getCursorInventory() : PlayerCursorInventory{
2692 return $this->cursorInventory;
2693 }
2694
2695 public function getCraftingGrid() : CraftingGrid{
2696 return $this->craftingGrid;
2697 }
2698
2704 return $this->creativeInventory;
2705 }
2706
2710 public function setCreativeInventory(CreativeInventory $inventory) : void{
2711 $this->creativeInventory = $inventory;
2712 if($this->spawned && $this->isConnected()){
2713 $this->getNetworkSession()->getInvManager()?->syncCreative();
2714 }
2715 }
2716
2721 private function doCloseInventory() : void{
2722 $inventories = [$this->craftingGrid, $this->cursorInventory];
2723 if($this->currentWindow instanceof TemporaryInventory){
2724 $inventories[] = $this->currentWindow;
2725 }
2726
2727 $builder = new TransactionBuilder();
2728 foreach($inventories as $inventory){
2729 $contents = $inventory->getContents();
2730
2731 if(count($contents) > 0){
2732 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2733 foreach($drops as $drop){
2734 $builder->addAction(new DropItemAction($drop));
2735 }
2736
2737 $builder->getInventory($inventory)->clearAll();
2738 }
2739 }
2740
2741 $actions = $builder->generateActions();
2742 if(count($actions) !== 0){
2743 $transaction = new InventoryTransaction($this, $actions);
2744 try{
2745 $transaction->execute();
2746 $this->logger->debug("Successfully evacuated items from temporary inventories");
2747 }catch(TransactionCancelledException){
2748 $this->logger->debug("Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2749 foreach($inventories as $inventory){
2750 $inventory->clearAll();
2751 }
2752 }catch(TransactionValidationException $e){
2753 throw new AssumptionFailedError("This server-generated transaction should never be invalid", 0, $e);
2754 }
2755 }
2756 }
2757
2761 public function getCurrentWindow() : ?Inventory{
2762 return $this->currentWindow;
2763 }
2764
2768 public function setCurrentWindow(Inventory $inventory) : bool{
2769 if($inventory === $this->currentWindow){
2770 return true;
2771 }
2772 $ev = new InventoryOpenEvent($inventory, $this);
2773 $ev->call();
2774 if($ev->isCancelled()){
2775 return false;
2776 }
2777
2778 $this->removeCurrentWindow();
2779
2780 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) === null){
2781 throw new \InvalidArgumentException("Player cannot open inventories in this state");
2782 }
2783 $this->logger->debug("Opening inventory " . get_class($inventory) . "#" . spl_object_id($inventory));
2784 $inventoryManager->onCurrentWindowChange($inventory);
2785 $inventory->onOpen($this);
2786 $this->currentWindow = $inventory;
2787 return true;
2788 }
2789
2790 public function removeCurrentWindow() : void{
2791 $this->doCloseInventory();
2792 if($this->currentWindow !== null){
2793 $currentWindow = $this->currentWindow;
2794 $this->logger->debug("Closing inventory " . get_class($this->currentWindow) . "#" . spl_object_id($this->currentWindow));
2795 $this->currentWindow->onClose($this);
2796 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !== null){
2797 $inventoryManager->onCurrentWindowRemove();
2798 }
2799 $this->currentWindow = null;
2800 (new InventoryCloseEvent($currentWindow, $this))->call();
2801 }
2802 }
2803
2804 protected function addPermanentInventories(Inventory ...$inventories) : void{
2805 foreach($inventories as $inventory){
2806 $inventory->onOpen($this);
2807 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2808 }
2809 }
2810
2811 protected function removePermanentInventories() : void{
2812 foreach($this->permanentWindows as $inventory){
2813 $inventory->onClose($this);
2814 }
2815 $this->permanentWindows = [];
2816 }
2817
2822 public function openSignEditor(Vector3 $position) : void{
2823 $block = $this->getWorld()->getBlock($position);
2824 if($block instanceof BaseSign){
2825 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2826 $this->getNetworkSession()->onOpenSignEditor($position, true);
2827 }else{
2828 throw new \InvalidArgumentException("Block at this position is not a sign");
2829 }
2830 }
2831
2832 use ChunkListenerNoOpTrait {
2833 onChunkChanged as private;
2834 onChunkUnloaded as private;
2835 }
2836
2837 public function onChunkChanged(int $chunkX, int $chunkZ, Chunk $chunk) : void{
2838 $status = $this->usedChunks[$hash = World::chunkHash($chunkX, $chunkZ)] ?? null;
2839 if($status === UsedChunkStatus::SENT){
2840 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2841 $this->nextChunkOrderRun = 0;
2842 }
2843 }
2844
2845 public function onChunkUnloaded(int $chunkX, int $chunkZ, Chunk $chunk) : void{
2846 if($this->isUsingChunk($chunkX, $chunkZ)){
2847 $this->logger->debug("Detected forced unload of chunk " . $chunkX . " " . $chunkZ);
2848 $this->unloadChunk($chunkX, $chunkZ);
2849 }
2850 }
2851}
onInteract(Player $player, Vector3 $clickPos)
Definition Entity.php:1119
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:1922
setCreativeInventory(CreativeInventory $inventory)
Definition Player.php:2710
hasItemCooldown(Item $item)
Definition Player.php:759
attackBlock(Vector3 $pos, int $face)
Definition Player.php:1845
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:2431
kick(Translatable|string $reason="", Translatable|string|null $quitMessage=null, Translatable|string|null $disconnectScreenMessage=null)
Definition Player.php:2298
teleport(Vector3 $pos, ?float $yaw=null, ?float $pitch=null)
Definition Player.php:2654
applyPostDamageEffects(EntityDamageEvent $source)
Definition Player.php:2578
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:2154
transfer(string $address, int $port=19132, Translatable|string|null $message=null)
Definition Player.php:2280
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:2629
sendMessage(Translatable|string $message)
Definition Player.php:2206
hasReceivedChunk(int $chunkX, int $chunkZ)
Definition Player.php:1063
static isValidUserName(?string $name)
Definition Player.php:206
openSignEditor(Vector3 $position)
Definition Player.php:2822
attackEntity(Entity $entity)
Definition Player.php:1947
breakBlock(Vector3 $pos)
Definition Player.php:1896
onDeathUpdate(int $tickDiff)
Definition Player.php:2509
sendToastNotification(string $title, string $body)
Definition Player.php:2230
resetItemCooldown(Item $item, ?int $ticks=null)
Definition Player.php:767
setTitleDuration(int $fadeIn, int $stay, int $fadeOut)
Definition Player.php:2197
sendPosition(Vector3 $pos, ?float $yaw=null, ?float $pitch=null, int $mode=MovePlayerPacket::MODE_NORMAL)
Definition Player.php:2648
setSpawn(?Vector3 $pos)
Definition Player.php:1129
onChunkUnloaded as onChunkChanged(int $chunkX, int $chunkZ, Chunk $chunk)
Definition Player.php:2837
setCurrentWindow(Inventory $inventory)
Definition Player.php:2768
sendData(?array $targets, ?array $data=null)
Definition Player.php:2621
isCreative(bool $literal=false)
Definition Player.php:1261
onChunkUnloaded(int $chunkX, int $chunkZ, Chunk $chunk)
Definition Player.php:2845
chat(string $message)
Definition Player.php:1574
sendActionBarMessage(string $message)
Definition Player.php:2172
sendPopup(string $message)
Definition Player.php:2219
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:2637
getUsedChunkStatus(int $chunkX, int $chunkZ)
Definition Player.php:1056
interactEntity(Entity $entity, Vector3 $clickPos)
Definition Player.php:2032
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:2331
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:2165