174 use PermissibleDelegateTrait;
176 private const MOVES_PER_TICK = 2;
177 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
180 private const MAX_CHAT_CHAR_LENGTH = 512;
186 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
187 private const MAX_REACH_DISTANCE_CREATIVE = 13;
188 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
189 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
191 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
193 public const TAG_FIRST_PLAYED =
"firstPlayed";
194 public const TAG_LAST_PLAYED =
"lastPlayed";
195 private const TAG_GAME_MODE =
"playerGameType";
196 private const TAG_SPAWN_WORLD =
"SpawnLevel";
197 private const TAG_SPAWN_X =
"SpawnX";
198 private const TAG_SPAWN_Y =
"SpawnY";
199 private const TAG_SPAWN_Z =
"SpawnZ";
200 private const TAG_DEATH_WORLD =
"DeathLevel";
201 private const TAG_DEATH_X =
"DeathPositionX";
202 private const TAG_DEATH_Y =
"DeathPositionY";
203 private const TAG_DEATH_Z =
"DeathPositionZ";
204 public const TAG_LEVEL =
"Level";
205 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
215 $lname = strtolower($name);
216 $len = strlen($name);
217 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
222 public bool $spawned =
false;
224 protected string $username;
225 protected string $displayName;
226 protected string $xuid =
"";
227 protected bool $authenticated;
230 protected ?InventoryWindow $currentWindow =
null;
232 protected array $permanentWindows = [];
233 protected Inventory $cursorInventory;
234 protected CraftingGrid $craftingGrid;
235 protected CreativeInventory $creativeInventory;
237 protected int $messageCounter = 2;
239 protected DateTimeImmutable $firstPlayed;
240 protected DateTimeImmutable $lastPlayed;
241 protected GameMode $gamemode;
247 protected array $usedChunks = [];
252 private array $activeChunkGenerationRequests = [];
257 protected array $loadQueue = [];
258 protected int $nextChunkOrderRun = 5;
261 private array $tickingChunks = [];
263 protected int $viewDistance = -1;
264 protected int $spawnThreshold;
265 protected int $spawnChunkLoadCount = 0;
266 protected int $chunksPerTick;
267 protected ChunkSelector $chunkSelector;
268 protected ChunkLoader $chunkLoader;
269 protected ChunkTicker $chunkTicker;
272 protected array $hiddenPlayers = [];
274 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
275 protected ?
float $lastMovementProcess =
null;
277 protected int $inAirTicks = 0;
279 protected float $stepHeight = 0.6;
281 protected ?Vector3 $sleeping =
null;
282 private ?
Position $spawnPosition =
null;
284 private bool $respawnLocked =
false;
286 private ?
Position $deathPosition =
null;
289 protected bool $autoJump =
true;
290 protected bool $allowFlight =
false;
291 protected bool $blockCollision =
true;
292 protected bool $flying =
false;
294 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
297 protected ?
int $lineHeight =
null;
298 protected string $locale =
"en_US";
300 protected int $startAction = -1;
306 protected array $usedItemsCooldown = [];
308 private int $lastEmoteTick = 0;
310 protected int $formIdCounter = 0;
312 protected array $forms = [];
314 protected \Logger $logger;
319 $username = TextFormat::clean($playerInfo->getUsername());
320 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
323 $this->networkSession = $session;
324 $this->playerInfo = $playerInfo;
325 $this->authenticated = $authenticated;
327 $this->username = $username;
328 $this->displayName = $this->username;
329 $this->locale = $this->playerInfo->getLocale();
331 $this->uuid = $this->playerInfo->getUuid();
332 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
334 $this->creativeInventory = CreativeInventory::getInstance();
336 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
337 if($this->
server->isOp($this->username)){
338 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
341 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
342 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
347 $world = $spawnLocation->
getWorld();
349 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
350 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
351 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
352 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
353 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
355 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
359 $this->setNameTag($this->username);
362 private function callDummyItemHeldEvent() : void{
363 $slot = $this->hotbar->getSelectedIndex();
372 protected function initEntity(
CompoundTag $nbt) : void{
373 parent::initEntity($nbt);
374 $this->addDefaultWindows();
376 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
377 function(Inventory $unused,
int $slot) :
void{
378 if($slot === $this->hotbar->getSelectedIndex()){
379 $this->setUsingItem(
false);
381 $this->callDummyItemHeldEvent();
385 $this->setUsingItem(
false);
386 $this->callDummyItemHeldEvent();
390 $now = (int) (microtime(
true) * 1000);
391 $createDateTimeImmutable =
static function(
string $tag) use ($nbt, $now) : DateTimeImmutable{
392 return new DateTimeImmutable(
'@' . $nbt->getLong($tag, $now) / 1000);
394 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
395 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
397 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
398 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
400 $this->internalSetGameMode($this->
server->getGamemode());
403 $this->keepMovement =
true;
405 $this->setNameTagVisible();
406 $this->setNameTagAlwaysVisible();
407 $this->setCanClimb();
409 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
410 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
412 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
413 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
417 public function getLeaveMessage() : Translatable|string{
419 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
425 public function isAuthenticated() : bool{
426 return $this->authenticated;
451 return parent::getUniqueId();
458 return $this->firstPlayed;
465 return $this->lastPlayed;
468 public function hasPlayedBefore() : bool{
469 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format(
'%s')) > 1;
482 if($this->allowFlight !== $value){
483 $this->allowFlight = $value;
484 $this->getNetworkSession()->syncAbilities($this);
495 return $this->allowFlight;
507 if($this->blockCollision !== $value){
508 $this->blockCollision = $value;
509 $this->getNetworkSession()->syncAbilities($this);
518 return $this->blockCollision;
521 public function setFlying(
bool $value) : void{
522 if($this->flying !== $value){
523 $this->flying = $value;
524 $this->resetFallDistance();
525 $this->getNetworkSession()->syncAbilities($this);
529 public function isFlying() : bool{
530 return $this->flying;
547 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
548 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
549 $this->getNetworkSession()->syncAbilities($this);
565 return $this->flightSpeedMultiplier;
568 public function setAutoJump(
bool $value) : void{
569 if($this->autoJump !== $value){
570 $this->autoJump = $value;
571 $this->getNetworkSession()->syncAdventureSettings();
575 public function hasAutoJump() : bool{
576 return $this->autoJump;
579 public function spawnTo(Player $player) : void{
580 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
581 parent::spawnTo($player);
585 public function getServer() : Server{
590 return $this->lineHeight ?? 7;
594 if($height !== null && $height < 1){
595 throw new \InvalidArgumentException(
"Line height must be at least 1");
597 $this->lineHeight = $height;
600 public function canSee(
Player $player) : bool{
601 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
604 public function hidePlayer(Player $player) : void{
605 if($player === $this){
608 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
609 $player->despawnFrom($this);
612 public function showPlayer(Player $player) : void{
613 if($player === $this){
616 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
617 if($player->isOnline()){
618 $player->spawnTo($this);
622 public function canCollideWith(Entity $entity) : bool{
626 public function canBeCollidedWith() : bool{
627 return !$this->isSpectator() && parent::canBeCollidedWith();
630 public function resetFallDistance() : void{
631 parent::resetFallDistance();
632 $this->inAirTicks = 0;
635 public function getViewDistance() : int{
636 return $this->viewDistance;
639 public function setViewDistance(
int $distance) : void{
640 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
642 if($newViewDistance !== $this->viewDistance){
643 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
647 $this->viewDistance = $newViewDistance;
649 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
651 $this->nextChunkOrderRun = 0;
653 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
655 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
658 public function isOnline() : bool{
659 return $this->isConnected();
662 public function isConnected() : bool{
663 return $this->networkSession !== null && $this->networkSession->isConnected();
666 public function getNetworkSession() : NetworkSession{
667 if($this->networkSession === null){
668 throw new \LogicException(
"Player is not connected");
670 return $this->networkSession;
677 return $this->username;
684 return $this->displayName;
687 public function setDisplayName(
string $name) : void{
691 $this->displayName = $ev->getNewName();
702 return $this->locale;
705 public function getLanguage() :
Language{
706 return $this->
server->getLanguage();
713 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
717 if($ev->isCancelled()){
718 $this->sendSkin([$this]);
722 $this->setSkin($ev->getNewSkin());
723 $this->sendSkin($this->server->getOnlinePlayers());
732 public function sendSkin(?array $targets =
null) : void{
733 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
740 return $this->startAction > -1;
743 public function setUsingItem(
bool $value) : void{
744 $this->startAction = $value ? $this->
server->getTick() : -1;
745 $this->networkPropertiesDirty =
true;
753 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
760 $this->checkItemCooldowns();
761 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
768 $this->checkItemCooldowns();
769 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
776 $ticks = $ticks ?? $item->getCooldownTicks();
778 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
779 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
783 protected function checkItemCooldowns() : void{
784 $serverTick = $this->
server->getTick();
785 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
786 if($cooldownUntil <= $serverTick){
787 unset($this->usedItemsCooldown[$itemId]);
792 protected function setPosition(Vector3 $pos) : bool{
793 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
794 if(parent::setPosition($pos)){
795 $newWorld = $this->getWorld();
796 if($oldWorld !== $newWorld){
797 if($oldWorld !==
null){
798 foreach($this->usedChunks as $index => $status){
799 World::getXZ($index, $X, $Z);
800 $this->unloadChunk($X, $Z, $oldWorld);
804 $this->usedChunks = [];
805 $this->loadQueue = [];
806 $this->getNetworkSession()->onEnterWorld();
815 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
816 $world = $world ?? $this->getWorld();
817 $index = World::chunkHash($x, $z);
818 if(isset($this->usedChunks[$index])){
819 foreach($world->getChunkEntities($x, $z) as $entity){
820 if($entity !== $this){
821 $entity->despawnFrom($this);
824 $this->getNetworkSession()->stopUsingChunk($x, $z);
825 unset($this->usedChunks[$index]);
826 unset($this->activeChunkGenerationRequests[$index]);
828 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
829 $world->unregisterChunkListener($this, $x, $z);
830 unset($this->loadQueue[$index]);
831 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
832 unset($this->tickingChunks[$index]);
835 protected function spawnEntitiesOnAllChunks() : void{
836 foreach($this->usedChunks as $chunkHash => $status){
837 if($status === UsedChunkStatus::SENT){
838 World::getXZ($chunkHash, $chunkX, $chunkZ);
839 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
844 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
845 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
846 if($entity !== $this && !$entity->isFlaggedForDespawn()){
847 $entity->spawnTo($this);
857 if(!$this->isConnected()){
861 Timings::$playerChunkSend->startTiming();
864 $world = $this->getWorld();
866 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
867 foreach($this->loadQueue as $index => $distance){
868 if($count >= $limit){
874 World::getXZ($index, $X, $Z);
878 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
879 $this->activeChunkGenerationRequests[$index] =
true;
880 unset($this->loadQueue[$index]);
881 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
882 $world->registerChunkListener($this, $X, $Z);
883 if(isset($this->tickingChunks[$index])){
884 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
887 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
888 function() use ($X, $Z, $index, $world) :
void{
889 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
892 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
898 unset($this->activeChunkGenerationRequests[$index]);
899 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
901 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
902 $this->usedChunks[$index] = UsedChunkStatus::SENT;
903 if($this->spawnChunkLoadCount === -1){
904 $this->spawnEntitiesOnChunk($X, $Z);
905 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
906 $this->spawnChunkLoadCount = -1;
908 $this->spawnEntitiesOnAllChunks();
910 $this->getNetworkSession()->notifyTerrainReady();
912 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
915 static function() :
void{
921 Timings::$playerChunkSend->stopTiming();
924 private function recheckBroadcastPermissions() : void{
926 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
927 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
928 ] as $permission => $channel){
929 if($this->hasPermission($permission)){
930 $this->
server->subscribeToBroadcastChannel($channel, $this);
932 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
945 $this->spawned =
true;
946 $this->recheckBroadcastPermissions();
947 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
948 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
949 $this->recheckBroadcastPermissions();
953 $ev =
new PlayerJoinEvent($this,
954 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
957 if($ev->getJoinMessage() !==
""){
958 $this->server->broadcastMessage($ev->getJoinMessage());
961 $this->noDamageTicks = 60;
965 if($this->getHealth() <= 0){
966 $this->logger->debug(
"Quit while dead, forcing respawn");
967 $this->actuallyRespawn();
978 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
979 $world = $this->getWorld();
980 foreach($oldTickingChunks as $hash => $_){
981 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
983 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
984 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
987 foreach($newTickingChunks as $hash => $_){
988 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
990 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
991 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
1001 if(!$this->isConnected() || $this->viewDistance === -1){
1005 Timings::$playerChunkOrder->startTiming();
1008 $tickingChunks = [];
1009 $unloadChunks = $this->usedChunks;
1011 $world = $this->getWorld();
1012 $tickingChunkRadius = $world->getChunkTickRadius();
1014 foreach($this->chunkSelector->selectChunks(
1015 $this->server->getAllowedViewDistance($this->viewDistance),
1016 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1017 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1018 ) as $radius => $hash){
1019 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1020 $newOrder[$hash] =
true;
1022 if($radius < $tickingChunkRadius){
1023 $tickingChunks[$hash] =
true;
1025 unset($unloadChunks[$hash]);
1028 foreach($unloadChunks as $index => $status){
1029 World::getXZ($index, $X, $Z);
1030 $this->unloadChunk($X, $Z);
1033 $this->loadQueue = $newOrder;
1035 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1036 $this->tickingChunks = $tickingChunks;
1038 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1039 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1042 Timings::$playerChunkOrder->stopTiming();
1050 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1058 return $this->usedChunks;
1065 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1072 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1073 return $status === UsedChunkStatus::SENT;
1080 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1081 $this->nextChunkOrderRun = PHP_INT_MAX;
1082 $this->orderChunks();
1085 if(count($this->loadQueue) > 0){
1086 $this->requestChunks();
1090 public function getDeathPosition() : ?Position{
1091 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1092 $this->deathPosition =
null;
1094 return $this->deathPosition;
1102 if($pos instanceof
Position && $pos->world !==
null){
1103 $world = $pos->world;
1105 $world = $this->getWorld();
1107 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1109 $this->deathPosition =
null;
1111 $this->networkPropertiesDirty =
true;
1118 if($this->hasValidCustomSpawn()){
1119 return $this->spawnPosition;
1121 $world = $this->
server->getWorldManager()->getDefaultWorld();
1123 return $world->getSpawnLocation();
1127 public function hasValidCustomSpawn() : bool{
1128 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1140 $world = $this->getWorld();
1142 $world = $pos->getWorld();
1144 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1146 $this->spawnPosition =
null;
1148 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1151 public function isSleeping() : bool{
1152 return $this->sleeping !== null;
1155 public function sleepOn(Vector3 $pos) : bool{
1156 $pos = $pos->floor();
1157 $b = $this->getWorld()->getBlock($pos);
1159 $ev =
new PlayerBedEnterEvent($this, $b);
1161 if($ev->isCancelled()){
1165 if($b instanceof Bed){
1167 $this->getWorld()->setBlock($pos, $b);
1170 $this->sleeping = $pos;
1171 $this->networkPropertiesDirty =
true;
1173 $this->setSpawn($pos);
1175 $this->getWorld()->setSleepTicks(60);
1180 public function stopSleep() : void{
1181 if($this->sleeping instanceof Vector3){
1182 $b = $this->getWorld()->getBlock($this->sleeping);
1183 if($b instanceof Bed){
1184 $b->setOccupied(
false);
1185 $this->getWorld()->setBlock($this->sleeping, $b);
1187 (
new PlayerBedLeaveEvent($this, $b))->call();
1189 $this->sleeping =
null;
1190 $this->networkPropertiesDirty =
true;
1192 $this->getWorld()->setSleepTicks(0);
1194 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1198 public function getGamemode() : GameMode{
1199 return $this->gamemode;
1202 protected function internalSetGameMode(GameMode $gameMode) : void{
1203 $this->gamemode = $gameMode;
1205 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1206 $this->hungerManager->setEnabled($this->isSurvival());
1208 if($this->isSpectator()){
1209 $this->setFlying(
true);
1210 $this->setHasBlockCollision(
false);
1212 $this->onGround =
false;
1216 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1218 if($this->isSurvival()){
1219 $this->setFlying(
false);
1221 $this->setHasBlockCollision(
true);
1222 $this->setSilent(
false);
1223 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1231 if($this->gamemode === $gm){
1237 if($ev->isCancelled()){
1241 $this->internalSetGameMode($gm);
1243 if($this->isSpectator()){
1244 $this->despawnFromAll();
1246 $this->spawnToAll();
1249 $this->getNetworkSession()->syncGameMode($this->gamemode);
1260 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1270 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1280 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1283 public function isSpectator() : bool{
1284 return $this->gamemode === GameMode::SPECTATOR;
1291 return $this->gamemode !== GameMode::CREATIVE;
1295 if($this->hasFiniteResources()){
1296 return parent::getDrops();
1303 if($this->hasFiniteResources()){
1304 return parent::getXpDropAmount();
1310 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1311 if($this->gamemode === GameMode::SPECTATOR){
1312 $this->onGround =
false;
1315 $bb =
new AxisAlignedBB(
1316 $this->boundingBox->minX,
1317 $this->location->y - 0.2,
1318 $this->boundingBox->minZ,
1319 $this->boundingBox->maxX,
1320 $this->location->y + 0.2,
1321 $this->boundingBox->maxZ
1326 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1328 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1336 protected function checkNearEntities() : void{
1337 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1338 $entity->scheduleUpdate();
1340 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1344 $entity->onCollideWithPlayer($this);
1348 public function getInAirTicks() : int{
1349 return $this->inAirTicks;
1361 Timings::$playerMove->startTiming();
1363 $this->actuallyHandleMovement($newPos);
1365 Timings::$playerMove->stopTiming();
1369 private function actuallyHandleMovement(Vector3 $newPos) : void{
1370 $this->moveRateLimit--;
1371 if($this->moveRateLimit < 0){
1375 $oldPos = $this->location;
1376 $distanceSquared = $newPos->distanceSquared($oldPos);
1380 if($distanceSquared > 225){
1392 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1393 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1395 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1397 $this->nextChunkOrderRun = 0;
1400 if(!$revert && $distanceSquared !== 0.0){
1401 $dx = $newPos->x - $oldPos->x;
1402 $dy = $newPos->y - $oldPos->y;
1403 $dz = $newPos->z - $oldPos->z;
1405 $this->move($dx, $dy, $dz);
1409 $this->revertMovement($oldPos);
1417 $now = microtime(true);
1418 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1419 $exceededRateLimit = $this->moveRateLimit < 0;
1420 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1421 $this->lastMovementProcess = $now;
1423 $from = clone $this->lastLocation;
1424 $to = clone $this->location;
1426 $delta = $to->distanceSquared($from);
1427 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1429 if($delta > 0.0001 || $deltaAngle > 1.0){
1430 if(PlayerMoveEvent::hasHandlers()){
1435 if($ev->isCancelled()){
1436 $this->revertMovement($from);
1440 if($to->distanceSquared($ev->getTo()) > 0.01){
1441 $this->teleport($ev->getTo());
1446 $this->lastLocation = $to;
1447 $this->broadcastMovement();
1449 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1450 if($horizontalDistanceTravelled > 0){
1452 if($this->isSprinting()){
1453 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, EntityExhaustEvent::CAUSE_SPRINTING);
1455 $this->hungerManager->exhaust(0.0, EntityExhaustEvent::CAUSE_WALKING);
1458 if($this->nextChunkOrderRun > 20){
1459 $this->nextChunkOrderRun = 20;
1464 if($exceededRateLimit){
1465 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1466 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1470 protected function revertMovement(Location $from) : void{
1471 $this->setPosition($from);
1472 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1475 protected function calculateFallDamage(
float $fallDistance) : float{
1476 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1484 public function setMotion(
Vector3 $motion) : bool{
1485 if(parent::setMotion($motion)){
1486 $this->broadcastMotion();
1487 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1494 protected function updateMovement(
bool $teleport =
false) : void{
1498 protected function tryChangeMovement() : void{
1502 public function onUpdate(int $currentTick) : bool{
1503 $tickDiff = $currentTick - $this->lastUpdate;
1509 $this->messageCounter = 2;
1511 $this->lastUpdate = $currentTick;
1513 if($this->justCreated){
1514 $this->onFirstUpdate($currentTick);
1517 if(!$this->isAlive() && $this->spawned){
1518 $this->onDeathUpdate($tickDiff);
1522 $this->timings->startTiming();
1525 Timings::$playerMove->startTiming();
1526 $this->processMostRecentMovements();
1527 $this->motion = Vector3::zero();
1528 if($this->onGround){
1529 $this->inAirTicks = 0;
1531 $this->inAirTicks += $tickDiff;
1533 Timings::$playerMove->stopTiming();
1535 Timings::$entityBaseTick->startTiming();
1536 $this->entityBaseTick($tickDiff);
1537 Timings::$entityBaseTick->stopTiming();
1539 if($this->isCreative() && $this->fireTicks > 1){
1540 $this->fireTicks = 1;
1543 if(!$this->isSpectator() && $this->isAlive()){
1544 Timings::$playerCheckNearEntities->startTiming();
1545 $this->checkNearEntities();
1546 Timings::$playerCheckNearEntities->stopTiming();
1549 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1550 $this->blockBreakHandler =
null;
1554 $this->timings->stopTiming();
1560 return $this->isCreative() || parent::canEat();
1564 return $this->isCreative() || parent::canBreathe();
1573 $eyePos = $this->getEyePos();
1574 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1578 $dV = $this->getDirectionVector();
1579 $eyeDot = $dV->dot($eyePos);
1580 $targetDot = $dV->dot($pos);
1581 return ($targetDot - $eyeDot) >= -$maxDiff;
1588 public function chat(
string $message) : bool{
1589 $this->removeCurrentWindow();
1591 if($this->messageCounter <= 0){
1597 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1598 if(strlen($message) > $maxTotalLength){
1602 $message = TextFormat::clean($message,
false);
1603 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1604 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1605 if(str_starts_with($messagePart,
'./')){
1606 $messagePart = substr($messagePart, 1);
1609 if(str_starts_with($messagePart,
"/")){
1610 Timings::$playerCommand->startTiming();
1611 $this->server->dispatchCommand($this, substr($messagePart, 1));
1612 Timings::$playerCommand->stopTiming();
1614 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1616 if(!$ev->isCancelled()){
1617 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1626 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1627 if(!$this->hotbar->isHotbarSlot($hotbarSlot)){
1630 if($hotbarSlot === $this->hotbar->getSelectedIndex()){
1634 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1636 if($ev->isCancelled()){
1640 $this->hotbar->setSelectedIndex($hotbarSlot);
1641 $this->setUsingItem(
false);
1649 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1650 $heldItemChanged = false;
1652 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->getMainHandItem())){
1655 $newReplica = clone $oldHeldItem;
1656 $newReplica->setCount($newHeldItem->getCount());
1657 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1658 $newDamage = $newHeldItem->getDamage();
1659 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1660 $newReplica->setDamage($newDamage);
1663 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1665 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1666 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1667 $this->broadcastSound(
new ItemBreakSound());
1669 $this->setMainHandItem($newHeldItem);
1670 $heldItemChanged =
true;
1674 if(!$heldItemChanged){
1675 $newHeldItem = $oldHeldItem;
1678 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1679 $this->setMainHandItem(array_shift($extraReturnedItems));
1681 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1683 $ev =
new PlayerDropItemEvent($this, $drop);
1684 if($this->isSpectator()){
1688 if(!$ev->isCancelled()){
1689 $this->dropItem($drop);
1700 $directionVector = $this->getDirectionVector();
1701 $item = $this->getMainHandItem();
1702 $oldItem = clone $item;
1705 if($this->hasItemCooldown($item) || $this->isSpectator()){
1711 if($ev->isCancelled()){
1715 $returnedItems = [];
1716 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1717 if($result === ItemUseResult::FAIL){
1721 $this->resetItemCooldown($oldItem);
1722 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1724 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1735 $slot = $this->getMainHandItem();
1737 $oldItem = clone $slot;
1740 if($this->hasItemCooldown($slot)){
1745 if($ev->isCancelled() || !$this->consumeObject($slot)){
1749 $this->setUsingItem(
false);
1750 $this->resetItemCooldown($oldItem);
1753 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1768 $item = $this->getMainHandItem();
1769 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1773 $oldItem = clone $item;
1775 $returnedItems = [];
1776 $result = $item->onReleaseUsing($this, $returnedItems);
1777 if($result === ItemUseResult::SUCCESS){
1778 $this->resetItemCooldown($oldItem);
1779 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1785 $this->setUsingItem(
false);
1789 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1790 $block = $this->getWorld()->getBlock($pos);
1791 if($block instanceof UnknownBlock){
1795 $item = $block->getPickedItem($addTileNBT);
1797 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1798 $existingSlot = $this->inventory->first($item);
1799 if($existingSlot === -1 && $this->hasFiniteResources()){
1804 if(!$ev->isCancelled()){
1805 $this->equipOrAddPickedItem($existingSlot, $item);
1811 public function pickEntity(
int $entityId) : bool{
1812 $entity = $this->getWorld()->getEntity($entityId);
1813 if($entity ===
null){
1817 $item = $entity->getPickedItem();
1822 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1823 $existingSlot = $this->inventory->first($item);
1824 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1829 if(!$ev->isCancelled()){
1830 $this->equipOrAddPickedItem($existingSlot, $item);
1836 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1837 if($existingSlot !== -1){
1838 if($existingSlot < $this->hotbar->getSize()){
1839 $this->hotbar->setSelectedIndex($existingSlot);
1841 $this->inventory->swap($this->hotbar->getSelectedIndex(), $existingSlot);
1844 $firstEmpty = $this->inventory->firstEmpty();
1845 if($firstEmpty === -1){
1846 $this->setMainHandItem($item);
1847 }elseif($firstEmpty < $this->hotbar->getSize()){
1848 $this->inventory->setItem($firstEmpty, $item);
1849 $this->hotbar->setSelectedIndex($firstEmpty);
1851 $this->inventory->swap($this->hotbar->getSelectedIndex(), $firstEmpty);
1852 $this->setMainHandItem($item);
1863 if($pos->distanceSquared($this->location) > 10000){
1867 $target = $this->getWorld()->getBlock($pos);
1869 $ev =
new PlayerInteractEvent($this, $this->getMainHandItem(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1870 if($this->isSpectator()){
1874 if($ev->isCancelled()){
1877 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1878 if($target->onAttack($this->getMainHandItem(), $face, $this)){
1882 $block = $target->getSide($face);
1883 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1884 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1885 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1889 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1890 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1896 public function continueBreakBlock(Vector3 $pos, Facing $face) : void{
1897 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1898 $this->blockBreakHandler->setTargetedFace($face);
1902 public function stopBreakBlock(Vector3 $pos) : void{
1903 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1904 $this->blockBreakHandler =
null;
1914 $this->removeCurrentWindow();
1916 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1917 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1918 $this->stopBreakBlock($pos);
1919 $item = $this->getMainHandItem();
1920 $oldItem = clone $item;
1921 $returnedItems = [];
1922 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1923 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1924 $this->hungerManager->exhaust(0.005, EntityExhaustEvent::CAUSE_MINING);
1928 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1940 $this->setUsingItem(false);
1942 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1943 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1944 $item = $this->getMainHandItem();
1945 $oldItem = clone $item;
1946 $returnedItems = [];
1947 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1948 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1952 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1965 if(!$entity->isAlive()){
1969 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1973 $heldItem = $this->getMainHandItem();
1974 $oldItem = clone $heldItem;
1976 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1977 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1978 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1980 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1984 $meleeEnchantmentDamage = 0;
1986 $meleeEnchantments = [];
1987 foreach($heldItem->getEnchantments() as $enchantment){
1988 $type = $enchantment->getType();
1989 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1990 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1991 $meleeEnchantments[] = $enchantment;
1994 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1996 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1997 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
2000 $entity->attack($ev);
2001 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
2003 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
2004 if($ev->isCancelled()){
2005 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
2008 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
2010 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2011 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2014 foreach($meleeEnchantments as $enchantment){
2015 $type = $enchantment->getType();
2016 assert($type instanceof MeleeWeaponEnchantment);
2017 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2020 if($this->isAlive()){
2023 $returnedItems = [];
2024 $heldItem->onAttackEntity($entity, $returnedItems);
2025 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2027 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_ATTACK);
2040 if(!$ev->isCancelled()){
2041 $this->broadcastSound(new EntityAttackNoDamageSound());
2042 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2052 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2053 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2059 $item = $this->getMainHandItem();
2060 $oldItem = clone $item;
2061 if(!$ev->isCancelled()){
2062 if($item->onInteractEntity($this, $entity, $clickPos)){
2063 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->getMainHandItem())){
2064 if($item instanceof Durable && $item->isBroken()){
2065 $this->broadcastSound(new ItemBreakSound());
2067 $this->setMainHandItem($item);
2070 return $entity->
onInteract($this, $clickPos);
2075 public function toggleSprint(
bool $sprint) : bool{
2076 if($sprint === $this->sprinting){
2079 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2081 if($ev->isCancelled()){
2084 $this->setSprinting($sprint);
2088 public function toggleSneak(
bool $sneak) : bool{
2089 if($sneak === $this->sneaking){
2092 $ev =
new PlayerToggleSneakEvent($this, $sneak);
2094 if($ev->isCancelled()){
2097 $this->setSneaking($sneak);
2101 public function toggleFlight(
bool $fly) : bool{
2102 if($fly === $this->flying){
2105 $ev =
new PlayerToggleFlightEvent($this, $fly);
2106 if(!$this->allowFlight){
2110 if($ev->isCancelled()){
2113 $this->setFlying($fly);
2117 public function toggleGlide(
bool $glide) : bool{
2118 if($glide === $this->gliding){
2121 $ev =
new PlayerToggleGlideEvent($this, $glide);
2123 if($ev->isCancelled()){
2126 $this->setGliding($glide);
2130 public function toggleSwim(
bool $swim) : bool{
2131 if($swim === $this->swimming){
2134 $ev =
new PlayerToggleSwimEvent($this, $swim);
2136 if($ev->isCancelled()){
2139 $this->setSwimming($swim);
2143 public function emote(
string $emoteId) : void{
2144 $currentTick = $this->
server->getTick();
2145 if($currentTick - $this->lastEmoteTick > 5){
2146 $this->lastEmoteTick = $currentTick;
2147 $event =
new PlayerEmoteEvent($this, $emoteId);
2149 if(!$event->isCancelled()){
2150 $emoteId = $event->getEmoteId();
2151 parent::emote($emoteId);
2161 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2171 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2172 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2173 if($subtitle !==
""){
2174 $this->sendSubTitle($subtitle);
2176 $this->getNetworkSession()->onTitle($title);
2183 $this->getNetworkSession()->onSubTitle($subtitle);
2190 $this->getNetworkSession()->onActionBar($message);
2197 $this->getNetworkSession()->onClearTitle();
2204 $this->getNetworkSession()->onResetTitleOptions();
2215 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2216 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2224 $this->getNetworkSession()->onChatMessage($message);
2227 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2228 $this->getNetworkSession()->onJukeboxPopup($message);
2237 $this->getNetworkSession()->onPopup($message);
2240 public function sendTip(
string $message) : void{
2241 $this->getNetworkSession()->onTip($message);
2248 $this->getNetworkSession()->onToastNotification($title, $body);
2257 $id = $this->formIdCounter++;
2258 if($this->getNetworkSession()->onFormSent($id, $form)){
2259 $this->forms[$id] = $form;
2263 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2264 if(!isset($this->forms[$formId])){
2265 $this->logger->debug(
"Got unexpected response for form $formId");
2270 $this->forms[$formId]->handleResponse($this, $responseData);
2271 }
catch(FormValidationException $e){
2272 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2273 $this->logger->logException($e);
2275 unset($this->forms[$formId]);
2285 $this->getNetworkSession()->onCloseAllForms();
2300 if(!$ev->isCancelled()){
2301 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2316 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2318 if(!$ev->isCancelled()){
2319 $reason = $ev->getDisconnectReason();
2321 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2323 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2324 if($disconnectScreenMessage ===
""){
2325 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2327 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2349 if(!$this->isConnected()){
2353 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2354 $this->onPostDisconnect($reason, $quitMessage);
2365 if($this->isConnected()){
2366 throw new \LogicException(
"Player is still connected");
2370 $this->server->unsubscribeFromAllBroadcastChannels($this);
2372 $this->removeCurrentWindow();
2374 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2376 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2377 $this->server->broadcastMessage($quitMessage);
2381 $this->spawned =
false;
2384 $this->blockBreakHandler =
null;
2385 $this->despawnFromAll();
2387 $this->
server->removeOnlinePlayer($this);
2389 foreach($this->
server->getOnlinePlayers() as $player){
2390 if(!$player->canSee($this)){
2391 $player->showPlayer($this);
2394 $this->hiddenPlayers = [];
2396 if($this->location->isValid()){
2397 foreach($this->usedChunks as $index => $status){
2398 World::getXZ($index, $chunkX, $chunkZ);
2399 $this->unloadChunk($chunkX, $chunkZ);
2402 if(count($this->usedChunks) !== 0){
2403 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2405 $this->loadQueue = [];
2407 $this->removeCurrentWindow();
2408 $this->removePermanentWindows();
2410 $this->perm->getPermissionRecalculationCallbacks()->clear();
2412 $this->flagForDespawn();
2416 $this->disconnect(
"Player destroyed");
2417 $this->cursorInventory->removeAllWindows();
2418 $this->craftingGrid->removeAllWindows();
2419 parent::onDispose();
2423 $this->networkSession = null;
2424 $this->spawnPosition =
null;
2425 $this->deathPosition =
null;
2426 $this->blockBreakHandler =
null;
2427 parent::destroyCycles();
2437 public function __destruct(){
2438 parent::__destruct();
2439 $this->logger->debug(
"Destroyed by garbage collector");
2447 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2451 $nbt = $this->saveNBT();
2453 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2455 if($this->location->isValid()){
2456 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2459 if($this->hasValidCustomSpawn()){
2460 $spawn = $this->getSpawn();
2461 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2462 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2463 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2464 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2467 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2468 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2469 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2470 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2471 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2474 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2475 $nbt->
setLong(self::TAG_FIRST_PLAYED, (
int) $this->firstPlayed->format(
'Uv'));
2476 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2485 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2491 $this->removeCurrentWindow();
2493 $this->setDeathPosition($this->getPosition());
2495 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2498 if(!$ev->getKeepInventory()){
2499 foreach($ev->getDrops() as $item){
2500 $this->getWorld()->dropItem($this->location, $item);
2503 $this->hotbar->setSelectedIndex(0);
2504 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2505 $clearInventory($this->inventory);
2506 $clearInventory($this->armorInventory);
2507 $clearInventory($this->offHandInventory);
2510 if(!$ev->getKeepXp()){
2511 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2512 $this->xpManager->setXpAndProgress(0, 0.0);
2515 if($ev->getDeathMessage() !==
""){
2516 $this->server->broadcastMessage($ev->getDeathMessage());
2519 $this->startDeathAnimation();
2521 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2525 parent::onDeathUpdate($tickDiff);
2529 public function respawn() : void{
2530 if($this->
server->isHardcore()){
2531 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2532 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2537 $this->actuallyRespawn();
2540 protected function actuallyRespawn() : void{
2541 if($this->respawnLocked){
2544 $this->respawnLocked =
true;
2546 $this->logger->debug(
"Waiting for safe respawn position to be located");
2547 $spawn = $this->getSpawn();
2548 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2549 function(Position $safeSpawn) :
void{
2550 if(!$this->isConnected()){
2553 $this->logger->debug(
"Respawn position located, completing respawn");
2554 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2555 $spawnPosition = $ev->getRespawnPosition();
2556 $spawnBlock = $spawnPosition->
getWorld()->getBlock($spawnPosition);
2557 if($spawnBlock instanceof RespawnAnchor){
2558 if($spawnBlock->getCharges() > 0){
2559 $spawnPosition->
getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2560 $spawnPosition->
getWorld()->addSound($spawnPosition,
new RespawnAnchorDepleteSound());
2562 $defaultSpawn = $this->
server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2563 if($defaultSpawn !==
null){
2564 $this->setSpawn($defaultSpawn);
2565 $ev->setRespawnPosition($defaultSpawn);
2566 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2572 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2573 $this->teleport($realSpawn);
2575 $this->setSprinting(
false);
2576 $this->setSneaking(
false);
2577 $this->setFlying(
false);
2579 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2580 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2581 $this->deadTicks = 0;
2582 $this->noDamageTicks = 60;
2584 $this->effectManager->clear();
2585 $this->setHealth($this->getMaxHealth());
2587 foreach($this->attributeMap->getAll() as $attr){
2588 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2591 $attr->resetToDefault();
2594 $this->spawnToAll();
2595 $this->scheduleUpdate();
2597 $this->getNetworkSession()->onServerRespawn();
2598 $this->respawnLocked =
false;
2601 if($this->isConnected()){
2602 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2609 parent::applyPostDamageEffects($source);
2611 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_DAMAGE);
2615 if(!$this->isAlive()){
2619 if($this->isCreative()
2620 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2623 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2627 parent::attack($source);
2630 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2631 parent::syncNetworkData($properties);
2633 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2634 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2636 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2637 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2639 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2640 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2642 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2643 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2645 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2646 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2647 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2651 public function sendData(?array $targets, ?array $data =
null) : void{
2652 if($targets === null){
2653 $targets = $this->getViewers();
2656 parent::sendData($targets, $data);
2660 if($this->spawned && $targets === null){
2661 $targets = $this->getViewers();
2664 parent::broadcastAnimation($animation, $targets);
2668 if($this->spawned && $targets === null){
2669 $targets = $this->getViewers();
2672 parent::broadcastSound($sound, $targets);
2678 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2679 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2685 if(parent::teleport($pos, $yaw, $pitch)){
2687 $this->removeCurrentWindow();
2690 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2691 $this->broadcastMovement(
true);
2693 $this->spawnToAll();
2695 $this->resetFallDistance();
2696 $this->nextChunkOrderRun = 0;
2697 if($this->spawnChunkLoadCount !== -1){
2698 $this->spawnChunkLoadCount = 0;
2700 $this->blockBreakHandler =
null;
2704 $this->resetLastMovements();
2712 protected function addDefaultWindows() : void{
2713 $this->cursorInventory = new SimpleInventory(1);
2714 $this->craftingGrid =
new CraftingGrid(CraftingGrid::SIZE_SMALL);
2716 $this->addPermanentWindows([
2717 new PlayerInventoryWindow($this, $this->inventory, PlayerInventoryWindow::TYPE_INVENTORY),
2718 new PlayerInventoryWindow($this, $this->armorInventory, PlayerInventoryWindow::TYPE_ARMOR),
2719 new PlayerInventoryWindow($this, $this->cursorInventory, PlayerInventoryWindow::TYPE_CURSOR),
2720 new PlayerInventoryWindow($this, $this->offHandInventory, PlayerInventoryWindow::TYPE_OFFHAND),
2721 new PlayerInventoryWindow($this, $this->craftingGrid, PlayerInventoryWindow::TYPE_CRAFTING),
2725 public function getCursorInventory() : Inventory{
2726 return $this->cursorInventory;
2729 public function getCraftingGrid() : CraftingGrid{
2730 return $this->craftingGrid;
2738 return $this->creativeInventory;
2745 $this->creativeInventory = $inventory;
2746 if($this->spawned && $this->isConnected()){
2747 $this->getNetworkSession()->getInvManager()?->syncCreative();
2755 private function doCloseInventory() : void{
2756 $windowsToClear = [];
2757 $mainInventoryWindow =
null;
2758 foreach($this->permanentWindows as $window){
2759 if($window->getType() === PlayerInventoryWindow::TYPE_CRAFTING || $window->getType() === PlayerInventoryWindow::TYPE_CURSOR){
2760 $windowsToClear[] = $window;
2761 }elseif($window->getType() === PlayerInventoryWindow::TYPE_INVENTORY){
2762 $mainInventoryWindow = $window;
2765 if($mainInventoryWindow ===
null){
2769 throw new AssumptionFailedError(
"This should never be null");
2772 if($this->currentWindow instanceof TemporaryInventoryWindow){
2773 $windowsToClear[] = $this->currentWindow;
2776 $builder =
new TransactionBuilder();
2777 foreach($windowsToClear as $window){
2778 $contents = $window->getInventory()->getContents();
2780 if(count($contents) > 0){
2781 $drops = $builder->getActionBuilder($mainInventoryWindow)->addItem(...$contents);
2782 foreach($drops as $drop){
2783 $builder->addAction(
new DropItemAction($drop));
2786 $builder->getActionBuilder($window)->clearAll();
2790 $actions = $builder->generateActions();
2791 if(count($actions) !== 0){
2792 $transaction =
new InventoryTransaction($this, $actions);
2794 $transaction->execute();
2795 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2796 }
catch(TransactionCancelledException){
2797 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2798 foreach($windowsToClear as $window){
2799 $window->getInventory()->clearAll();
2801 }
catch(TransactionValidationException $e){
2802 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2811 return $this->currentWindow;
2818 if($window === $this->currentWindow){
2821 if($window->getViewer() !== $this){
2822 throw new \InvalidArgumentException(
"Cannot reuse InventoryWindow instances, please create a new one for each player");
2826 if($ev->isCancelled()){
2830 $this->removeCurrentWindow();
2832 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2833 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2835 $this->logger->debug(
"Opening inventory window " . get_class($window) .
"#" . spl_object_id($window));
2836 $inventoryManager->onCurrentWindowChange($window);
2838 $this->currentWindow = $window;
2842 public function removeCurrentWindow() : void{
2843 $this->doCloseInventory();
2844 if($this->currentWindow !==
null){
2845 $currentWindow = $this->currentWindow;
2846 $this->logger->debug(
"Closing inventory window " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2847 $this->currentWindow->onClose();
2848 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2849 $inventoryManager->onCurrentWindowRemove();
2851 $this->currentWindow =
null;
2852 (
new InventoryCloseEvent($currentWindow, $this))->call();
2860 foreach($windows as $window){
2862 $this->permanentWindows[spl_object_id($window)] = $window;
2866 protected function removePermanentWindows() : void{
2867 foreach($this->permanentWindows as $window){
2870 $this->permanentWindows = [];
2878 return $this->permanentWindows;
2885 $block = $this->getWorld()->getBlock($position);
2887 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2888 $this->getNetworkSession()->onOpenSignEditor($position, $frontFace);
2890 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2894 use ChunkListenerNoOpTrait {
2895 onChunkChanged as
private;
2896 onChunkUnloaded as
private;
2900 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2901 if($status === UsedChunkStatus::SENT){
2902 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2903 $this->nextChunkOrderRun = 0;
2908 if($this->isUsingChunk($chunkX, $chunkZ)){
2909 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2910 $this->unloadChunk($chunkX, $chunkZ);