178 use PermissibleDelegateTrait;
180 private const MOVES_PER_TICK = 2;
181 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
184 private const MAX_CHAT_CHAR_LENGTH = 512;
190 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
191 private const MAX_REACH_DISTANCE_CREATIVE = 13;
192 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
193 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
195 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
197 public const TAG_FIRST_PLAYED =
"firstPlayed";
198 public const TAG_LAST_PLAYED =
"lastPlayed";
199 private const TAG_GAME_MODE =
"playerGameType";
200 private const TAG_SPAWN_WORLD =
"SpawnLevel";
201 private const TAG_SPAWN_X =
"SpawnX";
202 private const TAG_SPAWN_Y =
"SpawnY";
203 private const TAG_SPAWN_Z =
"SpawnZ";
204 private const TAG_DEATH_WORLD =
"DeathLevel";
205 private const TAG_DEATH_X =
"DeathPositionX";
206 private const TAG_DEATH_Y =
"DeathPositionY";
207 private const TAG_DEATH_Z =
"DeathPositionZ";
208 public const TAG_LEVEL =
"Level";
209 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
219 $lname = strtolower($name);
220 $len = strlen($name);
221 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
226 public bool $spawned =
false;
228 protected string $username;
229 protected string $displayName;
230 protected string $xuid =
"";
231 protected bool $authenticated;
234 protected ?InventoryWindow $currentWindow =
null;
236 protected array $permanentWindows = [];
237 protected Inventory $cursorInventory;
238 protected CraftingGrid $craftingGrid;
239 protected CreativeInventory $creativeInventory;
241 protected int $messageCounter = 2;
243 protected DateTimeImmutable $firstPlayed;
244 protected DateTimeImmutable $lastPlayed;
245 protected GameMode $gamemode;
251 protected array $usedChunks = [];
256 private array $activeChunkGenerationRequests = [];
261 protected array $loadQueue = [];
262 protected int $nextChunkOrderRun = 5;
265 private array $tickingChunks = [];
267 protected int $viewDistance = -1;
268 protected int $spawnThreshold;
269 protected int $spawnChunkLoadCount = 0;
270 protected int $chunksPerTick;
271 protected ChunkSelector $chunkSelector;
272 protected ChunkLoader $chunkLoader;
273 protected ChunkTicker $chunkTicker;
276 protected array $hiddenPlayers = [];
278 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
279 protected ?
float $lastMovementProcess =
null;
281 protected int $inAirTicks = 0;
283 protected float $stepHeight = 0.6;
285 protected ?Vector3 $sleeping =
null;
286 private ?
Position $spawnPosition =
null;
288 private bool $respawnLocked =
false;
290 private ?
Position $deathPosition =
null;
293 protected bool $autoJump =
true;
294 protected bool $allowFlight =
false;
295 protected bool $blockCollision =
true;
296 protected bool $flying =
false;
297 protected bool $sneakPressed =
false;
299 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
302 protected ?
int $lineHeight =
null;
305 protected string $locale =
"en_US";
307 protected int $startAction = -1;
313 protected array $usedItemsCooldown = [];
315 private int $lastEmoteTick = 0;
317 protected int $formIdCounter = 0;
319 protected array $forms = [];
321 protected \Logger $logger;
326 $username = TextFormat::clean($playerInfo->getUsername());
327 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
330 $this->networkSession = $session;
331 $this->playerInfo = $playerInfo;
332 $this->authenticated = $authenticated;
334 $this->username = $username;
335 $this->displayName = $this->username;
336 $this->locale = $this->playerInfo->getLocale();
338 $this->uuid = $this->playerInfo->getUuid();
339 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
341 $this->creativeInventory = CreativeInventory::getInstance();
343 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
344 if($this->
server->isOp($this->username)){
345 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
350 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
351 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
356 $world = $spawnLocation->
getWorld();
358 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
359 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
360 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
361 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
362 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
364 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
368 $this->setNameTag($this->username);
371 private function callDummyItemHeldEvent() : void{
372 $slot = $this->hotbar->getSelectedIndex();
381 protected function initEntity(
CompoundTag $nbt) : void{
382 parent::initEntity($nbt);
383 $this->addDefaultWindows();
385 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
386 function(Inventory $unused,
int $slot) :
void{
387 if($slot === $this->hotbar->getSelectedIndex()){
388 $this->setUsingItem(
false);
390 $this->callDummyItemHeldEvent();
394 $this->setUsingItem(
false);
395 $this->callDummyItemHeldEvent();
399 $now = (int) (microtime(
true) * 1000);
400 $createDateTimeImmutable =
static function(
string $tag) use ($nbt, $now) : DateTimeImmutable{
401 return new DateTimeImmutable(
'@' . $nbt->getLong($tag, $now) / 1000);
403 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
404 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
406 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
407 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
409 $this->internalSetGameMode($this->
server->getGamemode());
412 $this->keepMovement =
true;
414 $this->setNameTagVisible();
415 $this->setNameTagAlwaysVisible();
416 $this->setCanClimb();
418 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
419 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
421 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
422 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
426 public function getLeaveMessage() : Translatable|string{
428 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
434 public function isAuthenticated() : bool{
435 return $this->authenticated;
460 return parent::getUniqueId();
467 return $this->firstPlayed;
474 return $this->lastPlayed;
477 public function hasPlayedBefore() : bool{
478 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format(
'%s')) > 1;
491 if($this->allowFlight !== $value){
492 $this->allowFlight = $value;
493 $this->getNetworkSession()->syncAbilities($this);
504 return $this->allowFlight;
516 if($this->blockCollision !== $value){
517 $this->blockCollision = $value;
518 $this->getNetworkSession()->syncAbilities($this);
527 return $this->blockCollision;
530 public function setFlying(
bool $value) : void{
531 if($this->flying !== $value){
532 $this->flying = $value;
533 $this->resetFallDistance();
534 $this->getNetworkSession()->syncAbilities($this);
538 public function isFlying() : bool{
539 return $this->flying;
556 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
557 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
558 $this->getNetworkSession()->syncAbilities($this);
574 return $this->flightSpeedMultiplier;
577 public function setAutoJump(
bool $value) : void{
578 if($this->autoJump !== $value){
579 $this->autoJump = $value;
580 $this->getNetworkSession()->syncAdventureSettings();
584 public function hasAutoJump() : bool{
585 return $this->autoJump;
588 public function spawnTo(Player $player) : void{
589 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
590 parent::spawnTo($player);
594 public function getServer() : Server{
599 return $this->lineHeight ?? 7;
603 if($height !== null && $height < 1){
604 throw new \InvalidArgumentException(
"Line height must be at least 1");
606 $this->lineHeight = $height;
611 public function canSee(
Player $player) : bool{
612 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
615 public function hidePlayer(
Player $player) : void{
616 if($player === $this){
619 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
620 $player->despawnFrom($this);
623 public function showPlayer(Player $player) : void{
624 if($player === $this){
627 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
628 if($player->isOnline()){
629 $player->spawnTo($this);
633 public function canCollideWith(Entity $entity) : bool{
637 public function canBeCollidedWith() : bool{
638 return !$this->isSpectator() && parent::canBeCollidedWith();
641 public function resetFallDistance() : void{
642 parent::resetFallDistance();
643 $this->inAirTicks = 0;
646 public function getViewDistance() : int{
647 return $this->viewDistance;
650 public function setViewDistance(
int $distance) : void{
651 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
653 if($newViewDistance !== $this->viewDistance){
654 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
658 $this->viewDistance = $newViewDistance;
660 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
662 $this->nextChunkOrderRun = 0;
664 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
666 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
669 public function isOnline() : bool{
670 return $this->isConnected();
673 public function isConnected() : bool{
674 return $this->networkSession !== null && $this->networkSession->isConnected();
677 public function getNetworkSession() : NetworkSession{
678 if($this->networkSession === null){
679 throw new \LogicException(
"Player is not connected");
681 return $this->networkSession;
688 return $this->username;
695 return $this->displayName;
698 public function setDisplayName(
string $name) : void{
702 $this->displayName = $ev->getNewName();
713 return $this->locale;
716 public function getLanguage() :
Language{
717 return $this->
server->getLanguage();
724 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
728 if($ev->isCancelled()){
729 $this->sendSkin([$this]);
733 $this->setSkin($ev->getNewSkin());
734 $this->sendSkin($this->server->getOnlinePlayers());
743 public function sendSkin(?array $targets =
null) : void{
744 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
751 return $this->startAction > -1;
754 public function setUsingItem(
bool $value) : void{
755 $this->startAction = $value ? $this->
server->getTick() : -1;
756 $this->networkPropertiesDirty =
true;
764 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
771 $this->checkItemCooldowns();
772 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
779 $this->checkItemCooldowns();
780 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
787 $ticks = $ticks ?? $item->getCooldownTicks();
789 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
790 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
798 if($this->hasItemCooldown($item)){
799 unset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
800 $this->getNetworkSession()->onItemCooldownChanged($item, 0);
804 protected function checkItemCooldowns() : void{
805 $serverTick = $this->
server->getTick();
806 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
807 if($cooldownUntil <= $serverTick){
808 unset($this->usedItemsCooldown[$itemId]);
813 protected function setPosition(Vector3 $pos) : bool{
814 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
815 if(parent::setPosition($pos)){
816 $newWorld = $this->getWorld();
817 if($oldWorld !== $newWorld){
818 if($oldWorld !==
null){
819 foreach($this->usedChunks as $index => $status){
820 World::getXZ($index, $X, $Z);
821 $this->unloadChunk($X, $Z, $oldWorld);
825 $this->usedChunks = [];
826 $this->loadQueue = [];
827 $this->getNetworkSession()->onEnterWorld();
836 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
837 $world = $world ?? $this->getWorld();
838 $index = World::chunkHash($x, $z);
839 if(isset($this->usedChunks[$index])){
840 foreach($world->getChunkEntities($x, $z) as $entity){
841 if($entity !== $this){
842 $entity->despawnFrom($this);
845 $this->getNetworkSession()->stopUsingChunk($x, $z);
846 unset($this->usedChunks[$index]);
847 unset($this->activeChunkGenerationRequests[$index]);
849 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
850 $world->unregisterChunkListener($this, $x, $z);
851 unset($this->loadQueue[$index]);
852 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
853 unset($this->tickingChunks[$index]);
856 protected function spawnEntitiesOnAllChunks() : void{
857 foreach($this->usedChunks as $chunkHash => $status){
858 if($status === UsedChunkStatus::SENT){
859 World::getXZ($chunkHash, $chunkX, $chunkZ);
860 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
865 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
866 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
867 if($entity !== $this && !$entity->isFlaggedForDespawn()){
868 $entity->spawnTo($this);
878 if(!$this->isConnected()){
882 Timings::$playerChunkSend->startTiming();
885 $world = $this->getWorld();
887 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
888 foreach($this->loadQueue as $index => $distance){
889 if($count >= $limit){
895 World::getXZ($index, $X, $Z);
899 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
900 $this->activeChunkGenerationRequests[$index] =
true;
901 unset($this->loadQueue[$index]);
902 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
903 $world->registerChunkListener($this, $X, $Z);
904 if(isset($this->tickingChunks[$index])){
905 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
908 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
909 function() use ($X, $Z, $index, $world) :
void{
910 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
913 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
919 unset($this->activeChunkGenerationRequests[$index]);
920 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
922 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
923 $this->usedChunks[$index] = UsedChunkStatus::SENT;
924 if($this->spawnChunkLoadCount === -1){
925 $this->spawnEntitiesOnChunk($X, $Z);
926 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
927 $this->spawnChunkLoadCount = -1;
929 $this->spawnEntitiesOnAllChunks();
931 $this->getNetworkSession()->notifyTerrainReady();
933 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
936 static function() :
void{
942 Timings::$playerChunkSend->stopTiming();
945 private function recheckBroadcastPermissions() : void{
947 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
948 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
949 ] as $permission => $channel){
950 if($this->hasPermission($permission)){
951 $this->
server->subscribeToBroadcastChannel($channel, $this);
953 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
966 $this->spawned =
true;
967 $this->recheckBroadcastPermissions();
968 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
969 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
970 $this->recheckBroadcastPermissions();
974 $ev =
new PlayerJoinEvent($this,
975 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
978 if($ev->getJoinMessage() !==
""){
979 $this->server->broadcastMessage($ev->getJoinMessage());
982 $this->noDamageTicks = 60;
986 if($this->getHealth() <= 0){
987 $this->logger->debug(
"Quit while dead, forcing respawn");
988 $this->actuallyRespawn();
999 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
1000 $world = $this->getWorld();
1001 foreach($oldTickingChunks as $hash => $_){
1002 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
1004 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
1005 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
1008 foreach($newTickingChunks as $hash => $_){
1009 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
1011 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
1012 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
1022 if(!$this->isConnected() || $this->viewDistance === -1){
1026 Timings::$playerChunkOrder->startTiming();
1029 $tickingChunks = [];
1030 $unloadChunks = $this->usedChunks;
1032 $world = $this->getWorld();
1033 $tickingChunkRadius = $world->getChunkTickRadius();
1035 foreach($this->chunkSelector->selectChunks(
1036 $this->server->getAllowedViewDistance($this->viewDistance),
1037 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1038 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1039 ) as $radius => $hash){
1040 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1041 $newOrder[$hash] =
true;
1043 if($radius < $tickingChunkRadius){
1044 $tickingChunks[$hash] =
true;
1046 unset($unloadChunks[$hash]);
1049 foreach($unloadChunks as $index => $status){
1050 World::getXZ($index, $X, $Z);
1051 $this->unloadChunk($X, $Z);
1054 $this->loadQueue = $newOrder;
1056 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1057 $this->tickingChunks = $tickingChunks;
1059 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1060 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1063 Timings::$playerChunkOrder->stopTiming();
1071 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1079 return $this->usedChunks;
1086 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1093 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1094 return $status === UsedChunkStatus::SENT;
1101 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1102 $this->nextChunkOrderRun = PHP_INT_MAX;
1103 $this->orderChunks();
1106 if(count($this->loadQueue) > 0){
1107 $this->requestChunks();
1111 public function getDeathPosition() : ?Position{
1112 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1113 $this->deathPosition =
null;
1115 return $this->deathPosition;
1123 if($pos instanceof
Position && $pos->world !==
null){
1124 $world = $pos->world;
1126 $world = $this->getWorld();
1128 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1130 $this->deathPosition =
null;
1132 $this->networkPropertiesDirty =
true;
1139 if($this->hasValidCustomSpawn()){
1140 return $this->spawnPosition;
1142 $world = $this->
server->getWorldManager()->getDefaultWorld();
1144 return $world->getSpawnLocation();
1148 public function hasValidCustomSpawn() : bool{
1149 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1161 $world = $this->getWorld();
1163 $world = $pos->getWorld();
1165 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1167 $this->spawnPosition =
null;
1169 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1172 public function isSleeping() : bool{
1173 return $this->sleeping !== null;
1176 public function sleepOn(Vector3 $pos) : bool{
1177 $pos = $pos->floor();
1178 $b = $this->getWorld()->getBlock($pos);
1180 $ev =
new PlayerBedEnterEvent($this, $b);
1182 if($ev->isCancelled()){
1186 if($b instanceof Bed){
1188 $this->getWorld()->setBlock($pos, $b);
1191 $this->sleeping = $pos;
1192 $this->networkPropertiesDirty =
true;
1194 $this->setSpawn($pos);
1196 $this->getWorld()->setSleepTicks(60);
1201 public function stopSleep() : void{
1202 if($this->sleeping instanceof Vector3){
1203 $b = $this->getWorld()->getBlock($this->sleeping);
1204 if($b instanceof Bed){
1205 $b->setOccupied(
false);
1206 $this->getWorld()->setBlock($this->sleeping, $b);
1208 (
new PlayerBedLeaveEvent($this, $b))->call();
1210 $this->sleeping =
null;
1211 $this->networkPropertiesDirty =
true;
1213 $this->getWorld()->setSleepTicks(0);
1215 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1219 public function getGamemode() : GameMode{
1220 return $this->gamemode;
1223 protected function internalSetGameMode(GameMode $gameMode) : void{
1224 $this->gamemode = $gameMode;
1226 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1227 $this->hungerManager->setEnabled($this->isSurvival());
1229 if($this->isSpectator()){
1230 $this->setFlying(
true);
1231 $this->setHasBlockCollision(
false);
1233 $this->onGround =
false;
1237 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1239 if($this->isSurvival()){
1240 $this->setFlying(
false);
1242 $this->setHasBlockCollision(
true);
1243 $this->setSilent(
false);
1244 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1252 if($this->gamemode === $gm){
1258 if($ev->isCancelled()){
1262 $this->internalSetGameMode($gm);
1264 if($this->isSpectator()){
1265 $this->despawnFromAll();
1267 $this->spawnToAll();
1270 $this->getNetworkSession()->syncGameMode($this->gamemode);
1281 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1291 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1301 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1304 public function isSpectator() : bool{
1305 return $this->gamemode === GameMode::SPECTATOR;
1308 public function setSneakPressed(
bool $sneakPressed) : void{
1309 $this->sneakPressed = $sneakPressed;
1317 return $this->sneakPressed;
1324 return $this->gamemode !== GameMode::CREATIVE;
1328 if($this->hasFiniteResources()){
1329 return parent::getDrops();
1336 if($this->hasFiniteResources()){
1337 return parent::getXpDropAmount();
1343 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1344 if(!$this->blockCollision){
1345 $this->onGround =
false;
1348 $bb =
new AxisAlignedBB(
1349 $this->boundingBox->minX,
1350 $this->location->y - 0.2,
1351 $this->boundingBox->minZ,
1352 $this->boundingBox->maxX,
1353 $this->location->y + 0.2,
1354 $this->boundingBox->maxZ
1359 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1361 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1369 protected function checkNearEntities() : void{
1370 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1371 $entity->scheduleUpdate();
1373 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1377 $entity->onCollideWithPlayer($this);
1381 public function getInAirTicks() : int{
1382 return $this->inAirTicks;
1394 Timings::$playerMove->startTiming();
1396 $this->actuallyHandleMovement($newPos);
1398 Timings::$playerMove->stopTiming();
1402 private function actuallyHandleMovement(Vector3 $newPos) : void{
1403 $this->moveRateLimit--;
1404 if($this->moveRateLimit < 0){
1408 $oldPos = $this->location;
1409 $distanceSquared = $newPos->distanceSquared($oldPos);
1413 if($distanceSquared > 225){
1425 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1426 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1428 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1430 $this->nextChunkOrderRun = 0;
1433 if(!$revert && $distanceSquared !== 0.0){
1434 $dx = $newPos->x - $oldPos->x;
1435 $dy = $newPos->y - $oldPos->y;
1436 $dz = $newPos->z - $oldPos->z;
1438 $this->move($dx, $dy, $dz);
1442 $this->revertMovement($oldPos);
1450 $now = microtime(true);
1451 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1452 $exceededRateLimit = $this->moveRateLimit < 0;
1453 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1454 $this->lastMovementProcess = $now;
1456 $from = clone $this->lastLocation;
1457 $to = clone $this->location;
1459 $delta = $to->distanceSquared($from);
1460 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1462 if($delta > 0.0001 || $deltaAngle > 1.0){
1463 if(PlayerMoveEvent::hasHandlers()){
1468 if($ev->isCancelled()){
1469 $this->revertMovement($from);
1473 if($to->distanceSquared($ev->getTo()) > 0.01){
1474 $this->teleport($ev->getTo());
1479 $this->lastLocation = $to;
1480 $this->broadcastMovement();
1482 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1483 if($horizontalDistanceTravelled > 0){
1485 if($this->isSprinting()){
1486 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, EntityExhaustEvent::CAUSE_SPRINTING);
1488 $this->hungerManager->exhaust(0.0, EntityExhaustEvent::CAUSE_WALKING);
1491 if($this->nextChunkOrderRun > 20){
1492 $this->nextChunkOrderRun = 20;
1497 if($exceededRateLimit){
1498 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1499 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1503 protected function revertMovement(Location $from) : void{
1504 $this->setPosition($from);
1505 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1508 protected function calculateFallDamage(
float $fallDistance) : float{
1509 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1517 public function setMotion(
Vector3 $motion) : bool{
1518 if(parent::setMotion($motion)){
1519 $this->broadcastMotion();
1520 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1527 protected function updateMovement(
bool $teleport =
false) : void{
1531 protected function tryChangeMovement() : void{
1535 public function onUpdate(int $currentTick) : bool{
1536 $tickDiff = $currentTick - $this->lastUpdate;
1542 $this->messageCounter = 2;
1544 $this->lastUpdate = $currentTick;
1546 if($this->justCreated){
1547 $this->onFirstUpdate($currentTick);
1550 if(!$this->isAlive() && $this->spawned){
1551 $this->onDeathUpdate($tickDiff);
1555 $this->timings->startTiming();
1558 Timings::$playerMove->startTiming();
1559 $this->processMostRecentMovements();
1560 $this->motion = Vector3::zero();
1561 if($this->onGround){
1562 $this->inAirTicks = 0;
1564 $this->inAirTicks += $tickDiff;
1566 Timings::$playerMove->stopTiming();
1568 Timings::$entityBaseTick->startTiming();
1569 $this->entityBaseTick($tickDiff);
1570 Timings::$entityBaseTick->stopTiming();
1572 if($this->isCreative() && $this->fireTicks > 1){
1573 $this->fireTicks = 1;
1576 if(!$this->isSpectator() && $this->isAlive()){
1577 Timings::$playerCheckNearEntities->startTiming();
1578 $this->checkNearEntities();
1579 Timings::$playerCheckNearEntities->stopTiming();
1582 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1583 $this->blockBreakHandler =
null;
1586 if($this->isUsingItem() && $this->getItemUseDuration() % 4 === 0 && ($item = $this->getMainHandItem()) instanceof ConsumableItem){
1587 $this->broadcastAnimation(
new ConsumingItemAnimation($this, $item));
1591 $this->timings->stopTiming();
1597 return $this->isCreative() || parent::canEat();
1601 return $this->isCreative() || parent::canBreathe();
1610 $eyePos = $this->getEyePos();
1611 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1615 $dV = $this->getDirectionVector();
1616 $eyeDot = $dV->dot($eyePos);
1617 $targetDot = $dV->dot($pos);
1618 return ($targetDot - $eyeDot) >= -$maxDiff;
1625 public function chat(
string $message) : bool{
1626 $this->removeCurrentWindow();
1628 if($this->messageCounter <= 0){
1634 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1635 if(strlen($message) > $maxTotalLength){
1639 $message = TextFormat::clean($message,
false);
1640 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1641 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1642 if(str_starts_with($messagePart,
'./')){
1643 $messagePart = substr($messagePart, 1);
1646 if(str_starts_with($messagePart,
"/")){
1647 Timings::$playerCommand->startTiming();
1648 $this->server->dispatchCommand($this, substr($messagePart, 1));
1649 Timings::$playerCommand->stopTiming();
1651 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1653 if(!$ev->isCancelled()){
1654 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1663 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1664 if(!$this->hotbar->isHotbarSlot($hotbarSlot)){
1667 if($hotbarSlot === $this->hotbar->getSelectedIndex()){
1671 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1673 if($ev->isCancelled()){
1677 $this->hotbar->setSelectedIndex($hotbarSlot);
1678 $this->setUsingItem(
false);
1686 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1687 $heldItemChanged = false;
1689 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->getMainHandItem())){
1692 $newReplica = clone $oldHeldItem;
1693 $newReplica->setCount($newHeldItem->getCount());
1694 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1695 $newDamage = $newHeldItem->getDamage();
1696 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1697 $newReplica->setDamage($newDamage);
1700 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1702 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1703 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1704 $this->broadcastSound(
new ItemBreakSound());
1706 $this->setMainHandItem($newHeldItem);
1707 $heldItemChanged =
true;
1711 if(!$heldItemChanged){
1712 $newHeldItem = $oldHeldItem;
1715 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1716 $this->setMainHandItem(array_shift($extraReturnedItems));
1718 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1720 $ev =
new PlayerDropItemEvent($this, $drop);
1721 if($this->isSpectator()){
1725 if(!$ev->isCancelled()){
1726 $this->dropItem($drop);
1737 $directionVector = $this->getDirectionVector();
1738 $item = $this->getMainHandItem();
1739 $oldItem = clone $item;
1742 if($this->hasItemCooldown($item) || $this->isSpectator()){
1748 if($ev->isCancelled()){
1752 $returnedItems = [];
1753 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1754 if($result === ItemUseResult::FAIL){
1758 $this->resetItemCooldown($oldItem);
1759 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1761 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1772 $slot = $this->getMainHandItem();
1774 $oldItem = clone $slot;
1776 $residue = $slot->getResidue();
1778 if($this->hasItemCooldown($slot)){
1783 if($ev->isCancelled() || !$this->consumeObject($slot)){
1787 $this->setUsingItem(
false);
1788 $this->resetItemCooldown($oldItem);
1791 $this->returnItemsFromAction($oldItem, $slot, $ev->getResidue());
1806 $item = $this->getMainHandItem();
1807 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1811 $oldItem = clone $item;
1813 $returnedItems = [];
1814 $result = $item->onReleaseUsing($this, $returnedItems);
1815 if($result === ItemUseResult::SUCCESS){
1816 $this->resetItemCooldown($oldItem);
1817 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1823 $this->setUsingItem(
false);
1827 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1828 $block = $this->getWorld()->getBlock($pos);
1829 if($block instanceof UnknownBlock){
1833 $item = $block->getPickedItem($addTileNBT);
1835 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1836 $existingSlot = $this->inventory->first($item);
1837 if($existingSlot === -1 && $this->hasFiniteResources()){
1842 if(!$ev->isCancelled()){
1843 $this->equipOrAddPickedItem($existingSlot, $item);
1849 public function pickEntity(
int $entityId) : bool{
1850 $entity = $this->getWorld()->getEntity($entityId);
1853 if($entity ===
null || $entity->isFlaggedForDespawn()){
1857 $item = $entity->getPickedItem();
1862 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1863 $existingSlot = $this->inventory->first($item);
1864 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1869 if(!$ev->isCancelled()){
1870 $this->equipOrAddPickedItem($existingSlot, $item);
1876 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1877 if($existingSlot !== -1){
1878 if($existingSlot < $this->hotbar->getSize()){
1879 $this->hotbar->setSelectedIndex($existingSlot);
1881 $this->inventory->swap($this->hotbar->getSelectedIndex(), $existingSlot);
1884 $firstEmpty = $this->inventory->firstEmpty();
1885 if($firstEmpty === -1){
1886 $this->setMainHandItem($item);
1887 }elseif($firstEmpty < $this->hotbar->getSize()){
1888 $this->inventory->setItem($firstEmpty, $item);
1889 $this->hotbar->setSelectedIndex($firstEmpty);
1891 $this->inventory->swap($this->hotbar->getSelectedIndex(), $firstEmpty);
1892 $this->setMainHandItem($item);
1903 if($pos->distanceSquared($this->location) > 10000){
1907 $target = $this->getWorld()->getBlock($pos);
1909 $ev =
new PlayerInteractEvent($this, $this->getMainHandItem(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1910 if($this->isSpectator()){
1914 if($ev->isCancelled()){
1917 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1918 if($target->onAttack($this->getMainHandItem(), $face, $this)){
1922 $block = $target->getSide($face);
1923 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1924 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1925 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1929 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1930 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1936 public function continueBreakBlock(Vector3 $pos, Facing $face) : void{
1937 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1938 $this->blockBreakHandler->setTargetedFace($face);
1942 public function stopBreakBlock(Vector3 $pos) : void{
1943 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1944 $this->blockBreakHandler =
null;
1954 $this->removeCurrentWindow();
1956 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1957 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1958 $this->stopBreakBlock($pos);
1959 $item = $this->getMainHandItem();
1960 $oldItem = clone $item;
1961 $returnedItems = [];
1962 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1963 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1964 $this->hungerManager->exhaust(0.005, EntityExhaustEvent::CAUSE_MINING);
1968 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1980 $this->setUsingItem(false);
1982 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1983 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1984 $item = $this->getMainHandItem();
1985 $oldItem = clone $item;
1986 $returnedItems = [];
1987 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1988 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1992 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
2005 if(!$entity->isAlive()){
2009 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
2013 $heldItem = $this->getMainHandItem();
2014 $oldItem = clone $heldItem;
2016 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
2017 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2018 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
2020 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
2024 $meleeEnchantmentDamage = 0;
2026 $meleeEnchantments = [];
2027 foreach($heldItem->getEnchantments() as $enchantment){
2028 $type = $enchantment->getType();
2029 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
2030 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
2031 $meleeEnchantments[] = $enchantment;
2034 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
2036 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
2037 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
2040 $entity->attack($ev);
2041 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
2043 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
2044 if($ev->isCancelled()){
2045 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
2048 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
2050 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2051 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2053 if($ev->getModifier(EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS) > 0 && $entity instanceof Living){
2054 $entity->broadcastAnimation(
new MagicHitAnimation($entity));
2057 foreach($meleeEnchantments as $enchantment){
2058 $type = $enchantment->getType();
2059 assert($type instanceof MeleeWeaponEnchantment);
2060 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2063 if($this->isAlive()){
2066 $returnedItems = [];
2067 $heldItem->onAttackEntity($entity, $returnedItems);
2068 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2070 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_ATTACK);
2083 if(!$ev->isCancelled()){
2084 $this->broadcastSound(new EntityAttackNoDamageSound());
2085 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2095 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2096 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2102 $item = $this->getMainHandItem();
2103 $oldItem = clone $item;
2104 if(!$ev->isCancelled()){
2105 if($item->onInteractEntity($this, $entity, $clickPos)){
2106 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->getMainHandItem())){
2107 if($item instanceof Durable && $item->isBroken()){
2108 $this->broadcastSound(new ItemBreakSound());
2110 $this->setMainHandItem($item);
2113 return $entity->
onInteract($this, $clickPos);
2118 public function toggleSprint(
bool $sprint) : bool{
2119 if($sprint === $this->sprinting){
2122 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2124 if($ev->isCancelled()){
2127 $this->setSprinting($sprint);
2131 public function toggleSneak(
bool $sneak,
bool $sneakPressed =
true) : bool{
2132 if($sneak === $this->sneaking && $sneakPressed === $this->sneakPressed){
2135 $this->setSneakPressed($sneakPressed);
2137 $ev =
new PlayerToggleSneakEvent($this, $sneak, $sneakPressed);
2138 if($sneak === $this->sneaking){
2143 if($ev->isCancelled()){
2146 $this->setSneaking($sneak);
2150 public function toggleFlight(
bool $fly) : bool{
2151 if($fly === $this->flying){
2154 $ev =
new PlayerToggleFlightEvent($this, $fly);
2155 if(!$this->allowFlight){
2159 if($ev->isCancelled()){
2162 $this->setFlying($fly);
2166 public function toggleGlide(
bool $glide) : bool{
2167 if($glide === $this->gliding){
2170 $ev =
new PlayerToggleGlideEvent($this, $glide);
2172 if($ev->isCancelled()){
2175 $this->setGliding($glide);
2179 public function toggleSwim(
bool $swim) : bool{
2180 if($swim === $this->swimming){
2183 $ev =
new PlayerToggleSwimEvent($this, $swim);
2185 if($ev->isCancelled()){
2188 $this->setSwimming($swim);
2192 public function emote(
string $emoteId) : void{
2193 $currentTick = $this->
server->getTick();
2194 if($currentTick - $this->lastEmoteTick > 5){
2195 $this->lastEmoteTick = $currentTick;
2196 $event =
new PlayerEmoteEvent($this, $emoteId);
2198 if(!$event->isCancelled()){
2199 $emoteId = $event->getEmoteId();
2200 parent::emote($emoteId);
2210 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2220 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2221 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2222 if($subtitle !==
""){
2223 $this->sendSubTitle($subtitle);
2225 $this->getNetworkSession()->onTitle($title);
2232 $this->getNetworkSession()->onSubTitle($subtitle);
2239 $this->getNetworkSession()->onActionBar($message);
2246 $this->getNetworkSession()->onClearTitle();
2253 $this->getNetworkSession()->onResetTitleOptions();
2264 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2265 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2273 $this->getNetworkSession()->onChatMessage($message);
2276 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2277 $this->getNetworkSession()->onJukeboxPopup($message);
2286 $this->getNetworkSession()->onPopup($message);
2289 public function sendTip(
string $message) : void{
2290 $this->getNetworkSession()->onTip($message);
2297 $this->getNetworkSession()->onToastNotification($title, $body);
2306 $id = $this->formIdCounter++;
2307 if($this->getNetworkSession()->onFormSent($id, $form)){
2308 $this->forms[$id] = $form;
2312 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2313 if(!isset($this->forms[$formId])){
2314 $this->logger->debug(
"Got unexpected response for form $formId");
2319 $this->forms[$formId]->handleResponse($this, $responseData);
2320 }
catch(FormValidationException $e){
2321 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2322 $this->logger->logException($e);
2324 unset($this->forms[$formId]);
2334 public function hasPendingForm(
int $formId) : bool{
2335 return isset($this->forms[$formId]);
2342 $this->getNetworkSession()->onCloseAllForms();
2357 if(!$ev->isCancelled()){
2358 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2373 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2375 if(!$ev->isCancelled()){
2376 $reason = $ev->getDisconnectReason();
2378 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2380 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2381 if($disconnectScreenMessage ===
""){
2382 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2384 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2406 if(!$this->isConnected()){
2410 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2411 $this->onPostDisconnect($reason, $quitMessage);
2422 if($this->isConnected()){
2423 throw new \LogicException(
"Player is still connected");
2427 $this->server->unsubscribeFromAllBroadcastChannels($this);
2429 $this->removeCurrentWindow();
2431 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2433 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2434 $this->server->broadcastMessage($quitMessage);
2438 $this->spawned =
false;
2441 $this->blockBreakHandler =
null;
2442 $this->despawnFromAll();
2444 $this->
server->removeOnlinePlayer($this);
2446 foreach($this->
server->getOnlinePlayers() as $player){
2447 if(!$player->canSee($this)){
2448 $player->showPlayer($this);
2451 $this->hiddenPlayers = [];
2453 if($this->location->isValid()){
2454 foreach($this->usedChunks as $index => $status){
2455 World::getXZ($index, $chunkX, $chunkZ);
2456 $this->unloadChunk($chunkX, $chunkZ);
2459 if(count($this->usedChunks) !== 0){
2460 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2462 $this->loadQueue = [];
2464 $this->removeCurrentWindow();
2465 $this->removePermanentWindows();
2467 $this->perm->getPermissionRecalculationCallbacks()->clear();
2469 $this->flagForDespawn();
2473 $this->disconnect(
"Player destroyed");
2474 $this->cursorInventory->removeAllWindows();
2475 $this->craftingGrid->removeAllWindows();
2476 parent::onDispose();
2480 $this->networkSession = null;
2481 $this->spawnPosition =
null;
2482 $this->deathPosition =
null;
2483 $this->blockBreakHandler =
null;
2484 parent::destroyCycles();
2494 public function __destruct(){
2495 parent::__destruct();
2496 $this->logger->debug(
"Destroyed by garbage collector");
2504 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2508 $nbt = $this->saveNBT();
2510 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2512 if($this->location->isValid()){
2513 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2516 if($this->hasValidCustomSpawn()){
2517 $spawn = $this->getSpawn();
2518 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2519 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2520 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2521 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2524 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2525 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2526 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2527 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2528 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2531 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2532 $nbt->
setLong(self::TAG_FIRST_PLAYED, (
int) $this->firstPlayed->format(
'Uv'));
2533 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2542 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2548 $this->removeCurrentWindow();
2550 $this->setDeathPosition($this->getPosition());
2552 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2555 if(!$ev->getKeepInventory()){
2556 foreach($ev->getDrops() as $item){
2557 $this->getWorld()->dropItem($this->location, $item);
2560 $this->hotbar->setSelectedIndex(0);
2561 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2562 $clearInventory($this->inventory);
2563 $clearInventory($this->armorInventory);
2564 $clearInventory($this->offHandInventory);
2567 if(!$ev->getKeepXp()){
2568 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2569 $this->xpManager->setXpAndProgress(0, 0.0);
2572 if($ev->getDeathMessage() !==
""){
2573 $this->server->broadcastMessage($ev->getDeathMessage());
2576 $this->startDeathAnimation();
2578 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2582 parent::onDeathUpdate($tickDiff);
2586 public function respawn() : void{
2587 if($this->
server->isHardcore()){
2588 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2589 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2594 $this->actuallyRespawn();
2597 protected function actuallyRespawn() : void{
2598 if($this->respawnLocked){
2601 $this->respawnLocked =
true;
2603 $this->logger->debug(
"Waiting for safe respawn position to be located");
2604 $spawn = $this->getSpawn();
2605 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2606 function(Position $safeSpawn) :
void{
2607 if(!$this->isConnected()){
2610 $this->logger->debug(
"Respawn position located, completing respawn");
2611 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2612 $spawnPosition = $ev->getRespawnPosition();
2613 $spawnBlock = $spawnPosition->
getWorld()->getBlock($spawnPosition);
2614 if($spawnBlock instanceof RespawnAnchor){
2615 if($spawnBlock->getCharges() > 0){
2616 $spawnPosition->
getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2617 $spawnPosition->
getWorld()->addSound($spawnPosition,
new RespawnAnchorDepleteSound());
2619 $defaultSpawn = $this->
server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2620 if($defaultSpawn !==
null){
2621 $this->setSpawn($defaultSpawn);
2622 $ev->setRespawnPosition($defaultSpawn);
2623 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2629 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2630 $this->teleport($realSpawn);
2632 $this->setSprinting(
false);
2633 $this->setSneaking(
false);
2634 $this->setFlying(
false);
2636 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2637 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2638 $this->deadTicks = 0;
2639 $this->noDamageTicks = 60;
2641 $this->effectManager->clear();
2642 $this->setHealth($this->getMaxHealth());
2644 foreach($this->attributeMap->getAll() as $attr){
2645 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2648 $attr->resetToDefault();
2651 $this->spawnToAll();
2652 $this->scheduleUpdate();
2654 $this->getNetworkSession()->onServerRespawn();
2655 $this->respawnLocked =
false;
2658 if($this->isConnected()){
2659 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2666 parent::applyPostDamageEffects($source);
2668 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_DAMAGE);
2672 if(!$this->isAlive()){
2676 if($this->isCreative()
2677 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2680 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2684 parent::attack($source);
2687 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2688 parent::syncNetworkData($properties);
2690 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2691 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2693 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2694 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2696 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2697 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2699 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2700 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2702 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2703 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2704 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2708 public function sendData(?array $targets, ?array $data =
null) : void{
2709 if($targets === null){
2710 $targets = $this->getViewers();
2713 parent::sendData($targets, $data);
2717 if($this->spawned && $targets === null){
2718 $targets = $this->getViewers();
2721 parent::broadcastAnimation($animation, $targets);
2725 if($this->spawned && $targets === null){
2726 $targets = $this->getViewers();
2729 parent::broadcastSound($sound, $targets);
2735 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2736 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2742 if(parent::teleport($pos, $yaw, $pitch)){
2744 $this->removeCurrentWindow();
2747 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2748 $this->broadcastMovement(
true);
2750 $this->spawnToAll();
2752 $this->resetFallDistance();
2753 $this->nextChunkOrderRun = 0;
2754 if($this->spawnChunkLoadCount !== -1){
2755 $this->spawnChunkLoadCount = 0;
2757 $this->blockBreakHandler =
null;
2761 $this->resetLastMovements();
2769 protected function addDefaultWindows() : void{
2770 $this->cursorInventory = new SimpleInventory(1);
2771 $this->craftingGrid =
new CraftingGrid(CraftingGrid::SIZE_SMALL);
2773 $this->addPermanentWindows([
2774 new PlayerInventoryWindow($this, $this->inventory, PlayerInventoryWindow::TYPE_INVENTORY),
2775 new PlayerInventoryWindow($this, $this->armorInventory, PlayerInventoryWindow::TYPE_ARMOR),
2776 new PlayerInventoryWindow($this, $this->cursorInventory, PlayerInventoryWindow::TYPE_CURSOR),
2777 new PlayerInventoryWindow($this, $this->offHandInventory, PlayerInventoryWindow::TYPE_OFFHAND),
2778 new PlayerInventoryWindow($this, $this->craftingGrid, PlayerInventoryWindow::TYPE_CRAFTING),
2782 public function getCursorInventory() : Inventory{
2783 return $this->cursorInventory;
2786 public function getCraftingGrid() : CraftingGrid{
2787 return $this->craftingGrid;
2795 return $this->creativeInventory;
2802 $this->creativeInventory = $inventory;
2803 if($this->spawned && $this->isConnected()){
2804 $this->getNetworkSession()->getInvManager()?->syncCreative();
2812 private function doCloseInventory() : void{
2813 $windowsToClear = [];
2814 $mainInventoryWindow =
null;
2815 foreach($this->permanentWindows as $window){
2816 if($window->getType() === PlayerInventoryWindow::TYPE_CRAFTING || $window->getType() === PlayerInventoryWindow::TYPE_CURSOR){
2817 $windowsToClear[] = $window;
2818 }elseif($window->getType() === PlayerInventoryWindow::TYPE_INVENTORY){
2819 $mainInventoryWindow = $window;
2822 if($mainInventoryWindow ===
null){
2826 throw new AssumptionFailedError(
"This should never be null");
2829 if($this->currentWindow instanceof TemporaryInventoryWindow){
2830 $windowsToClear[] = $this->currentWindow;
2833 $builder =
new TransactionBuilder();
2834 foreach($windowsToClear as $window){
2835 $contents = $window->getInventory()->getContents();
2837 if(count($contents) > 0){
2838 $drops = $builder->getActionBuilder($mainInventoryWindow)->addItem(...$contents);
2839 foreach($drops as $drop){
2840 $builder->addAction(
new DropItemAction($drop));
2843 $builder->getActionBuilder($window)->clearAll();
2847 $actions = $builder->generateActions();
2848 if(count($actions) !== 0){
2849 $transaction =
new InventoryTransaction($this, $actions);
2851 $transaction->execute();
2852 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2853 }
catch(TransactionCancelledException){
2854 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2855 foreach($windowsToClear as $window){
2856 $window->getInventory()->clearAll();
2858 }
catch(TransactionValidationException $e){
2859 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2868 return $this->currentWindow;
2875 if($window === $this->currentWindow){
2878 if($window->getViewer() !== $this){
2879 throw new \InvalidArgumentException(
"Cannot reuse InventoryWindow instances, please create a new one for each player");
2883 if($ev->isCancelled()){
2887 $this->removeCurrentWindow();
2889 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2890 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2892 $this->logger->debug(
"Opening inventory window " . get_class($window) .
"#" . spl_object_id($window));
2893 $inventoryManager->onCurrentWindowChange($window);
2895 $this->currentWindow = $window;
2899 public function removeCurrentWindow() : void{
2900 $this->doCloseInventory();
2901 if($this->currentWindow !==
null){
2902 $currentWindow = $this->currentWindow;
2903 $this->logger->debug(
"Closing inventory window " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2904 $this->currentWindow->onClose();
2905 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2906 $inventoryManager->onCurrentWindowRemove();
2908 $this->currentWindow =
null;
2909 (
new InventoryCloseEvent($currentWindow, $this))->call();
2917 foreach($windows as $window){
2919 $this->permanentWindows[spl_object_id($window)] = $window;
2923 protected function removePermanentWindows() : void{
2924 foreach($this->permanentWindows as $window){
2927 $this->permanentWindows = [];
2935 return $this->permanentWindows;
2942 $block = $this->getWorld()->getBlock($position);
2944 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2945 $this->getNetworkSession()->onOpenSignEditor($position, $frontFace);
2947 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2951 use ChunkListenerNoOpTrait {
2952 onChunkChanged as
private;
2953 onChunkUnloaded as
private;
2957 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2958 if($status === UsedChunkStatus::SENT){
2959 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2960 $this->nextChunkOrderRun = 0;
2965 if($this->isUsingChunk($chunkX, $chunkZ)){
2966 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2967 $this->unloadChunk($chunkX, $chunkZ);