use of org.spongepowered.api.ResourceKey in project SpongeCommon by SpongePowered.
the class SpongeServerLocationValueParameter method parseValue.
@Override
@NonNull
public Optional<? extends ServerLocation> parseValue(@NonNull final CommandCause cause, final ArgumentReader.@NonNull Mutable reader) throws ArgumentParseException {
final ArgumentReader.Immutable state = reader.immutable();
ServerWorld serverWorld;
try {
final ResourceKey resourceLocation = reader.parseResourceKey("minecraft");
serverWorld = SpongeCommon.game().server().worldManager().world(resourceLocation).orElseThrow(() -> reader.createException(Component.text("Could not get world with key \"" + resourceLocation.toString() + "\"")));
} catch (final ArgumentParseException e) {
final Optional<ServerLocation> location = cause.location();
if (location.isPresent()) {
// do this as late as possible to prevent expense of regex.
if (!SpongeServerLocationValueParameter.STARTS_WITH_NUMBER.matcher(state.remaining()).find()) {
throw e;
}
serverWorld = location.get().world();
} else {
throw e;
}
reader.setState(state);
}
try {
reader.skipWhitespace();
final Vec3 vec3d = SpongeServerLocationValueParameter.VEC_3_ARGUMENT.parse((StringReader) reader).getPosition((CommandSourceStack) cause);
return Optional.of(serverWorld.location(VecHelper.toVector3d(vec3d)));
} catch (final CommandSyntaxException e) {
throw reader.createException(Component.text(e.getMessage()));
}
}
use of org.spongepowered.api.ResourceKey in project SpongeCommon by SpongePowered.
the class TimingsExport method reportTimings.
/**
* Builds an XML report of the timings to be uploaded for parsing.
*/
static void reportTimings() {
if (TimingsExport.requestingReport.isEmpty()) {
return;
}
TimingsReportListener listeners = new TimingsReportListener(TimingsExport.requestingReport);
TimingsExport.requestingReport.clear();
long now = System.currentTimeMillis();
final long lastReportDiff = now - TimingsExport.lastReport;
if (lastReportDiff < 60000) {
listeners.send(Component.text("Please wait at least 1 minute in between Timings reports. (" + (int) ((60000 - lastReportDiff) / 1000) + " seconds)", NamedTextColor.RED));
listeners.done();
return;
}
final long lastStartDiff = now - TimingsManager.timingStart;
if (lastStartDiff < 180000) {
listeners.send(Component.text("Please wait at least 3 minutes before generating a Timings report. Unlike Timings v1, v2 benefits from longer timings and is not as useful with short timings. (" + (int) ((180000 - lastStartDiff) / 1000) + " seconds)", NamedTextColor.RED));
listeners.done();
return;
}
listeners.send(Component.text("Preparing Timings Report...", NamedTextColor.GREEN));
TimingsExport.lastReport = now;
Platform platform = SpongeCommon.game().platform();
JsonObjectBuilder builder = JSONUtil.objectBuilder().add("version", platform.container(IMPLEMENTATION).metadata().version()).add("maxplayers", SpongeCommon.game().server().maxPlayers()).add("start", TimingsManager.timingStart / 1000).add("end", System.currentTimeMillis() / 1000).add("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000);
if (!TimingsManager.privacy) {
builder.add("server", TimingsExport.getServerName()).add("motd", PlainTextComponentSerializer.plainText().serialize(Sponge.server().motd())).add("online-mode", Sponge.server().isOnlineModeEnabled()).add("icon", SpongeCommon.server().getStatus().getFavicon());
}
final Runtime runtime = Runtime.getRuntime();
RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
builder.add("system", JSONUtil.objectBuilder().add("timingcost", TimingsExport.getCost()).add("name", System.getProperty("os.name")).add("version", System.getProperty("os.version")).add("jvmversion", System.getProperty("java.version")).add("arch", System.getProperty("os.arch")).add("maxmem", runtime.maxMemory()).add("cpu", runtime.availableProcessors()).add("runtime", ManagementFactory.getRuntimeMXBean().getUptime()).add("flags", TimingsExport.RUNTIME_FLAG_JOINER.join(runtimeBean.getInputArguments())).add("gc", JSONUtil.mapArrayToObject(ManagementFactory.getGarbageCollectorMXBeans(), (input) -> {
return JSONUtil.singleObjectPair(input.getName(), JSONUtil.arrayOf(input.getCollectionCount(), input.getCollectionTime()));
})));
Set<BlockEntityType> blockEntityTypeSet = Sets.newHashSet();
Set<EntityType<?>> entityTypeSet = Sets.newHashSet();
int size = TimingsManager.HISTORY.size();
TimingHistory[] history = new TimingHistory[size + 1];
int i = 0;
for (TimingHistory timingHistory : TimingsManager.HISTORY) {
blockEntityTypeSet.addAll(timingHistory.tileEntityTypeSet);
entityTypeSet.addAll(timingHistory.entityTypeSet);
history[i++] = timingHistory;
}
// Current snapshot
history[i] = new TimingHistory();
blockEntityTypeSet.addAll(history[i].tileEntityTypeSet);
entityTypeSet.addAll(history[i].entityTypeSet);
JsonObjectBuilder handlersBuilder = JSONUtil.objectBuilder();
for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
for (TimingHandler id : group.handlers) {
if (!id.timed && !id.isSpecial()) {
continue;
}
handlersBuilder.add(id.id, JSONUtil.arrayOf(group.id, id.name));
}
}
builder.add("idmap", JSONUtil.objectBuilder().add("groups", JSONUtil.mapArrayToObject(TimingIdentifier.GROUP_MAP.values(), (group) -> JSONUtil.singleObjectPair(group.id, group.name))).add("handlers", handlersBuilder).add("worlds", JSONUtil.mapArrayToObject(TimingHistory.worldMap.entrySet(), (entry) -> JSONUtil.singleObjectPair(entry.getValue(), entry.getKey()))).add("blockentity", JSONUtil.mapArrayToObject(blockEntityTypeSet, (blockEntityType) -> {
final ResourceKey resourceKey = Sponge.game().registry(RegistryTypes.BLOCK_ENTITY_TYPE).valueKey(blockEntityType);
return JSONUtil.singleObjectPair(TimingsPls.getBlockEntityId(blockEntityType), resourceKey);
})).add("entity", JSONUtil.mapArrayToObject(entityTypeSet, (entityType) -> {
final ResourceKey resourceKey = (ResourceKey) (Object) Registry.ENTITY_TYPE.getKey((net.minecraft.world.entity.EntityType<?>) entityType);
return JSONUtil.singleObjectPair(TimingsPls.getEntityId(entityType), resourceKey);
})));
// Information about loaded plugins
builder.add("plugins", JSONUtil.mapArrayToObject(SpongeCommon.game().pluginManager().plugins(), (plugin) -> {
@Nullable final URL homepageUrl = plugin.metadata().links().homepage().orElse(null);
final String homepage = homepageUrl != null ? homepageUrl.toString() : "<not specified>";
return JSONUtil.objectBuilder().add(plugin.metadata().id(), JSONUtil.objectBuilder().add("version", plugin.metadata().version()).add("description", plugin.metadata().description().orElse("")).add("website", homepage).add("authors", TimingsExport.AUTHOR_LIST_JOINER.join(plugin.metadata().contributors()))).build();
}));
// Information on the users Config
builder.add("config", JSONUtil.objectBuilder().add("sponge", TimingsExport.serializeConfigNode(SpongeConfigs.getCommon().getNode())));
new TimingsExport(listeners, builder.build(), history).start();
}
use of org.spongepowered.api.ResourceKey in project SpongeCommon by SpongePowered.
the class SpongeWorldManager method loadWorld0.
private CompletableFuture<org.spongepowered.api.world.server.ServerWorld> loadWorld0(final net.minecraft.resources.ResourceKey<Level> registryKey, final LevelStem template, final WorldGenSettings generatorSettings) {
final PrimaryLevelData defaultLevelData = (PrimaryLevelData) this.server.getWorldData();
final LevelSettings defaultLevelSettings = ((PrimaryLevelDataAccessor) defaultLevelData).accessor$settings();
final LevelStemBridge templateBridge = (LevelStemBridge) (Object) template;
final ResourceKey worldKey = ((ResourceKeyBridge) templateBridge).bridge$getKey();
final WorldType worldType = (WorldType) template.type();
final ResourceKey worldTypeKey = RegistryTypes.WORLD_TYPE.get().valueKey((WorldType) template.type());
MinecraftServerAccessor.accessor$LOGGER().info("Loading world '{}' ({})", worldKey, worldTypeKey);
final String directoryName = this.getDirectoryName(worldKey);
final boolean isVanillaSubLevel = this.isVanillaSubWorld(directoryName);
final LevelStorageSource.LevelStorageAccess storageSource;
try {
if (isVanillaSubLevel) {
storageSource = LevelStorageSource.createDefault(this.defaultWorldDirectory).createAccess(directoryName);
} else {
storageSource = LevelStorageSource.createDefault(this.customWorldsDirectory).createAccess(worldKey.namespace() + File.separator + worldKey.value());
}
} catch (final IOException e) {
e.printStackTrace();
return FutureUtil.completedWithException(new RuntimeException(String.format("Failed to create level data for world '%s'!", worldKey), e));
}
PrimaryLevelData levelData;
levelData = (PrimaryLevelData) storageSource.getDataTag((DynamicOps<Tag>) BootstrapProperties.worldSettingsAdapter, defaultLevelSettings.getDataPackConfig());
if (levelData == null) {
final LevelSettings levelSettings;
final WorldGenSettings generationSettings;
if (this.server.isDemo()) {
levelSettings = MinecraftServer.DEMO_SETTINGS;
generationSettings = WorldGenSettings.demoSettings(BootstrapProperties.registries);
} else {
levelSettings = new LevelSettings(directoryName, (GameType) (Object) BootstrapProperties.gameMode.get(Sponge.game()), templateBridge.bridge$hardcore().orElse(BootstrapProperties.hardcore), (Difficulty) (Object) BootstrapProperties.difficulty.get(Sponge.game()), templateBridge.bridge$commands().orElse(BootstrapProperties.commands), new GameRules(), defaultLevelData.getDataPackConfig());
generationSettings = generatorSettings;
}
levelData = new PrimaryLevelData(levelSettings, generationSettings, Lifecycle.stable());
}
((PrimaryLevelDataBridge) levelData).bridge$populateFromDimension(template);
final InheritableConfigHandle<WorldConfig> configAdapter = SpongeGameConfigs.createWorld(worldTypeKey, worldKey);
((PrimaryLevelDataBridge) levelData).bridge$configAdapter(configAdapter);
levelData.setModdedInfo(this.server.getServerModName(), this.server.getModdedStatus().isPresent());
final boolean isDebugGeneration = levelData.worldGenSettings().isDebug();
final long seed = BiomeManager.obfuscateSeed(levelData.worldGenSettings().seed());
final ChunkProgressListener chunkStatusListener = ((MinecraftServerAccessor) this.server).accessor$progressListenerFactory().create(11);
final ServerLevel world = new ServerLevel(this.server, ((MinecraftServerAccessor) this.server).accessor$executor(), storageSource, levelData, registryKey, (DimensionType) worldType, chunkStatusListener, template.generator(), isDebugGeneration, seed, ImmutableList.of(), true);
this.worlds.put(registryKey, world);
return SpongeCommon.asyncScheduler().submit(() -> this.prepareWorld(world, isDebugGeneration)).thenApply(w -> {
((MinecraftServerAccessor) this.server).invoker$forceDifficulty();
return w;
}).thenCompose(w -> this.postWorldLoad(w, false)).thenApply(w -> (org.spongepowered.api.world.server.ServerWorld) w);
}
use of org.spongepowered.api.ResourceKey in project SpongeCommon by SpongePowered.
the class SpongeWorldManager method loadWorld.
@Override
public CompletableFuture<org.spongepowered.api.world.server.ServerWorld> loadWorld(final WorldTemplate template) {
final ResourceKey key = Objects.requireNonNull(template, "template").key();
final net.minecraft.resources.ResourceKey<Level> registryKey = SpongeWorldManager.createRegistryKey(key);
if (Level.OVERWORLD.equals(registryKey)) {
FutureUtil.completedWithException(new IllegalArgumentException("The default world cannot be told to load!"));
}
final ServerLevel serverWorld = this.worlds.get(registryKey);
if (serverWorld != null) {
return CompletableFuture.completedFuture((org.spongepowered.api.world.server.ServerWorld) serverWorld);
}
this.saveTemplate(template);
return this.loadWorld0(registryKey, ((SpongeWorldTemplate) template).asDimension(), ((WorldGenSettings) template.generationConfig()));
}
use of org.spongepowered.api.ResourceKey in project SpongeCommon by SpongePowered.
the class SpongeWorldManager method loadLevel.
public void loadLevel() {
final PrimaryLevelData defaultLevelData = (PrimaryLevelData) this.server.getWorldData();
final WorldGenSettings defaultGenerationSettings = defaultLevelData.worldGenSettings();
final LevelSettings defaultLevelSettings = ((PrimaryLevelDataAccessor) defaultLevelData).accessor$settings();
final MappedRegistry<LevelStem> templates = defaultGenerationSettings.dimensions();
final boolean multiworldEnabled = this.server.isSingleplayer() || this.server.isNetherEnabled();
if (!multiworldEnabled) {
SpongeCommon.logger().warn("The option 'allow-nether' has been set to 'false' in the server.properties. " + "Multi-World support has been disabled and no worlds besides the default world will be loaded.");
}
for (final RegistryEntry<LevelStem> entry : ((Registry<LevelStem>) (Object) templates).streamEntries().collect(Collectors.toList())) {
final ResourceKey worldKey = entry.key();
final LevelStem template = entry.value();
final LevelStemBridge templateBridge = (LevelStemBridge) (Object) template;
((ResourceKeyBridge) templateBridge).bridge$setKey(worldKey);
final boolean isDefaultWorld = this.isDefaultWorld(worldKey);
if (!isDefaultWorld && !multiworldEnabled) {
continue;
}
final WorldType worldType = (WorldType) template.type();
final ResourceKey worldTypeKey = RegistryTypes.WORLD_TYPE.get().valueKey((WorldType) template.type());
MinecraftServerAccessor.accessor$LOGGER().info("Loading world '{}' ({})", worldKey, worldTypeKey);
if (!isDefaultWorld && !templateBridge.bridge$loadOnStartup()) {
SpongeCommon.logger().warn("World '{}' has been disabled from loading at startup. Skipping...", worldKey);
continue;
}
final String directoryName = this.getDirectoryName(worldKey);
final boolean isVanillaSubLevel = this.isVanillaSubWorld(directoryName);
final LevelStorageSource.LevelStorageAccess storageSource;
if (isDefaultWorld) {
storageSource = ((MinecraftServerAccessor) this.server).accessor$storageSource();
} else {
try {
if (isVanillaSubLevel) {
storageSource = LevelStorageSource.createDefault(this.defaultWorldDirectory).createAccess(directoryName);
} else {
storageSource = LevelStorageSource.createDefault(this.customWorldsDirectory).createAccess(worldKey.namespace() + File.separator + worldKey.value());
}
} catch (final IOException e) {
throw new RuntimeException(String.format("Failed to create level data for world '%s'!", worldKey), e);
}
}
PrimaryLevelData levelData;
final boolean isDebugGeneration;
if (isDefaultWorld) {
levelData = defaultLevelData;
isDebugGeneration = defaultGenerationSettings.isDebug();
} else {
levelData = (PrimaryLevelData) storageSource.getDataTag((DynamicOps<Tag>) BootstrapProperties.worldSettingsAdapter, defaultLevelSettings.getDataPackConfig());
if (levelData == null) {
final LevelSettings levelSettings;
final WorldGenSettings generationSettings;
if (this.server.isDemo()) {
levelSettings = MinecraftServer.DEMO_SETTINGS;
generationSettings = WorldGenSettings.demoSettings(BootstrapProperties.registries);
} else {
levelSettings = new LevelSettings(directoryName, (GameType) (Object) BootstrapProperties.gameMode.get(Sponge.game()), templateBridge.bridge$hardcore().orElse(BootstrapProperties.hardcore), (Difficulty) (Object) BootstrapProperties.difficulty.get(Sponge.game()), templateBridge.bridge$commands().orElse(BootstrapProperties.commands), new GameRules(), defaultLevelData.getDataPackConfig());
generationSettings = ((WorldGenSettingsBridge) defaultLevelData.worldGenSettings()).bridge$copy();
}
isDebugGeneration = generationSettings.isDebug();
((DimensionGeneratorSettingsAccessor) generationSettings).accessor$dimensions(new MappedRegistry<>(net.minecraft.core.Registry.LEVEL_STEM_REGISTRY, Lifecycle.stable()));
levelData = new PrimaryLevelData(levelSettings, generationSettings, Lifecycle.stable());
} else {
isDebugGeneration = levelData.worldGenSettings().isDebug();
}
}
((PrimaryLevelDataBridge) levelData).bridge$populateFromDimension(template);
final InheritableConfigHandle<WorldConfig> configAdapter = SpongeGameConfigs.createWorld(worldTypeKey, worldKey);
((PrimaryLevelDataBridge) levelData).bridge$configAdapter(configAdapter);
levelData.setModdedInfo(this.server.getServerModName(), this.server.getModdedStatus().isPresent());
final long seed = BiomeManager.obfuscateSeed(levelData.worldGenSettings().seed());
final net.minecraft.resources.ResourceKey<Level> registryKey = SpongeWorldManager.createRegistryKey(worldKey);
final ChunkProgressListener chunkStatusListener = ((MinecraftServerAccessor) this.server).accessor$progressListenerFactory().create(11);
final List<CustomSpawner> spawners;
if (isDefaultWorld) {
spawners = ImmutableList.of(new PhantomSpawner(), new PatrolSpawner(), new CatSpawner(), new VillageSiege(), new WanderingTraderSpawner(levelData));
} else {
spawners = ImmutableList.of();
}
final ServerLevel world = new ServerLevel(this.server, ((MinecraftServerAccessor) this.server).accessor$executor(), storageSource, levelData, registryKey, (DimensionType) worldType, chunkStatusListener, template.generator(), isDebugGeneration, seed, spawners, true);
// Ensure that the world border is registered.
world.getWorldBorder().applySettings(levelData.getWorldBorder());
this.worlds.put(registryKey, world);
this.prepareWorld(world, isDebugGeneration);
}
((MinecraftServerAccessor) this.server).invoker$forceDifficulty();
for (final Map.Entry<net.minecraft.resources.ResourceKey<Level>, ServerLevel> entry : this.worlds.entrySet()) {
try {
this.postWorldLoad(entry.getValue(), true).get();
} catch (final InterruptedException | ExecutionException e) {
throw new IllegalStateException(e);
}
}
((SpongeUserManager) Sponge.server().userManager()).init();
((SpongeServer) SpongeCommon.server()).getPlayerDataManager().load();
}
Aggregations