145 private const INCOMING_PACKET_BATCH_PER_TICK = 2;
146 private const INCOMING_PACKET_BATCH_BUFFER_TICKS = 100;
148 private const INCOMING_GAME_PACKETS_PER_TICK = 2;
149 private const INCOMING_GAME_PACKETS_BUFFER_TICKS = 100;
151 private const INCOMING_PACKET_BATCH_HARD_LIMIT = 300;
156 private \PrefixedLogger $logger;
157 private ?
Player $player =
null;
159 private ?
int $ping =
null;
163 private bool $connected =
true;
164 private bool $disconnectGuard =
false;
165 private bool $loggedIn =
false;
166 private bool $authenticated =
false;
167 private int $connectTime;
168 private ?
CompoundTag $cachedOfflinePlayerData =
null;
176 private array $sendBuffer = [];
181 private array $sendBufferAckPromises = [];
184 private \SplQueue $compressedQueue;
185 private bool $forceAsyncCompression =
true;
186 private bool $enableCompression =
false;
188 private int $nextAckReceiptId = 0;
193 private array $ackPromisesByReceiptId = [];
203 private string $noisyPacketBuffer =
"";
204 private int $noisyPacketsDropped = 0;
206 public function __construct(
218 $this->logger = new \PrefixedLogger($this->
server->getLogger(), $this->getLogPrefix());
220 $this->compressedQueue = new \SplQueue();
224 $this->connectTime = time();
225 $this->packetBatchLimiter =
new PacketRateLimiter(
"Packet Batches", self::INCOMING_PACKET_BATCH_PER_TICK, self::INCOMING_PACKET_BATCH_BUFFER_TICKS);
226 $this->gamePacketLimiter =
new PacketRateLimiter(
"Game Packets", self::INCOMING_GAME_PACKETS_PER_TICK, self::INCOMING_GAME_PACKETS_BUFFER_TICKS);
230 $this->onSessionStartSuccess(...)
233 $this->manager->add($this);
234 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_open()));
237 private function getLogPrefix() :
string{
238 return "NetworkSession: " . $this->getDisplayName();
241 public function getLogger() : \
Logger{
242 return $this->logger;
245 private function onSessionStartSuccess() :
void{
246 $this->logger->debug(
"Session start handshake completed, awaiting login packet");
247 $this->flushGamePacketQueue();
248 $this->enableCompression =
true;
254 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_playerName(TextFormat::AQUA . $info->getUsername() . TextFormat::RESET)));
255 $this->logger->setPrefix($this->getLogPrefix());
256 $this->manager->markLoginReceived($this);
258 $this->setAuthenticationStatus(...)
262 protected function createPlayer() :
void{
263 $this->
server->createPlayer($this, $this->info, $this->authenticated, $this->cachedOfflinePlayerData)->onCompletion(
264 $this->onPlayerCreated(...),
267 $this->disconnectWithError(
268 reason:
"Failed to create player",
269 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_internal()
275 private function onPlayerCreated(
Player $player) :
void{
276 if(!$this->isConnected()){
280 $this->player = $player;
281 if(!$this->
server->addOnlinePlayer($player)){
287 $effectManager = $this->player->getEffects();
288 $effectManager->getEffectAddHooks()->add($effectAddHook =
function(
EffectInstance $effect,
bool $replacesOldEffect) :
void{
289 $this->entityEventBroadcaster->onEntityEffectAdded([$this], $this->player, $effect, $replacesOldEffect);
291 $effectManager->getEffectRemoveHooks()->add($effectRemoveHook =
function(
EffectInstance $effect) :
void{
292 $this->entityEventBroadcaster->onEntityEffectRemoved([$this], $this->player, $effect);
294 $this->disposeHooks->add(
static function() use ($effectManager, $effectAddHook, $effectRemoveHook) :
void{
295 $effectManager->getEffectAddHooks()->remove($effectAddHook);
296 $effectManager->getEffectRemoveHooks()->remove($effectRemoveHook);
299 $permissionHooks = $this->player->getPermissionRecalculationCallbacks();
300 $permissionHooks->add($permHook =
function() :
void{
301 $this->logger->debug(
"Syncing available commands and abilities/permissions due to permission recalculation");
302 $this->syncAbilities($this->player);
303 $this->syncAvailableCommands();
305 $this->disposeHooks->add(
static function() use ($permissionHooks, $permHook) :
void{
306 $permissionHooks->remove($permHook);
308 $this->beginSpawnSequence();
311 public function getPlayer() : ?
Player{
312 return $this->player;
315 public function getPlayerInfo() : ?
PlayerInfo{
319 public function isConnected() :
bool{
320 return $this->connected && !$this->disconnectGuard;
323 public function getIp() :
string{
327 public function getPort() :
int{
331 public function getDisplayName() :
string{
332 return $this->info !==
null ? $this->info->getUsername() : $this->ip .
" " . $this->port;
345 public function updatePing(
int $ping) : void{
349 public function getHandler() : ?PacketHandler{
350 return $this->handler;
353 public function setHandler(?PacketHandler $handler) : void{
354 if($this->connected){
355 $this->handler = $handler;
356 if($this->handler !==
null){
357 $this->handler->setUp();
362 private function checkRepeatedPacketFilter(
string $buffer) : bool{
363 if($buffer === $this->noisyPacketBuffer){
364 $this->noisyPacketsDropped++;
370 $this->noisyPacketBuffer =
"";
371 $this->noisyPacketsDropped = 0;
380 if(!$this->connected){
384 Timings::$playerNetworkReceive->startTiming();
386 $this->packetBatchLimiter->decrement();
388 if($this->cipher !==
null){
389 Timings::$playerNetworkReceiveDecrypt->startTiming();
391 $payload = $this->cipher->decrypt($payload);
392 }
catch(DecryptionException $e){
393 $this->logger->debug(
"Encrypted packet: " . base64_encode($payload));
394 throw PacketHandlingException::wrap($e,
"Packet decryption error");
396 Timings::$playerNetworkReceiveDecrypt->stopTiming();
400 if(strlen($payload) < 1){
401 throw new PacketHandlingException(
"No bytes in payload");
404 if($this->enableCompression){
405 $compressionType = ord($payload[0]);
406 $compressed = substr($payload, 1);
407 if($compressionType === CompressionAlgorithm::NONE){
408 $decompressed = $compressed;
409 }elseif($compressionType === $this->compressor->getNetworkId()){
410 Timings::$playerNetworkReceiveDecompress->startTiming();
412 $decompressed = $this->compressor->decompress($compressed);
413 }
catch(DecompressionException $e){
414 $this->logger->debug(
"Failed to decompress packet: " . base64_encode($compressed));
415 throw PacketHandlingException::wrap($e,
"Compressed packet batch decode error");
417 Timings::$playerNetworkReceiveDecompress->stopTiming();
420 throw new PacketHandlingException(
"Packet compressed with unexpected compression type $compressionType");
423 $decompressed = $payload;
428 $stream =
new ByteBufferReader($decompressed);
429 foreach(PacketBatch::decodeRaw($stream) as $buffer){
430 if(++$count >= self::INCOMING_PACKET_BATCH_HARD_LIMIT){
434 throw new PacketHandlingException(
"Reached hard limit of " . self::INCOMING_PACKET_BATCH_HARD_LIMIT .
" per batch packet");
437 if($this->checkRepeatedPacketFilter($buffer)){
441 $this->gamePacketLimiter->decrement();
442 $packet = $this->packetPool->getPacket($buffer);
443 if($packet ===
null){
444 $this->logger->debug(
"Unknown packet: " . base64_encode($buffer));
445 throw new PacketHandlingException(
"Unknown packet received");
448 $this->handleDataPacket($packet, $buffer);
449 }
catch(PacketHandlingException $e){
450 $this->logger->debug($packet->getName() .
": " . base64_encode($buffer));
451 throw PacketHandlingException::wrap($e,
"Error processing " . $packet->getName());
452 }
catch(FilterNoisyPacketException){
453 $this->noisyPacketBuffer = $buffer;
455 if(!$this->isConnected()){
457 $this->logger->debug(
"Aborting batch processing due to server-side disconnection");
461 }
catch(PacketDecodeException|DataDecodeException $e){
462 $this->logger->logException($e);
463 throw PacketHandlingException::wrap($e,
"Packet batch decode error");
466 Timings::$playerNetworkReceive->stopTiming();
479 $timings = Timings::getReceiveDataPacketTimings($packet);
480 $timings->startTiming();
483 if(DataPacketDecodeEvent::hasHandlers()){
486 if($ev->isCancelled()){
491 $decodeTimings = Timings::getDecodeDataPacketTimings($packet);
492 $decodeTimings->startTiming();
494 $stream =
new ByteBufferReader($buffer);
496 $packet->decode($stream);
497 }
catch(PacketDecodeException $e){
498 throw PacketHandlingException::wrap($e);
500 if($stream->getUnreadLength() > 0){
501 $remains = substr($stream->getData(), $stream->getOffset());
502 $this->logger->debug(
"Still " . strlen($remains) .
" bytes unread in " . $packet->getName() .
": " . bin2hex($remains));
505 $decodeTimings->stopTiming();
508 if(DataPacketReceiveEvent::hasHandlers()){
509 $ev =
new DataPacketReceiveEvent($this, $packet);
511 if($ev->isCancelled()){
515 $handlerTimings = Timings::getHandleDataPacketTimings($packet);
516 $handlerTimings->startTiming();
518 if($this->handler ===
null || !$packet->handle($this->handler)){
519 $this->logger->debug(
"Unhandled " . $packet->getName() .
": " . base64_encode($stream->getData()));
522 $handlerTimings->stopTiming();
525 $timings->stopTiming();
529 public function handleAckReceipt(
int $receiptId) : void{
530 if(!$this->connected){
533 if(isset($this->ackPromisesByReceiptId[$receiptId])){
534 $promises = $this->ackPromisesByReceiptId[$receiptId];
535 unset($this->ackPromisesByReceiptId[$receiptId]);
536 foreach($promises as $promise){
537 $promise->resolve(
true);
545 private function sendDataPacketInternal(ClientboundPacket $packet,
bool $immediate, ?PromiseResolver $ackReceiptResolver) : bool{
546 if(!$this->connected){
550 if(!$this->loggedIn && !$packet->canBeSentBeforeLogin()){
551 throw new \InvalidArgumentException(
"Attempted to send " . get_class($packet) .
" to " . $this->getDisplayName() .
" too early");
554 $timings = Timings::getSendDataPacketTimings($packet);
555 $timings->startTiming();
557 if(DataPacketSendEvent::hasHandlers()){
558 $ev = new DataPacketSendEvent([$this], [$packet]);
560 if($ev->isCancelled()){
563 $packets = $ev->getPackets();
565 $packets = [$packet];
568 if($ackReceiptResolver !==
null){
569 $this->sendBufferAckPromises[] = $ackReceiptResolver;
571 $writer =
new ByteBufferWriter();
572 foreach($packets as $evPacket){
574 $this->addToSendBuffer(self::encodePacketTimed($writer, $evPacket));
577 $this->flushGamePacketQueue();
582 $timings->stopTiming();
586 public function sendDataPacket(ClientboundPacket $packet,
bool $immediate =
false) : bool{
587 return $this->sendDataPacketInternal($packet, $immediate, null);
597 if(!$this->sendDataPacketInternal($packet, $immediate, $resolver)){
607 public static function encodePacketTimed(ByteBufferWriter $serializer, ClientboundPacket $packet) : string{
608 $timings =
Timings::getEncodeDataPacketTimings($packet);
609 $timings->startTiming();
611 $packet->encode($serializer);
612 return $serializer->getData();
614 $timings->stopTiming();
621 public function addToSendBuffer(
string $buffer) : void{
622 $this->sendBuffer[] = $buffer;
625 private function flushGamePacketQueue() : void{
626 if(count($this->sendBuffer) > 0){
627 Timings::$playerNetworkSend->startTiming();
630 if($this->forceAsyncCompression){
634 $stream =
new ByteBufferWriter();
635 PacketBatch::encodeRaw($stream, $this->sendBuffer);
637 if($this->enableCompression){
638 $batch = $this->
server->prepareBatch($stream->getData(), $this->compressor, $syncMode, Timings::$playerNetworkSendCompressSessionBuffer);
640 $batch = $stream->getData();
642 $this->sendBuffer = [];
643 $ackPromises = $this->sendBufferAckPromises;
644 $this->sendBufferAckPromises = [];
647 $this->queueCompressedNoGamePacketFlush($batch, networkFlush:
true, ackPromises: $ackPromises);
649 Timings::$playerNetworkSend->stopTiming();
654 public function getBroadcaster() : PacketBroadcaster{ return $this->broadcaster; }
656 public function getEntityEventBroadcaster() : EntityEventBroadcaster{ return $this->entityEventBroadcaster; }
658 public function getCompressor() : Compressor{
659 return $this->compressor;
662 public function getTypeConverter() : TypeConverter{ return $this->typeConverter; }
664 public function queueCompressed(CompressBatchPromise|
string $payload,
bool $immediate =
false) : void{
665 Timings::$playerNetworkSend->startTiming();
669 $this->flushGamePacketQueue();
670 $this->queueCompressedNoGamePacketFlush($payload, $immediate);
672 Timings::$playerNetworkSend->stopTiming();
681 private function queueCompressedNoGamePacketFlush(CompressBatchPromise|
string $batch,
bool $networkFlush =
false, array $ackPromises = []) : void{
682 Timings::$playerNetworkSend->startTiming();
684 $this->compressedQueue->enqueue([$batch, $ackPromises, $networkFlush]);
685 if(is_string($batch)){
686 $this->flushCompressedQueue();
688 $batch->onResolve(
function() :
void{
689 if($this->connected){
690 $this->flushCompressedQueue();
695 Timings::$playerNetworkSend->stopTiming();
699 private function flushCompressedQueue() : void{
700 Timings::$playerNetworkSend->startTiming();
702 while(!$this->compressedQueue->isEmpty()){
704 [$current, $ackPromises, $networkFlush] = $this->compressedQueue->bottom();
705 if(is_string($current)){
706 $this->compressedQueue->dequeue();
707 $this->sendEncoded($current, $networkFlush, $ackPromises);
709 }elseif($current->hasResult()){
710 $this->compressedQueue->dequeue();
711 $this->sendEncoded($current->getResult(), $networkFlush, $ackPromises);
719 Timings::$playerNetworkSend->stopTiming();
727 private function sendEncoded(
string $payload,
bool $immediate, array $ackPromises) : void{
728 if($this->cipher !== null){
729 Timings::$playerNetworkSendEncrypt->startTiming();
730 $payload = $this->cipher->encrypt($payload);
731 Timings::$playerNetworkSendEncrypt->stopTiming();
734 if(count($ackPromises) > 0){
735 $ackReceiptId = $this->nextAckReceiptId++;
736 $this->ackPromisesByReceiptId[$ackReceiptId] = $ackPromises;
738 $ackReceiptId =
null;
740 $this->sender->send($payload, $immediate, $ackReceiptId);
746 private function tryDisconnect(\Closure $func, Translatable|
string $reason) : void{
747 if($this->connected && !$this->disconnectGuard){
748 $this->disconnectGuard =
true;
750 $this->disconnectGuard =
false;
751 $this->flushGamePacketQueue();
752 $this->sender->close(
"");
753 foreach($this->disposeHooks as $callback){
756 $this->disposeHooks->clear();
757 $this->setHandler(
null);
758 $this->connected =
false;
760 $ackPromisesByReceiptId = $this->ackPromisesByReceiptId;
761 $this->ackPromisesByReceiptId = [];
762 foreach($ackPromisesByReceiptId as $resolvers){
763 foreach($resolvers as $resolver){
767 $sendBufferAckPromises = $this->sendBufferAckPromises;
768 $this->sendBufferAckPromises = [];
769 foreach($sendBufferAckPromises as $resolver){
773 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_close($reason)));
781 private function dispose() : void{
782 $this->invManager = null;
785 private function sendDisconnectPacket(Translatable|
string $message) : void{
786 if($message instanceof Translatable){
787 $translated = $this->
server->getLanguage()->translate($message);
789 $translated = $message;
791 $this->sendDataPacket(DisconnectPacket::create(0, $translated,
""));
801 $this->tryDisconnect(function() use ($reason, $disconnectScreenMessage, $notify) : void{
803 $this->sendDisconnectPacket($disconnectScreenMessage ?? $reason);
805 if($this->player !==
null){
806 $this->player->onPostDisconnect($reason,
null);
811 public function disconnectWithError(Translatable|
string $reason, Translatable|
string|
null $disconnectScreenMessage =
null) : void{
812 $errorId = implode(
"-", str_split(bin2hex(random_bytes(6)), 4));
815 reason: KnownTranslationFactory::pocketmine_disconnect_error($reason, $errorId)->prefix(TextFormat::RED),
816 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error($disconnectScreenMessage ?? $reason, $errorId),
820 public function disconnectIncompatibleProtocol(
int $protocolVersion) : void{
821 $this->tryDisconnect(
822 function() use ($protocolVersion) : void{
823 $this->sendDataPacket(PlayStatusPacket::create($protocolVersion < ProtocolInfo::CURRENT_PROTOCOL ? PlayStatusPacket::LOGIN_FAILED_CLIENT : PlayStatusPacket::LOGIN_FAILED_SERVER), true);
825 KnownTranslationFactory::pocketmine_disconnect_incompatibleProtocol((
string) $protocolVersion)
834 $this->tryDisconnect(
function() use ($ip, $port, $reason) :
void{
835 $this->sendDataPacket(TransferPacket::create($ip, $port,
false),
true);
836 if($this->player !==
null){
837 $this->player->onPostDisconnect($reason,
null);
846 $this->tryDisconnect(function() use ($disconnectScreenMessage) : void{
847 $this->sendDisconnectPacket($disconnectScreenMessage);
856 $this->tryDisconnect(function() use ($reason) : void{
857 if($this->player !== null){
858 $this->player->onPostDisconnect($reason,
null);
863 private function setAuthenticationStatus(
bool $authenticated,
bool $authRequired,
Translatable|
string|
null $error, ?
string $clientPubKey) : void{
864 if(!$this->connected){
868 if($authenticated && !($this->info instanceof XboxLivePlayerInfo)){
869 $error =
"Expected XUID but none found";
870 }elseif($clientPubKey ===
null){
871 $error =
"Missing client public key";
876 $this->disconnectWithError(
877 reason: KnownTranslationFactory::pocketmine_disconnect_invalidSession($error),
878 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_authentication()
884 $this->authenticated = $authenticated;
886 if(!$this->authenticated){
888 $this->disconnect(
"Not authenticated", KnownTranslationFactory::disconnectionScreen_notAuthenticated());
891 if($this->info instanceof XboxLivePlayerInfo){
892 $this->logger->warning(
"Discarding unexpected XUID for non-authenticated player");
893 $this->info = $this->info->withoutXboxData();
896 $this->logger->debug(
"Xbox Live authenticated: " . ($this->authenticated ?
"YES" :
"NO"));
898 $checkXUID = $this->
server->getConfigGroup()->getPropertyBool(YmlServerProperties::PLAYER_VERIFY_XUID,
true);
899 $myXUID = $this->info instanceof XboxLivePlayerInfo ? $this->info->getXuid() :
"";
900 $kickForXUIDMismatch =
function(
string $xuid) use ($checkXUID, $myXUID) : bool{
901 if($checkXUID && $myXUID !== $xuid){
902 $this->logger->debug(
"XUID mismatch: expected '$xuid', but got '$myXUID'");
907 $this->disconnect(
"XUID does not match (possible impersonation attempt)");
913 foreach($this->manager->getSessions() as $existingSession){
914 if($existingSession === $this){
917 $info = $existingSession->getPlayerInfo();
918 if($info !==
null && (strcasecmp($info->getUsername(), $this->info->getUsername()) === 0 || $info->getUuid()->equals($this->info->getUuid()))){
919 if($kickForXUIDMismatch($info instanceof XboxLivePlayerInfo ? $info->getXuid() :
"")){
922 $ev =
new PlayerDuplicateLoginEvent($this, $existingSession, KnownTranslationFactory::disconnectionScreen_loggedinOtherLocation(),
null);
924 if($ev->isCancelled()){
925 $this->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
929 $existingSession->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
935 $this->cachedOfflinePlayerData = $this->
server->getOfflinePlayerData($this->info->getUsername());
937 $recordedXUID = $this->cachedOfflinePlayerData !==
null ? $this->cachedOfflinePlayerData->getTag(Player::TAG_LAST_KNOWN_XUID) :
null;
938 if(!($recordedXUID instanceof StringTag)){
939 $this->logger->debug(
"No previous XUID recorded, no choice but to trust this player");
940 }elseif(!$kickForXUIDMismatch($recordedXUID->getValue())){
941 $this->logger->debug(
"XUID match");
945 if(EncryptionContext::$ENABLED){
946 $this->
server->getAsyncPool()->submitTask(
new PrepareEncryptionTask($clientPubKey,
function(
string $encryptionKey,
string $handshakeJwt) :
void{
947 if(!$this->connected){
950 $this->sendDataPacket(ServerToClientHandshakePacket::create($handshakeJwt),
true);
952 $this->cipher = EncryptionContext::fakeGCM($encryptionKey);
954 $this->setHandler(
new HandshakePacketHandler($this->onServerLoginSuccess(...)));
955 $this->logger->debug(
"Enabled encryption");
958 $this->onServerLoginSuccess();
962 private function onServerLoginSuccess() : void{
963 $this->loggedIn = true;
965 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::LOGIN_SUCCESS));
967 $this->logger->debug(
"Initiating resource packs phase");
969 $packManager = $this->
server->getResourcePackManager();
970 $resourcePacks = $packManager->getResourceStack();
972 foreach($resourcePacks as $resourcePack){
973 $key = $packManager->getPackEncryptionKey($resourcePack->getPackId());
975 $keys[$resourcePack->getPackId()] = $key;
978 $event =
new PlayerResourcePackOfferEvent($this->info, $resourcePacks, $keys, $packManager->resourcePacksRequired());
980 $this->setHandler(
new ResourcePacksPacketHandler($this, $event->getResourcePacks(), $event->getEncryptionKeys(), $event->mustAccept(),
function() :
void{
981 $this->createPlayer();
985 private function beginSpawnSequence() : void{
986 $this->setHandler(new PreSpawnPacketHandler($this->
server, $this->player, $this, $this->invManager));
987 $this->player->setNoClientPredictions();
989 $this->logger->debug(
"Waiting for chunk radius request");
992 public function notifyTerrainReady() : void{
993 $this->logger->debug(
"Sending spawn notification, waiting for spawn response");
994 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::PLAYER_SPAWN));
995 $this->setHandler(
new SpawnResponsePacketHandler($this->onClientSpawnResponse(...)));
998 private function onClientSpawnResponse() : void{
999 $this->logger->debug(
"Received spawn response, entering in-game phase");
1000 $this->player->setNoClientPredictions(
false);
1001 $this->player->doFirstSpawn();
1002 $this->forceAsyncCompression =
false;
1003 $this->setHandler(
new InGamePacketHandler($this->player, $this, $this->invManager));
1006 public function onServerDeath(Translatable|
string $deathMessage) : void{
1007 if($this->handler instanceof InGamePacketHandler){
1008 $this->setHandler(
new DeathPacketHandler($this->player, $this, $this->invManager ??
throw new AssumptionFailedError(), $deathMessage));
1012 public function onServerRespawn() : void{
1013 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $this->player->getAttributeMap()->getAll());
1014 $this->player->sendData(
null);
1016 $this->syncAbilities($this->player);
1017 $this->invManager->syncAll();
1018 $this->setHandler(
new InGamePacketHandler($this->player, $this, $this->invManager));
1021 public function syncMovement(Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
1022 if($this->player !== null){
1023 $location = $this->player->getLocation();
1024 $yaw = $yaw ?? $location->getYaw();
1025 $pitch = $pitch ?? $location->getPitch();
1027 $this->sendDataPacket(MovePlayerPacket::simple(
1028 $this->player->getId(),
1029 $this->player->getOffsetPosition($pos),
1034 $this->player->onGround,
1039 if($this->handler instanceof InGamePacketHandler){
1040 $this->handler->forceMoveSync =
true;
1045 public function syncViewAreaRadius(
int $distance) : void{
1046 $this->sendDataPacket(ChunkRadiusUpdatedPacket::create($distance));
1049 public function syncViewAreaCenterPoint(Vector3 $newPos,
int $viewDistance) : void{
1050 $this->sendDataPacket(NetworkChunkPublisherUpdatePacket::create(BlockPosition::fromVector3($newPos), $viewDistance * 16, []));
1053 public function syncPlayerSpawnPoint(Position $newSpawn) : void{
1054 $newSpawnBlockPosition = BlockPosition::fromVector3($newSpawn);
1056 $this->sendDataPacket(SetSpawnPositionPacket::playerSpawn($newSpawnBlockPosition, DimensionIds::OVERWORLD, $newSpawnBlockPosition));
1059 public function syncWorldSpawnPoint(Position $newSpawn) : void{
1060 $this->sendDataPacket(SetSpawnPositionPacket::worldSpawn(BlockPosition::fromVector3($newSpawn), DimensionIds::OVERWORLD));
1063 public function syncGameMode(GameMode $mode,
bool $isRollback =
false) : void{
1064 $this->sendDataPacket(SetPlayerGameTypePacket::create($this->typeConverter->coreGameModeToProtocol($mode)));
1065 if($this->player !==
null){
1066 $this->syncAbilities($this->player);
1067 $this->syncAdventureSettings();
1069 if(!$isRollback && $this->invManager !==
null){
1070 $this->invManager->syncCreative();
1074 public function syncAbilities(Player $for) : void{
1075 $isOp = $for->hasPermission(DefaultPermissions::ROOT_OPERATOR);
1079 AbilitiesLayer::ABILITY_ALLOW_FLIGHT => $for->getAllowFlight(),
1080 AbilitiesLayer::ABILITY_FLYING => $for->isFlying(),
1081 AbilitiesLayer::ABILITY_NO_CLIP => !$for->hasBlockCollision(),
1082 AbilitiesLayer::ABILITY_OPERATOR => $isOp,
1083 AbilitiesLayer::ABILITY_TELEPORT => $for->hasPermission(DefaultPermissionNames::COMMAND_TELEPORT_SELF),
1084 AbilitiesLayer::ABILITY_INVULNERABLE => $for->isCreative(),
1085 AbilitiesLayer::ABILITY_MUTED =>
false,
1086 AbilitiesLayer::ABILITY_WORLD_BUILDER =>
false,
1087 AbilitiesLayer::ABILITY_INFINITE_RESOURCES => !$for->hasFiniteResources(),
1088 AbilitiesLayer::ABILITY_LIGHTNING =>
false,
1089 AbilitiesLayer::ABILITY_BUILD => !$for->isSpectator(),
1090 AbilitiesLayer::ABILITY_MINE => !$for->isSpectator(),
1091 AbilitiesLayer::ABILITY_DOORS_AND_SWITCHES => !$for->isSpectator(),
1092 AbilitiesLayer::ABILITY_OPEN_CONTAINERS => !$for->isSpectator(),
1093 AbilitiesLayer::ABILITY_ATTACK_PLAYERS => !$for->isSpectator(),
1094 AbilitiesLayer::ABILITY_ATTACK_MOBS => !$for->isSpectator(),
1095 AbilitiesLayer::ABILITY_PRIVILEGED_BUILDER =>
false,
1099 new AbilitiesLayer(AbilitiesLayer::LAYER_BASE, $boolAbilities, $for->getFlightSpeedMultiplier(), 1, 0.1),
1101 if(!$for->hasBlockCollision()){
1107 $layers[] = new AbilitiesLayer(AbilitiesLayer::LAYER_SPECTATOR, [
1108 AbilitiesLayer::ABILITY_FLYING => true,
1109 ], null, null, null);
1112 $this->sendDataPacket(UpdateAbilitiesPacket::create(
new AbilitiesData(
1113 $isOp ? CommandPermissions::OPERATOR : CommandPermissions::NORMAL,
1114 $isOp ? PlayerPermissions::OPERATOR : PlayerPermissions::MEMBER,
1120 public function syncAdventureSettings() : void{
1121 if($this->player === null){
1122 throw new \LogicException(
"Cannot sync adventure settings for a player that is not yet created");
1125 $this->sendDataPacket(UpdateAdventureSettingsPacket::create(
1126 noAttackingMobs:
false,
1127 noAttackingPlayers:
false,
1128 worldImmutable:
false,
1130 autoJump: $this->player->hasAutoJump()
1134 public function syncAvailableCommands() : void{
1136 foreach($this->
server->getCommandMap()->getCommands() as $command){
1137 if(isset($commandData[$command->getLabel()]) || $command->getLabel() ===
"help" || !$command->testPermissionSilent($this->player)){
1141 $lname = strtolower($command->getLabel());
1142 $aliases = $command->getAliases();
1144 if(count($aliases) > 0){
1145 if(!in_array($lname, $aliases,
true)){
1147 $aliases[] = $lname;
1149 $aliasObj =
new CommandHardEnum(ucfirst($command->getLabel()) .
"Aliases", $aliases);
1152 $description = $command->getDescription();
1153 $data =
new CommandData(
1155 $description instanceof Translatable ? $this->player->getLanguage()->translate($description) : $description,
1157 CommandPermissions::NORMAL,
1160 new CommandOverload(chaining:
false, parameters: [CommandParameter::standard(
"args", AvailableCommandsPacket::ARG_TYPE_RAWTEXT, 0,
true)])
1162 chainedSubCommandData: []
1165 $commandData[$command->getLabel()] = $data;
1168 $this->sendDataPacket(AvailableCommandsPacketAssembler::assemble(array_values($commandData), [], []));
1177 $language = $this->player->getLanguage();
1179 $untranslatedParameterCount = 0;
1180 $translated = $language->translateString($message->getText(), $parameters,
"pocketmine.", $untranslatedParameterCount);
1181 return [$translated, array_slice($parameters, 0, $untranslatedParameterCount)];
1184 public function onChatMessage(
Translatable|
string $message) : void{
1186 if(!$this->
server->isLanguageForced()){
1187 $this->sendDataPacket(TextPacket::translation(...$this->prepareClientTranslatableMessage($message)));
1189 $this->sendDataPacket(TextPacket::raw($this->player->getLanguage()->translate($message)));
1192 $this->sendDataPacket(TextPacket::raw($message));
1196 public function onJukeboxPopup(Translatable|
string $message) : void{
1198 if($message instanceof Translatable){
1199 if(!$this->server->isLanguageForced()){
1200 [$message, $parameters] = $this->prepareClientTranslatableMessage($message);
1202 $message = $this->player->getLanguage()->translate($message);
1205 $this->sendDataPacket(TextPacket::jukeboxPopup($message, $parameters));
1208 public function onPopup(
string $message) : void{
1209 $this->sendDataPacket(TextPacket::popup($message));
1212 public function onTip(
string $message) : void{
1213 $this->sendDataPacket(TextPacket::tip($message));
1216 public function onFormSent(
int $id, Form $form) : bool{
1217 return $this->sendDataPacket(ModalFormRequestPacket::create($id, json_encode($form, JSON_THROW_ON_ERROR)));
1220 public function onCloseAllForms() : void{
1221 $this->sendDataPacket(ClientboundCloseFormPacket::create());
1227 private function sendChunkPacket(
string $chunkPacket, \Closure $onCompletion, World $world) : void{
1228 $world->timings->syncChunkSend->startTiming();
1230 $this->queueCompressed($chunkPacket);
1233 $world->timings->syncChunkSend->stopTiming();
1243 $world = $this->player->getLocation()->getWorld();
1244 $promiseOrPacket = ChunkCache::getInstance($world, $this->compressor)->request($chunkX, $chunkZ);
1245 if(is_string($promiseOrPacket)){
1246 $this->sendChunkPacket($promiseOrPacket, $onCompletion, $world);
1249 $promiseOrPacket->onResolve(
1252 if(!$this->isConnected()){
1255 $currentWorld = $this->player->getLocation()->getWorld();
1256 if($world !== $currentWorld || ($status = $this->player->getUsedChunkStatus($chunkX, $chunkZ)) ===
null){
1257 $this->logger->debug(
"Tried to send no-longer-active chunk $chunkX $chunkZ in world " . $world->getFolderName());
1260 if($status !== UsedChunkStatus::REQUESTED_SENDING){
1267 $this->sendChunkPacket($promise->getResult(), $onCompletion, $world);
1272 public function stopUsingChunk(
int $chunkX,
int $chunkZ) : void{
1276 public function onEnterWorld() : void{
1277 if($this->player !== null){
1278 $world = $this->player->getWorld();
1279 $this->syncWorldTime($world->getTime());
1280 $this->syncWorldDifficulty($world->getDifficulty());
1281 $this->syncWorldSpawnPoint($world->getSpawnLocation());
1286 public function syncWorldTime(
int $worldTime) : void{
1287 $this->sendDataPacket(SetTimePacket::create($worldTime));
1290 public function syncWorldDifficulty(
int $worldDifficulty) : void{
1291 $this->sendDataPacket(SetDifficultyPacket::create($worldDifficulty));
1294 public function getInvManager() : ?InventoryManager{
1295 return $this->invManager;
1303 return
PlayerListEntry::createAdditionEntry($player->getUniqueId(), $player->getId(), $player->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($player->getSkin()), $player->getXuid());
1307 public function onPlayerAdded(
Player $p) : void{
1308 $this->sendDataPacket(PlayerListPacket::add([PlayerListEntry::createAdditionEntry($p->getUniqueId(), $p->getId(), $p->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($p->getSkin()), $p->getXuid())]));
1311 public function onPlayerRemoved(
Player $p) : void{
1312 if($p !== $this->player){
1313 $this->sendDataPacket(PlayerListPacket::remove([PlayerListEntry::createRemovalEntry($p->
getUniqueId())]));
1317 public function onTitle(
string $title) : void{
1318 $this->sendDataPacket(SetTitlePacket::title($title));
1321 public function onSubTitle(
string $subtitle) : void{
1322 $this->sendDataPacket(SetTitlePacket::subtitle($subtitle));
1325 public function onActionBar(
string $actionBar) : void{
1326 $this->sendDataPacket(SetTitlePacket::actionBarMessage($actionBar));
1329 public function onClearTitle() : void{
1330 $this->sendDataPacket(SetTitlePacket::clearTitle());
1333 public function onResetTitleOptions() : void{
1334 $this->sendDataPacket(SetTitlePacket::resetTitleOptions());
1337 public function onTitleDuration(
int $fadeIn,
int $stay,
int $fadeOut) : void{
1338 $this->sendDataPacket(SetTitlePacket::setAnimationTimes($fadeIn, $stay, $fadeOut));
1341 public function onToastNotification(
string $title,
string $body) : void{
1342 $this->sendDataPacket(ToastRequestPacket::create($title, $body));
1345 public function onOpenSignEditor(Vector3 $signPosition,
bool $frontSide) : void{
1346 $this->sendDataPacket(OpenSignPacket::create(BlockPosition::fromVector3($signPosition), $frontSide));
1349 public function onItemCooldownChanged(Item $item,
int $ticks) : void{
1350 $this->sendDataPacket(PlayerStartItemCooldownPacket::create(
1351 GlobalItemDataHandlers::getSerializer()->serializeType($item)->getName(),
1356 public function tick() : void{
1357 if(!$this->isConnected()){
1362 if($this->info ===
null){
1363 if(time() >= $this->connectTime + 10){
1364 $this->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_loginTimeout());
1370 if($this->player !==
null){
1371 $this->player->doChunkRequests();
1373 $dirtyAttributes = $this->player->getAttributeMap()->needSend();
1374 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $dirtyAttributes);
1375 foreach($dirtyAttributes as $attribute){
1378 $attribute->markSynchronized();
1381 Timings::$playerNetworkSendInventorySync->startTiming();
1383 $this->invManager?->flushPendingUpdates();
1385 Timings::$playerNetworkSendInventorySync->stopTiming();
1388 $this->flushGamePacketQueue();