| 1 | package net.minecraft.server;
|
| 2 |
|
| 3 | import com.google.common.base.Splitter;
|
| 4 | import com.google.common.collect.ImmutableList;
|
| 5 | import com.google.common.collect.Lists;
|
| 6 | import com.google.common.collect.Maps;
|
| 7 | import com.google.common.collect.Sets;
|
| 8 | import com.mojang.authlib.GameProfile;
|
| 9 | import com.mojang.datafixers.DataFixer;
|
| 10 | import com.mojang.jtracy.DiscontinuousFrame;
|
| 11 | import com.mojang.jtracy.TracyClient;
|
| 12 | import com.mojang.logging.LogUtils;
|
| 13 | import it.unimi.dsi.fastutil.objects.ObjectArrayList;
|
| 14 | import it.unimi.dsi.fastutil.objects.ObjectArraySet;
|
| 15 | import java.io.File;
|
| 16 | import java.io.IOException;
|
| 17 | import java.io.Writer;
|
| 18 | import java.lang.management.ThreadInfo;
|
| 19 | import java.net.Proxy;
|
| 20 | import java.nio.file.FileStore;
|
| 21 | import java.nio.file.Files;
|
| 22 | import java.nio.file.Path;
|
| 23 | import java.security.KeyPair;
|
| 24 | import java.util.Arrays;
|
| 25 | import java.util.Collection;
|
| 26 | import java.util.Collections;
|
| 27 | import java.util.Comparator;
|
| 28 | import java.util.List;
|
| 29 | import java.util.Locale;
|
| 30 | import java.util.Map;
|
| 31 | import java.util.Objects;
|
| 32 | import java.util.Optional;
|
| 33 | import java.util.Set;
|
| 34 | import java.util.UUID;
|
| 35 | import java.util.Map.Entry;
|
| 36 | import java.util.concurrent.CompletableFuture;
|
| 37 | import java.util.concurrent.Executor;
|
| 38 | import java.util.concurrent.RejectedExecutionException;
|
| 39 | import java.util.concurrent.atomic.AtomicReference;
|
| 40 | import java.util.concurrent.locks.LockSupport;
|
| 41 | import java.util.function.BooleanSupplier;
|
| 42 | import java.util.function.Consumer;
|
| 43 | import java.util.function.Function;
|
| 44 | import java.util.function.Supplier;
|
| 45 | import java.util.stream.Collectors;
|
| 46 | import net.fabricmc.fabric.api.attachment.v1.GlobalAttachmentsProvider;
|
| 47 | import net.fabricmc.fabric.api.resource.v1.DataResourceStore;
|
| 48 | import net.minecraft.CrashReport;
|
| 49 | import net.minecraft.CrashReportCategory;
|
| 50 | import net.minecraft.ReportType;
|
| 51 | import net.minecraft.ReportedException;
|
| 52 | import net.minecraft.SharedConstants;
|
| 53 | import net.minecraft.SystemReport;
|
| 54 | import net.minecraft.commands.CommandSource;
|
| 55 | import net.minecraft.commands.CommandSourceStack;
|
| 56 | import net.minecraft.commands.Commands;
|
| 57 | import net.minecraft.core.BlockPos;
|
| 58 | import net.minecraft.core.GlobalPos;
|
| 59 | import net.minecraft.core.HolderGetter;
|
| 60 | import net.minecraft.core.LayeredRegistryAccess;
|
| 61 | import net.minecraft.core.Registry;
|
| 62 | import net.minecraft.core.RegistryAccess;
|
| 63 | import net.minecraft.core.registries.Registries;
|
| 64 | import net.minecraft.data.worldgen.features.MiscOverworldFeatures;
|
| 65 | import net.minecraft.gametest.framework.GameTestTicker;
|
| 66 | import net.minecraft.nbt.Tag;
|
| 67 | import net.minecraft.network.PacketProcessor;
|
| 68 | import net.minecraft.network.chat.ChatDecorator;
|
| 69 | import net.minecraft.network.chat.ChatType;
|
| 70 | import net.minecraft.network.chat.Component;
|
| 71 | import net.minecraft.network.protocol.PacketType;
|
| 72 | import net.minecraft.network.protocol.game.ClientboundChangeDifficultyPacket;
|
| 73 | import net.minecraft.network.protocol.game.ClientboundEntityEventPacket;
|
| 74 | import net.minecraft.network.protocol.game.ClientboundGameEventPacket;
|
| 75 | import net.minecraft.network.protocol.game.ClientboundSetDefaultSpawnPositionPacket;
|
| 76 | import net.minecraft.network.protocol.game.ClientboundSetTimePacket;
|
| 77 | import net.minecraft.network.protocol.status.ServerStatus;
|
| 78 | import net.minecraft.resources.Identifier;
|
| 79 | import net.minecraft.resources.ResourceKey;
|
| 80 | import net.minecraft.server.bossevents.CustomBossEvents;
|
| 81 | import net.minecraft.server.level.ChunkLoadCounter;
|
| 82 | import net.minecraft.server.level.ChunkMap;
|
| 83 | import net.minecraft.server.level.DemoMode;
|
| 84 | import net.minecraft.server.level.PlayerSpawnFinder;
|
| 85 | import net.minecraft.server.level.ServerChunkCache;
|
| 86 | import net.minecraft.server.level.ServerLevel;
|
| 87 | import net.minecraft.server.level.ServerPlayer;
|
| 88 | import net.minecraft.server.level.ServerPlayerGameMode;
|
| 89 | import net.minecraft.server.level.progress.ChunkLoadStatusView;
|
| 90 | import net.minecraft.server.level.progress.LevelLoadListener;
|
| 91 | import net.minecraft.server.network.ServerConnectionListener;
|
| 92 | import net.minecraft.server.network.TextFilter;
|
| 93 | import net.minecraft.server.notifications.NotificationManager;
|
| 94 | import net.minecraft.server.notifications.ServerActivityMonitor;
|
| 95 | import net.minecraft.server.packs.PackType;
|
| 96 | import net.minecraft.server.packs.repository.Pack;
|
| 97 | import net.minecraft.server.packs.repository.PackRepository;
|
| 98 | import net.minecraft.server.packs.repository.PackSource;
|
| 99 | import net.minecraft.server.packs.resources.CloseableResourceManager;
|
| 100 | import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
| 101 | import net.minecraft.server.packs.resources.ResourceManager;
|
| 102 | import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
| 103 | import net.minecraft.server.permissions.PermissionSet;
|
| 104 | import net.minecraft.server.players.NameAndId;
|
| 105 | import net.minecraft.server.players.PlayerList;
|
| 106 | import net.minecraft.server.players.ServerOpListEntry;
|
| 107 | import net.minecraft.server.players.UserWhiteList;
|
| 108 | import net.minecraft.server.waypoints.ServerWaypointManager;
|
| 109 | import net.minecraft.tags.TagLoader;
|
| 110 | import net.minecraft.util.Crypt;
|
| 111 | import net.minecraft.util.CryptException;
|
| 112 | import net.minecraft.util.FileUtil;
|
| 113 | import net.minecraft.util.ModCheck;
|
| 114 | import net.minecraft.util.Mth;
|
| 115 | import net.minecraft.util.NativeModuleLister;
|
| 116 | import net.minecraft.util.PngInfo;
|
| 117 | import net.minecraft.util.RandomSource;
|
| 118 | import net.minecraft.util.TimeUtil;
|
| 119 | import net.minecraft.util.Util;
|
| 120 | import net.minecraft.util.debug.ServerDebugSubscribers;
|
| 121 | import net.minecraft.util.debugchart.SampleLogger;
|
| 122 | import net.minecraft.util.debugchart.TpsDebugDimensions;
|
| 123 | import net.minecraft.util.profiling.EmptyProfileResults;
|
| 124 | import net.minecraft.util.profiling.ProfileResults;
|
| 125 | import net.minecraft.util.profiling.Profiler;
|
| 126 | import net.minecraft.util.profiling.ProfilerFiller;
|
| 127 | import net.minecraft.util.profiling.ResultField;
|
| 128 | import net.minecraft.util.profiling.SingleTickProfiler;
|
| 129 | import net.minecraft.util.profiling.jfr.Environment;
|
| 130 | import net.minecraft.util.profiling.jfr.JvmProfiler;
|
| 131 | import net.minecraft.util.profiling.jfr.callback.ProfiledDuration;
|
| 132 | import net.minecraft.util.profiling.metrics.profiling.ActiveMetricsRecorder;
|
| 133 | import net.minecraft.util.profiling.metrics.profiling.InactiveMetricsRecorder;
|
| 134 | import net.minecraft.util.profiling.metrics.profiling.MetricsRecorder;
|
| 135 | import net.minecraft.util.profiling.metrics.profiling.ServerMetricsSamplersProvider;
|
| 136 | import net.minecraft.util.profiling.metrics.storage.MetricsPersister;
|
| 137 | import net.minecraft.util.thread.ReentrantBlockableEventLoop;
|
| 138 | import net.minecraft.world.Difficulty;
|
| 139 | import net.minecraft.world.RandomSequences;
|
| 140 | import net.minecraft.world.Stopwatches;
|
| 141 | import net.minecraft.world.clock.ClockTimeMarkers;
|
| 142 | import net.minecraft.world.clock.ServerClockManager;
|
| 143 | import net.minecraft.world.clock.WorldClocks;
|
| 144 | import net.minecraft.world.entity.ai.village.VillageSiege;
|
| 145 | import net.minecraft.world.entity.npc.CatSpawner;
|
| 146 | import net.minecraft.world.entity.npc.wanderingtrader.WanderingTraderSpawner;
|
| 147 | import net.minecraft.world.entity.player.Player;
|
| 148 | import net.minecraft.world.flag.FeatureFlagSet;
|
| 149 | import net.minecraft.world.flag.FeatureFlags;
|
| 150 | import net.minecraft.world.item.crafting.RecipeManager;
|
| 151 | import net.minecraft.world.level.ChunkPos;
|
| 152 | import net.minecraft.world.level.CustomSpawner;
|
| 153 | import net.minecraft.world.level.DataPackConfig;
|
| 154 | import net.minecraft.world.level.GameType;
|
| 155 | import net.minecraft.world.level.Level;
|
| 156 | import net.minecraft.world.level.LevelSettings;
|
| 157 | import net.minecraft.world.level.TicketStorage;
|
| 158 | import net.minecraft.world.level.WorldDataConfiguration;
|
| 159 | import net.minecraft.world.level.biome.BiomeManager;
|
| 160 | import net.minecraft.world.level.block.Block;
|
| 161 | import net.minecraft.world.level.chunk.status.ChunkStatus;
|
| 162 | import net.minecraft.world.level.chunk.storage.ChunkIOErrorReporter;
|
| 163 | import net.minecraft.world.level.chunk.storage.RegionStorageInfo;
|
| 164 | import net.minecraft.world.level.dimension.LevelStem;
|
| 165 | import net.minecraft.world.level.gamerules.GameRule;
|
| 166 | import net.minecraft.world.level.gamerules.GameRuleMap;
|
| 167 | import net.minecraft.world.level.gamerules.GameRuleTypeVisitor;
|
| 168 | import net.minecraft.world.level.gamerules.GameRules;
|
| 169 | import net.minecraft.world.level.levelgen.Heightmap;
|
| 170 | import net.minecraft.world.level.levelgen.PatrolSpawner;
|
| 171 | import net.minecraft.world.level.levelgen.PhantomSpawner;
|
| 172 | import net.minecraft.world.level.levelgen.WorldGenSettings;
|
| 173 | import net.minecraft.world.level.levelgen.WorldOptions;
|
| 174 | import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
|
| 175 | import net.minecraft.world.level.saveddata.WeatherData;
|
| 176 | import net.minecraft.world.level.storage.CommandStorage;
|
| 177 | import net.minecraft.world.level.storage.DerivedLevelData;
|
| 178 | import net.minecraft.world.level.storage.LevelData;
|
| 179 | import net.minecraft.world.level.storage.LevelResource;
|
| 180 | import net.minecraft.world.level.storage.LevelStorageSource;
|
| 181 | import net.minecraft.world.level.storage.PlayerDataStorage;
|
| 182 | import net.minecraft.world.level.storage.SavedDataStorage;
|
| 183 | import net.minecraft.world.level.storage.ServerLevelData;
|
| 184 | import net.minecraft.world.level.storage.WorldData;
|
| 185 | import net.minecraft.world.level.timers.TimerQueue;
|
| 186 | import net.minecraft.world.phys.Vec2;
|
| 187 | import net.minecraft.world.phys.Vec3;
|
| 188 | import net.minecraft.world.scores.ScoreboardSaveData;
|
| 189 | import org.jspecify.annotations.Nullable;
|
| 190 | import org.slf4j.Logger;
|
| 191 |
|
| 192 | public abstract class MinecraftServer
|
| 193 | extends ReentrantBlockableEventLoop<TickTask>
|
| 194 | implements CommandSource,
|
| 195 | ServerInfo,
|
| 196 | ChunkIOErrorReporter,
|
| 197 | GlobalAttachmentsProvider,
|
| 198 | DataResourceStore {
|
| 199 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 200 | public static final String VANILLA_BRAND = "vanilla";
|
| 201 | private static final float AVERAGE_TICK_TIME_SMOOTHING = 0.8F;
|
| 202 | private static final int TICK_STATS_SPAN = 100;
|
| 203 | private static final long OVERLOADED_THRESHOLD_NANOS = 20L * TimeUtil.NANOSECONDS_PER_SECOND / 20L;
|
| 204 | private static final int OVERLOADED_TICKS_THRESHOLD = 20;
|
| 205 | private static final long OVERLOADED_WARNING_INTERVAL_NANOS = 10L * TimeUtil.NANOSECONDS_PER_SECOND;
|
| 206 | private static final int OVERLOADED_TICKS_WARNING_INTERVAL = 100;
|
| 207 | private static final long STATUS_EXPIRE_TIME_NANOS = 5L * TimeUtil.NANOSECONDS_PER_SECOND;
|
| 208 | private static final long PREPARE_LEVELS_DEFAULT_DELAY_NANOS = 10L * TimeUtil.NANOSECONDS_PER_MILLISECOND;
|
| 209 | private static final int MAX_STATUS_PLAYER_SAMPLE = 12;
|
| 210 | public static final int SPAWN_POSITION_SEARCH_RADIUS = 5;
|
| 211 | private static final int SERVER_ACTIVITY_MONITOR_SECONDS_BETWEEN_NOTIFICATIONS = 30;
|
| 212 | private static final int AUTOSAVE_INTERVAL = 6000;
|
| 213 | private static final int MIMINUM_AUTOSAVE_TICKS = 100;
|
| 214 | private static final int MAX_TICK_LATENCY = 3;
|
| 215 | public static final int ABSOLUTE_MAX_WORLD_SIZE = 29999984;
|
| 216 | public static final LevelSettings DEMO_SETTINGS = new LevelSettings(
|
| 217 | "Demo World", GameType.SURVIVAL, LevelSettings.DifficultySettings.DEFAULT, false, WorldDataConfiguration.DEFAULT
|
| 218 | );
|
| 219 | public static final Supplier<GameRules> DEFAULT_GAME_RULES = () -> new GameRules(WorldDataConfiguration.DEFAULT.enabledFeatures());
|
| 220 | public static final NameAndId ANONYMOUS_PLAYER_PROFILE = new NameAndId(Util.NIL_UUID, "Anonymous Player");
|
| 221 | public static final String SERVER_THREAD_NAME = "Server thread";
|
| 222 | protected final LevelStorageSource.LevelStorageAccess storageSource;
|
| 223 | protected final PlayerDataStorage playerDataStorage;
|
| 224 | private final SavedDataStorage savedDataStorage;
|
| 225 | private final List<Runnable> tickables = Lists.newArrayList();
|
| 226 | private final GameRules gameRules;
|
| 227 | private MetricsRecorder metricsRecorder = InactiveMetricsRecorder.INSTANCE;
|
| 228 | private Consumer<ProfileResults> onMetricsRecordingStopped = results -> this.stopRecordingMetrics();
|
| 229 | private Consumer<Path> onMetricsRecordingFinished = ignored -> {};
|
| 230 | private boolean willStartRecordingMetrics;
|
| 231 | private MinecraftServer.@Nullable TimeProfiler debugCommandProfiler;
|
| 232 | private boolean debugCommandProfilerDelayStart;
|
| 233 | private final ServerConnectionListener connection;
|
| 234 | private final LevelLoadListener levelLoadListener;
|
| 235 | private @Nullable ServerStatus status;
|
| 236 | private ServerStatus.@Nullable Favicon statusIcon;
|
| 237 | private final RandomSource random = RandomSource.create();
|
| 238 | private final DataFixer fixerUpper;
|
| 239 | private String localIp;
|
| 240 | private int port = -1;
|
| 241 | private final LayeredRegistryAccess<RegistryLayer> registries;
|
| 242 | private final Map<ResourceKey<Level>, ServerLevel> levels = Maps.newLinkedHashMap();
|
| 243 | private PlayerList playerList;
|
| 244 | private volatile boolean running = true;
|
| 245 | private boolean stopped;
|
| 246 | private int tickCount;
|
| 247 | private int ticksUntilAutosave = 6000;
|
| 248 | protected final Proxy proxy;
|
| 249 | private boolean onlineMode;
|
| 250 | private boolean preventProxyConnections;
|
| 251 | private @Nullable String motd;
|
| 252 | private int playerIdleTimeout;
|
| 253 | private final long[] tickTimesNanos = new long[100];
|
| 254 | private long aggregatedTickTimesNanos = 0L;
|
| 255 | private @Nullable KeyPair keyPair;
|
| 256 | private @Nullable GameProfile singleplayerProfile;
|
| 257 | private boolean isDemo;
|
| 258 | private volatile boolean isReady;
|
| 259 | private long lastOverloadWarningNanos;
|
| 260 | protected final Services services;
|
| 261 | private final NotificationManager notificationManager;
|
| 262 | private final ServerActivityMonitor serverActivityMonitor;
|
| 263 | private long lastServerStatus;
|
| 264 | private final Thread serverThread;
|
| 265 | private long lastTickNanos = Util.getNanos();
|
| 266 | private long taskExecutionStartNanos = Util.getNanos();
|
| 267 | private long idleTimeNanos;
|
| 268 | private long nextTickTimeNanos = Util.getNanos();
|
| 269 | private boolean waitingForNextTick = false;
|
| 270 | private long delayedTasksMaxNextTickTimeNanos;
|
| 271 | private boolean mayHaveDelayedTasks;
|
| 272 | private final PackRepository packRepository;
|
| 273 | private final WorldGenSettings worldGenSettings;
|
| 274 | private final ServerScoreboard scoreboard = new ServerScoreboard(this);
|
| 275 | private @Nullable Stopwatches stopwatches;
|
| 276 | private @Nullable CommandStorage commandStorage;
|
| 277 | private final CustomBossEvents customBossEvents;
|
| 278 | private final RandomSequences randomSequences;
|
| 279 | private final WeatherData weatherData;
|
| 280 | private final ServerFunctionManager functionManager;
|
| 281 | private boolean enforceWhitelist;
|
| 282 | private boolean usingWhitelist;
|
| 283 | private float smoothedTickTimeMillis;
|
| 284 | private final Executor executor;
|
| 285 | private @Nullable String serverId;
|
| 286 | private MinecraftServer.ReloadableResources resources;
|
| 287 | private final StructureTemplateManager structureTemplateManager;
|
| 288 | private final ServerTickRateManager tickRateManager;
|
| 289 | private final ServerDebugSubscribers debugSubscribers = new ServerDebugSubscribers(this);
|
| 290 | protected final WorldData worldData;
|
| 291 | private LevelData.RespawnData effectiveRespawnData = LevelData.RespawnData.DEFAULT;
|
| 292 | private int emptyTicks;
|
| 293 | private volatile boolean isSaving;
|
| 294 | private final SuppressedExceptionCollector suppressedExceptions = new SuppressedExceptionCollector();
|
| 295 | private final DiscontinuousFrame tickFrame;
|
| 296 | private final PacketProcessor packetProcessor;
|
| 297 | private final TimerQueue<MinecraftServer> scheduledEvents;
|
| 298 | private final ServerClockManager clockManager;
|
| 299 |
|
| 300 | public static <S extends MinecraftServer> S spin(final Function<Thread, S> factory) {
|
| 301 | AtomicReference<S> serverReference = new AtomicReference<>();
|
| 302 | Thread thread = new Thread(() -> serverReference.get().runServer(), "Server thread");
|
| 303 | thread.setUncaughtExceptionHandler((t, e) -> LOGGER.error("Uncaught exception in server thread", e));
|
| 304 | if (Runtime.getRuntime().availableProcessors() > 4) {
|
| 305 | thread.setPriority(8);
|
| 306 | }
|
| 307 |
|
| 308 | S server = (S)factory.apply(thread);
|
| 309 | serverReference.set(server);
|
| 310 | thread.start();
|
| 311 | return server;
|
| 312 | }
|
| 313 |
|
| 314 | public MinecraftServer(
|
| 315 | final Thread serverThread,
|
| 316 | final LevelStorageSource.LevelStorageAccess storageSource,
|
| 317 | final PackRepository packRepository,
|
| 318 | final WorldStem worldStem,
|
| 319 | final Optional<GameRules> gameRules,
|
| 320 | final Proxy proxy,
|
| 321 | final DataFixer fixerUpper,
|
| 322 | final Services services,
|
| 323 | final LevelLoadListener levelLoadListener,
|
| 324 | final boolean propagatesCrashes,
|
| 325 | final NotificationManager notificationManager
|
| 326 | ) {
|
| 327 | super("Server", propagatesCrashes);
|
| 328 | this.registries = worldStem.registries();
|
| 329 | if (!this.registries.compositeAccess().lookupOrThrow(Registries.LEVEL_STEM).containsKey(LevelStem.OVERWORLD)) {
|
| 330 | throw new IllegalStateException("Missing Overworld dimension data");
|
| 331 | }
|
| 332 |
|
| 333 | this.savedDataStorage = new SavedDataStorage(storageSource.getLevelPath(LevelResource.DATA), fixerUpper, this.registries.compositeAccess());
|
| 334 | this.worldData = worldStem.worldDataAndGenSettings().data();
|
| 335 | this.worldGenSettings = worldStem.worldDataAndGenSettings().genSettings();
|
| 336 | this.savedDataStorage.set(WorldGenSettings.TYPE, this.worldGenSettings);
|
| 337 | this.proxy = proxy;
|
| 338 | this.packRepository = packRepository;
|
| 339 | this.resources = new MinecraftServer.ReloadableResources(worldStem.resourceManager(), worldStem.dataPackResources());
|
| 340 | this.services = services;
|
| 341 | this.connection = new ServerConnectionListener(this);
|
| 342 | this.tickRateManager = new ServerTickRateManager(this);
|
| 343 | this.levelLoadListener = levelLoadListener;
|
| 344 | this.storageSource = storageSource;
|
| 345 | this.playerDataStorage = storageSource.createPlayerStorage();
|
| 346 | this.randomSequences = this.savedDataStorage.computeIfAbsent(RandomSequences.TYPE);
|
| 347 | this.weatherData = this.getDataStorage().computeIfAbsent(WeatherData.TYPE);
|
| 348 | this.gameRules = new GameRules(this.worldData.enabledFeatures(), this.savedDataStorage.computeIfAbsent(GameRuleMap.TYPE));
|
| 349 | gameRules.ifPresent(g -> this.gameRules.setAll(g, null));
|
| 350 | this.fixerUpper = fixerUpper;
|
| 351 | this.functionManager = new ServerFunctionManager(this, this.resources.managers.getFunctionLibrary());
|
| 352 | HolderGetter<Block> blockLookup = this.registries.compositeAccess().lookupOrThrow(Registries.BLOCK).filterFeatures(this.worldData.enabledFeatures());
|
| 353 | this.structureTemplateManager = new StructureTemplateManager(worldStem.resourceManager(), storageSource, fixerUpper, blockLookup);
|
| 354 | this.serverThread = serverThread;
|
| 355 | this.executor = Util.backgroundExecutor();
|
| 356 | this.resources.managers.getRecipeManager().finalizeRecipeLoading(this.worldData.enabledFeatures());
|
| 357 | this.tickFrame = TracyClient.createDiscontinuousFrame("Server Tick");
|
| 358 | this.notificationManager = notificationManager;
|
| 359 | this.serverActivityMonitor = new ServerActivityMonitor(notificationManager, 30);
|
| 360 | this.packetProcessor = new PacketProcessor(serverThread);
|
| 361 | this.clockManager = this.getDataStorage().computeIfAbsent(ServerClockManager.TYPE);
|
| 362 | this.clockManager.init(this);
|
| 363 | this.customBossEvents = this.savedDataStorage.computeIfAbsent(CustomBossEvents.TYPE);
|
| 364 | this.scheduledEvents = this.savedDataStorage.computeIfAbsent(TimerQueue.TYPE);
|
| 365 | }
|
| 366 |
|
| 367 | protected abstract boolean initServer() throws IOException;
|
| 368 |
|
| 369 | public ChunkLoadStatusView createChunkLoadStatusView(final int radius) {
|
| 370 | return new ChunkLoadStatusView() {
|
| 371 | private @Nullable ChunkMap chunkMap;
|
| 372 | private int centerChunkX;
|
| 373 | private int centerChunkZ;
|
| 374 |
|
| 375 | @Override
|
| 376 | public void moveTo(final ResourceKey<Level> dimension, final ChunkPos centerChunk) {
|
| 377 | ServerLevel level = MinecraftServer.this.getLevel(dimension);
|
| 378 | this.chunkMap = level != null ? level.getChunkSource().chunkMap : null;
|
| 379 | this.centerChunkX = centerChunk.x();
|
| 380 | this.centerChunkZ = centerChunk.z();
|
| 381 | }
|
| 382 |
|
| 383 | @Override
|
| 384 | public @Nullable ChunkStatus get(final int x, final int z) {
|
| 385 | return this.chunkMap == null ? null : this.chunkMap.getLatestStatus(ChunkPos.pack(x + this.centerChunkX - radius, z + this.centerChunkZ - radius));
|
| 386 | }
|
| 387 |
|
| 388 | @Override
|
| 389 | public int radius() {
|
| 390 | return radius;
|
| 391 | }
|
| 392 | };
|
| 393 | }
|
| 394 |
|
| 395 | protected void loadLevel() {
|
| 396 | boolean startedWorldLoadProfiling = !JvmProfiler.INSTANCE.isRunning()
|
| 397 | && SharedConstants.DEBUG_JFR_PROFILING_ENABLE_LEVEL_LOADING
|
| 398 | && JvmProfiler.INSTANCE.start(Environment.from(this));
|
| 399 | ProfiledDuration profiledDuration = JvmProfiler.INSTANCE.onWorldLoadedStarted();
|
| 400 | this.worldData.setModdedInfo(this.getServerModName(), this.getModdedStatus().shouldReportAsModified());
|
| 401 | this.createLevels();
|
| 402 | this.forceDifficulty();
|
| 403 | this.prepareLevels();
|
| 404 | if (profiledDuration != null) {
|
| 405 | profiledDuration.finish(true);
|
| 406 | }
|
| 407 |
|
| 408 | if (startedWorldLoadProfiling) {
|
| 409 | try {
|
| 410 | JvmProfiler.INSTANCE.stop();
|
| 411 | } catch (Throwable t) {
|
| 412 | LOGGER.warn("Failed to stop JFR profiling", t);
|
| 413 | }
|
| 414 | }
|
| 415 | }
|
| 416 |
|
| 417 | protected void forceDifficulty() {
|
| 418 | }
|
| 419 |
|
| 420 | protected void createLevels() {
|
| 421 | ServerLevelData levelData = this.worldData.overworldData();
|
| 422 | boolean isDebug = this.worldData.isDebugWorld();
|
| 423 | Registry<LevelStem> dimensions = this.registries.compositeAccess().lookupOrThrow(Registries.LEVEL_STEM);
|
| 424 | WorldOptions worldOptions = this.worldGenSettings.options();
|
| 425 | long seed = worldOptions.seed();
|
| 426 | long biomeZoomSeed = BiomeManager.obfuscateSeed(seed);
|
| 427 | List<CustomSpawner> overworldCustomSpawners = ImmutableList.of(
|
| 428 | new PhantomSpawner(), new PatrolSpawner(), new CatSpawner(), new VillageSiege(), new WanderingTraderSpawner(this.savedDataStorage)
|
| 429 | );
|
| 430 | LevelStem overworldData = dimensions.getValue(LevelStem.OVERWORLD);
|
| 431 | ServerLevel overworld = new ServerLevel(
|
| 432 | this, this.executor, this.storageSource, levelData, Level.OVERWORLD, overworldData, isDebug, biomeZoomSeed, overworldCustomSpawners, true
|
| 433 | );
|
| 434 | this.levels.put(Level.OVERWORLD, overworld);
|
| 435 | this.scoreboard.load(this.savedDataStorage.computeIfAbsent(ScoreboardSaveData.TYPE).getData());
|
| 436 | this.commandStorage = new CommandStorage(this.savedDataStorage);
|
| 437 | this.stopwatches = this.savedDataStorage.computeIfAbsent(Stopwatches.TYPE);
|
| 438 | if (!levelData.isInitialized()) {
|
| 439 | try {
|
| 440 | setInitialSpawn(overworld, levelData, worldOptions.generateBonusChest(), isDebug, this.levelLoadListener);
|
| 441 | levelData.setInitialized(true);
|
| 442 | if (isDebug) {
|
| 443 | this.setupDebugLevel(this.worldData);
|
| 444 | }
|
| 445 | } catch (Throwable t) {
|
| 446 | CrashReport report = CrashReport.forThrowable(t, "Exception initializing level");
|
| 447 |
|
| 448 | try {
|
| 449 | overworld.fillReportDetails(report);
|
| 450 | } catch (Throwable var19) {
|
| 451 | }
|
| 452 |
|
| 453 | throw new ReportedException(report);
|
| 454 | }
|
| 455 |
|
| 456 | levelData.setInitialized(true);
|
| 457 | }
|
| 458 |
|
| 459 | GlobalPos focusPos = this.selectLevelLoadFocusPos();
|
| 460 | this.levelLoadListener.updateFocus(focusPos.dimension(), ChunkPos.containing(focusPos.pos()));
|
| 461 |
|
| 462 | for (Entry<ResourceKey<LevelStem>, LevelStem> entry : dimensions.entrySet()) {
|
| 463 | ResourceKey<LevelStem> name = entry.getKey();
|
| 464 | ServerLevel level;
|
| 465 | if (name != LevelStem.OVERWORLD) {
|
| 466 | ResourceKey<Level> dimension = ResourceKey.create(Registries.DIMENSION, name.identifier());
|
| 467 | DerivedLevelData derivedLevelData = new DerivedLevelData(this.worldData, levelData);
|
| 468 | level = new ServerLevel(
|
| 469 | this, this.executor, this.storageSource, derivedLevelData, dimension, entry.getValue(), isDebug, biomeZoomSeed, ImmutableList.of(), false
|
| 470 | );
|
| 471 | this.levels.put(dimension, level);
|
| 472 | } else {
|
| 473 | level = overworld;
|
| 474 | }
|
| 475 |
|
| 476 | level.getWorldBorder().setAbsoluteMaxSize(this.getAbsoluteMaxWorldSize());
|
| 477 | this.getPlayerList().addWorldborderListener(level);
|
| 478 | }
|
| 479 | }
|
| 480 |
|
| 481 | private static void setInitialSpawn(
|
| 482 | final ServerLevel level, final ServerLevelData levelData, final boolean spawnBonusChest, final boolean isDebug, final LevelLoadListener levelLoadListener
|
| 483 | ) {
|
| 484 | if (SharedConstants.DEBUG_ONLY_GENERATE_HALF_THE_WORLD && SharedConstants.DEBUG_WORLD_RECREATE) {
|
| 485 | levelData.setSpawn(LevelData.RespawnData.of(level.dimension(), new BlockPos(0, 64, -100), 0.0F, 0.0F));
|
| 486 | } else if (isDebug) {
|
| 487 | levelData.setSpawn(LevelData.RespawnData.of(level.dimension(), BlockPos.ZERO.above(80), 0.0F, 0.0F));
|
| 488 | } else {
|
| 489 | ServerChunkCache chunkSource = level.getChunkSource();
|
| 490 | ChunkPos spawnChunk = chunkSource.getGenerator().getOrigin(chunkSource.randomState());
|
| 491 | levelLoadListener.start(LevelLoadListener.Stage.PREPARE_GLOBAL_SPAWN, 0);
|
| 492 | levelLoadListener.updateFocus(level.dimension(), spawnChunk);
|
| 493 | int height = chunkSource.getGenerator().getSpawnHeight(level);
|
| 494 | if (height < level.getMinY()) {
|
| 495 | BlockPos worldPosition = spawnChunk.getWorldPosition();
|
| 496 | height = level.getHeight(Heightmap.Types.WORLD_SURFACE, worldPosition.getX() + 8, worldPosition.getZ() + 8);
|
| 497 | }
|
| 498 |
|
| 499 | levelData.setSpawn(LevelData.RespawnData.of(level.dimension(), spawnChunk.getWorldPosition().offset(8, height, 8), 0.0F, 0.0F));
|
| 500 | int xChunkOffset = 0;
|
| 501 | int zChunkOffset = 0;
|
| 502 | int dXChunk = 0;
|
| 503 | int dZChunk = -1;
|
| 504 |
|
| 505 | for (int i = 0; i < Mth.square(11); i++) {
|
| 506 | if (xChunkOffset >= -5 && xChunkOffset <= 5 && zChunkOffset >= -5 && zChunkOffset <= 5) {
|
| 507 | BlockPos testedPos = PlayerSpawnFinder.getSpawnPosInChunk(level, new ChunkPos(spawnChunk.x() + xChunkOffset, spawnChunk.z() + zChunkOffset));
|
| 508 | if (testedPos != null) {
|
| 509 | levelData.setSpawn(LevelData.RespawnData.of(level.dimension(), testedPos, 0.0F, 0.0F));
|
| 510 | break;
|
| 511 | }
|
| 512 | }
|
| 513 |
|
| 514 | if (xChunkOffset == zChunkOffset || xChunkOffset < 0 && xChunkOffset == -zChunkOffset || xChunkOffset > 0 && xChunkOffset == 1 - zChunkOffset) {
|
| 515 | int olddx = dXChunk;
|
| 516 | dXChunk = -dZChunk;
|
| 517 | dZChunk = olddx;
|
| 518 | }
|
| 519 |
|
| 520 | xChunkOffset += dXChunk;
|
| 521 | zChunkOffset += dZChunk;
|
| 522 | }
|
| 523 |
|
| 524 | if (spawnBonusChest) {
|
| 525 | level.registryAccess()
|
| 526 | .lookup(Registries.FEATURE)
|
| 527 | .flatMap(registry -> registry.get(MiscOverworldFeatures.BONUS_CHEST))
|
| 528 | .ifPresent(feature -> feature.value().place(level, chunkSource.getGenerator(), level.getRandom(), levelData.getRespawnData().pos()));
|
| 529 | }
|
| 530 |
|
| 531 | levelLoadListener.finish(LevelLoadListener.Stage.PREPARE_GLOBAL_SPAWN);
|
| 532 | }
|
| 533 | }
|
| 534 |
|
| 535 | private void setupDebugLevel(final WorldData worldData) {
|
| 536 | worldData.setDifficulty(Difficulty.PEACEFUL);
|
| 537 | worldData.setDifficultyLocked(true);
|
| 538 | ServerLevelData levelData = worldData.overworldData();
|
| 539 | this.getGameRules().set(GameRules.ADVANCE_WEATHER, false, this);
|
| 540 | this.clockManager.moveToTimeMarker(this.registryAccess().getOrThrow(WorldClocks.OVERWORLD), ClockTimeMarkers.NOON);
|
| 541 | levelData.setGameType(GameType.SPECTATOR);
|
| 542 | }
|
| 543 |
|
| 544 | private void prepareLevels() {
|
| 545 | ChunkLoadCounter chunkLoadCounter = new ChunkLoadCounter();
|
| 546 |
|
| 547 | for (ServerLevel level : this.levels.values()) {
|
| 548 | chunkLoadCounter.track(level, () -> {
|
| 549 | TicketStorage savedTickets = level.getDataStorage().get(TicketStorage.TYPE);
|
| 550 | if (savedTickets != null) {
|
| 551 | savedTickets.activateAllDeactivatedTickets();
|
| 552 | }
|
| 553 | });
|
| 554 | }
|
| 555 |
|
| 556 | this.levelLoadListener.start(LevelLoadListener.Stage.LOAD_INITIAL_CHUNKS, chunkLoadCounter.totalChunks());
|
| 557 |
|
| 558 | do {
|
| 559 | this.levelLoadListener.update(LevelLoadListener.Stage.LOAD_INITIAL_CHUNKS, chunkLoadCounter.readyChunks(), chunkLoadCounter.totalChunks());
|
| 560 | this.nextTickTimeNanos = Util.getNanos() + PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
|
| 561 | this.waitUntilNextTick();
|
| 562 | } while (chunkLoadCounter.pendingChunks() > 0);
|
| 563 |
|
| 564 | this.levelLoadListener.finish(LevelLoadListener.Stage.LOAD_INITIAL_CHUNKS);
|
| 565 | this.updateMobSpawningFlags();
|
| 566 | this.updateEffectiveRespawnData();
|
| 567 | }
|
| 568 |
|
| 569 | protected GlobalPos selectLevelLoadFocusPos() {
|
| 570 | return this.worldData.overworldData().getRespawnData().globalPos();
|
| 571 | }
|
| 572 |
|
| 573 | public GameType getDefaultGameType() {
|
| 574 | return this.worldData.getGameType();
|
| 575 | }
|
| 576 |
|
| 577 | public boolean isHardcore() {
|
| 578 | return this.worldData.isHardcore();
|
| 579 | }
|
| 580 |
|
| 581 | public abstract LevelBasedPermissionSet operatorUserPermissions();
|
| 582 |
|
| 583 | public abstract PermissionSet getFunctionCompilationPermissions();
|
| 584 |
|
| 585 | public abstract boolean shouldRconBroadcast();
|
| 586 |
|
| 587 | public boolean saveAllChunks(final boolean silent, final boolean flush, final boolean force) {
|
| 588 | this.scoreboard.storeToSaveDataIfDirty(this.getDataStorage().computeIfAbsent(ScoreboardSaveData.TYPE));
|
| 589 | boolean result = false;
|
| 590 |
|
| 591 | for (ServerLevel level : this.getAllLevels()) {
|
| 592 | if (!silent) {
|
| 593 | LOGGER.info("Saving chunks for level '{}'/{}", level, level.dimension().identifier());
|
| 594 | }
|
| 595 |
|
| 596 | level.save(null, flush, SharedConstants.DEBUG_DONT_SAVE_WORLD || level.noSave && !force);
|
| 597 | result = true;
|
| 598 | }
|
| 599 |
|
| 600 | GameProfile singleplayerProfile = this.getSingleplayerProfile();
|
| 601 | this.storageSource.saveDataTag(this.worldData, singleplayerProfile == null ? null : singleplayerProfile.id());
|
| 602 | if (flush) {
|
| 603 | this.savedDataStorage.saveAndJoin();
|
| 604 | } else {
|
| 605 | this.savedDataStorage.scheduleSave();
|
| 606 | }
|
| 607 |
|
| 608 | return result;
|
| 609 | }
|
| 610 |
|
| 611 | public boolean saveEverything(final boolean silent, final boolean flush, final boolean force) {
|
| 612 | try {
|
| 613 | this.isSaving = true;
|
| 614 | this.getPlayerList().saveAll();
|
| 615 | boolean result = this.saveAllChunks(silent, flush, force);
|
| 616 | this.warnOnLowDiskSpace();
|
| 617 | return result;
|
| 618 | } finally {
|
| 619 | this.isSaving = false;
|
| 620 | }
|
| 621 | }
|
| 622 |
|
| 623 | @Override
|
| 624 | public void close() {
|
| 625 | this.stopServer();
|
| 626 | }
|
| 627 |
|
| 628 | protected void stopServer() {
|
| 629 | this.packetProcessor.close();
|
| 630 | if (this.metricsRecorder.isRecording()) {
|
| 631 | this.cancelRecordingMetrics();
|
| 632 | }
|
| 633 |
|
| 634 | LOGGER.info("Stopping server");
|
| 635 | this.getConnection().stop();
|
| 636 | this.isSaving = true;
|
| 637 | if (this.playerList != null) {
|
| 638 | LOGGER.info("Saving players");
|
| 639 | this.playerList.saveAll();
|
| 640 | this.playerList.removeAll();
|
| 641 | }
|
| 642 |
|
| 643 | LOGGER.info("Saving worlds");
|
| 644 |
|
| 645 | for (ServerLevel level : this.getAllLevels()) {
|
| 646 | if (level != null) {
|
| 647 | level.noSave = false;
|
| 648 | }
|
| 649 | }
|
| 650 |
|
| 651 | while (this.levels.values().stream().anyMatch(l -> l.getChunkSource().chunkMap.hasWork())) {
|
| 652 | this.nextTickTimeNanos = Util.getNanos() + TimeUtil.NANOSECONDS_PER_MILLISECOND;
|
| 653 |
|
| 654 | for (ServerLevel level : this.getAllLevels()) {
|
| 655 | level.getChunkSource().deactivateTicketsOnClosing();
|
| 656 | level.getChunkSource().tick(() -> true, false);
|
| 657 | }
|
| 658 |
|
| 659 | this.waitUntilNextTick();
|
| 660 | }
|
| 661 |
|
| 662 | this.saveAllChunks(false, true, false);
|
| 663 |
|
| 664 | for (ServerLevel level : this.getAllLevels()) {
|
| 665 | if (level != null) {
|
| 666 | try {
|
| 667 | level.close();
|
| 668 | } catch (IOException e) {
|
| 669 | LOGGER.error("Exception closing the level", e);
|
| 670 | }
|
| 671 | }
|
| 672 | }
|
| 673 |
|
| 674 | this.isSaving = false;
|
| 675 | this.savedDataStorage.close();
|
| 676 | this.resources.close();
|
| 677 |
|
| 678 | try {
|
| 679 | this.storageSource.close();
|
| 680 | } catch (IOException e) {
|
| 681 | LOGGER.error("Failed to unlock level {}", this.storageSource.getLevelId(), e);
|
| 682 | }
|
| 683 | }
|
| 684 |
|
| 685 | public String getLocalIp() {
|
| 686 | return this.localIp;
|
| 687 | }
|
| 688 |
|
| 689 | public void setLocalIp(final String ip) {
|
| 690 | this.localIp = ip;
|
| 691 | }
|
| 692 |
|
| 693 | public boolean isRunning() {
|
| 694 | return this.running;
|
| 695 | }
|
| 696 |
|
| 697 | public void halt(final boolean wait) {
|
| 698 | this.running = false;
|
| 699 | if (wait) {
|
| 700 | try {
|
| 701 | this.serverThread.join();
|
| 702 | } catch (InterruptedException e) {
|
| 703 | LOGGER.error("Error while shutting down", e);
|
| 704 | }
|
| 705 | }
|
| 706 | }
|
| 707 |
|
| 708 | protected void runServer() {
|
| 709 | try {
|
| 710 | if (!this.initServer()) {
|
| 711 | throw new IllegalStateException("Failed to initialize server");
|
| 712 | }
|
| 713 |
|
| 714 | this.nextTickTimeNanos = Util.getNanos();
|
| 715 | this.statusIcon = this.loadStatusIcon().orElse(null);
|
| 716 | this.status = this.buildServerStatus();
|
| 717 |
|
| 718 | while (this.running) {
|
| 719 | long thisTickNanos;
|
| 720 | if (!this.isPaused() && this.tickRateManager.isSprinting() && this.tickRateManager.checkShouldSprintThisTick()) {
|
| 721 | thisTickNanos = 0L;
|
| 722 | this.nextTickTimeNanos = Util.getNanos();
|
| 723 | this.lastOverloadWarningNanos = this.nextTickTimeNanos;
|
| 724 | } else {
|
| 725 | thisTickNanos = this.tickRateManager.nanosecondsPerTick();
|
| 726 | long behindTimeNanos = Util.getNanos() - this.nextTickTimeNanos;
|
| 727 | if (behindTimeNanos > OVERLOADED_THRESHOLD_NANOS + 20L * thisTickNanos
|
| 728 | && this.nextTickTimeNanos - this.lastOverloadWarningNanos >= OVERLOADED_WARNING_INTERVAL_NANOS + 100L * thisTickNanos) {
|
| 729 | long ticks = behindTimeNanos / thisTickNanos;
|
| 730 | LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", behindTimeNanos / TimeUtil.NANOSECONDS_PER_MILLISECOND, ticks);
|
| 731 | this.nextTickTimeNanos += ticks * thisTickNanos;
|
| 732 | this.lastOverloadWarningNanos = this.nextTickTimeNanos;
|
| 733 | }
|
| 734 | }
|
| 735 |
|
| 736 | boolean sprinting = thisTickNanos == 0L;
|
| 737 | if (this.debugCommandProfilerDelayStart) {
|
| 738 | this.debugCommandProfilerDelayStart = false;
|
| 739 | this.debugCommandProfiler = new MinecraftServer.TimeProfiler(Util.getNanos(), this.tickCount);
|
| 740 | }
|
| 741 |
|
| 742 | this.nextTickTimeNanos += thisTickNanos;
|
| 743 |
|
| 744 | try (Profiler.Scope ignored = Profiler.use(this.createProfiler())) {
|
| 745 | this.processPacketsAndTick(sprinting);
|
| 746 | ProfilerFiller profiler = Profiler.get();
|
| 747 | profiler.push("nextTickWait");
|
| 748 | this.mayHaveDelayedTasks = true;
|
| 749 | this.delayedTasksMaxNextTickTimeNanos = Math.max(Util.getNanos() + thisTickNanos, this.nextTickTimeNanos);
|
| 750 | this.startMeasuringTaskExecutionTime();
|
| 751 | this.waitUntilNextTick();
|
| 752 | this.finishMeasuringTaskExecutionTime();
|
| 753 | if (sprinting) {
|
| 754 | this.tickRateManager.endTickWork();
|
| 755 | }
|
| 756 |
|
| 757 | profiler.pop();
|
| 758 | this.logFullTickTime();
|
| 759 | } finally {
|
| 760 | this.endMetricsRecordingTick();
|
| 761 | }
|
| 762 |
|
| 763 | this.isReady = true;
|
| 764 | JvmProfiler.INSTANCE.onServerTick(this.smoothedTickTimeMillis);
|
| 765 | }
|
| 766 | } catch (Throwable t) {
|
| 767 | LOGGER.error("Encountered an unexpected exception", t);
|
| 768 | CrashReport report = constructOrExtractCrashReport(t);
|
| 769 | this.fillSystemReport(report.getSystemReport());
|
| 770 | Path file = this.getServerDirectory().resolve("crash-reports").resolve("crash-" + Util.getFilenameFormattedDateTime() + "-server.txt");
|
| 771 | if (report.saveToFile(file, ReportType.CRASH)) {
|
| 772 | LOGGER.error("This crash report has been saved to: {}", file.toAbsolutePath());
|
| 773 | } else {
|
| 774 | LOGGER.error("We were unable to save this crash report to disk.");
|
| 775 | }
|
| 776 |
|
| 777 | this.onServerCrash(report);
|
| 778 | } finally {
|
| 779 | try {
|
| 780 | this.stopped = true;
|
| 781 | this.stopServer();
|
| 782 | } catch (Throwable t) {
|
| 783 | LOGGER.error("Exception stopping the server", t);
|
| 784 | } finally {
|
| 785 | this.onServerExit();
|
| 786 | }
|
| 787 | }
|
| 788 | }
|
| 789 |
|
| 790 | private void logFullTickTime() {
|
| 791 | long currentTime = Util.getNanos();
|
| 792 | if (this.isTickTimeLoggingEnabled()) {
|
| 793 | this.getTickTimeLogger().logSample(currentTime - this.lastTickNanos);
|
| 794 | }
|
| 795 |
|
| 796 | this.lastTickNanos = currentTime;
|
| 797 | }
|
| 798 |
|
| 799 | private void startMeasuringTaskExecutionTime() {
|
| 800 | if (this.isTickTimeLoggingEnabled()) {
|
| 801 | this.taskExecutionStartNanos = Util.getNanos();
|
| 802 | this.idleTimeNanos = 0L;
|
| 803 | }
|
| 804 | }
|
| 805 |
|
| 806 | private void finishMeasuringTaskExecutionTime() {
|
| 807 | if (this.isTickTimeLoggingEnabled()) {
|
| 808 | SampleLogger tickTimelogger = this.getTickTimeLogger();
|
| 809 | tickTimelogger.logPartialSample(Util.getNanos() - this.taskExecutionStartNanos - this.idleTimeNanos, TpsDebugDimensions.SCHEDULED_TASKS.ordinal());
|
| 810 | tickTimelogger.logPartialSample(this.idleTimeNanos, TpsDebugDimensions.IDLE.ordinal());
|
| 811 | }
|
| 812 | }
|
| 813 |
|
| 814 | private static CrashReport constructOrExtractCrashReport(final Throwable t) {
|
| 815 | ReportedException firstReported = null;
|
| 816 |
|
| 817 | for (Throwable cause = t; cause != null; cause = cause.getCause()) {
|
| 818 | if (cause instanceof ReportedException reportedException) {
|
| 819 | firstReported = reportedException;
|
| 820 | }
|
| 821 | }
|
| 822 |
|
| 823 | CrashReport report;
|
| 824 | if (firstReported != null) {
|
| 825 | report = firstReported.getReport();
|
| 826 | if (firstReported != t) {
|
| 827 | report.addCategory("Wrapped in").setDetailError("Wrapping exception", t);
|
| 828 | }
|
| 829 | } else {
|
| 830 | report = new CrashReport("Exception in server tick loop", t);
|
| 831 | }
|
| 832 |
|
| 833 | return report;
|
| 834 | }
|
| 835 |
|
| 836 | private boolean haveTime() {
|
| 837 | return this.runningTask() || Util.getNanos() < (this.mayHaveDelayedTasks ? this.delayedTasksMaxNextTickTimeNanos : this.nextTickTimeNanos);
|
| 838 | }
|
| 839 |
|
| 840 | public NotificationManager notificationManager() {
|
| 841 | return this.notificationManager;
|
| 842 | }
|
| 843 |
|
| 844 | protected void waitUntilNextTick() {
|
| 845 | this.runAllTasks();
|
| 846 | this.waitingForNextTick = true;
|
| 847 |
|
| 848 | try {
|
| 849 | this.managedBlock(() -> !this.haveTime());
|
| 850 | } finally {
|
| 851 | this.waitingForNextTick = false;
|
| 852 | }
|
| 853 | }
|
| 854 |
|
| 855 | @Override
|
| 856 | protected void waitForTasks() {
|
| 857 | boolean shouldLogTime = this.isTickTimeLoggingEnabled();
|
| 858 | long waitStart = shouldLogTime ? Util.getNanos() : 0L;
|
| 859 | long waitNanos = this.waitingForNextTick ? this.nextTickTimeNanos - Util.getNanos() : 100000L;
|
| 860 | LockSupport.parkNanos("waiting for tasks", waitNanos);
|
| 861 | if (shouldLogTime) {
|
| 862 | this.idleTimeNanos = this.idleTimeNanos + (Util.getNanos() - waitStart);
|
| 863 | }
|
| 864 | }
|
| 865 |
|
| 866 | public TickTask wrapRunnable(final Runnable runnable) {
|
| 867 | return new TickTask(this.tickCount, runnable);
|
| 868 | }
|
| 869 |
|
| 870 | protected boolean shouldRun(final TickTask task) {
|
| 871 | return task.getTick() + 3 < this.tickCount || this.haveTime();
|
| 872 | }
|
| 873 |
|
| 874 | @Override
|
| 875 | protected boolean pollTask() {
|
| 876 | boolean mayHaveMoreTasks = this.pollTaskInternal();
|
| 877 | this.mayHaveDelayedTasks = mayHaveMoreTasks;
|
| 878 | return mayHaveMoreTasks;
|
| 879 | }
|
| 880 |
|
| 881 | private boolean pollTaskInternal() {
|
| 882 | if (super.pollTask()) {
|
| 883 | return true;
|
| 884 | }
|
| 885 |
|
| 886 | if (this.tickRateManager.isSprinting() || this.shouldRunAllTasks() || this.haveTime()) {
|
| 887 | for (ServerLevel level : this.getAllLevels()) {
|
| 888 | if (level.getChunkSource().pollTask()) {
|
| 889 | return true;
|
| 890 | }
|
| 891 | }
|
| 892 | }
|
| 893 |
|
| 894 | return false;
|
| 895 | }
|
| 896 |
|
| 897 | protected void doRunTask(final TickTask task) {
|
| 898 | Profiler.get().incrementCounter("runTask");
|
| 899 | super.doRunTask(task);
|
| 900 | }
|
| 901 |
|
| 902 | private Optional<ServerStatus.Favicon> loadStatusIcon() {
|
| 903 | Optional<Path> iconPath = Optional.of(this.getFile("server-icon.png"))
|
| 904 | .filter(x$0 -> Files.isRegularFile(x$0))
|
| 905 | .or(() -> this.storageSource.getIconFile().filter(x$0 -> Files.isRegularFile(x$0)));
|
| 906 | return iconPath.flatMap(path -> {
|
| 907 | try {
|
| 908 | byte[] contents = Files.readAllBytes(path);
|
| 909 | PngInfo pngInfo = PngInfo.fromBytes(contents);
|
| 910 | if (pngInfo.width() == 64 && pngInfo.height() == 64) {
|
| 911 | return Optional.of(new ServerStatus.Favicon(contents));
|
| 912 | } else {
|
| 913 | throw new IllegalArgumentException("Invalid world icon size [" + pngInfo.width() + ", " + pngInfo.height() + "], but expected [64, 64]");
|
| 914 | }
|
| 915 | } catch (Exception e) {
|
| 916 | LOGGER.error("Couldn't load server icon", e);
|
| 917 | return Optional.empty();
|
| 918 | }
|
| 919 | });
|
| 920 | }
|
| 921 |
|
| 922 | public Optional<Path> getWorldScreenshotFile() {
|
| 923 | return this.storageSource.getIconFile();
|
| 924 | }
|
| 925 |
|
| 926 | public Path getServerDirectory() {
|
| 927 | return Path.of("");
|
| 928 | }
|
| 929 |
|
| 930 | public ServerActivityMonitor getServerActivityMonitor() {
|
| 931 | return this.serverActivityMonitor;
|
| 932 | }
|
| 933 |
|
| 934 | protected void onServerCrash(final CrashReport report) {
|
| 935 | }
|
| 936 |
|
| 937 | protected void onServerExit() {
|
| 938 | }
|
| 939 |
|
| 940 | public boolean isPaused() {
|
| 941 | return false;
|
| 942 | }
|
| 943 |
|
| 944 | protected void tickServer(final BooleanSupplier haveTime) {
|
| 945 | long nano = Util.getNanos();
|
| 946 | int emptyTickThreshold = this.pauseWhenEmptySeconds() * 20;
|
| 947 | if (emptyTickThreshold > 0) {
|
| 948 | if (this.playerList.getPlayerCount() == 0 && !this.tickRateManager.isSprinting()) {
|
| 949 | this.emptyTicks++;
|
| 950 | } else {
|
| 951 | this.emptyTicks = 0;
|
| 952 | }
|
| 953 |
|
| 954 | if (this.emptyTicks >= emptyTickThreshold) {
|
| 955 | if (this.emptyTicks == emptyTickThreshold) {
|
| 956 | LOGGER.info("Server empty for {} seconds, pausing", this.pauseWhenEmptySeconds());
|
| 957 | this.autoSave();
|
| 958 | }
|
| 959 |
|
| 960 | this.tickConnection();
|
| 961 | return;
|
| 962 | }
|
| 963 | }
|
| 964 |
|
| 965 | this.tickCount++;
|
| 966 | this.tickRateManager.tick();
|
| 967 | this.tickChildren(haveTime);
|
| 968 | if (nano - this.lastServerStatus >= STATUS_EXPIRE_TIME_NANOS) {
|
| 969 | this.lastServerStatus = nano;
|
| 970 | this.status = this.buildServerStatus();
|
| 971 | }
|
| 972 |
|
| 973 | this.ticksUntilAutosave--;
|
| 974 | if (this.ticksUntilAutosave <= 0) {
|
| 975 | this.autoSave();
|
| 976 | }
|
| 977 |
|
| 978 | ProfilerFiller profiler = Profiler.get();
|
| 979 | profiler.push("tallying");
|
| 980 | long tickTime = Util.getNanos() - nano;
|
| 981 | int tickIndex = this.tickCount % 100;
|
| 982 | this.aggregatedTickTimesNanos = this.aggregatedTickTimesNanos - this.tickTimesNanos[tickIndex];
|
| 983 | this.aggregatedTickTimesNanos += tickTime;
|
| 984 | this.tickTimesNanos[tickIndex] = tickTime;
|
| 985 | this.smoothedTickTimeMillis = this.smoothedTickTimeMillis * 0.8F + (float)tickTime / (float)TimeUtil.NANOSECONDS_PER_MILLISECOND * 0.19999999F;
|
| 986 | this.logTickMethodTime(nano);
|
| 987 | profiler.pop();
|
| 988 | }
|
| 989 |
|
| 990 | protected void processPacketsAndTick(final boolean sprinting) {
|
| 991 | ProfilerFiller profiler = Profiler.get();
|
| 992 | profiler.push("tick");
|
| 993 | this.tickFrame.start();
|
| 994 | profiler.push("scheduledPacketProcessing");
|
| 995 | this.packetProcessor.processQueuedPackets();
|
| 996 | profiler.pop();
|
| 997 | this.tickServer(sprinting ? () -> false : this::haveTime);
|
| 998 | this.tickFrame.end();
|
| 999 | profiler.pop();
|
| 1000 | }
|
| 1001 |
|
| 1002 | private void autoSave() {
|
| 1003 | this.ticksUntilAutosave = this.computeNextAutosaveInterval();
|
| 1004 | LOGGER.debug("Autosave started");
|
| 1005 | ProfilerFiller profiler = Profiler.get();
|
| 1006 | profiler.push("save");
|
| 1007 | this.saveEverything(true, false, false);
|
| 1008 | profiler.pop();
|
| 1009 | LOGGER.debug("Autosave finished");
|
| 1010 | }
|
| 1011 |
|
| 1012 | private void logTickMethodTime(final long startTime) {
|
| 1013 | if (this.isTickTimeLoggingEnabled()) {
|
| 1014 | this.getTickTimeLogger().logPartialSample(Util.getNanos() - startTime, TpsDebugDimensions.TICK_SERVER_METHOD.ordinal());
|
| 1015 | }
|
| 1016 | }
|
| 1017 |
|
| 1018 | private int computeNextAutosaveInterval() {
|
| 1019 | float ticksPerSecond;
|
| 1020 | if (this.tickRateManager.isSprinting()) {
|
| 1021 | long estimatedTickTimeNanos = this.getAverageTickTimeNanos() + 1L;
|
| 1022 | ticksPerSecond = (float)TimeUtil.NANOSECONDS_PER_SECOND / (float)estimatedTickTimeNanos;
|
| 1023 | } else {
|
| 1024 | ticksPerSecond = this.tickRateManager.tickrate();
|
| 1025 | }
|
| 1026 |
|
| 1027 | int intendedIntervalInSeconds = 300;
|
| 1028 | return Math.max(100, (int)(ticksPerSecond * 300.0F));
|
| 1029 | }
|
| 1030 |
|
| 1031 | public void onTickRateChanged() {
|
| 1032 | int newAutosaveInterval = this.computeNextAutosaveInterval();
|
| 1033 | if (newAutosaveInterval < this.ticksUntilAutosave) {
|
| 1034 | this.ticksUntilAutosave = newAutosaveInterval;
|
| 1035 | }
|
| 1036 | }
|
| 1037 |
|
| 1038 | protected abstract SampleLogger getTickTimeLogger();
|
| 1039 |
|
| 1040 | public abstract boolean isTickTimeLoggingEnabled();
|
| 1041 |
|
| 1042 | private ServerStatus buildServerStatus() {
|
| 1043 | ServerStatus.Players players = this.buildPlayerStatus();
|
| 1044 | return new ServerStatus(
|
| 1045 | Component.nullToEmpty(this.getMotd()),
|
| 1046 | Optional.of(players),
|
| 1047 | Optional.of(ServerStatus.Version.current()),
|
| 1048 | Optional.ofNullable(this.statusIcon),
|
| 1049 | this.enforceSecureProfile()
|
| 1050 | );
|
| 1051 | }
|
| 1052 |
|
| 1053 | private ServerStatus.Players buildPlayerStatus() {
|
| 1054 | List<ServerPlayer> players = this.playerList.getPlayers();
|
| 1055 | int maxPlayers = this.getMaxPlayers();
|
| 1056 | if (this.hidesOnlinePlayers()) {
|
| 1057 | return new ServerStatus.Players(maxPlayers, players.size(), List.of());
|
| 1058 | }
|
| 1059 |
|
| 1060 | int sampleSize = Math.min(players.size(), 12);
|
| 1061 | ObjectArrayList<NameAndId> sample = new ObjectArrayList<>(sampleSize);
|
| 1062 | int offset = Mth.nextInt(this.random, 0, players.size() - sampleSize);
|
| 1063 |
|
| 1064 | for (int i = 0; i < sampleSize; i++) {
|
| 1065 | ServerPlayer player = players.get(offset + i);
|
| 1066 | sample.add(player.allowsListing() ? player.nameAndId() : ANONYMOUS_PLAYER_PROFILE);
|
| 1067 | }
|
| 1068 |
|
| 1069 | Util.shuffle(sample, this.random);
|
| 1070 | return new ServerStatus.Players(maxPlayers, players.size(), sample);
|
| 1071 | }
|
| 1072 |
|
| 1073 | protected void tickChildren(final BooleanSupplier haveTime) {
|
| 1074 | ProfilerFiller profiler = Profiler.get();
|
| 1075 | this.getPlayerList().getPlayers().forEach(playerx -> playerx.connection.suspendFlushing());
|
| 1076 | profiler.push("commandFunctions");
|
| 1077 | this.getFunctions().tick();
|
| 1078 | profiler.pop();
|
| 1079 | if (this.tickRateManager.runsNormally()) {
|
| 1080 | profiler.push("clocks");
|
| 1081 | this.clockManager.tick();
|
| 1082 | profiler.pop();
|
| 1083 | }
|
| 1084 |
|
| 1085 | if (this.tickCount % 20 == 0) {
|
| 1086 | profiler.push("timeSync");
|
| 1087 | this.forceGameTimeSynchronization();
|
| 1088 | profiler.pop();
|
| 1089 | }
|
| 1090 |
|
| 1091 | profiler.push("levels");
|
| 1092 | this.updateEffectiveRespawnData();
|
| 1093 |
|
| 1094 | for (ServerLevel level : this.getAllLevels()) {
|
| 1095 | profiler.push(() -> level + " " + level.dimension().identifier());
|
| 1096 | profiler.push("tick");
|
| 1097 |
|
| 1098 | try {
|
| 1099 | level.tick(haveTime);
|
| 1100 | } catch (Throwable t) {
|
| 1101 | CrashReport report = CrashReport.forThrowable(t, "Exception ticking world");
|
| 1102 | level.fillReportDetails(report);
|
| 1103 | throw new ReportedException(report);
|
| 1104 | }
|
| 1105 |
|
| 1106 | profiler.pop();
|
| 1107 | profiler.pop();
|
| 1108 | }
|
| 1109 |
|
| 1110 | profiler.popPush("connection");
|
| 1111 | this.tickConnection();
|
| 1112 | profiler.popPush("players");
|
| 1113 | this.playerList.tick();
|
| 1114 | profiler.popPush("debugSubscribers");
|
| 1115 | this.debugSubscribers.tick();
|
| 1116 | if (this.tickRateManager.runsNormally()) {
|
| 1117 | profiler.popPush("gameTests");
|
| 1118 | GameTestTicker.SINGLETON.tick();
|
| 1119 | }
|
| 1120 |
|
| 1121 | profiler.popPush("server gui refresh");
|
| 1122 |
|
| 1123 | for (Runnable tickable : this.tickables) {
|
| 1124 | tickable.run();
|
| 1125 | }
|
| 1126 |
|
| 1127 | profiler.popPush("send chunks");
|
| 1128 |
|
| 1129 | for (ServerPlayer player : this.playerList.getPlayers()) {
|
| 1130 | player.connection.chunkSender.sendNextChunks(player);
|
| 1131 | player.connection.resumeFlushing();
|
| 1132 | }
|
| 1133 |
|
| 1134 | profiler.pop();
|
| 1135 | this.serverActivityMonitor.tick();
|
| 1136 | }
|
| 1137 |
|
| 1138 | private void updateEffectiveRespawnData() {
|
| 1139 | LevelData.RespawnData respawnData = this.worldData.overworldData().getRespawnData();
|
| 1140 | ServerLevel respawnLevel = this.findRespawnDimension();
|
| 1141 | this.effectiveRespawnData = respawnLevel.getWorldBorderAdjustedRespawnData(respawnData);
|
| 1142 | }
|
| 1143 |
|
| 1144 | protected void tickConnection() {
|
| 1145 | this.getConnection().tick();
|
| 1146 | }
|
| 1147 |
|
| 1148 | public void forceGameTimeSynchronization() {
|
| 1149 | ProfilerFiller profiler = Profiler.get();
|
| 1150 | profiler.push("timeSync");
|
| 1151 | this.playerList.broadcastAll(new ClientboundSetTimePacket(this.overworld().getGameTime(), Map.of()));
|
| 1152 | profiler.pop();
|
| 1153 | }
|
| 1154 |
|
| 1155 | public void addTickable(final Runnable tickable) {
|
| 1156 | this.tickables.add(tickable);
|
| 1157 | }
|
| 1158 |
|
| 1159 | protected void setId(final String serverId) {
|
| 1160 | this.serverId = serverId;
|
| 1161 | }
|
| 1162 |
|
| 1163 | public boolean isShutdown() {
|
| 1164 | return !this.serverThread.isAlive();
|
| 1165 | }
|
| 1166 |
|
| 1167 | public Path getFile(final String name) {
|
| 1168 | return this.getServerDirectory().resolve(name);
|
| 1169 | }
|
| 1170 |
|
| 1171 | public final ServerLevel overworld() {
|
| 1172 | return this.levels.get(Level.OVERWORLD);
|
| 1173 | }
|
| 1174 |
|
| 1175 | public @Nullable ServerLevel getLevel(final ResourceKey<Level> dimension) {
|
| 1176 | return this.levels.get(dimension);
|
| 1177 | }
|
| 1178 |
|
| 1179 | public Set<ResourceKey<Level>> levelKeys() {
|
| 1180 | return this.levels.keySet();
|
| 1181 | }
|
| 1182 |
|
| 1183 | public Iterable<ServerLevel> getAllLevels() {
|
| 1184 | return this.levels.values();
|
| 1185 | }
|
| 1186 |
|
| 1187 | @Override
|
| 1188 | public String getServerVersion() {
|
| 1189 | return SharedConstants.getCurrentVersion().name();
|
| 1190 | }
|
| 1191 |
|
| 1192 | @Override
|
| 1193 | public int getPlayerCount() {
|
| 1194 | return this.playerList.getPlayerCount();
|
| 1195 | }
|
| 1196 |
|
| 1197 | public String[] getPlayerNames() {
|
| 1198 | return this.playerList.getPlayerNamesArray();
|
| 1199 | }
|
| 1200 |
|
| 1201 | public String getServerModName() {
|
| 1202 | return "vanilla";
|
| 1203 | }
|
| 1204 |
|
| 1205 | public ServerClockManager clockManager() {
|
| 1206 | return this.clockManager;
|
| 1207 | }
|
| 1208 |
|
| 1209 | public SystemReport fillSystemReport(final SystemReport systemReport) {
|
| 1210 | systemReport.setDetail("Server Running", () -> Boolean.toString(this.running));
|
| 1211 | if (this.playerList != null) {
|
| 1212 | systemReport.setDetail(
|
| 1213 | "Player Count", () -> this.playerList.getPlayerCount() + " / " + this.playerList.getMaxPlayers() + "; " + this.playerList.getPlayers()
|
| 1214 | );
|
| 1215 | }
|
| 1216 |
|
| 1217 | systemReport.setDetail("Active Data Packs", () -> PackRepository.displayPackList(this.packRepository.getSelectedPacks()));
|
| 1218 | systemReport.setDetail("Available Data Packs", () -> PackRepository.displayPackList(this.packRepository.getAvailablePacks()));
|
| 1219 | systemReport.setDetail(
|
| 1220 | "Enabled Feature Flags",
|
| 1221 | () -> FeatureFlags.REGISTRY.toNames(this.worldData.enabledFeatures()).stream().map(Identifier::toString).collect(Collectors.joining(", "))
|
| 1222 | );
|
| 1223 | systemReport.setDetail("World Generation", () -> this.worldData.worldGenSettingsLifecycle().toString());
|
| 1224 | systemReport.setDetail("World Seed", () -> String.valueOf(this.worldGenSettings.options().seed()));
|
| 1225 | systemReport.setDetail("Suppressed Exceptions", this.suppressedExceptions::dump);
|
| 1226 | if (this.serverId != null) {
|
| 1227 | systemReport.setDetail("Server Id", () -> this.serverId);
|
| 1228 | }
|
| 1229 |
|
| 1230 | return this.fillServerSystemReport(systemReport);
|
| 1231 | }
|
| 1232 |
|
| 1233 | public abstract SystemReport fillServerSystemReport(final SystemReport systemReport);
|
| 1234 |
|
| 1235 | public ModCheck getModdedStatus() {
|
| 1236 | return ModCheck.identify("vanilla", this::getServerModName, "Server", MinecraftServer.class);
|
| 1237 | }
|
| 1238 |
|
| 1239 | @Override
|
| 1240 | public void sendSystemMessage(final Component message) {
|
| 1241 | LOGGER.info("System chat: {}", message.getString());
|
| 1242 | }
|
| 1243 |
|
| 1244 | public KeyPair getKeyPair() {
|
| 1245 | return Objects.requireNonNull(this.keyPair);
|
| 1246 | }
|
| 1247 |
|
| 1248 | public int getPort() {
|
| 1249 | return this.port;
|
| 1250 | }
|
| 1251 |
|
| 1252 | public void setPort(final int port) {
|
| 1253 | this.port = port;
|
| 1254 | }
|
| 1255 |
|
| 1256 | public @Nullable GameProfile getSingleplayerProfile() {
|
| 1257 | return this.singleplayerProfile;
|
| 1258 | }
|
| 1259 |
|
| 1260 | public void setSingleplayerProfile(final @Nullable GameProfile singleplayerProfile) {
|
| 1261 | this.singleplayerProfile = singleplayerProfile;
|
| 1262 | }
|
| 1263 |
|
| 1264 | public boolean isSingleplayer() {
|
| 1265 | return this.singleplayerProfile != null;
|
| 1266 | }
|
| 1267 |
|
| 1268 | protected void initializeKeyPair() {
|
| 1269 | LOGGER.info("Generating keypair");
|
| 1270 |
|
| 1271 | try {
|
| 1272 | this.keyPair = Crypt.generateKeyPair();
|
| 1273 | } catch (CryptException e) {
|
| 1274 | throw new IllegalStateException("Failed to generate key pair", e);
|
| 1275 | }
|
| 1276 | }
|
| 1277 |
|
| 1278 | public void setDifficulty(final Difficulty difficulty, final boolean ignoreLock) {
|
| 1279 | if (ignoreLock || !this.worldData.isDifficultyLocked()) {
|
| 1280 | this.worldData.setDifficulty(this.worldData.isHardcore() ? Difficulty.HARD : difficulty);
|
| 1281 | this.updateMobSpawningFlags();
|
| 1282 | this.getPlayerList().getPlayers().forEach(this::sendDifficultyUpdate);
|
| 1283 | }
|
| 1284 | }
|
| 1285 |
|
| 1286 | public int getScaledTrackingDistance(final int baseRange) {
|
| 1287 | return baseRange;
|
| 1288 | }
|
| 1289 |
|
| 1290 | public void updateMobSpawningFlags() {
|
| 1291 | for (ServerLevel level : this.getAllLevels()) {
|
| 1292 | level.setSpawnSettings(level.isSpawningMonsters());
|
| 1293 | }
|
| 1294 | }
|
| 1295 |
|
| 1296 | public void setDifficultyLocked(final boolean locked) {
|
| 1297 | this.worldData.setDifficultyLocked(locked);
|
| 1298 | this.getPlayerList().getPlayers().forEach(this::sendDifficultyUpdate);
|
| 1299 | }
|
| 1300 |
|
| 1301 | private void sendDifficultyUpdate(final ServerPlayer player) {
|
| 1302 | LevelData levelData = player.level().getLevelData();
|
| 1303 | player.connection.send(new ClientboundChangeDifficultyPacket(levelData.getDifficulty(), levelData.isDifficultyLocked()));
|
| 1304 | }
|
| 1305 |
|
| 1306 | public boolean isDemo() {
|
| 1307 | return this.isDemo;
|
| 1308 | }
|
| 1309 |
|
| 1310 | public void setDemo(final boolean demo) {
|
| 1311 | this.isDemo = demo;
|
| 1312 | }
|
| 1313 |
|
| 1314 | public Map<String, String> getCodeOfConducts() {
|
| 1315 | return Map.of();
|
| 1316 | }
|
| 1317 |
|
| 1318 | public Optional<MinecraftServer.ServerResourcePackInfo> getServerResourcePack() {
|
| 1319 | return Optional.empty();
|
| 1320 | }
|
| 1321 |
|
| 1322 | public boolean isResourcePackRequired() {
|
| 1323 | return this.getServerResourcePack().filter(MinecraftServer.ServerResourcePackInfo::isRequired).isPresent();
|
| 1324 | }
|
| 1325 |
|
| 1326 | public abstract boolean isDedicatedServer();
|
| 1327 |
|
| 1328 | public abstract int getRateLimitPacketsPerSecond();
|
| 1329 |
|
| 1330 | public abstract int getCommandSpamThresholdSeconds();
|
| 1331 |
|
| 1332 | public abstract int getChatSpamThresholdSeconds();
|
| 1333 |
|
| 1334 | public boolean usesAuthentication() {
|
| 1335 | return this.onlineMode;
|
| 1336 | }
|
| 1337 |
|
| 1338 | public void setUsesAuthentication(final boolean onlineMode) {
|
| 1339 | this.onlineMode = onlineMode;
|
| 1340 | }
|
| 1341 |
|
| 1342 | public boolean getPreventProxyConnections() {
|
| 1343 | return this.preventProxyConnections;
|
| 1344 | }
|
| 1345 |
|
| 1346 | public void setPreventProxyConnections(final boolean preventProxyConnections) {
|
| 1347 | this.preventProxyConnections = preventProxyConnections;
|
| 1348 | }
|
| 1349 |
|
| 1350 | public abstract boolean useNativeTransport();
|
| 1351 |
|
| 1352 | public boolean allowFlight() {
|
| 1353 | return true;
|
| 1354 | }
|
| 1355 |
|
| 1356 | @Override
|
| 1357 | public String getMotd() {
|
| 1358 | return this.motd;
|
| 1359 | }
|
| 1360 |
|
| 1361 | public void setMotd(final String motd) {
|
| 1362 | this.motd = motd;
|
| 1363 | }
|
| 1364 |
|
| 1365 | public boolean isStopped() {
|
| 1366 | return this.stopped;
|
| 1367 | }
|
| 1368 |
|
| 1369 | public PlayerList getPlayerList() {
|
| 1370 | return this.playerList;
|
| 1371 | }
|
| 1372 |
|
| 1373 | public void setPlayerList(final PlayerList players) {
|
| 1374 | this.playerList = players;
|
| 1375 | }
|
| 1376 |
|
| 1377 | public abstract boolean isPublished();
|
| 1378 |
|
| 1379 | public void setDefaultGameType(final GameType gameType) {
|
| 1380 | this.worldData.setGameType(gameType);
|
| 1381 | }
|
| 1382 |
|
| 1383 | public int enforceGameTypeForPlayers(final @Nullable GameType gameType) {
|
| 1384 | if (gameType == null) {
|
| 1385 | return 0;
|
| 1386 | }
|
| 1387 |
|
| 1388 | int count = 0;
|
| 1389 |
|
| 1390 | for (ServerPlayer player : this.getPlayerList().getPlayers()) {
|
| 1391 | if (player.setGameMode(gameType)) {
|
| 1392 | count++;
|
| 1393 | }
|
| 1394 | }
|
| 1395 |
|
| 1396 | return count;
|
| 1397 | }
|
| 1398 |
|
| 1399 | public ServerConnectionListener getConnection() {
|
| 1400 | return this.connection;
|
| 1401 | }
|
| 1402 |
|
| 1403 | public boolean isReady() {
|
| 1404 | return this.isReady;
|
| 1405 | }
|
| 1406 |
|
| 1407 | public boolean publishServer(final MinecraftServer.MultiplayerScope scope, final boolean allowCommands, final int port) {
|
| 1408 | return false;
|
| 1409 | }
|
| 1410 |
|
| 1411 | public boolean unpublishServer() {
|
| 1412 | return false;
|
| 1413 | }
|
| 1414 |
|
| 1415 | public int getTickCount() {
|
| 1416 | return this.tickCount;
|
| 1417 | }
|
| 1418 |
|
| 1419 | public boolean isUnderSpawnProtection(final ServerLevel level, final BlockPos pos, final Player player) {
|
| 1420 | return false;
|
| 1421 | }
|
| 1422 |
|
| 1423 | public boolean repliesToStatus() {
|
| 1424 | return true;
|
| 1425 | }
|
| 1426 |
|
| 1427 | public boolean hidesOnlinePlayers() {
|
| 1428 | return false;
|
| 1429 | }
|
| 1430 |
|
| 1431 | public Proxy getProxy() {
|
| 1432 | return this.proxy;
|
| 1433 | }
|
| 1434 |
|
| 1435 | public int playerIdleTimeout() {
|
| 1436 | return this.playerIdleTimeout;
|
| 1437 | }
|
| 1438 |
|
| 1439 | public void setPlayerIdleTimeout(final int playerIdleTimeout) {
|
| 1440 | this.playerIdleTimeout = playerIdleTimeout;
|
| 1441 | }
|
| 1442 |
|
| 1443 | public Services services() {
|
| 1444 | return this.services;
|
| 1445 | }
|
| 1446 |
|
| 1447 | public @Nullable ServerStatus getStatus() {
|
| 1448 | return this.status;
|
| 1449 | }
|
| 1450 |
|
| 1451 | public void invalidateStatus() {
|
| 1452 | this.lastServerStatus = 0L;
|
| 1453 | }
|
| 1454 |
|
| 1455 | public int getAbsoluteMaxWorldSize() {
|
| 1456 | return 29999984;
|
| 1457 | }
|
| 1458 |
|
| 1459 | @Override
|
| 1460 | public boolean scheduleExecutables() {
|
| 1461 | return super.scheduleExecutables() && !this.isStopped();
|
| 1462 | }
|
| 1463 |
|
| 1464 | @Override
|
| 1465 | public void executeIfPossible(final Runnable command) {
|
| 1466 | if (this.isStopped()) {
|
| 1467 | throw new RejectedExecutionException("Server already shutting down");
|
| 1468 | }
|
| 1469 |
|
| 1470 | super.executeIfPossible(command);
|
| 1471 | }
|
| 1472 |
|
| 1473 | @Override
|
| 1474 | public Thread getRunningThread() {
|
| 1475 | return this.serverThread;
|
| 1476 | }
|
| 1477 |
|
| 1478 | public int getCompressionThreshold() {
|
| 1479 | return 256;
|
| 1480 | }
|
| 1481 |
|
| 1482 | public boolean enforceSecureProfile() {
|
| 1483 | return false;
|
| 1484 | }
|
| 1485 |
|
| 1486 | public long getNextTickTime() {
|
| 1487 | return this.nextTickTimeNanos;
|
| 1488 | }
|
| 1489 |
|
| 1490 | public DataFixer getFixerUpper() {
|
| 1491 | return this.fixerUpper;
|
| 1492 | }
|
| 1493 |
|
| 1494 | public ServerAdvancementManager getAdvancements() {
|
| 1495 | return this.resources.managers.getAdvancements();
|
| 1496 | }
|
| 1497 |
|
| 1498 | public ServerFunctionManager getFunctions() {
|
| 1499 | return this.functionManager;
|
| 1500 | }
|
| 1501 |
|
| 1502 | public CompletableFuture<Void> reloadResources(final Collection<String> packsToEnable) {
|
| 1503 | CompletableFuture<Void> result = CompletableFuture.<ImmutableList>supplyAsync(
|
| 1504 | () -> packsToEnable.stream().map(this.packRepository::getPack).filter(Objects::nonNull).flatMap(Pack::open).collect(ImmutableList.toImmutableList()), this
|
| 1505 | )
|
| 1506 | .thenCompose(
|
| 1507 | packsToLoad -> {
|
| 1508 | CloseableResourceManager resources = new MultiPackResourceManager(PackType.SERVER_DATA, packsToLoad);
|
| 1509 | List<Registry.PendingTags<?>> postponedTags = TagLoader.loadTagsForExistingRegistries(resources, this.registries.compositeAccess());
|
| 1510 | return ReloadableServerResources.loadResources(
|
| 1511 | resources,
|
| 1512 | this.registries,
|
| 1513 | postponedTags,
|
| 1514 | this.worldData.enabledFeatures(),
|
| 1515 | this.isDedicatedServer() ? Commands.CommandSelection.DEDICATED : Commands.CommandSelection.INTEGRATED,
|
| 1516 | this.getFunctionCompilationPermissions(),
|
| 1517 | this.executor,
|
| 1518 | this
|
| 1519 | )
|
| 1520 | .whenComplete((unit, throwable) -> {
|
| 1521 | if (throwable != null) {
|
| 1522 | resources.close();
|
| 1523 | }
|
| 1524 | })
|
| 1525 | .thenApply(managers -> new MinecraftServer.ReloadableResources(resources, managers));
|
| 1526 | }
|
| 1527 | )
|
| 1528 | .thenAcceptAsync(newResources -> {
|
| 1529 | this.resources.close();
|
| 1530 | this.resources = newResources;
|
| 1531 | this.packRepository.setSelected(packsToEnable);
|
| 1532 | WorldDataConfiguration newConfig = new WorldDataConfiguration(getSelectedPacks(this.packRepository, true), this.worldData.enabledFeatures());
|
| 1533 | this.worldData.setDataConfiguration(newConfig);
|
| 1534 | this.resources.managers.updateComponentsAndStaticRegistryTags();
|
| 1535 | this.resources.managers.getRecipeManager().finalizeRecipeLoading(this.worldData.enabledFeatures());
|
| 1536 | this.getPlayerList().saveAll();
|
| 1537 | this.getPlayerList().reloadResources();
|
| 1538 | this.functionManager.replaceLibrary(this.resources.managers.getFunctionLibrary());
|
| 1539 | this.structureTemplateManager.onResourceManagerReload(this.resources.resourceManager);
|
| 1540 | }, this);
|
| 1541 | if (this.isSameThread()) {
|
| 1542 | this.managedBlock(result::isDone);
|
| 1543 | }
|
| 1544 |
|
| 1545 | return result;
|
| 1546 | }
|
| 1547 |
|
| 1548 | public static WorldDataConfiguration configurePackRepository(
|
| 1549 | final PackRepository packRepository, final WorldDataConfiguration initialDataConfig, final boolean initMode, final boolean safeMode
|
| 1550 | ) {
|
| 1551 | DataPackConfig dataPackConfig = initialDataConfig.dataPacks();
|
| 1552 | FeatureFlagSet forcedFeatures = initMode ? FeatureFlagSet.of() : initialDataConfig.enabledFeatures();
|
| 1553 | FeatureFlagSet allowedFeatures = initMode ? FeatureFlags.REGISTRY.allFlags() : initialDataConfig.enabledFeatures();
|
| 1554 | packRepository.reload();
|
| 1555 | if (safeMode) {
|
| 1556 | return configureRepositoryWithSelection(packRepository, List.of("vanilla"), forcedFeatures, false);
|
| 1557 | }
|
| 1558 |
|
| 1559 | Set<String> selected = Sets.newLinkedHashSet();
|
| 1560 |
|
| 1561 | for (String id : dataPackConfig.getEnabled()) {
|
| 1562 | if (packRepository.isAvailable(id)) {
|
| 1563 | selected.add(id);
|
| 1564 | } else {
|
| 1565 | LOGGER.warn("Missing data pack {}", id);
|
| 1566 | }
|
| 1567 | }
|
| 1568 |
|
| 1569 | for (Pack pack : packRepository.getAvailablePacks()) {
|
| 1570 | String packId = pack.getId();
|
| 1571 | if (!dataPackConfig.getDisabled().contains(packId)) {
|
| 1572 | FeatureFlagSet packFeatures = pack.getRequestedFeatures();
|
| 1573 | boolean isSelected = selected.contains(packId);
|
| 1574 | if (!isSelected && pack.getPackSource().shouldAddAutomatically()) {
|
| 1575 | if (packFeatures.isSubsetOf(allowedFeatures)) {
|
| 1576 | LOGGER.info("Found new data pack {}, loading it automatically", packId);
|
| 1577 | selected.add(packId);
|
| 1578 | } else {
|
| 1579 | LOGGER.info("Found new data pack {}, but can't load it due to missing features {}", packId, FeatureFlags.printMissingFlags(allowedFeatures, packFeatures));
|
| 1580 | }
|
| 1581 | }
|
| 1582 |
|
| 1583 | if (isSelected && !packFeatures.isSubsetOf(allowedFeatures)) {
|
| 1584 | LOGGER.warn(
|
| 1585 | "Pack {} requires features {} that are not enabled for this world, disabling pack.",
|
| 1586 | packId,
|
| 1587 | FeatureFlags.printMissingFlags(allowedFeatures, packFeatures)
|
| 1588 | );
|
| 1589 | selected.remove(packId);
|
| 1590 | }
|
| 1591 | }
|
| 1592 | }
|
| 1593 |
|
| 1594 | if (selected.isEmpty()) {
|
| 1595 | LOGGER.info("No datapacks selected, forcing vanilla");
|
| 1596 | selected.add("vanilla");
|
| 1597 | }
|
| 1598 |
|
| 1599 | return configureRepositoryWithSelection(packRepository, selected, forcedFeatures, true);
|
| 1600 | }
|
| 1601 |
|
| 1602 | private static WorldDataConfiguration configureRepositoryWithSelection(
|
| 1603 | final PackRepository packRepository, final Collection<String> selected, final FeatureFlagSet forcedFeatures, final boolean disableInactive
|
| 1604 | ) {
|
| 1605 | packRepository.setSelected(selected);
|
| 1606 | enableForcedFeaturePacks(packRepository, forcedFeatures);
|
| 1607 | DataPackConfig packConfig = getSelectedPacks(packRepository, disableInactive);
|
| 1608 | FeatureFlagSet packRequestedFeatures = packRepository.getRequestedFeatureFlags().join(forcedFeatures);
|
| 1609 | return new WorldDataConfiguration(packConfig, packRequestedFeatures);
|
| 1610 | }
|
| 1611 |
|
| 1612 | private static void enableForcedFeaturePacks(final PackRepository packRepository, final FeatureFlagSet forcedFeatures) {
|
| 1613 | FeatureFlagSet providedFeatures = packRepository.getRequestedFeatureFlags();
|
| 1614 | FeatureFlagSet missingFeatures = forcedFeatures.subtract(providedFeatures);
|
| 1615 | if (!missingFeatures.isEmpty()) {
|
| 1616 | Set<String> selected = new ObjectArraySet<>(packRepository.getSelectedIds());
|
| 1617 |
|
| 1618 | for (Pack pack : packRepository.getAvailablePacks()) {
|
| 1619 | if (missingFeatures.isEmpty()) {
|
| 1620 | break;
|
| 1621 | }
|
| 1622 |
|
| 1623 | if (pack.getPackSource() == PackSource.FEATURE) {
|
| 1624 | String packId = pack.getId();
|
| 1625 | FeatureFlagSet packFeatures = pack.getRequestedFeatures();
|
| 1626 | if (!packFeatures.isEmpty() && packFeatures.intersects(missingFeatures) && packFeatures.isSubsetOf(forcedFeatures)) {
|
| 1627 | if (!selected.add(packId)) {
|
| 1628 | throw new IllegalStateException("Tried to force '" + packId + "', but it was already enabled");
|
| 1629 | }
|
| 1630 |
|
| 1631 | LOGGER.info("Found feature pack ('{}') for requested feature, forcing to enabled", packId);
|
| 1632 | missingFeatures = missingFeatures.subtract(packFeatures);
|
| 1633 | }
|
| 1634 | }
|
| 1635 | }
|
| 1636 |
|
| 1637 | packRepository.setSelected(selected);
|
| 1638 | }
|
| 1639 | }
|
| 1640 |
|
| 1641 | private static DataPackConfig getSelectedPacks(final PackRepository packRepository, final boolean disableInactive) {
|
| 1642 | Collection<String> selected = packRepository.getSelectedIds();
|
| 1643 | List<String> enabled = ImmutableList.copyOf(selected);
|
| 1644 | List<String> disabled = disableInactive ? packRepository.getAvailableIds().stream().filter(id -> !selected.contains(id)).toList() : List.of();
|
| 1645 | return new DataPackConfig(enabled, disabled);
|
| 1646 | }
|
| 1647 |
|
| 1648 | public void kickUnlistedPlayers() {
|
| 1649 | if (this.isEnforceWhitelist() && this.isUsingWhitelist()) {
|
| 1650 | PlayerList playerList = this.getPlayerList();
|
| 1651 | UserWhiteList whiteList = playerList.getWhiteList();
|
| 1652 |
|
| 1653 | for (ServerPlayer player : Lists.newArrayList(playerList.getPlayers())) {
|
| 1654 | if (!whiteList.isWhiteListed(player.nameAndId())) {
|
| 1655 | player.connection.disconnect(Component.translatable("multiplayer.disconnect.not_whitelisted"));
|
| 1656 | }
|
| 1657 | }
|
| 1658 | }
|
| 1659 | }
|
| 1660 |
|
| 1661 | public PackRepository getPackRepository() {
|
| 1662 | return this.packRepository;
|
| 1663 | }
|
| 1664 |
|
| 1665 | public Commands getCommands() {
|
| 1666 | return this.resources.managers.getCommands();
|
| 1667 | }
|
| 1668 |
|
| 1669 | public CommandSourceStack createCommandSourceStack() {
|
| 1670 | ServerLevel level = this.findRespawnDimension();
|
| 1671 | return new CommandSourceStack(
|
| 1672 | this, Vec3.atLowerCornerOf(this.getRespawnData().pos()), Vec2.ZERO, level, LevelBasedPermissionSet.OWNER, Component.literal("Server"), this
|
| 1673 | );
|
| 1674 | }
|
| 1675 |
|
| 1676 | public ServerLevel findRespawnDimension() {
|
| 1677 | LevelData.RespawnData respawnData = this.getWorldData().overworldData().getRespawnData();
|
| 1678 | ResourceKey<Level> respawnDimension = respawnData.dimension();
|
| 1679 | ServerLevel respawnLevel = this.getLevel(respawnDimension);
|
| 1680 | return respawnLevel != null ? respawnLevel : this.overworld();
|
| 1681 | }
|
| 1682 |
|
| 1683 | public void setRespawnData(final LevelData.RespawnData respawnData) {
|
| 1684 | ServerLevelData levelData = this.worldData.overworldData();
|
| 1685 | LevelData.RespawnData oldRespawnData = levelData.getRespawnData();
|
| 1686 | if (!oldRespawnData.equals(respawnData)) {
|
| 1687 | levelData.setSpawn(respawnData);
|
| 1688 | this.getPlayerList().broadcastAll(new ClientboundSetDefaultSpawnPositionPacket(respawnData));
|
| 1689 | this.updateEffectiveRespawnData();
|
| 1690 | }
|
| 1691 | }
|
| 1692 |
|
| 1693 | public LevelData.RespawnData getRespawnData() {
|
| 1694 | return this.effectiveRespawnData;
|
| 1695 | }
|
| 1696 |
|
| 1697 | @Override
|
| 1698 | public boolean acceptsSuccess() {
|
| 1699 | return true;
|
| 1700 | }
|
| 1701 |
|
| 1702 | @Override
|
| 1703 | public boolean acceptsFailure() {
|
| 1704 | return true;
|
| 1705 | }
|
| 1706 |
|
| 1707 | @Override
|
| 1708 | public abstract boolean shouldInformAdmins();
|
| 1709 |
|
| 1710 | public WorldGenSettings getWorldGenSettings() {
|
| 1711 | return this.worldGenSettings;
|
| 1712 | }
|
| 1713 |
|
| 1714 | public RecipeManager getRecipeManager() {
|
| 1715 | return this.resources.managers.getRecipeManager();
|
| 1716 | }
|
| 1717 |
|
| 1718 | public ServerScoreboard getScoreboard() {
|
| 1719 | return this.scoreboard;
|
| 1720 | }
|
| 1721 |
|
| 1722 | public CommandStorage getCommandStorage() {
|
| 1723 | if (this.commandStorage == null) {
|
| 1724 | throw new NullPointerException("Called before server init");
|
| 1725 | } else {
|
| 1726 | return this.commandStorage;
|
| 1727 | }
|
| 1728 | }
|
| 1729 |
|
| 1730 | public Stopwatches getStopwatches() {
|
| 1731 | if (this.stopwatches == null) {
|
| 1732 | throw new NullPointerException("Called before server init");
|
| 1733 | } else {
|
| 1734 | return this.stopwatches;
|
| 1735 | }
|
| 1736 | }
|
| 1737 |
|
| 1738 | public CustomBossEvents getCustomBossEvents() {
|
| 1739 | return this.customBossEvents;
|
| 1740 | }
|
| 1741 |
|
| 1742 | public RandomSource getRandomSequence(final Identifier key) {
|
| 1743 | return this.randomSequences.get(key, this.worldGenSettings.options().seed());
|
| 1744 | }
|
| 1745 |
|
| 1746 | public RandomSequences getRandomSequences() {
|
| 1747 | return this.randomSequences;
|
| 1748 | }
|
| 1749 |
|
| 1750 | public void setWeatherParameters(final int clearTime, final int rainTime, final boolean raining, final boolean thundering) {
|
| 1751 | WeatherData weatherData = this.getWeatherData();
|
| 1752 | weatherData.setClearWeatherTime(clearTime);
|
| 1753 | weatherData.setRainTime(rainTime);
|
| 1754 | weatherData.setThunderTime(rainTime);
|
| 1755 | weatherData.setRaining(raining);
|
| 1756 | weatherData.setThundering(thundering);
|
| 1757 | }
|
| 1758 |
|
| 1759 | public WeatherData getWeatherData() {
|
| 1760 | return this.weatherData;
|
| 1761 | }
|
| 1762 |
|
| 1763 | public boolean isEnforceWhitelist() {
|
| 1764 | return this.enforceWhitelist;
|
| 1765 | }
|
| 1766 |
|
| 1767 | public void setEnforceWhitelist(final boolean enforceWhitelist) {
|
| 1768 | this.enforceWhitelist = enforceWhitelist;
|
| 1769 | }
|
| 1770 |
|
| 1771 | public boolean isUsingWhitelist() {
|
| 1772 | return this.usingWhitelist;
|
| 1773 | }
|
| 1774 |
|
| 1775 | public void setUsingWhitelist(final boolean usingWhitelist) {
|
| 1776 | this.usingWhitelist = usingWhitelist;
|
| 1777 | }
|
| 1778 |
|
| 1779 | public float getCurrentSmoothedTickTime() {
|
| 1780 | return this.smoothedTickTimeMillis;
|
| 1781 | }
|
| 1782 |
|
| 1783 | public ServerTickRateManager tickRateManager() {
|
| 1784 | return this.tickRateManager;
|
| 1785 | }
|
| 1786 |
|
| 1787 | public long getAverageTickTimeNanos() {
|
| 1788 | return this.aggregatedTickTimesNanos / Math.min(100, Math.max(this.tickCount, 1));
|
| 1789 | }
|
| 1790 |
|
| 1791 | public long[] getTickTimesNanos() {
|
| 1792 | return this.tickTimesNanos;
|
| 1793 | }
|
| 1794 |
|
| 1795 | public LevelBasedPermissionSet getProfilePermissions(final NameAndId nameAndId) {
|
| 1796 | if (this.getPlayerList().isOp(nameAndId)) {
|
| 1797 | ServerOpListEntry opListEntry = this.getPlayerList().getOps().get(nameAndId);
|
| 1798 | return opListEntry != null ? opListEntry.permissions() : this.operatorUserPermissions();
|
| 1799 | } else {
|
| 1800 | return LevelBasedPermissionSet.ALL;
|
| 1801 | }
|
| 1802 | }
|
| 1803 |
|
| 1804 | public abstract boolean isSingleplayerOwner(NameAndId nameAndId);
|
| 1805 |
|
| 1806 | public void dumpServerProperties(final Path path) throws IOException {
|
| 1807 | }
|
| 1808 |
|
| 1809 | private void saveDebugReport(final Path output) {
|
| 1810 | Path levelsDir = output.resolve("levels");
|
| 1811 |
|
| 1812 | try {
|
| 1813 | for (Entry<ResourceKey<Level>, ServerLevel> level : this.levels.entrySet()) {
|
| 1814 | Identifier levelId = level.getKey().identifier();
|
| 1815 | Path levelPath = levelId.resolveAgainst(levelsDir);
|
| 1816 | Files.createDirectories(levelPath);
|
| 1817 | level.getValue().saveDebugReport(levelPath);
|
| 1818 | }
|
| 1819 |
|
| 1820 | this.dumpGameRules(output.resolve("gamerules.txt"));
|
| 1821 | this.dumpClasspath(output.resolve("classpath.txt"));
|
| 1822 | this.dumpMiscStats(output.resolve("stats.txt"));
|
| 1823 | this.dumpThreads(output.resolve("threads.txt"));
|
| 1824 | this.dumpServerProperties(output.resolve("server.properties.txt"));
|
| 1825 | this.dumpNativeModules(output.resolve("modules.txt"));
|
| 1826 | } catch (IOException e) {
|
| 1827 | LOGGER.warn("Failed to save debug report", e);
|
| 1828 | }
|
| 1829 | }
|
| 1830 |
|
| 1831 | private void dumpMiscStats(final Path path) throws IOException {
|
| 1832 | try (Writer output = Files.newBufferedWriter(path)) {
|
| 1833 | output.write(String.format(Locale.ROOT, "pending_tasks: %d\n", this.getPendingTasksCount()));
|
| 1834 | output.write(String.format(Locale.ROOT, "average_tick_time: %f\n", this.getCurrentSmoothedTickTime()));
|
| 1835 | output.write(String.format(Locale.ROOT, "tick_times: %s\n", Arrays.toString(this.tickTimesNanos)));
|
| 1836 | output.write(String.format(Locale.ROOT, "queue: %s\n", Util.backgroundExecutor()));
|
| 1837 | }
|
| 1838 | }
|
| 1839 |
|
| 1840 | private void dumpGameRules(final Path path) throws IOException {
|
| 1841 | try (Writer output = Files.newBufferedWriter(path)) {
|
| 1842 | final List<String> entries = Lists.newArrayList();
|
| 1843 | final GameRules gameRules = this.getGameRules();
|
| 1844 | gameRules.visitGameRuleTypes(new GameRuleTypeVisitor() {
|
| 1845 | @Override
|
| 1846 | public <T> void visit(final GameRule<T> gameRule) {
|
| 1847 | entries.add(String.format(Locale.ROOT, "%s=%s\n", gameRule.getIdentifier(), gameRules.getAsString(gameRule)));
|
| 1848 | }
|
| 1849 | });
|
| 1850 |
|
| 1851 | for (String entry : entries) {
|
| 1852 | output.write(entry);
|
| 1853 | }
|
| 1854 | }
|
| 1855 | }
|
| 1856 |
|
| 1857 | private void dumpClasspath(final Path path) throws IOException {
|
| 1858 | try (Writer output = Files.newBufferedWriter(path)) {
|
| 1859 | String classpath = System.getProperty("java.class.path");
|
| 1860 | String separator = File.pathSeparator;
|
| 1861 |
|
| 1862 | for (String s : Splitter.on(separator).split(classpath)) {
|
| 1863 | output.write(s);
|
| 1864 | output.write("\n");
|
| 1865 | }
|
| 1866 | }
|
| 1867 | }
|
| 1868 |
|
| 1869 | private void dumpThreads(final Path path) throws IOException {
|
| 1870 | ThreadInfo[] threadInfos = Util.dumpThreadInfo();
|
| 1871 | Arrays.sort(threadInfos, Comparator.comparing(ThreadInfo::getThreadName));
|
| 1872 |
|
| 1873 | try (Writer output = Files.newBufferedWriter(path)) {
|
| 1874 | for (ThreadInfo threadInfo : threadInfos) {
|
| 1875 | output.write(threadInfo.toString());
|
| 1876 | output.write(10);
|
| 1877 | }
|
| 1878 | }
|
| 1879 | }
|
| 1880 |
|
| 1881 | private void dumpNativeModules(final Path path) throws IOException {
|
| 1882 | try (Writer output = Files.newBufferedWriter(path)) {
|
| 1883 | List<NativeModuleLister.NativeModuleInfo> modules;
|
| 1884 | try {
|
| 1885 | modules = Lists.newArrayList(NativeModuleLister.listModules());
|
| 1886 | } catch (Throwable t) {
|
| 1887 | LOGGER.warn("Failed to list native modules", t);
|
| 1888 | return;
|
| 1889 | }
|
| 1890 |
|
| 1891 | modules.sort(Comparator.comparing(NativeModuleLister.NativeModuleInfo::name, String.CASE_INSENSITIVE_ORDER));
|
| 1892 |
|
| 1893 | for (NativeModuleLister.NativeModuleInfo module : modules) {
|
| 1894 | output.write(module.toString());
|
| 1895 | output.write(10);
|
| 1896 | }
|
| 1897 | }
|
| 1898 | }
|
| 1899 |
|
| 1900 | private ProfilerFiller createProfiler() {
|
| 1901 | if (this.willStartRecordingMetrics) {
|
| 1902 | this.metricsRecorder = ActiveMetricsRecorder.createStarted(
|
| 1903 | new ServerMetricsSamplersProvider(Util.timeSource(), this.isDedicatedServer()),
|
| 1904 | Util.timeSource(),
|
| 1905 | Util.ioPool(),
|
| 1906 | new MetricsPersister("server"),
|
| 1907 | this.onMetricsRecordingStopped,
|
| 1908 | reportPath -> {
|
| 1909 | this.executeBlocking(() -> this.saveDebugReport(reportPath.resolve("server")));
|
| 1910 | this.onMetricsRecordingFinished.accept(reportPath);
|
| 1911 | }
|
| 1912 | );
|
| 1913 | this.willStartRecordingMetrics = false;
|
| 1914 | }
|
| 1915 |
|
| 1916 | this.metricsRecorder.startTick();
|
| 1917 | return SingleTickProfiler.decorateFiller(this.metricsRecorder.getProfiler(), SingleTickProfiler.createTickProfiler("Server"));
|
| 1918 | }
|
| 1919 |
|
| 1920 | protected void endMetricsRecordingTick() {
|
| 1921 | this.metricsRecorder.endTick();
|
| 1922 | }
|
| 1923 |
|
| 1924 | public boolean isRecordingMetrics() {
|
| 1925 | return this.metricsRecorder.isRecording();
|
| 1926 | }
|
| 1927 |
|
| 1928 | public void startRecordingMetrics(final Consumer<ProfileResults> onStopped, final Consumer<Path> onFinished) {
|
| 1929 | this.onMetricsRecordingStopped = report -> {
|
| 1930 | this.stopRecordingMetrics();
|
| 1931 | onStopped.accept(report);
|
| 1932 | };
|
| 1933 | this.onMetricsRecordingFinished = onFinished;
|
| 1934 | this.willStartRecordingMetrics = true;
|
| 1935 | }
|
| 1936 |
|
| 1937 | public void stopRecordingMetrics() {
|
| 1938 | this.metricsRecorder = InactiveMetricsRecorder.INSTANCE;
|
| 1939 | }
|
| 1940 |
|
| 1941 | public void finishRecordingMetrics() {
|
| 1942 | this.metricsRecorder.end();
|
| 1943 | }
|
| 1944 |
|
| 1945 | public void cancelRecordingMetrics() {
|
| 1946 | this.metricsRecorder.cancel();
|
| 1947 | }
|
| 1948 |
|
| 1949 | public Path getWorldPath(final LevelResource resource) {
|
| 1950 | return this.storageSource.getLevelPath(resource);
|
| 1951 | }
|
| 1952 |
|
| 1953 | public boolean forceSynchronousWrites() {
|
| 1954 | return true;
|
| 1955 | }
|
| 1956 |
|
| 1957 | public StructureTemplateManager getStructureTemplateManager() {
|
| 1958 | return this.structureTemplateManager;
|
| 1959 | }
|
| 1960 |
|
| 1961 | public WorldData getWorldData() {
|
| 1962 | return this.worldData;
|
| 1963 | }
|
| 1964 |
|
| 1965 | public RegistryAccess.Frozen registryAccess() {
|
| 1966 | return this.registries.compositeAccess();
|
| 1967 | }
|
| 1968 |
|
| 1969 | public LayeredRegistryAccess<RegistryLayer> registries() {
|
| 1970 | return this.registries;
|
| 1971 | }
|
| 1972 |
|
| 1973 | public ReloadableServerRegistries.Holder reloadableRegistries() {
|
| 1974 | return this.resources.managers.fullRegistries();
|
| 1975 | }
|
| 1976 |
|
| 1977 | public TextFilter createTextFilterForPlayer(final ServerPlayer player) {
|
| 1978 | return TextFilter.DUMMY;
|
| 1979 | }
|
| 1980 |
|
| 1981 | public ServerPlayerGameMode createGameModeForPlayer(final ServerPlayer player) {
|
| 1982 | return this.isDemo() ? new DemoMode(player) : new ServerPlayerGameMode(player);
|
| 1983 | }
|
| 1984 |
|
| 1985 | public @Nullable GameType getForcedGameType() {
|
| 1986 | return null;
|
| 1987 | }
|
| 1988 |
|
| 1989 | public boolean forceGameMode() {
|
| 1990 | return false;
|
| 1991 | }
|
| 1992 |
|
| 1993 | public void setForceGameMode(final boolean forceGameMode) {
|
| 1994 | }
|
| 1995 |
|
| 1996 | public ResourceManager getResourceManager() {
|
| 1997 | return this.resources.resourceManager;
|
| 1998 | }
|
| 1999 |
|
| 2000 | public boolean isCurrentlySaving() {
|
| 2001 | return this.isSaving;
|
| 2002 | }
|
| 2003 |
|
| 2004 | public boolean isTimeProfilerRunning() {
|
| 2005 | return this.debugCommandProfilerDelayStart || this.debugCommandProfiler != null;
|
| 2006 | }
|
| 2007 |
|
| 2008 | public void startTimeProfiler() {
|
| 2009 | this.debugCommandProfilerDelayStart = true;
|
| 2010 | }
|
| 2011 |
|
| 2012 | public ProfileResults stopTimeProfiler() {
|
| 2013 | if (this.debugCommandProfiler == null) {
|
| 2014 | return EmptyProfileResults.EMPTY;
|
| 2015 | }
|
| 2016 |
|
| 2017 | ProfileResults results = this.debugCommandProfiler.stop(Util.getNanos(), this.tickCount);
|
| 2018 | this.debugCommandProfiler = null;
|
| 2019 | return results;
|
| 2020 | }
|
| 2021 |
|
| 2022 | public int getMaxChainedNeighborUpdates() {
|
| 2023 | return 1000000;
|
| 2024 | }
|
| 2025 |
|
| 2026 | public void logChatMessage(final Component message, final ChatType.Bound chatType, final @Nullable String tag) {
|
| 2027 | String decoratedMessage = chatType.decorate(message).getString();
|
| 2028 | if (tag != null) {
|
| 2029 | LOGGER.info("[{}] {}", tag, decoratedMessage);
|
| 2030 | } else {
|
| 2031 | LOGGER.info("{}", decoratedMessage);
|
| 2032 | }
|
| 2033 | }
|
| 2034 |
|
| 2035 | public ChatDecorator getChatDecorator() {
|
| 2036 | return ChatDecorator.PLAIN;
|
| 2037 | }
|
| 2038 |
|
| 2039 | public boolean logIPs() {
|
| 2040 | return true;
|
| 2041 | }
|
| 2042 |
|
| 2043 | public void handleCustomClickAction(final Identifier id, final Optional<Tag> payload) {
|
| 2044 | LOGGER.debug("Received custom click action {} with payload {}", id, payload.orElse(null));
|
| 2045 | }
|
| 2046 |
|
| 2047 | public LevelLoadListener getLevelLoadListener() {
|
| 2048 | return this.levelLoadListener;
|
| 2049 | }
|
| 2050 |
|
| 2051 | public boolean setAutoSave(final boolean enable) {
|
| 2052 | boolean success = false;
|
| 2053 |
|
| 2054 | for (ServerLevel level : this.getAllLevels()) {
|
| 2055 | if (level != null && level.noSave == enable) {
|
| 2056 | level.noSave = !enable;
|
| 2057 | success = true;
|
| 2058 | }
|
| 2059 | }
|
| 2060 |
|
| 2061 | return success;
|
| 2062 | }
|
| 2063 |
|
| 2064 | public boolean isAutoSave() {
|
| 2065 | for (ServerLevel level : this.getAllLevels()) {
|
| 2066 | if (level != null && !level.noSave) {
|
| 2067 | return true;
|
| 2068 | }
|
| 2069 | }
|
| 2070 |
|
| 2071 | return false;
|
| 2072 | }
|
| 2073 |
|
| 2074 | public <T> void onGameRuleChanged(final GameRule<T> rule, final T value) {
|
| 2075 | this.notificationManager().onGameRuleChanged(rule, value);
|
| 2076 | if (rule == GameRules.REDUCED_DEBUG_INFO) {
|
| 2077 | byte event = (byte)((Boolean)value ? 22 : 23);
|
| 2078 |
|
| 2079 | for (ServerPlayer player : this.getPlayerList().getPlayers()) {
|
| 2080 | player.connection.send(new ClientboundEntityEventPacket(player, event));
|
| 2081 | }
|
| 2082 | } else if (rule == GameRules.LIMITED_CRAFTING || rule == GameRules.IMMEDIATE_RESPAWN) {
|
| 2083 | ClientboundGameEventPacket.Type eventType = rule == GameRules.LIMITED_CRAFTING
|
| 2084 | ? ClientboundGameEventPacket.LIMITED_CRAFTING
|
| 2085 | : ClientboundGameEventPacket.IMMEDIATE_RESPAWN;
|
| 2086 | ClientboundGameEventPacket packet = new ClientboundGameEventPacket(eventType, (Boolean)value ? 1.0F : 0.0F);
|
| 2087 | this.getPlayerList().getPlayers().forEach(playerx -> playerx.connection.send(packet));
|
| 2088 | } else if (rule == GameRules.LOCATOR_BAR) {
|
| 2089 | this.getAllLevels().forEach(level -> {
|
| 2090 | ServerWaypointManager waypointManager = level.getWaypointManager();
|
| 2091 | if ((Boolean)value) {
|
| 2092 | level.players().forEach(waypointManager::updatePlayer);
|
| 2093 | } else {
|
| 2094 | waypointManager.breakAllConnections();
|
| 2095 | }
|
| 2096 | });
|
| 2097 | } else if (rule == GameRules.SPAWN_MONSTERS) {
|
| 2098 | this.updateMobSpawningFlags();
|
| 2099 | } else if (rule == GameRules.ADVANCE_TIME) {
|
| 2100 | this.getPlayerList().broadcastAll(this.clockManager().createFullSyncPacket());
|
| 2101 | }
|
| 2102 | }
|
| 2103 |
|
| 2104 | @Deprecated
|
| 2105 | public GameRules getGlobalGameRules() {
|
| 2106 | return this.overworld().getGameRules();
|
| 2107 | }
|
| 2108 |
|
| 2109 | public SavedDataStorage getDataStorage() {
|
| 2110 | return this.savedDataStorage;
|
| 2111 | }
|
| 2112 |
|
| 2113 | public TimerQueue<MinecraftServer> getScheduledEvents() {
|
| 2114 | return this.scheduledEvents;
|
| 2115 | }
|
| 2116 |
|
| 2117 | public GameRules getGameRules() {
|
| 2118 | return this.gameRules;
|
| 2119 | }
|
| 2120 |
|
| 2121 | public boolean acceptsTransfers() {
|
| 2122 | return false;
|
| 2123 | }
|
| 2124 |
|
| 2125 | private void storeChunkIoError(final CrashReport report, final ChunkPos pos, final RegionStorageInfo storageInfo) {
|
| 2126 | Util.ioPool().execute(() -> {
|
| 2127 | try {
|
| 2128 | Path debugDir = this.getFile("debug");
|
| 2129 | FileUtil.createDirectoriesSafe(debugDir);
|
| 2130 | String sanitizedLevelName = FileUtil.sanitizeName(storageInfo.level());
|
| 2131 | Path reportFile = debugDir.resolve("chunk-" + sanitizedLevelName + "-" + Util.getFilenameFormattedDateTime() + "-server.txt");
|
| 2132 | FileStore fileStore = Files.getFileStore(debugDir);
|
| 2133 | long remainingSpace = fileStore.getUsableSpace();
|
| 2134 | if (remainingSpace < 8192L) {
|
| 2135 | LOGGER.warn("Not storing chunk IO report due to low space on drive {}", fileStore.name());
|
| 2136 | return;
|
| 2137 | }
|
| 2138 |
|
| 2139 | CrashReportCategory category = report.addCategory("Chunk Info");
|
| 2140 | category.setDetail("Level", storageInfo::level);
|
| 2141 | category.setDetail("Dimension", () -> storageInfo.dimension().identifier().toString());
|
| 2142 | category.setDetail("Storage", storageInfo::type);
|
| 2143 | category.setDetail("Position", pos::toString);
|
| 2144 | report.saveToFile(reportFile, ReportType.CHUNK_IO_ERROR);
|
| 2145 | LOGGER.info("Saved details to {}", report.getSaveFile());
|
| 2146 | } catch (Exception e) {
|
| 2147 | LOGGER.warn("Failed to store chunk IO exception", e);
|
| 2148 | }
|
| 2149 | });
|
| 2150 | }
|
| 2151 |
|
| 2152 | @Override
|
| 2153 | public void reportChunkLoadFailure(final Throwable throwable, final RegionStorageInfo storageInfo, final ChunkPos pos) {
|
| 2154 | LOGGER.error("Failed to load chunk {},{}", pos.x(), pos.z(), throwable);
|
| 2155 | this.suppressedExceptions.addEntry("chunk/load", throwable);
|
| 2156 | this.storeChunkIoError(CrashReport.forThrowable(throwable, "Chunk load failure"), pos, storageInfo);
|
| 2157 | this.warnOnLowDiskSpace();
|
| 2158 | }
|
| 2159 |
|
| 2160 | @Override
|
| 2161 | public void reportChunkSaveFailure(final Throwable throwable, final RegionStorageInfo storageInfo, final ChunkPos pos) {
|
| 2162 | LOGGER.error("Failed to save chunk {},{}", pos.x(), pos.z(), throwable);
|
| 2163 | this.suppressedExceptions.addEntry("chunk/save", throwable);
|
| 2164 | this.storeChunkIoError(CrashReport.forThrowable(throwable, "Chunk save failure"), pos, storageInfo);
|
| 2165 | this.warnOnLowDiskSpace();
|
| 2166 | }
|
| 2167 |
|
| 2168 | protected void warnOnLowDiskSpace() {
|
| 2169 | if (this.storageSource.checkForLowDiskSpace()) {
|
| 2170 | this.sendLowDiskSpaceWarning();
|
| 2171 | }
|
| 2172 | }
|
| 2173 |
|
| 2174 | public void sendLowDiskSpaceWarning() {
|
| 2175 | LOGGER.warn("Low disk space! Might not be able to save the world.");
|
| 2176 | }
|
| 2177 |
|
| 2178 | public void reportPacketHandlingException(final Throwable throwable, final PacketType<?> packetType) {
|
| 2179 | this.suppressedExceptions.addEntry("packet/" + packetType, throwable);
|
| 2180 | }
|
| 2181 |
|
| 2182 | public ServerLinks serverLinks() {
|
| 2183 | return ServerLinks.EMPTY;
|
| 2184 | }
|
| 2185 |
|
| 2186 | protected int pauseWhenEmptySeconds() {
|
| 2187 | return 0;
|
| 2188 | }
|
| 2189 |
|
| 2190 | public PacketProcessor packetProcessor() {
|
| 2191 | return this.packetProcessor;
|
| 2192 | }
|
| 2193 |
|
| 2194 | public ServerDebugSubscribers debugSubscribers() {
|
| 2195 | return this.debugSubscribers;
|
| 2196 | }
|
| 2197 |
|
| 2198 | public enum MultiplayerScope {
|
| 2199 | OFF("off"),
|
| 2200 | LAN("lan");
|
| 2201 |
|
| 2202 | private final Component translatable;
|
| 2203 | private final Component tooltip;
|
| 2204 |
|
| 2205 | MultiplayerScope(final String key) {
|
| 2206 | this.translatable = Component.translatable("menu.multiplayerOptions.network." + key);
|
| 2207 | this.tooltip = Component.translatable("menu.multiplayerOptions.network." + key + ".tooltip");
|
| 2208 | }
|
| 2209 |
|
| 2210 | public Component getDisplayName() {
|
| 2211 | return this.translatable;
|
| 2212 | }
|
| 2213 |
|
| 2214 | public Component getTooltip() {
|
| 2215 | return this.tooltip;
|
| 2216 | }
|
| 2217 | }
|
| 2218 |
|
| 2219 | private record ReloadableResources(CloseableResourceManager resourceManager, ReloadableServerResources managers) implements AutoCloseable {
|
| 2220 | @Override
|
| 2221 | public void close() {
|
| 2222 | this.resourceManager.close();
|
| 2223 | }
|
| 2224 | }
|
| 2225 |
|
| 2226 | public record ServerResourcePackInfo(UUID id, String url, String hash, boolean isRequired, @Nullable Component prompt) {
|
| 2227 | }
|
| 2228 |
|
| 2229 | private static class TimeProfiler {
|
| 2230 | private final long startNanos;
|
| 2231 | private final int startTick;
|
| 2232 |
|
| 2233 | private TimeProfiler(final long startNanos, final int startTick) {
|
| 2234 | this.startNanos = startNanos;
|
| 2235 | this.startTick = startTick;
|
| 2236 | }
|
| 2237 |
|
| 2238 | private ProfileResults stop(final long stopNanos, final int stopTick) {
|
| 2239 | return new ProfileResults() {
|
| 2240 | @Override
|
| 2241 | public List<ResultField> getTimes(final String path) {
|
| 2242 | return Collections.emptyList();
|
| 2243 | }
|
| 2244 |
|
| 2245 | @Override
|
| 2246 | public boolean saveResults(final Path file) {
|
| 2247 | return false;
|
| 2248 | }
|
| 2249 |
|
| 2250 | @Override
|
| 2251 | public long getStartTimeNano() {
|
| 2252 | return TimeProfiler.this.startNanos;
|
| 2253 | }
|
| 2254 |
|
| 2255 | @Override
|
| 2256 | public int getStartTimeTicks() {
|
| 2257 | return TimeProfiler.this.startTick;
|
| 2258 | }
|
| 2259 |
|
| 2260 | @Override
|
| 2261 | public long getEndTimeNano() {
|
| 2262 | return stopNanos;
|
| 2263 | }
|
| 2264 |
|
| 2265 | @Override
|
| 2266 | public int getEndTimeTicks() {
|
| 2267 | return stopTick;
|
| 2268 | }
|
| 2269 |
|
| 2270 | @Override
|
| 2271 | public String getProfilerResults() {
|
| 2272 | return "";
|
| 2273 | }
|
| 2274 | };
|
| 2275 | }
|
| 2276 | }
|
| 2277 | }
|
| 2278 |
|