| 1 | package net.minecraft.commands.arguments;
|
| 2 |
|
| 3 | import com.mojang.brigadier.StringReader;
|
| 4 | import com.mojang.brigadier.arguments.ArgumentType;
|
| 5 | import com.mojang.brigadier.context.CommandContext;
|
| 6 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 7 | import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
| 8 | import com.mojang.brigadier.suggestion.Suggestions;
|
| 9 | import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
| 10 | import java.util.Collection;
|
| 11 | import java.util.concurrent.CompletableFuture;
|
| 12 | import java.util.stream.Collectors;
|
| 13 | import java.util.stream.Stream;
|
| 14 | import net.minecraft.commands.CommandSourceStack;
|
| 15 | import net.minecraft.commands.SharedSuggestionProvider;
|
| 16 | import net.minecraft.core.registries.Registries;
|
| 17 | import net.minecraft.network.chat.Component;
|
| 18 | import net.minecraft.resources.Identifier;
|
| 19 | import net.minecraft.resources.ResourceKey;
|
| 20 | import net.minecraft.server.level.ServerLevel;
|
| 21 | import net.minecraft.world.level.Level;
|
| 22 |
|
| 23 | public class DimensionArgument implements ArgumentType<Identifier> {
|
| 24 | private static final Collection<String> EXAMPLES = Stream.of(Level.OVERWORLD, Level.NETHER)
|
| 25 | .map(key -> key.identifier().toString())
|
| 26 | .collect(Collectors.toList());
|
| 27 | private static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType(
|
| 28 | value -> Component.translatableEscape("argument.dimension.invalid", value)
|
| 29 | );
|
| 30 |
|
| 31 | public Identifier parse(final StringReader reader) throws CommandSyntaxException {
|
| 32 | return Identifier.read(reader);
|
| 33 | }
|
| 34 |
|
| 35 | @Override
|
| 36 | public <S> CompletableFuture<Suggestions> listSuggestions(final CommandContext<S> context, final SuggestionsBuilder builder) {
|
| 37 | return context.getSource() instanceof SharedSuggestionProvider
|
| 38 | ? SharedSuggestionProvider.suggestResource(((SharedSuggestionProvider)context.getSource()).levels().stream().map(ResourceKey::identifier), builder)
|
| 39 | : Suggestions.empty();
|
| 40 | }
|
| 41 |
|
| 42 | @Override
|
| 43 | public Collection<String> getExamples() {
|
| 44 | return EXAMPLES;
|
| 45 | }
|
| 46 |
|
| 47 | public static DimensionArgument dimension() {
|
| 48 | return new DimensionArgument();
|
| 49 | }
|
| 50 |
|
| 51 | public static ServerLevel getDimension(final CommandContext<CommandSourceStack> context, final String name) throws CommandSyntaxException {
|
| 52 | Identifier location = context.getArgument(name, Identifier.class);
|
| 53 | ResourceKey<Level> key = ResourceKey.create(Registries.DIMENSION, location);
|
| 54 | ServerLevel level = context.getSource().getServer().getLevel(key);
|
| 55 | if (level == null) {
|
| 56 | throw ERROR_INVALID_VALUE.create(location);
|
| 57 | } else {
|
| 58 | return level;
|
| 59 | }
|
| 60 | }
|
| 61 | }
|
| 62 |
|