171 use PermissibleDelegateTrait;
173 private const MOVES_PER_TICK = 2;
174 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
177 private const MAX_CHAT_CHAR_LENGTH = 512;
183 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
184 private const MAX_REACH_DISTANCE_CREATIVE = 13;
185 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
186 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
188 public const TAG_FIRST_PLAYED =
"firstPlayed";
189 public const TAG_LAST_PLAYED =
"lastPlayed";
190 private const TAG_GAME_MODE =
"playerGameType";
191 private const TAG_SPAWN_WORLD =
"SpawnLevel";
192 private const TAG_SPAWN_X =
"SpawnX";
193 private const TAG_SPAWN_Y =
"SpawnY";
194 private const TAG_SPAWN_Z =
"SpawnZ";
195 private const TAG_DEATH_WORLD =
"DeathLevel";
196 private const TAG_DEATH_X =
"DeathPositionX";
197 private const TAG_DEATH_Y =
"DeathPositionY";
198 private const TAG_DEATH_Z =
"DeathPositionZ";
199 public const TAG_LEVEL =
"Level";
200 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
210 $lname = strtolower($name);
211 $len = strlen($name);
212 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
217 public bool $spawned =
false;
219 protected string $username;
220 protected string $displayName;
221 protected string $xuid =
"";
222 protected bool $authenticated;
225 protected ?Inventory $currentWindow =
null;
227 protected array $permanentWindows = [];
228 protected PlayerCursorInventory $cursorInventory;
229 protected PlayerCraftingInventory $craftingGrid;
230 protected CreativeInventory $creativeInventory;
232 protected int $messageCounter = 2;
234 protected int $firstPlayed;
235 protected int $lastPlayed;
236 protected GameMode $gamemode;
242 protected array $usedChunks = [];
247 private array $activeChunkGenerationRequests = [];
252 protected array $loadQueue = [];
253 protected int $nextChunkOrderRun = 5;
256 private array $tickingChunks = [];
258 protected int $viewDistance = -1;
259 protected int $spawnThreshold;
260 protected int $spawnChunkLoadCount = 0;
261 protected int $chunksPerTick;
262 protected ChunkSelector $chunkSelector;
263 protected ChunkLoader $chunkLoader;
264 protected ChunkTicker $chunkTicker;
267 protected array $hiddenPlayers = [];
269 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
270 protected ?
float $lastMovementProcess =
null;
272 protected int $inAirTicks = 0;
274 protected float $stepHeight = 0.6;
276 protected ?Vector3 $sleeping =
null;
277 private ?
Position $spawnPosition =
null;
279 private bool $respawnLocked =
false;
281 private ?
Position $deathPosition =
null;
284 protected bool $autoJump =
true;
285 protected bool $allowFlight =
false;
286 protected bool $blockCollision =
true;
287 protected bool $flying =
false;
290 protected ?
int $lineHeight =
null;
291 protected string $locale =
"en_US";
293 protected int $startAction = -1;
299 protected array $usedItemsCooldown = [];
301 private int $lastEmoteTick = 0;
303 protected int $formIdCounter = 0;
305 protected array $forms = [];
307 protected \Logger $logger;
312 $username = TextFormat::clean($playerInfo->getUsername());
313 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
316 $this->networkSession = $session;
317 $this->playerInfo = $playerInfo;
318 $this->authenticated = $authenticated;
320 $this->username = $username;
321 $this->displayName = $this->username;
322 $this->locale = $this->playerInfo->getLocale();
324 $this->uuid = $this->playerInfo->getUuid();
325 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
327 $this->creativeInventory = CreativeInventory::getInstance();
329 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
330 if($this->
server->isOp($this->username)){
331 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
334 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
335 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
338 $this->chunkLoader =
new class implements
ChunkLoader{};
340 $world = $spawnLocation->
getWorld();
342 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
343 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
344 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
345 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
346 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
348 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
352 $this->setNameTag($this->username);
355 private function callDummyItemHeldEvent() : void{
356 $slot = $this->inventory->getHeldItemIndex();
365 protected function initEntity(
CompoundTag $nbt) : void{
366 parent::initEntity($nbt);
367 $this->addDefaultWindows();
369 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
370 function(Inventory $unused,
int $slot) :
void{
371 if($slot === $this->inventory->getHeldItemIndex()){
372 $this->setUsingItem(
false);
374 $this->callDummyItemHeldEvent();
378 $this->setUsingItem(
false);
379 $this->callDummyItemHeldEvent();
383 $this->firstPlayed = $nbt->getLong(self::TAG_FIRST_PLAYED, $now = (
int) (microtime(
true) * 1000));
384 $this->lastPlayed = $nbt->getLong(self::TAG_LAST_PLAYED, $now);
386 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
387 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
389 $this->internalSetGameMode($this->
server->getGamemode());
392 $this->keepMovement =
true;
394 $this->setNameTagVisible();
395 $this->setNameTagAlwaysVisible();
396 $this->setCanClimb();
398 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
399 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
401 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
402 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
406 public function getLeaveMessage() : Translatable|string{
408 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
414 public function isAuthenticated() : bool{
415 return $this->authenticated;
440 return parent::getUniqueId();
447 return $this->firstPlayed;
454 return $this->lastPlayed;
457 public function hasPlayedBefore() : bool{
458 return $this->lastPlayed - $this->firstPlayed > 1;
471 if($this->allowFlight !== $value){
472 $this->allowFlight = $value;
473 $this->getNetworkSession()->syncAbilities($this);
484 return $this->allowFlight;
496 if($this->blockCollision !== $value){
497 $this->blockCollision = $value;
498 $this->getNetworkSession()->syncAbilities($this);
507 return $this->blockCollision;
510 public function setFlying(
bool $value) : void{
511 if($this->flying !== $value){
512 $this->flying = $value;
513 $this->resetFallDistance();
514 $this->getNetworkSession()->syncAbilities($this);
518 public function isFlying() : bool{
519 return $this->flying;
522 public function setAutoJump(
bool $value) : void{
523 if($this->autoJump !== $value){
524 $this->autoJump = $value;
525 $this->getNetworkSession()->syncAdventureSettings();
529 public function hasAutoJump() : bool{
530 return $this->autoJump;
533 public function spawnTo(Player $player) : void{
534 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
535 parent::spawnTo($player);
539 public function getServer() : Server{
544 return $this->lineHeight ?? 7;
548 if($height !== null && $height < 1){
549 throw new \InvalidArgumentException(
"Line height must be at least 1");
551 $this->lineHeight = $height;
554 public function canSee(
Player $player) : bool{
555 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
558 public function hidePlayer(Player $player) : void{
559 if($player === $this){
562 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
563 $player->despawnFrom($this);
566 public function showPlayer(Player $player) : void{
567 if($player === $this){
570 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
571 if($player->isOnline()){
572 $player->spawnTo($this);
576 public function canCollideWith(Entity $entity) : bool{
580 public function canBeCollidedWith() : bool{
581 return !$this->isSpectator() && parent::canBeCollidedWith();
584 public function resetFallDistance() : void{
585 parent::resetFallDistance();
586 $this->inAirTicks = 0;
589 public function getViewDistance() : int{
590 return $this->viewDistance;
593 public function setViewDistance(
int $distance) : void{
594 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
596 if($newViewDistance !== $this->viewDistance){
597 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
601 $this->viewDistance = $newViewDistance;
603 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
605 $this->nextChunkOrderRun = 0;
607 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
609 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
612 public function isOnline() : bool{
613 return $this->isConnected();
616 public function isConnected() : bool{
617 return $this->networkSession !== null && $this->networkSession->isConnected();
620 public function getNetworkSession() : NetworkSession{
621 if($this->networkSession === null){
622 throw new \LogicException(
"Player is not connected");
624 return $this->networkSession;
631 return $this->username;
638 return $this->displayName;
641 public function setDisplayName(
string $name) : void{
645 $this->displayName = $ev->getNewName();
656 return $this->locale;
659 public function getLanguage() :
Language{
660 return $this->
server->getLanguage();
667 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
671 if($ev->isCancelled()){
672 $this->sendSkin([$this]);
676 $this->setSkin($ev->getNewSkin());
677 $this->sendSkin($this->server->getOnlinePlayers());
686 public function sendSkin(?array $targets =
null) : void{
687 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
694 return $this->startAction > -1;
697 public function setUsingItem(
bool $value) : void{
698 $this->startAction = $value ? $this->
server->getTick() : -1;
699 $this->networkPropertiesDirty =
true;
707 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
714 $this->checkItemCooldowns();
715 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
722 $this->checkItemCooldowns();
723 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
730 $ticks = $ticks ?? $item->getCooldownTicks();
732 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
733 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
737 protected function checkItemCooldowns() : void{
738 $serverTick = $this->
server->getTick();
739 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
740 if($cooldownUntil <= $serverTick){
741 unset($this->usedItemsCooldown[$itemId]);
746 protected function setPosition(Vector3 $pos) : bool{
747 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
748 if(parent::setPosition($pos)){
749 $newWorld = $this->getWorld();
750 if($oldWorld !== $newWorld){
751 if($oldWorld !==
null){
752 foreach($this->usedChunks as $index => $status){
753 World::getXZ($index, $X, $Z);
754 $this->unloadChunk($X, $Z, $oldWorld);
758 $this->usedChunks = [];
759 $this->loadQueue = [];
760 $this->getNetworkSession()->onEnterWorld();
769 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
770 $world = $world ?? $this->getWorld();
771 $index = World::chunkHash($x, $z);
772 if(isset($this->usedChunks[$index])){
773 foreach($world->getChunkEntities($x, $z) as $entity){
774 if($entity !== $this){
775 $entity->despawnFrom($this);
778 $this->getNetworkSession()->stopUsingChunk($x, $z);
779 unset($this->usedChunks[$index]);
780 unset($this->activeChunkGenerationRequests[$index]);
782 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
783 $world->unregisterChunkListener($this, $x, $z);
784 unset($this->loadQueue[$index]);
785 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
786 unset($this->tickingChunks[$index]);
789 protected function spawnEntitiesOnAllChunks() : void{
790 foreach($this->usedChunks as $chunkHash => $status){
791 if($status === UsedChunkStatus::SENT){
792 World::getXZ($chunkHash, $chunkX, $chunkZ);
793 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
798 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
799 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
800 if($entity !== $this && !$entity->isFlaggedForDespawn()){
801 $entity->spawnTo($this);
811 if(!$this->isConnected()){
815 Timings::$playerChunkSend->startTiming();
818 $world = $this->getWorld();
820 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
821 foreach($this->loadQueue as $index => $distance){
822 if($count >= $limit){
828 World::getXZ($index, $X, $Z);
829 assert(is_int($X) && is_int($Z));
833 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
834 $this->activeChunkGenerationRequests[$index] =
true;
835 unset($this->loadQueue[$index]);
836 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
837 $world->registerChunkListener($this, $X, $Z);
838 if(isset($this->tickingChunks[$index])){
839 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
842 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
843 function() use ($X, $Z, $index, $world) :
void{
844 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
847 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
853 unset($this->activeChunkGenerationRequests[$index]);
854 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
856 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
857 $this->usedChunks[$index] = UsedChunkStatus::SENT;
858 if($this->spawnChunkLoadCount === -1){
859 $this->spawnEntitiesOnChunk($X, $Z);
860 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
861 $this->spawnChunkLoadCount = -1;
863 $this->spawnEntitiesOnAllChunks();
865 $this->getNetworkSession()->notifyTerrainReady();
867 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
870 static function() :
void{
876 Timings::$playerChunkSend->stopTiming();
879 private function recheckBroadcastPermissions() : void{
881 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
882 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
883 ] as $permission => $channel){
884 if($this->hasPermission($permission)){
885 $this->
server->subscribeToBroadcastChannel($channel, $this);
887 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
900 $this->spawned =
true;
901 $this->recheckBroadcastPermissions();
902 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
903 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
904 $this->recheckBroadcastPermissions();
908 $ev =
new PlayerJoinEvent($this,
909 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
912 if($ev->getJoinMessage() !==
""){
913 $this->server->broadcastMessage($ev->getJoinMessage());
916 $this->noDamageTicks = 60;
920 if($this->getHealth() <= 0){
921 $this->logger->debug(
"Quit while dead, forcing respawn");
922 $this->actuallyRespawn();
933 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
934 $world = $this->getWorld();
935 foreach($oldTickingChunks as $hash => $_){
936 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
938 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
939 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
942 foreach($newTickingChunks as $hash => $_){
943 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
945 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
946 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
956 if(!$this->isConnected() || $this->viewDistance === -1){
960 Timings::$playerChunkOrder->startTiming();
964 $unloadChunks = $this->usedChunks;
966 $world = $this->getWorld();
967 $tickingChunkRadius = $world->getChunkTickRadius();
969 foreach($this->chunkSelector->selectChunks(
970 $this->server->getAllowedViewDistance($this->viewDistance),
971 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
972 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
973 ) as $radius => $hash){
974 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
975 $newOrder[$hash] =
true;
977 if($radius < $tickingChunkRadius){
978 $tickingChunks[$hash] =
true;
980 unset($unloadChunks[$hash]);
983 foreach($unloadChunks as $index => $status){
984 World::getXZ($index, $X, $Z);
985 $this->unloadChunk($X, $Z);
988 $this->loadQueue = $newOrder;
990 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
991 $this->tickingChunks = $tickingChunks;
993 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
994 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
997 Timings::$playerChunkOrder->stopTiming();
1005 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1013 return $this->usedChunks;
1020 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1027 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1028 return $status === UsedChunkStatus::SENT;
1035 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1036 $this->nextChunkOrderRun = PHP_INT_MAX;
1037 $this->orderChunks();
1040 if(count($this->loadQueue) > 0){
1041 $this->requestChunks();
1045 public function getDeathPosition() : ?Position{
1046 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1047 $this->deathPosition =
null;
1049 return $this->deathPosition;
1057 if($pos instanceof
Position && $pos->world !==
null){
1058 $world = $pos->world;
1060 $world = $this->getWorld();
1062 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1064 $this->deathPosition =
null;
1066 $this->networkPropertiesDirty =
true;
1073 if($this->hasValidCustomSpawn()){
1074 return $this->spawnPosition;
1076 $world = $this->
server->getWorldManager()->getDefaultWorld();
1078 return $world->getSpawnLocation();
1082 public function hasValidCustomSpawn() : bool{
1083 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1095 $world = $this->getWorld();
1097 $world = $pos->getWorld();
1099 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1101 $this->spawnPosition =
null;
1103 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1106 public function isSleeping() : bool{
1107 return $this->sleeping !== null;
1110 public function sleepOn(Vector3 $pos) : bool{
1111 $pos = $pos->floor();
1112 $b = $this->getWorld()->getBlock($pos);
1114 $ev =
new PlayerBedEnterEvent($this, $b);
1116 if($ev->isCancelled()){
1120 if($b instanceof Bed){
1122 $this->getWorld()->setBlock($pos, $b);
1125 $this->sleeping = $pos;
1126 $this->networkPropertiesDirty =
true;
1128 $this->setSpawn($pos);
1130 $this->getWorld()->setSleepTicks(60);
1135 public function stopSleep() : void{
1136 if($this->sleeping instanceof Vector3){
1137 $b = $this->getWorld()->getBlock($this->sleeping);
1138 if($b instanceof Bed){
1139 $b->setOccupied(
false);
1140 $this->getWorld()->setBlock($this->sleeping, $b);
1142 (
new PlayerBedLeaveEvent($this, $b))->call();
1144 $this->sleeping =
null;
1145 $this->networkPropertiesDirty =
true;
1147 $this->getWorld()->setSleepTicks(0);
1149 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1153 public function getGamemode() : GameMode{
1154 return $this->gamemode;
1157 protected function internalSetGameMode(GameMode $gameMode) : void{
1158 $this->gamemode = $gameMode;
1160 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1161 $this->hungerManager->setEnabled($this->isSurvival());
1163 if($this->isSpectator()){
1164 $this->setFlying(
true);
1165 $this->setHasBlockCollision(
false);
1167 $this->onGround =
false;
1171 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1173 if($this->isSurvival()){
1174 $this->setFlying(
false);
1176 $this->setHasBlockCollision(
true);
1177 $this->setSilent(
false);
1178 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1186 if($this->gamemode === $gm){
1192 if($ev->isCancelled()){
1196 $this->internalSetGameMode($gm);
1198 if($this->isSpectator()){
1199 $this->despawnFromAll();
1201 $this->spawnToAll();
1204 $this->getNetworkSession()->syncGameMode($this->gamemode);
1215 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1225 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1235 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1238 public function isSpectator() : bool{
1239 return $this->gamemode === GameMode::SPECTATOR;
1246 return $this->gamemode !== GameMode::CREATIVE;
1250 if($this->hasFiniteResources()){
1251 return parent::getDrops();
1258 if($this->hasFiniteResources()){
1259 return parent::getXpDropAmount();
1265 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1266 if($this->gamemode === GameMode::SPECTATOR){
1267 $this->onGround =
false;
1269 $bb = clone $this->boundingBox;
1270 $bb->minY = $this->location->y - 0.2;
1271 $bb->maxY = $this->location->y + 0.2;
1275 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1277 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1285 protected function checkNearEntities() : void{
1286 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1287 $entity->scheduleUpdate();
1289 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1293 $entity->onCollideWithPlayer($this);
1297 public function getInAirTicks() : int{
1298 return $this->inAirTicks;
1310 Timings::$playerMove->startTiming();
1312 $this->actuallyHandleMovement($newPos);
1314 Timings::$playerMove->stopTiming();
1318 private function actuallyHandleMovement(Vector3 $newPos) : void{
1319 $this->moveRateLimit--;
1320 if($this->moveRateLimit < 0){
1324 $oldPos = $this->location;
1325 $distanceSquared = $newPos->distanceSquared($oldPos);
1329 if($distanceSquared > 225){
1341 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1342 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1344 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1346 $this->nextChunkOrderRun = 0;
1349 if(!$revert && $distanceSquared != 0){
1350 $dx = $newPos->x - $oldPos->x;
1351 $dy = $newPos->y - $oldPos->y;
1352 $dz = $newPos->z - $oldPos->z;
1354 $this->move($dx, $dy, $dz);
1358 $this->revertMovement($oldPos);
1366 $now = microtime(true);
1367 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1368 $exceededRateLimit = $this->moveRateLimit < 0;
1369 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1370 $this->lastMovementProcess = $now;
1372 $from = clone $this->lastLocation;
1373 $to = clone $this->location;
1375 $delta = $to->distanceSquared($from);
1376 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1378 if($delta > 0.0001 || $deltaAngle > 1.0){
1379 if(PlayerMoveEvent::hasHandlers()){
1384 if($ev->isCancelled()){
1385 $this->revertMovement($from);
1389 if($to->distanceSquared($ev->getTo()) > 0.01){
1390 $this->teleport($ev->getTo());
1395 $this->lastLocation = $to;
1396 $this->broadcastMovement();
1398 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1399 if($horizontalDistanceTravelled > 0){
1401 if($this->isSprinting()){
1402 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, PlayerExhaustEvent::CAUSE_SPRINTING);
1404 $this->hungerManager->exhaust(0.0, PlayerExhaustEvent::CAUSE_WALKING);
1407 if($this->nextChunkOrderRun > 20){
1408 $this->nextChunkOrderRun = 20;
1413 if($exceededRateLimit){
1414 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1415 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1419 protected function revertMovement(Location $from) : void{
1420 $this->setPosition($from);
1421 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1424 protected function calculateFallDamage(
float $fallDistance) : float{
1425 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1433 public function setMotion(
Vector3 $motion) : bool{
1434 if(parent::setMotion($motion)){
1435 $this->broadcastMotion();
1436 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1443 protected function updateMovement(
bool $teleport =
false) : void{
1447 protected function tryChangeMovement() : void{
1451 public function onUpdate(int $currentTick) : bool{
1452 $tickDiff = $currentTick - $this->lastUpdate;
1458 $this->messageCounter = 2;
1460 $this->lastUpdate = $currentTick;
1462 if($this->justCreated){
1463 $this->onFirstUpdate($currentTick);
1466 if(!$this->isAlive() && $this->spawned){
1467 $this->onDeathUpdate($tickDiff);
1471 $this->timings->startTiming();
1474 Timings::$playerMove->startTiming();
1475 $this->processMostRecentMovements();
1476 $this->motion = Vector3::zero();
1477 if($this->onGround){
1478 $this->inAirTicks = 0;
1480 $this->inAirTicks += $tickDiff;
1482 Timings::$playerMove->stopTiming();
1484 Timings::$entityBaseTick->startTiming();
1485 $this->entityBaseTick($tickDiff);
1486 Timings::$entityBaseTick->stopTiming();
1488 if($this->isCreative() && $this->fireTicks > 1){
1489 $this->fireTicks = 1;
1492 if(!$this->isSpectator() && $this->isAlive()){
1493 Timings::$playerCheckNearEntities->startTiming();
1494 $this->checkNearEntities();
1495 Timings::$playerCheckNearEntities->stopTiming();
1498 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1499 $this->blockBreakHandler =
null;
1503 $this->timings->stopTiming();
1509 return $this->isCreative() || parent::canEat();
1513 return $this->isCreative() || parent::canBreathe();
1522 $eyePos = $this->getEyePos();
1523 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1527 $dV = $this->getDirectionVector();
1528 $eyeDot = $dV->dot($eyePos);
1529 $targetDot = $dV->dot($pos);
1530 return ($targetDot - $eyeDot) >= -$maxDiff;
1537 public function chat(
string $message) : bool{
1538 $this->removeCurrentWindow();
1540 if($this->messageCounter <= 0){
1546 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1547 if(strlen($message) > $maxTotalLength){
1551 $message = TextFormat::clean($message,
false);
1552 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1553 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1554 if(str_starts_with($messagePart,
'./')){
1555 $messagePart = substr($messagePart, 1);
1558 if(str_starts_with($messagePart,
"/")){
1559 Timings::$playerCommand->startTiming();
1560 $this->server->dispatchCommand($this, substr($messagePart, 1));
1561 Timings::$playerCommand->stopTiming();
1563 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1565 if(!$ev->isCancelled()){
1566 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1575 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1576 if(!$this->inventory->isHotbarSlot($hotbarSlot)){
1579 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1583 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1585 if($ev->isCancelled()){
1589 $this->inventory->setHeldItemIndex($hotbarSlot);
1590 $this->setUsingItem(
false);
1598 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1599 $heldItemChanged = false;
1601 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1604 $newReplica = clone $oldHeldItem;
1605 $newReplica->setCount($newHeldItem->getCount());
1606 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1607 $newReplica->setDamage($newHeldItem->getDamage());
1609 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1611 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1612 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1613 $this->broadcastSound(
new ItemBreakSound());
1615 $this->inventory->setItemInHand($newHeldItem);
1616 $heldItemChanged =
true;
1620 if(!$heldItemChanged){
1621 $newHeldItem = $oldHeldItem;
1624 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1625 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1627 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1629 $ev =
new PlayerDropItemEvent($this, $drop);
1630 if($this->isSpectator()){
1634 if(!$ev->isCancelled()){
1635 $this->dropItem($drop);
1646 $directionVector = $this->getDirectionVector();
1647 $item = $this->inventory->getItemInHand();
1648 $oldItem = clone $item;
1651 if($this->hasItemCooldown($item) || $this->isSpectator()){
1657 if($ev->isCancelled()){
1661 $returnedItems = [];
1662 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1663 if($result === ItemUseResult::FAIL){
1667 $this->resetItemCooldown($oldItem);
1668 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1670 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1681 $slot = $this->inventory->getItemInHand();
1683 $oldItem = clone $slot;
1686 if($this->hasItemCooldown($slot)){
1691 if($ev->isCancelled() || !$this->consumeObject($slot)){
1695 $this->setUsingItem(
false);
1696 $this->resetItemCooldown($oldItem);
1699 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1714 $item = $this->inventory->getItemInHand();
1715 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1719 $oldItem = clone $item;
1721 $returnedItems = [];
1722 $result = $item->onReleaseUsing($this, $returnedItems);
1723 if($result === ItemUseResult::SUCCESS){
1724 $this->resetItemCooldown($oldItem);
1725 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1731 $this->setUsingItem(
false);
1735 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1736 $block = $this->getWorld()->getBlock($pos);
1737 if($block instanceof UnknownBlock){
1741 $item = $block->getPickedItem($addTileNBT);
1743 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1744 $existingSlot = $this->inventory->first($item);
1745 if($existingSlot === -1 && $this->hasFiniteResources()){
1750 if(!$ev->isCancelled()){
1751 $this->equipOrAddPickedItem($existingSlot, $item);
1757 public function pickEntity(
int $entityId) : bool{
1758 $entity = $this->getWorld()->getEntity($entityId);
1759 if($entity ===
null){
1763 $item = $entity->getPickedItem();
1768 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1769 $existingSlot = $this->inventory->first($item);
1770 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1775 if(!$ev->isCancelled()){
1776 $this->equipOrAddPickedItem($existingSlot, $item);
1782 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1783 if($existingSlot !== -1){
1784 if($existingSlot < $this->inventory->getHotbarSize()){
1785 $this->inventory->setHeldItemIndex($existingSlot);
1787 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1790 $firstEmpty = $this->inventory->firstEmpty();
1791 if($firstEmpty === -1){
1792 $this->inventory->setItemInHand($item);
1793 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1794 $this->inventory->setItem($firstEmpty, $item);
1795 $this->inventory->setHeldItemIndex($firstEmpty);
1797 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1798 $this->inventory->setItemInHand($item);
1809 if($pos->distanceSquared($this->location) > 10000){
1813 $target = $this->getWorld()->getBlock($pos);
1815 $ev =
new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1816 if($this->isSpectator()){
1820 if($ev->isCancelled()){
1823 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1824 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1828 $block = $target->getSide($face);
1829 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1830 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1831 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1835 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1836 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1842 public function continueBreakBlock(Vector3 $pos,
int $face) : void{
1843 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1844 $this->blockBreakHandler->setTargetedFace($face);
1848 public function stopBreakBlock(Vector3 $pos) : void{
1849 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1850 $this->blockBreakHandler =
null;
1860 $this->removeCurrentWindow();
1862 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1863 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1864 $this->stopBreakBlock($pos);
1865 $item = $this->inventory->getItemInHand();
1866 $oldItem = clone $item;
1867 $returnedItems = [];
1868 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1869 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1870 $this->hungerManager->exhaust(0.005, PlayerExhaustEvent::CAUSE_MINING);
1874 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1886 $this->setUsingItem(false);
1888 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1889 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1890 $item = $this->inventory->getItemInHand();
1891 $oldItem = clone $item;
1892 $returnedItems = [];
1893 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1894 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1898 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1911 if(!$entity->isAlive()){
1915 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1919 $heldItem = $this->inventory->getItemInHand();
1920 $oldItem = clone $heldItem;
1922 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1923 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1924 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1926 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1930 $meleeEnchantmentDamage = 0;
1932 $meleeEnchantments = [];
1933 foreach($heldItem->getEnchantments() as $enchantment){
1934 $type = $enchantment->getType();
1935 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1936 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1937 $meleeEnchantments[] = $enchantment;
1940 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1942 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1943 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
1946 $entity->attack($ev);
1947 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1949 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1950 if($ev->isCancelled()){
1951 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
1954 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
1956 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
1957 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
1960 foreach($meleeEnchantments as $enchantment){
1961 $type = $enchantment->getType();
1962 assert($type instanceof MeleeWeaponEnchantment);
1963 $type->onPostAttack($this, $entity, $enchantment->getLevel());
1966 if($this->isAlive()){
1969 $returnedItems = [];
1970 $heldItem->onAttackEntity($entity, $returnedItems);
1971 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
1973 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
1986 if(!$ev->isCancelled()){
1987 $this->broadcastSound(new EntityAttackNoDamageSound());
1988 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1998 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1999 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2005 $item = $this->inventory->getItemInHand();
2006 $oldItem = clone $item;
2007 if(!$ev->isCancelled()){
2008 if($item->onInteractEntity($this, $entity, $clickPos)){
2009 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
2010 if($item instanceof Durable && $item->isBroken()){
2011 $this->broadcastSound(new ItemBreakSound());
2013 $this->inventory->setItemInHand($item);
2016 return $entity->
onInteract($this, $clickPos);
2021 public function toggleSprint(
bool $sprint) : bool{
2022 if($sprint === $this->sprinting){
2025 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2027 if($ev->isCancelled()){
2030 $this->setSprinting($sprint);
2034 public function toggleSneak(
bool $sneak) : bool{
2035 if($sneak === $this->sneaking){
2038 $ev =
new PlayerToggleSneakEvent($this, $sneak);
2040 if($ev->isCancelled()){
2043 $this->setSneaking($sneak);
2047 public function toggleFlight(
bool $fly) : bool{
2048 if($fly === $this->flying){
2051 $ev =
new PlayerToggleFlightEvent($this, $fly);
2052 if(!$this->allowFlight){
2056 if($ev->isCancelled()){
2059 $this->setFlying($fly);
2063 public function toggleGlide(
bool $glide) : bool{
2064 if($glide === $this->gliding){
2067 $ev =
new PlayerToggleGlideEvent($this, $glide);
2069 if($ev->isCancelled()){
2072 $this->setGliding($glide);
2076 public function toggleSwim(
bool $swim) : bool{
2077 if($swim === $this->swimming){
2080 $ev =
new PlayerToggleSwimEvent($this, $swim);
2082 if($ev->isCancelled()){
2085 $this->setSwimming($swim);
2089 public function emote(
string $emoteId) : void{
2090 $currentTick = $this->
server->getTick();
2091 if($currentTick - $this->lastEmoteTick > 5){
2092 $this->lastEmoteTick = $currentTick;
2093 $event =
new PlayerEmoteEvent($this, $emoteId);
2095 if(!$event->isCancelled()){
2096 $emoteId = $event->getEmoteId();
2097 parent::emote($emoteId);
2107 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2117 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2118 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2119 if($subtitle !==
""){
2120 $this->sendSubTitle($subtitle);
2122 $this->getNetworkSession()->onTitle($title);
2129 $this->getNetworkSession()->onSubTitle($subtitle);
2136 $this->getNetworkSession()->onActionBar($message);
2143 $this->getNetworkSession()->onClearTitle();
2150 $this->getNetworkSession()->onResetTitleOptions();
2161 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2162 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2170 $this->getNetworkSession()->onChatMessage($message);
2173 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2174 $this->getNetworkSession()->onJukeboxPopup($message);
2183 $this->getNetworkSession()->onPopup($message);
2186 public function sendTip(
string $message) : void{
2187 $this->getNetworkSession()->onTip($message);
2194 $this->getNetworkSession()->onToastNotification($title, $body);
2203 $id = $this->formIdCounter++;
2204 if($this->getNetworkSession()->onFormSent($id, $form)){
2205 $this->forms[$id] = $form;
2209 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2210 if(!isset($this->forms[$formId])){
2211 $this->logger->debug(
"Got unexpected response for form $formId");
2216 $this->forms[$formId]->handleResponse($this, $responseData);
2217 }
catch(FormValidationException $e){
2218 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2219 $this->logger->logException($e);
2221 unset($this->forms[$formId]);
2231 $this->getNetworkSession()->onCloseAllForms();
2246 if(!$ev->isCancelled()){
2247 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2262 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2264 if(!$ev->isCancelled()){
2265 $reason = $ev->getDisconnectReason();
2267 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2269 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2270 if($disconnectScreenMessage ===
""){
2271 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2273 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2295 if(!$this->isConnected()){
2299 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2300 $this->onPostDisconnect($reason, $quitMessage);
2311 if($this->isConnected()){
2312 throw new \LogicException(
"Player is still connected");
2316 $this->server->unsubscribeFromAllBroadcastChannels($this);
2318 $this->removeCurrentWindow();
2320 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2322 if(($quitMessage = $ev->getQuitMessage()) !=
""){
2323 $this->server->broadcastMessage($quitMessage);
2327 $this->spawned =
false;
2330 $this->blockBreakHandler =
null;
2331 $this->despawnFromAll();
2333 $this->
server->removeOnlinePlayer($this);
2335 foreach($this->
server->getOnlinePlayers() as $player){
2336 if(!$player->canSee($this)){
2337 $player->showPlayer($this);
2340 $this->hiddenPlayers = [];
2342 if($this->location->isValid()){
2343 foreach($this->usedChunks as $index => $status){
2344 World::getXZ($index, $chunkX, $chunkZ);
2345 $this->unloadChunk($chunkX, $chunkZ);
2348 if(count($this->usedChunks) !== 0){
2349 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2351 $this->loadQueue = [];
2353 $this->removeCurrentWindow();
2354 $this->removePermanentInventories();
2356 $this->perm->getPermissionRecalculationCallbacks()->clear();
2358 $this->flagForDespawn();
2362 $this->disconnect(
"Player destroyed");
2363 $this->cursorInventory->removeAllViewers();
2364 $this->craftingGrid->removeAllViewers();
2365 parent::onDispose();
2369 $this->networkSession = null;
2370 unset($this->cursorInventory);
2371 unset($this->craftingGrid);
2372 $this->spawnPosition =
null;
2373 $this->deathPosition =
null;
2374 $this->blockBreakHandler =
null;
2375 parent::destroyCycles();
2385 public function __destruct(){
2386 parent::__destruct();
2387 $this->logger->debug(
"Destroyed by garbage collector");
2395 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2399 $nbt = $this->saveNBT();
2401 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2403 if($this->location->isValid()){
2404 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2407 if($this->hasValidCustomSpawn()){
2408 $spawn = $this->getSpawn();
2409 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2410 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2411 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2412 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2415 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2416 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2417 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2418 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2419 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2422 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2423 $nbt->
setLong(self::TAG_FIRST_PLAYED, $this->firstPlayed);
2424 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2433 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2439 $this->removeCurrentWindow();
2441 $this->setDeathPosition($this->getPosition());
2443 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2446 if(!$ev->getKeepInventory()){
2447 foreach($ev->getDrops() as $item){
2448 $this->getWorld()->dropItem($this->location, $item);
2451 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2452 $this->inventory->setHeldItemIndex(0);
2453 $clearInventory($this->inventory);
2454 $clearInventory($this->armorInventory);
2455 $clearInventory($this->offHandInventory);
2458 if(!$ev->getKeepXp()){
2459 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2460 $this->xpManager->setXpAndProgress(0, 0.0);
2463 if($ev->getDeathMessage() !=
""){
2464 $this->server->broadcastMessage($ev->getDeathMessage());
2467 $this->startDeathAnimation();
2469 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2473 parent::onDeathUpdate($tickDiff);
2477 public function respawn() : void{
2478 if($this->
server->isHardcore()){
2479 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2480 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2485 $this->actuallyRespawn();
2488 protected function actuallyRespawn() : void{
2489 if($this->respawnLocked){
2492 $this->respawnLocked =
true;
2494 $this->logger->debug(
"Waiting for safe respawn position to be located");
2495 $spawn = $this->getSpawn();
2496 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2497 function(Position $safeSpawn) :
void{
2498 if(!$this->isConnected()){
2501 $this->logger->debug(
"Respawn position located, completing respawn");
2502 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2505 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2506 $this->teleport($realSpawn);
2508 $this->setSprinting(
false);
2509 $this->setSneaking(
false);
2510 $this->setFlying(
false);
2512 $this->extinguish();
2513 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2514 $this->deadTicks = 0;
2515 $this->noDamageTicks = 60;
2517 $this->effectManager->clear();
2518 $this->setHealth($this->getMaxHealth());
2520 foreach($this->attributeMap->getAll() as $attr){
2521 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2524 $attr->resetToDefault();
2527 $this->spawnToAll();
2528 $this->scheduleUpdate();
2530 $this->getNetworkSession()->onServerRespawn();
2531 $this->respawnLocked =
false;
2534 if($this->isConnected()){
2535 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2542 parent::applyPostDamageEffects($source);
2544 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2548 if(!$this->isAlive()){
2552 if($this->isCreative()
2553 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2556 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2560 parent::attack($source);
2563 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2564 parent::syncNetworkData($properties);
2566 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2567 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2569 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2570 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2572 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2573 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2575 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2576 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2578 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2579 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2580 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2584 public function sendData(?array $targets, ?array $data =
null) : void{
2585 if($targets === null){
2586 $targets = $this->getViewers();
2589 parent::sendData($targets, $data);
2593 if($this->spawned && $targets === null){
2594 $targets = $this->getViewers();
2597 parent::broadcastAnimation($animation, $targets);
2601 if($this->spawned && $targets === null){
2602 $targets = $this->getViewers();
2605 parent::broadcastSound($sound, $targets);
2611 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2612 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2618 if(parent::teleport($pos, $yaw, $pitch)){
2620 $this->removeCurrentWindow();
2623 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2624 $this->broadcastMovement(
true);
2626 $this->spawnToAll();
2628 $this->resetFallDistance();
2629 $this->nextChunkOrderRun = 0;
2630 if($this->spawnChunkLoadCount !== -1){
2631 $this->spawnChunkLoadCount = 0;
2633 $this->blockBreakHandler =
null;
2637 $this->resetLastMovements();
2645 protected function addDefaultWindows() : void{
2646 $this->cursorInventory = new PlayerCursorInventory($this);
2647 $this->craftingGrid =
new PlayerCraftingInventory($this);
2649 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2654 public function getCursorInventory() : PlayerCursorInventory{
2655 return $this->cursorInventory;
2658 public function getCraftingGrid() : CraftingGrid{
2659 return $this->craftingGrid;
2667 return $this->creativeInventory;
2674 $this->creativeInventory = $inventory;
2675 if($this->spawned && $this->isConnected()){
2676 $this->getNetworkSession()->getInvManager()?->syncCreative();
2684 private function doCloseInventory() : void{
2685 $inventories = [$this->craftingGrid, $this->cursorInventory];
2686 if($this->currentWindow instanceof TemporaryInventory){
2687 $inventories[] = $this->currentWindow;
2690 $builder =
new TransactionBuilder();
2691 foreach($inventories as $inventory){
2692 $contents = $inventory->getContents();
2694 if(count($contents) > 0){
2695 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2696 foreach($drops as $drop){
2697 $builder->addAction(
new DropItemAction($drop));
2700 $builder->getInventory($inventory)->clearAll();
2704 $actions = $builder->generateActions();
2705 if(count($actions) !== 0){
2706 $transaction =
new InventoryTransaction($this, $actions);
2708 $transaction->execute();
2709 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2710 }
catch(TransactionCancelledException){
2711 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2712 foreach($inventories as $inventory){
2713 $inventory->clearAll();
2715 }
catch(TransactionValidationException $e){
2716 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2725 return $this->currentWindow;
2732 if($inventory === $this->currentWindow){
2737 if($ev->isCancelled()){
2741 $this->removeCurrentWindow();
2743 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2744 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2746 $this->logger->debug(
"Opening inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
2747 $inventoryManager->onCurrentWindowChange($inventory);
2748 $inventory->onOpen($this);
2749 $this->currentWindow = $inventory;
2753 public function removeCurrentWindow() : void{
2754 $this->doCloseInventory();
2755 if($this->currentWindow !==
null){
2756 $currentWindow = $this->currentWindow;
2757 $this->logger->debug(
"Closing inventory " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2758 $this->currentWindow->onClose($this);
2759 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2760 $inventoryManager->onCurrentWindowRemove();
2762 $this->currentWindow =
null;
2763 (
new InventoryCloseEvent($currentWindow, $this))->call();
2767 protected function addPermanentInventories(Inventory ...$inventories) : void{
2768 foreach($inventories as $inventory){
2769 $inventory->onOpen($this);
2770 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2774 protected function removePermanentInventories() : void{
2775 foreach($this->permanentWindows as $inventory){
2776 $inventory->onClose($this);
2778 $this->permanentWindows = [];
2786 $block = $this->getWorld()->getBlock($position);
2788 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2789 $this->getNetworkSession()->onOpenSignEditor($position,
true);
2791 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2795 use ChunkListenerNoOpTrait {
2796 onChunkChanged as
private;
2797 onChunkUnloaded as
private;
2801 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2802 if($status === UsedChunkStatus::SENT){
2803 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2804 $this->nextChunkOrderRun = 0;
2809 if($this->isUsingChunk($chunkX, $chunkZ)){
2810 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2811 $this->unloadChunk($chunkX, $chunkZ);