use of org.spongepowered.api.world.DimensionType in project SpongeCommon by SpongePowered.
the class SpongeCommandFactory method createSpongeChunksCommand.
// Flag children
private static CommandSpec createSpongeChunksCommand() {
return CommandSpec.builder().description(Text.of("Print chunk information, optionally dump")).arguments(optional(seq(literal(Text.of("dump"), "dump"), optional(literal(Text.of("dump-all"), "all"))))).permission("sponge.command.chunks").executor(new ConfigUsingExecutor(true) {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
CommandResult res = super.execute(src, args);
if (args.hasAny("dump")) {
File file = new File(new File(new File("."), "chunk-dumps"), "chunk-info-" + DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss").format(Instant.now()) + "-server.txt");
src.sendMessage(Text.of("Writing chunk info to: ", file));
ChunkSaveHelper.writeChunks(file, args.hasAny("dump-all"));
src.sendMessage(Text.of("Chunk info complete"));
}
return res;
}
@Override
protected Text processGlobal(SpongeConfig<GlobalConfig> config, CommandSource source, CommandContext args) throws CommandException {
for (World world : SpongeImpl.getGame().getServer().getWorlds()) {
source.sendMessage(Text.of("World ", Text.of(TextStyles.BOLD, world.getName()), getChunksInfo(((WorldServer) world))));
}
return Text.of("Printed chunk info for all worlds ");
}
@Override
protected Text processDimension(SpongeConfig<DimensionConfig> config, DimensionType dim, CommandSource source, CommandContext args) throws CommandException {
SpongeImpl.getGame().getServer().getWorlds().stream().filter(world -> world.getDimension().getType().equals(dim)).forEach(world -> source.sendMessage(Text.of("World ", Text.of(TextStyles.BOLD, world.getName()), getChunksInfo(((WorldServer) world)))));
return Text.of("Printed chunk info for all worlds in dimension ", dim.getName());
}
@Override
protected Text processWorld(SpongeConfig<WorldConfig> config, World world, CommandSource source, CommandContext args) throws CommandException {
return getChunksInfo((WorldServer) world);
}
protected Text key(Object text) {
return Text.of(TextColors.GOLD, text);
}
protected Text value(Object text) {
return Text.of(TextColors.GRAY, text);
}
protected Text getChunksInfo(WorldServer worldserver) {
return Text.of(NEWLINE_TEXT, key("DimensionId: "), value(WorldManager.getDimensionId(worldserver)), NEWLINE_TEXT, key("Loaded chunks: "), value(worldserver.getChunkProvider().getLoadedChunkCount()), NEWLINE_TEXT, key("Active chunks: "), value(worldserver.getChunkProvider().getLoadedChunks().size()), NEWLINE_TEXT, key("Entities: "), value(worldserver.loadedEntityList.size()), NEWLINE_TEXT, key("Tile Entities: "), value(worldserver.loadedTileEntityList.size()), NEWLINE_TEXT, key("Removed Entities:"), value(worldserver.unloadedEntityList.size()), NEWLINE_TEXT, key("Removed Tile Entities: "), value(worldserver.tileEntitiesToBeRemoved), NEWLINE_TEXT);
}
}).build();
}
use of org.spongepowered.api.world.DimensionType in project Skree by Skelril.
the class WorldSystem method buildArchetype.
private void buildArchetype(ArchetypeConfig archetypeConfig) throws Throwable {
GameRegistry registry = Sponge.getRegistry();
Optional<WorldArchetype> optTargetArchetype = registry.getType(WorldArchetype.class, archetypeConfig.getId());
if (optTargetArchetype.isPresent()) {
return;
}
WorldArchetype.Builder archeTypeBuilder = obtainAutoloadingWorld();
String dimensionName = archetypeConfig.getDimension();
DimensionType dimension = registry.getType(DimensionType.class, dimensionName).orElseThrow((Supplier<Throwable>) () -> {
List<String> valid = registry.getAllOf(DimensionType.class).stream().map(DimensionType::getId).collect(Collectors.toList());
return new RuntimeException("No dimension type: " + dimensionName + "; Valid dimension types: " + Joiner.on(", ").join(valid));
});
archeTypeBuilder.dimension(dimension);
String generatorName = archetypeConfig.getGenerator();
GeneratorType generator = registry.getType(GeneratorType.class, generatorName).orElseThrow((Supplier<Throwable>) () -> {
List<String> valid = registry.getAllOf(GeneratorType.class).stream().map(GeneratorType::getId).collect(Collectors.toList());
return new RuntimeException("No generator type: " + generatorName + "; Valid generator types: " + Joiner.on(", ").join(valid));
});
archeTypeBuilder.generator(generator);
boolean usesMapFeatures = archetypeConfig.usesMapFeatures();
archeTypeBuilder.usesMapFeatures(usesMapFeatures);
List<WorldGeneratorModifier> modifiers = new ArrayList<>();
for (String modifierId : archetypeConfig.getModifiers()) {
modifiers.add(registry.getType(WorldGeneratorModifier.class, modifierId).orElseThrow((Supplier<Throwable>) () -> {
return new RuntimeException("No world generator modifier: " + modifierId);
}));
}
archeTypeBuilder.generatorModifiers(modifiers.toArray(new WorldGeneratorModifier[modifiers.size()]));
archeTypeBuilder.build(archetypeConfig.getId(), archetypeConfig.getName());
}
use of org.spongepowered.api.world.DimensionType in project ProjectWorlds by trentech.
the class CommandCreate method process.
@Override
public CommandResult process(CommandSource source, String arguments) throws CommandException {
if (arguments.equalsIgnoreCase("create")) {
throw new CommandException(getHelp().getUsageText());
}
String[] args = arguments.split(" ");
if (args[args.length - 1].equalsIgnoreCase("--help")) {
help.execute(source);
return CommandResult.success();
}
String worldName;
try {
worldName = args[0];
} catch (Exception e) {
throw new CommandException(getHelp().getUsageText());
}
if (Sponge.getServer().getWorldProperties(worldName).isPresent()) {
throw new CommandException(Text.of(TextColors.RED, worldName, " already exists"), false);
}
WorldArchetype.Builder builder = WorldArchetype.builder();
List<WorldGeneratorModifier> modifiers = new ArrayList<>();
if (args.length > 2) {
boolean skip = false;
for (int i = 1; i < args.length - 1; i++) {
if (skip) {
skip = false;
continue;
}
String arg = args[i];
String value;
try {
value = args[i + 1];
} catch (Exception e) {
throw new CommandException(getHelp().getUsageText());
}
if (arg.equalsIgnoreCase("-d") || arg.equalsIgnoreCase("-dimension")) {
Optional<DimensionType> optionalDimension = Sponge.getRegistry().getType(DimensionType.class, value);
if (!optionalDimension.isPresent()) {
source.sendMessage(Text.of(TextColors.YELLOW, value, " is not a valid DimensionType"));
throw new CommandException(getHelp().getUsageText());
}
builder.dimension(optionalDimension.get());
} else if (arg.equalsIgnoreCase("-g") || arg.equalsIgnoreCase("-generator")) {
String[] split = value.split("\\{");
Optional<GeneratorType> optionalGenerator = Sponge.getRegistry().getType(GeneratorType.class, split[0]);
if (!optionalGenerator.isPresent()) {
source.sendMessage(Text.of(TextColors.YELLOW, value, " is not a valid GeneratorType"));
throw new CommandException(getHelp().getUsageText());
}
builder.generator(optionalGenerator.get());
if (split.length == 2) {
builder.generatorSettings(DataContainer.createNew().set(DataQuery.of("customSettings"), split[1].replace("\\}", "")));
}
} else if (arg.equalsIgnoreCase("-gm") || arg.equalsIgnoreCase("-gamemode")) {
Optional<GameMode> optionalGamemode = Optional.empty();
try {
optionalGamemode = Gamemode.get(Integer.parseInt(value));
} catch (Exception e) {
optionalGamemode = Gamemode.get(value);
}
if (!optionalGamemode.isPresent()) {
source.sendMessage(Text.of(TextColors.YELLOW, value, " is not a valid GameMode"));
throw new CommandException(getHelp().getUsageText());
}
builder.gameMode(optionalGamemode.get());
} else if (arg.equalsIgnoreCase("-m") || arg.equalsIgnoreCase("-modifier")) {
Optional<WorldGeneratorModifier> optionalModifier = Sponge.getRegistry().getType(WorldGeneratorModifier.class, value);
if (!optionalModifier.isPresent()) {
source.sendMessage(Text.of(TextColors.YELLOW, value, " is not a valid WorldGeneratorModifier"));
throw new CommandException(getHelp().getUsageText());
}
modifiers.add(optionalModifier.get());
} else if (arg.equalsIgnoreCase("-s") || arg.equalsIgnoreCase("-seed")) {
try {
Long s = Long.parseLong(value);
builder.seed(s);
} catch (Exception e) {
builder.seed(value.hashCode());
}
} else if (arg.equalsIgnoreCase("-df") || arg.equalsIgnoreCase("-difficulty")) {
Optional<Difficulty> optionalDifficulty = Sponge.getRegistry().getType(Difficulty.class, value);
if (!optionalDifficulty.isPresent()) {
source.sendMessage(Text.of(TextColors.YELLOW, value, " is not a valid Difficulty"));
throw new CommandException(getHelp().getUsageText());
}
builder.difficulty(optionalDifficulty.get());
} else if (arg.equalsIgnoreCase("-l") || arg.equalsIgnoreCase("-loadonstartup")) {
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
builder.loadsOnStartup(Boolean.valueOf(value));
} else {
source.sendMessage(Text.of(TextColors.YELLOW, value, " is not a valid Boolean"));
throw new CommandException(getHelp().getUsageText());
}
} else if (arg.equalsIgnoreCase("-k") || arg.equalsIgnoreCase("-keepspawnloaded")) {
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
builder.keepsSpawnLoaded(Boolean.valueOf(value));
} else {
source.sendMessage(Text.of(TextColors.YELLOW, value, " is not a valid Boolean"));
throw new CommandException(getHelp().getUsageText());
}
} else if (arg.equalsIgnoreCase("-c") || arg.equalsIgnoreCase("-allowcommands")) {
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
builder.commandsAllowed(Boolean.valueOf(value));
} else {
source.sendMessage(Text.of(TextColors.YELLOW, value, " is not a valid Boolean"));
throw new CommandException(getHelp().getUsageText());
}
} else if (arg.equalsIgnoreCase("-b") || arg.equalsIgnoreCase("-bonuschest")) {
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
builder.generateBonusChest(Boolean.valueOf(value));
} else {
source.sendMessage(Text.of(TextColors.YELLOW, value, " is not a valid Boolean"));
throw new CommandException(getHelp().getUsageText());
}
} else if (arg.equalsIgnoreCase("-f") || arg.equalsIgnoreCase("-mapfeatures")) {
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
builder.usesMapFeatures(Boolean.valueOf(value));
} else {
source.sendMessage(Text.of(TextColors.YELLOW, value, " is not a valid Boolean"));
throw new CommandException(getHelp().getUsageText());
}
} else {
source.sendMessage(Text.of(TextColors.YELLOW, value, " is not a valid Flag"));
throw new CommandException(getHelp().getUsageText());
}
skip = true;
}
}
WorldArchetype settings = builder.enabled(true).keepsSpawnLoaded(true).loadsOnStartup(true).build(worldName, worldName);
WorldProperties properties;
try {
properties = Sponge.getServer().createWorldProperties(worldName, settings);
properties.setGeneratorModifiers(modifiers);
} catch (IOException e) {
e.printStackTrace();
throw new CommandException(Text.of(TextColors.RED, "Something went wrong. Check server log for details"), false);
}
Sponge.getServer().saveWorldProperties(properties);
worlds.add(worldName);
source.sendMessage(Text.of(TextColors.DARK_GREEN, worldName, " created successfully"));
return CommandResult.success();
}
use of org.spongepowered.api.world.DimensionType in project ProjectWorlds by trentech.
the class Common method initHelp.
public static void initHelp() {
Usage usageCopy = new Usage(Argument.of("<oldWorld>", "Specifies the name of world you want to copy")).addArgument(Argument.of("<newWorld>", "Enter the name of the new world"));
Help worldCopy = new Help("world copy", "copy", "Allows you to make a new world from an existing world").setPermission("pjw.cmd.world.copy").setUsage(usageCopy).addExample("/world copy srcWorld newWorld");
String dimTypes = null;
for (DimensionType type : Sponge.getRegistry().getAllOf(DimensionType.class)) {
if (dimTypes == null) {
dimTypes = type.getId();
} else {
dimTypes = dimTypes + "\n" + type.getId();
}
}
String genTypes = null;
for (GeneratorType type : Sponge.getRegistry().getAllOf(GeneratorType.class)) {
if (genTypes == null) {
genTypes = type.getId();
} else {
genTypes = genTypes + "\n" + type.getId();
}
}
String modTypes = null;
for (WorldGeneratorModifier type : Sponge.getRegistry().getAllOf(WorldGeneratorModifier.class)) {
if (modTypes == null) {
modTypes = type.getId();
} else {
modTypes = modTypes + "\n" + type.getId();
}
}
String gameModes = null;
for (Gamemode type : Gamemode.values()) {
if (gameModes == null) {
gameModes = type.getGameMode().getName() + " -or- " + type.getIndex();
} else {
gameModes = gameModes + "\n" + type.getGameMode().getName() + " -or- " + type.getIndex();
}
}
String difficulties = null;
for (Difficulty type : Sponge.getRegistry().getAllOf(Difficulty.class)) {
if (difficulties == null) {
difficulties = type.getId();
} else {
difficulties = difficulties + "\n" + type.getId();
}
}
Usage usageCreate = new Usage(Argument.of("<world>", "Specifies the name of the world")).addArgument(Argument.of("[-d <dimensionType>]", dimTypes)).addArgument(Argument.of("[-g <generatorType>]", genTypes)).addArgument(Argument.of("[-m <modifier>]", modTypes)).addArgument(Argument.of("[-df <difficulty>]", difficulties)).addArgument(Argument.of("[-gm <gameMode>]", gameModes)).addArgument(Argument.of("[-s <seed>]", "Sets the seed. If not specified this will default to using a random seed.")).addArgument(Argument.of("[-l <true|false>]", "Sets whether to load when the server starts. Default is true")).addArgument(Argument.of("[-k <true|false>]", "Sets whether the spawn chunks should remain loaded when no players are present. Default is true")).addArgument(Argument.of("[-b <true|false>]", "Set whether to generator bonus chest. Default is false")).addArgument(Argument.of("[-c <true|false>]", "Sets whether commands are allowed to be executed. Default is true")).addArgument(Argument.of("[-f <true|false>]", "Sets whether this world will generate map features such as villages and strongholds. Default is true"));
Help worldCreate = new Help("world create", "create", "Allows you to creating new worlds with a combination of features. This does not automatically load newly created worlds.").setPermission("pjw.cmd.world.create").setUsage(usageCreate).addExample("/world create NewWorld -d minecraft:overworld -g minecraft:overworld").addExample("/world create NewWorld -g minecraft:flat{3;30*minecraft:bedrock;1}").addExample("/world create NewWorld -d sponge:nether -m sponge:skylands").addExample("/world create NewWorld -s -12309830198412353456");
Usage usageModifier = new Usage(Argument.of("<world>", "Specifies the targetted world")).addArgument(Argument.of("<modifier>", modTypes)).addArgument(Argument.of("[-r]", "Adding this flag removes the specified modifier from the given world"));
Help worldModifier = new Help("world modifier", "modifier", "Allows you to add or remove WorldGeneratorModifier's from the given world. This will have no effect on existing chunks only ungenerated chunks.").setPermission("pjw.cmd.world.modifier").setUsage(usageModifier).addExample("/world modifier World sponge:void").addExample("/world modifier World sponge:skylands -s");
Usage usageRemove = new Usage(Argument.of("<world>", "Specifies the targetted world"));
Help worldRemove = new Help("world remove", "remove", "Delete worlds you no longer need. Worlds must be unloaded before you can delete them").setPermission("pjw.cmd.world.remove").setUsage(usageRemove).addExample("/world remove OldWorld");
Usage usageDifficulty = new Usage(Argument.of("<world>", "Specifies the targetted world")).addArgument(Argument.of("[difficulty]", difficulties));
Help worldDifficulty = new Help("world difficulty", "difficulty", "Set the difficulty level for each world").setPermission("pjw.cmd.world.difficulty").setUsage(usageDifficulty).addExample("/world difficulty MyWorld HARD").addExample("/world difficulty MyWorld");
Usage usageEnable = new Usage(Argument.of("<world>", "Specifies the targetted world")).addArgument(Argument.of("[true|false]"));
Help worldEnable = new Help("world enable", "enable", "Enable and disable worlds from loading").setPermission("pjw.cmd.world.enable").setUsage(usageEnable).addExample("/world enable MyWorld false").addExample("/world enable MyWorld true");
Help worldUseMapFeatures = new Help("world usemapfeatures", "usemapfeatures", "Sets whether this world will generate map features such as villages and strongholds").setPermission("pjw.cmd.world.usemapfeatures").setUsage(usageEnable).addExample("/world usemapfeatures MyWorld false").addExample("/world usemapfeatures MyWorld true");
Usage usageFill = new Usage(Argument.of("<world>", "Specifies the targetted world")).addArgument(Argument.of("<diameter>", "Set the diameter of the world border or enter 'stop' to cancel already running process. The specified diameter applies to the x and z axis. The world border extends over the entire y-axis")).addArgument(Argument.of("[interval]", "Sets the interval between generation runs. Must be greater than 0. Default is 10."));
Help worldFill = new Help("world fill", "fill", "Pre generate chunks in a world outwards from center spawn").setPermission("pjw.cmd.world.fill").setUsage(usageFill).addExample("/world fill MyWorld stop").addExample("/world fill MyWorld 1000");
Usage usageGamemode = new Usage(Argument.of("<world>", "Specifies the targetted world")).addArgument(Argument.of("[gamemode]", gameModes));
Help worldGamemode = new Help("world gamemode", "gamemode", "Change gamemode of the specified world").setPermission("pjw.cmd.world.gamemode").setUsage(usageGamemode).addExample("/world gamemode MyWorld SURVIVAL").addExample("/world gamemode");
Usage usageGamerule = new Usage(Argument.of("<world>", "Specifies the targetted world")).addArgument(Argument.of("[rule]", "Specifies the game rule to set or query. May be any value, but only certain predefined game rules will affect gameplay.")).addArgument(Argument.of("[value]", "Specifies the value to set the game rule to. May be any value, though only true or false specified for predefined game rules will actually affect gameplay, except in the case of randomTickSpeed and spawnRadius, where any integer 0 or greater will affect gameplay"));
Help worldGamerule = new Help("world gamerule", "gamerule", " Configure varies world properties").setPermission("pjw.cmd.world.gamerule").setUsage(usageGamerule).addExample("/world gamerule MyWorld mobGriefing false").addExample("/world gamerule MyWorld");
Help worldHardcore = new Help("world hardcore", "hardcore", "Toggle on and off hardcore mode for world").setPermission("pjw.cmd.world.hardcore").setUsage(usageEnable).addExample("/world hardcore MyWorld false").addExample("/world hardcore MyWorld");
Usage usageTime = new Usage(Argument.of("<world>", "Specifies the targetted world")).addArgument(Argument.of("[time]", "Sets the time of day, in ticks. The total number of ticks in a day is 24000, however this value does not reset to zero at the start of each day but rather keeps counting passed 24000."));
Help worldTime = new Help("world time", "time", "Set the time of world").setPermission("pjw.cmd.world.time").setUsage(usageTime).addExample("/world time MyWorld 6000").addExample("/world time MyWorld");
Usage usageWeather = new Usage(Argument.of("<world>", "Specifies the targetted world")).addArgument(Argument.of("[clear|rain|thunder]", "clear: Set the weather to clear, rain: Set the weather to rain (or snow in cold biomes), thunder: Set the weather to a thunderstorm (or a thunder snowstorm in cold biomes)")).addArgument(Argument.of("[duration]", "Specifies the duration the set weather will occur."));
Help worldWeather = new Help("world weather", "weather", "Set the weather of world").setPermission("pjw.cmd.world.weather").setUsage(usageWeather).addExample("/world weather MyWorld clear").addExample("/world weather MyWorld");
Usage usageImport = new Usage(Argument.of("<world>", "Specifies the targetted world")).addArgument(Argument.of("<dimensionType>", dimTypes)).addArgument(Argument.of("<generatorType>", genTypes)).addArgument(Argument.of("[modifer]", modTypes));
Help worldImport = new Help("world import", "import", "Import worlds not native to Sponge").setPermission("pjw.cmd.world.import").setUsage(usageImport).addExample("/world import NewWorld minecraft:overworld overworld sponge:void").addExample("/world import NewWorld minecraft:overworld overworld");
Help worldKeepSpawnLoaded = new Help("world keepspawnloaded", "keepspawnloaded", "Keeps spawn point of world loaded in memory").setPermission("pjw.cmd.world.keepspawnloaded").setUsage(usageEnable).addExample("/world keepspawnloaded MyWorld true").addExample("/world keepspawnloaded MyWorld");
Help worldLoadOnStartup = new Help("world loadonstartup", "loadonstartup", "Set whether to load world on startup").setPermission("pjw.cmd.world.loadonstartup").setUsage(usageEnable).addExample("/world loadonstartup MyWorld true").addExample("/world loadonstartup MyWorld");
Help worldList = new Help("world list", "list", "Lists all known worlds, loaded or unloaded").setPermission("pjw.cmd.world.list");
Usage usageLoad = new Usage(Argument.of("<world>", "Specifies the targetted world"));
Help worldLoad = new Help("world load", "load", "Loads sepcified world. If world is a non Sponge created world you will need to /world import").setPermission("pjw.cmd.world.load").setUsage(usageLoad).addExample("/world load BukkitWorld overworld").addExample("/world load NewWorld");
Help worldProperties = new Help("world properties", "properties", "View all properties associated with a world").setPermission("pjw.cmd.world.properties").setUsage(usageLoad).addExample("/world properties MyWorld").addExample("/world properties");
Help worldPvp = new Help("world pvp", "pvp", "Toggle on and off pvp for world").setPermission("pjw.cmd.world.pvp").setUsage(usageEnable).addExample("/world pvp MyWorld true").addExample("/world pvp MyWorld");
Usage usageRegen = new Usage(Argument.of("<world>", "Specifies the targetted world")).addArgument(Argument.of("[true|false]", "Set whether or not to preserve the seed. Default value is 'true'")).addArgument(Argument.of("[seed]", "Specifies a seed. Optional. Random seed is chosen if previous argument is false and this is not set"));
Help worldRegen = new Help("world regen", "regen", "Regenerates a world. You can preserve seed by setting true (true is default if none specified), or generate a new seed, random or specified").setPermission("pjw.cmd.world.regen").setUsage(usageRegen).addExample("/world regen MyWorld true").addExample("/world regen MyWorld false 3700507149557916849");
Usage usageRename = new Usage(Argument.of("<srcWorld>", "Specifies the targetted world")).addArgument(Argument.of("<newWorld>", "Specifies the new world name"));
Help worldRename = new Help("world rename", "rename", "Allows for renaming worlds. World must be unloaded before you can rename world").setPermission("pjw.cmd.world.rename").setUsage(usageRename).addExample("/world rename MyWorld NewWorldName");
Usage usageSetSpawn = new Usage(Argument.of("[<world>", "Specifies the targetted world")).addArgument(Argument.of("[x,y,z]]", "Specifies the coordinates to set spawn to. x and z must fall within the range -30,000,000 to 30,000,000 (exclusive, without the commas), and y must be within the range -4096 to 4096 inclusive."));
Help worldSetSpawn = new Help("world setspawn", "setspawn", "Sets the spawn point of specified world. If no arguments present sets spawn of current world to player location").setPermission("pjw.cmd.world.setspawn").setUsage(usageSetSpawn).addExample("/world setspawn MyWorld -153,75,300").addExample("/world setspawn");
Usage usageTeleport = new Usage(Argument.of("<world>", "Specifies the targetted world")).addArgument(Argument.of("[-c <x,y,z>]", "Specifies the coordinates to teleport to. x and z must fall within the range -30,000,000 to 30,000,000 (exclusive, without the commas), and y must be within the range -4096 to 4096 inclusive. Set to 'random' to teleport to random location")).addArgument(Argument.of("[-d <direction>]", "Specifies the direction player will face upon teleporting. The following can be used: NORTH, NORTH_WEST, WEST, SOUTH_WEST, SOUTH, SOUTH_EAST, EAST, NORTH_EAST")).addArgument(Argument.of("[-f]", "Skip safe location check. This flag has no effect with '-c random'"));
Help worldTeleport = new Help("world teleport", "teleport", "Teleport to specified world and location").setPermission("pjw.cmd.world.teleport").setUsage(usageTeleport).addExample("/world teleport MyWorld -c -153,75,300 -d WEST").addExample("/world teleport MyWorld -c -153,75,300").addExample("/world teleport MyWorld").addExample("/world teleport MyWorld -f");
Help worldUnload = new Help("world unload", "unload", "Unloads specified world. If players are in world, they will be teleported to default spawn").setPermission("pjw.cmd.world.unload").setUsage(usageLoad).addExample("/world unload MyWorld");
Help world = new Help("world", "world", "Base Project Worlds command").setPermission("pjw.cmd.world").addChild(worldUnload).addChild(worldTeleport).addChild(worldSetSpawn).addChild(worldRename).addChild(worldRegen).addChild(worldPvp).addChild(worldProperties).addChild(worldLoad).addChild(worldList).addChild(worldKeepSpawnLoaded).addChild(worldUseMapFeatures).addChild(worldImport).addChild(worldHardcore).addChild(worldGamerule).addChild(worldGamemode).addChild(worldFill).addChild(worldEnable).addChild(worldDifficulty).addChild(worldRemove).addChild(worldCreate).addChild(worldCopy).addChild(worldTime).addChild(worldWeather).addChild(worldLoadOnStartup).addChild(worldModifier);
Help.register(world);
}
use of org.spongepowered.api.world.DimensionType in project LanternServer by LanternPowered.
the class LanternWorldPropertiesIO method convert.
static LanternWorldProperties convert(LevelData levelData, WorldConfig worldConfig, boolean copyLevelSettingsToConfig) {
final LanternWorldProperties properties = new LanternWorldProperties(levelData.uniqueId, levelData.worldName, worldConfig);
final DataView dataView = levelData.worldData.getView(DATA).get();
final DataView spongeRootDataView = levelData.spongeWorldData;
final DataView spongeDataView;
if (spongeRootDataView != null) {
spongeDataView = spongeRootDataView.getView(DataQueries.SPONGE_DATA).orElse(null);
spongeDataView.remove(DataQueries.SPONGE_DATA);
} else {
spongeDataView = null;
}
final DataView lanternDataView = spongeDataView == null ? null : spongeDataView.getView(LANTERN).orElse(null);
properties.setLastPlayedTime(dataView.getLong(LAST_PLAYED).get());
properties.mapFeatures = dataView.getInt(MAP_FEATURES).get() > 0;
properties.setInitialized(dataView.getInt(INITIALIZED).get() > 0);
dataView.getInt(DIFFICULTY_LOCKED).ifPresent(v -> properties.setDifficultyLocked(v > 0));
final LanternWorldBorder border = properties.getWorldBorder();
dataView.getDouble(BORDER_CENTER_X).ifPresent(v -> border.centerX = v);
dataView.getDouble(BORDER_CENTER_Z).ifPresent(v -> border.centerZ = v);
dataView.getDouble(BORDER_SIZE_START).ifPresent(v -> border.diameterStart = v);
dataView.getDouble(BORDER_SIZE_END).ifPresent(v -> border.diameterEnd = v);
dataView.getLong(BORDER_SIZE_LERP_TIME).ifPresent(v -> border.lerpTime = v);
dataView.getDouble(BORDER_DAMAGE).ifPresent(v -> border.damage = v);
dataView.getDouble(BORDER_DAMAGE_THRESHOLD).ifPresent(v -> border.damageThreshold = v);
dataView.getInt(BORDER_WARNING_BLOCKS).ifPresent(v -> border.warningDistance = v);
dataView.getInt(BORDER_WARNING_TIME).ifPresent(v -> border.warningTime = v);
if (spongeRootDataView != null) {
properties.setAdditionalProperties(spongeRootDataView.copy().remove(DataQueries.SPONGE_DATA));
}
// Get the sponge properties
if (spongeDataView != null) {
// This can be null, this is provided in the lantern-server
final String dimensionTypeId = spongeDataView.getString(DIMENSION_TYPE).get();
if (dimensionTypeId.equalsIgnoreCase(OVERWORLD)) {
properties.setDimensionType(DimensionTypes.OVERWORLD);
} else if (dimensionTypeId.equalsIgnoreCase(NETHER)) {
properties.setDimensionType(DimensionTypes.NETHER);
} else if (dimensionTypeId.equalsIgnoreCase(END)) {
properties.setDimensionType(DimensionTypes.THE_END);
} else {
final DimensionType dimensionType = Sponge.getRegistry().getType(DimensionType.class, dimensionTypeId).orElse(null);
if (dimensionType == null) {
Lantern.getLogger().warn("Could not find a dimension type with id {} for the world {}, falling back to overworld...", dimensionTypeId, levelData.worldName);
}
properties.setDimensionType(dimensionType == null ? DimensionTypes.OVERWORLD : dimensionType);
}
PortalAgentType portalAgentType = null;
if (spongeDataView.contains(PORTAL_AGENT_TYPE)) {
final String portalAgentTypeId = spongeDataView.getString(PORTAL_AGENT_TYPE).get();
portalAgentType = Sponge.getRegistry().getType(PortalAgentType.class, portalAgentTypeId).orElse(null);
if (portalAgentType == null) {
Lantern.getLogger().warn("Could not find a portal agent type with id {} for the world {}, falling back to default...", portalAgentTypeId, levelData.worldName);
}
}
properties.setPortalAgentType(portalAgentType == null ? PortalAgentTypes.DEFAULT : portalAgentType);
spongeDataView.getInt(GENERATE_BONUS_CHEST).ifPresent(v -> properties.setGenerateBonusChest(v > 0));
spongeDataView.getInt(SERIALIZATION_BEHAVIOR).ifPresent(v -> properties.setSerializationBehavior(v == 0 ? SerializationBehaviors.MANUAL : v == 1 ? SerializationBehaviors.AUTOMATIC : SerializationBehaviors.NONE));
// Tracker
final Optional<List<DataView>> optTrackerUniqueIdViews = spongeDataView.getViewList(TRACKER_UUID_TABLE);
if (optTrackerUniqueIdViews.isPresent()) {
final List<DataView> trackerUniqueIdViews = optTrackerUniqueIdViews.get();
final Object2IntMap<UUID> trackerUniqueIds = properties.getTrackerIdAllocator().getUniqueIds();
final List<UUID> uniqueIdsByIndex = properties.getTrackerIdAllocator().getUniqueIdsByIndex();
for (DataView view : trackerUniqueIdViews) {
UUID uniqueId = null;
if (!view.isEmpty()) {
final long most = view.getLong(UUID_MOST).get();
final long least = view.getLong(UUID_LEAST).get();
uniqueId = new UUID(most, least);
trackerUniqueIds.put(uniqueId, uniqueIdsByIndex.size());
}
uniqueIdsByIndex.add(uniqueId);
}
}
}
// Weather
final WeatherData weatherData = properties.getWeatherData();
if (lanternDataView != null) {
final DataView weatherView = lanternDataView.getView(WEATHER).get();
final String weatherTypeId = weatherView.getString(WEATHER_TYPE).get();
final Optional<Weather> weatherType = Sponge.getRegistry().getType(Weather.class, weatherTypeId);
if (weatherType.isPresent()) {
weatherData.setWeather((LanternWeather) weatherType.get());
} else {
Lantern.getLogger().info("Unknown weather type: {}, the server will default to {}", weatherTypeId, weatherData.getWeather().getId());
}
weatherData.setRunningDuration(weatherView.getLong(WEATHER_RUNNING_DURATION).get());
weatherData.setRemainingDuration(weatherView.getLong(WEATHER_REMAINING_DURATION).get());
} else {
final boolean raining = dataView.getInt(RAINING).get() > 0;
final long rainTime = dataView.getLong(RAIN_TIME).get();
final boolean thundering = dataView.getInt(THUNDERING).get() > 0;
final long thunderTime = dataView.getLong(THUNDER_TIME).get();
final long clearWeatherTime = dataView.getLong(CLEAR_WEATHER_TIME).get();
if (thundering) {
weatherData.setWeather((LanternWeather) Weathers.THUNDER_STORM);
weatherData.setRemainingDuration(thunderTime);
} else if (raining) {
weatherData.setWeather((LanternWeather) Weathers.RAIN);
weatherData.setRemainingDuration(rainTime);
} else {
weatherData.setRemainingDuration(clearWeatherTime);
}
}
// Time
final TimeData timeData = properties.getTimeData();
final long age = dataView.getLong(AGE).get();
timeData.setAge(age);
final long time = dataView.getLong(TIME).orElse(age);
timeData.setDayTime(time);
if (lanternDataView != null && lanternDataView.contains(MOON_PHASE)) {
timeData.setMoonPhase(MoonPhase.valueOf(lanternDataView.getString(MOON_PHASE).get().toUpperCase()));
} else {
timeData.setMoonPhase(MoonPhase.values()[(int) (time / TimeUniverse.TICKS_IN_A_DAY) % 8]);
}
// Get the spawn position
final Optional<Integer> spawnX = dataView.getInt(SPAWN_X);
final Optional<Integer> spawnY = dataView.getInt(SPAWN_Y);
final Optional<Integer> spawnZ = dataView.getInt(SPAWN_Z);
if (spawnX.isPresent() && spawnY.isPresent() && spawnZ.isPresent()) {
properties.setSpawnPosition(new Vector3i(spawnX.get(), spawnY.get(), spawnZ.get()));
}
// Get the game rules
final DataView rulesView = dataView.getView(GAME_RULES).orElse(null);
if (rulesView != null) {
for (Entry<DataQuery, Object> en : rulesView.getValues(false).entrySet()) {
try {
properties.getRules().getOrCreateRule(RuleType.getOrCreate(en.getKey().toString(), RuleDataTypes.STRING, "")).setRawValue((String) en.getValue());
} catch (IllegalArgumentException e) {
Lantern.getLogger().warn("An error occurred while loading a game rule ({}) this one will be skipped", en.getKey().toString(), e);
}
}
}
if (copyLevelSettingsToConfig) {
worldConfig.getGeneration().setSeed(dataView.getLong(SEED).get());
worldConfig.setGameMode(GameModeRegistryModule.get().getByInternalId(dataView.getInt(GAME_MODE).get()).orElse(GameModes.SURVIVAL));
worldConfig.setHardcore(dataView.getInt(HARDCORE).get() > 0);
worldConfig.setDifficulty(DifficultyRegistryModule.get().getByInternalId(dataView.getInt(DIFFICULTY).get()).orElse(Difficulties.NORMAL));
if (dataView.contains(GENERATOR_NAME)) {
final String genName0 = dataView.getString(GENERATOR_NAME).get();
final String genName = genName0.indexOf(':') == -1 ? "minecraft:" + genName0 : genName0;
final GeneratorType generatorType = Sponge.getRegistry().getType(GeneratorType.class, genName).orElse(properties.getDimensionType().getDefaultGeneratorType());
DataContainer generatorSettings = null;
if (dataView.contains(GENERATOR_OPTIONS)) {
String options = dataView.getString(GENERATOR_OPTIONS).get();
String customSettings = null;
if (genName0.equalsIgnoreCase("flat")) {
customSettings = options;
// custom generator options to the flat generator
if (dataView.contains(GENERATOR_OPTIONS_EXTRA)) {
options = dataView.getString(GENERATOR_OPTIONS_EXTRA).get();
} else {
options = "";
}
}
if (!options.isEmpty()) {
try {
generatorSettings = JsonDataFormat.readContainer(options, false);
} catch (Exception e) {
Lantern.getLogger().warn("Unknown generator settings format \"{}\" for type {}, using defaults...", options, genName, e);
}
}
if (generatorSettings == null) {
generatorSettings = generatorType.getGeneratorSettings();
}
if (customSettings != null) {
generatorSettings.set(AbstractFlatGeneratorType.SETTINGS, customSettings);
}
} else {
generatorSettings = generatorType.getGeneratorSettings();
}
worldConfig.getGeneration().setGeneratorType(generatorType);
worldConfig.getGeneration().setGeneratorSettings(generatorSettings);
worldConfig.setLowHorizon(generatorType == GeneratorTypes.FLAT);
}
if (spongeDataView != null) {
spongeDataView.getInt(ENABLED).ifPresent(v -> worldConfig.setWorldEnabled(v > 0));
worldConfig.setKeepSpawnLoaded(spongeDataView.getInt(KEEP_SPAWN_LOADED).map(v -> v > 0).orElse(properties.getDimensionType().doesKeepSpawnLoaded()));
spongeDataView.getInt(LOAD_ON_STARTUP).ifPresent(v -> worldConfig.setKeepSpawnLoaded(v > 0));
spongeDataView.getStringList(GENERATOR_MODIFIERS).ifPresent(v -> {
final List<String> modifiers = worldConfig.getGeneration().getGenerationModifiers();
modifiers.clear();
modifiers.addAll(v);
properties.updateWorldGenModifiers(modifiers);
});
} else {
final LanternDimensionType dimensionType = properties.getDimensionType();
worldConfig.setKeepSpawnLoaded(dimensionType.doesKeepSpawnLoaded());
worldConfig.setDoesWaterEvaporate(dimensionType.doesWaterEvaporate());
}
}
return properties;
}
Aggregations