142 private const INCOMING_PACKET_BATCH_PER_TICK = 2;
143 private const INCOMING_PACKET_BATCH_BUFFER_TICKS = 100;
145 private const INCOMING_GAME_PACKETS_PER_TICK = 2;
146 private const INCOMING_GAME_PACKETS_BUFFER_TICKS = 100;
151 private \PrefixedLogger $logger;
152 private ?
Player $player =
null;
154 private ?
int $ping =
null;
158 private bool $connected =
true;
159 private bool $disconnectGuard =
false;
160 private bool $loggedIn =
false;
161 private bool $authenticated =
false;
162 private int $connectTime;
163 private ?
CompoundTag $cachedOfflinePlayerData =
null;
171 private array $sendBuffer = [];
176 private array $sendBufferAckPromises = [];
179 private \SplQueue $compressedQueue;
180 private bool $forceAsyncCompression =
true;
181 private bool $enableCompression =
false;
183 private int $nextAckReceiptId = 0;
188 private array $ackPromisesByReceiptId = [];
198 public function __construct(
210 $this->logger = new \PrefixedLogger($this->
server->getLogger(), $this->getLogPrefix());
212 $this->compressedQueue = new \SplQueue();
216 $this->connectTime = time();
217 $this->packetBatchLimiter =
new PacketRateLimiter(
"Packet Batches", self::INCOMING_PACKET_BATCH_PER_TICK, self::INCOMING_PACKET_BATCH_BUFFER_TICKS);
218 $this->gamePacketLimiter =
new PacketRateLimiter(
"Game Packets", self::INCOMING_GAME_PACKETS_PER_TICK, self::INCOMING_GAME_PACKETS_BUFFER_TICKS);
222 $this->onSessionStartSuccess(...)
225 $this->manager->add($this);
226 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_open()));
229 private function getLogPrefix() :
string{
230 return "NetworkSession: " . $this->getDisplayName();
233 public function getLogger() : \
Logger{
234 return $this->logger;
237 private function onSessionStartSuccess() :
void{
238 $this->logger->debug(
"Session start handshake completed, awaiting login packet");
239 $this->flushGamePacketQueue();
240 $this->enableCompression =
true;
246 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_playerName(TextFormat::AQUA . $info->getUsername() . TextFormat::RESET)));
247 $this->logger->setPrefix($this->getLogPrefix());
248 $this->manager->markLoginReceived($this);
250 $this->setAuthenticationStatus(...)
254 protected function createPlayer() :
void{
255 $this->
server->createPlayer($this, $this->info, $this->authenticated, $this->cachedOfflinePlayerData)->onCompletion(
256 $this->onPlayerCreated(...),
259 $this->disconnectWithError(
260 reason:
"Failed to create player",
261 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_internal()
267 private function onPlayerCreated(
Player $player) :
void{
268 if(!$this->isConnected()){
272 $this->player = $player;
273 if(!$this->
server->addOnlinePlayer($player)){
279 $effectManager = $this->player->getEffects();
280 $effectManager->getEffectAddHooks()->add($effectAddHook =
function(
EffectInstance $effect,
bool $replacesOldEffect) :
void{
281 $this->entityEventBroadcaster->onEntityEffectAdded([$this], $this->player, $effect, $replacesOldEffect);
283 $effectManager->getEffectRemoveHooks()->add($effectRemoveHook =
function(
EffectInstance $effect) :
void{
284 $this->entityEventBroadcaster->onEntityEffectRemoved([$this], $this->player, $effect);
286 $this->disposeHooks->add(
static function() use ($effectManager, $effectAddHook, $effectRemoveHook) :
void{
287 $effectManager->getEffectAddHooks()->remove($effectAddHook);
288 $effectManager->getEffectRemoveHooks()->remove($effectRemoveHook);
291 $permissionHooks = $this->player->getPermissionRecalculationCallbacks();
292 $permissionHooks->add($permHook =
function() :
void{
293 $this->logger->debug(
"Syncing available commands and abilities/permissions due to permission recalculation");
294 $this->syncAbilities($this->player);
295 $this->syncAvailableCommands();
297 $this->disposeHooks->add(
static function() use ($permissionHooks, $permHook) :
void{
298 $permissionHooks->remove($permHook);
300 $this->beginSpawnSequence();
303 public function getPlayer() : ?
Player{
304 return $this->player;
307 public function getPlayerInfo() : ?
PlayerInfo{
311 public function isConnected() :
bool{
312 return $this->connected && !$this->disconnectGuard;
315 public function getIp() :
string{
319 public function getPort() :
int{
323 public function getDisplayName() :
string{
324 return $this->info !==
null ? $this->info->getUsername() : $this->ip .
" " . $this->port;
337 public function updatePing(
int $ping) : void{
341 public function getHandler() : ?PacketHandler{
342 return $this->handler;
345 public function setHandler(?PacketHandler $handler) : void{
346 if($this->connected){
347 $this->handler = $handler;
348 if($this->handler !==
null){
349 $this->handler->setUp();
358 if(!$this->connected){
362 Timings::$playerNetworkReceive->startTiming();
364 $this->packetBatchLimiter->decrement();
366 if($this->cipher !==
null){
367 Timings::$playerNetworkReceiveDecrypt->startTiming();
369 $payload = $this->cipher->decrypt($payload);
370 }
catch(DecryptionException $e){
371 $this->logger->debug(
"Encrypted packet: " . base64_encode($payload));
372 throw PacketHandlingException::wrap($e,
"Packet decryption error");
374 Timings::$playerNetworkReceiveDecrypt->stopTiming();
378 if(strlen($payload) < 1){
379 throw new PacketHandlingException(
"No bytes in payload");
382 if($this->enableCompression){
383 $compressionType = ord($payload[0]);
384 $compressed = substr($payload, 1);
385 if($compressionType === CompressionAlgorithm::NONE){
386 $decompressed = $compressed;
387 }elseif($compressionType === $this->compressor->getNetworkId()){
388 Timings::$playerNetworkReceiveDecompress->startTiming();
390 $decompressed = $this->compressor->decompress($compressed);
391 }
catch(DecompressionException $e){
392 $this->logger->debug(
"Failed to decompress packet: " . base64_encode($compressed));
393 throw PacketHandlingException::wrap($e,
"Compressed packet batch decode error");
395 Timings::$playerNetworkReceiveDecompress->stopTiming();
398 throw new PacketHandlingException(
"Packet compressed with unexpected compression type $compressionType");
401 $decompressed = $payload;
405 $stream =
new ByteBufferReader($decompressed);
406 foreach(PacketBatch::decodeRaw($stream) as $buffer){
407 $this->gamePacketLimiter->decrement();
408 $packet = $this->packetPool->getPacket($buffer);
409 if($packet ===
null){
410 $this->logger->debug(
"Unknown packet: " . base64_encode($buffer));
411 throw new PacketHandlingException(
"Unknown packet received");
414 $this->handleDataPacket($packet, $buffer);
415 }
catch(PacketHandlingException $e){
416 $this->logger->debug($packet->getName() .
": " . base64_encode($buffer));
417 throw PacketHandlingException::wrap($e,
"Error processing " . $packet->getName());
419 if(!$this->isConnected()){
421 $this->logger->debug(
"Aborting batch processing due to server-side disconnection");
425 }
catch(PacketDecodeException|DataDecodeException $e){
426 $this->logger->logException($e);
427 throw PacketHandlingException::wrap($e,
"Packet batch decode error");
430 Timings::$playerNetworkReceive->stopTiming();
442 $timings = Timings::getReceiveDataPacketTimings($packet);
443 $timings->startTiming();
446 if(DataPacketDecodeEvent::hasHandlers()){
449 if($ev->isCancelled()){
454 $decodeTimings = Timings::getDecodeDataPacketTimings($packet);
455 $decodeTimings->startTiming();
457 $stream =
new ByteBufferReader($buffer);
459 $packet->decode($stream);
460 }
catch(PacketDecodeException $e){
461 throw PacketHandlingException::wrap($e);
463 if($stream->getUnreadLength() > 0){
464 $remains = substr($stream->getData(), $stream->getOffset());
465 $this->logger->debug(
"Still " . strlen($remains) .
" bytes unread in " . $packet->getName() .
": " . bin2hex($remains));
468 $decodeTimings->stopTiming();
471 if(DataPacketReceiveEvent::hasHandlers()){
472 $ev =
new DataPacketReceiveEvent($this, $packet);
474 if($ev->isCancelled()){
478 $handlerTimings = Timings::getHandleDataPacketTimings($packet);
479 $handlerTimings->startTiming();
481 if($this->handler ===
null || !$packet->handle($this->handler)){
482 $this->logger->debug(
"Unhandled " . $packet->getName() .
": " . base64_encode($stream->getData()));
485 $handlerTimings->stopTiming();
488 $timings->stopTiming();
492 public function handleAckReceipt(
int $receiptId) : void{
493 if(!$this->connected){
496 if(isset($this->ackPromisesByReceiptId[$receiptId])){
497 $promises = $this->ackPromisesByReceiptId[$receiptId];
498 unset($this->ackPromisesByReceiptId[$receiptId]);
499 foreach($promises as $promise){
500 $promise->resolve(
true);
508 private function sendDataPacketInternal(ClientboundPacket $packet,
bool $immediate, ?PromiseResolver $ackReceiptResolver) : bool{
509 if(!$this->connected){
513 if(!$this->loggedIn && !$packet->canBeSentBeforeLogin()){
514 throw new \InvalidArgumentException(
"Attempted to send " . get_class($packet) .
" to " . $this->getDisplayName() .
" too early");
517 $timings = Timings::getSendDataPacketTimings($packet);
518 $timings->startTiming();
520 if(DataPacketSendEvent::hasHandlers()){
521 $ev = new DataPacketSendEvent([$this], [$packet]);
523 if($ev->isCancelled()){
526 $packets = $ev->getPackets();
528 $packets = [$packet];
531 if($ackReceiptResolver !==
null){
532 $this->sendBufferAckPromises[] = $ackReceiptResolver;
534 $writer =
new ByteBufferWriter();
535 foreach($packets as $evPacket){
537 $this->addToSendBuffer(self::encodePacketTimed($writer, $evPacket));
540 $this->flushGamePacketQueue();
545 $timings->stopTiming();
549 public function sendDataPacket(ClientboundPacket $packet,
bool $immediate =
false) : bool{
550 return $this->sendDataPacketInternal($packet, $immediate, null);
560 if(!$this->sendDataPacketInternal($packet, $immediate, $resolver)){
570 public static function encodePacketTimed(ByteBufferWriter $serializer, ClientboundPacket $packet) : string{
571 $timings =
Timings::getEncodeDataPacketTimings($packet);
572 $timings->startTiming();
574 $packet->encode($serializer);
575 return $serializer->getData();
577 $timings->stopTiming();
584 public function addToSendBuffer(
string $buffer) : void{
585 $this->sendBuffer[] = $buffer;
588 private function flushGamePacketQueue() : void{
589 if(count($this->sendBuffer) > 0){
590 Timings::$playerNetworkSend->startTiming();
593 if($this->forceAsyncCompression){
597 $stream =
new ByteBufferWriter();
598 PacketBatch::encodeRaw($stream, $this->sendBuffer);
600 if($this->enableCompression){
601 $batch = $this->
server->prepareBatch($stream->getData(), $this->compressor, $syncMode, Timings::$playerNetworkSendCompressSessionBuffer);
603 $batch = $stream->getData();
605 $this->sendBuffer = [];
606 $ackPromises = $this->sendBufferAckPromises;
607 $this->sendBufferAckPromises = [];
610 $this->queueCompressedNoGamePacketFlush($batch, networkFlush:
true, ackPromises: $ackPromises);
612 Timings::$playerNetworkSend->stopTiming();
617 public function getBroadcaster() : PacketBroadcaster{ return $this->broadcaster; }
619 public function getEntityEventBroadcaster() : EntityEventBroadcaster{ return $this->entityEventBroadcaster; }
621 public function getCompressor() : Compressor{
622 return $this->compressor;
625 public function getTypeConverter() : TypeConverter{ return $this->typeConverter; }
627 public function queueCompressed(CompressBatchPromise|
string $payload,
bool $immediate =
false) : void{
628 Timings::$playerNetworkSend->startTiming();
632 $this->flushGamePacketQueue();
633 $this->queueCompressedNoGamePacketFlush($payload, $immediate);
635 Timings::$playerNetworkSend->stopTiming();
644 private function queueCompressedNoGamePacketFlush(CompressBatchPromise|
string $batch,
bool $networkFlush =
false, array $ackPromises = []) : void{
645 Timings::$playerNetworkSend->startTiming();
647 $this->compressedQueue->enqueue([$batch, $ackPromises, $networkFlush]);
648 if(is_string($batch)){
649 $this->flushCompressedQueue();
651 $batch->onResolve(
function() :
void{
652 if($this->connected){
653 $this->flushCompressedQueue();
658 Timings::$playerNetworkSend->stopTiming();
662 private function flushCompressedQueue() : void{
663 Timings::$playerNetworkSend->startTiming();
665 while(!$this->compressedQueue->isEmpty()){
667 [$current, $ackPromises, $networkFlush] = $this->compressedQueue->bottom();
668 if(is_string($current)){
669 $this->compressedQueue->dequeue();
670 $this->sendEncoded($current, $networkFlush, $ackPromises);
672 }elseif($current->hasResult()){
673 $this->compressedQueue->dequeue();
674 $this->sendEncoded($current->getResult(), $networkFlush, $ackPromises);
682 Timings::$playerNetworkSend->stopTiming();
690 private function sendEncoded(
string $payload,
bool $immediate, array $ackPromises) : void{
691 if($this->cipher !== null){
692 Timings::$playerNetworkSendEncrypt->startTiming();
693 $payload = $this->cipher->encrypt($payload);
694 Timings::$playerNetworkSendEncrypt->stopTiming();
697 if(count($ackPromises) > 0){
698 $ackReceiptId = $this->nextAckReceiptId++;
699 $this->ackPromisesByReceiptId[$ackReceiptId] = $ackPromises;
701 $ackReceiptId =
null;
703 $this->sender->send($payload, $immediate, $ackReceiptId);
709 private function tryDisconnect(\Closure $func, Translatable|
string $reason) : void{
710 if($this->connected && !$this->disconnectGuard){
711 $this->disconnectGuard =
true;
713 $this->disconnectGuard =
false;
714 $this->flushGamePacketQueue();
715 $this->sender->close(
"");
716 foreach($this->disposeHooks as $callback){
719 $this->disposeHooks->clear();
720 $this->setHandler(
null);
721 $this->connected =
false;
723 $ackPromisesByReceiptId = $this->ackPromisesByReceiptId;
724 $this->ackPromisesByReceiptId = [];
725 foreach($ackPromisesByReceiptId as $resolvers){
726 foreach($resolvers as $resolver){
730 $sendBufferAckPromises = $this->sendBufferAckPromises;
731 $this->sendBufferAckPromises = [];
732 foreach($sendBufferAckPromises as $resolver){
736 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_close($reason)));
744 private function dispose() : void{
745 $this->invManager = null;
748 private function sendDisconnectPacket(Translatable|
string $message) : void{
749 if($message instanceof Translatable){
750 $translated = $this->
server->getLanguage()->translate($message);
752 $translated = $message;
754 $this->sendDataPacket(DisconnectPacket::create(0, $translated,
""));
764 $this->tryDisconnect(function() use ($reason, $disconnectScreenMessage, $notify) : void{
766 $this->sendDisconnectPacket($disconnectScreenMessage ?? $reason);
768 if($this->player !==
null){
769 $this->player->onPostDisconnect($reason,
null);
774 public function disconnectWithError(Translatable|
string $reason, Translatable|
string|
null $disconnectScreenMessage =
null) : void{
775 $errorId = implode(
"-", str_split(bin2hex(random_bytes(6)), 4));
778 reason: KnownTranslationFactory::pocketmine_disconnect_error($reason, $errorId)->prefix(TextFormat::RED),
779 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error($disconnectScreenMessage ?? $reason, $errorId),
783 public function disconnectIncompatibleProtocol(
int $protocolVersion) : void{
784 $this->tryDisconnect(
785 function() use ($protocolVersion) : void{
786 $this->sendDataPacket(PlayStatusPacket::create($protocolVersion < ProtocolInfo::CURRENT_PROTOCOL ? PlayStatusPacket::LOGIN_FAILED_CLIENT : PlayStatusPacket::LOGIN_FAILED_SERVER), true);
788 KnownTranslationFactory::pocketmine_disconnect_incompatibleProtocol((
string) $protocolVersion)
797 $this->tryDisconnect(
function() use ($ip, $port, $reason) :
void{
798 $this->sendDataPacket(TransferPacket::create($ip, $port,
false),
true);
799 if($this->player !==
null){
800 $this->player->onPostDisconnect($reason,
null);
809 $this->tryDisconnect(function() use ($disconnectScreenMessage) : void{
810 $this->sendDisconnectPacket($disconnectScreenMessage);
819 $this->tryDisconnect(function() use ($reason) : void{
820 if($this->player !== null){
821 $this->player->onPostDisconnect($reason,
null);
826 private function setAuthenticationStatus(
bool $authenticated,
bool $authRequired,
Translatable|
string|
null $error, ?
string $clientPubKey) : void{
827 if(!$this->connected){
831 if($authenticated && !($this->info instanceof XboxLivePlayerInfo)){
832 $error =
"Expected XUID but none found";
833 }elseif($clientPubKey ===
null){
834 $error =
"Missing client public key";
839 $this->disconnectWithError(
840 reason: KnownTranslationFactory::pocketmine_disconnect_invalidSession($error),
841 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_authentication()
847 $this->authenticated = $authenticated;
849 if(!$this->authenticated){
851 $this->disconnect(
"Not authenticated", KnownTranslationFactory::disconnectionScreen_notAuthenticated());
854 if($this->info instanceof XboxLivePlayerInfo){
855 $this->logger->warning(
"Discarding unexpected XUID for non-authenticated player");
856 $this->info = $this->info->withoutXboxData();
859 $this->logger->debug(
"Xbox Live authenticated: " . ($this->authenticated ?
"YES" :
"NO"));
861 $checkXUID = $this->
server->getConfigGroup()->getPropertyBool(YmlServerProperties::PLAYER_VERIFY_XUID,
true);
862 $myXUID = $this->info instanceof XboxLivePlayerInfo ? $this->info->getXuid() :
"";
863 $kickForXUIDMismatch =
function(
string $xuid) use ($checkXUID, $myXUID) : bool{
864 if($checkXUID && $myXUID !== $xuid){
865 $this->logger->debug(
"XUID mismatch: expected '$xuid', but got '$myXUID'");
870 $this->disconnect(
"XUID does not match (possible impersonation attempt)");
876 foreach($this->manager->getSessions() as $existingSession){
877 if($existingSession === $this){
880 $info = $existingSession->getPlayerInfo();
881 if($info !==
null && (strcasecmp($info->getUsername(), $this->info->getUsername()) === 0 || $info->getUuid()->equals($this->info->getUuid()))){
882 if($kickForXUIDMismatch($info instanceof XboxLivePlayerInfo ? $info->getXuid() :
"")){
885 $ev =
new PlayerDuplicateLoginEvent($this, $existingSession, KnownTranslationFactory::disconnectionScreen_loggedinOtherLocation(),
null);
887 if($ev->isCancelled()){
888 $this->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
892 $existingSession->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
898 $this->cachedOfflinePlayerData = $this->
server->getOfflinePlayerData($this->info->getUsername());
900 $recordedXUID = $this->cachedOfflinePlayerData !==
null ? $this->cachedOfflinePlayerData->getTag(Player::TAG_LAST_KNOWN_XUID) :
null;
901 if(!($recordedXUID instanceof StringTag)){
902 $this->logger->debug(
"No previous XUID recorded, no choice but to trust this player");
903 }elseif(!$kickForXUIDMismatch($recordedXUID->getValue())){
904 $this->logger->debug(
"XUID match");
908 if(EncryptionContext::$ENABLED){
909 $this->
server->getAsyncPool()->submitTask(
new PrepareEncryptionTask($clientPubKey,
function(
string $encryptionKey,
string $handshakeJwt) :
void{
910 if(!$this->connected){
913 $this->sendDataPacket(ServerToClientHandshakePacket::create($handshakeJwt),
true);
915 $this->cipher = EncryptionContext::fakeGCM($encryptionKey);
917 $this->setHandler(
new HandshakePacketHandler($this->onServerLoginSuccess(...)));
918 $this->logger->debug(
"Enabled encryption");
921 $this->onServerLoginSuccess();
925 private function onServerLoginSuccess() : void{
926 $this->loggedIn = true;
928 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::LOGIN_SUCCESS));
930 $this->logger->debug(
"Initiating resource packs phase");
932 $packManager = $this->
server->getResourcePackManager();
933 $resourcePacks = $packManager->getResourceStack();
935 foreach($resourcePacks as $resourcePack){
936 $key = $packManager->getPackEncryptionKey($resourcePack->getPackId());
938 $keys[$resourcePack->getPackId()] = $key;
941 $event =
new PlayerResourcePackOfferEvent($this->info, $resourcePacks, $keys, $packManager->resourcePacksRequired());
943 $this->setHandler(
new ResourcePacksPacketHandler($this, $event->getResourcePacks(), $event->getEncryptionKeys(), $event->mustAccept(),
function() :
void{
944 $this->createPlayer();
948 private function beginSpawnSequence() : void{
949 $this->setHandler(new PreSpawnPacketHandler($this->
server, $this->player, $this, $this->invManager));
950 $this->player->setNoClientPredictions();
952 $this->logger->debug(
"Waiting for chunk radius request");
955 public function notifyTerrainReady() : void{
956 $this->logger->debug(
"Sending spawn notification, waiting for spawn response");
957 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::PLAYER_SPAWN));
958 $this->setHandler(
new SpawnResponsePacketHandler($this->onClientSpawnResponse(...)));
961 private function onClientSpawnResponse() : void{
962 $this->logger->debug(
"Received spawn response, entering in-game phase");
963 $this->player->setNoClientPredictions(
false);
964 $this->player->doFirstSpawn();
965 $this->forceAsyncCompression =
false;
966 $this->setHandler(
new InGamePacketHandler($this->player, $this, $this->invManager));
969 public function onServerDeath(Translatable|
string $deathMessage) : void{
970 if($this->handler instanceof InGamePacketHandler){
971 $this->setHandler(
new DeathPacketHandler($this->player, $this, $this->invManager ??
throw new AssumptionFailedError(), $deathMessage));
975 public function onServerRespawn() : void{
976 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $this->player->getAttributeMap()->getAll());
977 $this->player->sendData(
null);
979 $this->syncAbilities($this->player);
980 $this->invManager->syncAll();
981 $this->setHandler(
new InGamePacketHandler($this->player, $this, $this->invManager));
984 public function syncMovement(Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
985 if($this->player !== null){
986 $location = $this->player->getLocation();
987 $yaw = $yaw ?? $location->getYaw();
988 $pitch = $pitch ?? $location->getPitch();
990 $this->sendDataPacket(MovePlayerPacket::simple(
991 $this->player->getId(),
992 $this->player->getOffsetPosition($pos),
997 $this->player->onGround,
1002 if($this->handler instanceof InGamePacketHandler){
1003 $this->handler->forceMoveSync =
true;
1008 public function syncViewAreaRadius(
int $distance) : void{
1009 $this->sendDataPacket(ChunkRadiusUpdatedPacket::create($distance));
1012 public function syncViewAreaCenterPoint(Vector3 $newPos,
int $viewDistance) : void{
1013 $this->sendDataPacket(NetworkChunkPublisherUpdatePacket::create(BlockPosition::fromVector3($newPos), $viewDistance * 16, []));
1016 public function syncPlayerSpawnPoint(Position $newSpawn) : void{
1017 $newSpawnBlockPosition = BlockPosition::fromVector3($newSpawn);
1019 $this->sendDataPacket(SetSpawnPositionPacket::playerSpawn($newSpawnBlockPosition, DimensionIds::OVERWORLD, $newSpawnBlockPosition));
1022 public function syncWorldSpawnPoint(Position $newSpawn) : void{
1023 $this->sendDataPacket(SetSpawnPositionPacket::worldSpawn(BlockPosition::fromVector3($newSpawn), DimensionIds::OVERWORLD));
1026 public function syncGameMode(GameMode $mode,
bool $isRollback =
false) : void{
1027 $this->sendDataPacket(SetPlayerGameTypePacket::create($this->typeConverter->coreGameModeToProtocol($mode)));
1028 if($this->player !==
null){
1029 $this->syncAbilities($this->player);
1030 $this->syncAdventureSettings();
1032 if(!$isRollback && $this->invManager !==
null){
1033 $this->invManager->syncCreative();
1037 public function syncAbilities(Player $for) : void{
1038 $isOp = $for->hasPermission(DefaultPermissions::ROOT_OPERATOR);
1042 AbilitiesLayer::ABILITY_ALLOW_FLIGHT => $for->getAllowFlight(),
1043 AbilitiesLayer::ABILITY_FLYING => $for->isFlying(),
1044 AbilitiesLayer::ABILITY_NO_CLIP => !$for->hasBlockCollision(),
1045 AbilitiesLayer::ABILITY_OPERATOR => $isOp,
1046 AbilitiesLayer::ABILITY_TELEPORT => $for->hasPermission(DefaultPermissionNames::COMMAND_TELEPORT_SELF),
1047 AbilitiesLayer::ABILITY_INVULNERABLE => $for->isCreative(),
1048 AbilitiesLayer::ABILITY_MUTED =>
false,
1049 AbilitiesLayer::ABILITY_WORLD_BUILDER =>
false,
1050 AbilitiesLayer::ABILITY_INFINITE_RESOURCES => !$for->hasFiniteResources(),
1051 AbilitiesLayer::ABILITY_LIGHTNING =>
false,
1052 AbilitiesLayer::ABILITY_BUILD => !$for->isSpectator(),
1053 AbilitiesLayer::ABILITY_MINE => !$for->isSpectator(),
1054 AbilitiesLayer::ABILITY_DOORS_AND_SWITCHES => !$for->isSpectator(),
1055 AbilitiesLayer::ABILITY_OPEN_CONTAINERS => !$for->isSpectator(),
1056 AbilitiesLayer::ABILITY_ATTACK_PLAYERS => !$for->isSpectator(),
1057 AbilitiesLayer::ABILITY_ATTACK_MOBS => !$for->isSpectator(),
1058 AbilitiesLayer::ABILITY_PRIVILEGED_BUILDER =>
false,
1062 new AbilitiesLayer(AbilitiesLayer::LAYER_BASE, $boolAbilities, $for->getFlightSpeedMultiplier(), 1, 0.1),
1064 if(!$for->hasBlockCollision()){
1070 $layers[] = new AbilitiesLayer(AbilitiesLayer::LAYER_SPECTATOR, [
1071 AbilitiesLayer::ABILITY_FLYING => true,
1072 ], null, null, null);
1075 $this->sendDataPacket(UpdateAbilitiesPacket::create(
new AbilitiesData(
1076 $isOp ? CommandPermissions::OPERATOR : CommandPermissions::NORMAL,
1077 $isOp ? PlayerPermissions::OPERATOR : PlayerPermissions::MEMBER,
1083 public function syncAdventureSettings() : void{
1084 if($this->player === null){
1085 throw new \LogicException(
"Cannot sync adventure settings for a player that is not yet created");
1088 $this->sendDataPacket(UpdateAdventureSettingsPacket::create(
1089 noAttackingMobs:
false,
1090 noAttackingPlayers:
false,
1091 worldImmutable:
false,
1093 autoJump: $this->player->hasAutoJump()
1097 public function syncAvailableCommands() : void{
1099 $globalAliasMap = $this->
server->getCommandMap()->getAliasMap();
1100 $userAliasMap = $this->player->getCommandAliasMap();
1101 foreach($this->
server->getCommandMap()->getUniqueCommands() as $command){
1102 if(!$command->testPermissionSilent($this->player)){
1106 $userAliases = $userAliasMap->getMergedAliases($command->getId(), $globalAliasMap);
1108 $aliases = array_values(array_filter($userAliases, fn(
string $alias) => $alias !==
"help" && $alias !==
"?"));
1109 if(count($aliases) === 0){
1112 $firstNetworkAlias = $aliases[0];
1115 $lname = strtolower($firstNetworkAlias);
1116 $aliasObj =
new CommandEnum(ucfirst($firstNetworkAlias) .
"Aliases", $aliases);
1118 $description = $command->getDescription();
1119 $data =
new CommandData(
1121 $description instanceof Translatable ? $this->player->getLanguage()->translate($description) : $description,
1126 new CommandOverload(chaining:
false, parameters: [CommandParameter::standard(
"args", AvailableCommandsPacket::ARG_TYPE_RAWTEXT, 0,
true)])
1128 chainedSubCommandData: []
1131 $commandData[] = $data;
1134 $this->sendDataPacket(AvailableCommandsPacket::create($commandData, [], [], []));
1143 $language = $this->player->getLanguage();
1145 return [$language->translateString($message->getText(), $parameters,
"pocketmine."), $parameters];
1148 public function onChatMessage(
Translatable|
string $message) : void{
1150 if(!$this->
server->isLanguageForced()){
1151 $this->sendDataPacket(TextPacket::translation(...$this->prepareClientTranslatableMessage($message)));
1153 $this->sendDataPacket(TextPacket::raw($this->player->getLanguage()->translate($message)));
1156 $this->sendDataPacket(TextPacket::raw($message));
1160 public function onJukeboxPopup(Translatable|
string $message) : void{
1162 if($message instanceof Translatable){
1163 if(!$this->server->isLanguageForced()){
1164 [$message, $parameters] = $this->prepareClientTranslatableMessage($message);
1166 $message = $this->player->getLanguage()->translate($message);
1169 $this->sendDataPacket(TextPacket::jukeboxPopup($message, $parameters));
1172 public function onPopup(
string $message) : void{
1173 $this->sendDataPacket(TextPacket::popup($message));
1176 public function onTip(
string $message) : void{
1177 $this->sendDataPacket(TextPacket::tip($message));
1180 public function onFormSent(
int $id, Form $form) : bool{
1181 return $this->sendDataPacket(ModalFormRequestPacket::create($id, json_encode($form, JSON_THROW_ON_ERROR)));
1184 public function onCloseAllForms() : void{
1185 $this->sendDataPacket(ClientboundCloseFormPacket::create());
1191 private function sendChunkPacket(
string $chunkPacket, \Closure $onCompletion, World $world) : void{
1192 $world->timings->syncChunkSend->startTiming();
1194 $this->queueCompressed($chunkPacket);
1197 $world->timings->syncChunkSend->stopTiming();
1207 $world = $this->player->getLocation()->getWorld();
1208 $promiseOrPacket = ChunkCache::getInstance($world, $this->compressor)->request($chunkX, $chunkZ);
1209 if(is_string($promiseOrPacket)){
1210 $this->sendChunkPacket($promiseOrPacket, $onCompletion, $world);
1213 $promiseOrPacket->onResolve(
1216 if(!$this->isConnected()){
1219 $currentWorld = $this->player->getLocation()->getWorld();
1220 if($world !== $currentWorld || ($status = $this->player->getUsedChunkStatus($chunkX, $chunkZ)) ===
null){
1221 $this->logger->debug(
"Tried to send no-longer-active chunk $chunkX $chunkZ in world " . $world->getFolderName());
1224 if($status !== UsedChunkStatus::REQUESTED_SENDING){
1231 $this->sendChunkPacket($promise->getResult(), $onCompletion, $world);
1236 public function stopUsingChunk(
int $chunkX,
int $chunkZ) : void{
1240 public function onEnterWorld() : void{
1241 if($this->player !== null){
1242 $world = $this->player->getWorld();
1243 $this->syncWorldTime($world->getTime());
1244 $this->syncWorldDifficulty($world->getDifficulty());
1245 $this->syncWorldSpawnPoint($world->getSpawnLocation());
1250 public function syncWorldTime(
int $worldTime) : void{
1251 $this->sendDataPacket(SetTimePacket::create($worldTime));
1254 public function syncWorldDifficulty(
int $worldDifficulty) : void{
1255 $this->sendDataPacket(SetDifficultyPacket::create($worldDifficulty));
1258 public function getInvManager() : ?InventoryManager{
1259 return $this->invManager;
1267 return
PlayerListEntry::createAdditionEntry($player->getUniqueId(), $player->getId(), $player->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($player->getSkin()), $player->getXuid());
1271 public function onPlayerAdded(
Player $p) : void{
1272 $this->sendDataPacket(PlayerListPacket::add([PlayerListEntry::createAdditionEntry($p->getUniqueId(), $p->getId(), $p->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($p->getSkin()), $p->getXuid())]));
1275 public function onPlayerRemoved(
Player $p) : void{
1276 if($p !== $this->player){
1277 $this->sendDataPacket(PlayerListPacket::remove([PlayerListEntry::createRemovalEntry($p->
getUniqueId())]));
1281 public function onTitle(
string $title) : void{
1282 $this->sendDataPacket(SetTitlePacket::title($title));
1285 public function onSubTitle(
string $subtitle) : void{
1286 $this->sendDataPacket(SetTitlePacket::subtitle($subtitle));
1289 public function onActionBar(
string $actionBar) : void{
1290 $this->sendDataPacket(SetTitlePacket::actionBarMessage($actionBar));
1293 public function onClearTitle() : void{
1294 $this->sendDataPacket(SetTitlePacket::clearTitle());
1297 public function onResetTitleOptions() : void{
1298 $this->sendDataPacket(SetTitlePacket::resetTitleOptions());
1301 public function onTitleDuration(
int $fadeIn,
int $stay,
int $fadeOut) : void{
1302 $this->sendDataPacket(SetTitlePacket::setAnimationTimes($fadeIn, $stay, $fadeOut));
1305 public function onToastNotification(
string $title,
string $body) : void{
1306 $this->sendDataPacket(ToastRequestPacket::create($title, $body));
1309 public function onOpenSignEditor(Vector3 $signPosition,
bool $frontSide) : void{
1310 $this->sendDataPacket(OpenSignPacket::create(BlockPosition::fromVector3($signPosition), $frontSide));
1313 public function onItemCooldownChanged(Item $item,
int $ticks) : void{
1314 $this->sendDataPacket(PlayerStartItemCooldownPacket::create(
1315 GlobalItemDataHandlers::getSerializer()->serializeType($item)->getName(),
1320 public function tick() : void{
1321 if(!$this->isConnected()){
1326 if($this->info ===
null){
1327 if(time() >= $this->connectTime + 10){
1328 $this->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_loginTimeout());
1334 if($this->player !==
null){
1335 $this->player->doChunkRequests();
1337 $dirtyAttributes = $this->player->getAttributeMap()->needSend();
1338 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $dirtyAttributes);
1339 foreach($dirtyAttributes as $attribute){
1342 $attribute->markSynchronized();
1345 Timings::$playerNetworkSendInventorySync->startTiming();
1347 $this->invManager?->flushPendingUpdates();
1349 Timings::$playerNetworkSendInventorySync->stopTiming();
1352 $this->flushGamePacketQueue();