184 public const BROADCAST_CHANNEL_ADMINISTRATIVE =
"pocketmine.broadcast.admin";
185 public const BROADCAST_CHANNEL_USERS =
"pocketmine.broadcast.user";
187 public const DEFAULT_SERVER_NAME = VersionInfo::NAME .
" Server";
188 public const DEFAULT_MAX_PLAYERS = 20;
189 public const DEFAULT_PORT_IPV4 = 19132;
190 public const DEFAULT_PORT_IPV6 = 19133;
191 public const DEFAULT_MAX_VIEW_DISTANCE = 16;
198 public const TARGET_TICKS_PER_SECOND = 20;
202 public const TARGET_SECONDS_PER_TICK = 1 / self::TARGET_TICKS_PER_SECOND;
203 public const TARGET_NANOSECONDS_PER_TICK = 1_000_000_000 / self::TARGET_TICKS_PER_SECOND;
208 private const TPS_OVERLOAD_WARNING_THRESHOLD = self::TARGET_TICKS_PER_SECOND * 0.6;
210 private const TICKS_PER_WORLD_CACHE_CLEAR = 5 * self::TARGET_TICKS_PER_SECOND;
211 private const TICKS_PER_TPS_OVERLOAD_WARNING = 5 * self::TARGET_TICKS_PER_SECOND;
212 private const TICKS_PER_STATS_REPORT = 300 * self::TARGET_TICKS_PER_SECOND;
214 private const DEFAULT_ASYNC_COMPRESSION_THRESHOLD = 10_000;
216 private static ?
Server $instance =
null;
224 private Config $operators;
226 private Config $whitelist;
228 private bool $isRunning =
true;
230 private bool $hasStopped =
false;
234 private float $profilingTickRate = self::TARGET_TICKS_PER_SECOND;
241 private int $tickCounter = 0;
242 private float $nextTick = 0;
244 private array $tickAverage;
246 private array $useAverage;
247 private float $currentTPS = self::TARGET_TICKS_PER_SECOND;
248 private float $currentUse = 0;
249 private float $startTime;
251 private bool $doTitleTick =
true;
253 private int $sendUsageTicker = 0;
268 private int $maxPlayers;
270 private bool $onlineMode =
true;
273 private bool $networkCompressionAsync =
true;
274 private int $networkCompressionAsyncThreshold = self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD;
277 private bool $forceLanguage =
false;
279 private UuidInterface $serverID;
281 private string $dataPath;
282 private string $pluginPath;
290 private array $uniquePlayers = [];
297 private array $playerList = [];
305 private array $broadcastSubscribers = [];
307 public function getName() : string{
311 public function isRunning() : bool{
312 return $this->isRunning;
315 public function getPocketMineVersion() : string{
316 return VersionInfo::VERSION()->getFullVersion(true);
319 public function getVersion() : string{
320 return ProtocolInfo::MINECRAFT_VERSION;
323 public function getApiVersion() : string{
324 return VersionInfo::BASE_VERSION;
327 public function getFilePath() : string{
331 public function getResourcePath() : string{
335 public function getDataPath() : string{
336 return $this->dataPath;
339 public function getPluginPath() : string{
340 return $this->pluginPath;
343 public function getMaxPlayers() : int{
344 return $this->maxPlayers;
352 return $this->onlineMode;
359 return $this->getOnlineMode();
362 public function getPort() : int{
363 return $this->configGroup->getConfigInt(
ServerProperties::SERVER_PORT_IPV4, self::DEFAULT_PORT_IPV4);
366 public function getPortV6() : int{
367 return $this->configGroup->getConfigInt(ServerProperties::SERVER_PORT_IPV6, self::DEFAULT_PORT_IPV6);
370 public function getViewDistance() : int{
371 return max(2, $this->configGroup->getConfigInt(ServerProperties::VIEW_DISTANCE, self::DEFAULT_MAX_VIEW_DISTANCE));
378 return max(2, min($distance, $this->memoryManager->getViewDistance($this->getViewDistance())));
381 public function getIp() : string{
383 return $str !==
"" ? $str :
"0.0.0.0";
386 public function getIpV6() : string{
387 $str = $this->configGroup->getConfigString(ServerProperties::SERVER_IPV6);
388 return $str !==
"" ? $str :
"::";
391 public function getServerUniqueId() : UuidInterface{
392 return $this->serverID;
395 public function getGamemode() : GameMode{
396 return GameMode::fromString($this->configGroup->getConfigString(ServerProperties::GAME_MODE)) ?? GameMode::SURVIVAL;
399 public function getForceGamemode() : bool{
400 return $this->configGroup->getConfigBool(ServerProperties::FORCE_GAME_MODE, false);
410 public function hasWhitelist() : bool{
411 return $this->configGroup->getConfigBool(
ServerProperties::WHITELIST, false);
414 public function isHardcore() : bool{
415 return $this->configGroup->getConfigBool(ServerProperties::HARDCORE, false);
418 public function getMotd() : string{
419 return $this->configGroup->getConfigString(ServerProperties::MOTD, self::DEFAULT_SERVER_NAME);
422 public function getLoader() : ThreadSafeClassLoader{
423 return $this->autoloader;
426 public function getLogger() : AttachableThreadSafeLogger{
427 return $this->logger;
430 public function getUpdater() : UpdateChecker{
431 return $this->updater;
434 public function getPluginManager() : PluginManager{
435 return $this->pluginManager;
438 public function getCraftingManager() : CraftingManager{
439 return $this->craftingManager;
442 public function getResourcePackManager() : ResourcePackManager{
443 return $this->resourceManager;
446 public function getWorldManager() : WorldManager{
447 return $this->worldManager;
450 public function getAsyncPool() : AsyncPool{
451 return $this->asyncPool;
454 public function getTick() : int{
455 return $this->tickCounter;
462 return round($this->currentTPS, 2);
469 return round(array_sum($this->tickAverage) / count($this->tickAverage), 2);
476 return round($this->currentUse * 100, 2);
483 return round((array_sum($this->useAverage) / count($this->useAverage)) * 100, 2);
486 public function getStartTime() : float{
487 return $this->startTime;
490 public function getCommandMap() : SimpleCommandMap{
491 return $this->commandMap;
498 return $this->playerList;
501 public function shouldSavePlayerData() : bool{
502 return $this->configGroup->getPropertyBool(Yml::PLAYER_SAVE_PLAYER_DATA, true);
505 public function getOfflinePlayer(
string $name) : Player|OfflinePlayer|null{
506 $name = strtolower($name);
507 $result = $this->getPlayerExact($name);
509 if($result ===
null){
510 $result =
new OfflinePlayer($name, $this->getOfflinePlayerData($name));
520 return $this->playerDataProvider->hasData($name);
523 public function getOfflinePlayerData(
string $name) : ?
CompoundTag{
526 return $this->playerDataProvider->loadData($name);
527 }
catch(PlayerDataLoadException $e){
528 $this->logger->debug(
"Failed to load player data for $name: " . $e->getMessage());
529 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_data_playerCorrupted($name)));
535 public function saveOfflinePlayerData(
string $name, CompoundTag $nbtTag) : void{
536 $ev = new PlayerDataSaveEvent($nbtTag, $name, $this->getPlayerExact($name));
537 if(!$this->shouldSavePlayerData()){
543 if(!$ev->isCancelled()){
544 Timings::$syncPlayerDataSave->time(function() use ($name, $ev) : void{
546 $this->playerDataProvider->saveData($name, $ev->getSaveData());
547 }catch(PlayerDataSaveException $e){
548 $this->logger->critical($this->language->translate(KnownTranslationFactory::pocketmine_data_saveError($name, $e->getMessage())));
549 $this->logger->logException($e);
561 $class = $ev->getPlayerClass();
563 if($offlinePlayerData !==
null && ($world = $this->worldManager->getWorldByName($offlinePlayerData->getString(Player::TAG_LEVEL,
""))) !==
null){
564 $playerPos = EntityDataHelper::parseLocation($offlinePlayerData, $world);
566 $world = $this->worldManager->getDefaultWorld();
568 throw new AssumptionFailedError(
"Default world should always be loaded");
575 $createPlayer =
function(
Location $location) use ($playerPromiseResolver, $class, $session, $playerInfo, $authenticated, $offlinePlayerData) :
void{
577 $player =
new $class($this, $session, $playerInfo, $authenticated, $location, $offlinePlayerData);
578 if(!$player->hasPlayedBefore()){
579 $player->onGround =
true;
581 $playerPromiseResolver->resolve($player);
584 if($playerPos ===
null){
585 $world->requestSafeSpawn()->onCompletion(
586 function(Position $spawn) use ($createPlayer, $playerPromiseResolver, $session, $world) :
void{
587 if(!$session->isConnected()){
588 $playerPromiseResolver->reject();
591 $createPlayer(Location::fromObject($spawn, $world));
593 function() use ($playerPromiseResolver, $session) : void{
594 if($session->isConnected()){
595 $session->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
597 $playerPromiseResolver->reject();
601 $createPlayer($playerPos);
604 return $playerPromiseResolver->getPromise();
619 $name = strtolower($name);
620 $delta = PHP_INT_MAX;
621 foreach($this->getOnlinePlayers() as $player){
622 if(stripos($player->getName(), $name) === 0){
623 $curDelta = strlen($player->getName()) - strlen($name);
624 if($curDelta < $delta){
641 $name = strtolower($name);
642 foreach($this->getOnlinePlayers() as $player){
643 if(strtolower($player->getName()) === $name){
655 return $this->playerList[$rawUUID] ?? null;
662 return $this->getPlayerByRawUUID($uuid->getBytes());
666 return $this->configGroup;
674 if(($command = $this->commandMap->getCommand($name)) instanceof
PluginOwned){
681 public function getNameBans() :
BanList{
682 return $this->banByName;
685 public function getIPBans() : BanList{
686 return $this->banByIP;
689 public function addOp(
string $name) : void{
690 $this->operators->set(strtolower($name), true);
692 if(($player = $this->getPlayerExact($name)) !==
null){
693 $player->setBasePermission(DefaultPermissions::ROOT_OPERATOR,
true);
695 $this->operators->save();
698 public function removeOp(
string $name) : void{
699 $lowercaseName = strtolower($name);
700 foreach($this->operators->getAll() as $operatorName => $_){
701 $operatorName = (string) $operatorName;
702 if($lowercaseName === strtolower($operatorName)){
703 $this->operators->remove($operatorName);
707 if(($player = $this->getPlayerExact($name)) !==
null){
708 $player->unsetBasePermission(DefaultPermissions::ROOT_OPERATOR);
710 $this->operators->save();
713 public function addWhitelist(
string $name) : void{
714 $this->whitelist->set(strtolower($name), true);
715 $this->whitelist->save();
718 public function removeWhitelist(
string $name) : void{
719 $this->whitelist->remove(strtolower($name));
720 $this->whitelist->save();
723 public function isWhitelisted(
string $name) : bool{
724 return !$this->hasWhitelist() || $this->operators->exists($name, true) || $this->whitelist->exists($name, true);
727 public function isOp(
string $name) : bool{
728 return $this->operators->exists($name, true);
731 public function getWhitelisted() : Config{
732 return $this->whitelist;
735 public function getOps() : Config{
736 return $this->operators;
744 $section = $this->configGroup->getProperty(Yml::ALIASES);
746 if(is_array($section)){
747 foreach(Utils::promoteKeys($section) as $key => $value){
751 if(is_array($value)){
754 $commands[] = (string) $value;
757 $result[(string) $key] = $commands;
764 public static function getInstance() : Server{
765 if(self::$instance === null){
766 throw new \RuntimeException(
"Attempt to retrieve Server instance outside server thread");
768 return self::$instance;
771 public function __construct(
772 private ThreadSafeClassLoader $autoloader,
773 private AttachableThreadSafeLogger $logger,
777 if(self::$instance !==
null){
778 throw new \LogicException(
"Only one server instance can exist at once");
780 self::$instance = $this;
781 $this->startTime = microtime(
true);
782 $this->tickAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, self::TARGET_TICKS_PER_SECOND);
783 $this->useAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, 0);
786 $this->tickSleeper =
new TimeTrackingSleeperHandler(Timings::$serverInterrupts);
788 $this->signalHandler =
new SignalHandler(
function() :
void{
789 $this->logger->info(
"Received signal interrupt, stopping the server");
797 Path::join($dataPath,
"worlds"),
798 Path::join($dataPath,
"players")
800 if(!file_exists($neededPath)){
801 mkdir($neededPath, 0777);
805 $this->dataPath = realpath($dataPath) . DIRECTORY_SEPARATOR;
806 $this->pluginPath = realpath($pluginPath) . DIRECTORY_SEPARATOR;
808 $this->logger->info(
"Loading server configuration");
809 $pocketmineYmlPath = Path::join($this->dataPath,
"pocketmine.yml");
810 if(!file_exists($pocketmineYmlPath)){
811 $content = Filesystem::fileGetContents(Path::join(\
pocketmine\RESOURCE_PATH,
"pocketmine.yml"));
812 if(VersionInfo::IS_DEVELOPMENT_BUILD){
813 $content = str_replace(
"preferred-channel: stable",
"preferred-channel: beta", $content);
815 @file_put_contents($pocketmineYmlPath, $content);
818 $this->configGroup =
new ServerConfigGroup(
819 new Config($pocketmineYmlPath, Config::YAML, []),
820 new Config(Path::join($this->dataPath,
"server.properties"), Config::PROPERTIES, [
821 ServerProperties::MOTD => self::DEFAULT_SERVER_NAME,
822 ServerProperties::SERVER_PORT_IPV4 => self::DEFAULT_PORT_IPV4,
823 ServerProperties::SERVER_PORT_IPV6 => self::DEFAULT_PORT_IPV6,
824 ServerProperties::ENABLE_IPV6 =>
true,
825 ServerProperties::WHITELIST =>
false,
826 ServerProperties::MAX_PLAYERS => self::DEFAULT_MAX_PLAYERS,
827 ServerProperties::GAME_MODE => GameMode::SURVIVAL->name,
828 ServerProperties::FORCE_GAME_MODE =>
false,
829 ServerProperties::HARDCORE =>
false,
830 ServerProperties::PVP =>
true,
831 ServerProperties::DIFFICULTY => World::DIFFICULTY_NORMAL,
832 ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS =>
"",
833 ServerProperties::DEFAULT_WORLD_NAME =>
"world",
834 ServerProperties::DEFAULT_WORLD_SEED =>
"",
835 ServerProperties::DEFAULT_WORLD_GENERATOR =>
"DEFAULT",
836 ServerProperties::ENABLE_QUERY =>
true,
837 ServerProperties::AUTO_SAVE =>
true,
838 ServerProperties::VIEW_DISTANCE => self::DEFAULT_MAX_VIEW_DISTANCE,
839 ServerProperties::XBOX_AUTH =>
true,
840 ServerProperties::LANGUAGE =>
"eng"
844 $debugLogLevel = $this->configGroup->getPropertyInt(Yml::DEBUG_LEVEL, 1);
845 if($this->logger instanceof MainLogger){
846 $this->logger->setLogDebug($debugLogLevel > 1);
849 $this->forceLanguage = $this->configGroup->getPropertyBool(Yml::SETTINGS_FORCE_LANGUAGE,
false);
850 $selectedLang = $this->configGroup->getConfigString(ServerProperties::LANGUAGE, $this->configGroup->getPropertyString(
"settings.language", Language::FALLBACK_LANGUAGE));
852 $this->language =
new Language($selectedLang);
853 }
catch(LanguageNotFoundException $e){
854 $this->logger->error($e->getMessage());
856 $this->language =
new Language(Language::FALLBACK_LANGUAGE);
857 }
catch(LanguageNotFoundException $e){
858 $this->logger->emergency(
"Fallback language \"" . Language::FALLBACK_LANGUAGE .
"\" not found");
863 $this->logger->info($this->language->translate(KnownTranslationFactory::language_selected($this->language->getName(), $this->language->getLang())));
865 if(VersionInfo::IS_DEVELOPMENT_BUILD){
866 if(!$this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_DEV_BUILDS,
false)){
867 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error1(VersionInfo::NAME)));
868 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error2()));
869 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error3()));
870 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error4(Yml::SETTINGS_ENABLE_DEV_BUILDS)));
871 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error5(
"https://github.com/pmmp/PocketMine-MP/releases")));
872 $this->forceShutdownExit();
877 $this->logger->warning(str_repeat(
"-", 40));
878 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning1(VersionInfo::NAME)));
879 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning2()));
880 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning3()));
881 $this->logger->warning(str_repeat(
"-", 40));
884 $this->memoryManager =
new MemoryManager($this);
886 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_start(TextFormat::AQUA . $this->getVersion() . TextFormat::RESET)));
888 if(($poolSize = $this->configGroup->getPropertyString(Yml::SETTINGS_ASYNC_WORKERS,
"auto")) ===
"auto"){
890 $processors = Utils::getCoreCount() - 2;
893 $poolSize = max(1, $processors);
896 $poolSize = max(1, (
int) $poolSize);
899 TimingsHandler::setEnabled($this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_PROFILING,
false));
900 $this->profilingTickRate = $this->configGroup->getPropertyInt(Yml::SETTINGS_PROFILE_REPORT_TRIGGER, self::TARGET_TICKS_PER_SECOND);
902 $this->asyncPool =
new AsyncPool($poolSize, max(-1, $this->configGroup->getPropertyInt(Yml::MEMORY_ASYNC_WORKER_HARD_LIMIT, 256)), $this->autoloader, $this->logger, $this->tickSleeper);
903 $this->asyncPool->addWorkerStartHook(
function(
int $i) :
void{
904 if(TimingsHandler::isEnabled()){
905 $this->asyncPool->submitTaskToWorker(TimingsControlTask::setEnabled(
true), $i);
908 TimingsHandler::getToggleCallbacks()->add(
function(
bool $enable) :
void{
909 foreach($this->asyncPool->getRunningWorkers() as $workerId){
910 $this->asyncPool->submitTaskToWorker(TimingsControlTask::setEnabled($enable), $workerId);
913 TimingsHandler::getReloadCallbacks()->add(
function() :
void{
914 foreach($this->asyncPool->getRunningWorkers() as $workerId){
915 $this->asyncPool->submitTaskToWorker(TimingsControlTask::reload(), $workerId);
918 TimingsHandler::getCollectCallbacks()->add(
function() : array{
920 foreach($this->asyncPool->getRunningWorkers() as $workerId){
921 $resolver =
new PromiseResolver();
922 $this->asyncPool->submitTaskToWorker(
new TimingsCollectionTask($resolver), $workerId);
924 $promises[] = $resolver->getPromise();
930 $netCompressionThreshold = -1;
931 if($this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256) >= 0){
932 $netCompressionThreshold = $this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256);
934 if($netCompressionThreshold < 0){
935 $netCompressionThreshold =
null;
938 $netCompressionLevel = $this->configGroup->getPropertyInt(Yml::NETWORK_COMPRESSION_LEVEL, 6);
939 if($netCompressionLevel < 1 || $netCompressionLevel > 9){
940 $this->logger->warning(
"Invalid network compression level $netCompressionLevel set, setting to default 6");
941 $netCompressionLevel = 6;
943 ZlibCompressor::setInstance(
new ZlibCompressor($netCompressionLevel, $netCompressionThreshold, ZlibCompressor::DEFAULT_MAX_DECOMPRESSION_SIZE));
945 $this->networkCompressionAsync = $this->configGroup->getPropertyBool(Yml::NETWORK_ASYNC_COMPRESSION,
true);
946 $this->networkCompressionAsyncThreshold = max(
947 $this->configGroup->getPropertyInt(Yml::NETWORK_ASYNC_COMPRESSION_THRESHOLD, self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD),
948 $netCompressionThreshold ?? self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD
951 EncryptionContext::$ENABLED = $this->configGroup->getPropertyBool(Yml::NETWORK_ENABLE_ENCRYPTION,
true);
953 $this->doTitleTick = $this->configGroup->getPropertyBool(Yml::CONSOLE_TITLE_TICK,
true) && Terminal::hasFormattingCodes();
955 $this->operators =
new Config(Path::join($this->dataPath,
"ops.txt"), Config::ENUM);
956 $this->whitelist =
new Config(Path::join($this->dataPath,
"white-list.txt"), Config::ENUM);
958 $bannedTxt = Path::join($this->dataPath,
"banned.txt");
959 $bannedPlayersTxt = Path::join($this->dataPath,
"banned-players.txt");
960 if(file_exists($bannedTxt) && !file_exists($bannedPlayersTxt)){
961 @rename($bannedTxt, $bannedPlayersTxt);
963 @touch($bannedPlayersTxt);
964 $this->banByName =
new BanList($bannedPlayersTxt);
965 $this->banByName->load();
966 $bannedIpsTxt = Path::join($this->dataPath,
"banned-ips.txt");
967 @touch($bannedIpsTxt);
968 $this->banByIP =
new BanList($bannedIpsTxt);
969 $this->banByIP->load();
971 $this->maxPlayers = $this->configGroup->getConfigInt(ServerProperties::MAX_PLAYERS, self::DEFAULT_MAX_PLAYERS);
973 $this->onlineMode = $this->configGroup->getConfigBool(ServerProperties::XBOX_AUTH,
true);
974 if($this->onlineMode){
975 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_enabled()));
977 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_disabled()));
978 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authWarning()));
979 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authProperty_disabled()));
982 if($this->configGroup->getConfigBool(ServerProperties::HARDCORE,
false) && $this->getDifficulty() < World::DIFFICULTY_HARD){
983 $this->configGroup->setConfigInt(ServerProperties::DIFFICULTY, World::DIFFICULTY_HARD);
986 @cli_set_process_title($this->getName() .
" " . $this->getPocketMineVersion());
988 $this->serverID = Utils::getMachineUniqueId($this->getIp() . $this->getPort());
990 $this->logger->debug(
"Server unique id: " . $this->getServerUniqueId());
991 $this->logger->debug(
"Machine unique id: " . Utils::getMachineUniqueId());
993 $this->network =
new Network($this->logger);
994 $this->network->setName($this->getMotd());
996 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_info(
998 (VersionInfo::IS_DEVELOPMENT_BUILD ? TextFormat::YELLOW :
"") . $this->getPocketMineVersion() . TextFormat::RESET
1000 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_license($this->getName())));
1002 DefaultPermissions::registerCorePermissions();
1004 $this->commandMap =
new SimpleCommandMap($this);
1006 $this->craftingManager = CraftingManagerFromDataHelper::make(Path::join(\
pocketmine\BEDROCK_DATA_PATH,
"recipes"));
1008 $this->resourceManager =
new ResourcePackManager(Path::join($this->dataPath,
"resource_packs"), $this->logger);
1010 $pluginGraylist =
null;
1011 $graylistFile = Path::join($this->dataPath,
"plugin_list.yml");
1012 if(!file_exists($graylistFile)){
1013 copy(Path::join(\
pocketmine\RESOURCE_PATH,
'plugin_list.yml'), $graylistFile);
1016 $pluginGraylist = PluginGraylist::fromArray(yaml_parse(Filesystem::fileGetContents($graylistFile)));
1017 }
catch(\InvalidArgumentException $e){
1018 $this->logger->emergency(
"Failed to load $graylistFile: " . $e->getMessage());
1019 $this->forceShutdownExit();
1022 $this->pluginManager =
new PluginManager($this, $this->configGroup->getPropertyBool(Yml::PLUGINS_LEGACY_DATA_DIR,
true) ?
null : Path::join($this->dataPath,
"plugin_data"), $pluginGraylist);
1023 $this->pluginManager->registerInterface(
new PharPluginLoader($this->autoloader));
1024 $this->pluginManager->registerInterface(
new ScriptPluginLoader());
1026 $providerManager =
new WorldProviderManager();
1028 ($format = $providerManager->getProviderByName($formatName = $this->configGroup->getPropertyString(Yml::LEVEL_SETTINGS_DEFAULT_FORMAT,
""))) !==
null &&
1029 $format instanceof WritableWorldProviderManagerEntry
1031 $providerManager->setDefault($format);
1032 }elseif($formatName !==
""){
1033 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_level_badDefaultFormat($formatName)));
1036 $this->worldManager =
new WorldManager($this, Path::join($this->dataPath,
"worlds"), $providerManager);
1037 $this->worldManager->setAutoSave($this->configGroup->getConfigBool(ServerProperties::AUTO_SAVE, $this->worldManager->getAutoSave()));
1038 $this->worldManager->setAutoSaveInterval($this->configGroup->getPropertyInt(Yml::TICKS_PER_AUTOSAVE, $this->worldManager->getAutoSaveInterval()));
1040 $this->updater =
new UpdateChecker($this, $this->configGroup->getPropertyString(Yml::AUTO_UPDATER_HOST,
"update.pmmp.io"));
1042 $this->queryInfo =
new QueryInfo($this);
1044 $this->playerDataProvider =
new DatFilePlayerDataProvider(Path::join($this->dataPath,
"players"));
1046 register_shutdown_function($this->crashDump(...));
1048 $loadErrorCount = 0;
1049 $this->pluginManager->loadPlugins($this->pluginPath, $loadErrorCount);
1050 if($loadErrorCount > 0){
1051 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someLoadErrors()));
1052 $this->forceShutdownExit();
1055 if(!$this->enablePlugins(PluginEnableOrder::STARTUP)){
1056 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1057 $this->forceShutdownExit();
1061 if(!$this->startupPrepareWorlds()){
1062 $this->forceShutdownExit();
1066 if(!$this->enablePlugins(PluginEnableOrder::POSTWORLD)){
1067 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1068 $this->forceShutdownExit();
1072 if(!$this->startupPrepareNetworkInterfaces()){
1073 $this->forceShutdownExit();
1077 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED,
true)){
1078 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1079 $this->sendUsage(SendUsageTask::TYPE_OPEN);
1082 $this->configGroup->save();
1084 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_defaultGameMode($this->getGamemode()->getTranslatableName())));
1085 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_donate(TextFormat::AQUA .
"https://patreon.com/pocketminemp" . TextFormat::RESET)));
1086 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_startFinished(strval(round(microtime(
true) - $this->startTime, 3)))));
1088 $forwarder =
new BroadcastLoggerForwarder($this, $this->logger, $this->language);
1089 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_ADMINISTRATIVE, $forwarder);
1090 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_USERS, $forwarder);
1093 if($this->configGroup->getPropertyBool(Yml::CONSOLE_ENABLE_INPUT,
true)){
1094 $this->console =
new ConsoleReaderChildProcessDaemon($this->logger);
1097 $this->tickProcessor();
1098 $this->forceShutdown();
1099 }
catch(\Throwable $e){
1100 $this->exceptionHandler($e);
1104 private function startupPrepareWorlds() : bool{
1105 $getGenerator = function(string $generatorName, string $generatorOptions, string $worldName) : ?string{
1106 $generatorEntry = GeneratorManager::getInstance()->getGenerator($generatorName);
1107 if($generatorEntry ===
null){
1108 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1110 KnownTranslationFactory::pocketmine_level_unknownGenerator($generatorName)
1115 $generatorEntry->validateGeneratorOptions($generatorOptions);
1116 }
catch(InvalidGeneratorOptionsException $e){
1117 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1119 KnownTranslationFactory::pocketmine_level_invalidGeneratorOptions($generatorOptions, $generatorName, $e->getMessage())
1123 return $generatorEntry->getGeneratorClass();
1126 $anyWorldFailedToLoad =
false;
1128 foreach(Utils::promoteKeys((array) $this->configGroup->getProperty(Yml::WORLDS, [])) as $name => $options){
1129 if(!is_string($name)){
1133 if($options ===
null){
1135 }elseif(!is_array($options)){
1139 if(!$this->worldManager->loadWorld($name,
true)){
1140 if($this->worldManager->isWorldGenerated($name)){
1142 $anyWorldFailedToLoad = true;
1145 $creationOptions = WorldCreationOptions::create();
1148 $generatorName = $options[
"generator"] ??
"default";
1149 $generatorOptions = isset($options[
"preset"]) && is_string($options[
"preset"]) ? $options[
"preset"] :
"";
1151 $generatorClass = $getGenerator($generatorName, $generatorOptions, $name);
1152 if($generatorClass ===
null){
1153 $anyWorldFailedToLoad =
true;
1156 $creationOptions->setGeneratorClass($generatorClass);
1157 $creationOptions->setGeneratorOptions($generatorOptions);
1159 $creationOptions->setDifficulty($this->getDifficulty());
1160 if(isset($options[
"difficulty"]) && is_string($options[
"difficulty"])){
1161 $creationOptions->setDifficulty(World::getDifficultyFromString($options[
"difficulty"]));
1164 if(isset($options[
"seed"])){
1165 $convertedSeed = Generator::convertSeed((
string) ($options[
"seed"] ??
""));
1166 if($convertedSeed !==
null){
1167 $creationOptions->setSeed($convertedSeed);
1171 $this->worldManager->generateWorld($name, $creationOptions);
1175 if($this->worldManager->getDefaultWorld() ===
null){
1176 $default = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_NAME,
"world");
1177 if(trim($default) ==
""){
1178 $this->logger->warning(
"level-name cannot be null, using default");
1180 $this->configGroup->setConfigString(ServerProperties::DEFAULT_WORLD_NAME,
"world");
1182 if(!$this->worldManager->loadWorld($default,
true)){
1183 if($this->worldManager->isWorldGenerated($default)){
1184 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1188 $generatorName = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR);
1189 $generatorOptions = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS);
1190 $generatorClass = $getGenerator($generatorName, $generatorOptions, $default);
1192 if($generatorClass ===
null){
1193 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1196 $creationOptions = WorldCreationOptions::create()
1197 ->setGeneratorClass($generatorClass)
1198 ->setGeneratorOptions($generatorOptions);
1199 $convertedSeed = Generator::convertSeed($this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_SEED));
1200 if($convertedSeed !==
null){
1201 $creationOptions->setSeed($convertedSeed);
1203 $creationOptions->setDifficulty($this->getDifficulty());
1204 $this->worldManager->generateWorld($default, $creationOptions);
1207 $world = $this->worldManager->getWorldByName($default);
1208 if($world ===
null){
1209 throw new AssumptionFailedError(
"We just loaded/generated the default world, so it must exist");
1211 $this->worldManager->setDefaultWorld($world);
1214 return !$anyWorldFailedToLoad;
1217 private function startupPrepareConnectableNetworkInterfaces(
1222 PacketBroadcaster $packetBroadcaster,
1223 EntityEventBroadcaster $entityEventBroadcaster,
1224 TypeConverter $typeConverter
1226 $prettyIp = $ipV6 ?
"[$ip]" : $ip;
1228 $rakLibRegistered = $this->network->registerInterface(
new RakLibInterface($this, $ip, $port, $ipV6, $packetBroadcaster, $entityEventBroadcaster, $typeConverter));
1229 }
catch(NetworkInterfaceStartException $e){
1230 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStartFailed(
1237 if($rakLibRegistered){
1238 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStart($prettyIp, (
string) $port)));
1241 if(!$rakLibRegistered){
1244 $this->network->registerInterface(
new DedicatedQueryNetworkInterface($ip, $port, $ipV6,
new \
PrefixedLogger($this->logger,
"Dedicated Query Interface")));
1246 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_query_running($prettyIp, (
string) $port)));
1251 private function startupPrepareNetworkInterfaces() : bool{
1252 $useQuery = $this->configGroup->getConfigBool(ServerProperties::ENABLE_QUERY, true);
1254 $typeConverter = TypeConverter::getInstance();
1255 $packetBroadcaster =
new StandardPacketBroadcaster($this);
1256 $entityEventBroadcaster =
new StandardEntityEventBroadcaster($packetBroadcaster, $typeConverter);
1259 !$this->startupPrepareConnectableNetworkInterfaces($this->getIp(), $this->getPort(),
false, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter) ||
1261 $this->configGroup->getConfigBool(ServerProperties::ENABLE_IPV6,
true) &&
1262 !$this->startupPrepareConnectableNetworkInterfaces($this->getIpV6(), $this->getPortV6(),
true, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter)
1269 $this->network->registerRawPacketHandler(
new QueryHandler($this));
1272 foreach($this->getIPBans()->getEntries() as $entry){
1273 $this->network->blockAddress($entry->getName(), -1);
1276 if($this->configGroup->getPropertyBool(Yml::NETWORK_UPNP_FORWARDING,
false)){
1277 $this->network->registerInterface(
new UPnPNetworkInterface($this->logger, Internet::getInternalIP(), $this->getPort()));
1288 $this->broadcastSubscribers[$channelId][spl_object_id($subscriber)] = $subscriber;
1295 if(isset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)])){
1296 if(count($this->broadcastSubscribers[$channelId]) === 1){
1297 unset($this->broadcastSubscribers[$channelId]);
1299 unset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)]);
1308 foreach(
Utils::stringifyKeys($this->broadcastSubscribers) as $channelId => $recipients){
1309 $this->unsubscribeFromBroadcastChannel($channelId, $subscriber);
1320 return $this->broadcastSubscribers[$channelId] ?? [];
1327 $recipients = $recipients ?? $this->getBroadcastChannelSubscribers(self::BROADCAST_CHANNEL_USERS);
1329 foreach($recipients as $recipient){
1330 $recipient->sendMessage($message);
1333 return count($recipients);
1339 private function getPlayerBroadcastSubscribers(
string $channelId) : array{
1342 foreach($this->broadcastSubscribers[$channelId] as $subscriber){
1343 if($subscriber instanceof Player){
1344 $players[spl_object_id($subscriber)] = $subscriber;
1353 public function broadcastTip(
string $tip, ?array $recipients =
null) : int{
1354 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1356 foreach($recipients as $recipient){
1357 $recipient->sendTip($tip);
1360 return count($recipients);
1367 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1369 foreach($recipients as $recipient){
1370 $recipient->sendPopup($popup);
1373 return count($recipients);
1382 public function broadcastTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1, ?array $recipients =
null) : int{
1383 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1385 foreach($recipients as $recipient){
1386 $recipient->sendTitle($title, $subtitle, $fadeIn, $stay, $fadeOut);
1389 return count($recipients);
1405 public function prepareBatch(
string $buffer, Compressor $compressor, ?
bool $sync =
null, ?TimingsHandler $timings =
null) : CompressBatchPromise|string{
1406 $timings ??= Timings::$playerNetworkSendCompress;
1408 $timings->startTiming();
1410 $threshold = $compressor->getCompressionThreshold();
1411 if($threshold ===
null || strlen($buffer) < $compressor->getCompressionThreshold()){
1412 $compressionType = CompressionAlgorithm::NONE;
1413 $compressed = $buffer;
1416 $sync ??= !$this->networkCompressionAsync;
1418 if(!$sync && strlen($buffer) >= $this->networkCompressionAsyncThreshold){
1419 $promise =
new CompressBatchPromise();
1420 $task =
new CompressBatchTask($buffer, $promise, $compressor);
1421 $this->asyncPool->submitTask($task);
1425 $compressionType = $compressor->getNetworkId();
1426 $compressed = $compressor->compress($buffer);
1429 return chr($compressionType) . $compressed;
1431 $timings->stopTiming();
1435 public function enablePlugins(PluginEnableOrder $type) : bool{
1437 foreach($this->pluginManager->getPlugins() as $plugin){
1438 if(!$plugin->isEnabled() && $plugin->getDescription()->getOrder() === $type){
1439 if(!$this->pluginManager->enablePlugin($plugin)){
1440 $allSuccess =
false;
1445 if($type === PluginEnableOrder::POSTWORLD){
1446 $this->commandMap->registerServerAliases();
1459 if($ev->isCancelled()){
1463 $commandLine = $ev->getCommand();
1466 return $this->commandMap->dispatch($sender, $commandLine);
1473 if($this->isRunning){
1474 $this->isRunning =
false;
1475 $this->signalHandler->unregister();
1479 private function forceShutdownExit() : void{
1480 $this->forceShutdown();
1481 Process::kill(Process::pid());
1484 public function forceShutdown() : void{
1485 if($this->hasStopped){
1489 if($this->doTitleTick){
1493 if($this->isRunning){
1494 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_forcingShutdown()));
1497 if(!$this->isRunning()){
1498 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1501 $this->hasStopped =
true;
1505 if(isset($this->pluginManager)){
1506 $this->logger->debug(
"Disabling all plugins");
1507 $this->pluginManager->disablePlugins();
1510 if(isset($this->network)){
1511 $this->network->getSessionManager()->close($this->configGroup->getPropertyString(Yml::SETTINGS_SHUTDOWN_MESSAGE,
"Server closed"));
1514 if(isset($this->worldManager)){
1515 $this->logger->debug(
"Unloading all worlds");
1516 foreach($this->worldManager->getWorlds() as $world){
1517 $this->worldManager->unloadWorld($world,
true);
1521 $this->logger->debug(
"Removing event handlers");
1522 HandlerListManager::global()->unregisterAll();
1524 if(isset($this->asyncPool)){
1525 $this->logger->debug(
"Shutting down async task worker pool");
1526 $this->asyncPool->shutdown();
1529 if(isset($this->configGroup)){
1530 $this->logger->debug(
"Saving properties");
1531 $this->configGroup->save();
1534 if($this->console !==
null){
1535 $this->logger->debug(
"Closing console");
1536 $this->console->quit();
1539 if(isset($this->network)){
1540 $this->logger->debug(
"Stopping network interfaces");
1541 foreach($this->network->getInterfaces() as $interface){
1542 $this->logger->debug(
"Stopping network interface " . get_class($interface));
1543 $this->network->unregisterInterface($interface);
1546 }
catch(\Throwable $e){
1547 $this->logger->logException($e);
1548 $this->logger->emergency(
"Crashed while crashing, killing process");
1549 @Process::kill(Process::pid());
1554 public function getQueryInformation() : QueryInfo{
1555 return $this->queryInfo;
1563 while(@ob_end_flush()){}
1566 if($trace ===
null){
1567 $trace = $e->getTrace();
1573 $this->logger->logException($e, $trace);
1575 if($e instanceof ThreadCrashException){
1576 $info = $e->getCrashInfo();
1577 $type = $info->getType();
1578 $errstr = $info->getMessage();
1579 $errfile = $info->getFile();
1580 $errline = $info->getLine();
1581 $printableTrace = $info->getTrace();
1582 $thread = $info->getThreadName();
1584 $type = get_class($e);
1585 $errstr = $e->getMessage();
1586 $errfile = $e->getFile();
1587 $errline = $e->getLine();
1588 $printableTrace = Utils::printableTraceWithMetadata($trace);
1592 $errstr = preg_replace(
'/\s+/',
' ', trim($errstr));
1596 "message" => $errstr,
1597 "fullFile" => $errfile,
1598 "file" => Filesystem::cleanPath($errfile),
1600 "trace" => $printableTrace,
1604 global $lastExceptionError, $lastError;
1605 $lastExceptionError = $lastError;
1609 private function writeCrashDumpFile(CrashDump $dump) : string{
1610 $crashFolder = Path::join($this->dataPath,
"crashdumps");
1611 if(!is_dir($crashFolder)){
1612 mkdir($crashFolder);
1614 $crashDumpPath = Path::join($crashFolder, date(
"D_M_j-H.i.s-T_Y", (
int) $dump->getData()->time) .
".log");
1616 $fp = @fopen($crashDumpPath,
"wb");
1617 if(!is_resource($fp)){
1618 throw new \RuntimeException(
"Unable to open new file to generate crashdump");
1620 $writer =
new CrashDumpRenderer($fp, $dump->getData());
1621 $writer->renderHumanReadable();
1622 $dump->encodeData($writer);
1625 return $crashDumpPath;
1628 public function crashDump() : void{
1629 while(@ob_end_flush()){}
1630 if(!$this->isRunning){
1633 if($this->sendUsageTicker > 0){
1634 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1636 $this->hasStopped =
false;
1638 ini_set(
"error_reporting",
'0');
1639 ini_set(
"memory_limit",
'-1');
1641 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_create()));
1642 $dump =
new CrashDump($this, $this->pluginManager ??
null);
1644 $crashDumpPath = $this->writeCrashDumpFile($dump);
1646 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_submit($crashDumpPath)));
1648 if($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_ENABLED,
true)){
1651 $stamp = Path::join($this->dataPath,
"crashdumps",
".last_crash");
1652 $crashInterval = 120;
1653 if(($lastReportTime = @filemtime($stamp)) !==
false && $lastReportTime + $crashInterval >= time()){
1655 $this->logger->debug(
"Not sending crashdump due to last crash less than $crashInterval seconds ago");
1659 if($dump->getData()->error[
"type"] === \ParseError::class){
1663 if(strrpos(VersionInfo::GIT_HASH(),
"-dirty") !==
false || VersionInfo::GIT_HASH() === str_repeat(
"00", 20)){
1664 $this->logger->debug(
"Not sending crashdump due to locally modified");
1669 $url = ($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_USE_HTTPS,
true) ?
"https" :
"http") .
"://" . $this->configGroup->getPropertyString(Yml::AUTO_REPORT_HOST,
"crash.pmmp.io") .
"/submit/api";
1670 $postUrlError =
"Unknown error";
1671 $reply = Internet::postURL($url, [
1673 "name" => $this->getName() .
" " . $this->getPocketMineVersion(),
1675 "reportPaste" => base64_encode($dump->getEncodedData())
1676 ], 10, [], $postUrlError);
1678 if($reply !==
null && is_object($data = json_decode($reply->getBody()))){
1679 if(isset($data->crashId) && is_int($data->crashId) && isset($data->crashUrl) && is_string($data->crashUrl)){
1680 $reportId = $data->crashId;
1681 $reportUrl = $data->crashUrl;
1682 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_archive($reportUrl, (
string) $reportId)));
1683 }elseif(isset($data->error) && is_string($data->error)){
1684 $this->logger->emergency(
"Automatic crash report submission failed: $data->error");
1686 $this->logger->emergency(
"Invalid JSON response received from crash archive: " . $reply->getBody());
1689 $this->logger->emergency(
"Failed to communicate with crash archive: $postUrlError");
1693 }
catch(\Throwable $e){
1694 $this->logger->logException($e);
1696 $this->logger->critical($this->language->translate(KnownTranslationFactory::pocketmine_crash_error($e->getMessage())));
1697 }
catch(\Throwable $e){}
1700 $this->forceShutdown();
1701 $this->isRunning =
false;
1704 $uptime = time() - ((int) $this->startTime);
1706 $spacing = $minUptime - $uptime;
1708 echo
"--- Uptime {$uptime}s - waiting {$spacing}s to throttle automatic restart (you can kill the process safely now) ---" . PHP_EOL;
1711 @Process::kill(Process::pid());
1723 return $this->tickSleeper;
1726 private function tickProcessor() : void{
1727 $this->nextTick = microtime(true);
1729 while($this->isRunning){
1733 $this->tickSleeper->sleepUntil($this->nextTick);
1737 public function addOnlinePlayer(Player $player) : bool{
1738 $ev = new PlayerLoginEvent($player,
"Plugin reason");
1740 if($ev->isCancelled() || !$player->isConnected()){
1741 $player->disconnect($ev->getKickMessage());
1746 $session = $player->getNetworkSession();
1747 $position = $player->getPosition();
1748 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_player_logIn(
1749 TextFormat::AQUA . $player->getName() . TextFormat::RESET,
1751 (
string) $session->getPort(),
1752 (
string) $player->getId(),
1753 $position->getWorld()->getDisplayName(),
1754 (
string) round($position->x, 4),
1755 (
string) round($position->y, 4),
1756 (
string) round($position->z, 4)
1759 foreach($this->playerList as $p){
1760 $p->getNetworkSession()->onPlayerAdded($player);
1762 $rawUUID = $player->getUniqueId()->getBytes();
1763 $this->playerList[$rawUUID] = $player;
1765 if($this->sendUsageTicker > 0){
1766 $this->uniquePlayers[$rawUUID] = $rawUUID;
1772 public function removeOnlinePlayer(Player $player) : void{
1773 if(isset($this->playerList[$rawUUID = $player->getUniqueId()->getBytes()])){
1774 unset($this->playerList[$rawUUID]);
1775 foreach($this->playerList as $p){
1776 $p->getNetworkSession()->onPlayerRemoved($player);
1781 public function sendUsage(
int $type = SendUsageTask::TYPE_STATUS) : void{
1782 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED, true)){
1783 $this->asyncPool->submitTask(
new SendUsageTask($this, $type, $this->uniquePlayers));
1785 $this->uniquePlayers = [];
1788 public function getLanguage() : Language{
1789 return $this->language;
1792 public function isLanguageForced() : bool{
1793 return $this->forceLanguage;
1796 public function getNetwork() : Network{
1797 return $this->network;
1800 public function getMemoryManager() : MemoryManager{
1801 return $this->memoryManager;
1804 private function titleTick() : void{
1805 Timings::$titleTick->startTiming();
1807 $u = Process::getAdvancedMemoryUsage();
1808 $usage = sprintf(
"%g/%g/%g MB @ %d threads", round(($u[0] / 1024) / 1024, 2), round(($u[1] / 1024) / 1024, 2), round(($u[2] / 1024) / 1024, 2), Process::getThreadCount());
1810 $online = count($this->playerList);
1811 $connecting = $this->network->getConnectionCount() - $online;
1812 $bandwidthStats = $this->network->getBandwidthTracker();
1814 echo
"\x1b]0;" . $this->getName() .
" " .
1815 $this->getPocketMineVersion() .
1816 " | Online $online/" . $this->maxPlayers .
1817 ($connecting > 0 ?
" (+$connecting connecting)" :
"") .
1818 " | Memory " . $usage .
1819 " | U " . round($bandwidthStats->getSend()->getAverageBytes() / 1024, 2) .
1820 " D " . round($bandwidthStats->getReceive()->getAverageBytes() / 1024, 2) .
1821 " kB/s | TPS " . $this->getTicksPerSecondAverage() .
1822 " | Load " . $this->getTickUsageAverage() .
"%\x07";
1824 Timings::$titleTick->stopTiming();
1830 private function tick() : void{
1831 $tickTime = microtime(true);
1832 if(($tickTime - $this->nextTick) < -0.025){
1836 Timings::$serverTick->startTiming();
1838 ++$this->tickCounter;
1840 Timings::$scheduler->startTiming();
1841 $this->pluginManager->tickSchedulers($this->tickCounter);
1842 Timings::$scheduler->stopTiming();
1844 Timings::$schedulerAsync->startTiming();
1845 $this->asyncPool->collectTasks();
1846 Timings::$schedulerAsync->stopTiming();
1848 $this->worldManager->tick($this->tickCounter);
1850 Timings::$connection->startTiming();
1851 $this->network->tick();
1852 Timings::$connection->stopTiming();
1854 if(($this->tickCounter % self::TARGET_TICKS_PER_SECOND) === 0){
1855 if($this->doTitleTick){
1858 $this->currentTPS = self::TARGET_TICKS_PER_SECOND;
1859 $this->currentUse = 0;
1861 $queryRegenerateEvent =
new QueryRegenerateEvent(
new QueryInfo($this));
1862 $queryRegenerateEvent->call();
1863 $this->queryInfo = $queryRegenerateEvent->getQueryInfo();
1865 $this->network->updateName();
1866 $this->network->getBandwidthTracker()->rotateAverageHistory();
1869 if($this->sendUsageTicker > 0 && --$this->sendUsageTicker === 0){
1870 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1871 $this->sendUsage(SendUsageTask::TYPE_STATUS);
1874 if(($this->tickCounter % self::TICKS_PER_WORLD_CACHE_CLEAR) === 0){
1875 foreach($this->worldManager->getWorlds() as $world){
1876 $world->clearCache();
1880 if(($this->tickCounter % self::TICKS_PER_TPS_OVERLOAD_WARNING) === 0 && $this->getTicksPerSecondAverage() < self::TPS_OVERLOAD_WARNING_THRESHOLD){
1881 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_tickOverload()));
1884 $this->memoryManager->check();
1886 if($this->console !==
null){
1887 Timings::$serverCommand->startTiming();
1888 while(($line = $this->console->readLine()) !==
null){
1889 $this->consoleSender ??=
new ConsoleCommandSender($this, $this->language);
1890 $this->dispatchCommand($this->consoleSender, $line);
1892 Timings::$serverCommand->stopTiming();
1895 Timings::$serverTick->stopTiming();
1897 $now = microtime(
true);
1898 $totalTickTimeSeconds = $now - $tickTime + ($this->tickSleeper->getNotificationProcessingTime() / 1_000_000_000);
1899 $this->currentTPS = min(self::TARGET_TICKS_PER_SECOND, 1 / max(0.001, $totalTickTimeSeconds));
1900 $this->currentUse = min(1, $totalTickTimeSeconds / self::TARGET_SECONDS_PER_TICK);
1902 TimingsHandler::tick($this->currentTPS <= $this->profilingTickRate);
1904 $idx = $this->tickCounter % self::TARGET_TICKS_PER_SECOND;
1905 $this->tickAverage[$idx] = $this->currentTPS;
1906 $this->useAverage[$idx] = $this->currentUse;
1907 $this->tickSleeper->resetNotificationProcessingTime();
1909 if(($this->nextTick - $tickTime) < -1){
1910 $this->nextTick = $tickTime;
1912 $this->nextTick += self::TARGET_SECONDS_PER_TICK;