141 private const INCOMING_PACKET_BATCH_PER_TICK = 2;
142 private const INCOMING_PACKET_BATCH_BUFFER_TICKS = 100;
144 private const INCOMING_GAME_PACKETS_PER_TICK = 2;
145 private const INCOMING_GAME_PACKETS_BUFFER_TICKS = 100;
150 private \PrefixedLogger $logger;
151 private ?
Player $player =
null;
153 private ?
int $ping =
null;
157 private bool $connected =
true;
158 private bool $disconnectGuard =
false;
159 private bool $loggedIn =
false;
160 private bool $authenticated =
false;
161 private int $connectTime;
162 private ?
CompoundTag $cachedOfflinePlayerData =
null;
167 private array $sendBuffer = [];
172 private array $sendBufferAckPromises = [];
175 private \SplQueue $compressedQueue;
176 private bool $forceAsyncCompression =
true;
177 private bool $enableCompression =
false;
179 private int $nextAckReceiptId = 0;
184 private array $ackPromisesByReceiptId = [];
194 public function __construct(
206 $this->logger = new \PrefixedLogger($this->
server->getLogger(), $this->getLogPrefix());
208 $this->compressedQueue = new \SplQueue();
212 $this->connectTime = time();
213 $this->packetBatchLimiter =
new PacketRateLimiter(
"Packet Batches", self::INCOMING_PACKET_BATCH_PER_TICK, self::INCOMING_PACKET_BATCH_BUFFER_TICKS);
214 $this->gamePacketLimiter =
new PacketRateLimiter(
"Game Packets", self::INCOMING_GAME_PACKETS_PER_TICK, self::INCOMING_GAME_PACKETS_BUFFER_TICKS);
218 $this->onSessionStartSuccess(...)
221 $this->manager->add($this);
222 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_open()));
225 private function getLogPrefix() :
string{
226 return "NetworkSession: " . $this->getDisplayName();
229 public function getLogger() : \
Logger{
230 return $this->logger;
233 private function onSessionStartSuccess() :
void{
234 $this->logger->debug(
"Session start handshake completed, awaiting login packet");
235 $this->flushSendBuffer(
true);
236 $this->enableCompression =
true;
242 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_playerName(TextFormat::AQUA . $info->getUsername() . TextFormat::RESET)));
243 $this->logger->setPrefix($this->getLogPrefix());
244 $this->manager->markLoginReceived($this);
246 $this->setAuthenticationStatus(...)
250 protected function createPlayer() :
void{
251 $this->
server->createPlayer($this, $this->info, $this->authenticated, $this->cachedOfflinePlayerData)->onCompletion(
252 $this->onPlayerCreated(...),
255 $this->disconnectWithError(
256 reason:
"Failed to create player",
257 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_internal()
263 private function onPlayerCreated(
Player $player) :
void{
264 if(!$this->isConnected()){
268 $this->player = $player;
269 if(!$this->
server->addOnlinePlayer($player)){
275 $effectManager = $this->player->getEffects();
276 $effectManager->getEffectAddHooks()->add($effectAddHook =
function(
EffectInstance $effect,
bool $replacesOldEffect) :
void{
277 $this->entityEventBroadcaster->onEntityEffectAdded([$this], $this->player, $effect, $replacesOldEffect);
279 $effectManager->getEffectRemoveHooks()->add($effectRemoveHook =
function(
EffectInstance $effect) :
void{
280 $this->entityEventBroadcaster->onEntityEffectRemoved([$this], $this->player, $effect);
282 $this->disposeHooks->add(
static function() use ($effectManager, $effectAddHook, $effectRemoveHook) :
void{
283 $effectManager->getEffectAddHooks()->remove($effectAddHook);
284 $effectManager->getEffectRemoveHooks()->remove($effectRemoveHook);
287 $permissionHooks = $this->player->getPermissionRecalculationCallbacks();
288 $permissionHooks->add($permHook =
function() :
void{
289 $this->logger->debug(
"Syncing available commands and abilities/permissions due to permission recalculation");
290 $this->syncAbilities($this->player);
291 $this->syncAvailableCommands();
293 $this->disposeHooks->add(
static function() use ($permissionHooks, $permHook) :
void{
294 $permissionHooks->remove($permHook);
296 $this->beginSpawnSequence();
299 public function getPlayer() : ?
Player{
300 return $this->player;
303 public function getPlayerInfo() : ?
PlayerInfo{
307 public function isConnected() :
bool{
308 return $this->connected && !$this->disconnectGuard;
311 public function getIp() :
string{
315 public function getPort() :
int{
319 public function getDisplayName() :
string{
320 return $this->info !==
null ? $this->info->getUsername() : $this->ip .
" " . $this->port;
333 public function updatePing(
int $ping) : void{
337 public function getHandler() : ?PacketHandler{
338 return $this->handler;
341 public function setHandler(?PacketHandler $handler) : void{
342 if($this->connected){
343 $this->handler = $handler;
344 if($this->handler !==
null){
345 $this->handler->setUp();
354 if(!$this->connected){
358 Timings::$playerNetworkReceive->startTiming();
360 $this->packetBatchLimiter->decrement();
362 if($this->cipher !==
null){
363 Timings::$playerNetworkReceiveDecrypt->startTiming();
365 $payload = $this->cipher->decrypt($payload);
366 }
catch(DecryptionException $e){
367 $this->logger->debug(
"Encrypted packet: " . base64_encode($payload));
368 throw PacketHandlingException::wrap($e,
"Packet decryption error");
370 Timings::$playerNetworkReceiveDecrypt->stopTiming();
374 if(strlen($payload) < 1){
375 throw new PacketHandlingException(
"No bytes in payload");
378 if($this->enableCompression){
379 $compressionType = ord($payload[0]);
380 $compressed = substr($payload, 1);
381 if($compressionType === CompressionAlgorithm::NONE){
382 $decompressed = $compressed;
383 }elseif($compressionType === $this->compressor->getNetworkId()){
384 Timings::$playerNetworkReceiveDecompress->startTiming();
386 $decompressed = $this->compressor->decompress($compressed);
387 }
catch(DecompressionException $e){
388 $this->logger->debug(
"Failed to decompress packet: " . base64_encode($compressed));
389 throw PacketHandlingException::wrap($e,
"Compressed packet batch decode error");
391 Timings::$playerNetworkReceiveDecompress->stopTiming();
394 throw new PacketHandlingException(
"Packet compressed with unexpected compression type $compressionType");
397 $decompressed = $payload;
401 $stream =
new BinaryStream($decompressed);
402 foreach(PacketBatch::decodeRaw($stream) as $buffer){
403 $this->gamePacketLimiter->decrement();
404 $packet = $this->packetPool->getPacket($buffer);
405 if($packet ===
null){
406 $this->logger->debug(
"Unknown packet: " . base64_encode($buffer));
407 throw new PacketHandlingException(
"Unknown packet received");
410 $this->handleDataPacket($packet, $buffer);
411 }
catch(PacketHandlingException $e){
412 $this->logger->debug($packet->getName() .
": " . base64_encode($buffer));
413 throw PacketHandlingException::wrap($e,
"Error processing " . $packet->getName());
416 }
catch(PacketDecodeException|BinaryDataException $e){
417 $this->logger->logException($e);
418 throw PacketHandlingException::wrap($e,
"Packet batch decode error");
421 Timings::$playerNetworkReceive->stopTiming();
433 $timings = Timings::getReceiveDataPacketTimings($packet);
434 $timings->startTiming();
437 if(DataPacketDecodeEvent::hasHandlers()){
440 if($ev->isCancelled()){
445 $decodeTimings = Timings::getDecodeDataPacketTimings($packet);
446 $decodeTimings->startTiming();
448 $stream = PacketSerializer::decoder($buffer, 0);
450 $packet->decode($stream);
451 }
catch(PacketDecodeException $e){
452 throw PacketHandlingException::wrap($e);
454 if(!$stream->feof()){
455 $remains = substr($stream->getBuffer(), $stream->getOffset());
456 $this->logger->debug(
"Still " . strlen($remains) .
" bytes unread in " . $packet->getName() .
": " . bin2hex($remains));
459 $decodeTimings->stopTiming();
462 if(DataPacketReceiveEvent::hasHandlers()){
463 $ev =
new DataPacketReceiveEvent($this, $packet);
465 if($ev->isCancelled()){
469 $handlerTimings = Timings::getHandleDataPacketTimings($packet);
470 $handlerTimings->startTiming();
472 if($this->handler ===
null || !$packet->handle($this->handler)){
473 $this->logger->debug(
"Unhandled " . $packet->getName() .
": " . base64_encode($stream->getBuffer()));
476 $handlerTimings->stopTiming();
479 $timings->stopTiming();
483 public function handleAckReceipt(
int $receiptId) : void{
484 if(!$this->connected){
487 if(isset($this->ackPromisesByReceiptId[$receiptId])){
488 $promises = $this->ackPromisesByReceiptId[$receiptId];
489 unset($this->ackPromisesByReceiptId[$receiptId]);
490 foreach($promises as $promise){
491 $promise->resolve(
true);
499 private function sendDataPacketInternal(ClientboundPacket $packet,
bool $immediate, ?PromiseResolver $ackReceiptResolver) : bool{
500 if(!$this->connected){
504 if(!$this->loggedIn && !$packet->canBeSentBeforeLogin()){
505 throw new \InvalidArgumentException(
"Attempted to send " . get_class($packet) .
" to " . $this->getDisplayName() .
" too early");
508 $timings = Timings::getSendDataPacketTimings($packet);
509 $timings->startTiming();
511 if(DataPacketSendEvent::hasHandlers()){
512 $ev = new DataPacketSendEvent([$this], [$packet]);
514 if($ev->isCancelled()){
517 $packets = $ev->getPackets();
519 $packets = [$packet];
522 if($ackReceiptResolver !==
null){
523 $this->sendBufferAckPromises[] = $ackReceiptResolver;
525 foreach($packets as $evPacket){
526 $this->addToSendBuffer(self::encodePacketTimed(PacketSerializer::encoder(), $evPacket));
529 $this->flushSendBuffer(true);
534 $timings->stopTiming();
538 public function sendDataPacket(ClientboundPacket $packet,
bool $immediate =
false) : bool{
539 return $this->sendDataPacketInternal($packet, $immediate, null);
548 if(!$this->sendDataPacketInternal($packet, $immediate, $resolver)){
558 public static function encodePacketTimed(PacketSerializer $serializer, ClientboundPacket $packet) : string{
559 $timings =
Timings::getEncodeDataPacketTimings($packet);
560 $timings->startTiming();
562 $packet->encode($serializer);
563 return $serializer->getBuffer();
565 $timings->stopTiming();
572 public function addToSendBuffer(
string $buffer) : void{
573 $this->sendBuffer[] = $buffer;
576 private function flushSendBuffer(
bool $immediate =
false) : void{
577 if(count($this->sendBuffer) > 0){
578 Timings::$playerNetworkSend->startTiming();
583 }elseif($this->forceAsyncCompression){
587 $stream =
new BinaryStream();
588 PacketBatch::encodeRaw($stream, $this->sendBuffer);
590 if($this->enableCompression){
591 $batch = $this->
server->prepareBatch($stream->getBuffer(), $this->compressor, $syncMode, Timings::$playerNetworkSendCompressSessionBuffer);
593 $batch = $stream->getBuffer();
595 $this->sendBuffer = [];
596 $ackPromises = $this->sendBufferAckPromises;
597 $this->sendBufferAckPromises = [];
598 $this->queueCompressedNoBufferFlush($batch, $immediate, $ackPromises);
600 Timings::$playerNetworkSend->stopTiming();
605 public function getBroadcaster() : PacketBroadcaster{ return $this->broadcaster; }
607 public function getEntityEventBroadcaster() : EntityEventBroadcaster{ return $this->entityEventBroadcaster; }
609 public function getCompressor() : Compressor{
610 return $this->compressor;
613 public function getTypeConverter() : TypeConverter{ return $this->typeConverter; }
615 public function queueCompressed(CompressBatchPromise|
string $payload,
bool $immediate =
false) : void{
616 Timings::$playerNetworkSend->startTiming();
618 $this->flushSendBuffer($immediate);
619 $this->queueCompressedNoBufferFlush($payload, $immediate);
621 Timings::$playerNetworkSend->stopTiming();
630 private function queueCompressedNoBufferFlush(CompressBatchPromise|
string $batch,
bool $immediate =
false, array $ackPromises = []) : void{
631 Timings::$playerNetworkSend->startTiming();
633 if(is_string($batch)){
636 $this->sendEncoded($batch,
true, $ackPromises);
638 $this->compressedQueue->enqueue([$batch, $ackPromises]);
639 $this->flushCompressedQueue();
643 $this->sendEncoded($batch->getResult(),
true, $ackPromises);
645 $this->compressedQueue->enqueue([$batch, $ackPromises]);
646 $batch->onResolve(
function() :
void{
647 if($this->connected){
648 $this->flushCompressedQueue();
653 Timings::$playerNetworkSend->stopTiming();
657 private function flushCompressedQueue() : void{
658 Timings::$playerNetworkSend->startTiming();
660 while(!$this->compressedQueue->isEmpty()){
662 [$current, $ackPromises] = $this->compressedQueue->bottom();
663 if(is_string($current)){
664 $this->compressedQueue->dequeue();
665 $this->sendEncoded($current,
false, $ackPromises);
667 }elseif($current->hasResult()){
668 $this->compressedQueue->dequeue();
669 $this->sendEncoded($current->getResult(),
false, $ackPromises);
677 Timings::$playerNetworkSend->stopTiming();
685 private function sendEncoded(
string $payload,
bool $immediate, array $ackPromises) : void{
686 if($this->cipher !== null){
687 Timings::$playerNetworkSendEncrypt->startTiming();
688 $payload = $this->cipher->encrypt($payload);
689 Timings::$playerNetworkSendEncrypt->stopTiming();
692 if(count($ackPromises) > 0){
693 $ackReceiptId = $this->nextAckReceiptId++;
694 $this->ackPromisesByReceiptId[$ackReceiptId] = $ackPromises;
696 $ackReceiptId =
null;
698 $this->sender->send($payload, $immediate, $ackReceiptId);
704 private function tryDisconnect(\Closure $func, Translatable|
string $reason) : void{
705 if($this->connected && !$this->disconnectGuard){
706 $this->disconnectGuard =
true;
708 $this->disconnectGuard =
false;
709 $this->flushSendBuffer(
true);
710 $this->sender->close(
"");
711 foreach($this->disposeHooks as $callback){
714 $this->disposeHooks->clear();
715 $this->setHandler(
null);
716 $this->connected =
false;
718 $ackPromisesByReceiptId = $this->ackPromisesByReceiptId;
719 $this->ackPromisesByReceiptId = [];
720 foreach($ackPromisesByReceiptId as $resolvers){
721 foreach($resolvers as $resolver){
725 $sendBufferAckPromises = $this->sendBufferAckPromises;
726 $this->sendBufferAckPromises = [];
727 foreach($sendBufferAckPromises as $resolver){
731 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_close($reason)));
739 private function dispose() : void{
740 $this->invManager = null;
743 private function sendDisconnectPacket(Translatable|
string $message) : void{
744 if($message instanceof Translatable){
745 $translated = $this->
server->getLanguage()->translate($message);
747 $translated = $message;
749 $this->sendDataPacket(DisconnectPacket::create(0, $translated,
""));
759 $this->tryDisconnect(function() use ($reason, $disconnectScreenMessage, $notify) : void{
761 $this->sendDisconnectPacket($disconnectScreenMessage ?? $reason);
763 if($this->player !==
null){
764 $this->player->onPostDisconnect($reason,
null);
769 public function disconnectWithError(Translatable|
string $reason, Translatable|
string|
null $disconnectScreenMessage =
null) : void{
770 $errorId = implode(
"-", str_split(bin2hex(random_bytes(6)), 4));
773 reason: KnownTranslationFactory::pocketmine_disconnect_error($reason, $errorId)->prefix(TextFormat::RED),
774 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error($disconnectScreenMessage ?? $reason, $errorId),
778 public function disconnectIncompatibleProtocol(
int $protocolVersion) : void{
779 $this->tryDisconnect(
780 function() use ($protocolVersion) : void{
781 $this->sendDataPacket(PlayStatusPacket::create($protocolVersion < ProtocolInfo::CURRENT_PROTOCOL ? PlayStatusPacket::LOGIN_FAILED_CLIENT : PlayStatusPacket::LOGIN_FAILED_SERVER), true);
783 KnownTranslationFactory::pocketmine_disconnect_incompatibleProtocol((
string) $protocolVersion)
792 $this->tryDisconnect(
function() use ($ip, $port, $reason) :
void{
793 $this->sendDataPacket(TransferPacket::create($ip, $port,
false),
true);
794 if($this->player !==
null){
795 $this->player->onPostDisconnect($reason,
null);
804 $this->tryDisconnect(function() use ($disconnectScreenMessage) : void{
805 $this->sendDisconnectPacket($disconnectScreenMessage);
814 $this->tryDisconnect(function() use ($reason) : void{
815 if($this->player !== null){
816 $this->player->onPostDisconnect($reason,
null);
821 private function setAuthenticationStatus(
bool $authenticated,
bool $authRequired,
Translatable|
string|
null $error, ?
string $clientPubKey) : void{
822 if(!$this->connected){
826 if($authenticated && !($this->info instanceof XboxLivePlayerInfo)){
827 $error =
"Expected XUID but none found";
828 }elseif($clientPubKey ===
null){
829 $error =
"Missing client public key";
834 $this->disconnectWithError(
835 reason: KnownTranslationFactory::pocketmine_disconnect_invalidSession($error),
836 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_authentication()
842 $this->authenticated = $authenticated;
844 if(!$this->authenticated){
846 $this->disconnect(
"Not authenticated", KnownTranslationFactory::disconnectionScreen_notAuthenticated());
849 if($this->info instanceof XboxLivePlayerInfo){
850 $this->logger->warning(
"Discarding unexpected XUID for non-authenticated player");
851 $this->info = $this->info->withoutXboxData();
854 $this->logger->debug(
"Xbox Live authenticated: " . ($this->authenticated ?
"YES" :
"NO"));
856 $checkXUID = $this->
server->getConfigGroup()->getPropertyBool(YmlServerProperties::PLAYER_VERIFY_XUID,
true);
857 $myXUID = $this->info instanceof XboxLivePlayerInfo ? $this->info->getXuid() :
"";
858 $kickForXUIDMismatch =
function(
string $xuid) use ($checkXUID, $myXUID) : bool{
859 if($checkXUID && $myXUID !== $xuid){
860 $this->logger->debug(
"XUID mismatch: expected '$xuid', but got '$myXUID'");
865 $this->disconnect(
"XUID does not match (possible impersonation attempt)");
871 foreach($this->manager->getSessions() as $existingSession){
872 if($existingSession === $this){
875 $info = $existingSession->getPlayerInfo();
876 if($info !==
null && (strcasecmp($info->getUsername(), $this->info->getUsername()) === 0 || $info->getUuid()->equals($this->info->getUuid()))){
877 if($kickForXUIDMismatch($info instanceof XboxLivePlayerInfo ? $info->getXuid() :
"")){
880 $ev =
new PlayerDuplicateLoginEvent($this, $existingSession, KnownTranslationFactory::disconnectionScreen_loggedinOtherLocation(),
null);
882 if($ev->isCancelled()){
883 $this->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
887 $existingSession->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
893 $this->cachedOfflinePlayerData = $this->
server->getOfflinePlayerData($this->info->getUsername());
895 $recordedXUID = $this->cachedOfflinePlayerData !==
null ? $this->cachedOfflinePlayerData->getTag(Player::TAG_LAST_KNOWN_XUID) :
null;
896 if(!($recordedXUID instanceof StringTag)){
897 $this->logger->debug(
"No previous XUID recorded, no choice but to trust this player");
898 }elseif(!$kickForXUIDMismatch($recordedXUID->getValue())){
899 $this->logger->debug(
"XUID match");
903 if(EncryptionContext::$ENABLED){
904 $this->
server->getAsyncPool()->submitTask(
new PrepareEncryptionTask($clientPubKey,
function(
string $encryptionKey,
string $handshakeJwt) :
void{
905 if(!$this->connected){
908 $this->sendDataPacket(ServerToClientHandshakePacket::create($handshakeJwt),
true);
910 $this->cipher = EncryptionContext::fakeGCM($encryptionKey);
912 $this->setHandler(
new HandshakePacketHandler($this->onServerLoginSuccess(...)));
913 $this->logger->debug(
"Enabled encryption");
916 $this->onServerLoginSuccess();
920 private function onServerLoginSuccess() : void{
921 $this->loggedIn = true;
923 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::LOGIN_SUCCESS));
925 $this->logger->debug(
"Initiating resource packs phase");
927 $packManager = $this->
server->getResourcePackManager();
928 $resourcePacks = $packManager->getResourceStack();
930 foreach($resourcePacks as $resourcePack){
931 $key = $packManager->getPackEncryptionKey($resourcePack->getPackId());
933 $keys[$resourcePack->getPackId()] = $key;
936 $event =
new PlayerResourcePackOfferEvent($this->info, $resourcePacks, $keys, $packManager->resourcePacksRequired());
938 $this->setHandler(
new ResourcePacksPacketHandler($this, $event->getResourcePacks(), $event->getEncryptionKeys(), $event->mustAccept(),
function() :
void{
939 $this->createPlayer();
943 private function beginSpawnSequence() : void{
944 $this->setHandler(new PreSpawnPacketHandler($this->
server, $this->player, $this, $this->invManager));
945 $this->player->setNoClientPredictions();
947 $this->logger->debug(
"Waiting for chunk radius request");
950 public function notifyTerrainReady() : void{
951 $this->logger->debug(
"Sending spawn notification, waiting for spawn response");
952 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::PLAYER_SPAWN));
953 $this->setHandler(
new SpawnResponsePacketHandler($this->onClientSpawnResponse(...)));
956 private function onClientSpawnResponse() : void{
957 $this->logger->debug(
"Received spawn response, entering in-game phase");
958 $this->player->setNoClientPredictions(
false);
959 $this->player->doFirstSpawn();
960 $this->forceAsyncCompression =
false;
961 $this->setHandler(
new InGamePacketHandler($this->player, $this, $this->invManager));
964 public function onServerDeath(Translatable|
string $deathMessage) : void{
965 if($this->handler instanceof InGamePacketHandler){
966 $this->setHandler(
new DeathPacketHandler($this->player, $this, $this->invManager ??
throw new AssumptionFailedError(), $deathMessage));
970 public function onServerRespawn() : void{
971 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $this->player->getAttributeMap()->getAll());
972 $this->player->sendData(
null);
974 $this->syncAbilities($this->player);
975 $this->invManager->syncAll();
976 $this->setHandler(
new InGamePacketHandler($this->player, $this, $this->invManager));
979 public function syncMovement(Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
980 if($this->player !== null){
981 $location = $this->player->getLocation();
982 $yaw = $yaw ?? $location->getYaw();
983 $pitch = $pitch ?? $location->getPitch();
985 $this->sendDataPacket(MovePlayerPacket::simple(
986 $this->player->getId(),
987 $this->player->getOffsetPosition($pos),
992 $this->player->onGround,
997 if($this->handler instanceof InGamePacketHandler){
998 $this->handler->forceMoveSync =
true;
1003 public function syncViewAreaRadius(
int $distance) : void{
1004 $this->sendDataPacket(ChunkRadiusUpdatedPacket::create($distance));
1007 public function syncViewAreaCenterPoint(Vector3 $newPos,
int $viewDistance) : void{
1008 $this->sendDataPacket(NetworkChunkPublisherUpdatePacket::create(BlockPosition::fromVector3($newPos), $viewDistance * 16, []));
1011 public function syncPlayerSpawnPoint(Position $newSpawn) : void{
1012 $newSpawnBlockPosition = BlockPosition::fromVector3($newSpawn);
1014 $this->sendDataPacket(SetSpawnPositionPacket::playerSpawn($newSpawnBlockPosition, DimensionIds::OVERWORLD, $newSpawnBlockPosition));
1017 public function syncWorldSpawnPoint(Position $newSpawn) : void{
1018 $this->sendDataPacket(SetSpawnPositionPacket::worldSpawn(BlockPosition::fromVector3($newSpawn), DimensionIds::OVERWORLD));
1021 public function syncGameMode(GameMode $mode,
bool $isRollback =
false) : void{
1022 $this->sendDataPacket(SetPlayerGameTypePacket::create($this->typeConverter->coreGameModeToProtocol($mode)));
1023 if($this->player !==
null){
1024 $this->syncAbilities($this->player);
1025 $this->syncAdventureSettings();
1027 if(!$isRollback && $this->invManager !==
null){
1028 $this->invManager->syncCreative();
1032 public function syncAbilities(Player $for) : void{
1033 $isOp = $for->hasPermission(DefaultPermissions::ROOT_OPERATOR);
1037 AbilitiesLayer::ABILITY_ALLOW_FLIGHT => $for->getAllowFlight(),
1038 AbilitiesLayer::ABILITY_FLYING => $for->isFlying(),
1039 AbilitiesLayer::ABILITY_NO_CLIP => !$for->hasBlockCollision(),
1040 AbilitiesLayer::ABILITY_OPERATOR => $isOp,
1041 AbilitiesLayer::ABILITY_TELEPORT => $for->hasPermission(DefaultPermissionNames::COMMAND_TELEPORT_SELF),
1042 AbilitiesLayer::ABILITY_INVULNERABLE => $for->isCreative(),
1043 AbilitiesLayer::ABILITY_MUTED =>
false,
1044 AbilitiesLayer::ABILITY_WORLD_BUILDER =>
false,
1045 AbilitiesLayer::ABILITY_INFINITE_RESOURCES => !$for->hasFiniteResources(),
1046 AbilitiesLayer::ABILITY_LIGHTNING =>
false,
1047 AbilitiesLayer::ABILITY_BUILD => !$for->isSpectator(),
1048 AbilitiesLayer::ABILITY_MINE => !$for->isSpectator(),
1049 AbilitiesLayer::ABILITY_DOORS_AND_SWITCHES => !$for->isSpectator(),
1050 AbilitiesLayer::ABILITY_OPEN_CONTAINERS => !$for->isSpectator(),
1051 AbilitiesLayer::ABILITY_ATTACK_PLAYERS => !$for->isSpectator(),
1052 AbilitiesLayer::ABILITY_ATTACK_MOBS => !$for->isSpectator(),
1053 AbilitiesLayer::ABILITY_PRIVILEGED_BUILDER =>
false,
1058 new AbilitiesLayer(AbilitiesLayer::LAYER_BASE, $boolAbilities, 0.05, 0.1),
1060 if(!$for->hasBlockCollision()){
1066 $layers[] = new AbilitiesLayer(AbilitiesLayer::LAYER_SPECTATOR, [
1067 AbilitiesLayer::ABILITY_FLYING => true,
1071 $this->sendDataPacket(UpdateAbilitiesPacket::create(
new AbilitiesData(
1072 $isOp ? CommandPermissions::OPERATOR : CommandPermissions::NORMAL,
1073 $isOp ? PlayerPermissions::OPERATOR : PlayerPermissions::MEMBER,
1079 public function syncAdventureSettings() : void{
1080 if($this->player === null){
1081 throw new \LogicException(
"Cannot sync adventure settings for a player that is not yet created");
1084 $this->sendDataPacket(UpdateAdventureSettingsPacket::create(
1085 noAttackingMobs:
false,
1086 noAttackingPlayers:
false,
1087 worldImmutable:
false,
1089 autoJump: $this->player->hasAutoJump()
1093 public function syncAvailableCommands() : void{
1095 foreach($this->
server->getCommandMap()->getCommands() as $name => $command){
1096 if(isset($commandData[$command->getLabel()]) || $command->getLabel() ===
"help" || !$command->testPermissionSilent($this->player)){
1100 $lname = strtolower($command->getLabel());
1101 $aliases = $command->getAliases();
1103 if(count($aliases) > 0){
1104 if(!in_array($lname, $aliases,
true)){
1106 $aliases[] = $lname;
1108 $aliasObj =
new CommandEnum(ucfirst($command->getLabel()) .
"Aliases", array_values($aliases));
1111 $description = $command->getDescription();
1112 $data =
new CommandData(
1114 $description instanceof Translatable ? $this->player->getLanguage()->translate($description) : $description,
1119 new CommandOverload(chaining:
false, parameters: [CommandParameter::standard(
"args", AvailableCommandsPacket::ARG_TYPE_RAWTEXT, 0,
true)])
1121 chainedSubCommandData: []
1124 $commandData[$command->getLabel()] = $data;
1127 $this->sendDataPacket(AvailableCommandsPacket::create($commandData, [], [], []));
1136 $language = $this->player->getLanguage();
1138 return [$language->translateString($message->getText(), $parameters,
"pocketmine."), $parameters];
1141 public function onChatMessage(
Translatable|
string $message) : void{
1143 if(!$this->
server->isLanguageForced()){
1144 $this->sendDataPacket(TextPacket::translation(...$this->prepareClientTranslatableMessage($message)));
1146 $this->sendDataPacket(TextPacket::raw($this->player->getLanguage()->translate($message)));
1149 $this->sendDataPacket(TextPacket::raw($message));
1153 public function onJukeboxPopup(Translatable|
string $message) : void{
1155 if($message instanceof Translatable){
1156 if(!$this->server->isLanguageForced()){
1157 [$message, $parameters] = $this->prepareClientTranslatableMessage($message);
1159 $message = $this->player->getLanguage()->translate($message);
1162 $this->sendDataPacket(TextPacket::jukeboxPopup($message, $parameters));
1165 public function onPopup(
string $message) : void{
1166 $this->sendDataPacket(TextPacket::popup($message));
1169 public function onTip(
string $message) : void{
1170 $this->sendDataPacket(TextPacket::tip($message));
1173 public function onFormSent(
int $id, Form $form) : bool{
1174 return $this->sendDataPacket(ModalFormRequestPacket::create($id, json_encode($form, JSON_THROW_ON_ERROR)));
1177 public function onCloseAllForms() : void{
1178 $this->sendDataPacket(ClientboundCloseFormPacket::create());
1187 $world = $this->player->getLocation()->getWorld();
1188 ChunkCache::getInstance($world, $this->compressor)->request($chunkX, $chunkZ)->onResolve(
1192 if(!$this->isConnected()){
1195 $currentWorld = $this->player->getLocation()->getWorld();
1196 if($world !== $currentWorld || ($status = $this->player->getUsedChunkStatus($chunkX, $chunkZ)) ===
null){
1197 $this->logger->debug(
"Tried to send no-longer-active chunk $chunkX $chunkZ in world " . $world->getFolderName());
1200 if($status !== UsedChunkStatus::REQUESTED_SENDING){
1207 $world->timings->syncChunkSend->startTiming();
1209 $this->queueCompressed($promise);
1212 $world->timings->syncChunkSend->stopTiming();
1218 public function stopUsingChunk(
int $chunkX,
int $chunkZ) : void{
1222 public function onEnterWorld() : void{
1223 if($this->player !== null){
1224 $world = $this->player->getWorld();
1225 $this->syncWorldTime($world->getTime());
1226 $this->syncWorldDifficulty($world->getDifficulty());
1227 $this->syncWorldSpawnPoint($world->getSpawnLocation());
1232 public function syncWorldTime(
int $worldTime) : void{
1233 $this->sendDataPacket(SetTimePacket::create($worldTime));
1236 public function syncWorldDifficulty(
int $worldDifficulty) : void{
1237 $this->sendDataPacket(SetDifficultyPacket::create($worldDifficulty));
1240 public function getInvManager() : ?InventoryManager{
1241 return $this->invManager;
1249 return
PlayerListEntry::createAdditionEntry($player->getUniqueId(), $player->getId(), $player->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($player->getSkin()), $player->getXuid());
1253 public function onPlayerAdded(
Player $p) : void{
1254 $this->sendDataPacket(PlayerListPacket::add([PlayerListEntry::createAdditionEntry($p->getUniqueId(), $p->getId(), $p->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($p->getSkin()), $p->getXuid())]));
1257 public function onPlayerRemoved(
Player $p) : void{
1258 if($p !== $this->player){
1259 $this->sendDataPacket(PlayerListPacket::remove([PlayerListEntry::createRemovalEntry($p->
getUniqueId())]));
1263 public function onTitle(
string $title) : void{
1264 $this->sendDataPacket(SetTitlePacket::title($title));
1267 public function onSubTitle(
string $subtitle) : void{
1268 $this->sendDataPacket(SetTitlePacket::subtitle($subtitle));
1271 public function onActionBar(
string $actionBar) : void{
1272 $this->sendDataPacket(SetTitlePacket::actionBarMessage($actionBar));
1275 public function onClearTitle() : void{
1276 $this->sendDataPacket(SetTitlePacket::clearTitle());
1279 public function onResetTitleOptions() : void{
1280 $this->sendDataPacket(SetTitlePacket::resetTitleOptions());
1283 public function onTitleDuration(
int $fadeIn,
int $stay,
int $fadeOut) : void{
1284 $this->sendDataPacket(SetTitlePacket::setAnimationTimes($fadeIn, $stay, $fadeOut));
1287 public function onToastNotification(
string $title,
string $body) : void{
1288 $this->sendDataPacket(ToastRequestPacket::create($title, $body));
1291 public function onOpenSignEditor(Vector3 $signPosition,
bool $frontSide) : void{
1292 $this->sendDataPacket(OpenSignPacket::create(BlockPosition::fromVector3($signPosition), $frontSide));
1295 public function onItemCooldownChanged(Item $item,
int $ticks) : void{
1296 $this->sendDataPacket(PlayerStartItemCooldownPacket::create(
1297 GlobalItemDataHandlers::getSerializer()->serializeType($item)->getName(),
1302 public function tick() : void{
1303 if(!$this->isConnected()){
1308 if($this->info ===
null){
1309 if(time() >= $this->connectTime + 10){
1310 $this->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_loginTimeout());
1316 if($this->player !==
null){
1317 $this->player->doChunkRequests();
1319 $dirtyAttributes = $this->player->getAttributeMap()->needSend();
1320 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $dirtyAttributes);
1321 foreach($dirtyAttributes as $attribute){
1324 $attribute->markSynchronized();
1327 Timings::$playerNetworkSendInventorySync->startTiming();
1329 $this->invManager?->flushPendingUpdates();
1331 Timings::$playerNetworkSendInventorySync->stopTiming();
1334 $this->flushSendBuffer();