147 private const INCOMING_PACKET_BATCH_PER_TICK = 2;
148 private const INCOMING_PACKET_BATCH_BUFFER_TICKS = 100;
150 private const INCOMING_GAME_PACKETS_PER_TICK = 2;
151 private const INCOMING_GAME_PACKETS_BUFFER_TICKS = 100;
153 private const INCOMING_PACKET_BATCH_HARD_LIMIT = 300;
158 private \PrefixedLogger $logger;
159 private ?
Player $player =
null;
161 private ?
int $ping =
null;
168 private ?array $handlerActions =
null;
170 private bool $connected =
true;
171 private bool $disconnectGuard =
false;
172 private bool $loggedIn =
false;
173 private bool $authenticated =
false;
174 private int $connectTime;
175 private ?
CompoundTag $cachedOfflinePlayerData =
null;
183 private array $sendBuffer = [];
188 private array $sendBufferAckPromises = [];
191 private \SplQueue $compressedQueue;
192 private bool $forceAsyncCompression =
true;
193 private bool $enableCompression =
false;
195 private int $nextAckReceiptId = 0;
200 private array $ackPromisesByReceiptId = [];
210 private string $noisyPacketBuffer =
"";
211 private int $noisyPacketsDropped = 0;
213 public function __construct(
225 $this->logger = new \PrefixedLogger($this->
server->getLogger(), $this->getLogPrefix());
227 $this->compressedQueue = new \SplQueue();
231 $this->connectTime = time();
232 $this->packetBatchLimiter =
new PacketRateLimiter(
"Packet Batches", self::INCOMING_PACKET_BATCH_PER_TICK, self::INCOMING_PACKET_BATCH_BUFFER_TICKS);
233 $this->gamePacketLimiter =
new PacketRateLimiter(
"Game Packets", self::INCOMING_GAME_PACKETS_PER_TICK, self::INCOMING_GAME_PACKETS_BUFFER_TICKS);
237 $this->onSessionStartSuccess(...)
240 $this->manager->add($this);
241 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_open()));
244 private function getLogPrefix() :
string{
245 return "NetworkSession: " . $this->getDisplayName();
248 public function getLogger() : \
Logger{
249 return $this->logger;
252 private function onSessionStartSuccess() :
void{
253 $this->logger->debug(
"Session start handshake completed, awaiting login packet");
254 $this->flushGamePacketQueue();
255 $this->enableCompression =
true;
261 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_playerName(TextFormat::AQUA . $info->getUsername() . TextFormat::RESET)));
262 $this->logger->setPrefix($this->getLogPrefix());
263 $this->manager->markLoginReceived($this);
265 $this->setAuthenticationStatus(...)
269 protected function createPlayer() :
void{
270 $this->
server->createPlayer($this, $this->info, $this->authenticated, $this->cachedOfflinePlayerData)->onCompletion(
271 $this->onPlayerCreated(...),
274 $this->disconnectWithError(
275 reason:
"Failed to create player",
276 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_internal()
282 private function onPlayerCreated(
Player $player) :
void{
283 if(!$this->isConnected()){
287 $this->player = $player;
288 if(!$this->
server->addOnlinePlayer($player)){
294 $effectManager = $this->player->getEffects();
295 $effectManager->getEffectAddHooks()->add($effectAddHook =
function(
EffectInstance $effect,
bool $replacesOldEffect) :
void{
296 $this->entityEventBroadcaster->onEntityEffectAdded([$this], $this->player, $effect, $replacesOldEffect);
298 $effectManager->getEffectRemoveHooks()->add($effectRemoveHook =
function(
EffectInstance $effect) :
void{
299 $this->entityEventBroadcaster->onEntityEffectRemoved([$this], $this->player, $effect);
301 $this->disposeHooks->add(
static function() use ($effectManager, $effectAddHook, $effectRemoveHook) :
void{
302 $effectManager->getEffectAddHooks()->remove($effectAddHook);
303 $effectManager->getEffectRemoveHooks()->remove($effectRemoveHook);
306 $permissionHooks = $this->player->getPermissionRecalculationCallbacks();
307 $permissionHooks->add($permHook =
function() :
void{
308 $this->logger->debug(
"Syncing available commands and abilities/permissions due to permission recalculation");
309 $this->syncAbilities($this->player);
310 $this->syncAvailableCommands();
312 $this->disposeHooks->add(
static function() use ($permissionHooks, $permHook) :
void{
313 $permissionHooks->remove($permHook);
315 $this->beginSpawnSequence();
318 public function getPlayer() : ?
Player{
319 return $this->player;
322 public function getPlayerInfo() : ?
PlayerInfo{
326 public function isConnected() :
bool{
327 return $this->connected && !$this->disconnectGuard;
330 public function getIp() :
string{
334 public function getPort() :
int{
338 public function getDisplayName() :
string{
339 return $this->info !==
null ? $this->info->getUsername() : $this->ip .
" " . $this->port;
352 public function updatePing(
int $ping) : void{
356 public function getHandler() : ?PacketHandler{
357 return $this->handler;
360 public function setHandler(?PacketHandler $handler) : void{
361 if($this->connected){
362 $this->handler = $handler;
363 if($this->handler !==
null){
364 $this->handlerActions = PacketHandlerInspector::getHandlerActions($this->handler);
365 $this->handler->setUp();
367 $this->handlerActions =
null;
372 private function checkRepeatedPacketFilter(
string $buffer) : bool{
373 if($buffer === $this->noisyPacketBuffer){
374 $this->noisyPacketsDropped++;
380 $this->noisyPacketBuffer =
"";
381 $this->noisyPacketsDropped = 0;
390 if(!$this->connected){
394 Timings::$playerNetworkReceive->startTiming();
396 $this->packetBatchLimiter->decrement();
398 if($this->cipher !==
null){
399 Timings::$playerNetworkReceiveDecrypt->startTiming();
401 $payload = $this->cipher->decrypt($payload);
402 }
catch(DecryptionException $e){
403 $this->logger->debug(
"Encrypted packet: " . base64_encode($payload));
404 throw PacketHandlingException::wrap($e,
"Packet decryption error");
406 Timings::$playerNetworkReceiveDecrypt->stopTiming();
410 if(strlen($payload) < 1){
411 throw new PacketHandlingException(
"No bytes in payload");
414 if($this->enableCompression){
415 $compressionType = ord($payload[0]);
416 $compressed = substr($payload, 1);
417 if($compressionType === CompressionAlgorithm::NONE){
418 $decompressed = $compressed;
419 }elseif($compressionType === $this->compressor->getNetworkId()){
420 Timings::$playerNetworkReceiveDecompress->startTiming();
422 $decompressed = $this->compressor->decompress($compressed);
423 }
catch(DecompressionException $e){
424 $this->logger->debug(
"Failed to decompress packet: " . base64_encode($compressed));
425 throw PacketHandlingException::wrap($e,
"Compressed packet batch decode error");
427 Timings::$playerNetworkReceiveDecompress->stopTiming();
430 throw new PacketHandlingException(
"Packet compressed with unexpected compression type $compressionType");
433 $decompressed = $payload;
438 $stream =
new ByteBufferReader($decompressed);
439 foreach(PacketBatch::decodeRaw($stream) as $buffer){
440 if(++$count >= self::INCOMING_PACKET_BATCH_HARD_LIMIT){
444 throw new PacketHandlingException(
"Reached hard limit of " . self::INCOMING_PACKET_BATCH_HARD_LIMIT .
" per batch packet");
447 if($this->checkRepeatedPacketFilter($buffer)){
451 $this->gamePacketLimiter->decrement();
452 $packet = $this->packetPool->getPacket($buffer);
453 if($packet ===
null){
454 $this->logger->debug(
"Unknown packet: " . base64_encode($buffer));
455 throw new PacketHandlingException(
"Unknown packet received");
458 $this->handleDataPacket($packet, $buffer);
459 }
catch(PacketHandlingException $e){
460 $this->unhandledPacketDebug($packet, $buffer,
"Packet processing error");
461 throw PacketHandlingException::wrap($e,
"Error processing " . $packet->getName());
462 }
catch(FilterNoisyPacketException){
463 $this->noisyPacketBuffer = $buffer;
465 if(!$this->isConnected()){
467 $this->logger->debug(
"Aborting batch processing due to server-side disconnection");
471 }
catch(PacketDecodeException|DataDecodeException $e){
472 $this->logger->logException($e);
473 throw PacketHandlingException::wrap($e,
"Packet batch decode error");
476 Timings::$playerNetworkReceive->stopTiming();
480 private function unhandledPacketDebug(Packet $packet,
string $buffer,
string $label) : void{
481 $debugSegment = substr($buffer, 0, 1024);
482 $debugSegmentLength = strlen($debugSegment);
483 $fullLength = strlen($buffer);
484 $truncatedLabel = $debugSegmentLength === $fullLength ?
"" :
" ... (" . ($fullLength - $debugSegmentLength) .
" bytes not shown)";
485 $this->logger->debug($label .
": " . $packet->getName() .
" ($fullLength bytes): " . base64_encode($debugSegment) . $truncatedLabel);
497 $timings = Timings::getReceiveDataPacketTimings($packet);
498 $timings->startTiming();
501 $handlerAction = PacketHandlerAction::DISCARD_WITH_DEBUG;
504 if($this->handlerActions !==
null && isset($this->handlerActions[$packet::class])){
505 $handlerAction = $this->handlerActions[$packet::class];
507 if(DataPacketDecodeEvent::hasHandlers()){
508 $ev =
new DataPacketDecodeEvent($this, $packet->pid(), $buffer);
509 $cancel = $handlerAction !== PacketHandlerAction::HANDLED;
514 if($cancel && !$ev->isCancelled()){
516 $handlerAction = PacketHandlerAction::HANDLED;
517 }elseif(!$cancel && $ev->isCancelled()){
519 $handlerAction = PacketHandlerAction::DISCARD_SILENT;
523 if($handlerAction !== PacketHandlerAction::HANDLED){
524 if($handlerAction === PacketHandlerAction::DISCARD_WITH_DEBUG){
525 $this->unhandledPacketDebug($packet, $buffer,
"Discarded without decoding");
530 $decodeTimings = Timings::getDecodeDataPacketTimings($packet);
531 $decodeTimings->startTiming();
533 $stream =
new ByteBufferReader($buffer);
535 $packet->decode($stream);
536 }
catch(PacketDecodeException $e){
537 throw PacketHandlingException::wrap($e);
539 if($stream->getUnreadLength() > 0){
540 $remains = substr($stream->getData(), $stream->getOffset());
541 $this->logger->debug(
"Still " . strlen($remains) .
" bytes unread in " . $packet->getName() .
": " . bin2hex($remains));
544 $decodeTimings->stopTiming();
547 if(DataPacketReceiveEvent::hasHandlers()){
548 $ev =
new DataPacketReceiveEvent($this, $packet);
550 if($ev->isCancelled()){
554 $handlerTimings = Timings::getHandleDataPacketTimings($packet);
555 $handlerTimings->startTiming();
557 if($this->handler ===
null || !$packet->handle($this->handler)){
558 $this->unhandledPacketDebug($packet, $buffer,
"Handler rejected");
561 $handlerTimings->stopTiming();
564 $timings->stopTiming();
568 public function handleAckReceipt(
int $receiptId) : void{
569 if(!$this->connected){
572 if(isset($this->ackPromisesByReceiptId[$receiptId])){
573 $promises = $this->ackPromisesByReceiptId[$receiptId];
574 unset($this->ackPromisesByReceiptId[$receiptId]);
575 foreach($promises as $promise){
576 $promise->resolve(
true);
584 private function sendDataPacketInternal(ClientboundPacket $packet,
bool $immediate, ?PromiseResolver $ackReceiptResolver) : bool{
585 if(!$this->connected){
589 if(!$this->loggedIn && !$packet->canBeSentBeforeLogin()){
590 throw new \InvalidArgumentException(
"Attempted to send " . get_class($packet) .
" to " . $this->getDisplayName() .
" too early");
593 $timings = Timings::getSendDataPacketTimings($packet);
594 $timings->startTiming();
596 if(DataPacketSendEvent::hasHandlers()){
597 $ev = new DataPacketSendEvent([$this], [$packet]);
599 if($ev->isCancelled()){
602 $packets = $ev->getPackets();
604 $packets = [$packet];
607 if($ackReceiptResolver !==
null){
608 $this->sendBufferAckPromises[] = $ackReceiptResolver;
610 $writer =
new ByteBufferWriter();
611 foreach($packets as $evPacket){
613 $this->addToSendBuffer(self::encodePacketTimed($writer, $evPacket));
616 $this->flushGamePacketQueue();
621 $timings->stopTiming();
625 public function sendDataPacket(ClientboundPacket $packet,
bool $immediate =
false) : bool{
626 return $this->sendDataPacketInternal($packet, $immediate, null);
636 if(!$this->sendDataPacketInternal($packet, $immediate, $resolver)){
646 public static function encodePacketTimed(ByteBufferWriter $serializer, ClientboundPacket $packet) : string{
647 $timings =
Timings::getEncodeDataPacketTimings($packet);
648 $timings->startTiming();
650 $packet->encode($serializer);
651 return $serializer->getData();
653 $timings->stopTiming();
660 public function addToSendBuffer(
string $buffer) : void{
661 $this->sendBuffer[] = $buffer;
664 private function flushGamePacketQueue() : void{
665 if(count($this->sendBuffer) > 0){
666 Timings::$playerNetworkSend->startTiming();
669 if($this->forceAsyncCompression){
673 $stream =
new ByteBufferWriter();
674 PacketBatch::encodeRaw($stream, $this->sendBuffer);
676 if($this->enableCompression){
677 $batch = $this->
server->prepareBatch($stream->getData(), $this->compressor, $syncMode, Timings::$playerNetworkSendCompressSessionBuffer);
679 $batch = $stream->getData();
681 $this->sendBuffer = [];
682 $ackPromises = $this->sendBufferAckPromises;
683 $this->sendBufferAckPromises = [];
686 $this->queueCompressedNoGamePacketFlush($batch, networkFlush:
true, ackPromises: $ackPromises);
688 Timings::$playerNetworkSend->stopTiming();
693 public function getBroadcaster() : PacketBroadcaster{ return $this->broadcaster; }
695 public function getEntityEventBroadcaster() : EntityEventBroadcaster{ return $this->entityEventBroadcaster; }
697 public function getCompressor() : Compressor{
698 return $this->compressor;
701 public function getTypeConverter() : TypeConverter{ return $this->typeConverter; }
703 public function queueCompressed(CompressBatchPromise|
string $payload,
bool $immediate =
false) : void{
704 Timings::$playerNetworkSend->startTiming();
708 $this->flushGamePacketQueue();
709 $this->queueCompressedNoGamePacketFlush($payload, $immediate);
711 Timings::$playerNetworkSend->stopTiming();
720 private function queueCompressedNoGamePacketFlush(CompressBatchPromise|
string $batch,
bool $networkFlush =
false, array $ackPromises = []) : void{
721 Timings::$playerNetworkSend->startTiming();
723 $this->compressedQueue->enqueue([$batch, $ackPromises, $networkFlush]);
724 if(is_string($batch)){
725 $this->flushCompressedQueue();
727 $batch->onResolve(
function() :
void{
728 if($this->connected){
729 $this->flushCompressedQueue();
734 Timings::$playerNetworkSend->stopTiming();
738 private function flushCompressedQueue() : void{
739 Timings::$playerNetworkSend->startTiming();
741 while(!$this->compressedQueue->isEmpty()){
743 [$current, $ackPromises, $networkFlush] = $this->compressedQueue->bottom();
744 if(is_string($current)){
745 $this->compressedQueue->dequeue();
746 $this->sendEncoded($current, $networkFlush, $ackPromises);
748 }elseif($current->hasResult()){
749 $this->compressedQueue->dequeue();
750 $this->sendEncoded($current->getResult(), $networkFlush, $ackPromises);
758 Timings::$playerNetworkSend->stopTiming();
766 private function sendEncoded(
string $payload,
bool $immediate, array $ackPromises) : void{
767 if($this->cipher !== null){
768 Timings::$playerNetworkSendEncrypt->startTiming();
769 $payload = $this->cipher->encrypt($payload);
770 Timings::$playerNetworkSendEncrypt->stopTiming();
773 if(count($ackPromises) > 0){
774 $ackReceiptId = $this->nextAckReceiptId++;
775 $this->ackPromisesByReceiptId[$ackReceiptId] = $ackPromises;
777 $ackReceiptId =
null;
779 $this->sender->send($payload, $immediate, $ackReceiptId);
785 private function tryDisconnect(\Closure $func, Translatable|
string $reason) : void{
786 if($this->connected && !$this->disconnectGuard){
787 $this->disconnectGuard =
true;
789 $this->disconnectGuard =
false;
790 $this->flushGamePacketQueue();
791 $this->sender->close(
"");
792 foreach($this->disposeHooks as $callback){
795 $this->disposeHooks->clear();
796 $this->setHandler(
null);
797 $this->connected =
false;
799 $ackPromisesByReceiptId = $this->ackPromisesByReceiptId;
800 $this->ackPromisesByReceiptId = [];
801 foreach($ackPromisesByReceiptId as $resolvers){
802 foreach($resolvers as $resolver){
806 $sendBufferAckPromises = $this->sendBufferAckPromises;
807 $this->sendBufferAckPromises = [];
808 foreach($sendBufferAckPromises as $resolver){
812 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_close($reason)));
820 private function dispose() : void{
821 $this->invManager = null;
824 private function sendDisconnectPacket(Translatable|
string $message) : void{
825 if($message instanceof Translatable){
826 $translated = $this->
server->getLanguage()->translate($message);
828 $translated = $message;
830 $this->sendDataPacket(DisconnectPacket::create(0, $translated,
""));
840 $this->tryDisconnect(function() use ($reason, $disconnectScreenMessage, $notify) : void{
842 $this->sendDisconnectPacket($disconnectScreenMessage ?? $reason);
844 if($this->player !==
null){
845 $this->player->onPostDisconnect($reason,
null);
850 public function disconnectWithError(Translatable|
string $reason, Translatable|
string|
null $disconnectScreenMessage =
null) : void{
851 $errorId = implode(
"-", str_split(bin2hex(random_bytes(6)), 4));
854 reason: KnownTranslationFactory::pocketmine_disconnect_error($reason, $errorId)->prefix(TextFormat::RED),
855 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error($disconnectScreenMessage ?? $reason, $errorId),
859 public function disconnectIncompatibleProtocol(
int $protocolVersion) : void{
860 $this->tryDisconnect(
861 function() use ($protocolVersion) : void{
862 $this->sendDataPacket(PlayStatusPacket::create($protocolVersion < ProtocolInfo::CURRENT_PROTOCOL ? PlayStatusPacket::LOGIN_FAILED_CLIENT : PlayStatusPacket::LOGIN_FAILED_SERVER), true);
864 KnownTranslationFactory::pocketmine_disconnect_incompatibleProtocol((
string) $protocolVersion)
873 $this->tryDisconnect(
function() use ($ip, $port, $reason) :
void{
874 $this->sendDataPacket(TransferPacket::create($ip, $port,
false),
true);
875 if($this->player !==
null){
876 $this->player->onPostDisconnect($reason,
null);
885 $this->tryDisconnect(function() use ($disconnectScreenMessage) : void{
886 $this->sendDisconnectPacket($disconnectScreenMessage);
895 $this->tryDisconnect(function() use ($reason) : void{
896 if($this->player !== null){
897 $this->player->onPostDisconnect($reason,
null);
902 private function setAuthenticationStatus(
bool $authenticated,
bool $authRequired,
Translatable|
string|
null $error, ?
string $clientPubKey) : void{
903 if(!$this->connected){
907 if($authenticated && !($this->info instanceof XboxLivePlayerInfo)){
908 $error =
"Expected XUID but none found";
909 }elseif($clientPubKey ===
null){
910 $error =
"Missing client public key";
915 $this->disconnectWithError(
916 reason: KnownTranslationFactory::pocketmine_disconnect_invalidSession($error),
917 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_authentication()
923 $this->authenticated = $authenticated;
925 if(!$this->authenticated){
927 $this->disconnect(
"Not authenticated", KnownTranslationFactory::disconnectionScreen_notAuthenticated());
930 if($this->info instanceof XboxLivePlayerInfo){
931 $this->logger->warning(
"Discarding unexpected XUID for non-authenticated player");
932 $this->info = $this->info->withoutXboxData();
935 $this->logger->debug(
"Xbox Live authenticated: " . ($this->authenticated ?
"YES" :
"NO"));
937 $checkXUID = $this->
server->getConfigGroup()->getPropertyBool(YmlServerProperties::PLAYER_VERIFY_XUID,
true);
938 $myXUID = $this->info instanceof XboxLivePlayerInfo ? $this->info->getXuid() :
"";
939 $kickForXUIDMismatch =
function(
string $xuid) use ($checkXUID, $myXUID) : bool{
940 if($checkXUID && $myXUID !== $xuid){
941 $this->logger->debug(
"XUID mismatch: expected '$xuid', but got '$myXUID'");
946 $this->disconnect(
"XUID does not match (possible impersonation attempt)");
952 foreach($this->manager->getSessions() as $existingSession){
953 if($existingSession === $this){
956 $info = $existingSession->getPlayerInfo();
957 if($info !==
null && (strcasecmp($info->getUsername(), $this->info->getUsername()) === 0 || $info->getUuid()->equals($this->info->getUuid()))){
958 if($kickForXUIDMismatch($info instanceof XboxLivePlayerInfo ? $info->getXuid() :
"")){
961 $ev =
new PlayerDuplicateLoginEvent($this, $existingSession, KnownTranslationFactory::disconnectionScreen_loggedinOtherLocation(),
null);
963 if($ev->isCancelled()){
964 $this->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
968 $existingSession->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
974 $this->cachedOfflinePlayerData = $this->
server->getOfflinePlayerData($this->info->getUsername());
976 $recordedXUID = $this->cachedOfflinePlayerData !==
null ? $this->cachedOfflinePlayerData->getTag(Player::TAG_LAST_KNOWN_XUID) :
null;
977 if(!($recordedXUID instanceof StringTag)){
978 $this->logger->debug(
"No previous XUID recorded, no choice but to trust this player");
979 }elseif(!$kickForXUIDMismatch($recordedXUID->getValue())){
980 $this->logger->debug(
"XUID match");
984 if(EncryptionContext::$ENABLED){
985 $this->
server->getAsyncPool()->submitTask(
new PrepareEncryptionTask($clientPubKey,
function(
string $encryptionKey,
string $handshakeJwt) :
void{
986 if(!$this->connected){
989 $this->sendDataPacket(ServerToClientHandshakePacket::create($handshakeJwt),
true);
991 $this->cipher = EncryptionContext::fakeGCM($encryptionKey);
993 $this->setHandler(
new HandshakePacketHandler($this->onServerLoginSuccess(...)));
994 $this->logger->debug(
"Enabled encryption");
997 $this->onServerLoginSuccess();
1001 private function onServerLoginSuccess() : void{
1002 $this->loggedIn = true;
1004 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::LOGIN_SUCCESS));
1006 $this->logger->debug(
"Initiating resource packs phase");
1008 $packManager = $this->
server->getResourcePackManager();
1009 $resourcePacks = $packManager->getResourceStack();
1011 foreach($resourcePacks as $resourcePack){
1012 $key = $packManager->getPackEncryptionKey($resourcePack->getPackId());
1014 $keys[$resourcePack->getPackId()->toString()] = $key;
1017 $event =
new PlayerResourcePackOfferEvent($this->info, $resourcePacks, $keys, $packManager->resourcePacksRequired());
1019 $this->setHandler(
new ResourcePacksPacketHandler($this, $event->getResourcePacks(), $event->getEncryptionKeys(), $event->mustAccept(),
function() :
void{
1020 $this->createPlayer();
1024 private function beginSpawnSequence() : void{
1025 $this->setHandler(new PreSpawnPacketHandler($this->
server, $this->player, $this, $this->invManager));
1026 $this->player->setNoClientPredictions();
1028 $this->logger->debug(
"Waiting for chunk radius request");
1031 public function notifyTerrainReady() : void{
1032 $this->logger->debug(
"Sending spawn notification, waiting for spawn response");
1033 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::PLAYER_SPAWN));
1034 $this->setHandler(
new SpawnResponsePacketHandler($this->onClientSpawnResponse(...)));
1037 private function onClientSpawnResponse() : void{
1038 $this->logger->debug(
"Received spawn response, entering in-game phase");
1039 $this->player->setNoClientPredictions(
false);
1040 $this->player->doFirstSpawn();
1041 $this->forceAsyncCompression =
false;
1042 $this->setHandler(
new InGamePacketHandler($this->player, $this, $this->invManager));
1045 public function onServerDeath(Translatable|
string $deathMessage) : void{
1046 if($this->handler instanceof InGamePacketHandler){
1047 $this->setHandler(
new DeathPacketHandler($this->player, $this, $this->invManager ??
throw new AssumptionFailedError(), $deathMessage));
1051 public function onServerRespawn() : void{
1052 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $this->player->getAttributeMap()->getAll());
1053 $this->player->sendData(
null);
1055 $this->syncAbilities($this->player);
1056 $this->invManager->syncAll();
1057 $this->setHandler(
new InGamePacketHandler($this->player, $this, $this->invManager));
1060 public function syncMovement(Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
1061 if($this->player !== null){
1062 $location = $this->player->getLocation();
1063 $yaw = $yaw ?? $location->getYaw();
1064 $pitch = $pitch ?? $location->getPitch();
1066 $this->sendDataPacket(MovePlayerPacket::simple(
1067 $this->player->getId(),
1068 $this->player->getOffsetPosition($pos),
1073 $this->player->onGround,
1078 if($this->handler instanceof InGamePacketHandler){
1079 $this->handler->forceMoveSync =
true;
1084 public function syncViewAreaRadius(
int $distance) : void{
1085 $this->sendDataPacket(ChunkRadiusUpdatedPacket::create($distance));
1088 public function syncViewAreaCenterPoint(Vector3 $newPos,
int $viewDistance) : void{
1089 $this->sendDataPacket(NetworkChunkPublisherUpdatePacket::create(BlockPosition::fromVector3($newPos), $viewDistance * 16, []));
1092 public function syncPlayerSpawnPoint(Position $newSpawn) : void{
1093 $newSpawnBlockPosition = BlockPosition::fromVector3($newSpawn);
1095 $this->sendDataPacket(SetSpawnPositionPacket::playerSpawn($newSpawnBlockPosition, DimensionIds::OVERWORLD, $newSpawnBlockPosition));
1098 public function syncWorldSpawnPoint(Position $newSpawn) : void{
1099 $this->sendDataPacket(SetSpawnPositionPacket::worldSpawn(BlockPosition::fromVector3($newSpawn), DimensionIds::OVERWORLD));
1102 public function syncGameMode(GameMode $mode,
bool $isRollback =
false) : void{
1103 $this->sendDataPacket(SetPlayerGameTypePacket::create($this->typeConverter->coreGameModeToProtocol($mode)));
1104 if($this->player !==
null){
1105 $this->syncAbilities($this->player);
1106 $this->syncAdventureSettings();
1108 if(!$isRollback && $this->invManager !==
null){
1109 $this->invManager->syncCreative();
1113 public function syncAbilities(Player $for) : void{
1114 $isOp = $for->hasPermission(DefaultPermissions::ROOT_OPERATOR);
1118 AbilitiesLayer::ABILITY_ALLOW_FLIGHT => $for->getAllowFlight(),
1119 AbilitiesLayer::ABILITY_FLYING => $for->isFlying(),
1120 AbilitiesLayer::ABILITY_NO_CLIP => !$for->hasBlockCollision(),
1121 AbilitiesLayer::ABILITY_OPERATOR => $isOp,
1122 AbilitiesLayer::ABILITY_TELEPORT => $for->hasPermission(DefaultPermissionNames::COMMAND_TELEPORT_SELF),
1123 AbilitiesLayer::ABILITY_INVULNERABLE => $for->isCreative(),
1124 AbilitiesLayer::ABILITY_MUTED =>
false,
1125 AbilitiesLayer::ABILITY_WORLD_BUILDER =>
false,
1126 AbilitiesLayer::ABILITY_INFINITE_RESOURCES => !$for->hasFiniteResources(),
1127 AbilitiesLayer::ABILITY_LIGHTNING =>
false,
1128 AbilitiesLayer::ABILITY_BUILD => !$for->isSpectator(),
1129 AbilitiesLayer::ABILITY_MINE => !$for->isSpectator(),
1130 AbilitiesLayer::ABILITY_DOORS_AND_SWITCHES => !$for->isSpectator(),
1131 AbilitiesLayer::ABILITY_OPEN_CONTAINERS => !$for->isSpectator(),
1132 AbilitiesLayer::ABILITY_ATTACK_PLAYERS => !$for->isSpectator(),
1133 AbilitiesLayer::ABILITY_ATTACK_MOBS => !$for->isSpectator(),
1134 AbilitiesLayer::ABILITY_PRIVILEGED_BUILDER =>
false,
1138 new AbilitiesLayer(AbilitiesLayer::LAYER_BASE, $boolAbilities, $for->getFlightSpeedMultiplier(), 1, 0.1),
1140 if(!$for->hasBlockCollision()){
1146 $layers[] = new AbilitiesLayer(AbilitiesLayer::LAYER_SPECTATOR, [
1147 AbilitiesLayer::ABILITY_FLYING => true,
1148 ], null, null, null);
1151 $this->sendDataPacket(UpdateAbilitiesPacket::create(
new AbilitiesData(
1152 $isOp ? CommandPermissions::OPERATOR : CommandPermissions::NORMAL,
1153 $isOp ? PlayerPermissions::OPERATOR : PlayerPermissions::MEMBER,
1159 public function syncAdventureSettings() : void{
1160 if($this->player === null){
1161 throw new \LogicException(
"Cannot sync adventure settings for a player that is not yet created");
1164 $this->sendDataPacket(UpdateAdventureSettingsPacket::create(
1165 noAttackingMobs:
false,
1166 noAttackingPlayers:
false,
1167 worldImmutable:
false,
1169 autoJump: $this->player->hasAutoJump()
1173 public function syncAvailableCommands() : void{
1175 $globalAliasMap = $this->
server->getCommandMap()->getAliasMap();
1176 $userAliasMap = $this->player->getCommandAliasMap();
1177 foreach($this->
server->getCommandMap()->getUniqueCommands() as $command){
1178 if(!$command->testPermissionSilent($this->player)){
1182 $userAliases = $userAliasMap->getMergedAliases($command->getId(), $globalAliasMap);
1184 $aliases = array_values(array_filter($userAliases, fn(
string $alias) => $alias !==
"help" && $alias !==
"?"));
1185 if(count($aliases) === 0){
1188 $firstNetworkAlias = $aliases[0];
1191 $lname = strtolower($firstNetworkAlias);
1192 $aliasObj =
new CommandHardEnum(ucfirst($firstNetworkAlias) .
"Aliases", $aliases);
1194 $description = $command->getDescription();
1195 $data =
new CommandData(
1197 $description instanceof Translatable ? $this->player->getLanguage()->translate($description) : $description,
1199 CommandPermissions::NORMAL,
1202 new CommandOverload(chaining:
false, parameters: [CommandParameter::standard(
"args", AvailableCommandsPacket::ARG_TYPE_RAWTEXT, 0,
true)])
1204 chainedSubCommandData: []
1207 $commandData[] = $data;
1210 $this->sendDataPacket(AvailableCommandsPacketAssembler::assemble($commandData, [], []));
1219 $language = $this->player->getLanguage();
1221 $untranslatedParameterCount = 0;
1222 $translated = $language->translateString($message->getText(), $parameters,
"pocketmine.", $untranslatedParameterCount);
1223 return [$translated, array_slice($parameters, 0, $untranslatedParameterCount)];
1226 public function onChatMessage(
Translatable|
string $message) : void{
1228 if(!$this->
server->isLanguageForced()){
1229 $this->sendDataPacket(TextPacket::translation(...$this->prepareClientTranslatableMessage($message)));
1231 $this->sendDataPacket(TextPacket::raw($this->player->getLanguage()->translate($message)));
1234 $this->sendDataPacket(TextPacket::raw($message));
1238 public function onJukeboxPopup(Translatable|
string $message) : void{
1240 if($message instanceof Translatable){
1241 if(!$this->server->isLanguageForced()){
1242 [$message, $parameters] = $this->prepareClientTranslatableMessage($message);
1244 $message = $this->player->getLanguage()->translate($message);
1247 $this->sendDataPacket(TextPacket::jukeboxPopup($message, $parameters));
1250 public function onPopup(
string $message) : void{
1251 $this->sendDataPacket(TextPacket::popup($message));
1254 public function onTip(
string $message) : void{
1255 $this->sendDataPacket(TextPacket::tip($message));
1258 public function onFormSent(
int $id, Form $form) : bool{
1259 return $this->sendDataPacket(ModalFormRequestPacket::create($id, json_encode($form, JSON_THROW_ON_ERROR)));
1262 public function onCloseAllForms() : void{
1263 $this->sendDataPacket(ClientboundCloseFormPacket::create());
1269 private function sendChunkPacket(
string $chunkPacket, \Closure $onCompletion, World $world) : void{
1270 $world->timings->syncChunkSend->startTiming();
1272 $this->queueCompressed($chunkPacket);
1275 $world->timings->syncChunkSend->stopTiming();
1285 $world = $this->player->getLocation()->getWorld();
1286 $promiseOrPacket = ChunkCache::getInstance($world, $this->compressor)->request($chunkX, $chunkZ);
1287 if(is_string($promiseOrPacket)){
1288 $this->sendChunkPacket($promiseOrPacket, $onCompletion, $world);
1291 $promiseOrPacket->onResolve(
1294 if(!$this->isConnected()){
1297 $currentWorld = $this->player->getLocation()->getWorld();
1298 if($world !== $currentWorld || ($status = $this->player->getUsedChunkStatus($chunkX, $chunkZ)) ===
null){
1299 $this->logger->debug(
"Tried to send no-longer-active chunk $chunkX $chunkZ in world " . $world->getFolderName());
1302 if($status !== UsedChunkStatus::REQUESTED_SENDING){
1309 $this->sendChunkPacket($promise->getResult(), $onCompletion, $world);
1314 public function stopUsingChunk(
int $chunkX,
int $chunkZ) : void{
1318 public function onEnterWorld() : void{
1319 if($this->player !== null){
1320 $world = $this->player->getWorld();
1321 $this->syncWorldTime($world->getTime());
1322 $this->syncWorldDifficulty($world->getDifficulty());
1323 $this->syncWorldSpawnPoint($world->getSpawnLocation());
1328 public function syncWorldTime(
int $worldTime) : void{
1329 $this->sendDataPacket(SetTimePacket::create($worldTime));
1332 public function syncWorldDifficulty(
int $worldDifficulty) : void{
1333 $this->sendDataPacket(SetDifficultyPacket::create($worldDifficulty));
1336 public function getInvManager() : ?InventoryManager{
1337 return $this->invManager;
1345 return
PlayerListEntry::createAdditionEntry($player->getUniqueId(), $player->getId(), $player->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($player->getSkin()), $player->getXuid());
1349 public function onPlayerAdded(
Player $p) : void{
1350 $this->sendDataPacket(PlayerListPacket::add([PlayerListEntry::createAdditionEntry($p->getUniqueId(), $p->getId(), $p->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($p->getSkin()), $p->getXuid())]));
1353 public function onPlayerRemoved(
Player $p) : void{
1354 if($p !== $this->player){
1355 $this->sendDataPacket(PlayerListPacket::remove([PlayerListEntry::createRemovalEntry($p->
getUniqueId())]));
1359 public function onTitle(
string $title) : void{
1360 $this->sendDataPacket(SetTitlePacket::title($title));
1363 public function onSubTitle(
string $subtitle) : void{
1364 $this->sendDataPacket(SetTitlePacket::subtitle($subtitle));
1367 public function onActionBar(
string $actionBar) : void{
1368 $this->sendDataPacket(SetTitlePacket::actionBarMessage($actionBar));
1371 public function onClearTitle() : void{
1372 $this->sendDataPacket(SetTitlePacket::clearTitle());
1375 public function onResetTitleOptions() : void{
1376 $this->sendDataPacket(SetTitlePacket::resetTitleOptions());
1379 public function onTitleDuration(
int $fadeIn,
int $stay,
int $fadeOut) : void{
1380 $this->sendDataPacket(SetTitlePacket::setAnimationTimes($fadeIn, $stay, $fadeOut));
1383 public function onToastNotification(
string $title,
string $body) : void{
1384 $this->sendDataPacket(ToastRequestPacket::create($title, $body));
1387 public function onOpenSignEditor(Vector3 $signPosition,
bool $frontSide) : void{
1388 $this->sendDataPacket(OpenSignPacket::create(BlockPosition::fromVector3($signPosition), $frontSide));
1391 public function onItemCooldownChanged(Item $item,
int $ticks) : void{
1392 $this->sendDataPacket(PlayerStartItemCooldownPacket::create(
1393 GlobalItemDataHandlers::getSerializer()->serializeType($item)->getName(),
1398 public function tick() : void{
1399 if(!$this->isConnected()){
1404 if($this->info ===
null){
1405 if(time() >= $this->connectTime + 10){
1406 $this->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_loginTimeout());
1412 if($this->player !==
null){
1413 $this->player->doChunkRequests();
1415 $dirtyAttributes = $this->player->getAttributeMap()->needSend();
1416 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $dirtyAttributes);
1417 foreach($dirtyAttributes as $attribute){
1420 $attribute->markSynchronized();
1423 Timings::$playerNetworkSendInventorySync->startTiming();
1425 $this->invManager?->flushPendingUpdates();
1427 Timings::$playerNetworkSendInventorySync->stopTiming();
1430 $this->flushGamePacketQueue();