170 use PermissibleDelegateTrait;
172 private const MOVES_PER_TICK = 2;
173 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
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;
187 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
189 public const TAG_FIRST_PLAYED =
"firstPlayed";
190 public const TAG_LAST_PLAYED =
"lastPlayed";
191 private const TAG_GAME_MODE =
"playerGameType";
192 private const TAG_SPAWN_WORLD =
"SpawnLevel";
193 private const TAG_SPAWN_X =
"SpawnX";
194 private const TAG_SPAWN_Y =
"SpawnY";
195 private const TAG_SPAWN_Z =
"SpawnZ";
196 private const TAG_DEATH_WORLD =
"DeathLevel";
197 private const TAG_DEATH_X =
"DeathPositionX";
198 private const TAG_DEATH_Y =
"DeathPositionY";
199 private const TAG_DEATH_Z =
"DeathPositionZ";
200 public const TAG_LEVEL =
"Level";
201 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
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;
218 public bool $spawned =
false;
220 protected string $username;
221 protected string $displayName;
222 protected string $xuid =
"";
223 protected bool $authenticated;
226 protected ?Inventory $currentWindow =
null;
228 protected array $permanentWindows = [];
229 protected PlayerCursorInventory $cursorInventory;
230 protected PlayerCraftingInventory $craftingGrid;
231 protected CreativeInventory $creativeInventory;
233 protected int $messageCounter = 2;
235 protected int $firstPlayed;
236 protected int $lastPlayed;
237 protected GameMode $gamemode;
243 protected array $usedChunks = [];
248 private array $activeChunkGenerationRequests = [];
253 protected array $loadQueue = [];
254 protected int $nextChunkOrderRun = 5;
257 private array $tickingChunks = [];
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;
268 protected array $hiddenPlayers = [];
270 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
271 protected ?
float $lastMovementProcess =
null;
273 protected int $inAirTicks = 0;
275 protected float $stepHeight = 0.6;
277 protected ?Vector3 $sleeping =
null;
278 private ?
Position $spawnPosition =
null;
280 private bool $respawnLocked =
false;
282 private ?
Position $deathPosition =
null;
285 protected bool $autoJump =
true;
286 protected bool $allowFlight =
false;
287 protected bool $blockCollision =
true;
288 protected bool $flying =
false;
290 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
293 protected ?
int $lineHeight =
null;
294 protected string $locale =
"en_US";
296 protected int $startAction = -1;
302 protected array $usedItemsCooldown = [];
304 private int $lastEmoteTick = 0;
306 protected int $formIdCounter = 0;
308 protected array $forms = [];
310 protected \Logger $logger;
315 $username = TextFormat::clean($playerInfo->getUsername());
316 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
319 $this->networkSession = $session;
320 $this->playerInfo = $playerInfo;
321 $this->authenticated = $authenticated;
323 $this->username = $username;
324 $this->displayName = $this->username;
325 $this->locale = $this->playerInfo->getLocale();
327 $this->uuid = $this->playerInfo->getUuid();
328 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
330 $this->creativeInventory = CreativeInventory::getInstance();
332 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
333 if($this->
server->isOp($this->username)){
334 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
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);
341 $this->chunkLoader =
new class implements
ChunkLoader{};
343 $world = $spawnLocation->
getWorld();
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;
351 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
355 $this->setNameTag($this->username);
358 private function callDummyItemHeldEvent() : void{
359 $slot = $this->inventory->getHeldItemIndex();
368 protected function initEntity(
CompoundTag $nbt) : void{
369 parent::initEntity($nbt);
370 $this->addDefaultWindows();
372 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
373 function(Inventory $unused,
int $slot) :
void{
374 if($slot === $this->inventory->getHeldItemIndex()){
375 $this->setUsingItem(
false);
377 $this->callDummyItemHeldEvent();
381 $this->setUsingItem(
false);
382 $this->callDummyItemHeldEvent();
386 $this->firstPlayed = $nbt->getLong(self::TAG_FIRST_PLAYED, $now = (
int) (microtime(
true) * 1000));
387 $this->lastPlayed = $nbt->getLong(self::TAG_LAST_PLAYED, $now);
389 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
390 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
392 $this->internalSetGameMode($this->
server->getGamemode());
395 $this->keepMovement =
true;
397 $this->setNameTagVisible();
398 $this->setNameTagAlwaysVisible();
399 $this->setCanClimb();
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);
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);
409 public function getLeaveMessage() : Translatable|string{
411 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
417 public function isAuthenticated() : bool{
418 return $this->authenticated;
443 return parent::getUniqueId();
450 return $this->firstPlayed;
457 return $this->lastPlayed;
460 public function hasPlayedBefore() : bool{
461 return $this->lastPlayed - $this->firstPlayed > 1;
474 if($this->allowFlight !== $value){
475 $this->allowFlight = $value;
476 $this->getNetworkSession()->syncAbilities($this);
487 return $this->allowFlight;
499 if($this->blockCollision !== $value){
500 $this->blockCollision = $value;
501 $this->getNetworkSession()->syncAbilities($this);
510 return $this->blockCollision;
513 public function setFlying(
bool $value) : void{
514 if($this->flying !== $value){
515 $this->flying = $value;
516 $this->resetFallDistance();
517 $this->getNetworkSession()->syncAbilities($this);
521 public function isFlying() : bool{
522 return $this->flying;
539 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
540 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
541 $this->getNetworkSession()->syncAbilities($this);
557 return $this->flightSpeedMultiplier;
560 public function setAutoJump(
bool $value) : void{
561 if($this->autoJump !== $value){
562 $this->autoJump = $value;
563 $this->getNetworkSession()->syncAdventureSettings();
567 public function hasAutoJump() : bool{
568 return $this->autoJump;
571 public function spawnTo(Player $player) : void{
572 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
573 parent::spawnTo($player);
577 public function getServer() : Server{
582 return $this->lineHeight ?? 7;
586 if($height !== null && $height < 1){
587 throw new \InvalidArgumentException(
"Line height must be at least 1");
589 $this->lineHeight = $height;
592 public function canSee(
Player $player) : bool{
593 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
596 public function hidePlayer(Player $player) : void{
597 if($player === $this){
600 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
601 $player->despawnFrom($this);
604 public function showPlayer(Player $player) : void{
605 if($player === $this){
608 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
609 if($player->isOnline()){
610 $player->spawnTo($this);
614 public function canCollideWith(Entity $entity) : bool{
618 public function canBeCollidedWith() : bool{
619 return !$this->isSpectator() && parent::canBeCollidedWith();
622 public function resetFallDistance() : void{
623 parent::resetFallDistance();
624 $this->inAirTicks = 0;
627 public function getViewDistance() : int{
628 return $this->viewDistance;
631 public function setViewDistance(
int $distance) : void{
632 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
634 if($newViewDistance !== $this->viewDistance){
635 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
639 $this->viewDistance = $newViewDistance;
641 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
643 $this->nextChunkOrderRun = 0;
645 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
647 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
650 public function isOnline() : bool{
651 return $this->isConnected();
654 public function isConnected() : bool{
655 return $this->networkSession !== null && $this->networkSession->isConnected();
658 public function getNetworkSession() : NetworkSession{
659 if($this->networkSession === null){
660 throw new \LogicException(
"Player is not connected");
662 return $this->networkSession;
669 return $this->username;
676 return $this->displayName;
679 public function setDisplayName(
string $name) : void{
683 $this->displayName = $ev->getNewName();
694 return $this->locale;
697 public function getLanguage() :
Language{
698 return $this->
server->getLanguage();
705 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
709 if($ev->isCancelled()){
710 $this->sendSkin([$this]);
714 $this->setSkin($ev->getNewSkin());
715 $this->sendSkin($this->server->getOnlinePlayers());
724 public function sendSkin(?array $targets =
null) : void{
725 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
732 return $this->startAction > -1;
735 public function setUsingItem(
bool $value) : void{
736 $this->startAction = $value ? $this->
server->getTick() : -1;
737 $this->networkPropertiesDirty =
true;
745 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
752 $this->checkItemCooldowns();
753 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
760 $this->checkItemCooldowns();
761 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
768 $ticks = $ticks ?? $item->getCooldownTicks();
770 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
771 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
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]);
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);
796 $this->usedChunks = [];
797 $this->loadQueue = [];
798 $this->getNetworkSession()->onEnterWorld();
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);
816 $this->getNetworkSession()->stopUsingChunk($x, $z);
817 unset($this->usedChunks[$index]);
818 unset($this->activeChunkGenerationRequests[$index]);
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]);
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);
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);
849 if(!$this->isConnected()){
853 Timings::$playerChunkSend->startTiming();
856 $world = $this->getWorld();
858 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
859 foreach($this->loadQueue as $index => $distance){
860 if($count >= $limit){
866 World::getXZ($index, $X, $Z);
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);
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()){
884 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
890 unset($this->activeChunkGenerationRequests[$index]);
891 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
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;
900 $this->spawnEntitiesOnAllChunks();
902 $this->getNetworkSession()->notifyTerrainReady();
904 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
907 static function() :
void{
913 Timings::$playerChunkSend->stopTiming();
916 private function recheckBroadcastPermissions() : void{
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);
924 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
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();
945 $ev =
new PlayerJoinEvent($this,
946 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
949 if($ev->getJoinMessage() !==
""){
950 $this->server->broadcastMessage($ev->getJoinMessage());
953 $this->noDamageTicks = 60;
957 if($this->getHealth() <= 0){
958 $this->logger->debug(
"Quit while dead, forcing respawn");
959 $this->actuallyRespawn();
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])){
975 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
976 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
979 foreach($newTickingChunks as $hash => $_){
980 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
982 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
983 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
993 if(!$this->isConnected() || $this->viewDistance === -1){
997 Timings::$playerChunkOrder->startTiming();
1000 $tickingChunks = [];
1001 $unloadChunks = $this->usedChunks;
1003 $world = $this->getWorld();
1004 $tickingChunkRadius = $world->getChunkTickRadius();
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;
1014 if($radius < $tickingChunkRadius){
1015 $tickingChunks[$hash] =
true;
1017 unset($unloadChunks[$hash]);
1020 foreach($unloadChunks as $index => $status){
1021 World::getXZ($index, $X, $Z);
1022 $this->unloadChunk($X, $Z);
1025 $this->loadQueue = $newOrder;
1027 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1028 $this->tickingChunks = $tickingChunks;
1030 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1031 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1034 Timings::$playerChunkOrder->stopTiming();
1042 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1050 return $this->usedChunks;
1057 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1064 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1065 return $status === UsedChunkStatus::SENT;
1072 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1073 $this->nextChunkOrderRun = PHP_INT_MAX;
1074 $this->orderChunks();
1077 if(count($this->loadQueue) > 0){
1078 $this->requestChunks();
1082 public function getDeathPosition() : ?Position{
1083 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1084 $this->deathPosition =
null;
1086 return $this->deathPosition;
1094 if($pos instanceof
Position && $pos->world !==
null){
1095 $world = $pos->world;
1097 $world = $this->getWorld();
1099 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1101 $this->deathPosition =
null;
1103 $this->networkPropertiesDirty =
true;
1110 if($this->hasValidCustomSpawn()){
1111 return $this->spawnPosition;
1113 $world = $this->
server->getWorldManager()->getDefaultWorld();
1115 return $world->getSpawnLocation();
1119 public function hasValidCustomSpawn() : bool{
1120 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1132 $world = $this->getWorld();
1134 $world = $pos->getWorld();
1136 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1138 $this->spawnPosition =
null;
1140 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1143 public function isSleeping() : bool{
1144 return $this->sleeping !== null;
1147 public function sleepOn(Vector3 $pos) : bool{
1148 $pos = $pos->floor();
1149 $b = $this->getWorld()->getBlock($pos);
1151 $ev =
new PlayerBedEnterEvent($this, $b);
1153 if($ev->isCancelled()){
1157 if($b instanceof Bed){
1159 $this->getWorld()->setBlock($pos, $b);
1162 $this->sleeping = $pos;
1163 $this->networkPropertiesDirty =
true;
1165 $this->setSpawn($pos);
1167 $this->getWorld()->setSleepTicks(60);
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);
1179 (
new PlayerBedLeaveEvent($this, $b))->call();
1181 $this->sleeping =
null;
1182 $this->networkPropertiesDirty =
true;
1184 $this->getWorld()->setSleepTicks(0);
1186 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1190 public function getGamemode() : GameMode{
1191 return $this->gamemode;
1194 protected function internalSetGameMode(GameMode $gameMode) : void{
1195 $this->gamemode = $gameMode;
1197 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1198 $this->hungerManager->setEnabled($this->isSurvival());
1200 if($this->isSpectator()){
1201 $this->setFlying(
true);
1202 $this->setHasBlockCollision(
false);
1204 $this->onGround =
false;
1208 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1210 if($this->isSurvival()){
1211 $this->setFlying(
false);
1213 $this->setHasBlockCollision(
true);
1214 $this->setSilent(
false);
1215 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1223 if($this->gamemode === $gm){
1229 if($ev->isCancelled()){
1233 $this->internalSetGameMode($gm);
1235 if($this->isSpectator()){
1236 $this->despawnFromAll();
1238 $this->spawnToAll();
1241 $this->getNetworkSession()->syncGameMode($this->gamemode);
1252 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1262 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1272 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1275 public function isSpectator() : bool{
1276 return $this->gamemode === GameMode::SPECTATOR;
1283 return $this->gamemode !== GameMode::CREATIVE;
1287 if($this->hasFiniteResources()){
1288 return parent::getDrops();
1295 if($this->hasFiniteResources()){
1296 return parent::getXpDropAmount();
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;
1306 $bb = clone $this->boundingBox;
1307 $bb->minY = $this->location->y - 0.2;
1308 $bb->maxY = $this->location->y + 0.2;
1312 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1314 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1322 protected function checkNearEntities() : void{
1323 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1324 $entity->scheduleUpdate();
1326 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1330 $entity->onCollideWithPlayer($this);
1334 public function getInAirTicks() : int{
1335 return $this->inAirTicks;
1347 Timings::$playerMove->startTiming();
1349 $this->actuallyHandleMovement($newPos);
1351 Timings::$playerMove->stopTiming();
1355 private function actuallyHandleMovement(Vector3 $newPos) : void{
1356 $this->moveRateLimit--;
1357 if($this->moveRateLimit < 0){
1361 $oldPos = $this->location;
1362 $distanceSquared = $newPos->distanceSquared($oldPos);
1366 if($distanceSquared > 225){
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);
1381 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1383 $this->nextChunkOrderRun = 0;
1386 if(!$revert && $distanceSquared !== 0.0){
1387 $dx = $newPos->x - $oldPos->x;
1388 $dy = $newPos->y - $oldPos->y;
1389 $dz = $newPos->z - $oldPos->z;
1391 $this->move($dx, $dy, $dz);
1395 $this->revertMovement($oldPos);
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;
1409 $from = clone $this->lastLocation;
1410 $to = clone $this->location;
1412 $delta = $to->distanceSquared($from);
1413 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1415 if($delta > 0.0001 || $deltaAngle > 1.0){
1416 if(PlayerMoveEvent::hasHandlers()){
1421 if($ev->isCancelled()){
1422 $this->revertMovement($from);
1426 if($to->distanceSquared($ev->getTo()) > 0.01){
1427 $this->teleport($ev->getTo());
1432 $this->lastLocation = $to;
1433 $this->broadcastMovement();
1435 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1436 if($horizontalDistanceTravelled > 0){
1438 if($this->isSprinting()){
1439 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, PlayerExhaustEvent::CAUSE_SPRINTING);
1441 $this->hungerManager->exhaust(0.0, PlayerExhaustEvent::CAUSE_WALKING);
1444 if($this->nextChunkOrderRun > 20){
1445 $this->nextChunkOrderRun = 20;
1450 if($exceededRateLimit){
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);
1456 protected function revertMovement(Location $from) : void{
1457 $this->setPosition($from);
1458 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1461 protected function calculateFallDamage(
float $fallDistance) : float{
1462 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
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));
1480 protected function updateMovement(
bool $teleport =
false) : void{
1484 protected function tryChangeMovement() : void{
1488 public function onUpdate(int $currentTick) : bool{
1489 $tickDiff = $currentTick - $this->lastUpdate;
1495 $this->messageCounter = 2;
1497 $this->lastUpdate = $currentTick;
1499 if($this->justCreated){
1500 $this->onFirstUpdate($currentTick);
1503 if(!$this->isAlive() && $this->spawned){
1504 $this->onDeathUpdate($tickDiff);
1508 $this->timings->startTiming();
1511 Timings::$playerMove->startTiming();
1512 $this->processMostRecentMovements();
1513 $this->motion = Vector3::zero();
1514 if($this->onGround){
1515 $this->inAirTicks = 0;
1517 $this->inAirTicks += $tickDiff;
1519 Timings::$playerMove->stopTiming();
1521 Timings::$entityBaseTick->startTiming();
1522 $this->entityBaseTick($tickDiff);
1523 Timings::$entityBaseTick->stopTiming();
1525 if($this->isCreative() && $this->fireTicks > 1){
1526 $this->fireTicks = 1;
1529 if(!$this->isSpectator() && $this->isAlive()){
1530 Timings::$playerCheckNearEntities->startTiming();
1531 $this->checkNearEntities();
1532 Timings::$playerCheckNearEntities->stopTiming();
1535 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1536 $this->blockBreakHandler =
null;
1540 $this->timings->stopTiming();
1546 return $this->isCreative() || parent::canEat();
1550 return $this->isCreative() || parent::canBreathe();
1559 $eyePos = $this->getEyePos();
1560 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1564 $dV = $this->getDirectionVector();
1565 $eyeDot = $dV->dot($eyePos);
1566 $targetDot = $dV->dot($pos);
1567 return ($targetDot - $eyeDot) >= -$maxDiff;
1574 public function chat(
string $message) : bool{
1575 $this->removeCurrentWindow();
1577 if($this->messageCounter <= 0){
1583 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1584 if(strlen($message) > $maxTotalLength){
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);
1595 if(str_starts_with($messagePart,
"/")){
1596 Timings::$playerCommand->startTiming();
1597 $this->server->dispatchCommand($this, substr($messagePart, 1));
1598 Timings::$playerCommand->stopTiming();
1600 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1602 if(!$ev->isCancelled()){
1603 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1612 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1613 if(!$this->inventory->isHotbarSlot($hotbarSlot)){
1616 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1620 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1622 if($ev->isCancelled()){
1626 $this->inventory->setHeldItemIndex($hotbarSlot);
1627 $this->setUsingItem(
false);
1635 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1636 $heldItemChanged = false;
1638 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1641 $newReplica = clone $oldHeldItem;
1642 $newReplica->setCount($newHeldItem->getCount());
1643 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1644 $newReplica->setDamage($newHeldItem->getDamage());
1646 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1648 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1649 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1650 $this->broadcastSound(
new ItemBreakSound());
1652 $this->inventory->setItemInHand($newHeldItem);
1653 $heldItemChanged =
true;
1657 if(!$heldItemChanged){
1658 $newHeldItem = $oldHeldItem;
1661 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1662 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1664 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1666 $ev =
new PlayerDropItemEvent($this, $drop);
1667 if($this->isSpectator()){
1671 if(!$ev->isCancelled()){
1672 $this->dropItem($drop);
1683 $directionVector = $this->getDirectionVector();
1684 $item = $this->inventory->getItemInHand();
1685 $oldItem = clone $item;
1688 if($this->hasItemCooldown($item) || $this->isSpectator()){
1694 if($ev->isCancelled()){
1698 $returnedItems = [];
1699 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1700 if($result === ItemUseResult::FAIL){
1704 $this->resetItemCooldown($oldItem);
1705 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1707 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1718 $slot = $this->inventory->getItemInHand();
1720 $oldItem = clone $slot;
1723 if($this->hasItemCooldown($slot)){
1728 if($ev->isCancelled() || !$this->consumeObject($slot)){
1732 $this->setUsingItem(
false);
1733 $this->resetItemCooldown($oldItem);
1736 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1751 $item = $this->inventory->getItemInHand();
1752 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1756 $oldItem = clone $item;
1758 $returnedItems = [];
1759 $result = $item->onReleaseUsing($this, $returnedItems);
1760 if($result === ItemUseResult::SUCCESS){
1761 $this->resetItemCooldown($oldItem);
1762 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1768 $this->setUsingItem(
false);
1772 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1773 $block = $this->getWorld()->getBlock($pos);
1774 if($block instanceof UnknownBlock){
1778 $item = $block->getPickedItem($addTileNBT);
1780 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1781 $existingSlot = $this->inventory->first($item);
1782 if($existingSlot === -1 && $this->hasFiniteResources()){
1787 if(!$ev->isCancelled()){
1788 $this->equipOrAddPickedItem($existingSlot, $item);
1794 public function pickEntity(
int $entityId) : bool{
1795 $entity = $this->getWorld()->getEntity($entityId);
1796 if($entity ===
null){
1800 $item = $entity->getPickedItem();
1805 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1806 $existingSlot = $this->inventory->first($item);
1807 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1812 if(!$ev->isCancelled()){
1813 $this->equipOrAddPickedItem($existingSlot, $item);
1819 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1820 if($existingSlot !== -1){
1821 if($existingSlot < $this->inventory->getHotbarSize()){
1822 $this->inventory->setHeldItemIndex($existingSlot);
1824 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1827 $firstEmpty = $this->inventory->firstEmpty();
1828 if($firstEmpty === -1){
1829 $this->inventory->setItemInHand($item);
1830 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1831 $this->inventory->setItem($firstEmpty, $item);
1832 $this->inventory->setHeldItemIndex($firstEmpty);
1834 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1835 $this->inventory->setItemInHand($item);
1846 if($pos->distanceSquared($this->location) > 10000){
1850 $target = $this->getWorld()->getBlock($pos);
1852 $ev =
new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1853 if($this->isSpectator()){
1857 if($ev->isCancelled()){
1860 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1861 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
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());
1872 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1873 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
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);
1885 public function stopBreakBlock(Vector3 $pos) : void{
1886 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1887 $this->blockBreakHandler =
null;
1897 $this->removeCurrentWindow();
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);
1911 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1923 $this->setUsingItem(false);
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();
1928 $oldItem = clone $item;
1929 $returnedItems = [];
1930 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1931 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1935 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1948 if(!$entity->isAlive()){
1952 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1956 $heldItem = $this->inventory->getItemInHand();
1957 $oldItem = clone $heldItem;
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");
1963 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
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;
1977 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
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);
1983 $entity->attack($ev);
1984 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1986 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1987 if($ev->isCancelled()){
1988 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
1991 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
1993 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
1994 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
1997 foreach($meleeEnchantments as $enchantment){
1998 $type = $enchantment->getType();
1999 assert($type instanceof MeleeWeaponEnchantment);
2000 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2003 if($this->isAlive()){
2006 $returnedItems = [];
2007 $heldItem->onAttackEntity($entity, $returnedItems);
2008 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2010 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
2023 if(!$ev->isCancelled()){
2024 $this->broadcastSound(new EntityAttackNoDamageSound());
2025 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
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");
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());
2050 $this->inventory->setItemInHand($item);
2053 return $entity->
onInteract($this, $clickPos);
2058 public function toggleSprint(
bool $sprint) : bool{
2059 if($sprint === $this->sprinting){
2062 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2064 if($ev->isCancelled()){
2067 $this->setSprinting($sprint);
2071 public function toggleSneak(
bool $sneak) : bool{
2072 if($sneak === $this->sneaking){
2075 $ev =
new PlayerToggleSneakEvent($this, $sneak);
2077 if($ev->isCancelled()){
2080 $this->setSneaking($sneak);
2084 public function toggleFlight(
bool $fly) : bool{
2085 if($fly === $this->flying){
2088 $ev =
new PlayerToggleFlightEvent($this, $fly);
2089 if(!$this->allowFlight){
2093 if($ev->isCancelled()){
2096 $this->setFlying($fly);
2100 public function toggleGlide(
bool $glide) : bool{
2101 if($glide === $this->gliding){
2104 $ev =
new PlayerToggleGlideEvent($this, $glide);
2106 if($ev->isCancelled()){
2109 $this->setGliding($glide);
2113 public function toggleSwim(
bool $swim) : bool{
2114 if($swim === $this->swimming){
2117 $ev =
new PlayerToggleSwimEvent($this, $swim);
2119 if($ev->isCancelled()){
2122 $this->setSwimming($swim);
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);
2132 if(!$event->isCancelled()){
2133 $emoteId = $event->getEmoteId();
2134 parent::emote($emoteId);
2144 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
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);
2159 $this->getNetworkSession()->onTitle($title);
2166 $this->getNetworkSession()->onSubTitle($subtitle);
2173 $this->getNetworkSession()->onActionBar($message);
2180 $this->getNetworkSession()->onClearTitle();
2187 $this->getNetworkSession()->onResetTitleOptions();
2198 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2199 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2207 $this->getNetworkSession()->onChatMessage($message);
2210 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2211 $this->getNetworkSession()->onJukeboxPopup($message);
2220 $this->getNetworkSession()->onPopup($message);
2223 public function sendTip(
string $message) : void{
2224 $this->getNetworkSession()->onTip($message);
2231 $this->getNetworkSession()->onToastNotification($title, $body);
2240 $id = $this->formIdCounter++;
2241 if($this->getNetworkSession()->onFormSent($id, $form)){
2242 $this->forms[$id] = $form;
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");
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);
2258 unset($this->forms[$formId]);
2268 $this->getNetworkSession()->onCloseAllForms();
2283 if(!$ev->isCancelled()){
2284 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2299 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2301 if(!$ev->isCancelled()){
2302 $reason = $ev->getDisconnectReason();
2304 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2306 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2307 if($disconnectScreenMessage ===
""){
2308 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2310 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2332 if(!$this->isConnected()){
2336 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2337 $this->onPostDisconnect($reason, $quitMessage);
2348 if($this->isConnected()){
2349 throw new \LogicException(
"Player is still connected");
2353 $this->server->unsubscribeFromAllBroadcastChannels($this);
2355 $this->removeCurrentWindow();
2357 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2359 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2360 $this->server->broadcastMessage($quitMessage);
2364 $this->spawned =
false;
2367 $this->blockBreakHandler =
null;
2368 $this->despawnFromAll();
2370 $this->
server->removeOnlinePlayer($this);
2372 foreach($this->
server->getOnlinePlayers() as $player){
2373 if(!$player->canSee($this)){
2374 $player->showPlayer($this);
2377 $this->hiddenPlayers = [];
2379 if($this->location->isValid()){
2380 foreach($this->usedChunks as $index => $status){
2381 World::getXZ($index, $chunkX, $chunkZ);
2382 $this->unloadChunk($chunkX, $chunkZ);
2385 if(count($this->usedChunks) !== 0){
2386 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2388 $this->loadQueue = [];
2390 $this->removeCurrentWindow();
2391 $this->removePermanentInventories();
2393 $this->perm->getPermissionRecalculationCallbacks()->clear();
2395 $this->flagForDespawn();
2399 $this->disconnect(
"Player destroyed");
2400 $this->cursorInventory->removeAllViewers();
2401 $this->craftingGrid->removeAllViewers();
2402 parent::onDispose();
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();
2422 public function __destruct(){
2423 parent::__destruct();
2424 $this->logger->debug(
"Destroyed by garbage collector");
2432 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2436 $nbt = $this->saveNBT();
2438 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2440 if($this->location->isValid()){
2441 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
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());
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());
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));
2470 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2476 $this->removeCurrentWindow();
2478 $this->setDeathPosition($this->getPosition());
2480 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2483 if(!$ev->getKeepInventory()){
2484 foreach($ev->getDrops() as $item){
2485 $this->getWorld()->dropItem($this->location, $item);
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);
2495 if(!$ev->getKeepXp()){
2496 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2497 $this->xpManager->setXpAndProgress(0, 0.0);
2500 if($ev->getDeathMessage() !==
""){
2501 $this->server->broadcastMessage($ev->getDeathMessage());
2504 $this->startDeathAnimation();
2506 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2510 parent::onDeathUpdate($tickDiff);
2514 public function respawn() : void{
2515 if($this->
server->isHardcore()){
2516 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2517 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2522 $this->actuallyRespawn();
2525 protected function actuallyRespawn() : void{
2526 if($this->respawnLocked){
2529 $this->respawnLocked =
true;
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()){
2538 $this->logger->debug(
"Respawn position located, completing respawn");
2539 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2542 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2543 $this->teleport($realSpawn);
2545 $this->setSprinting(
false);
2546 $this->setSneaking(
false);
2547 $this->setFlying(
false);
2549 $this->extinguish();
2550 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2551 $this->deadTicks = 0;
2552 $this->noDamageTicks = 60;
2554 $this->effectManager->clear();
2555 $this->setHealth($this->getMaxHealth());
2557 foreach($this->attributeMap->getAll() as $attr){
2558 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2561 $attr->resetToDefault();
2564 $this->spawnToAll();
2565 $this->scheduleUpdate();
2567 $this->getNetworkSession()->onServerRespawn();
2568 $this->respawnLocked =
false;
2571 if($this->isConnected()){
2572 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2579 parent::applyPostDamageEffects($source);
2581 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2585 if(!$this->isAlive()){
2589 if($this->isCreative()
2590 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2593 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2597 parent::attack($source);
2600 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2601 parent::syncNetworkData($properties);
2603 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2604 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
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));
2609 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2610 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2612 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2613 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
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);
2621 public function sendData(?array $targets, ?array $data =
null) : void{
2622 if($targets === null){
2623 $targets = $this->getViewers();
2626 parent::sendData($targets, $data);
2630 if($this->spawned && $targets === null){
2631 $targets = $this->getViewers();
2634 parent::broadcastAnimation($animation, $targets);
2638 if($this->spawned && $targets === null){
2639 $targets = $this->getViewers();
2642 parent::broadcastSound($sound, $targets);
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);
2655 if(parent::teleport($pos, $yaw, $pitch)){
2657 $this->removeCurrentWindow();
2660 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2661 $this->broadcastMovement(
true);
2663 $this->spawnToAll();
2665 $this->resetFallDistance();
2666 $this->nextChunkOrderRun = 0;
2667 if($this->spawnChunkLoadCount !== -1){
2668 $this->spawnChunkLoadCount = 0;
2670 $this->blockBreakHandler =
null;
2674 $this->resetLastMovements();
2682 protected function addDefaultWindows() : void{
2683 $this->cursorInventory = new PlayerCursorInventory($this);
2684 $this->craftingGrid =
new PlayerCraftingInventory($this);
2686 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2691 public function getCursorInventory() : PlayerCursorInventory{
2692 return $this->cursorInventory;
2695 public function getCraftingGrid() : CraftingGrid{
2696 return $this->craftingGrid;
2704 return $this->creativeInventory;
2711 $this->creativeInventory = $inventory;
2712 if($this->spawned && $this->isConnected()){
2713 $this->getNetworkSession()->getInvManager()?->syncCreative();
2721 private function doCloseInventory() : void{
2722 $inventories = [$this->craftingGrid, $this->cursorInventory];
2723 if($this->currentWindow instanceof TemporaryInventory){
2724 $inventories[] = $this->currentWindow;
2727 $builder =
new TransactionBuilder();
2728 foreach($inventories as $inventory){
2729 $contents = $inventory->getContents();
2731 if(count($contents) > 0){
2732 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2733 foreach($drops as $drop){
2734 $builder->addAction(
new DropItemAction($drop));
2737 $builder->getInventory($inventory)->clearAll();
2741 $actions = $builder->generateActions();
2742 if(count($actions) !== 0){
2743 $transaction =
new InventoryTransaction($this, $actions);
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();
2752 }
catch(TransactionValidationException $e){
2753 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2762 return $this->currentWindow;
2769 if($inventory === $this->currentWindow){
2774 if($ev->isCancelled()){
2778 $this->removeCurrentWindow();
2780 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2781 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
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;
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();
2799 $this->currentWindow =
null;
2800 (
new InventoryCloseEvent($currentWindow, $this))->call();
2804 protected function addPermanentInventories(Inventory ...$inventories) : void{
2805 foreach($inventories as $inventory){
2806 $inventory->onOpen($this);
2807 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2811 protected function removePermanentInventories() : void{
2812 foreach($this->permanentWindows as $inventory){
2813 $inventory->onClose($this);
2815 $this->permanentWindows = [];
2823 $block = $this->getWorld()->getBlock($position);
2825 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2826 $this->getNetworkSession()->onOpenSignEditor($position,
true);
2828 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2832 use ChunkListenerNoOpTrait {
2833 onChunkChanged as
private;
2834 onChunkUnloaded as
private;
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;
2846 if($this->isUsingChunk($chunkX, $chunkZ)){
2847 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2848 $this->unloadChunk($chunkX, $chunkZ);