PaperMC/paper-server/nms-patches/net/minecraft/server/MinecraftServer.patch
2022-03-04 18:53:19 +11:00

746 lines
38 KiB
Diff

--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -163,6 +163,26 @@
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
+// CraftBukkit start
+import com.mojang.serialization.DynamicOps;
+import com.mojang.serialization.Lifecycle;
+import jline.console.ConsoleReader;
+import joptsimple.OptionSet;
+import net.minecraft.nbt.DynamicOpsNBT;
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.server.dedicated.DedicatedServer;
+import net.minecraft.server.dedicated.DedicatedServerProperties;
+import net.minecraft.util.datafix.DataConverterRegistry;
+import net.minecraft.world.level.biome.WorldChunkManager;
+import net.minecraft.world.level.levelgen.ChunkGeneratorAbstract;
+import net.minecraft.world.level.storage.WorldDataServer;
+import org.bukkit.Bukkit;
+import org.bukkit.craftbukkit.CraftServer;
+import org.bukkit.craftbukkit.Main;
+import org.bukkit.craftbukkit.generator.CustomWorldChunkManager;
+import org.bukkit.event.server.ServerLoadEvent;
+// CraftBukkit end
+
public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant<TickTask> implements ICommandListener, AutoCloseable {
public static final Logger LOGGER = LogUtils.getLogger();
@@ -255,6 +275,21 @@
protected SaveData worldData;
private volatile boolean isSaving;
+ // CraftBukkit start
+ public final DataPackConfiguration datapackconfiguration;
+ public final DynamicOps<NBTBase> registryreadops;
+ public org.bukkit.craftbukkit.CraftServer server;
+ public OptionSet options;
+ public org.bukkit.command.ConsoleCommandSender console;
+ public org.bukkit.command.RemoteConsoleCommandSender remoteConsole;
+ public ConsoleReader reader;
+ public static int currentTick = (int) (System.currentTimeMillis() / 50);
+ public java.util.Queue<Runnable> processQueue = new java.util.concurrent.ConcurrentLinkedQueue<Runnable>();
+ public int autosavePeriod;
+ public CommandDispatcher vanillaCommandDispatcher;
+ private boolean forceTicks;
+ // CraftBukkit end
+
public static <S extends MinecraftServer> S spin(Function<Thread, S> function) {
AtomicReference<S> atomicreference = new AtomicReference();
Thread thread = new Thread(() -> {
@@ -268,14 +303,14 @@
thread.setPriority(8);
}
- S s0 = (MinecraftServer) function.apply(thread);
+ S s0 = function.apply(thread); // CraftBukkit - decompile error
atomicreference.set(s0);
thread.start();
return s0;
}
- public MinecraftServer(Thread thread, Convertable.ConversionSession convertable_conversionsession, ResourcePackRepository resourcepackrepository, WorldStem worldstem, Proxy proxy, DataFixer datafixer, @Nullable MinecraftSessionService minecraftsessionservice, @Nullable GameProfileRepository gameprofilerepository, @Nullable UserCache usercache, WorldLoadListenerFactory worldloadlistenerfactory) {
+ public MinecraftServer(OptionSet options, DataPackConfiguration datapackconfiguration, DynamicOps<NBTBase> registryreadops, Thread thread, Convertable.ConversionSession convertable_conversionsession, ResourcePackRepository resourcepackrepository, WorldStem worldstem, Proxy proxy, DataFixer datafixer, @Nullable MinecraftSessionService minecraftsessionservice, @Nullable GameProfileRepository gameprofilerepository, @Nullable UserCache usercache, WorldLoadListenerFactory worldloadlistenerfactory) {
super("Server");
this.metricsRecorder = InactiveMetricsRecorder.INSTANCE;
this.profiler = this.metricsRecorder.getProfiler();
@@ -287,7 +322,7 @@
this.status = new ServerPing();
this.random = new Random();
this.port = -1;
- this.levels = Maps.newLinkedHashMap();
+ this.levels = Maps.newLinkedHashMap(); // CraftBukkit - keep order, k+v already use identity methods
this.running = true;
this.tickTimes = new long[100];
this.resourcePack = "";
@@ -317,13 +352,41 @@
this.structureManager = new DefinedStructureManager(worldstem.resourceManager(), convertable_conversionsession, datafixer);
this.serverThread = thread;
this.executor = SystemUtils.backgroundExecutor();
+ // CraftBukkit start
+ this.options = options;
+ this.datapackconfiguration = datapackconfiguration;
+ this.registryreadops = registryreadops;
+ this.vanillaCommandDispatcher = worldstem.dataPackResources().commands; // CraftBukkit
+ // Try to see if we're actually running in a terminal, disable jline if not
+ if (System.console() == null && System.getProperty("jline.terminal") == null) {
+ System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
+ Main.useJline = false;
+ }
+
+ try {
+ reader = new ConsoleReader(System.in, System.out);
+ reader.setExpandEvents(false); // Avoid parsing exceptions for uncommonly used event designators
+ } catch (Throwable e) {
+ try {
+ // Try again with jline disabled for Windows users without C++ 2008 Redistributable
+ System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
+ System.setProperty("user.language", "en");
+ Main.useJline = false;
+ reader = new ConsoleReader(System.in, System.out);
+ reader.setExpandEvents(false);
+ } catch (IOException ex) {
+ LOGGER.warn((String) null, ex);
+ }
+ }
+ Runtime.getRuntime().addShutdownHook(new org.bukkit.craftbukkit.util.ServerShutdownThread(this));
}
+ // CraftBukkit end
private void readScoreboard(WorldPersistentData worldpersistentdata) {
ScoreboardServer scoreboardserver = this.getScoreboard();
Objects.requireNonNull(scoreboardserver);
- Function function = scoreboardserver::createData;
+ Function<net.minecraft.nbt.NBTTagCompound, net.minecraft.world.scores.PersistentScoreboard> function = scoreboardserver::createData; // CraftBukkit - decompile error
ScoreboardServer scoreboardserver1 = this.getScoreboard();
Objects.requireNonNull(scoreboardserver1);
@@ -332,7 +395,7 @@
protected abstract boolean initServer() throws IOException;
- protected void loadLevel() {
+ protected void loadLevel(String s) { // CraftBukkit
if (!JvmProfiler.INSTANCE.isRunning()) {
;
}
@@ -340,13 +403,8 @@
boolean flag = false;
ProfiledDuration profiledduration = JvmProfiler.INSTANCE.onWorldLoadedStarted();
- this.detectBundledResources();
- this.worldData.setModdedInfo(this.getServerModName(), this.getModdedStatus().shouldReportAsModified());
- WorldLoadListener worldloadlistener = this.progressListenerFactory.create(11);
+ loadWorld0(s); // CraftBukkit
- this.createLevels(worldloadlistener);
- this.forceDifficulty();
- this.prepareLevels(worldloadlistener);
if (profiledduration != null) {
profiledduration.finish();
}
@@ -361,36 +419,206 @@
}
- protected void forceDifficulty() {}
+ // CraftBukkit start
+ private void loadWorld0(String s) {
+ Convertable.ConversionSession worldSession = this.storageSource;
+ IRegistryCustom.Dimension iregistrycustom_dimension = this.registryHolder;
+ WorldDataServer overworldData = (WorldDataServer) worldSession.getDataTag(registryreadops, datapackconfiguration, iregistrycustom_dimension.allElementsLifecycle());
+ if (overworldData == null) {
+ WorldSettings worldsettings;
+ GeneratorSettings generatorsettings;
+
+ if (this.isDemo()) {
+ worldsettings = MinecraftServer.DEMO_SETTINGS;
+ generatorsettings = GeneratorSettings.demoSettings(iregistrycustom_dimension);
+ } else {
+ DedicatedServerProperties dedicatedserverproperties = ((DedicatedServer) this).getProperties();
- protected void createLevels(WorldLoadListener worldloadlistener) {
- IWorldDataServer iworlddataserver = this.worldData.overworldData();
- GeneratorSettings generatorsettings = this.worldData.worldGenSettings();
- boolean flag = generatorsettings.isDebug();
- long i = generatorsettings.seed();
- long j = BiomeManager.obfuscateSeed(i);
- List<MobSpawner> list = ImmutableList.of(new MobSpawnerPhantom(), new MobSpawnerPatrol(), new MobSpawnerCat(), new VillageSiege(), new MobSpawnerTrader(iworlddataserver));
- IRegistry<WorldDimension> iregistry = generatorsettings.dimensions();
- WorldDimension worlddimension = (WorldDimension) iregistry.get(WorldDimension.OVERWORLD);
- Holder holder;
- Object object;
-
- if (worlddimension == null) {
- holder = this.registryAccess().registryOrThrow(IRegistry.DIMENSION_TYPE_REGISTRY).getOrCreateHolder(DimensionManager.OVERWORLD_LOCATION);
- object = GeneratorSettings.makeDefaultOverworld(this.registryAccess(), (new Random()).nextLong());
- } else {
- holder = worlddimension.typeHolder();
- object = worlddimension.generator();
+ worldsettings = new WorldSettings(dedicatedserverproperties.levelName, dedicatedserverproperties.gamemode, dedicatedserverproperties.hardcore, dedicatedserverproperties.difficulty, false, new GameRules(), datapackconfiguration);
+ generatorsettings = options.has("bonusChest") ? dedicatedserverproperties.getWorldGenSettings(iregistrycustom_dimension).withBonusChest() : dedicatedserverproperties.getWorldGenSettings(iregistrycustom_dimension);
+ }
+
+ overworldData = new WorldDataServer(worldsettings, generatorsettings, Lifecycle.stable());
}
- WorldServer worldserver = new WorldServer(this, this.executor, this.storageSource, iworlddataserver, World.OVERWORLD, holder, worldloadlistener, (ChunkGenerator) object, flag, j, list, true);
+ GeneratorSettings overworldSettings = overworldData.worldGenSettings();
+ IRegistry<WorldDimension> iregistry = overworldSettings.dimensions();
+ for (WorldDimension worldDimension : iregistry) {
+ ResourceKey<WorldDimension> dimensionKey = iregistry.getResourceKey(worldDimension).get();
+
+ WorldServer world;
+ int dimension = 0;
+
+ if (dimensionKey == WorldDimension.NETHER) {
+ if (isNetherEnabled()) {
+ dimension = -1;
+ } else {
+ continue;
+ }
+ } else if (dimensionKey == WorldDimension.END) {
+ if (server.getAllowEnd()) {
+ dimension = 1;
+ } else {
+ continue;
+ }
+ } else if (dimensionKey != WorldDimension.OVERWORLD) {
+ dimension = -999;
+ }
+
+ String worldType = (dimension == -999) ? dimensionKey.location().getNamespace() + "_" + dimensionKey.location().getPath() : org.bukkit.World.Environment.getEnvironment(dimension).toString().toLowerCase();
+ String name = (dimensionKey == WorldDimension.OVERWORLD) ? s : s + "_" + worldType;
+ if (dimension != 0) {
+ File newWorld = Convertable.getStorageFolder(new File(name).toPath(), dimensionKey).toFile();
+ File oldWorld = Convertable.getStorageFolder(new File(s).toPath(), dimensionKey).toFile();
+ File oldLevelDat = new File(new File(s), "level.dat"); // The data folders exist on first run as they are created in the PersistentCollection constructor above, but the level.dat won't
+
+ if (!newWorld.isDirectory() && oldWorld.isDirectory() && oldLevelDat.isFile()) {
+ MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder required ----");
+ MinecraftServer.LOGGER.info("Unfortunately due to the way that Minecraft implemented multiworld support in 1.6, Bukkit requires that you move your " + worldType + " folder to a new location in order to operate correctly.");
+ MinecraftServer.LOGGER.info("We will move this folder for you, but it will mean that you need to move it back should you wish to stop using Bukkit in the future.");
+ MinecraftServer.LOGGER.info("Attempting to move " + oldWorld + " to " + newWorld + "...");
+
+ if (newWorld.exists()) {
+ MinecraftServer.LOGGER.warn("A file or folder already exists at " + newWorld + "!");
+ MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+ } else if (newWorld.getParentFile().mkdirs()) {
+ if (oldWorld.renameTo(newWorld)) {
+ MinecraftServer.LOGGER.info("Success! To restore " + worldType + " in the future, simply move " + newWorld + " to " + oldWorld);
+ // Migrate world data too.
+ try {
+ com.google.common.io.Files.copy(oldLevelDat, new File(new File(name), "level.dat"));
+ org.apache.commons.io.FileUtils.copyDirectory(new File(new File(s), "data"), new File(new File(name), "data"));
+ } catch (IOException exception) {
+ MinecraftServer.LOGGER.warn("Unable to migrate world data.");
+ }
+ MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder complete ----");
+ } else {
+ MinecraftServer.LOGGER.warn("Could not move folder " + oldWorld + " to " + newWorld + "!");
+ MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+ }
+ } else {
+ MinecraftServer.LOGGER.warn("Could not create path for " + newWorld + "!");
+ MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+ }
+ }
- this.levels.put(World.OVERWORLD, worldserver);
- WorldPersistentData worldpersistentdata = worldserver.getDataStorage();
+ try {
+ worldSession = Convertable.createDefault(server.getWorldContainer().toPath()).createAccess(name, dimensionKey);
+ } catch (IOException ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ org.bukkit.generator.ChunkGenerator gen = this.server.getGenerator(name);
+ org.bukkit.generator.BiomeProvider biomeProvider = this.server.getBiomeProvider(name);
+
+ WorldDataServer worlddata = (WorldDataServer) worldSession.getDataTag((DynamicOps) registryreadops, datapackconfiguration, iregistrycustom_dimension.allElementsLifecycle());
+ if (worlddata == null) {
+ WorldSettings worldsettings;
+ GeneratorSettings generatorsettings;
+
+ if (this.isDemo()) {
+ worldsettings = MinecraftServer.DEMO_SETTINGS;
+ generatorsettings = GeneratorSettings.demoSettings(iregistrycustom_dimension);
+ } else {
+ DedicatedServerProperties dedicatedserverproperties = ((DedicatedServer) this).getProperties();
+
+ worldsettings = new WorldSettings(dedicatedserverproperties.levelName, dedicatedserverproperties.gamemode, dedicatedserverproperties.hardcore, dedicatedserverproperties.difficulty, false, new GameRules(), datapackconfiguration);
+ generatorsettings = options.has("bonusChest") ? dedicatedserverproperties.getWorldGenSettings(iregistrycustom_dimension).withBonusChest() : dedicatedserverproperties.getWorldGenSettings(iregistrycustom_dimension);
+ }
+
+ worlddata = new WorldDataServer(worldsettings, generatorsettings, Lifecycle.stable());
+ }
+ worlddata.checkName(name); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to take the last loaded world as respawn (in this case the end)
+ if (options.has("forceUpgrade")) {
+ net.minecraft.server.Main.forceUpgrade(worldSession, DataConverterRegistry.getDataFixer(), options.has("eraseCache"), () -> {
+ return true;
+ }, worlddata.worldGenSettings());
+ }
+
+ IWorldDataServer iworlddataserver = worlddata;
+ GeneratorSettings generatorsettings = worlddata.worldGenSettings();
+ boolean flag = generatorsettings.isDebug();
+ long i = generatorsettings.seed();
+ long j = BiomeManager.obfuscateSeed(i);
+ List<MobSpawner> list = ImmutableList.of(new MobSpawnerPhantom(), new MobSpawnerPatrol(), new MobSpawnerCat(), new VillageSiege(), new MobSpawnerTrader(iworlddataserver));
+ WorldDimension worlddimension = (WorldDimension) iregistry.get(dimensionKey);
+ Holder<DimensionManager> holder;
+ ChunkGenerator chunkgenerator;
+
+ if (worlddimension == null) {
+ holder = this.registryAccess().registryOrThrow(IRegistry.DIMENSION_TYPE_REGISTRY).getOrCreateHolder(DimensionManager.OVERWORLD_LOCATION);
+ chunkgenerator = GeneratorSettings.makeDefaultOverworld(this.registryHolder, (new Random()).nextLong());
+ } else {
+ holder = worlddimension.typeHolder();
+ chunkgenerator = worlddimension.generator();
+ }
+
+ org.bukkit.generator.WorldInfo worldInfo = new org.bukkit.craftbukkit.generator.CraftWorldInfo(iworlddataserver, worldSession, org.bukkit.World.Environment.getEnvironment(dimension), holder.value());
+ if (biomeProvider == null && gen != null) {
+ biomeProvider = gen.getDefaultBiomeProvider(worldInfo);
+ }
+
+ if (biomeProvider != null) {
+ WorldChunkManager worldChunkManager = new CustomWorldChunkManager(worldInfo, biomeProvider, registryHolder.ownedRegistryOrThrow(IRegistry.BIOME_REGISTRY));
+ if (chunkgenerator instanceof ChunkGeneratorAbstract cga) {
+ chunkgenerator = new ChunkGeneratorAbstract(cga.structureSets, cga.noises, worldChunkManager, chunkgenerator.ringPlacementSeed, cga.settings);
+ }
+ }
+
+ ResourceKey<World> worldKey = ResourceKey.create(IRegistry.DIMENSION_REGISTRY, dimensionKey.location());
+
+ if (dimensionKey == WorldDimension.OVERWORLD) {
+ this.worldData = worlddata;
+ this.worldData.setGameType(((DedicatedServer) this).getProperties().gamemode); // From DedicatedServer.init
+
+ WorldLoadListener worldloadlistener = this.progressListenerFactory.create(11);
+
+ world = new WorldServer(this, this.executor, worldSession, iworlddataserver, worldKey, holder, worldloadlistener, chunkgenerator, flag, j, list, true, org.bukkit.World.Environment.getEnvironment(dimension), gen, biomeProvider);
+ WorldPersistentData worldpersistentdata = world.getDataStorage();
+ this.readScoreboard(worldpersistentdata);
+ this.server.scoreboardManager = new org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager(this, world.getScoreboard());
+ this.commandStorage = new PersistentCommandStorage(worldpersistentdata);
+ } else {
+ WorldLoadListener worldloadlistener = this.progressListenerFactory.create(11);
+ world = new WorldServer(this, this.executor, worldSession, iworlddataserver, worldKey, holder, worldloadlistener, chunkgenerator, flag, j, ImmutableList.of(), true, org.bukkit.World.Environment.getEnvironment(dimension), gen, biomeProvider);
+ }
- this.readScoreboard(worldpersistentdata);
- this.commandStorage = new PersistentCommandStorage(worldpersistentdata);
+ worlddata.setModdedInfo(this.getServerModName(), this.getModdedStatus().shouldReportAsModified());
+ this.initWorld(world, worlddata, worldData, worlddata.worldGenSettings());
+
+ this.levels.put(world.dimension(), world);
+ this.getPlayerList().addWorldborderListener(world);
+
+ if (worlddata.getCustomBossEvents() != null) {
+ this.getCustomBossEvents().load(worlddata.getCustomBossEvents());
+ }
+ }
+ this.forceDifficulty();
+ for (WorldServer worldserver : this.getAllLevels()) {
+ this.prepareLevels(worldserver.getChunkSource().chunkMap.progressListener, worldserver);
+ worldserver.entityManager.tick(); // SPIGOT-6526: Load pending entities so they are available to the API
+ this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldLoadEvent(worldserver.getWorld()));
+ }
+
+ this.server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.POSTWORLD);
+ this.server.getPluginManager().callEvent(new ServerLoadEvent(ServerLoadEvent.LoadType.STARTUP));
+ this.connection.acceptConnections();
+ }
+ // CraftBukkit end
+
+ protected void forceDifficulty() {}
+
+ // CraftBukkit start
+ public void initWorld(WorldServer worldserver, IWorldDataServer iworlddataserver, SaveData saveData, GeneratorSettings generatorsettings) {
+ boolean flag = generatorsettings.isDebug();
+ // CraftBukkit start
+ if (worldserver.generator != null) {
+ worldserver.getWorld().getPopulators().addAll(worldserver.generator.getDefaultPopulators(worldserver.getWorld()));
+ }
WorldBorder worldborder = worldserver.getWorldBorder();
+ worldborder.applySettings(iworlddataserver.getWorldBorder()); // CraftBukkit - move up so that WorldBorder is set during WorldInitEvent
+ this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldInitEvent(worldserver.getWorld())); // CraftBukkit - SPIGOT-5569: Call WorldInitEvent before any chunks are generated
if (!iworlddataserver.isInitialized()) {
try {
@@ -414,31 +642,8 @@
iworlddataserver.setInitialized(true);
}
- this.getPlayerList().addWorldborderListener(worldserver);
- if (this.worldData.getCustomBossEvents() != null) {
- this.getCustomBossEvents().load(this.worldData.getCustomBossEvents());
- }
-
- Iterator iterator = iregistry.entrySet().iterator();
-
- while (iterator.hasNext()) {
- Entry<ResourceKey<WorldDimension>, WorldDimension> entry = (Entry) iterator.next();
- ResourceKey<WorldDimension> resourcekey = (ResourceKey) entry.getKey();
-
- if (resourcekey != WorldDimension.OVERWORLD) {
- ResourceKey<World> resourcekey1 = ResourceKey.create(IRegistry.DIMENSION_REGISTRY, resourcekey.location());
- Holder<DimensionManager> holder1 = ((WorldDimension) entry.getValue()).typeHolder();
- ChunkGenerator chunkgenerator = ((WorldDimension) entry.getValue()).generator();
- SecondaryWorldData secondaryworlddata = new SecondaryWorldData(this.worldData, iworlddataserver);
- WorldServer worldserver1 = new WorldServer(this, this.executor, this.storageSource, secondaryworlddata, resourcekey1, holder1, worldloadlistener, chunkgenerator, flag, j, ImmutableList.of(), false);
-
- worldborder.addListener(new IWorldBorderListener.a(worldserver1.getWorldBorder()));
- this.levels.put(resourcekey1, worldserver1);
- }
- }
-
- worldborder.applySettings(iworlddataserver.getWorldBorder());
}
+ // CraftBukkit end
private static void setInitialSpawn(WorldServer worldserver, IWorldDataServer iworlddataserver, boolean flag, boolean flag1) {
if (flag1) {
@@ -446,6 +651,21 @@
} else {
ChunkGenerator chunkgenerator = worldserver.getChunkSource().getGenerator();
ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(chunkgenerator.climateSampler().findSpawnPosition());
+ // CraftBukkit start
+ if (worldserver.generator != null) {
+ Random rand = new Random(worldserver.getSeed());
+ org.bukkit.Location spawn = worldserver.generator.getFixedSpawnLocation(worldserver.getWorld(), rand);
+
+ if (spawn != null) {
+ if (spawn.getWorld() != worldserver.getWorld()) {
+ throw new IllegalStateException("Cannot set spawn point for " + iworlddataserver.getLevelName() + " to be in another world (" + spawn.getWorld().getName() + ")");
+ } else {
+ iworlddataserver.setSpawn(new BlockPosition(spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ()), spawn.getYaw());
+ return;
+ }
+ }
+ }
+ // CraftBukkit end
int i = chunkgenerator.getSpawnHeight(worldserver);
if (i < worldserver.getMinBuildHeight()) {
@@ -503,8 +723,11 @@
iworlddataserver.setGameType(EnumGamemode.SPECTATOR);
}
- public void prepareLevels(WorldLoadListener worldloadlistener) {
- WorldServer worldserver = this.overworld();
+ // CraftBukkit start
+ public void prepareLevels(WorldLoadListener worldloadlistener, WorldServer worldserver) {
+ // WorldServer worldserver = this.overworld();
+ this.forceTicks = true;
+ // CraftBukkit end
MinecraftServer.LOGGER.info("Preparing start region for dimension {}", worldserver.dimension().location());
BlockPosition blockposition = worldserver.getSharedSpawnPos();
@@ -514,19 +737,23 @@
chunkproviderserver.getLightEngine().setTaskPerBatch(500);
this.nextTickTime = SystemUtils.getMillis();
- chunkproviderserver.addRegionTicket(TicketType.START, new ChunkCoordIntPair(blockposition), 11, Unit.INSTANCE);
+ // CraftBukkit start
+ if (worldserver.getWorld().getKeepSpawnInMemory()) {
+ chunkproviderserver.addRegionTicket(TicketType.START, new ChunkCoordIntPair(blockposition), 11, Unit.INSTANCE);
- while (chunkproviderserver.getTickingGenerated() != 441) {
- this.nextTickTime = SystemUtils.getMillis() + 10L;
- this.waitUntilNextTick();
+ while (chunkproviderserver.getTickingGenerated() != 441) {
+ // this.nextTickTime = SystemUtils.getMillis() + 10L;
+ this.executeModerately();
+ }
}
- this.nextTickTime = SystemUtils.getMillis() + 10L;
- this.waitUntilNextTick();
- Iterator iterator = this.levels.values().iterator();
+ // this.nextTickTime = SystemUtils.getMillis() + 10L;
+ this.executeModerately();
+ // Iterator iterator = this.levels.values().iterator();
- while (iterator.hasNext()) {
- WorldServer worldserver1 = (WorldServer) iterator.next();
+ if (true) {
+ WorldServer worldserver1 = worldserver;
+ // CraftBukkit end
ForcedChunk forcedchunk = (ForcedChunk) worldserver1.getDataStorage().get(ForcedChunk::load, "chunks");
if (forcedchunk != null) {
@@ -541,11 +768,18 @@
}
}
- this.nextTickTime = SystemUtils.getMillis() + 10L;
- this.waitUntilNextTick();
+ // CraftBukkit start
+ // this.nextTickTime = SystemUtils.getMillis() + 10L;
+ this.executeModerately();
+ // CraftBukkit end
worldloadlistener.stop();
chunkproviderserver.getLightEngine().setTaskPerBatch(5);
- this.updateMobSpawningFlags();
+ // CraftBukkit start
+ // this.updateMobSpawningFlags();
+ worldserver.setSpawnSettings(this.isSpawningMonsters(), this.isSpawningAnimals());
+
+ this.forceTicks = false;
+ // CraftBukkit end
}
protected void detectBundledResources() {
@@ -590,12 +824,16 @@
worldserver.save((IProgressUpdate) null, flag1, worldserver.noSave && !flag2);
}
+ // CraftBukkit start - moved to WorldServer.save
+ /*
WorldServer worldserver1 = this.overworld();
IWorldDataServer iworlddataserver = this.worldData.overworldData();
iworlddataserver.setWorldBorder(worldserver1.getWorldBorder().createSettings());
this.worldData.setCustomBossEvents(this.getCustomBossEvents().save());
this.storageSource.saveDataTag(this.registryAccess(), this.worldData, this.getPlayerList().getSingleplayerData());
+ */
+ // CraftBukkit end
if (flag1) {
Iterator iterator1 = this.getAllLevels().iterator();
@@ -630,8 +868,29 @@
this.stopServer();
}
+ // CraftBukkit start
+ private boolean hasStopped = false;
+ private final Object stopLock = new Object();
+ public final boolean hasStopped() {
+ synchronized (stopLock) {
+ return hasStopped;
+ }
+ }
+ // CraftBukkit end
+
public void stopServer() {
+ // CraftBukkit start - prevent double stopping on multiple threads
+ synchronized(stopLock) {
+ if (hasStopped) return;
+ hasStopped = true;
+ }
+ // CraftBukkit end
MinecraftServer.LOGGER.info("Stopping server");
+ // CraftBukkit start
+ if (this.server != null) {
+ this.server.disablePlugins();
+ }
+ // CraftBukkit end
if (this.getConnection() != null) {
this.getConnection().stop();
}
@@ -641,6 +900,7 @@
MinecraftServer.LOGGER.info("Saving players");
this.playerList.saveAll();
this.playerList.removeAll();
+ try { Thread.sleep(100); } catch (InterruptedException ex) {} // CraftBukkit - SPIGOT-625 - give server at least a chance to send packets
}
MinecraftServer.LOGGER.info("Saving worlds");
@@ -732,9 +992,10 @@
while (this.running) {
long i = SystemUtils.getMillis() - this.nextTickTime;
- if (i > 2000L && this.nextTickTime - this.lastOverloadWarning >= 15000L) {
+ if (i > 5000L && this.nextTickTime - this.lastOverloadWarning >= 30000L) { // CraftBukkit
long j = i / 50L;
+ if (server.getWarnOnOverload()) // CraftBukkit
MinecraftServer.LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", i, j);
this.nextTickTime += j * 50L;
this.lastOverloadWarning = this.nextTickTime;
@@ -745,6 +1006,7 @@
this.debugCommandProfiler = new MinecraftServer.b(SystemUtils.getNanos(), this.tickCount);
}
+ MinecraftServer.currentTick = (int) (System.currentTimeMillis() / 50); // CraftBukkit
this.nextTickTime += 50L;
this.startMetricsRecordingTick();
this.profiler.push("tick");
@@ -789,6 +1051,12 @@
this.profileCache.clearExecutor();
}
+ // CraftBukkit start - Restore terminal to original settings
+ try {
+ reader.getTerminal().restore();
+ } catch (Exception ignored) {
+ }
+ // CraftBukkit end
this.onServerExit();
}
@@ -822,8 +1090,15 @@
}
private boolean haveTime() {
- return this.runningTask() || SystemUtils.getMillis() < (this.mayHaveDelayedTasks ? this.delayedTasksMaxNextTickTime : this.nextTickTime);
+ // CraftBukkit start
+ return this.forceTicks || this.runningTask() || SystemUtils.getMillis() < (this.mayHaveDelayedTasks ? this.delayedTasksMaxNextTickTime : this.nextTickTime);
+ }
+
+ private void executeModerately() {
+ this.runAllTasks();
+ java.util.concurrent.locks.LockSupport.parkNanos("executing tasks", 1000L);
}
+ // CraftBukkit end
protected void waitUntilNextTick() {
this.runAllTasks();
@@ -869,7 +1144,7 @@
}
}
- protected void doRunTask(TickTask ticktask) {
+ public void doRunTask(TickTask ticktask) { // CraftBukkit - decompile error
this.getProfiler().incrementCounter("runTask");
super.doRunTask(ticktask);
}
@@ -940,7 +1215,7 @@
}
}
- if (this.tickCount % 6000 == 0) {
+ if (autosavePeriod > 0 && this.tickCount % autosavePeriod == 0) { // CraftBukkit
MinecraftServer.LOGGER.debug("Autosave started");
this.profiler.push("save");
this.saveEverything(true, false, false);
@@ -959,22 +1234,39 @@
}
public void tickChildren(BooleanSupplier booleansupplier) {
+ this.server.getScheduler().mainThreadHeartbeat(this.tickCount); // CraftBukkit
this.profiler.push("commandFunctions");
this.getFunctions().tick();
this.profiler.popPush("levels");
Iterator iterator = this.getAllLevels().iterator();
+ // CraftBukkit start
+ // Run tasks that are waiting on processing
+ while (!processQueue.isEmpty()) {
+ processQueue.remove().run();
+ }
+
+ // Send time updates to everyone, it will get the right time from the world the player is in.
+ if (this.tickCount % 20 == 0) {
+ for (int i = 0; i < this.getPlayerList().players.size(); ++i) {
+ EntityPlayer entityplayer = (EntityPlayer) this.getPlayerList().players.get(i);
+ entityplayer.connection.send(new PacketPlayOutUpdateTime(entityplayer.level.getGameTime(), entityplayer.getPlayerTime(), entityplayer.level.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT))); // Add support for per player time
+ }
+ }
+
while (iterator.hasNext()) {
WorldServer worldserver = (WorldServer) iterator.next();
this.profiler.push(() -> {
return worldserver + " " + worldserver.dimension().location();
});
+ /* Drop global time updates
if (this.tickCount % 20 == 0) {
this.profiler.push("timeSync");
this.playerList.broadcastAll(new PacketPlayOutUpdateTime(worldserver.getGameTime(), worldserver.getDayTime(), worldserver.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT)), worldserver.dimension());
this.profiler.pop();
}
+ // CraftBukkit end */
this.profiler.push("tick");
@@ -1063,7 +1355,7 @@
@DontObfuscate
public String getServerModName() {
- return "vanilla";
+ return server.getName(); // CraftBukkit - cb > vanilla!
}
public SystemReport fillSystemReport(SystemReport systemreport) {
@@ -1406,11 +1698,11 @@
public CompletableFuture<Void> reloadResources(Collection<String> collection) {
IRegistryCustom.Dimension iregistrycustom_dimension = this.registryAccess();
CompletableFuture<Void> completablefuture = CompletableFuture.supplyAsync(() -> {
- Stream stream = collection.stream();
+ Stream<String> stream = collection.stream(); // CraftBukkit - decompile error
ResourcePackRepository resourcepackrepository = this.packRepository;
Objects.requireNonNull(this.packRepository);
- return (ImmutableList) stream.map(resourcepackrepository::getPack).filter(Objects::nonNull).map(ResourcePackLoader::open).collect(ImmutableList.toImmutableList());
+ return stream.map(resourcepackrepository::getPack).filter(Objects::nonNull).map(ResourcePackLoader::open).collect(ImmutableList.toImmutableList()); // CraftBukkit - decompile error
}, this).thenCompose((immutablelist) -> {
ResourceManager resourcemanager = new ResourceManager(EnumResourcePackType.SERVER_DATA, immutablelist);
@@ -1425,6 +1717,7 @@
}).thenAcceptAsync((minecraftserver_a) -> {
this.resources.close();
this.resources = minecraftserver_a;
+ this.server.syncCommands(); // SPIGOT-5884: Lost on reload
this.packRepository.setSelected(collection);
this.worldData.setDataPackConfig(getSelectedPacks(this.packRepository));
this.resources.managers.updateRegistryTags(this.registryAccess());
@@ -1774,7 +2067,7 @@
try {
label51:
{
- ArrayList arraylist;
+ ArrayList<NativeModuleLister.a> arraylist; // CraftBukkit - decompile error
try {
arraylist = Lists.newArrayList(NativeModuleLister.listModules());
@@ -1824,6 +2117,22 @@
}
+ // CraftBukkit start
+ @Override
+ public boolean isSameThread() {
+ return super.isSameThread() || this.isStopped(); // CraftBukkit - MC-142590
+ }
+
+ public boolean isDebugging() {
+ return false;
+ }
+
+ @Deprecated
+ public static MinecraftServer getServer() {
+ return (Bukkit.getServer() instanceof CraftServer) ? ((CraftServer) Bukkit.getServer()).getServer() : null;
+ }
+ // CraftBukkit end
+
private void startMetricsRecordingTick() {
if (this.willStartRecordingMetrics) {
this.metricsRecorder = ActiveMetricsRecorder.createStarted(new ServerMetricsSamplersProvider(SystemUtils.timeSource, this.isDedicatedServer()), SystemUtils.timeSource, SystemUtils.ioPool(), new MetricsPersister("server"), this.onMetricsRecordingStopped, (path) -> {
@@ -1935,8 +2244,10 @@
}
}
- private static record a(IReloadableResourceManager a, DataPackResources b) implements AutoCloseable {
+ // CraftBukkit start - decompile error
+ public static record a(IReloadableResourceManager resourceManager, DataPackResources managers) implements AutoCloseable {
+ /*
final IReloadableResourceManager resourceManager;
final DataPackResources managers;
@@ -1944,6 +2255,8 @@
this.resourceManager = ireloadableresourcemanager;
this.managers = datapackresources;
}
+ */
+ // CraftBukkit end
public void close() {
this.resourceManager.close();