172 use PermissibleDelegateTrait;
174 private const MOVES_PER_TICK = 2;
175 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
178 private const MAX_CHAT_CHAR_LENGTH = 512;
184 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
185 private const MAX_REACH_DISTANCE_CREATIVE = 13;
186 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
187 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
189 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
191 public const TAG_FIRST_PLAYED =
"firstPlayed";
192 public const TAG_LAST_PLAYED =
"lastPlayed";
193 private const TAG_GAME_MODE =
"playerGameType";
194 private const TAG_SPAWN_WORLD =
"SpawnLevel";
195 private const TAG_SPAWN_X =
"SpawnX";
196 private const TAG_SPAWN_Y =
"SpawnY";
197 private const TAG_SPAWN_Z =
"SpawnZ";
198 private const TAG_DEATH_WORLD =
"DeathLevel";
199 private const TAG_DEATH_X =
"DeathPositionX";
200 private const TAG_DEATH_Y =
"DeathPositionY";
201 private const TAG_DEATH_Z =
"DeathPositionZ";
202 public const TAG_LEVEL =
"Level";
203 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
213 $lname = strtolower($name);
214 $len = strlen($name);
215 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
220 public bool $spawned =
false;
222 protected string $username;
223 protected string $displayName;
224 protected string $xuid =
"";
225 protected bool $authenticated;
228 protected ?Inventory $currentWindow =
null;
230 protected array $permanentWindows = [];
231 protected PlayerCursorInventory $cursorInventory;
232 protected PlayerCraftingInventory $craftingGrid;
233 protected CreativeInventory $creativeInventory;
235 protected int $messageCounter = 2;
237 protected DateTimeImmutable $firstPlayed;
238 protected DateTimeImmutable $lastPlayed;
239 protected GameMode $gamemode;
245 protected array $usedChunks = [];
250 private array $activeChunkGenerationRequests = [];
255 protected array $loadQueue = [];
256 protected int $nextChunkOrderRun = 5;
259 private array $tickingChunks = [];
261 protected int $viewDistance = -1;
262 protected int $spawnThreshold;
263 protected int $spawnChunkLoadCount = 0;
264 protected int $chunksPerTick;
265 protected ChunkSelector $chunkSelector;
266 protected ChunkLoader $chunkLoader;
267 protected ChunkTicker $chunkTicker;
270 protected array $hiddenPlayers = [];
272 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
273 protected ?
float $lastMovementProcess =
null;
275 protected int $inAirTicks = 0;
277 protected float $stepHeight = 0.6;
279 protected ?Vector3 $sleeping =
null;
280 private ?
Position $spawnPosition =
null;
282 private bool $respawnLocked =
false;
284 private ?
Position $deathPosition =
null;
287 protected bool $autoJump =
true;
288 protected bool $allowFlight =
false;
289 protected bool $blockCollision =
true;
290 protected bool $flying =
false;
292 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
295 protected ?
int $lineHeight =
null;
296 protected string $locale =
"en_US";
298 protected int $startAction = -1;
304 protected array $usedItemsCooldown = [];
306 private int $lastEmoteTick = 0;
308 protected int $formIdCounter = 0;
310 protected array $forms = [];
312 protected \Logger $logger;
317 $username = TextFormat::clean($playerInfo->getUsername());
318 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
321 $this->networkSession = $session;
322 $this->playerInfo = $playerInfo;
323 $this->authenticated = $authenticated;
325 $this->username = $username;
326 $this->displayName = $this->username;
327 $this->locale = $this->playerInfo->getLocale();
329 $this->uuid = $this->playerInfo->getUuid();
330 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
332 $this->creativeInventory = CreativeInventory::getInstance();
334 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
335 if($this->
server->isOp($this->username)){
336 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
339 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
340 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
343 $this->chunkLoader =
new class implements
ChunkLoader{};
345 $world = $spawnLocation->
getWorld();
347 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
348 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
349 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
350 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
351 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
353 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
357 $this->setNameTag($this->username);
360 private function callDummyItemHeldEvent() : void{
361 $slot = $this->inventory->getHeldItemIndex();
370 protected function initEntity(
CompoundTag $nbt) : void{
371 parent::initEntity($nbt);
372 $this->addDefaultWindows();
374 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
375 function(Inventory $unused,
int $slot) :
void{
376 if($slot === $this->inventory->getHeldItemIndex()){
377 $this->setUsingItem(
false);
379 $this->callDummyItemHeldEvent();
383 $this->setUsingItem(
false);
384 $this->callDummyItemHeldEvent();
388 $now = (int) (microtime(
true) * 1000);
389 $createDateTimeImmutable =
static function(
string $tag) use ($nbt, $now) : DateTimeImmutable{
390 return new DateTimeImmutable(
'@' . $nbt->getLong($tag, $now) / 1000);
392 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
393 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
395 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
396 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
398 $this->internalSetGameMode($this->
server->getGamemode());
401 $this->keepMovement =
true;
403 $this->setNameTagVisible();
404 $this->setNameTagAlwaysVisible();
405 $this->setCanClimb();
407 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
408 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
410 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
411 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
415 public function getLeaveMessage() : Translatable|string{
417 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
423 public function isAuthenticated() : bool{
424 return $this->authenticated;
449 return parent::getUniqueId();
456 return $this->firstPlayed;
463 return $this->lastPlayed;
466 public function hasPlayedBefore() : bool{
467 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format(
'%s')) > 1;
480 if($this->allowFlight !== $value){
481 $this->allowFlight = $value;
482 $this->getNetworkSession()->syncAbilities($this);
493 return $this->allowFlight;
505 if($this->blockCollision !== $value){
506 $this->blockCollision = $value;
507 $this->getNetworkSession()->syncAbilities($this);
516 return $this->blockCollision;
519 public function setFlying(
bool $value) : void{
520 if($this->flying !== $value){
521 $this->flying = $value;
522 $this->resetFallDistance();
523 $this->getNetworkSession()->syncAbilities($this);
527 public function isFlying() : bool{
528 return $this->flying;
545 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
546 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
547 $this->getNetworkSession()->syncAbilities($this);
563 return $this->flightSpeedMultiplier;
566 public function setAutoJump(
bool $value) : void{
567 if($this->autoJump !== $value){
568 $this->autoJump = $value;
569 $this->getNetworkSession()->syncAdventureSettings();
573 public function hasAutoJump() : bool{
574 return $this->autoJump;
577 public function spawnTo(Player $player) : void{
578 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
579 parent::spawnTo($player);
583 public function getServer() : Server{
588 return $this->lineHeight ?? 7;
592 if($height !== null && $height < 1){
593 throw new \InvalidArgumentException(
"Line height must be at least 1");
595 $this->lineHeight = $height;
598 public function canSee(
Player $player) : bool{
599 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
602 public function hidePlayer(Player $player) : void{
603 if($player === $this){
606 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
607 $player->despawnFrom($this);
610 public function showPlayer(Player $player) : void{
611 if($player === $this){
614 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
615 if($player->isOnline()){
616 $player->spawnTo($this);
620 public function canCollideWith(Entity $entity) : bool{
624 public function canBeCollidedWith() : bool{
625 return !$this->isSpectator() && parent::canBeCollidedWith();
628 public function resetFallDistance() : void{
629 parent::resetFallDistance();
630 $this->inAirTicks = 0;
633 public function getViewDistance() : int{
634 return $this->viewDistance;
637 public function setViewDistance(
int $distance) : void{
638 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
640 if($newViewDistance !== $this->viewDistance){
641 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
645 $this->viewDistance = $newViewDistance;
647 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
649 $this->nextChunkOrderRun = 0;
651 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
653 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
656 public function isOnline() : bool{
657 return $this->isConnected();
660 public function isConnected() : bool{
661 return $this->networkSession !== null && $this->networkSession->isConnected();
664 public function getNetworkSession() : NetworkSession{
665 if($this->networkSession === null){
666 throw new \LogicException(
"Player is not connected");
668 return $this->networkSession;
675 return $this->username;
682 return $this->displayName;
685 public function setDisplayName(
string $name) : void{
689 $this->displayName = $ev->getNewName();
700 return $this->locale;
703 public function getLanguage() :
Language{
704 return $this->
server->getLanguage();
711 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
715 if($ev->isCancelled()){
716 $this->sendSkin([$this]);
720 $this->setSkin($ev->getNewSkin());
721 $this->sendSkin($this->server->getOnlinePlayers());
730 public function sendSkin(?array $targets =
null) : void{
731 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
738 return $this->startAction > -1;
741 public function setUsingItem(
bool $value) : void{
742 $this->startAction = $value ? $this->
server->getTick() : -1;
743 $this->networkPropertiesDirty =
true;
751 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
758 $this->checkItemCooldowns();
759 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
766 $this->checkItemCooldowns();
767 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
774 $ticks = $ticks ?? $item->getCooldownTicks();
776 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
777 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
781 protected function checkItemCooldowns() : void{
782 $serverTick = $this->
server->getTick();
783 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
784 if($cooldownUntil <= $serverTick){
785 unset($this->usedItemsCooldown[$itemId]);
790 protected function setPosition(Vector3 $pos) : bool{
791 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
792 if(parent::setPosition($pos)){
793 $newWorld = $this->getWorld();
794 if($oldWorld !== $newWorld){
795 if($oldWorld !==
null){
796 foreach($this->usedChunks as $index => $status){
797 World::getXZ($index, $X, $Z);
798 $this->unloadChunk($X, $Z, $oldWorld);
802 $this->usedChunks = [];
803 $this->loadQueue = [];
804 $this->getNetworkSession()->onEnterWorld();
813 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
814 $world = $world ?? $this->getWorld();
815 $index = World::chunkHash($x, $z);
816 if(isset($this->usedChunks[$index])){
817 foreach($world->getChunkEntities($x, $z) as $entity){
818 if($entity !== $this){
819 $entity->despawnFrom($this);
822 $this->getNetworkSession()->stopUsingChunk($x, $z);
823 unset($this->usedChunks[$index]);
824 unset($this->activeChunkGenerationRequests[$index]);
826 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
827 $world->unregisterChunkListener($this, $x, $z);
828 unset($this->loadQueue[$index]);
829 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
830 unset($this->tickingChunks[$index]);
833 protected function spawnEntitiesOnAllChunks() : void{
834 foreach($this->usedChunks as $chunkHash => $status){
835 if($status === UsedChunkStatus::SENT){
836 World::getXZ($chunkHash, $chunkX, $chunkZ);
837 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
842 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
843 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
844 if($entity !== $this && !$entity->isFlaggedForDespawn()){
845 $entity->spawnTo($this);
855 if(!$this->isConnected()){
859 Timings::$playerChunkSend->startTiming();
862 $world = $this->getWorld();
864 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
865 foreach($this->loadQueue as $index => $distance){
866 if($count >= $limit){
872 World::getXZ($index, $X, $Z);
876 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
877 $this->activeChunkGenerationRequests[$index] =
true;
878 unset($this->loadQueue[$index]);
879 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
880 $world->registerChunkListener($this, $X, $Z);
881 if(isset($this->tickingChunks[$index])){
882 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
885 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
886 function() use ($X, $Z, $index, $world) :
void{
887 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
890 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
896 unset($this->activeChunkGenerationRequests[$index]);
897 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
899 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
900 $this->usedChunks[$index] = UsedChunkStatus::SENT;
901 if($this->spawnChunkLoadCount === -1){
902 $this->spawnEntitiesOnChunk($X, $Z);
903 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
904 $this->spawnChunkLoadCount = -1;
906 $this->spawnEntitiesOnAllChunks();
908 $this->getNetworkSession()->notifyTerrainReady();
910 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
913 static function() :
void{
919 Timings::$playerChunkSend->stopTiming();
922 private function recheckBroadcastPermissions() : void{
924 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
925 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
926 ] as $permission => $channel){
927 if($this->hasPermission($permission)){
928 $this->
server->subscribeToBroadcastChannel($channel, $this);
930 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
943 $this->spawned =
true;
944 $this->recheckBroadcastPermissions();
945 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
946 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
947 $this->recheckBroadcastPermissions();
951 $ev =
new PlayerJoinEvent($this,
952 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
955 if($ev->getJoinMessage() !==
""){
956 $this->server->broadcastMessage($ev->getJoinMessage());
959 $this->noDamageTicks = 60;
963 if($this->getHealth() <= 0){
964 $this->logger->debug(
"Quit while dead, forcing respawn");
965 $this->actuallyRespawn();
976 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
977 $world = $this->getWorld();
978 foreach($oldTickingChunks as $hash => $_){
979 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
981 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
982 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
985 foreach($newTickingChunks as $hash => $_){
986 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
988 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
989 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
999 if(!$this->isConnected() || $this->viewDistance === -1){
1003 Timings::$playerChunkOrder->startTiming();
1006 $tickingChunks = [];
1007 $unloadChunks = $this->usedChunks;
1009 $world = $this->getWorld();
1010 $tickingChunkRadius = $world->getChunkTickRadius();
1012 foreach($this->chunkSelector->selectChunks(
1013 $this->server->getAllowedViewDistance($this->viewDistance),
1014 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1015 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1016 ) as $radius => $hash){
1017 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1018 $newOrder[$hash] =
true;
1020 if($radius < $tickingChunkRadius){
1021 $tickingChunks[$hash] =
true;
1023 unset($unloadChunks[$hash]);
1026 foreach($unloadChunks as $index => $status){
1027 World::getXZ($index, $X, $Z);
1028 $this->unloadChunk($X, $Z);
1031 $this->loadQueue = $newOrder;
1033 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1034 $this->tickingChunks = $tickingChunks;
1036 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1037 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1040 Timings::$playerChunkOrder->stopTiming();
1048 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1056 return $this->usedChunks;
1063 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1070 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1071 return $status === UsedChunkStatus::SENT;
1078 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1079 $this->nextChunkOrderRun = PHP_INT_MAX;
1080 $this->orderChunks();
1083 if(count($this->loadQueue) > 0){
1084 $this->requestChunks();
1088 public function getDeathPosition() : ?Position{
1089 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1090 $this->deathPosition =
null;
1092 return $this->deathPosition;
1100 if($pos instanceof
Position && $pos->world !==
null){
1101 $world = $pos->world;
1103 $world = $this->getWorld();
1105 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1107 $this->deathPosition =
null;
1109 $this->networkPropertiesDirty =
true;
1116 if($this->hasValidCustomSpawn()){
1117 return $this->spawnPosition;
1119 $world = $this->
server->getWorldManager()->getDefaultWorld();
1121 return $world->getSpawnLocation();
1125 public function hasValidCustomSpawn() : bool{
1126 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1138 $world = $this->getWorld();
1140 $world = $pos->getWorld();
1142 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1144 $this->spawnPosition =
null;
1146 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1149 public function isSleeping() : bool{
1150 return $this->sleeping !== null;
1153 public function sleepOn(Vector3 $pos) : bool{
1154 $pos = $pos->floor();
1155 $b = $this->getWorld()->getBlock($pos);
1157 $ev =
new PlayerBedEnterEvent($this, $b);
1159 if($ev->isCancelled()){
1163 if($b instanceof Bed){
1165 $this->getWorld()->setBlock($pos, $b);
1168 $this->sleeping = $pos;
1169 $this->networkPropertiesDirty =
true;
1171 $this->setSpawn($pos);
1173 $this->getWorld()->setSleepTicks(60);
1178 public function stopSleep() : void{
1179 if($this->sleeping instanceof Vector3){
1180 $b = $this->getWorld()->getBlock($this->sleeping);
1181 if($b instanceof Bed){
1182 $b->setOccupied(
false);
1183 $this->getWorld()->setBlock($this->sleeping, $b);
1185 (
new PlayerBedLeaveEvent($this, $b))->call();
1187 $this->sleeping =
null;
1188 $this->networkPropertiesDirty =
true;
1190 $this->getWorld()->setSleepTicks(0);
1192 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1196 public function getGamemode() : GameMode{
1197 return $this->gamemode;
1200 protected function internalSetGameMode(GameMode $gameMode) : void{
1201 $this->gamemode = $gameMode;
1203 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1204 $this->hungerManager->setEnabled($this->isSurvival());
1206 if($this->isSpectator()){
1207 $this->setFlying(
true);
1208 $this->setHasBlockCollision(
false);
1210 $this->onGround =
false;
1214 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1216 if($this->isSurvival()){
1217 $this->setFlying(
false);
1219 $this->setHasBlockCollision(
true);
1220 $this->setSilent(
false);
1221 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1229 if($this->gamemode === $gm){
1235 if($ev->isCancelled()){
1239 $this->internalSetGameMode($gm);
1241 if($this->isSpectator()){
1242 $this->despawnFromAll();
1244 $this->spawnToAll();
1247 $this->getNetworkSession()->syncGameMode($this->gamemode);
1258 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1268 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1278 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1281 public function isSpectator() : bool{
1282 return $this->gamemode === GameMode::SPECTATOR;
1289 return $this->gamemode !== GameMode::CREATIVE;
1293 if($this->hasFiniteResources()){
1294 return parent::getDrops();
1301 if($this->hasFiniteResources()){
1302 return parent::getXpDropAmount();
1308 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1309 if($this->gamemode === GameMode::SPECTATOR){
1310 $this->onGround =
false;
1312 $bb = clone $this->boundingBox;
1313 $bb->minY = $this->location->y - 0.2;
1314 $bb->maxY = $this->location->y + 0.2;
1318 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1320 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1328 protected function checkNearEntities() : void{
1329 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1330 $entity->scheduleUpdate();
1332 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1336 $entity->onCollideWithPlayer($this);
1340 public function getInAirTicks() : int{
1341 return $this->inAirTicks;
1353 Timings::$playerMove->startTiming();
1355 $this->actuallyHandleMovement($newPos);
1357 Timings::$playerMove->stopTiming();
1361 private function actuallyHandleMovement(Vector3 $newPos) : void{
1362 $this->moveRateLimit--;
1363 if($this->moveRateLimit < 0){
1367 $oldPos = $this->location;
1368 $distanceSquared = $newPos->distanceSquared($oldPos);
1372 if($distanceSquared > 225){
1384 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1385 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1387 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1389 $this->nextChunkOrderRun = 0;
1392 if(!$revert && $distanceSquared !== 0.0){
1393 $dx = $newPos->x - $oldPos->x;
1394 $dy = $newPos->y - $oldPos->y;
1395 $dz = $newPos->z - $oldPos->z;
1397 $this->move($dx, $dy, $dz);
1401 $this->revertMovement($oldPos);
1409 $now = microtime(true);
1410 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1411 $exceededRateLimit = $this->moveRateLimit < 0;
1412 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1413 $this->lastMovementProcess = $now;
1415 $from = clone $this->lastLocation;
1416 $to = clone $this->location;
1418 $delta = $to->distanceSquared($from);
1419 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1421 if($delta > 0.0001 || $deltaAngle > 1.0){
1422 if(PlayerMoveEvent::hasHandlers()){
1427 if($ev->isCancelled()){
1428 $this->revertMovement($from);
1432 if($to->distanceSquared($ev->getTo()) > 0.01){
1433 $this->teleport($ev->getTo());
1438 $this->lastLocation = $to;
1439 $this->broadcastMovement();
1441 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1442 if($horizontalDistanceTravelled > 0){
1444 if($this->isSprinting()){
1445 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, PlayerExhaustEvent::CAUSE_SPRINTING);
1447 $this->hungerManager->exhaust(0.0, PlayerExhaustEvent::CAUSE_WALKING);
1450 if($this->nextChunkOrderRun > 20){
1451 $this->nextChunkOrderRun = 20;
1456 if($exceededRateLimit){
1457 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1458 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1462 protected function revertMovement(Location $from) : void{
1463 $this->setPosition($from);
1464 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1467 protected function calculateFallDamage(
float $fallDistance) : float{
1468 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1476 public function setMotion(
Vector3 $motion) : bool{
1477 if(parent::setMotion($motion)){
1478 $this->broadcastMotion();
1479 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1486 protected function updateMovement(
bool $teleport =
false) : void{
1490 protected function tryChangeMovement() : void{
1494 public function onUpdate(int $currentTick) : bool{
1495 $tickDiff = $currentTick - $this->lastUpdate;
1501 $this->messageCounter = 2;
1503 $this->lastUpdate = $currentTick;
1505 if($this->justCreated){
1506 $this->onFirstUpdate($currentTick);
1509 if(!$this->isAlive() && $this->spawned){
1510 $this->onDeathUpdate($tickDiff);
1514 $this->timings->startTiming();
1517 Timings::$playerMove->startTiming();
1518 $this->processMostRecentMovements();
1519 $this->motion = Vector3::zero();
1520 if($this->onGround){
1521 $this->inAirTicks = 0;
1523 $this->inAirTicks += $tickDiff;
1525 Timings::$playerMove->stopTiming();
1527 Timings::$entityBaseTick->startTiming();
1528 $this->entityBaseTick($tickDiff);
1529 Timings::$entityBaseTick->stopTiming();
1531 if($this->isCreative() && $this->fireTicks > 1){
1532 $this->fireTicks = 1;
1535 if(!$this->isSpectator() && $this->isAlive()){
1536 Timings::$playerCheckNearEntities->startTiming();
1537 $this->checkNearEntities();
1538 Timings::$playerCheckNearEntities->stopTiming();
1541 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1542 $this->blockBreakHandler =
null;
1546 $this->timings->stopTiming();
1552 return $this->isCreative() || parent::canEat();
1556 return $this->isCreative() || parent::canBreathe();
1565 $eyePos = $this->getEyePos();
1566 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1570 $dV = $this->getDirectionVector();
1571 $eyeDot = $dV->dot($eyePos);
1572 $targetDot = $dV->dot($pos);
1573 return ($targetDot - $eyeDot) >= -$maxDiff;
1580 public function chat(
string $message) : bool{
1581 $this->removeCurrentWindow();
1583 if($this->messageCounter <= 0){
1589 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1590 if(strlen($message) > $maxTotalLength){
1594 $message = TextFormat::clean($message,
false);
1595 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1596 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1597 if(str_starts_with($messagePart,
'./')){
1598 $messagePart = substr($messagePart, 1);
1601 if(str_starts_with($messagePart,
"/")){
1602 Timings::$playerCommand->startTiming();
1603 $this->server->dispatchCommand($this, substr($messagePart, 1));
1604 Timings::$playerCommand->stopTiming();
1606 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1608 if(!$ev->isCancelled()){
1609 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1618 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1619 if(!$this->inventory->isHotbarSlot($hotbarSlot)){
1622 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1626 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1628 if($ev->isCancelled()){
1632 $this->inventory->setHeldItemIndex($hotbarSlot);
1633 $this->setUsingItem(
false);
1641 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1642 $heldItemChanged = false;
1644 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1647 $newReplica = clone $oldHeldItem;
1648 $newReplica->setCount($newHeldItem->getCount());
1649 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1650 $newReplica->setDamage($newHeldItem->getDamage());
1652 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1654 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1655 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1656 $this->broadcastSound(
new ItemBreakSound());
1658 $this->inventory->setItemInHand($newHeldItem);
1659 $heldItemChanged =
true;
1663 if(!$heldItemChanged){
1664 $newHeldItem = $oldHeldItem;
1667 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1668 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1670 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1672 $ev =
new PlayerDropItemEvent($this, $drop);
1673 if($this->isSpectator()){
1677 if(!$ev->isCancelled()){
1678 $this->dropItem($drop);
1689 $directionVector = $this->getDirectionVector();
1690 $item = $this->inventory->getItemInHand();
1691 $oldItem = clone $item;
1694 if($this->hasItemCooldown($item) || $this->isSpectator()){
1700 if($ev->isCancelled()){
1704 $returnedItems = [];
1705 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1706 if($result === ItemUseResult::FAIL){
1710 $this->resetItemCooldown($oldItem);
1711 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1713 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1724 $slot = $this->inventory->getItemInHand();
1726 $oldItem = clone $slot;
1729 if($this->hasItemCooldown($slot)){
1734 if($ev->isCancelled() || !$this->consumeObject($slot)){
1738 $this->setUsingItem(
false);
1739 $this->resetItemCooldown($oldItem);
1742 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1757 $item = $this->inventory->getItemInHand();
1758 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1762 $oldItem = clone $item;
1764 $returnedItems = [];
1765 $result = $item->onReleaseUsing($this, $returnedItems);
1766 if($result === ItemUseResult::SUCCESS){
1767 $this->resetItemCooldown($oldItem);
1768 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1774 $this->setUsingItem(
false);
1778 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1779 $block = $this->getWorld()->getBlock($pos);
1780 if($block instanceof UnknownBlock){
1784 $item = $block->getPickedItem($addTileNBT);
1786 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1787 $existingSlot = $this->inventory->first($item);
1788 if($existingSlot === -1 && $this->hasFiniteResources()){
1793 if(!$ev->isCancelled()){
1794 $this->equipOrAddPickedItem($existingSlot, $item);
1800 public function pickEntity(
int $entityId) : bool{
1801 $entity = $this->getWorld()->getEntity($entityId);
1802 if($entity ===
null){
1806 $item = $entity->getPickedItem();
1811 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1812 $existingSlot = $this->inventory->first($item);
1813 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1818 if(!$ev->isCancelled()){
1819 $this->equipOrAddPickedItem($existingSlot, $item);
1825 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1826 if($existingSlot !== -1){
1827 if($existingSlot < $this->inventory->getHotbarSize()){
1828 $this->inventory->setHeldItemIndex($existingSlot);
1830 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1833 $firstEmpty = $this->inventory->firstEmpty();
1834 if($firstEmpty === -1){
1835 $this->inventory->setItemInHand($item);
1836 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1837 $this->inventory->setItem($firstEmpty, $item);
1838 $this->inventory->setHeldItemIndex($firstEmpty);
1840 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1841 $this->inventory->setItemInHand($item);
1852 if($pos->distanceSquared($this->location) > 10000){
1856 $target = $this->getWorld()->getBlock($pos);
1858 $ev =
new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1859 if($this->isSpectator()){
1863 if($ev->isCancelled()){
1866 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1867 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1871 $block = $target->getSide($face);
1872 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1873 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1874 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1878 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1879 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1885 public function continueBreakBlock(Vector3 $pos,
int $face) : void{
1886 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1887 $this->blockBreakHandler->setTargetedFace($face);
1891 public function stopBreakBlock(Vector3 $pos) : void{
1892 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1893 $this->blockBreakHandler =
null;
1903 $this->removeCurrentWindow();
1905 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1906 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1907 $this->stopBreakBlock($pos);
1908 $item = $this->inventory->getItemInHand();
1909 $oldItem = clone $item;
1910 $returnedItems = [];
1911 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1912 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1913 $this->hungerManager->exhaust(0.005, PlayerExhaustEvent::CAUSE_MINING);
1917 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1929 $this->setUsingItem(false);
1931 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1932 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1933 $item = $this->inventory->getItemInHand();
1934 $oldItem = clone $item;
1935 $returnedItems = [];
1936 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1937 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1941 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1954 if(!$entity->isAlive()){
1958 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1962 $heldItem = $this->inventory->getItemInHand();
1963 $oldItem = clone $heldItem;
1965 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1966 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1967 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1969 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1973 $meleeEnchantmentDamage = 0;
1975 $meleeEnchantments = [];
1976 foreach($heldItem->getEnchantments() as $enchantment){
1977 $type = $enchantment->getType();
1978 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1979 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1980 $meleeEnchantments[] = $enchantment;
1983 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1985 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1986 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
1989 $entity->attack($ev);
1990 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1992 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1993 if($ev->isCancelled()){
1994 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
1997 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
1999 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2000 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2003 foreach($meleeEnchantments as $enchantment){
2004 $type = $enchantment->getType();
2005 assert($type instanceof MeleeWeaponEnchantment);
2006 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2009 if($this->isAlive()){
2012 $returnedItems = [];
2013 $heldItem->onAttackEntity($entity, $returnedItems);
2014 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2016 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
2029 if(!$ev->isCancelled()){
2030 $this->broadcastSound(new EntityAttackNoDamageSound());
2031 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2041 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2042 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2048 $item = $this->inventory->getItemInHand();
2049 $oldItem = clone $item;
2050 if(!$ev->isCancelled()){
2051 if($item->onInteractEntity($this, $entity, $clickPos)){
2052 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
2053 if($item instanceof Durable && $item->isBroken()){
2054 $this->broadcastSound(new ItemBreakSound());
2056 $this->inventory->setItemInHand($item);
2059 return $entity->
onInteract($this, $clickPos);
2064 public function toggleSprint(
bool $sprint) : bool{
2065 if($sprint === $this->sprinting){
2068 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2070 if($ev->isCancelled()){
2073 $this->setSprinting($sprint);
2077 public function toggleSneak(
bool $sneak) : bool{
2078 if($sneak === $this->sneaking){
2081 $ev =
new PlayerToggleSneakEvent($this, $sneak);
2083 if($ev->isCancelled()){
2086 $this->setSneaking($sneak);
2090 public function toggleFlight(
bool $fly) : bool{
2091 if($fly === $this->flying){
2094 $ev =
new PlayerToggleFlightEvent($this, $fly);
2095 if(!$this->allowFlight){
2099 if($ev->isCancelled()){
2102 $this->setFlying($fly);
2106 public function toggleGlide(
bool $glide) : bool{
2107 if($glide === $this->gliding){
2110 $ev =
new PlayerToggleGlideEvent($this, $glide);
2112 if($ev->isCancelled()){
2115 $this->setGliding($glide);
2119 public function toggleSwim(
bool $swim) : bool{
2120 if($swim === $this->swimming){
2123 $ev =
new PlayerToggleSwimEvent($this, $swim);
2125 if($ev->isCancelled()){
2128 $this->setSwimming($swim);
2132 public function emote(
string $emoteId) : void{
2133 $currentTick = $this->
server->getTick();
2134 if($currentTick - $this->lastEmoteTick > 5){
2135 $this->lastEmoteTick = $currentTick;
2136 $event =
new PlayerEmoteEvent($this, $emoteId);
2138 if(!$event->isCancelled()){
2139 $emoteId = $event->getEmoteId();
2140 parent::emote($emoteId);
2150 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2160 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2161 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2162 if($subtitle !==
""){
2163 $this->sendSubTitle($subtitle);
2165 $this->getNetworkSession()->onTitle($title);
2172 $this->getNetworkSession()->onSubTitle($subtitle);
2179 $this->getNetworkSession()->onActionBar($message);
2186 $this->getNetworkSession()->onClearTitle();
2193 $this->getNetworkSession()->onResetTitleOptions();
2204 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2205 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2213 $this->getNetworkSession()->onChatMessage($message);
2216 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2217 $this->getNetworkSession()->onJukeboxPopup($message);
2226 $this->getNetworkSession()->onPopup($message);
2229 public function sendTip(
string $message) : void{
2230 $this->getNetworkSession()->onTip($message);
2237 $this->getNetworkSession()->onToastNotification($title, $body);
2246 $id = $this->formIdCounter++;
2247 if($this->getNetworkSession()->onFormSent($id, $form)){
2248 $this->forms[$id] = $form;
2252 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2253 if(!isset($this->forms[$formId])){
2254 $this->logger->debug(
"Got unexpected response for form $formId");
2259 $this->forms[$formId]->handleResponse($this, $responseData);
2260 }
catch(FormValidationException $e){
2261 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2262 $this->logger->logException($e);
2264 unset($this->forms[$formId]);
2274 $this->getNetworkSession()->onCloseAllForms();
2289 if(!$ev->isCancelled()){
2290 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2305 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2307 if(!$ev->isCancelled()){
2308 $reason = $ev->getDisconnectReason();
2310 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2312 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2313 if($disconnectScreenMessage ===
""){
2314 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2316 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2338 if(!$this->isConnected()){
2342 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2343 $this->onPostDisconnect($reason, $quitMessage);
2354 if($this->isConnected()){
2355 throw new \LogicException(
"Player is still connected");
2359 $this->server->unsubscribeFromAllBroadcastChannels($this);
2361 $this->removeCurrentWindow();
2363 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2365 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2366 $this->server->broadcastMessage($quitMessage);
2370 $this->spawned =
false;
2373 $this->blockBreakHandler =
null;
2374 $this->despawnFromAll();
2376 $this->
server->removeOnlinePlayer($this);
2378 foreach($this->
server->getOnlinePlayers() as $player){
2379 if(!$player->canSee($this)){
2380 $player->showPlayer($this);
2383 $this->hiddenPlayers = [];
2385 if($this->location->isValid()){
2386 foreach($this->usedChunks as $index => $status){
2387 World::getXZ($index, $chunkX, $chunkZ);
2388 $this->unloadChunk($chunkX, $chunkZ);
2391 if(count($this->usedChunks) !== 0){
2392 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2394 $this->loadQueue = [];
2396 $this->removeCurrentWindow();
2397 $this->removePermanentInventories();
2399 $this->perm->getPermissionRecalculationCallbacks()->clear();
2401 $this->flagForDespawn();
2405 $this->disconnect(
"Player destroyed");
2406 $this->cursorInventory->removeAllViewers();
2407 $this->craftingGrid->removeAllViewers();
2408 parent::onDispose();
2412 $this->networkSession = null;
2413 unset($this->cursorInventory);
2414 unset($this->craftingGrid);
2415 $this->spawnPosition =
null;
2416 $this->deathPosition =
null;
2417 $this->blockBreakHandler =
null;
2418 parent::destroyCycles();
2428 public function __destruct(){
2429 parent::__destruct();
2430 $this->logger->debug(
"Destroyed by garbage collector");
2438 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2442 $nbt = $this->saveNBT();
2444 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2446 if($this->location->isValid()){
2447 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2450 if($this->hasValidCustomSpawn()){
2451 $spawn = $this->getSpawn();
2452 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2453 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2454 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2455 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2458 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2459 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2460 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2461 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2462 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2465 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2466 $nbt->
setLong(self::TAG_FIRST_PLAYED, (
int) $this->firstPlayed->format(
'Uv'));
2467 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2476 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2482 $this->removeCurrentWindow();
2484 $this->setDeathPosition($this->getPosition());
2486 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2489 if(!$ev->getKeepInventory()){
2490 foreach($ev->getDrops() as $item){
2491 $this->getWorld()->dropItem($this->location, $item);
2494 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2495 $this->inventory->setHeldItemIndex(0);
2496 $clearInventory($this->inventory);
2497 $clearInventory($this->armorInventory);
2498 $clearInventory($this->offHandInventory);
2501 if(!$ev->getKeepXp()){
2502 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2503 $this->xpManager->setXpAndProgress(0, 0.0);
2506 if($ev->getDeathMessage() !==
""){
2507 $this->server->broadcastMessage($ev->getDeathMessage());
2510 $this->startDeathAnimation();
2512 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2516 parent::onDeathUpdate($tickDiff);
2520 public function respawn() : void{
2521 if($this->
server->isHardcore()){
2522 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2523 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2528 $this->actuallyRespawn();
2531 protected function actuallyRespawn() : void{
2532 if($this->respawnLocked){
2535 $this->respawnLocked =
true;
2537 $this->logger->debug(
"Waiting for safe respawn position to be located");
2538 $spawn = $this->getSpawn();
2539 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2540 function(Position $safeSpawn) :
void{
2541 if(!$this->isConnected()){
2544 $this->logger->debug(
"Respawn position located, completing respawn");
2545 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2548 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2549 $this->teleport($realSpawn);
2551 $this->setSprinting(
false);
2552 $this->setSneaking(
false);
2553 $this->setFlying(
false);
2555 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2556 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2557 $this->deadTicks = 0;
2558 $this->noDamageTicks = 60;
2560 $this->effectManager->clear();
2561 $this->setHealth($this->getMaxHealth());
2563 foreach($this->attributeMap->getAll() as $attr){
2564 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2567 $attr->resetToDefault();
2570 $this->spawnToAll();
2571 $this->scheduleUpdate();
2573 $this->getNetworkSession()->onServerRespawn();
2574 $this->respawnLocked =
false;
2577 if($this->isConnected()){
2578 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2585 parent::applyPostDamageEffects($source);
2587 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2591 if(!$this->isAlive()){
2595 if($this->isCreative()
2596 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2599 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2603 parent::attack($source);
2606 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2607 parent::syncNetworkData($properties);
2609 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2610 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2612 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2613 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2615 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2616 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2618 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2619 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2621 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2622 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2623 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2627 public function sendData(?array $targets, ?array $data =
null) : void{
2628 if($targets === null){
2629 $targets = $this->getViewers();
2632 parent::sendData($targets, $data);
2636 if($this->spawned && $targets === null){
2637 $targets = $this->getViewers();
2640 parent::broadcastAnimation($animation, $targets);
2644 if($this->spawned && $targets === null){
2645 $targets = $this->getViewers();
2648 parent::broadcastSound($sound, $targets);
2654 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2655 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2661 if(parent::teleport($pos, $yaw, $pitch)){
2663 $this->removeCurrentWindow();
2666 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2667 $this->broadcastMovement(
true);
2669 $this->spawnToAll();
2671 $this->resetFallDistance();
2672 $this->nextChunkOrderRun = 0;
2673 if($this->spawnChunkLoadCount !== -1){
2674 $this->spawnChunkLoadCount = 0;
2676 $this->blockBreakHandler =
null;
2680 $this->resetLastMovements();
2688 protected function addDefaultWindows() : void{
2689 $this->cursorInventory = new PlayerCursorInventory($this);
2690 $this->craftingGrid =
new PlayerCraftingInventory($this);
2692 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2697 public function getCursorInventory() : PlayerCursorInventory{
2698 return $this->cursorInventory;
2701 public function getCraftingGrid() : CraftingGrid{
2702 return $this->craftingGrid;
2710 return $this->creativeInventory;
2717 $this->creativeInventory = $inventory;
2718 if($this->spawned && $this->isConnected()){
2719 $this->getNetworkSession()->getInvManager()?->syncCreative();
2727 private function doCloseInventory() : void{
2728 $inventories = [$this->craftingGrid, $this->cursorInventory];
2729 if($this->currentWindow instanceof TemporaryInventory){
2730 $inventories[] = $this->currentWindow;
2733 $builder =
new TransactionBuilder();
2734 foreach($inventories as $inventory){
2735 $contents = $inventory->getContents();
2737 if(count($contents) > 0){
2738 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2739 foreach($drops as $drop){
2740 $builder->addAction(
new DropItemAction($drop));
2743 $builder->getInventory($inventory)->clearAll();
2747 $actions = $builder->generateActions();
2748 if(count($actions) !== 0){
2749 $transaction =
new InventoryTransaction($this, $actions);
2751 $transaction->execute();
2752 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2753 }
catch(TransactionCancelledException){
2754 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2755 foreach($inventories as $inventory){
2756 $inventory->clearAll();
2758 }
catch(TransactionValidationException $e){
2759 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2768 return $this->currentWindow;
2775 if($inventory === $this->currentWindow){
2780 if($ev->isCancelled()){
2784 $this->removeCurrentWindow();
2786 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2787 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2789 $this->logger->debug(
"Opening inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
2790 $inventoryManager->onCurrentWindowChange($inventory);
2791 $inventory->onOpen($this);
2792 $this->currentWindow = $inventory;
2796 public function removeCurrentWindow() : void{
2797 $this->doCloseInventory();
2798 if($this->currentWindow !==
null){
2799 $currentWindow = $this->currentWindow;
2800 $this->logger->debug(
"Closing inventory " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2801 $this->currentWindow->onClose($this);
2802 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2803 $inventoryManager->onCurrentWindowRemove();
2805 $this->currentWindow =
null;
2806 (
new InventoryCloseEvent($currentWindow, $this))->call();
2810 protected function addPermanentInventories(Inventory ...$inventories) : void{
2811 foreach($inventories as $inventory){
2812 $inventory->onOpen($this);
2813 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2817 protected function removePermanentInventories() : void{
2818 foreach($this->permanentWindows as $inventory){
2819 $inventory->onClose($this);
2821 $this->permanentWindows = [];
2829 $block = $this->getWorld()->getBlock($position);
2831 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2832 $this->getNetworkSession()->onOpenSignEditor($position,
true);
2834 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2838 use ChunkListenerNoOpTrait {
2839 onChunkChanged as
private;
2840 onChunkUnloaded as
private;
2844 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2845 if($status === UsedChunkStatus::SENT){
2846 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2847 $this->nextChunkOrderRun = 0;
2852 if($this->isUsingChunk($chunkX, $chunkZ)){
2853 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2854 $this->unloadChunk($chunkX, $chunkZ);