Initial Commit
This commit is contained in:
1 parent
377b32db6e
commit
2d9a5eecba
14134 files changed
+1160982
No files matched your search
+179
@@ -0,0 +1,179 @@
|
||||
package net.minecraft.commands;
|
||||
|
||||
import com.mojang.brigadier.exceptions.BuiltInExceptionProvider;
|
||||
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public class BrigadierExceptions implements BuiltInExceptionProvider {
|
||||
private static final Dynamic2CommandExceptionType DOUBLE_TOO_SMALL = new Dynamic2CommandExceptionType((p_77203_, p_77204_) -> {
|
||||
return Component.translatable("argument.double.low", p_77204_, p_77203_);
|
||||
});
|
||||
private static final Dynamic2CommandExceptionType DOUBLE_TOO_BIG = new Dynamic2CommandExceptionType((p_77198_, p_77199_) -> {
|
||||
return Component.translatable("argument.double.big", p_77199_, p_77198_);
|
||||
});
|
||||
private static final Dynamic2CommandExceptionType FLOAT_TOO_SMALL = new Dynamic2CommandExceptionType((p_77191_, p_77192_) -> {
|
||||
return Component.translatable("argument.float.low", p_77192_, p_77191_);
|
||||
});
|
||||
private static final Dynamic2CommandExceptionType FLOAT_TOO_BIG = new Dynamic2CommandExceptionType((p_77186_, p_77187_) -> {
|
||||
return Component.translatable("argument.float.big", p_77187_, p_77186_);
|
||||
});
|
||||
private static final Dynamic2CommandExceptionType INTEGER_TOO_SMALL = new Dynamic2CommandExceptionType((p_77175_, p_77176_) -> {
|
||||
return Component.translatable("argument.integer.low", p_77176_, p_77175_);
|
||||
});
|
||||
private static final Dynamic2CommandExceptionType INTEGER_TOO_BIG = new Dynamic2CommandExceptionType((p_77170_, p_77171_) -> {
|
||||
return Component.translatable("argument.integer.big", p_77171_, p_77170_);
|
||||
});
|
||||
private static final Dynamic2CommandExceptionType LONG_TOO_SMALL = new Dynamic2CommandExceptionType((p_77165_, p_77166_) -> {
|
||||
return Component.translatable("argument.long.low", p_77166_, p_77165_);
|
||||
});
|
||||
private static final Dynamic2CommandExceptionType LONG_TOO_BIG = new Dynamic2CommandExceptionType((p_77160_, p_77161_) -> {
|
||||
return Component.translatable("argument.long.big", p_77161_, p_77160_);
|
||||
});
|
||||
private static final DynamicCommandExceptionType LITERAL_INCORRECT = new DynamicCommandExceptionType((p_77206_) -> {
|
||||
return Component.translatable("argument.literal.incorrect", p_77206_);
|
||||
});
|
||||
private static final SimpleCommandExceptionType READER_EXPECTED_START_OF_QUOTE = new SimpleCommandExceptionType(Component.translatable("parsing.quote.expected.start"));
|
||||
private static final SimpleCommandExceptionType READER_EXPECTED_END_OF_QUOTE = new SimpleCommandExceptionType(Component.translatable("parsing.quote.expected.end"));
|
||||
private static final DynamicCommandExceptionType READER_INVALID_ESCAPE = new DynamicCommandExceptionType((p_77201_) -> {
|
||||
return Component.translatable("parsing.quote.escape", p_77201_);
|
||||
});
|
||||
private static final DynamicCommandExceptionType READER_INVALID_BOOL = new DynamicCommandExceptionType((p_77196_) -> {
|
||||
return Component.translatable("parsing.bool.invalid", p_77196_);
|
||||
});
|
||||
private static final DynamicCommandExceptionType READER_INVALID_INT = new DynamicCommandExceptionType((p_77189_) -> {
|
||||
return Component.translatable("parsing.int.invalid", p_77189_);
|
||||
});
|
||||
private static final SimpleCommandExceptionType READER_EXPECTED_INT = new SimpleCommandExceptionType(Component.translatable("parsing.int.expected"));
|
||||
private static final DynamicCommandExceptionType READER_INVALID_LONG = new DynamicCommandExceptionType((p_77184_) -> {
|
||||
return Component.translatable("parsing.long.invalid", p_77184_);
|
||||
});
|
||||
private static final SimpleCommandExceptionType READER_EXPECTED_LONG = new SimpleCommandExceptionType(Component.translatable("parsing.long.expected"));
|
||||
private static final DynamicCommandExceptionType READER_INVALID_DOUBLE = new DynamicCommandExceptionType((p_77173_) -> {
|
||||
return Component.translatable("parsing.double.invalid", p_77173_);
|
||||
});
|
||||
private static final SimpleCommandExceptionType READER_EXPECTED_DOUBLE = new SimpleCommandExceptionType(Component.translatable("parsing.double.expected"));
|
||||
private static final DynamicCommandExceptionType READER_INVALID_FLOAT = new DynamicCommandExceptionType((p_77168_) -> {
|
||||
return Component.translatable("parsing.float.invalid", p_77168_);
|
||||
});
|
||||
private static final SimpleCommandExceptionType READER_EXPECTED_FLOAT = new SimpleCommandExceptionType(Component.translatable("parsing.float.expected"));
|
||||
private static final SimpleCommandExceptionType READER_EXPECTED_BOOL = new SimpleCommandExceptionType(Component.translatable("parsing.bool.expected"));
|
||||
private static final DynamicCommandExceptionType READER_EXPECTED_SYMBOL = new DynamicCommandExceptionType((p_77163_) -> {
|
||||
return Component.translatable("parsing.expected", p_77163_);
|
||||
});
|
||||
private static final SimpleCommandExceptionType DISPATCHER_UNKNOWN_COMMAND = new SimpleCommandExceptionType(Component.translatable("command.unknown.command"));
|
||||
private static final SimpleCommandExceptionType DISPATCHER_UNKNOWN_ARGUMENT = new SimpleCommandExceptionType(Component.translatable("command.unknown.argument"));
|
||||
private static final SimpleCommandExceptionType DISPATCHER_EXPECTED_ARGUMENT_SEPARATOR = new SimpleCommandExceptionType(Component.translatable("command.expected.separator"));
|
||||
private static final DynamicCommandExceptionType DISPATCHER_PARSE_EXCEPTION = new DynamicCommandExceptionType((p_77158_) -> {
|
||||
return Component.translatable("command.exception", p_77158_);
|
||||
});
|
||||
|
||||
public Dynamic2CommandExceptionType doubleTooLow() {
|
||||
return DOUBLE_TOO_SMALL;
|
||||
}
|
||||
|
||||
public Dynamic2CommandExceptionType doubleTooHigh() {
|
||||
return DOUBLE_TOO_BIG;
|
||||
}
|
||||
|
||||
public Dynamic2CommandExceptionType floatTooLow() {
|
||||
return FLOAT_TOO_SMALL;
|
||||
}
|
||||
|
||||
public Dynamic2CommandExceptionType floatTooHigh() {
|
||||
return FLOAT_TOO_BIG;
|
||||
}
|
||||
|
||||
public Dynamic2CommandExceptionType integerTooLow() {
|
||||
return INTEGER_TOO_SMALL;
|
||||
}
|
||||
|
||||
public Dynamic2CommandExceptionType integerTooHigh() {
|
||||
return INTEGER_TOO_BIG;
|
||||
}
|
||||
|
||||
public Dynamic2CommandExceptionType longTooLow() {
|
||||
return LONG_TOO_SMALL;
|
||||
}
|
||||
|
||||
public Dynamic2CommandExceptionType longTooHigh() {
|
||||
return LONG_TOO_BIG;
|
||||
}
|
||||
|
||||
public DynamicCommandExceptionType literalIncorrect() {
|
||||
return LITERAL_INCORRECT;
|
||||
}
|
||||
|
||||
public SimpleCommandExceptionType readerExpectedStartOfQuote() {
|
||||
return READER_EXPECTED_START_OF_QUOTE;
|
||||
}
|
||||
|
||||
public SimpleCommandExceptionType readerExpectedEndOfQuote() {
|
||||
return READER_EXPECTED_END_OF_QUOTE;
|
||||
}
|
||||
|
||||
public DynamicCommandExceptionType readerInvalidEscape() {
|
||||
return READER_INVALID_ESCAPE;
|
||||
}
|
||||
|
||||
public DynamicCommandExceptionType readerInvalidBool() {
|
||||
return READER_INVALID_BOOL;
|
||||
}
|
||||
|
||||
public DynamicCommandExceptionType readerInvalidInt() {
|
||||
return READER_INVALID_INT;
|
||||
}
|
||||
|
||||
public SimpleCommandExceptionType readerExpectedInt() {
|
||||
return READER_EXPECTED_INT;
|
||||
}
|
||||
|
||||
public DynamicCommandExceptionType readerInvalidLong() {
|
||||
return READER_INVALID_LONG;
|
||||
}
|
||||
|
||||
public SimpleCommandExceptionType readerExpectedLong() {
|
||||
return READER_EXPECTED_LONG;
|
||||
}
|
||||
|
||||
public DynamicCommandExceptionType readerInvalidDouble() {
|
||||
return READER_INVALID_DOUBLE;
|
||||
}
|
||||
|
||||
public SimpleCommandExceptionType readerExpectedDouble() {
|
||||
return READER_EXPECTED_DOUBLE;
|
||||
}
|
||||
|
||||
public DynamicCommandExceptionType readerInvalidFloat() {
|
||||
return READER_INVALID_FLOAT;
|
||||
}
|
||||
|
||||
public SimpleCommandExceptionType readerExpectedFloat() {
|
||||
return READER_EXPECTED_FLOAT;
|
||||
}
|
||||
|
||||
public SimpleCommandExceptionType readerExpectedBool() {
|
||||
return READER_EXPECTED_BOOL;
|
||||
}
|
||||
|
||||
public DynamicCommandExceptionType readerExpectedSymbol() {
|
||||
return READER_EXPECTED_SYMBOL;
|
||||
}
|
||||
|
||||
public SimpleCommandExceptionType dispatcherUnknownCommand() {
|
||||
return DISPATCHER_UNKNOWN_COMMAND;
|
||||
}
|
||||
|
||||
public SimpleCommandExceptionType dispatcherUnknownArgument() {
|
||||
return DISPATCHER_UNKNOWN_ARGUMENT;
|
||||
}
|
||||
|
||||
public SimpleCommandExceptionType dispatcherExpectedArgumentSeparator() {
|
||||
return DISPATCHER_EXPECTED_ARGUMENT_SEPARATOR;
|
||||
}
|
||||
|
||||
public DynamicCommandExceptionType dispatcherParseException() {
|
||||
return DISPATCHER_PARSE_EXCEPTION;
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package net.minecraft.commands;
|
||||
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.flag.FeatureFlagSet;
|
||||
|
||||
public interface CommandBuildContext {
|
||||
<T> HolderLookup<T> holderLookup(ResourceKey<? extends Registry<T>> pRegistryResourceKey);
|
||||
|
||||
static CommandBuildContext simple(final HolderLookup.Provider pProvider, final FeatureFlagSet pEnabledFeatures) {
|
||||
return new CommandBuildContext() {
|
||||
public <T> HolderLookup<T> holderLookup(ResourceKey<? extends Registry<T>> p_255791_) {
|
||||
return pProvider.lookupOrThrow(p_255791_).filterFeatures(pEnabledFeatures);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static CommandBuildContext.Configurable configurable(final RegistryAccess pRegistryAccess, final FeatureFlagSet pEnabledFeatures) {
|
||||
return new CommandBuildContext.Configurable() {
|
||||
CommandBuildContext.MissingTagAccessPolicy missingTagAccessPolicy = CommandBuildContext.MissingTagAccessPolicy.FAIL;
|
||||
|
||||
public void missingTagAccessPolicy(CommandBuildContext.MissingTagAccessPolicy p_256626_) {
|
||||
this.missingTagAccessPolicy = p_256626_;
|
||||
}
|
||||
|
||||
public <T> HolderLookup<T> holderLookup(ResourceKey<? extends Registry<T>> p_256616_) {
|
||||
Registry<T> registry = pRegistryAccess.registryOrThrow(p_256616_);
|
||||
final HolderLookup.RegistryLookup<T> registrylookup = registry.asLookup();
|
||||
final HolderLookup.RegistryLookup<T> registrylookup1 = registry.asTagAddingLookup();
|
||||
HolderLookup.RegistryLookup<T> registrylookup2 = new HolderLookup.RegistryLookup.Delegate<T>() {
|
||||
protected HolderLookup.RegistryLookup<T> parent() {
|
||||
HolderLookup.RegistryLookup holderlookup$registrylookup;
|
||||
switch (missingTagAccessPolicy) {
|
||||
case FAIL:
|
||||
holderlookup$registrylookup = registrylookup;
|
||||
break;
|
||||
case CREATE_NEW:
|
||||
holderlookup$registrylookup = registrylookup1;
|
||||
break;
|
||||
default:
|
||||
throw new IncompatibleClassChangeError();
|
||||
}
|
||||
|
||||
return holderlookup$registrylookup;
|
||||
}
|
||||
};
|
||||
return registrylookup2.filterFeatures(pEnabledFeatures);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public interface Configurable extends CommandBuildContext {
|
||||
void missingTagAccessPolicy(CommandBuildContext.MissingTagAccessPolicy pMissingTagAccessPolicy);
|
||||
}
|
||||
|
||||
public static enum MissingTagAccessPolicy {
|
||||
CREATE_NEW,
|
||||
FAIL;
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package net.minecraft.commands;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.brigadier.CommandDispatcher;
|
||||
import com.mojang.brigadier.ParseResults;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.ServerFunctionManager;
|
||||
|
||||
public class CommandFunction {
|
||||
private final CommandFunction.Entry[] entries;
|
||||
final ResourceLocation id;
|
||||
|
||||
public CommandFunction(ResourceLocation pId, CommandFunction.Entry[] pEntries) {
|
||||
this.id = pId;
|
||||
this.entries = pEntries;
|
||||
}
|
||||
|
||||
public ResourceLocation getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public CommandFunction.Entry[] getEntries() {
|
||||
return this.entries;
|
||||
}
|
||||
|
||||
public static CommandFunction fromLines(ResourceLocation pId, CommandDispatcher<CommandSourceStack> pDispatcher, CommandSourceStack pSource, List<String> pLines) {
|
||||
List<CommandFunction.Entry> list = Lists.newArrayListWithCapacity(pLines.size());
|
||||
|
||||
for(int i = 0; i < pLines.size(); ++i) {
|
||||
int j = i + 1;
|
||||
String s = pLines.get(i).trim();
|
||||
StringReader stringreader = new StringReader(s);
|
||||
if (stringreader.canRead() && stringreader.peek() != '#') {
|
||||
if (stringreader.peek() == '/') {
|
||||
stringreader.skip();
|
||||
if (stringreader.peek() == '/') {
|
||||
throw new IllegalArgumentException("Unknown or invalid command '" + s + "' on line " + j + " (if you intended to make a comment, use '#' not '//')");
|
||||
}
|
||||
|
||||
String s1 = stringreader.readUnquotedString();
|
||||
throw new IllegalArgumentException("Unknown or invalid command '" + s + "' on line " + j + " (did you mean '" + s1 + "'? Do not use a preceding forwards slash.)");
|
||||
}
|
||||
|
||||
try {
|
||||
ParseResults<CommandSourceStack> parseresults = pDispatcher.parse(stringreader, pSource);
|
||||
if (parseresults.getReader().canRead()) {
|
||||
throw Commands.getParseException(parseresults);
|
||||
}
|
||||
|
||||
list.add(new CommandFunction.CommandEntry(parseresults));
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
throw new IllegalArgumentException("Whilst parsing command on line " + j + ": " + commandsyntaxexception.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new CommandFunction(pId, list.toArray(new CommandFunction.Entry[0]));
|
||||
}
|
||||
|
||||
public static class CacheableFunction {
|
||||
public static final CommandFunction.CacheableFunction NONE = new CommandFunction.CacheableFunction((ResourceLocation)null);
|
||||
@Nullable
|
||||
private final ResourceLocation id;
|
||||
private boolean resolved;
|
||||
private Optional<CommandFunction> function = Optional.empty();
|
||||
|
||||
public CacheableFunction(@Nullable ResourceLocation pId) {
|
||||
this.id = pId;
|
||||
}
|
||||
|
||||
public CacheableFunction(CommandFunction pFunction) {
|
||||
this.resolved = true;
|
||||
this.id = null;
|
||||
this.function = Optional.of(pFunction);
|
||||
}
|
||||
|
||||
public Optional<CommandFunction> get(ServerFunctionManager pFunctionManager) {
|
||||
if (!this.resolved) {
|
||||
if (this.id != null) {
|
||||
this.function = pFunctionManager.get(this.id);
|
||||
}
|
||||
|
||||
this.resolved = true;
|
||||
}
|
||||
|
||||
return this.function;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public ResourceLocation getId() {
|
||||
return this.function.map((p_78001_) -> {
|
||||
return p_78001_.id;
|
||||
}).orElse(this.id);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CommandEntry implements CommandFunction.Entry {
|
||||
private final ParseResults<CommandSourceStack> parse;
|
||||
|
||||
public CommandEntry(ParseResults<CommandSourceStack> pParse) {
|
||||
this.parse = pParse;
|
||||
}
|
||||
|
||||
public void execute(ServerFunctionManager pFunctionManager, CommandSourceStack pSource, Deque<ServerFunctionManager.QueuedCommand> pQueuedCommands, int pCommandLimit, int pDepth, @Nullable ServerFunctionManager.TraceCallbacks pTracer) throws CommandSyntaxException {
|
||||
if (pTracer != null) {
|
||||
String s = this.parse.getReader().getString();
|
||||
pTracer.onCommand(pDepth, s);
|
||||
int i = this.execute(pFunctionManager, pSource);
|
||||
pTracer.onReturn(pDepth, s, i);
|
||||
} else {
|
||||
this.execute(pFunctionManager, pSource);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private int execute(ServerFunctionManager pFunctionManager, CommandSourceStack pSource) throws CommandSyntaxException {
|
||||
return pFunctionManager.getDispatcher().execute(Commands.mapSource(this.parse, (p_242934_) -> {
|
||||
return pSource;
|
||||
}));
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.parse.getReader().getString();
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Entry {
|
||||
void execute(ServerFunctionManager pFunctionManager, CommandSourceStack pSource, Deque<ServerFunctionManager.QueuedCommand> pQueuedCommands, int pCommandLimit, int pDepth, @Nullable ServerFunctionManager.TraceCallbacks pTracer) throws CommandSyntaxException;
|
||||
}
|
||||
|
||||
public static class FunctionEntry implements CommandFunction.Entry {
|
||||
private final CommandFunction.CacheableFunction function;
|
||||
|
||||
public FunctionEntry(CommandFunction pFunction) {
|
||||
this.function = new CommandFunction.CacheableFunction(pFunction);
|
||||
}
|
||||
|
||||
public void execute(ServerFunctionManager pFunctionManager, CommandSourceStack pSource, Deque<ServerFunctionManager.QueuedCommand> pQueuedCommands, int pCommandLimit, int pDepth, @Nullable ServerFunctionManager.TraceCallbacks pTracer) {
|
||||
Util.ifElse(this.function.get(pFunctionManager), (p_164900_) -> {
|
||||
CommandFunction.Entry[] acommandfunction$entry = p_164900_.getEntries();
|
||||
if (pTracer != null) {
|
||||
pTracer.onCall(pDepth, p_164900_.getId(), acommandfunction$entry.length);
|
||||
}
|
||||
|
||||
int i = pCommandLimit - pQueuedCommands.size();
|
||||
int j = Math.min(acommandfunction$entry.length, i);
|
||||
|
||||
for(int k = j - 1; k >= 0; --k) {
|
||||
pQueuedCommands.addFirst(new ServerFunctionManager.QueuedCommand(pSource, pDepth + 1, acommandfunction$entry[k]));
|
||||
}
|
||||
|
||||
}, () -> {
|
||||
if (pTracer != null) {
|
||||
pTracer.onCall(pDepth, this.function.getId(), -1);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "function " + this.function.getId();
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package net.minecraft.commands;
|
||||
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public class CommandRuntimeException extends RuntimeException {
|
||||
private final Component message;
|
||||
|
||||
public CommandRuntimeException(Component pMessage) {
|
||||
super(pMessage.getString(), (Throwable)null, CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES, CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES);
|
||||
this.message = pMessage;
|
||||
}
|
||||
|
||||
public Component getComponent() {
|
||||
return this.message;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package net.minecraft.commands;
|
||||
|
||||
import java.util.Map;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.network.chat.PlayerChatMessage;
|
||||
|
||||
public interface CommandSigningContext {
|
||||
CommandSigningContext ANONYMOUS = new CommandSigningContext() {
|
||||
@Nullable
|
||||
public PlayerChatMessage getArgument(String p_242898_) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
@Nullable
|
||||
PlayerChatMessage getArgument(String pName);
|
||||
|
||||
public static record SignedArguments(Map<String, PlayerChatMessage> arguments) implements CommandSigningContext {
|
||||
@Nullable
|
||||
public PlayerChatMessage getArgument(String p_242852_) {
|
||||
return this.arguments.get(p_242852_);
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package net.minecraft.commands;
|
||||
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public interface CommandSource {
|
||||
/** A {@code CommandSource} that ignores all messages. */
|
||||
CommandSource NULL = new CommandSource() {
|
||||
public void sendSystemMessage(Component p_230799_) {
|
||||
}
|
||||
|
||||
public boolean acceptsSuccess() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean acceptsFailure() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean shouldInformAdmins() {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
void sendSystemMessage(Component pComponent);
|
||||
|
||||
boolean acceptsSuccess();
|
||||
|
||||
boolean acceptsFailure();
|
||||
|
||||
boolean shouldInformAdmins();
|
||||
|
||||
default boolean alwaysAccepts() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
package net.minecraft.commands;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.brigadier.ResultConsumer;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Collection;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.function.IntConsumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.commands.arguments.EntityAnchorArgument;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.network.chat.ChatType;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.OutgoingChatMessage;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.util.TaskChainer;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.flag.FeatureFlagSet;
|
||||
import net.minecraft.world.level.GameRules;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.phys.Vec2;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class CommandSourceStack implements SharedSuggestionProvider, net.minecraftforge.common.extensions.IForgeCommandSourceStack {
|
||||
public static final SimpleCommandExceptionType ERROR_NOT_PLAYER = new SimpleCommandExceptionType(Component.translatable("permissions.requires.player"));
|
||||
public static final SimpleCommandExceptionType ERROR_NOT_ENTITY = new SimpleCommandExceptionType(Component.translatable("permissions.requires.entity"));
|
||||
public final CommandSource source;
|
||||
private final Vec3 worldPosition;
|
||||
private final ServerLevel level;
|
||||
private final int permissionLevel;
|
||||
private final String textName;
|
||||
private final Component displayName;
|
||||
private final MinecraftServer server;
|
||||
private final boolean silent;
|
||||
@Nullable
|
||||
private final Entity entity;
|
||||
@Nullable
|
||||
private final ResultConsumer<CommandSourceStack> consumer;
|
||||
private final EntityAnchorArgument.Anchor anchor;
|
||||
private final Vec2 rotation;
|
||||
private final CommandSigningContext signingContext;
|
||||
private final TaskChainer chatMessageChainer;
|
||||
private final IntConsumer returnValueConsumer;
|
||||
|
||||
public CommandSourceStack(CommandSource pSource, Vec3 pWorldPosition, Vec2 pRotation, ServerLevel pLevel, int pPermissionLevel, String pTextName, Component pDisplayName, MinecraftServer pServer, @Nullable Entity pEntity) {
|
||||
this(pSource, pWorldPosition, pRotation, pLevel, pPermissionLevel, pTextName, pDisplayName, pServer, pEntity, false, (p_81361_, p_81362_, p_81363_) -> {
|
||||
}, EntityAnchorArgument.Anchor.FEET, CommandSigningContext.ANONYMOUS, TaskChainer.immediate(pServer), (p_280930_) -> {
|
||||
});
|
||||
}
|
||||
|
||||
protected CommandSourceStack(CommandSource pSource, Vec3 pWorldPosition, Vec2 pRotation, ServerLevel pLevel, int pPermissionLevel, String pTextName, Component pDisplayName, MinecraftServer pServer, @Nullable Entity pEntity, boolean pSilent, @Nullable ResultConsumer<CommandSourceStack> pConsumer, EntityAnchorArgument.Anchor pAnchor, CommandSigningContext pSigningContext, TaskChainer pChatMessageContainer, IntConsumer pReturnValueConsumer) {
|
||||
this.source = pSource;
|
||||
this.worldPosition = pWorldPosition;
|
||||
this.level = pLevel;
|
||||
this.silent = pSilent;
|
||||
this.entity = pEntity;
|
||||
this.permissionLevel = pPermissionLevel;
|
||||
this.textName = pTextName;
|
||||
this.displayName = pDisplayName;
|
||||
this.server = pServer;
|
||||
this.consumer = pConsumer;
|
||||
this.anchor = pAnchor;
|
||||
this.rotation = pRotation;
|
||||
this.signingContext = pSigningContext;
|
||||
this.chatMessageChainer = pChatMessageContainer;
|
||||
this.returnValueConsumer = pReturnValueConsumer;
|
||||
}
|
||||
|
||||
public CommandSourceStack withSource(CommandSource pSource) {
|
||||
return this.source == pSource ? this : new CommandSourceStack(pSource, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
|
||||
}
|
||||
|
||||
public CommandSourceStack withEntity(Entity pEntity) {
|
||||
return this.entity == pEntity ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, pEntity.getName().getString(), pEntity.getDisplayName(), this.server, pEntity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
|
||||
}
|
||||
|
||||
public CommandSourceStack withPosition(Vec3 pPos) {
|
||||
return this.worldPosition.equals(pPos) ? this : new CommandSourceStack(this.source, pPos, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
|
||||
}
|
||||
|
||||
public CommandSourceStack withRotation(Vec2 pRotation) {
|
||||
return this.rotation.equals(pRotation) ? this : new CommandSourceStack(this.source, this.worldPosition, pRotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
|
||||
}
|
||||
|
||||
public CommandSourceStack withCallback(ResultConsumer<CommandSourceStack> pConsumer) {
|
||||
return Objects.equals(this.consumer, pConsumer) ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, pConsumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
|
||||
}
|
||||
|
||||
public CommandSourceStack withCallback(ResultConsumer<CommandSourceStack> pResultConsumer, BinaryOperator<ResultConsumer<CommandSourceStack>> pResultConsumerSelector) {
|
||||
ResultConsumer<CommandSourceStack> resultconsumer = pResultConsumerSelector.apply(this.consumer, pResultConsumer);
|
||||
return this.withCallback(resultconsumer);
|
||||
}
|
||||
|
||||
public CommandSourceStack withSuppressedOutput() {
|
||||
return !this.silent && !this.source.alwaysAccepts() ? new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, true, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer) : this;
|
||||
}
|
||||
|
||||
public CommandSourceStack withPermission(int pPermissionLevel) {
|
||||
return pPermissionLevel == this.permissionLevel ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, pPermissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
|
||||
}
|
||||
|
||||
public CommandSourceStack withMaximumPermission(int pPermissionLevel) {
|
||||
return pPermissionLevel <= this.permissionLevel ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, pPermissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
|
||||
}
|
||||
|
||||
public CommandSourceStack withAnchor(EntityAnchorArgument.Anchor pAnchor) {
|
||||
return pAnchor == this.anchor ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, pAnchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
|
||||
}
|
||||
|
||||
public CommandSourceStack withLevel(ServerLevel pLevel) {
|
||||
if (pLevel == this.level) {
|
||||
return this;
|
||||
} else {
|
||||
double d0 = DimensionType.getTeleportationScale(this.level.dimensionType(), pLevel.dimensionType());
|
||||
Vec3 vec3 = new Vec3(this.worldPosition.x * d0, this.worldPosition.y, this.worldPosition.z * d0);
|
||||
return new CommandSourceStack(this.source, vec3, this.rotation, pLevel, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
|
||||
}
|
||||
}
|
||||
|
||||
public CommandSourceStack facing(Entity pEntity, EntityAnchorArgument.Anchor pAnchor) {
|
||||
return this.facing(pAnchor.apply(pEntity));
|
||||
}
|
||||
|
||||
public CommandSourceStack facing(Vec3 pLookPos) {
|
||||
Vec3 vec3 = this.anchor.apply(this);
|
||||
double d0 = pLookPos.x - vec3.x;
|
||||
double d1 = pLookPos.y - vec3.y;
|
||||
double d2 = pLookPos.z - vec3.z;
|
||||
double d3 = Math.sqrt(d0 * d0 + d2 * d2);
|
||||
float f = Mth.wrapDegrees((float)(-(Mth.atan2(d1, d3) * (double)(180F / (float)Math.PI))));
|
||||
float f1 = Mth.wrapDegrees((float)(Mth.atan2(d2, d0) * (double)(180F / (float)Math.PI)) - 90.0F);
|
||||
return this.withRotation(new Vec2(f, f1));
|
||||
}
|
||||
|
||||
public CommandSourceStack withSigningContext(CommandSigningContext pSigningContext) {
|
||||
return pSigningContext == this.signingContext ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, pSigningContext, this.chatMessageChainer, this.returnValueConsumer);
|
||||
}
|
||||
|
||||
public CommandSourceStack withChatMessageChainer(TaskChainer pChatMessageChainer) {
|
||||
return pChatMessageChainer == this.chatMessageChainer ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, pChatMessageChainer, this.returnValueConsumer);
|
||||
}
|
||||
|
||||
public CommandSourceStack withReturnValueConsumer(IntConsumer pReturnValueConsumer) {
|
||||
return pReturnValueConsumer == this.returnValueConsumer ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, pReturnValueConsumer);
|
||||
}
|
||||
|
||||
public Component getDisplayName() {
|
||||
return this.displayName;
|
||||
}
|
||||
|
||||
public String getTextName() {
|
||||
return this.textName;
|
||||
}
|
||||
|
||||
public boolean hasPermission(int pLevel) {
|
||||
return this.permissionLevel >= pLevel;
|
||||
}
|
||||
|
||||
public Vec3 getPosition() {
|
||||
return this.worldPosition;
|
||||
}
|
||||
|
||||
public ServerLevel getLevel() {
|
||||
return this.level;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Entity getEntity() {
|
||||
return this.entity;
|
||||
}
|
||||
|
||||
public Entity getEntityOrException() throws CommandSyntaxException {
|
||||
if (this.entity == null) {
|
||||
throw ERROR_NOT_ENTITY.create();
|
||||
} else {
|
||||
return this.entity;
|
||||
}
|
||||
}
|
||||
|
||||
public ServerPlayer getPlayerOrException() throws CommandSyntaxException {
|
||||
Entity entity = this.entity;
|
||||
if (entity instanceof ServerPlayer) {
|
||||
return (ServerPlayer)entity;
|
||||
} else {
|
||||
throw ERROR_NOT_PLAYER.create();
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public ServerPlayer getPlayer() {
|
||||
Entity entity = this.entity;
|
||||
ServerPlayer serverplayer1;
|
||||
if (entity instanceof ServerPlayer serverplayer) {
|
||||
serverplayer1 = serverplayer;
|
||||
} else {
|
||||
serverplayer1 = null;
|
||||
}
|
||||
|
||||
return serverplayer1;
|
||||
}
|
||||
|
||||
public boolean isPlayer() {
|
||||
return this.entity instanceof ServerPlayer;
|
||||
}
|
||||
|
||||
public Vec2 getRotation() {
|
||||
return this.rotation;
|
||||
}
|
||||
|
||||
public MinecraftServer getServer() {
|
||||
return this.server;
|
||||
}
|
||||
|
||||
public EntityAnchorArgument.Anchor getAnchor() {
|
||||
return this.anchor;
|
||||
}
|
||||
|
||||
public CommandSigningContext getSigningContext() {
|
||||
return this.signingContext;
|
||||
}
|
||||
|
||||
public TaskChainer getChatMessageChainer() {
|
||||
return this.chatMessageChainer;
|
||||
}
|
||||
|
||||
public IntConsumer getReturnValueConsumer() {
|
||||
return this.returnValueConsumer;
|
||||
}
|
||||
|
||||
public boolean shouldFilterMessageTo(ServerPlayer pReceiver) {
|
||||
ServerPlayer serverplayer = this.getPlayer();
|
||||
if (pReceiver == serverplayer) {
|
||||
return false;
|
||||
} else {
|
||||
return serverplayer != null && serverplayer.isTextFilteringEnabled() || pReceiver.isTextFilteringEnabled();
|
||||
}
|
||||
}
|
||||
|
||||
public void sendChatMessage(OutgoingChatMessage pMessage, boolean pShouldFilter, ChatType.Bound pBoundChatType) {
|
||||
if (!this.silent) {
|
||||
ServerPlayer serverplayer = this.getPlayer();
|
||||
if (serverplayer != null) {
|
||||
serverplayer.sendChatMessage(pMessage, pShouldFilter, pBoundChatType);
|
||||
} else {
|
||||
this.source.sendSystemMessage(pBoundChatType.decorate(pMessage.content()));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public void sendSystemMessage(Component pMessage) {
|
||||
if (!this.silent) {
|
||||
ServerPlayer serverplayer = this.getPlayer();
|
||||
if (serverplayer != null) {
|
||||
serverplayer.sendSystemMessage(pMessage);
|
||||
} else {
|
||||
this.source.sendSystemMessage(pMessage);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public void sendSuccess(Supplier<Component> pMessageSupplier, boolean pAllowLogging) {
|
||||
boolean flag = this.source.acceptsSuccess() && !this.silent;
|
||||
boolean flag1 = pAllowLogging && this.source.shouldInformAdmins() && !this.silent;
|
||||
if (flag || flag1) {
|
||||
Component component = pMessageSupplier.get();
|
||||
if (flag) {
|
||||
this.source.sendSystemMessage(component);
|
||||
}
|
||||
|
||||
if (flag1) {
|
||||
this.broadcastToAdmins(component);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void broadcastToAdmins(Component pMessage) {
|
||||
Component component = Component.translatable("chat.type.admin", this.getDisplayName(), pMessage).withStyle(ChatFormatting.GRAY, ChatFormatting.ITALIC);
|
||||
if (this.server.getGameRules().getBoolean(GameRules.RULE_SENDCOMMANDFEEDBACK)) {
|
||||
for(ServerPlayer serverplayer : this.server.getPlayerList().getPlayers()) {
|
||||
if (serverplayer != this.source && this.server.getPlayerList().isOp(serverplayer.getGameProfile())) {
|
||||
serverplayer.sendSystemMessage(component);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.source != this.server && this.server.getGameRules().getBoolean(GameRules.RULE_LOGADMINCOMMANDS)) {
|
||||
this.server.sendSystemMessage(component);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void sendFailure(Component pMessage) {
|
||||
if (this.source.acceptsFailure() && !this.silent) {
|
||||
this.source.sendSystemMessage(Component.empty().append(pMessage).withStyle(ChatFormatting.RED));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void onCommandComplete(CommandContext<CommandSourceStack> pContext, boolean pSuccess, int pResult) {
|
||||
if (this.consumer != null) {
|
||||
this.consumer.onCommandComplete(pContext, pSuccess, pResult);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Collection<String> getOnlinePlayerNames() {
|
||||
return Lists.newArrayList(this.server.getPlayerNames());
|
||||
}
|
||||
|
||||
public Collection<String> getAllTeams() {
|
||||
return this.server.getScoreboard().getTeamNames();
|
||||
}
|
||||
|
||||
public Stream<ResourceLocation> getAvailableSounds() {
|
||||
return BuiltInRegistries.SOUND_EVENT.stream().map(SoundEvent::getLocation);
|
||||
}
|
||||
|
||||
public Stream<ResourceLocation> getRecipeNames() {
|
||||
return this.server.getRecipeManager().getRecipeIds();
|
||||
}
|
||||
|
||||
public CompletableFuture<Suggestions> customSuggestion(CommandContext<?> pContext) {
|
||||
return Suggestions.empty();
|
||||
}
|
||||
|
||||
public CompletableFuture<Suggestions> suggestRegistryElements(ResourceKey<? extends Registry<?>> pResourceKey, SharedSuggestionProvider.ElementSuggestionType pRegistryKey, SuggestionsBuilder pBuilder, CommandContext<?> pContext) {
|
||||
return this.registryAccess().registry(pResourceKey).map((p_212328_) -> {
|
||||
this.suggestRegistryElements(p_212328_, pRegistryKey, pBuilder);
|
||||
return pBuilder.buildFuture();
|
||||
}).orElseGet(Suggestions::empty);
|
||||
}
|
||||
|
||||
public Set<ResourceKey<Level>> levels() {
|
||||
return this.server.levelKeys();
|
||||
}
|
||||
|
||||
public RegistryAccess registryAccess() {
|
||||
return this.server.registryAccess();
|
||||
}
|
||||
|
||||
public FeatureFlagSet enabledFeatures() {
|
||||
return this.level.enabledFeatures();
|
||||
}
|
||||
}
|
||||
+462
@@ -0,0 +1,462 @@
|
||||
package net.minecraft.commands;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.mojang.brigadier.CommandDispatcher;
|
||||
import com.mojang.brigadier.ParseResults;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.builder.ArgumentBuilder;
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContextBuilder;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.tree.CommandNode;
|
||||
import com.mojang.brigadier.tree.RootCommandNode;
|
||||
import com.mojang.logging.LogUtils;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.UnaryOperator;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfos;
|
||||
import net.minecraft.commands.synchronization.ArgumentUtils;
|
||||
import net.minecraft.commands.synchronization.SuggestionProviders;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.data.registries.VanillaRegistries;
|
||||
import net.minecraft.gametest.framework.TestCommand;
|
||||
import net.minecraft.network.chat.ClickEvent;
|
||||
import net.minecraft.network.chat.CommonComponents;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.ComponentUtils;
|
||||
import net.minecraft.network.chat.HoverEvent;
|
||||
import net.minecraft.network.chat.MutableComponent;
|
||||
import net.minecraft.network.protocol.game.ClientboundCommandsPacket;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.commands.AdvancementCommands;
|
||||
import net.minecraft.server.commands.AttributeCommand;
|
||||
import net.minecraft.server.commands.BanIpCommands;
|
||||
import net.minecraft.server.commands.BanListCommands;
|
||||
import net.minecraft.server.commands.BanPlayerCommands;
|
||||
import net.minecraft.server.commands.BossBarCommands;
|
||||
import net.minecraft.server.commands.ClearInventoryCommands;
|
||||
import net.minecraft.server.commands.CloneCommands;
|
||||
import net.minecraft.server.commands.DamageCommand;
|
||||
import net.minecraft.server.commands.DataPackCommand;
|
||||
import net.minecraft.server.commands.DeOpCommands;
|
||||
import net.minecraft.server.commands.DebugCommand;
|
||||
import net.minecraft.server.commands.DefaultGameModeCommands;
|
||||
import net.minecraft.server.commands.DifficultyCommand;
|
||||
import net.minecraft.server.commands.EffectCommands;
|
||||
import net.minecraft.server.commands.EmoteCommands;
|
||||
import net.minecraft.server.commands.EnchantCommand;
|
||||
import net.minecraft.server.commands.ExecuteCommand;
|
||||
import net.minecraft.server.commands.ExperienceCommand;
|
||||
import net.minecraft.server.commands.FillBiomeCommand;
|
||||
import net.minecraft.server.commands.FillCommand;
|
||||
import net.minecraft.server.commands.ForceLoadCommand;
|
||||
import net.minecraft.server.commands.FunctionCommand;
|
||||
import net.minecraft.server.commands.GameModeCommand;
|
||||
import net.minecraft.server.commands.GameRuleCommand;
|
||||
import net.minecraft.server.commands.GiveCommand;
|
||||
import net.minecraft.server.commands.HelpCommand;
|
||||
import net.minecraft.server.commands.ItemCommands;
|
||||
import net.minecraft.server.commands.JfrCommand;
|
||||
import net.minecraft.server.commands.KickCommand;
|
||||
import net.minecraft.server.commands.KillCommand;
|
||||
import net.minecraft.server.commands.ListPlayersCommand;
|
||||
import net.minecraft.server.commands.LocateCommand;
|
||||
import net.minecraft.server.commands.LootCommand;
|
||||
import net.minecraft.server.commands.MsgCommand;
|
||||
import net.minecraft.server.commands.OpCommand;
|
||||
import net.minecraft.server.commands.PardonCommand;
|
||||
import net.minecraft.server.commands.PardonIpCommand;
|
||||
import net.minecraft.server.commands.ParticleCommand;
|
||||
import net.minecraft.server.commands.PerfCommand;
|
||||
import net.minecraft.server.commands.PlaceCommand;
|
||||
import net.minecraft.server.commands.PlaySoundCommand;
|
||||
import net.minecraft.server.commands.PublishCommand;
|
||||
import net.minecraft.server.commands.RecipeCommand;
|
||||
import net.minecraft.server.commands.ReloadCommand;
|
||||
import net.minecraft.server.commands.ReturnCommand;
|
||||
import net.minecraft.server.commands.RideCommand;
|
||||
import net.minecraft.server.commands.SaveAllCommand;
|
||||
import net.minecraft.server.commands.SaveOffCommand;
|
||||
import net.minecraft.server.commands.SaveOnCommand;
|
||||
import net.minecraft.server.commands.SayCommand;
|
||||
import net.minecraft.server.commands.ScheduleCommand;
|
||||
import net.minecraft.server.commands.ScoreboardCommand;
|
||||
import net.minecraft.server.commands.SeedCommand;
|
||||
import net.minecraft.server.commands.SetBlockCommand;
|
||||
import net.minecraft.server.commands.SetPlayerIdleTimeoutCommand;
|
||||
import net.minecraft.server.commands.SetSpawnCommand;
|
||||
import net.minecraft.server.commands.SetWorldSpawnCommand;
|
||||
import net.minecraft.server.commands.SpawnArmorTrimsCommand;
|
||||
import net.minecraft.server.commands.SpectateCommand;
|
||||
import net.minecraft.server.commands.SpreadPlayersCommand;
|
||||
import net.minecraft.server.commands.StopCommand;
|
||||
import net.minecraft.server.commands.StopSoundCommand;
|
||||
import net.minecraft.server.commands.SummonCommand;
|
||||
import net.minecraft.server.commands.TagCommand;
|
||||
import net.minecraft.server.commands.TeamCommand;
|
||||
import net.minecraft.server.commands.TeamMsgCommand;
|
||||
import net.minecraft.server.commands.TeleportCommand;
|
||||
import net.minecraft.server.commands.TellRawCommand;
|
||||
import net.minecraft.server.commands.TimeCommand;
|
||||
import net.minecraft.server.commands.TitleCommand;
|
||||
import net.minecraft.server.commands.TriggerCommand;
|
||||
import net.minecraft.server.commands.WeatherCommand;
|
||||
import net.minecraft.server.commands.WhitelistCommand;
|
||||
import net.minecraft.server.commands.WorldBorderCommand;
|
||||
import net.minecraft.server.commands.data.DataCommands;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.util.profiling.jfr.JvmProfiler;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
public class Commands {
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
public static final int LEVEL_ALL = 0;
|
||||
public static final int LEVEL_MODERATORS = 1;
|
||||
public static final int LEVEL_GAMEMASTERS = 2;
|
||||
public static final int LEVEL_ADMINS = 3;
|
||||
public static final int LEVEL_OWNERS = 4;
|
||||
private final CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher<>();
|
||||
|
||||
public Commands(Commands.CommandSelection pSelection, CommandBuildContext pContext) {
|
||||
AdvancementCommands.register(this.dispatcher);
|
||||
AttributeCommand.register(this.dispatcher, pContext);
|
||||
ExecuteCommand.register(this.dispatcher, pContext);
|
||||
BossBarCommands.register(this.dispatcher);
|
||||
ClearInventoryCommands.register(this.dispatcher, pContext);
|
||||
CloneCommands.register(this.dispatcher, pContext);
|
||||
DamageCommand.register(this.dispatcher, pContext);
|
||||
DataCommands.register(this.dispatcher);
|
||||
DataPackCommand.register(this.dispatcher);
|
||||
DebugCommand.register(this.dispatcher);
|
||||
DefaultGameModeCommands.register(this.dispatcher);
|
||||
DifficultyCommand.register(this.dispatcher);
|
||||
EffectCommands.register(this.dispatcher, pContext);
|
||||
EmoteCommands.register(this.dispatcher);
|
||||
EnchantCommand.register(this.dispatcher, pContext);
|
||||
ExperienceCommand.register(this.dispatcher);
|
||||
FillCommand.register(this.dispatcher, pContext);
|
||||
FillBiomeCommand.register(this.dispatcher, pContext);
|
||||
ForceLoadCommand.register(this.dispatcher);
|
||||
FunctionCommand.register(this.dispatcher);
|
||||
GameModeCommand.register(this.dispatcher);
|
||||
GameRuleCommand.register(this.dispatcher);
|
||||
GiveCommand.register(this.dispatcher, pContext);
|
||||
HelpCommand.register(this.dispatcher);
|
||||
ItemCommands.register(this.dispatcher, pContext);
|
||||
KickCommand.register(this.dispatcher);
|
||||
KillCommand.register(this.dispatcher);
|
||||
ListPlayersCommand.register(this.dispatcher);
|
||||
LocateCommand.register(this.dispatcher, pContext);
|
||||
LootCommand.register(this.dispatcher, pContext);
|
||||
MsgCommand.register(this.dispatcher);
|
||||
ParticleCommand.register(this.dispatcher, pContext);
|
||||
PlaceCommand.register(this.dispatcher);
|
||||
PlaySoundCommand.register(this.dispatcher);
|
||||
ReloadCommand.register(this.dispatcher);
|
||||
RecipeCommand.register(this.dispatcher);
|
||||
ReturnCommand.register(this.dispatcher);
|
||||
RideCommand.register(this.dispatcher);
|
||||
SayCommand.register(this.dispatcher);
|
||||
ScheduleCommand.register(this.dispatcher);
|
||||
ScoreboardCommand.register(this.dispatcher);
|
||||
SeedCommand.register(this.dispatcher, pSelection != Commands.CommandSelection.INTEGRATED);
|
||||
SetBlockCommand.register(this.dispatcher, pContext);
|
||||
SetSpawnCommand.register(this.dispatcher);
|
||||
SetWorldSpawnCommand.register(this.dispatcher);
|
||||
SpectateCommand.register(this.dispatcher);
|
||||
SpreadPlayersCommand.register(this.dispatcher);
|
||||
StopSoundCommand.register(this.dispatcher);
|
||||
SummonCommand.register(this.dispatcher, pContext);
|
||||
TagCommand.register(this.dispatcher);
|
||||
TeamCommand.register(this.dispatcher);
|
||||
TeamMsgCommand.register(this.dispatcher);
|
||||
TeleportCommand.register(this.dispatcher);
|
||||
TellRawCommand.register(this.dispatcher);
|
||||
TimeCommand.register(this.dispatcher);
|
||||
TitleCommand.register(this.dispatcher);
|
||||
TriggerCommand.register(this.dispatcher);
|
||||
WeatherCommand.register(this.dispatcher);
|
||||
WorldBorderCommand.register(this.dispatcher);
|
||||
if (JvmProfiler.INSTANCE.isAvailable()) {
|
||||
JfrCommand.register(this.dispatcher);
|
||||
}
|
||||
|
||||
if (net.minecraftforge.gametest.ForgeGameTestHooks.isGametestEnabled()) {
|
||||
TestCommand.register(this.dispatcher);
|
||||
SpawnArmorTrimsCommand.register(this.dispatcher);
|
||||
}
|
||||
|
||||
if (pSelection.includeDedicated) {
|
||||
BanIpCommands.register(this.dispatcher);
|
||||
BanListCommands.register(this.dispatcher);
|
||||
BanPlayerCommands.register(this.dispatcher);
|
||||
DeOpCommands.register(this.dispatcher);
|
||||
OpCommand.register(this.dispatcher);
|
||||
PardonCommand.register(this.dispatcher);
|
||||
PardonIpCommand.register(this.dispatcher);
|
||||
PerfCommand.register(this.dispatcher);
|
||||
SaveAllCommand.register(this.dispatcher);
|
||||
SaveOffCommand.register(this.dispatcher);
|
||||
SaveOnCommand.register(this.dispatcher);
|
||||
SetPlayerIdleTimeoutCommand.register(this.dispatcher);
|
||||
StopCommand.register(this.dispatcher);
|
||||
WhitelistCommand.register(this.dispatcher);
|
||||
}
|
||||
|
||||
if (pSelection.includeIntegrated) {
|
||||
PublishCommand.register(this.dispatcher);
|
||||
}
|
||||
net.minecraftforge.event.ForgeEventFactory.onCommandRegister(this.dispatcher, pSelection, pContext);
|
||||
|
||||
this.dispatcher.setConsumer((p_230954_, p_230955_, p_230956_) -> {
|
||||
p_230954_.getSource().onCommandComplete(p_230954_, p_230955_, p_230956_);
|
||||
p_230954_.getSource().onCommandComplete(p_230954_, p_230955_, p_230956_);
|
||||
});
|
||||
}
|
||||
|
||||
public static <S> ParseResults<S> mapSource(ParseResults<S> pParseResults, UnaryOperator<S> p_242890_) {
|
||||
CommandContextBuilder<S> commandcontextbuilder = pParseResults.getContext();
|
||||
CommandContextBuilder<S> commandcontextbuilder1 = commandcontextbuilder.withSource(p_242890_.apply(commandcontextbuilder.getSource()));
|
||||
return new ParseResults<>(commandcontextbuilder1, pParseResults.getReader(), pParseResults.getExceptions());
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a command.
|
||||
*
|
||||
* @return The success value of the command, or 0 if an exception occurred.
|
||||
*/
|
||||
public int performPrefixedCommand(CommandSourceStack pSource, String pCommand) {
|
||||
pCommand = pCommand.startsWith("/") ? pCommand.substring(1) : pCommand;
|
||||
return this.performCommand(this.dispatcher.parse(pCommand, pSource), pCommand);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a command.
|
||||
*
|
||||
* @return The success value of the command, or 0 if an exception occurred.
|
||||
*/
|
||||
public int performCommand(ParseResults<CommandSourceStack> pParseResults, String pCommand) {
|
||||
CommandSourceStack commandsourcestack = pParseResults.getContext().getSource();
|
||||
commandsourcestack.getServer().getProfiler().push(() -> {
|
||||
return "/" + pCommand;
|
||||
});
|
||||
|
||||
try {
|
||||
try {
|
||||
net.minecraftforge.event.CommandEvent event = new net.minecraftforge.event.CommandEvent(pParseResults);
|
||||
if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event)) {
|
||||
if (event.getException() instanceof Exception exception) {
|
||||
throw exception;
|
||||
} else if (event.getException() != null) {
|
||||
com.google.common.base.Throwables.throwIfUnchecked(event.getException());
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
return this.dispatcher.execute(event.getParseResults());
|
||||
} catch (CommandRuntimeException commandruntimeexception) {
|
||||
commandsourcestack.sendFailure(commandruntimeexception.getComponent());
|
||||
return 0;
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
commandsourcestack.sendFailure(ComponentUtils.fromMessage(commandsyntaxexception.getRawMessage()));
|
||||
if (commandsyntaxexception.getInput() != null && commandsyntaxexception.getCursor() >= 0) {
|
||||
int j = Math.min(commandsyntaxexception.getInput().length(), commandsyntaxexception.getCursor());
|
||||
MutableComponent mutablecomponent1 = Component.empty().withStyle(ChatFormatting.GRAY).withStyle((p_82134_) -> {
|
||||
return p_82134_.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/" + pCommand));
|
||||
});
|
||||
if (j > 10) {
|
||||
mutablecomponent1.append(CommonComponents.ELLIPSIS);
|
||||
}
|
||||
|
||||
mutablecomponent1.append(commandsyntaxexception.getInput().substring(Math.max(0, j - 10), j));
|
||||
if (j < commandsyntaxexception.getInput().length()) {
|
||||
Component component = Component.literal(commandsyntaxexception.getInput().substring(j)).withStyle(ChatFormatting.RED, ChatFormatting.UNDERLINE);
|
||||
mutablecomponent1.append(component);
|
||||
}
|
||||
|
||||
mutablecomponent1.append(Component.translatable("command.context.here").withStyle(ChatFormatting.RED, ChatFormatting.ITALIC));
|
||||
commandsourcestack.sendFailure(mutablecomponent1);
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
MutableComponent mutablecomponent = Component.literal(exception.getMessage() == null ? exception.getClass().getName() : exception.getMessage());
|
||||
if (LOGGER.isDebugEnabled()) {
|
||||
LOGGER.error("Command exception: /{}", pCommand, exception);
|
||||
StackTraceElement[] astacktraceelement = exception.getStackTrace();
|
||||
|
||||
for(int i = 0; i < Math.min(astacktraceelement.length, 3); ++i) {
|
||||
mutablecomponent.append("\n\n").append(astacktraceelement[i].getMethodName()).append("\n ").append(astacktraceelement[i].getFileName()).append(":").append(String.valueOf(astacktraceelement[i].getLineNumber()));
|
||||
}
|
||||
}
|
||||
|
||||
commandsourcestack.sendFailure(Component.translatable("command.failed").withStyle((p_82137_) -> {
|
||||
return p_82137_.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, mutablecomponent));
|
||||
}));
|
||||
if (SharedConstants.IS_RUNNING_IN_IDE) {
|
||||
commandsourcestack.sendFailure(Component.literal(Util.describeError(exception)));
|
||||
LOGGER.error("'/{}' threw an exception", pCommand, exception);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
} finally {
|
||||
commandsourcestack.getServer().getProfiler().pop();
|
||||
}
|
||||
}
|
||||
|
||||
public void sendCommands(ServerPlayer pPlayer) {
|
||||
Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> map = Maps.newHashMap();
|
||||
RootCommandNode<SharedSuggestionProvider> rootcommandnode = new RootCommandNode<>();
|
||||
map.put(this.dispatcher.getRoot(), rootcommandnode);
|
||||
// FORGE: Use our own command node merging method to handle redirect nodes properly, see issue #7551
|
||||
net.minecraftforge.server.command.CommandHelper.mergeCommandNode(this.dispatcher.getRoot(), rootcommandnode, map, pPlayer.createCommandSourceStack(), ctx -> 0, suggest -> SuggestionProviders.safelySwap((com.mojang.brigadier.suggestion.SuggestionProvider<SharedSuggestionProvider>) (com.mojang.brigadier.suggestion.SuggestionProvider<?>) suggest));
|
||||
pPlayer.connection.send(new ClientboundCommandsPacket(rootcommandnode));
|
||||
}
|
||||
|
||||
private void fillUsableCommands(CommandNode<CommandSourceStack> pRootCommandSource, CommandNode<SharedSuggestionProvider> pRootSuggestion, CommandSourceStack pSource, Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> pCommandNodeToSuggestionNode) {
|
||||
for(CommandNode<CommandSourceStack> commandnode : pRootCommandSource.getChildren()) {
|
||||
if (commandnode.canUse(pSource)) {
|
||||
ArgumentBuilder<SharedSuggestionProvider, ?> argumentbuilder = (ArgumentBuilder)commandnode.createBuilder();
|
||||
argumentbuilder.requires((p_82126_) -> {
|
||||
return true;
|
||||
});
|
||||
if (argumentbuilder.getCommand() != null) {
|
||||
argumentbuilder.executes((p_82102_) -> {
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
if (argumentbuilder instanceof RequiredArgumentBuilder) {
|
||||
RequiredArgumentBuilder<SharedSuggestionProvider, ?> requiredargumentbuilder = (RequiredArgumentBuilder)argumentbuilder;
|
||||
if (requiredargumentbuilder.getSuggestionsProvider() != null) {
|
||||
requiredargumentbuilder.suggests(SuggestionProviders.safelySwap(requiredargumentbuilder.getSuggestionsProvider()));
|
||||
}
|
||||
}
|
||||
|
||||
if (argumentbuilder.getRedirect() != null) {
|
||||
argumentbuilder.redirect(pCommandNodeToSuggestionNode.get(argumentbuilder.getRedirect()));
|
||||
}
|
||||
|
||||
CommandNode<SharedSuggestionProvider> commandnode1 = argumentbuilder.build();
|
||||
pCommandNodeToSuggestionNode.put(commandnode, commandnode1);
|
||||
pRootSuggestion.addChild(commandnode1);
|
||||
if (!commandnode.getChildren().isEmpty()) {
|
||||
this.fillUsableCommands(commandnode, commandnode1, pSource, pCommandNodeToSuggestionNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new argument. Intended to be imported statically. The benefit of this over the brigadier {@link
|
||||
* LiteralArgumentBuilder#literal} method is that it is typed to {@link CommandSource}.
|
||||
*/
|
||||
public static LiteralArgumentBuilder<CommandSourceStack> literal(String pName) {
|
||||
return LiteralArgumentBuilder.literal(pName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new argument. Intended to be imported statically. The benefit of this over the brigadier {@link
|
||||
* RequiredArgumentBuilder#argument} method is that it is typed to {@link CommandSource}.
|
||||
*/
|
||||
public static <T> RequiredArgumentBuilder<CommandSourceStack, T> argument(String pName, ArgumentType<T> pType) {
|
||||
return RequiredArgumentBuilder.argument(pName, pType);
|
||||
}
|
||||
|
||||
public static Predicate<String> createValidator(Commands.ParseFunction pParser) {
|
||||
return (p_82124_) -> {
|
||||
try {
|
||||
pParser.parse(new StringReader(p_82124_));
|
||||
return true;
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public CommandDispatcher<CommandSourceStack> getDispatcher() {
|
||||
return this.dispatcher;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static <S> CommandSyntaxException getParseException(ParseResults<S> pResult) {
|
||||
if (!pResult.getReader().canRead()) {
|
||||
return null;
|
||||
} else if (pResult.getExceptions().size() == 1) {
|
||||
return pResult.getExceptions().values().iterator().next();
|
||||
} else {
|
||||
return pResult.getContext().getRange().isEmpty() ? CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().createWithContext(pResult.getReader()) : CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().createWithContext(pResult.getReader());
|
||||
}
|
||||
}
|
||||
|
||||
public static CommandBuildContext createValidationContext(final HolderLookup.Provider pProvider) {
|
||||
return new CommandBuildContext() {
|
||||
public <T> HolderLookup<T> holderLookup(ResourceKey<? extends Registry<T>> p_256244_) {
|
||||
final HolderLookup.RegistryLookup<T> registrylookup = pProvider.lookupOrThrow(p_256244_);
|
||||
return new HolderLookup.Delegate<T>(registrylookup) {
|
||||
public Optional<HolderSet.Named<T>> get(TagKey<T> p_255936_) {
|
||||
return Optional.of(this.getOrThrow(p_255936_));
|
||||
}
|
||||
|
||||
public HolderSet.Named<T> getOrThrow(TagKey<T> p_255953_) {
|
||||
Optional<HolderSet.Named<T>> optional = registrylookup.get(p_255953_);
|
||||
return optional.orElseGet(() -> {
|
||||
return HolderSet.emptyNamed(registrylookup, p_255953_);
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static void validate() {
|
||||
CommandBuildContext commandbuildcontext = createValidationContext(VanillaRegistries.createLookup());
|
||||
CommandDispatcher<CommandSourceStack> commanddispatcher = (new Commands(Commands.CommandSelection.ALL, commandbuildcontext)).getDispatcher();
|
||||
RootCommandNode<CommandSourceStack> rootcommandnode = commanddispatcher.getRoot();
|
||||
commanddispatcher.findAmbiguities((p_230947_, p_230948_, p_230949_, p_230950_) -> {
|
||||
LOGGER.warn("Ambiguity between arguments {} and {} with inputs: {}", commanddispatcher.getPath(p_230948_), commanddispatcher.getPath(p_230949_), p_230950_);
|
||||
});
|
||||
Set<ArgumentType<?>> set = ArgumentUtils.findUsedArgumentTypes(rootcommandnode);
|
||||
Set<ArgumentType<?>> set1 = set.stream().filter((p_230961_) -> {
|
||||
return !ArgumentTypeInfos.isClassRecognized(p_230961_.getClass());
|
||||
}).collect(Collectors.toSet());
|
||||
if (!set1.isEmpty()) {
|
||||
LOGGER.warn("Missing type registration for following arguments:\n {}", set1.stream().map((p_230952_) -> {
|
||||
return "\t" + p_230952_;
|
||||
}).collect(Collectors.joining(",\n")));
|
||||
throw new IllegalStateException("Unregistered argument types");
|
||||
}
|
||||
}
|
||||
|
||||
public static enum CommandSelection {
|
||||
ALL(true, true),
|
||||
DEDICATED(false, true),
|
||||
INTEGRATED(true, false);
|
||||
|
||||
final boolean includeIntegrated;
|
||||
final boolean includeDedicated;
|
||||
|
||||
private CommandSelection(boolean pIncludeIntegrated, boolean pIncludeDedicated) {
|
||||
this.includeIntegrated = pIncludeIntegrated;
|
||||
this.includeDedicated = pIncludeDedicated;
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ParseFunction {
|
||||
void parse(StringReader pInput) throws CommandSyntaxException;
|
||||
}
|
||||
}
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
package net.minecraft.commands;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.brigadier.Message;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.flag.FeatureFlagSet;
|
||||
import net.minecraft.world.level.Level;
|
||||
|
||||
public interface SharedSuggestionProvider {
|
||||
Collection<String> getOnlinePlayerNames();
|
||||
|
||||
default Collection<String> getCustomTabSugggestions() {
|
||||
return this.getOnlinePlayerNames();
|
||||
}
|
||||
|
||||
default Collection<String> getSelectedEntities() {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
Collection<String> getAllTeams();
|
||||
|
||||
Stream<ResourceLocation> getAvailableSounds();
|
||||
|
||||
Stream<ResourceLocation> getRecipeNames();
|
||||
|
||||
CompletableFuture<Suggestions> customSuggestion(CommandContext<?> pContext);
|
||||
|
||||
default Collection<SharedSuggestionProvider.TextCoordinates> getRelevantCoordinates() {
|
||||
return Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_GLOBAL);
|
||||
}
|
||||
|
||||
default Collection<SharedSuggestionProvider.TextCoordinates> getAbsoluteCoordinates() {
|
||||
return Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_GLOBAL);
|
||||
}
|
||||
|
||||
Set<ResourceKey<Level>> levels();
|
||||
|
||||
RegistryAccess registryAccess();
|
||||
|
||||
FeatureFlagSet enabledFeatures();
|
||||
|
||||
default void suggestRegistryElements(Registry<?> pRegistry, SharedSuggestionProvider.ElementSuggestionType pType, SuggestionsBuilder pBuilder) {
|
||||
if (pType.shouldSuggestTags()) {
|
||||
suggestResource(pRegistry.getTagNames().map(TagKey::location), pBuilder, "#");
|
||||
}
|
||||
|
||||
if (pType.shouldSuggestElements()) {
|
||||
suggestResource(pRegistry.keySet(), pBuilder);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
CompletableFuture<Suggestions> suggestRegistryElements(ResourceKey<? extends Registry<?>> pResourceKey, SharedSuggestionProvider.ElementSuggestionType pRegistryKey, SuggestionsBuilder pBuilder, CommandContext<?> pContext);
|
||||
|
||||
boolean hasPermission(int pPermissionLevel);
|
||||
|
||||
static <T> void filterResources(Iterable<T> pResources, String pInput, Function<T, ResourceLocation> pLocationFunction, Consumer<T> pResourceConsumer) {
|
||||
boolean flag = pInput.indexOf(58) > -1;
|
||||
|
||||
for(T t : pResources) {
|
||||
ResourceLocation resourcelocation = pLocationFunction.apply(t);
|
||||
if (flag) {
|
||||
String s = resourcelocation.toString();
|
||||
if (matchesSubStr(pInput, s)) {
|
||||
pResourceConsumer.accept(t);
|
||||
}
|
||||
} else if (matchesSubStr(pInput, resourcelocation.getNamespace()) || resourcelocation.getNamespace().equals("minecraft") && matchesSubStr(pInput, resourcelocation.getPath())) {
|
||||
pResourceConsumer.accept(t);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static <T> void filterResources(Iterable<T> pResources, String pRemaining, String pPrefix, Function<T, ResourceLocation> pLocationFunction, Consumer<T> pResourceConsumer) {
|
||||
if (pRemaining.isEmpty()) {
|
||||
pResources.forEach(pResourceConsumer);
|
||||
} else {
|
||||
String s = Strings.commonPrefix(pRemaining, pPrefix);
|
||||
if (!s.isEmpty()) {
|
||||
String s1 = pRemaining.substring(s.length());
|
||||
filterResources(pResources, s1, pLocationFunction, pResourceConsumer);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static CompletableFuture<Suggestions> suggestResource(Iterable<ResourceLocation> pResources, SuggestionsBuilder pBuilder, String pPrefix) {
|
||||
String s = pBuilder.getRemaining().toLowerCase(Locale.ROOT);
|
||||
filterResources(pResources, s, pPrefix, (p_82985_) -> {
|
||||
return p_82985_;
|
||||
}, (p_82917_) -> {
|
||||
pBuilder.suggest(pPrefix + p_82917_);
|
||||
});
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
|
||||
static CompletableFuture<Suggestions> suggestResource(Stream<ResourceLocation> p_205107_, SuggestionsBuilder p_205108_, String p_205109_) {
|
||||
return suggestResource(p_205107_::iterator, p_205108_, p_205109_);
|
||||
}
|
||||
|
||||
static CompletableFuture<Suggestions> suggestResource(Iterable<ResourceLocation> pResources, SuggestionsBuilder pBuilder) {
|
||||
String s = pBuilder.getRemaining().toLowerCase(Locale.ROOT);
|
||||
filterResources(pResources, s, (p_82966_) -> {
|
||||
return p_82966_;
|
||||
}, (p_82925_) -> {
|
||||
pBuilder.suggest(p_82925_.toString());
|
||||
});
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
|
||||
static <T> CompletableFuture<Suggestions> suggestResource(Iterable<T> pResources, SuggestionsBuilder pBuilder, Function<T, ResourceLocation> pLocationFunction, Function<T, Message> pSuggestionFunction) {
|
||||
String s = pBuilder.getRemaining().toLowerCase(Locale.ROOT);
|
||||
filterResources(pResources, s, pLocationFunction, (p_82922_) -> {
|
||||
pBuilder.suggest(pLocationFunction.apply(p_82922_).toString(), pSuggestionFunction.apply(p_82922_));
|
||||
});
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
|
||||
static CompletableFuture<Suggestions> suggestResource(Stream<ResourceLocation> pResourceLocations, SuggestionsBuilder pBuilder) {
|
||||
return suggestResource(pResourceLocations::iterator, pBuilder);
|
||||
}
|
||||
|
||||
static <T> CompletableFuture<Suggestions> suggestResource(Stream<T> pResources, SuggestionsBuilder pBuilder, Function<T, ResourceLocation> pLocationFunction, Function<T, Message> pSuggestionFunction) {
|
||||
return suggestResource(pResources::iterator, pBuilder, pLocationFunction, pSuggestionFunction);
|
||||
}
|
||||
|
||||
static CompletableFuture<Suggestions> suggestCoordinates(String pRemaining, Collection<SharedSuggestionProvider.TextCoordinates> pCoordinates, SuggestionsBuilder pBuilder, Predicate<String> pValidator) {
|
||||
List<String> list = Lists.newArrayList();
|
||||
if (Strings.isNullOrEmpty(pRemaining)) {
|
||||
for(SharedSuggestionProvider.TextCoordinates sharedsuggestionprovider$textcoordinates : pCoordinates) {
|
||||
String s = sharedsuggestionprovider$textcoordinates.x + " " + sharedsuggestionprovider$textcoordinates.y + " " + sharedsuggestionprovider$textcoordinates.z;
|
||||
if (pValidator.test(s)) {
|
||||
list.add(sharedsuggestionprovider$textcoordinates.x);
|
||||
list.add(sharedsuggestionprovider$textcoordinates.x + " " + sharedsuggestionprovider$textcoordinates.y);
|
||||
list.add(s);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String[] astring = pRemaining.split(" ");
|
||||
if (astring.length == 1) {
|
||||
for(SharedSuggestionProvider.TextCoordinates sharedsuggestionprovider$textcoordinates1 : pCoordinates) {
|
||||
String s1 = astring[0] + " " + sharedsuggestionprovider$textcoordinates1.y + " " + sharedsuggestionprovider$textcoordinates1.z;
|
||||
if (pValidator.test(s1)) {
|
||||
list.add(astring[0] + " " + sharedsuggestionprovider$textcoordinates1.y);
|
||||
list.add(s1);
|
||||
}
|
||||
}
|
||||
} else if (astring.length == 2) {
|
||||
for(SharedSuggestionProvider.TextCoordinates sharedsuggestionprovider$textcoordinates2 : pCoordinates) {
|
||||
String s2 = astring[0] + " " + astring[1] + " " + sharedsuggestionprovider$textcoordinates2.z;
|
||||
if (pValidator.test(s2)) {
|
||||
list.add(s2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return suggest(list, pBuilder);
|
||||
}
|
||||
|
||||
static CompletableFuture<Suggestions> suggest2DCoordinates(String pRemaining, Collection<SharedSuggestionProvider.TextCoordinates> pCoordinates, SuggestionsBuilder pBuilder, Predicate<String> pValidator) {
|
||||
List<String> list = Lists.newArrayList();
|
||||
if (Strings.isNullOrEmpty(pRemaining)) {
|
||||
for(SharedSuggestionProvider.TextCoordinates sharedsuggestionprovider$textcoordinates : pCoordinates) {
|
||||
String s = sharedsuggestionprovider$textcoordinates.x + " " + sharedsuggestionprovider$textcoordinates.z;
|
||||
if (pValidator.test(s)) {
|
||||
list.add(sharedsuggestionprovider$textcoordinates.x);
|
||||
list.add(s);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String[] astring = pRemaining.split(" ");
|
||||
if (astring.length == 1) {
|
||||
for(SharedSuggestionProvider.TextCoordinates sharedsuggestionprovider$textcoordinates1 : pCoordinates) {
|
||||
String s1 = astring[0] + " " + sharedsuggestionprovider$textcoordinates1.z;
|
||||
if (pValidator.test(s1)) {
|
||||
list.add(s1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return suggest(list, pBuilder);
|
||||
}
|
||||
|
||||
static CompletableFuture<Suggestions> suggest(Iterable<String> pStrings, SuggestionsBuilder pBuilder) {
|
||||
String s = pBuilder.getRemaining().toLowerCase(Locale.ROOT);
|
||||
|
||||
for(String s1 : pStrings) {
|
||||
if (matchesSubStr(s, s1.toLowerCase(Locale.ROOT))) {
|
||||
pBuilder.suggest(s1);
|
||||
}
|
||||
}
|
||||
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
|
||||
static CompletableFuture<Suggestions> suggest(Stream<String> pStrings, SuggestionsBuilder pBuilder) {
|
||||
String s = pBuilder.getRemaining().toLowerCase(Locale.ROOT);
|
||||
pStrings.filter((p_82975_) -> {
|
||||
return matchesSubStr(s, p_82975_.toLowerCase(Locale.ROOT));
|
||||
}).forEach(pBuilder::suggest);
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
|
||||
static CompletableFuture<Suggestions> suggest(String[] pStrings, SuggestionsBuilder pBuilder) {
|
||||
String s = pBuilder.getRemaining().toLowerCase(Locale.ROOT);
|
||||
|
||||
for(String s1 : pStrings) {
|
||||
if (matchesSubStr(s, s1.toLowerCase(Locale.ROOT))) {
|
||||
pBuilder.suggest(s1);
|
||||
}
|
||||
}
|
||||
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
|
||||
static <T> CompletableFuture<Suggestions> suggest(Iterable<T> pResources, SuggestionsBuilder pBuilder, Function<T, String> pStringFunction, Function<T, Message> pSuggestionFunction) {
|
||||
String s = pBuilder.getRemaining().toLowerCase(Locale.ROOT);
|
||||
|
||||
for(T t : pResources) {
|
||||
String s1 = pStringFunction.apply(t);
|
||||
if (matchesSubStr(s, s1.toLowerCase(Locale.ROOT))) {
|
||||
pBuilder.suggest(s1, pSuggestionFunction.apply(t));
|
||||
}
|
||||
}
|
||||
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
|
||||
static boolean matchesSubStr(String pInput, String pSubstring) {
|
||||
for(int i = 0; !pSubstring.startsWith(pInput, i); ++i) {
|
||||
i = pSubstring.indexOf(95, i);
|
||||
if (i < 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static enum ElementSuggestionType {
|
||||
TAGS,
|
||||
ELEMENTS,
|
||||
ALL;
|
||||
|
||||
public boolean shouldSuggestTags() {
|
||||
return this == TAGS || this == ALL;
|
||||
}
|
||||
|
||||
public boolean shouldSuggestElements() {
|
||||
return this == ELEMENTS || this == ALL;
|
||||
}
|
||||
}
|
||||
|
||||
public static class TextCoordinates {
|
||||
public static final SharedSuggestionProvider.TextCoordinates DEFAULT_LOCAL = new SharedSuggestionProvider.TextCoordinates("^", "^", "^");
|
||||
public static final SharedSuggestionProvider.TextCoordinates DEFAULT_GLOBAL = new SharedSuggestionProvider.TextCoordinates("~", "~", "~");
|
||||
public final String x;
|
||||
public final String y;
|
||||
public final String z;
|
||||
|
||||
public TextCoordinates(String pX, String pY, String pZ) {
|
||||
this.x = pX;
|
||||
this.y = pY;
|
||||
this.z = pZ;
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.arguments.coordinates.WorldCoordinate;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.util.Mth;
|
||||
|
||||
public class AngleArgument implements ArgumentType<AngleArgument.SingleAngle> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("0", "~", "~-5");
|
||||
public static final SimpleCommandExceptionType ERROR_NOT_COMPLETE = new SimpleCommandExceptionType(Component.translatable("argument.angle.incomplete"));
|
||||
public static final SimpleCommandExceptionType ERROR_INVALID_ANGLE = new SimpleCommandExceptionType(Component.translatable("argument.angle.invalid"));
|
||||
|
||||
public static AngleArgument angle() {
|
||||
return new AngleArgument();
|
||||
}
|
||||
|
||||
public static float getAngle(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, AngleArgument.SingleAngle.class).getAngle(pContext.getSource());
|
||||
}
|
||||
|
||||
public AngleArgument.SingleAngle parse(StringReader pReader) throws CommandSyntaxException {
|
||||
if (!pReader.canRead()) {
|
||||
throw ERROR_NOT_COMPLETE.createWithContext(pReader);
|
||||
} else {
|
||||
boolean flag = WorldCoordinate.isRelative(pReader);
|
||||
float f = pReader.canRead() && pReader.peek() != ' ' ? pReader.readFloat() : 0.0F;
|
||||
if (!Float.isNaN(f) && !Float.isInfinite(f)) {
|
||||
return new AngleArgument.SingleAngle(f, flag);
|
||||
} else {
|
||||
throw ERROR_INVALID_ANGLE.createWithContext(pReader);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static final class SingleAngle {
|
||||
private final float angle;
|
||||
private final boolean isRelative;
|
||||
|
||||
SingleAngle(float pAngle, boolean pIsRelative) {
|
||||
this.angle = pAngle;
|
||||
this.isRelative = pIsRelative;
|
||||
}
|
||||
|
||||
public float getAngle(CommandSourceStack pSource) {
|
||||
return Mth.wrapDegrees(this.isRelative ? this.angle + pSource.getRotation().y : this.angle);
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.chat.MessageSignature;
|
||||
import net.minecraft.network.chat.SignableCommand;
|
||||
|
||||
public record ArgumentSignatures(List<ArgumentSignatures.Entry> entries) {
|
||||
public static final ArgumentSignatures EMPTY = new ArgumentSignatures(List.of());
|
||||
private static final int MAX_ARGUMENT_COUNT = 8;
|
||||
private static final int MAX_ARGUMENT_NAME_LENGTH = 16;
|
||||
|
||||
public ArgumentSignatures(FriendlyByteBuf pBuffer) {
|
||||
this(pBuffer.<ArgumentSignatures.Entry, List<ArgumentSignatures.Entry>>readCollection(FriendlyByteBuf.limitValue(ArrayList::new, 8), ArgumentSignatures.Entry::new));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public MessageSignature get(String pKey) {
|
||||
for(ArgumentSignatures.Entry argumentsignatures$entry : this.entries) {
|
||||
if (argumentsignatures$entry.name.equals(pKey)) {
|
||||
return argumentsignatures$entry.signature;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public void write(FriendlyByteBuf pBuffer) {
|
||||
pBuffer.writeCollection(this.entries, (p_241214_, p_241215_) -> {
|
||||
p_241215_.write(p_241214_);
|
||||
});
|
||||
}
|
||||
|
||||
public static ArgumentSignatures signCommand(SignableCommand<?> pCommand, ArgumentSignatures.Signer pSigner) {
|
||||
List<ArgumentSignatures.Entry> list = pCommand.arguments().stream().map((p_247962_) -> {
|
||||
MessageSignature messagesignature = pSigner.sign(p_247962_.value());
|
||||
return messagesignature != null ? new ArgumentSignatures.Entry(p_247962_.name(), messagesignature) : null;
|
||||
}).filter(Objects::nonNull).toList();
|
||||
return new ArgumentSignatures(list);
|
||||
}
|
||||
|
||||
public static record Entry(String name, MessageSignature signature) {
|
||||
public Entry(FriendlyByteBuf pBuffer) {
|
||||
this(pBuffer.readUtf(16), MessageSignature.read(pBuffer));
|
||||
}
|
||||
|
||||
public void write(FriendlyByteBuf pBuffer) {
|
||||
pBuffer.writeUtf(this.name, 16);
|
||||
MessageSignature.write(pBuffer, this.signature);
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Signer {
|
||||
@Nullable
|
||||
MessageSignature sign(String pArgumentText);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public class ColorArgument implements ArgumentType<ChatFormatting> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("red", "green");
|
||||
public static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType((p_85470_) -> {
|
||||
return Component.translatable("argument.color.invalid", p_85470_);
|
||||
});
|
||||
|
||||
private ColorArgument() {
|
||||
}
|
||||
|
||||
public static ColorArgument color() {
|
||||
return new ColorArgument();
|
||||
}
|
||||
|
||||
public static ChatFormatting getColor(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, ChatFormatting.class);
|
||||
}
|
||||
|
||||
public ChatFormatting parse(StringReader pReader) throws CommandSyntaxException {
|
||||
String s = pReader.readUnquotedString();
|
||||
ChatFormatting chatformatting = ChatFormatting.getByName(s);
|
||||
if (chatformatting != null && !chatformatting.isFormat()) {
|
||||
return chatformatting;
|
||||
} else {
|
||||
throw ERROR_INVALID_VALUE.create(s);
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return SharedSuggestionProvider.suggest(ChatFormatting.getNames(true, false), pBuilder);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public class ComponentArgument implements ArgumentType<Component> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("\"hello world\"", "\"\"", "\"{\"text\":\"hello world\"}", "[\"\"]");
|
||||
public static final DynamicCommandExceptionType ERROR_INVALID_JSON = new DynamicCommandExceptionType((p_87121_) -> {
|
||||
return Component.translatable("argument.component.invalid", p_87121_);
|
||||
});
|
||||
|
||||
private ComponentArgument() {
|
||||
}
|
||||
|
||||
public static Component getComponent(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, Component.class);
|
||||
}
|
||||
|
||||
public static ComponentArgument textComponent() {
|
||||
return new ComponentArgument();
|
||||
}
|
||||
|
||||
public Component parse(StringReader pReader) throws CommandSyntaxException {
|
||||
try {
|
||||
Component component = Component.Serializer.fromJson(pReader);
|
||||
if (component == null) {
|
||||
throw ERROR_INVALID_JSON.createWithContext(pReader, "empty");
|
||||
} else {
|
||||
return component;
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
String s = exception.getCause() != null ? exception.getCause().getMessage() : exception.getMessage();
|
||||
throw ERROR_INVALID_JSON.createWithContext(pReader, s);
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.TagParser;
|
||||
|
||||
public class CompoundTagArgument implements ArgumentType<CompoundTag> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("{}", "{foo=bar}");
|
||||
|
||||
private CompoundTagArgument() {
|
||||
}
|
||||
|
||||
public static CompoundTagArgument compoundTag() {
|
||||
return new CompoundTagArgument();
|
||||
}
|
||||
|
||||
public static <S> CompoundTag getCompoundTag(CommandContext<S> pContext, String pName) {
|
||||
return pContext.getArgument(pName, CompoundTag.class);
|
||||
}
|
||||
|
||||
public CompoundTag parse(StringReader pReader) throws CommandSyntaxException {
|
||||
return (new TagParser(pReader)).readStruct();
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.level.Level;
|
||||
|
||||
public class DimensionArgument implements ArgumentType<ResourceLocation> {
|
||||
private static final Collection<String> EXAMPLES = Stream.of(Level.OVERWORLD, Level.NETHER).map((p_88814_) -> {
|
||||
return p_88814_.location().toString();
|
||||
}).collect(Collectors.toList());
|
||||
private static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType((p_88812_) -> {
|
||||
return Component.translatable("argument.dimension.invalid", p_88812_);
|
||||
});
|
||||
|
||||
public ResourceLocation parse(StringReader p_88807_) throws CommandSyntaxException {
|
||||
return ResourceLocation.read(p_88807_);
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return pContext.getSource() instanceof SharedSuggestionProvider ? SharedSuggestionProvider.suggestResource(((SharedSuggestionProvider)pContext.getSource()).levels().stream().map(ResourceKey::location), pBuilder) : Suggestions.empty();
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static DimensionArgument dimension() {
|
||||
return new DimensionArgument();
|
||||
}
|
||||
|
||||
public static ServerLevel getDimension(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
ResourceLocation resourcelocation = pContext.getArgument(pName, ResourceLocation.class);
|
||||
ResourceKey<Level> resourcekey = ResourceKey.create(Registries.DIMENSION, resourcelocation);
|
||||
ServerLevel serverlevel = pContext.getSource().getServer().getLevel(resourcekey);
|
||||
if (serverlevel == null) {
|
||||
throw ERROR_INVALID_VALUE.create(resourcelocation);
|
||||
} else {
|
||||
return serverlevel;
|
||||
}
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiFunction;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class EntityAnchorArgument implements ArgumentType<EntityAnchorArgument.Anchor> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("eyes", "feet");
|
||||
private static final DynamicCommandExceptionType ERROR_INVALID = new DynamicCommandExceptionType((p_90357_) -> {
|
||||
return Component.translatable("argument.anchor.invalid", p_90357_);
|
||||
});
|
||||
|
||||
public static EntityAnchorArgument.Anchor getAnchor(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, EntityAnchorArgument.Anchor.class);
|
||||
}
|
||||
|
||||
public static EntityAnchorArgument anchor() {
|
||||
return new EntityAnchorArgument();
|
||||
}
|
||||
|
||||
public EntityAnchorArgument.Anchor parse(StringReader p_90352_) throws CommandSyntaxException {
|
||||
int i = p_90352_.getCursor();
|
||||
String s = p_90352_.readUnquotedString();
|
||||
EntityAnchorArgument.Anchor entityanchorargument$anchor = EntityAnchorArgument.Anchor.getByName(s);
|
||||
if (entityanchorargument$anchor == null) {
|
||||
p_90352_.setCursor(i);
|
||||
throw ERROR_INVALID.createWithContext(p_90352_, s);
|
||||
} else {
|
||||
return entityanchorargument$anchor;
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return SharedSuggestionProvider.suggest(EntityAnchorArgument.Anchor.BY_NAME.keySet(), pBuilder);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static enum Anchor {
|
||||
FEET("feet", (p_90389_, p_90390_) -> {
|
||||
return p_90389_;
|
||||
}),
|
||||
EYES("eyes", (p_90382_, p_90383_) -> {
|
||||
return new Vec3(p_90382_.x, p_90382_.y + (double)p_90383_.getEyeHeight(), p_90382_.z);
|
||||
});
|
||||
|
||||
static final Map<String, EntityAnchorArgument.Anchor> BY_NAME = Util.make(Maps.newHashMap(), (p_90387_) -> {
|
||||
for(EntityAnchorArgument.Anchor entityanchorargument$anchor : values()) {
|
||||
p_90387_.put(entityanchorargument$anchor.name, entityanchorargument$anchor);
|
||||
}
|
||||
|
||||
});
|
||||
private final String name;
|
||||
private final BiFunction<Vec3, Entity, Vec3> transform;
|
||||
|
||||
private Anchor(String pName, BiFunction<Vec3, Entity, Vec3> pTransform) {
|
||||
this.name = pName;
|
||||
this.transform = pTransform;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static EntityAnchorArgument.Anchor getByName(String pName) {
|
||||
return BY_NAME.get(pName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the coordinate based on the given entity's position.
|
||||
*/
|
||||
public Vec3 apply(Entity pEntity) {
|
||||
return this.transform.apply(pEntity.position(), pEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the coordinate based on the given command source's position. If the source is not an entity, no offsetting
|
||||
* occurs.
|
||||
*/
|
||||
public Vec3 apply(CommandSourceStack pSource) {
|
||||
Entity entity = pSource.getEntity();
|
||||
return entity == null ? pSource.getPosition() : this.transform.apply(pSource.getPosition(), entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelector;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
|
||||
public class EntityArgument implements ArgumentType<EntitySelector> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("Player", "0123", "@e", "@e[type=foo]", "dd12be42-52a9-4a91-a8a1-11c01849e498");
|
||||
public static final SimpleCommandExceptionType ERROR_NOT_SINGLE_ENTITY = new SimpleCommandExceptionType(Component.translatable("argument.entity.toomany"));
|
||||
public static final SimpleCommandExceptionType ERROR_NOT_SINGLE_PLAYER = new SimpleCommandExceptionType(Component.translatable("argument.player.toomany"));
|
||||
public static final SimpleCommandExceptionType ERROR_ONLY_PLAYERS_ALLOWED = new SimpleCommandExceptionType(Component.translatable("argument.player.entities"));
|
||||
public static final SimpleCommandExceptionType NO_ENTITIES_FOUND = new SimpleCommandExceptionType(Component.translatable("argument.entity.notfound.entity"));
|
||||
public static final SimpleCommandExceptionType NO_PLAYERS_FOUND = new SimpleCommandExceptionType(Component.translatable("argument.entity.notfound.player"));
|
||||
public static final SimpleCommandExceptionType ERROR_SELECTORS_NOT_ALLOWED = new SimpleCommandExceptionType(Component.translatable("argument.entity.selector.not_allowed"));
|
||||
final boolean single;
|
||||
final boolean playersOnly;
|
||||
|
||||
protected EntityArgument(boolean pSingle, boolean pPlayersOnly) {
|
||||
this.single = pSingle;
|
||||
this.playersOnly = pPlayersOnly;
|
||||
}
|
||||
|
||||
public static EntityArgument entity() {
|
||||
return new EntityArgument(true, false);
|
||||
}
|
||||
|
||||
public static Entity getEntity(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return pContext.getArgument(pName, EntitySelector.class).findSingleEntity(pContext.getSource());
|
||||
}
|
||||
|
||||
public static EntityArgument entities() {
|
||||
return new EntityArgument(false, false);
|
||||
}
|
||||
|
||||
public static Collection<? extends Entity> getEntities(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
Collection<? extends Entity> collection = getOptionalEntities(pContext, pName);
|
||||
if (collection.isEmpty()) {
|
||||
throw NO_ENTITIES_FOUND.create();
|
||||
} else {
|
||||
return collection;
|
||||
}
|
||||
}
|
||||
|
||||
public static Collection<? extends Entity> getOptionalEntities(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return pContext.getArgument(pName, EntitySelector.class).findEntities(pContext.getSource());
|
||||
}
|
||||
|
||||
public static Collection<ServerPlayer> getOptionalPlayers(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return pContext.getArgument(pName, EntitySelector.class).findPlayers(pContext.getSource());
|
||||
}
|
||||
|
||||
public static EntityArgument player() {
|
||||
return new EntityArgument(true, true);
|
||||
}
|
||||
|
||||
public static ServerPlayer getPlayer(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return pContext.getArgument(pName, EntitySelector.class).findSinglePlayer(pContext.getSource());
|
||||
}
|
||||
|
||||
public static EntityArgument players() {
|
||||
return new EntityArgument(false, true);
|
||||
}
|
||||
|
||||
public static Collection<ServerPlayer> getPlayers(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
List<ServerPlayer> list = pContext.getArgument(pName, EntitySelector.class).findPlayers(pContext.getSource());
|
||||
if (list.isEmpty()) {
|
||||
throw NO_PLAYERS_FOUND.create();
|
||||
} else {
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
public EntitySelector parse(StringReader pReader) throws CommandSyntaxException {
|
||||
int i = 0;
|
||||
EntitySelectorParser entityselectorparser = new EntitySelectorParser(pReader);
|
||||
EntitySelector entityselector = entityselectorparser.parse();
|
||||
if (entityselector.getMaxResults() > 1 && this.single) {
|
||||
if (this.playersOnly) {
|
||||
pReader.setCursor(0);
|
||||
throw ERROR_NOT_SINGLE_PLAYER.createWithContext(pReader);
|
||||
} else {
|
||||
pReader.setCursor(0);
|
||||
throw ERROR_NOT_SINGLE_ENTITY.createWithContext(pReader);
|
||||
}
|
||||
} else if (entityselector.includesEntities() && this.playersOnly && !entityselector.isSelfSelector()) {
|
||||
pReader.setCursor(0);
|
||||
throw ERROR_ONLY_PLAYERS_ALLOWED.createWithContext(pReader);
|
||||
} else {
|
||||
return entityselector;
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
S s = pContext.getSource();
|
||||
if (s instanceof SharedSuggestionProvider sharedsuggestionprovider) {
|
||||
StringReader stringreader = new StringReader(pBuilder.getInput());
|
||||
stringreader.setCursor(pBuilder.getStart());
|
||||
EntitySelectorParser entityselectorparser = new EntitySelectorParser(stringreader, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(sharedsuggestionprovider));
|
||||
|
||||
try {
|
||||
entityselectorparser.parse();
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
}
|
||||
|
||||
return entityselectorparser.fillSuggestions(pBuilder, (p_91457_) -> {
|
||||
Collection<String> collection = sharedsuggestionprovider.getOnlinePlayerNames();
|
||||
Iterable<String> iterable = (Iterable<String>)(this.playersOnly ? collection : Iterables.concat(collection, sharedsuggestionprovider.getSelectedEntities()));
|
||||
SharedSuggestionProvider.suggest(iterable, p_91457_);
|
||||
});
|
||||
} else {
|
||||
return Suggestions.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static class Info implements ArgumentTypeInfo<EntityArgument, EntityArgument.Info.Template> {
|
||||
private static final byte FLAG_SINGLE = 1;
|
||||
private static final byte FLAG_PLAYERS_ONLY = 2;
|
||||
|
||||
public void serializeToNetwork(EntityArgument.Info.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
int i = 0;
|
||||
if (pTemplate.single) {
|
||||
i |= 1;
|
||||
}
|
||||
|
||||
if (pTemplate.playersOnly) {
|
||||
i |= 2;
|
||||
}
|
||||
|
||||
pBuffer.writeByte(i);
|
||||
}
|
||||
|
||||
public EntityArgument.Info.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
byte b0 = pBuffer.readByte();
|
||||
return new EntityArgument.Info.Template((b0 & 1) != 0, (b0 & 2) != 0);
|
||||
}
|
||||
|
||||
public void serializeToJson(EntityArgument.Info.Template pTemplate, JsonObject pJson) {
|
||||
pJson.addProperty("amount", pTemplate.single ? "single" : "multiple");
|
||||
pJson.addProperty("type", pTemplate.playersOnly ? "players" : "entities");
|
||||
}
|
||||
|
||||
public EntityArgument.Info.Template unpack(EntityArgument pArgument) {
|
||||
return new EntityArgument.Info.Template(pArgument.single, pArgument.playersOnly);
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<EntityArgument> {
|
||||
final boolean single;
|
||||
final boolean playersOnly;
|
||||
|
||||
Template(boolean pSingle, boolean pPlayersOnly) {
|
||||
this.single = pSingle;
|
||||
this.playersOnly = pPlayersOnly;
|
||||
}
|
||||
|
||||
public EntityArgument instantiate(CommandBuildContext pContext) {
|
||||
return new EntityArgument(this.single, this.playersOnly);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<EntityArgument, ?> type() {
|
||||
return Info.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.level.GameType;
|
||||
|
||||
public class GameModeArgument implements ArgumentType<GameType> {
|
||||
private static final Collection<String> EXAMPLES = Stream.of(GameType.SURVIVAL, GameType.CREATIVE).map(GameType::getName).collect(Collectors.toList());
|
||||
private static final GameType[] VALUES = GameType.values();
|
||||
private static final DynamicCommandExceptionType ERROR_INVALID = new DynamicCommandExceptionType((p_260119_) -> {
|
||||
return Component.translatable("argument.gamemode.invalid", p_260119_);
|
||||
});
|
||||
|
||||
public GameType parse(StringReader pReader) throws CommandSyntaxException {
|
||||
String s = pReader.readUnquotedString();
|
||||
GameType gametype = GameType.byName(s, (GameType)null);
|
||||
if (gametype == null) {
|
||||
throw ERROR_INVALID.createWithContext(pReader, s);
|
||||
} else {
|
||||
return gametype;
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return pContext.getSource() instanceof SharedSuggestionProvider ? SharedSuggestionProvider.suggest(Arrays.stream(VALUES).map(GameType::getName), pBuilder) : Suggestions.empty();
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static GameModeArgument gameMode() {
|
||||
return new GameModeArgument();
|
||||
}
|
||||
|
||||
public static GameType getGameMode(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return pContext.getArgument(pName, GameType.class);
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelector;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
|
||||
public class GameProfileArgument implements ArgumentType<GameProfileArgument.Result> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("Player", "0123", "dd12be42-52a9-4a91-a8a1-11c01849e498", "@e");
|
||||
public static final SimpleCommandExceptionType ERROR_UNKNOWN_PLAYER = new SimpleCommandExceptionType(Component.translatable("argument.player.unknown"));
|
||||
|
||||
public static Collection<GameProfile> getGameProfiles(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return pContext.getArgument(pName, GameProfileArgument.Result.class).getNames(pContext.getSource());
|
||||
}
|
||||
|
||||
public static GameProfileArgument gameProfile() {
|
||||
return new GameProfileArgument();
|
||||
}
|
||||
|
||||
public GameProfileArgument.Result parse(StringReader pReader) throws CommandSyntaxException {
|
||||
if (pReader.canRead() && pReader.peek() == '@') {
|
||||
EntitySelectorParser entityselectorparser = new EntitySelectorParser(pReader);
|
||||
EntitySelector entityselector = entityselectorparser.parse();
|
||||
if (entityselector.includesEntities()) {
|
||||
throw EntityArgument.ERROR_ONLY_PLAYERS_ALLOWED.create();
|
||||
} else {
|
||||
return new GameProfileArgument.SelectorResult(entityselector);
|
||||
}
|
||||
} else {
|
||||
int i = pReader.getCursor();
|
||||
|
||||
while(pReader.canRead() && pReader.peek() != ' ') {
|
||||
pReader.skip();
|
||||
}
|
||||
|
||||
String s = pReader.getString().substring(i, pReader.getCursor());
|
||||
return (p_94595_) -> {
|
||||
Optional<GameProfile> optional = p_94595_.getServer().getProfileCache().get(s);
|
||||
return Collections.singleton(optional.orElseThrow(ERROR_UNKNOWN_PLAYER::create));
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
if (pContext.getSource() instanceof SharedSuggestionProvider) {
|
||||
StringReader stringreader = new StringReader(pBuilder.getInput());
|
||||
stringreader.setCursor(pBuilder.getStart());
|
||||
EntitySelectorParser entityselectorparser = new EntitySelectorParser(stringreader);
|
||||
|
||||
try {
|
||||
entityselectorparser.parse();
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
}
|
||||
|
||||
return entityselectorparser.fillSuggestions(pBuilder, (p_94589_) -> {
|
||||
SharedSuggestionProvider.suggest(((SharedSuggestionProvider)pContext.getSource()).getOnlinePlayerNames(), p_94589_);
|
||||
});
|
||||
} else {
|
||||
return Suggestions.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Result {
|
||||
Collection<GameProfile> getNames(CommandSourceStack pSource) throws CommandSyntaxException;
|
||||
}
|
||||
|
||||
public static class SelectorResult implements GameProfileArgument.Result {
|
||||
private final EntitySelector selector;
|
||||
|
||||
public SelectorResult(EntitySelector pSelector) {
|
||||
this.selector = pSelector;
|
||||
}
|
||||
|
||||
public Collection<GameProfile> getNames(CommandSourceStack pSource) throws CommandSyntaxException {
|
||||
List<ServerPlayer> list = this.selector.findPlayers(pSource);
|
||||
if (list.isEmpty()) {
|
||||
throw EntityArgument.NO_PLAYERS_FOUND.create();
|
||||
} else {
|
||||
List<GameProfile> list1 = Lists.newArrayList();
|
||||
|
||||
for(ServerPlayer serverplayer : list) {
|
||||
list1.add(serverplayer.getGameProfile());
|
||||
}
|
||||
|
||||
return list1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.serialization.Codec;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.util.StringRepresentable;
|
||||
import net.minecraft.world.level.levelgen.Heightmap;
|
||||
|
||||
public class HeightmapTypeArgument extends StringRepresentableArgument<Heightmap.Types> {
|
||||
private static final Codec<Heightmap.Types> LOWER_CASE_CODEC = StringRepresentable.fromEnumWithMapping(HeightmapTypeArgument::keptTypes, (p_275334_) -> {
|
||||
return p_275334_.toLowerCase(Locale.ROOT);
|
||||
});
|
||||
|
||||
private static Heightmap.Types[] keptTypes() {
|
||||
return Arrays.stream(Heightmap.Types.values()).filter(Heightmap.Types::keepAfterWorldgen).toArray((p_275295_) -> {
|
||||
return new Heightmap.Types[p_275295_];
|
||||
});
|
||||
}
|
||||
|
||||
private HeightmapTypeArgument() {
|
||||
super(LOWER_CASE_CODEC, HeightmapTypeArgument::keptTypes);
|
||||
}
|
||||
|
||||
public static HeightmapTypeArgument heightmap() {
|
||||
return new HeightmapTypeArgument();
|
||||
}
|
||||
|
||||
public static Heightmap.Types getHeightmap(CommandContext<CommandSourceStack> pContext, String pArgument) {
|
||||
return pContext.getArgument(pArgument, Heightmap.Types.class);
|
||||
}
|
||||
|
||||
protected String convertId(String pId) {
|
||||
return pId.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.commands.CommandSigningContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelector;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.MutableComponent;
|
||||
import net.minecraft.network.chat.PlayerChatMessage;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.network.FilteredText;
|
||||
|
||||
public class MessageArgument implements SignedArgument<MessageArgument.Message> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("Hello world!", "foo", "@e", "Hello @p :)");
|
||||
|
||||
public static MessageArgument message() {
|
||||
return new MessageArgument();
|
||||
}
|
||||
|
||||
public static Component getMessage(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
MessageArgument.Message messageargument$message = pContext.getArgument(pName, MessageArgument.Message.class);
|
||||
return messageargument$message.resolveComponent(pContext.getSource());
|
||||
}
|
||||
|
||||
public static void resolveChatMessage(CommandContext<CommandSourceStack> pContext, String pKey, Consumer<PlayerChatMessage> pCallback) throws CommandSyntaxException {
|
||||
MessageArgument.Message messageargument$message = pContext.getArgument(pKey, MessageArgument.Message.class);
|
||||
CommandSourceStack commandsourcestack = pContext.getSource();
|
||||
Component component = messageargument$message.resolveComponent(commandsourcestack);
|
||||
CommandSigningContext commandsigningcontext = commandsourcestack.getSigningContext();
|
||||
PlayerChatMessage playerchatmessage = commandsigningcontext.getArgument(pKey);
|
||||
if (playerchatmessage != null) {
|
||||
resolveSignedMessage(pCallback, commandsourcestack, playerchatmessage.withUnsignedContent(component));
|
||||
} else {
|
||||
resolveDisguisedMessage(pCallback, commandsourcestack, PlayerChatMessage.system(messageargument$message.text).withUnsignedContent(component));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void resolveSignedMessage(Consumer<PlayerChatMessage> pCallback, CommandSourceStack pSource, PlayerChatMessage pMessage) {
|
||||
MinecraftServer minecraftserver = pSource.getServer();
|
||||
CompletableFuture<FilteredText> completablefuture = filterPlainText(pSource, pMessage);
|
||||
CompletableFuture<Component> completablefuture1 = minecraftserver.getChatDecorator().decorate(pSource.getPlayer(), pMessage.decoratedContent());
|
||||
pSource.getChatMessageChainer().append((p_247979_) -> {
|
||||
return CompletableFuture.allOf(completablefuture, completablefuture1).thenAcceptAsync((p_247970_) -> {
|
||||
PlayerChatMessage playerchatmessage = pMessage.withUnsignedContent(completablefuture1.join()).filter(completablefuture.join().mask());
|
||||
pCallback.accept(playerchatmessage);
|
||||
}, p_247979_);
|
||||
});
|
||||
}
|
||||
|
||||
private static void resolveDisguisedMessage(Consumer<PlayerChatMessage> pCallback, CommandSourceStack pSource, PlayerChatMessage pMessage) {
|
||||
MinecraftServer minecraftserver = pSource.getServer();
|
||||
CompletableFuture<Component> completablefuture = minecraftserver.getChatDecorator().decorate(pSource.getPlayer(), pMessage.decoratedContent());
|
||||
pSource.getChatMessageChainer().append((p_247974_) -> {
|
||||
return completablefuture.thenAcceptAsync((p_247965_) -> {
|
||||
pCallback.accept(pMessage.withUnsignedContent(p_247965_));
|
||||
}, p_247974_);
|
||||
});
|
||||
}
|
||||
|
||||
private static CompletableFuture<FilteredText> filterPlainText(CommandSourceStack pSource, PlayerChatMessage pMessage) {
|
||||
ServerPlayer serverplayer = pSource.getPlayer();
|
||||
return serverplayer != null && pMessage.hasSignatureFrom(serverplayer.getUUID()) ? serverplayer.getTextFilter().processStreamMessage(pMessage.signedContent()) : CompletableFuture.completedFuture(FilteredText.passThrough(pMessage.signedContent()));
|
||||
}
|
||||
|
||||
public MessageArgument.Message parse(StringReader pReader) throws CommandSyntaxException {
|
||||
return MessageArgument.Message.parseText(pReader, true);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static class Message {
|
||||
final String text;
|
||||
private final MessageArgument.Part[] parts;
|
||||
|
||||
public Message(String pText, MessageArgument.Part[] pParts) {
|
||||
this.text = pText;
|
||||
this.parts = pParts;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return this.text;
|
||||
}
|
||||
|
||||
public MessageArgument.Part[] getParts() {
|
||||
return this.parts;
|
||||
}
|
||||
|
||||
Component resolveComponent(CommandSourceStack pSource) throws CommandSyntaxException {
|
||||
return this.toComponent(pSource, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(pSource));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts this message into a text component, replacing any selectors in the text with the actual evaluated
|
||||
* selector.
|
||||
*/
|
||||
public Component toComponent(CommandSourceStack pSource, boolean pAllowSelectors) throws CommandSyntaxException {
|
||||
if (this.parts.length != 0 && pAllowSelectors) {
|
||||
MutableComponent mutablecomponent = Component.literal(this.text.substring(0, this.parts[0].getStart()));
|
||||
int i = this.parts[0].getStart();
|
||||
|
||||
for(MessageArgument.Part messageargument$part : this.parts) {
|
||||
Component component = messageargument$part.toComponent(pSource);
|
||||
if (i < messageargument$part.getStart()) {
|
||||
mutablecomponent.append(this.text.substring(i, messageargument$part.getStart()));
|
||||
}
|
||||
|
||||
if (component != null) {
|
||||
mutablecomponent.append(component);
|
||||
}
|
||||
|
||||
i = messageargument$part.getEnd();
|
||||
}
|
||||
|
||||
if (i < this.text.length()) {
|
||||
mutablecomponent.append(this.text.substring(i));
|
||||
}
|
||||
|
||||
return mutablecomponent;
|
||||
} else {
|
||||
return Component.literal(this.text);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a message. The algorithm for this is simply to run through and look for selectors, ignoring any invalid
|
||||
* selectors in the text (since players may type e.g. "[@]").
|
||||
*/
|
||||
public static MessageArgument.Message parseText(StringReader pReader, boolean pAllowSelectors) throws CommandSyntaxException {
|
||||
String s = pReader.getString().substring(pReader.getCursor(), pReader.getTotalLength());
|
||||
if (!pAllowSelectors) {
|
||||
pReader.setCursor(pReader.getTotalLength());
|
||||
return new MessageArgument.Message(s, new MessageArgument.Part[0]);
|
||||
} else {
|
||||
List<MessageArgument.Part> list = Lists.newArrayList();
|
||||
int i = pReader.getCursor();
|
||||
|
||||
while(true) {
|
||||
int j;
|
||||
EntitySelector entityselector;
|
||||
while(true) {
|
||||
if (!pReader.canRead()) {
|
||||
return new MessageArgument.Message(s, list.toArray(new MessageArgument.Part[0]));
|
||||
}
|
||||
|
||||
if (pReader.peek() == '@') {
|
||||
j = pReader.getCursor();
|
||||
|
||||
try {
|
||||
EntitySelectorParser entityselectorparser = new EntitySelectorParser(pReader);
|
||||
entityselector = entityselectorparser.parse();
|
||||
break;
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
if (commandsyntaxexception.getType() != EntitySelectorParser.ERROR_MISSING_SELECTOR_TYPE && commandsyntaxexception.getType() != EntitySelectorParser.ERROR_UNKNOWN_SELECTOR_TYPE) {
|
||||
throw commandsyntaxexception;
|
||||
}
|
||||
|
||||
pReader.setCursor(j + 1);
|
||||
}
|
||||
} else {
|
||||
pReader.skip();
|
||||
}
|
||||
}
|
||||
|
||||
list.add(new MessageArgument.Part(j - i, pReader.getCursor() - i, entityselector));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class Part {
|
||||
private final int start;
|
||||
private final int end;
|
||||
private final EntitySelector selector;
|
||||
|
||||
public Part(int pStart, int pEnd, EntitySelector pSelector) {
|
||||
this.start = pStart;
|
||||
this.end = pEnd;
|
||||
this.selector = pSelector;
|
||||
}
|
||||
|
||||
public int getStart() {
|
||||
return this.start;
|
||||
}
|
||||
|
||||
public int getEnd() {
|
||||
return this.end;
|
||||
}
|
||||
|
||||
public EntitySelector getSelector() {
|
||||
return this.selector;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the selector and returns the component produced by it. This method does not actually appear to ever return
|
||||
* null.
|
||||
*/
|
||||
@Nullable
|
||||
public Component toComponent(CommandSourceStack pSource) throws CommandSyntaxException {
|
||||
return EntitySelector.joinNames(this.selector.findEntities(pSource));
|
||||
}
|
||||
}
|
||||
}
|
||||
+758
@@ -0,0 +1,758 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.nbt.CollectionTag;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.nbt.NbtUtils;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.nbt.TagParser;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import org.apache.commons.lang3.mutable.MutableBoolean;
|
||||
|
||||
public class NbtPathArgument implements ArgumentType<NbtPathArgument.NbtPath> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo.bar", "foo[0]", "[0]", "[]", "{foo=bar}");
|
||||
public static final SimpleCommandExceptionType ERROR_INVALID_NODE = new SimpleCommandExceptionType(Component.translatable("arguments.nbtpath.node.invalid"));
|
||||
public static final SimpleCommandExceptionType ERROR_DATA_TOO_DEEP = new SimpleCommandExceptionType(Component.translatable("arguments.nbtpath.too_deep"));
|
||||
public static final DynamicCommandExceptionType ERROR_NOTHING_FOUND = new DynamicCommandExceptionType((p_99502_) -> {
|
||||
return Component.translatable("arguments.nbtpath.nothing_found", p_99502_);
|
||||
});
|
||||
static final DynamicCommandExceptionType ERROR_EXPECTED_LIST = new DynamicCommandExceptionType((p_263253_) -> {
|
||||
return Component.translatable("commands.data.modify.expected_list", p_263253_);
|
||||
});
|
||||
static final DynamicCommandExceptionType ERROR_INVALID_INDEX = new DynamicCommandExceptionType((p_263252_) -> {
|
||||
return Component.translatable("commands.data.modify.invalid_index", p_263252_);
|
||||
});
|
||||
private static final char INDEX_MATCH_START = '[';
|
||||
private static final char INDEX_MATCH_END = ']';
|
||||
private static final char KEY_MATCH_START = '{';
|
||||
private static final char KEY_MATCH_END = '}';
|
||||
private static final char QUOTED_KEY_START = '"';
|
||||
private static final char SINGLE_QUOTED_KEY_START = '\'';
|
||||
|
||||
public static NbtPathArgument nbtPath() {
|
||||
return new NbtPathArgument();
|
||||
}
|
||||
|
||||
public static NbtPathArgument.NbtPath getPath(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, NbtPathArgument.NbtPath.class);
|
||||
}
|
||||
|
||||
public NbtPathArgument.NbtPath parse(StringReader pReader) throws CommandSyntaxException {
|
||||
List<NbtPathArgument.Node> list = Lists.newArrayList();
|
||||
int i = pReader.getCursor();
|
||||
Object2IntMap<NbtPathArgument.Node> object2intmap = new Object2IntOpenHashMap<>();
|
||||
boolean flag = true;
|
||||
|
||||
while(pReader.canRead() && pReader.peek() != ' ') {
|
||||
NbtPathArgument.Node nbtpathargument$node = parseNode(pReader, flag);
|
||||
list.add(nbtpathargument$node);
|
||||
object2intmap.put(nbtpathargument$node, pReader.getCursor() - i);
|
||||
flag = false;
|
||||
if (pReader.canRead()) {
|
||||
char c0 = pReader.peek();
|
||||
if (c0 != ' ' && c0 != '[' && c0 != '{') {
|
||||
pReader.expect('.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new NbtPathArgument.NbtPath(pReader.getString().substring(i, pReader.getCursor()), list.toArray(new NbtPathArgument.Node[0]), object2intmap);
|
||||
}
|
||||
|
||||
private static NbtPathArgument.Node parseNode(StringReader pReader, boolean pFirst) throws CommandSyntaxException {
|
||||
Object object;
|
||||
switch (pReader.peek()) {
|
||||
case '"':
|
||||
case '\'':
|
||||
object = readObjectNode(pReader, pReader.readString());
|
||||
break;
|
||||
case '[':
|
||||
pReader.skip();
|
||||
int i = pReader.peek();
|
||||
if (i == 123) {
|
||||
CompoundTag compoundtag1 = (new TagParser(pReader)).readStruct();
|
||||
pReader.expect(']');
|
||||
object = new NbtPathArgument.MatchElementNode(compoundtag1);
|
||||
} else if (i == 93) {
|
||||
pReader.skip();
|
||||
object = NbtPathArgument.AllElementsNode.INSTANCE;
|
||||
} else {
|
||||
int j = pReader.readInt();
|
||||
pReader.expect(']');
|
||||
object = new NbtPathArgument.IndexedElementNode(j);
|
||||
}
|
||||
break;
|
||||
case '{':
|
||||
if (!pFirst) {
|
||||
throw ERROR_INVALID_NODE.createWithContext(pReader);
|
||||
}
|
||||
|
||||
CompoundTag compoundtag = (new TagParser(pReader)).readStruct();
|
||||
object = new NbtPathArgument.MatchRootObjectNode(compoundtag);
|
||||
break;
|
||||
default:
|
||||
object = readObjectNode(pReader, readUnquotedName(pReader));
|
||||
}
|
||||
|
||||
return (NbtPathArgument.Node)object;
|
||||
}
|
||||
|
||||
private static NbtPathArgument.Node readObjectNode(StringReader pReader, String pName) throws CommandSyntaxException {
|
||||
if (pReader.canRead() && pReader.peek() == '{') {
|
||||
CompoundTag compoundtag = (new TagParser(pReader)).readStruct();
|
||||
return new NbtPathArgument.MatchObjectNode(pName, compoundtag);
|
||||
} else {
|
||||
return new NbtPathArgument.CompoundChildNode(pName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a tag name until the next special character. Throws if the result would be a 0-length string. Does not
|
||||
* handle quoted tag names.
|
||||
*/
|
||||
private static String readUnquotedName(StringReader pReader) throws CommandSyntaxException {
|
||||
int i = pReader.getCursor();
|
||||
|
||||
while(pReader.canRead() && isAllowedInUnquotedName(pReader.peek())) {
|
||||
pReader.skip();
|
||||
}
|
||||
|
||||
if (pReader.getCursor() == i) {
|
||||
throw ERROR_INVALID_NODE.createWithContext(pReader);
|
||||
} else {
|
||||
return pReader.getString().substring(i, pReader.getCursor());
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {@code true} if the given character is normal for a tag name; otherwise {@code false} if it has special
|
||||
* meaning for paths.
|
||||
*/
|
||||
private static boolean isAllowedInUnquotedName(char pCh) {
|
||||
return pCh != ' ' && pCh != '"' && pCh != '\'' && pCh != '[' && pCh != ']' && pCh != '.' && pCh != '{' && pCh != '}';
|
||||
}
|
||||
|
||||
static Predicate<Tag> createTagPredicate(CompoundTag pTag) {
|
||||
return (p_99507_) -> {
|
||||
return NbtUtils.compareNbt(pTag, p_99507_, true);
|
||||
};
|
||||
}
|
||||
|
||||
static class AllElementsNode implements NbtPathArgument.Node {
|
||||
public static final NbtPathArgument.AllElementsNode INSTANCE = new NbtPathArgument.AllElementsNode();
|
||||
|
||||
private AllElementsNode() {
|
||||
}
|
||||
|
||||
public void getTag(Tag pTag, List<Tag> pTags) {
|
||||
if (pTag instanceof CollectionTag) {
|
||||
pTags.addAll((CollectionTag)pTag);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void getOrCreateTag(Tag pTag, Supplier<Tag> pSupplier, List<Tag> pTags) {
|
||||
if (pTag instanceof CollectionTag<?> collectiontag) {
|
||||
if (collectiontag.isEmpty()) {
|
||||
Tag tag = pSupplier.get();
|
||||
if (collectiontag.addTag(0, tag)) {
|
||||
pTags.add(tag);
|
||||
}
|
||||
} else {
|
||||
pTags.addAll(collectiontag);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an empty element of the type read by this node.
|
||||
*/
|
||||
public Tag createPreferredParentTag() {
|
||||
return new ListTag();
|
||||
}
|
||||
|
||||
public int setTag(Tag pTag, Supplier<Tag> pSupplier) {
|
||||
if (!(pTag instanceof CollectionTag<?> collectiontag)) {
|
||||
return 0;
|
||||
} else {
|
||||
int i = collectiontag.size();
|
||||
if (i == 0) {
|
||||
collectiontag.addTag(0, pSupplier.get());
|
||||
return 1;
|
||||
} else {
|
||||
Tag tag = pSupplier.get();
|
||||
int j = i - (int)collectiontag.stream().filter(tag::equals).count();
|
||||
if (j == 0) {
|
||||
return 0;
|
||||
} else {
|
||||
collectiontag.clear();
|
||||
if (!collectiontag.addTag(0, tag)) {
|
||||
return 0;
|
||||
} else {
|
||||
for(int k = 1; k < i; ++k) {
|
||||
collectiontag.addTag(k, pSupplier.get());
|
||||
}
|
||||
|
||||
return j;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int removeTag(Tag pTag) {
|
||||
if (pTag instanceof CollectionTag<?> collectiontag) {
|
||||
int i = collectiontag.size();
|
||||
if (i > 0) {
|
||||
collectiontag.clear();
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static class CompoundChildNode implements NbtPathArgument.Node {
|
||||
private final String name;
|
||||
|
||||
public CompoundChildNode(String pName) {
|
||||
this.name = pName;
|
||||
}
|
||||
|
||||
public void getTag(Tag pTag, List<Tag> pTags) {
|
||||
if (pTag instanceof CompoundTag) {
|
||||
Tag tag = ((CompoundTag)pTag).get(this.name);
|
||||
if (tag != null) {
|
||||
pTags.add(tag);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void getOrCreateTag(Tag pTag, Supplier<Tag> pSupplier, List<Tag> pTags) {
|
||||
if (pTag instanceof CompoundTag compoundtag) {
|
||||
Tag tag;
|
||||
if (compoundtag.contains(this.name)) {
|
||||
tag = compoundtag.get(this.name);
|
||||
} else {
|
||||
tag = pSupplier.get();
|
||||
compoundtag.put(this.name, tag);
|
||||
}
|
||||
|
||||
pTags.add(tag);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an empty element of the type read by this node.
|
||||
*/
|
||||
public Tag createPreferredParentTag() {
|
||||
return new CompoundTag();
|
||||
}
|
||||
|
||||
public int setTag(Tag pTag, Supplier<Tag> pSupplier) {
|
||||
if (pTag instanceof CompoundTag compoundtag) {
|
||||
Tag tag = pSupplier.get();
|
||||
Tag tag1 = compoundtag.put(this.name, tag);
|
||||
if (!tag.equals(tag1)) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int removeTag(Tag pTag) {
|
||||
if (pTag instanceof CompoundTag compoundtag) {
|
||||
if (compoundtag.contains(this.name)) {
|
||||
compoundtag.remove(this.name);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static class IndexedElementNode implements NbtPathArgument.Node {
|
||||
private final int index;
|
||||
|
||||
public IndexedElementNode(int pIndex) {
|
||||
this.index = pIndex;
|
||||
}
|
||||
|
||||
public void getTag(Tag pTag, List<Tag> pTags) {
|
||||
if (pTag instanceof CollectionTag<?> collectiontag) {
|
||||
int i = collectiontag.size();
|
||||
int j = this.index < 0 ? i + this.index : this.index;
|
||||
if (0 <= j && j < i) {
|
||||
pTags.add(collectiontag.get(j));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void getOrCreateTag(Tag pTag, Supplier<Tag> pSupplier, List<Tag> pTags) {
|
||||
this.getTag(pTag, pTags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an empty element of the type read by this node.
|
||||
*/
|
||||
public Tag createPreferredParentTag() {
|
||||
return new ListTag();
|
||||
}
|
||||
|
||||
public int setTag(Tag pTag, Supplier<Tag> pSupplier) {
|
||||
if (pTag instanceof CollectionTag<?> collectiontag) {
|
||||
int i = collectiontag.size();
|
||||
int j = this.index < 0 ? i + this.index : this.index;
|
||||
if (0 <= j && j < i) {
|
||||
Tag tag = collectiontag.get(j);
|
||||
Tag tag1 = pSupplier.get();
|
||||
if (!tag1.equals(tag) && collectiontag.setTag(j, tag1)) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int removeTag(Tag pTag) {
|
||||
if (pTag instanceof CollectionTag<?> collectiontag) {
|
||||
int i = collectiontag.size();
|
||||
int j = this.index < 0 ? i + this.index : this.index;
|
||||
if (0 <= j && j < i) {
|
||||
collectiontag.remove(j);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static class MatchElementNode implements NbtPathArgument.Node {
|
||||
private final CompoundTag pattern;
|
||||
private final Predicate<Tag> predicate;
|
||||
|
||||
public MatchElementNode(CompoundTag pPattern) {
|
||||
this.pattern = pPattern;
|
||||
this.predicate = NbtPathArgument.createTagPredicate(pPattern);
|
||||
}
|
||||
|
||||
public void getTag(Tag pTag, List<Tag> pTags) {
|
||||
if (pTag instanceof ListTag listtag) {
|
||||
listtag.stream().filter(this.predicate).forEach(pTags::add);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void getOrCreateTag(Tag pTag, Supplier<Tag> pSupplier, List<Tag> pTags) {
|
||||
MutableBoolean mutableboolean = new MutableBoolean();
|
||||
if (pTag instanceof ListTag listtag) {
|
||||
listtag.stream().filter(this.predicate).forEach((p_99571_) -> {
|
||||
pTags.add(p_99571_);
|
||||
mutableboolean.setTrue();
|
||||
});
|
||||
if (mutableboolean.isFalse()) {
|
||||
CompoundTag compoundtag = this.pattern.copy();
|
||||
listtag.add(compoundtag);
|
||||
pTags.add(compoundtag);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an empty element of the type read by this node.
|
||||
*/
|
||||
public Tag createPreferredParentTag() {
|
||||
return new ListTag();
|
||||
}
|
||||
|
||||
public int setTag(Tag pTag, Supplier<Tag> pSupplier) {
|
||||
int i = 0;
|
||||
if (pTag instanceof ListTag listtag) {
|
||||
int j = listtag.size();
|
||||
if (j == 0) {
|
||||
listtag.add(pSupplier.get());
|
||||
++i;
|
||||
} else {
|
||||
for(int k = 0; k < j; ++k) {
|
||||
Tag tag = listtag.get(k);
|
||||
if (this.predicate.test(tag)) {
|
||||
Tag tag1 = pSupplier.get();
|
||||
if (!tag1.equals(tag) && listtag.setTag(k, tag1)) {
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
public int removeTag(Tag pTag) {
|
||||
int i = 0;
|
||||
if (pTag instanceof ListTag listtag) {
|
||||
for(int j = listtag.size() - 1; j >= 0; --j) {
|
||||
if (this.predicate.test(listtag.get(j))) {
|
||||
listtag.remove(j);
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
static class MatchObjectNode implements NbtPathArgument.Node {
|
||||
private final String name;
|
||||
private final CompoundTag pattern;
|
||||
private final Predicate<Tag> predicate;
|
||||
|
||||
public MatchObjectNode(String pName, CompoundTag pPattern) {
|
||||
this.name = pName;
|
||||
this.pattern = pPattern;
|
||||
this.predicate = NbtPathArgument.createTagPredicate(pPattern);
|
||||
}
|
||||
|
||||
public void getTag(Tag pTag, List<Tag> pTags) {
|
||||
if (pTag instanceof CompoundTag) {
|
||||
Tag tag = ((CompoundTag)pTag).get(this.name);
|
||||
if (this.predicate.test(tag)) {
|
||||
pTags.add(tag);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void getOrCreateTag(Tag pTag, Supplier<Tag> pSupplier, List<Tag> pTags) {
|
||||
if (pTag instanceof CompoundTag compoundtag) {
|
||||
Tag tag = compoundtag.get(this.name);
|
||||
if (tag == null) {
|
||||
Tag compoundtag1 = this.pattern.copy();
|
||||
compoundtag.put(this.name, compoundtag1);
|
||||
pTags.add(compoundtag1);
|
||||
} else if (this.predicate.test(tag)) {
|
||||
pTags.add(tag);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an empty element of the type read by this node.
|
||||
*/
|
||||
public Tag createPreferredParentTag() {
|
||||
return new CompoundTag();
|
||||
}
|
||||
|
||||
public int setTag(Tag pTag, Supplier<Tag> pSupplier) {
|
||||
if (pTag instanceof CompoundTag compoundtag) {
|
||||
Tag tag = compoundtag.get(this.name);
|
||||
if (this.predicate.test(tag)) {
|
||||
Tag tag1 = pSupplier.get();
|
||||
if (!tag1.equals(tag)) {
|
||||
compoundtag.put(this.name, tag1);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int removeTag(Tag pTag) {
|
||||
if (pTag instanceof CompoundTag compoundtag) {
|
||||
Tag tag = compoundtag.get(this.name);
|
||||
if (this.predicate.test(tag)) {
|
||||
compoundtag.remove(this.name);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static class MatchRootObjectNode implements NbtPathArgument.Node {
|
||||
private final Predicate<Tag> predicate;
|
||||
|
||||
public MatchRootObjectNode(CompoundTag pTag) {
|
||||
this.predicate = NbtPathArgument.createTagPredicate(pTag);
|
||||
}
|
||||
|
||||
public void getTag(Tag pTag, List<Tag> pTags) {
|
||||
if (pTag instanceof CompoundTag && this.predicate.test(pTag)) {
|
||||
pTags.add(pTag);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void getOrCreateTag(Tag pTag, Supplier<Tag> pSupplier, List<Tag> pTags) {
|
||||
this.getTag(pTag, pTags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an empty element of the type read by this node.
|
||||
*/
|
||||
public Tag createPreferredParentTag() {
|
||||
return new CompoundTag();
|
||||
}
|
||||
|
||||
public int setTag(Tag pTag, Supplier<Tag> pSupplier) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int removeTag(Tag pTag) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static class NbtPath {
|
||||
private final String original;
|
||||
private final Object2IntMap<NbtPathArgument.Node> nodeToOriginalPosition;
|
||||
private final NbtPathArgument.Node[] nodes;
|
||||
|
||||
public NbtPath(String pOriginal, NbtPathArgument.Node[] pNodes, Object2IntMap<NbtPathArgument.Node> pNodeToOriginPosition) {
|
||||
this.original = pOriginal;
|
||||
this.nodes = pNodes;
|
||||
this.nodeToOriginalPosition = pNodeToOriginPosition;
|
||||
}
|
||||
|
||||
public List<Tag> get(Tag pTag) throws CommandSyntaxException {
|
||||
List<Tag> list = Collections.singletonList(pTag);
|
||||
|
||||
for(NbtPathArgument.Node nbtpathargument$node : this.nodes) {
|
||||
list = nbtpathargument$node.get(list);
|
||||
if (list.isEmpty()) {
|
||||
throw this.createNotFoundException(nbtpathargument$node);
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public int countMatching(Tag pTag) {
|
||||
List<Tag> list = Collections.singletonList(pTag);
|
||||
|
||||
for(NbtPathArgument.Node nbtpathargument$node : this.nodes) {
|
||||
list = nbtpathargument$node.get(list);
|
||||
if (list.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return list.size();
|
||||
}
|
||||
|
||||
private List<Tag> getOrCreateParents(Tag pTag) throws CommandSyntaxException {
|
||||
List<Tag> list = Collections.singletonList(pTag);
|
||||
|
||||
for(int i = 0; i < this.nodes.length - 1; ++i) {
|
||||
NbtPathArgument.Node nbtpathargument$node = this.nodes[i];
|
||||
int j = i + 1;
|
||||
list = nbtpathargument$node.getOrCreate(list, this.nodes[j]::createPreferredParentTag);
|
||||
if (list.isEmpty()) {
|
||||
throw this.createNotFoundException(nbtpathargument$node);
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public List<Tag> getOrCreate(Tag pTag, Supplier<Tag> pSupplier) throws CommandSyntaxException {
|
||||
List<Tag> list = this.getOrCreateParents(pTag);
|
||||
NbtPathArgument.Node nbtpathargument$node = this.nodes[this.nodes.length - 1];
|
||||
return nbtpathargument$node.getOrCreate(list, pSupplier);
|
||||
}
|
||||
|
||||
private static int apply(List<Tag> pTags, Function<Tag, Integer> pFunction) {
|
||||
return pTags.stream().map(pFunction).reduce(0, (p_99633_, p_99634_) -> {
|
||||
return p_99633_ + p_99634_;
|
||||
});
|
||||
}
|
||||
|
||||
public static boolean isTooDeep(Tag pTag, int pCurrentDepth) {
|
||||
if (pCurrentDepth >= 512) {
|
||||
return true;
|
||||
} else {
|
||||
if (pTag instanceof CompoundTag) {
|
||||
CompoundTag compoundtag = (CompoundTag)pTag;
|
||||
|
||||
for(String s : compoundtag.getAllKeys()) {
|
||||
Tag tag = compoundtag.get(s);
|
||||
if (tag != null && isTooDeep(tag, pCurrentDepth + 1)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else if (pTag instanceof ListTag) {
|
||||
for(Tag tag1 : (ListTag)pTag) {
|
||||
if (isTooDeep(tag1, pCurrentDepth + 1)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public int set(Tag pTag, Tag pOther) throws CommandSyntaxException {
|
||||
if (isTooDeep(pOther, this.estimatePathDepth())) {
|
||||
throw NbtPathArgument.ERROR_DATA_TOO_DEEP.create();
|
||||
} else {
|
||||
Tag tag = pOther.copy();
|
||||
List<Tag> list = this.getOrCreateParents(pTag);
|
||||
if (list.isEmpty()) {
|
||||
return 0;
|
||||
} else {
|
||||
NbtPathArgument.Node nbtpathargument$node = this.nodes[this.nodes.length - 1];
|
||||
MutableBoolean mutableboolean = new MutableBoolean(false);
|
||||
return apply(list, (p_263259_) -> {
|
||||
return nbtpathargument$node.setTag(p_263259_, () -> {
|
||||
if (mutableboolean.isFalse()) {
|
||||
mutableboolean.setTrue();
|
||||
return tag;
|
||||
} else {
|
||||
return tag.copy();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int estimatePathDepth() {
|
||||
return this.nodes.length;
|
||||
}
|
||||
|
||||
public int insert(int pIndex, CompoundTag pRootTag, List<Tag> pTagsToInsert) throws CommandSyntaxException {
|
||||
List<Tag> list = new ArrayList<>(pTagsToInsert.size());
|
||||
|
||||
for(Tag tag : pTagsToInsert) {
|
||||
Tag tag1 = tag.copy();
|
||||
list.add(tag1);
|
||||
if (isTooDeep(tag1, this.estimatePathDepth())) {
|
||||
throw NbtPathArgument.ERROR_DATA_TOO_DEEP.create();
|
||||
}
|
||||
}
|
||||
|
||||
Collection<Tag> collection = this.getOrCreate(pRootTag, ListTag::new);
|
||||
int j = 0;
|
||||
boolean flag1 = false;
|
||||
|
||||
for(Tag tag2 : collection) {
|
||||
if (!(tag2 instanceof CollectionTag)) {
|
||||
throw NbtPathArgument.ERROR_EXPECTED_LIST.create(tag2);
|
||||
}
|
||||
|
||||
CollectionTag<?> collectiontag = (CollectionTag)tag2;
|
||||
boolean flag = false;
|
||||
int i = pIndex < 0 ? collectiontag.size() + pIndex + 1 : pIndex;
|
||||
|
||||
for(Tag tag3 : list) {
|
||||
try {
|
||||
if (collectiontag.addTag(i, flag1 ? tag3.copy() : tag3)) {
|
||||
++i;
|
||||
flag = true;
|
||||
}
|
||||
} catch (IndexOutOfBoundsException indexoutofboundsexception) {
|
||||
throw NbtPathArgument.ERROR_INVALID_INDEX.create(i);
|
||||
}
|
||||
}
|
||||
|
||||
flag1 = true;
|
||||
j += flag ? 1 : 0;
|
||||
}
|
||||
|
||||
return j;
|
||||
}
|
||||
|
||||
public int remove(Tag pTag) {
|
||||
List<Tag> list = Collections.singletonList(pTag);
|
||||
|
||||
for(int i = 0; i < this.nodes.length - 1; ++i) {
|
||||
list = this.nodes[i].get(list);
|
||||
}
|
||||
|
||||
NbtPathArgument.Node nbtpathargument$node = this.nodes[this.nodes.length - 1];
|
||||
return apply(list, nbtpathargument$node::removeTag);
|
||||
}
|
||||
|
||||
private CommandSyntaxException createNotFoundException(NbtPathArgument.Node pNode) {
|
||||
int i = this.nodeToOriginalPosition.getInt(pNode);
|
||||
return NbtPathArgument.ERROR_NOTHING_FOUND.create(this.original.substring(0, i));
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.original;
|
||||
}
|
||||
}
|
||||
|
||||
interface Node {
|
||||
void getTag(Tag p_99666_, List<Tag> p_99667_);
|
||||
|
||||
void getOrCreateTag(Tag pTag, Supplier<Tag> pSupplier, List<Tag> pTags);
|
||||
|
||||
/**
|
||||
* Creates an empty element of the type read by this node.
|
||||
*/
|
||||
Tag createPreferredParentTag();
|
||||
|
||||
int setTag(Tag pTag, Supplier<Tag> pSupplier);
|
||||
|
||||
int removeTag(Tag pTag);
|
||||
|
||||
default List<Tag> get(List<Tag> pTags) {
|
||||
return this.collect(pTags, this::getTag);
|
||||
}
|
||||
|
||||
default List<Tag> getOrCreate(List<Tag> pTags, Supplier<Tag> pSupplier) {
|
||||
return this.collect(pTags, (p_99663_, p_99664_) -> {
|
||||
this.getOrCreateTag(p_99663_, pSupplier, p_99664_);
|
||||
});
|
||||
}
|
||||
|
||||
default List<Tag> collect(List<Tag> pTags, BiConsumer<Tag, List<Tag>> pConsumer) {
|
||||
List<Tag> list = Lists.newArrayList();
|
||||
|
||||
for(Tag tag : pTags) {
|
||||
pConsumer.accept(tag, list);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.nbt.TagParser;
|
||||
|
||||
public class NbtTagArgument implements ArgumentType<Tag> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("0", "0b", "0l", "0.0", "\"foo\"", "{foo=bar}", "[0]");
|
||||
|
||||
private NbtTagArgument() {
|
||||
}
|
||||
|
||||
public static NbtTagArgument nbtTag() {
|
||||
return new NbtTagArgument();
|
||||
}
|
||||
|
||||
public static <S> Tag getNbtTag(CommandContext<S> pContext, String pName) {
|
||||
return pContext.getArgument(pName, Tag.class);
|
||||
}
|
||||
|
||||
public Tag parse(StringReader pReader) throws CommandSyntaxException {
|
||||
return (new TagParser(pReader)).readValue();
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.scores.Objective;
|
||||
import net.minecraft.world.scores.Scoreboard;
|
||||
|
||||
public class ObjectiveArgument implements ArgumentType<String> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "*", "012");
|
||||
private static final DynamicCommandExceptionType ERROR_OBJECTIVE_NOT_FOUND = new DynamicCommandExceptionType((p_101971_) -> {
|
||||
return Component.translatable("arguments.objective.notFound", p_101971_);
|
||||
});
|
||||
private static final DynamicCommandExceptionType ERROR_OBJECTIVE_READ_ONLY = new DynamicCommandExceptionType((p_101969_) -> {
|
||||
return Component.translatable("arguments.objective.readonly", p_101969_);
|
||||
});
|
||||
|
||||
public static ObjectiveArgument objective() {
|
||||
return new ObjectiveArgument();
|
||||
}
|
||||
|
||||
public static Objective getObjective(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
String s = pContext.getArgument(pName, String.class);
|
||||
Scoreboard scoreboard = pContext.getSource().getScoreboard();
|
||||
Objective objective = scoreboard.getObjective(s);
|
||||
if (objective == null) {
|
||||
throw ERROR_OBJECTIVE_NOT_FOUND.create(s);
|
||||
} else {
|
||||
return objective;
|
||||
}
|
||||
}
|
||||
|
||||
public static Objective getWritableObjective(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
Objective objective = getObjective(pContext, pName);
|
||||
if (objective.getCriteria().isReadOnly()) {
|
||||
throw ERROR_OBJECTIVE_READ_ONLY.create(objective.getName());
|
||||
} else {
|
||||
return objective;
|
||||
}
|
||||
}
|
||||
|
||||
public String parse(StringReader p_101959_) throws CommandSyntaxException {
|
||||
return p_101959_.readUnquotedString();
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
S s = pContext.getSource();
|
||||
if (s instanceof CommandSourceStack commandsourcestack) {
|
||||
return SharedSuggestionProvider.suggest(commandsourcestack.getScoreboard().getObjectiveNames(), pBuilder);
|
||||
} else if (s instanceof SharedSuggestionProvider sharedsuggestionprovider) {
|
||||
return sharedsuggestionprovider.customSuggestion(pContext);
|
||||
} else {
|
||||
return Suggestions.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.stats.Stat;
|
||||
import net.minecraft.stats.StatType;
|
||||
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
|
||||
|
||||
public class ObjectiveCriteriaArgument implements ArgumentType<ObjectiveCriteria> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo.bar.baz", "minecraft:foo");
|
||||
public static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType((p_102569_) -> {
|
||||
return Component.translatable("argument.criteria.invalid", p_102569_);
|
||||
});
|
||||
|
||||
private ObjectiveCriteriaArgument() {
|
||||
}
|
||||
|
||||
public static ObjectiveCriteriaArgument criteria() {
|
||||
return new ObjectiveCriteriaArgument();
|
||||
}
|
||||
|
||||
public static ObjectiveCriteria getCriteria(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, ObjectiveCriteria.class);
|
||||
}
|
||||
|
||||
public ObjectiveCriteria parse(StringReader pReader) throws CommandSyntaxException {
|
||||
int i = pReader.getCursor();
|
||||
|
||||
while(pReader.canRead() && pReader.peek() != ' ') {
|
||||
pReader.skip();
|
||||
}
|
||||
|
||||
String s = pReader.getString().substring(i, pReader.getCursor());
|
||||
return ObjectiveCriteria.byName(s).orElseThrow(() -> {
|
||||
pReader.setCursor(i);
|
||||
return ERROR_INVALID_VALUE.create(s);
|
||||
});
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
List<String> list = Lists.newArrayList(ObjectiveCriteria.getCustomCriteriaNames());
|
||||
|
||||
for(StatType<?> stattype : BuiltInRegistries.STAT_TYPE) {
|
||||
for(Object object : stattype.getRegistry()) {
|
||||
String s = this.getName(stattype, object);
|
||||
list.add(s);
|
||||
}
|
||||
}
|
||||
|
||||
return SharedSuggestionProvider.suggest(list, pBuilder);
|
||||
}
|
||||
|
||||
public <T> String getName(StatType<T> pType, Object pValue) {
|
||||
return Stat.buildName(pType, (T)pValue);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.scores.Score;
|
||||
|
||||
public class OperationArgument implements ArgumentType<OperationArgument.Operation> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("=", ">", "<");
|
||||
private static final SimpleCommandExceptionType ERROR_INVALID_OPERATION = new SimpleCommandExceptionType(Component.translatable("arguments.operation.invalid"));
|
||||
private static final SimpleCommandExceptionType ERROR_DIVIDE_BY_ZERO = new SimpleCommandExceptionType(Component.translatable("arguments.operation.div0"));
|
||||
|
||||
public static OperationArgument operation() {
|
||||
return new OperationArgument();
|
||||
}
|
||||
|
||||
public static OperationArgument.Operation getOperation(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, OperationArgument.Operation.class);
|
||||
}
|
||||
|
||||
public OperationArgument.Operation parse(StringReader pReader) throws CommandSyntaxException {
|
||||
if (!pReader.canRead()) {
|
||||
throw ERROR_INVALID_OPERATION.create();
|
||||
} else {
|
||||
int i = pReader.getCursor();
|
||||
|
||||
while(pReader.canRead() && pReader.peek() != ' ') {
|
||||
pReader.skip();
|
||||
}
|
||||
|
||||
return getOperation(pReader.getString().substring(i, pReader.getCursor()));
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return SharedSuggestionProvider.suggest(new String[]{"=", "+=", "-=", "*=", "/=", "%=", "<", ">", "><"}, pBuilder);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes an {@link net.minecraft.commands.arguments.OperationArgument.Operation} instance based on the given name.
|
||||
* This method handles all operations.
|
||||
*/
|
||||
private static OperationArgument.Operation getOperation(String pName) throws CommandSyntaxException {
|
||||
return (pName.equals("><") ? (p_103279_, p_103280_) -> {
|
||||
int i = p_103279_.getScore();
|
||||
p_103279_.setScore(p_103280_.getScore());
|
||||
p_103280_.setScore(i);
|
||||
} : getSimpleOperation(pName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes an {@link net.minecraft.commands.arguments.OperationArgument.Operation} instance based on the given name.
|
||||
* This method actually returns {@link net.minecraft.commands.arguments.OperationArgument.SimpleOperation}, which is
|
||||
* used as a functional interface target with 2 ints. It handles all operations other than swap (><).
|
||||
*/
|
||||
private static OperationArgument.SimpleOperation getSimpleOperation(String pName) throws CommandSyntaxException {
|
||||
switch (pName) {
|
||||
case "=":
|
||||
return (p_103298_, p_103299_) -> {
|
||||
return p_103299_;
|
||||
};
|
||||
case "+=":
|
||||
return (p_103295_, p_103296_) -> {
|
||||
return p_103295_ + p_103296_;
|
||||
};
|
||||
case "-=":
|
||||
return (p_103292_, p_103293_) -> {
|
||||
return p_103292_ - p_103293_;
|
||||
};
|
||||
case "*=":
|
||||
return (p_103289_, p_103290_) -> {
|
||||
return p_103289_ * p_103290_;
|
||||
};
|
||||
case "/=":
|
||||
return (p_264713_, p_264714_) -> {
|
||||
if (p_264714_ == 0) {
|
||||
throw ERROR_DIVIDE_BY_ZERO.create();
|
||||
} else {
|
||||
return Mth.floorDiv(p_264713_, p_264714_);
|
||||
}
|
||||
};
|
||||
case "%=":
|
||||
return (p_103271_, p_103272_) -> {
|
||||
if (p_103272_ == 0) {
|
||||
throw ERROR_DIVIDE_BY_ZERO.create();
|
||||
} else {
|
||||
return Mth.positiveModulo(p_103271_, p_103272_);
|
||||
}
|
||||
};
|
||||
case "<":
|
||||
return Math::min;
|
||||
case ">":
|
||||
return Math::max;
|
||||
default:
|
||||
throw ERROR_INVALID_OPERATION.create();
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Operation {
|
||||
void apply(Score pTargetScore, Score pSourceScore) throws CommandSyntaxException;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface SimpleOperation extends OperationArgument.Operation {
|
||||
int apply(int pTargetScore, int pSourceScore) throws CommandSyntaxException;
|
||||
|
||||
default void apply(Score pTargetScore, Score pSourceScore) throws CommandSyntaxException {
|
||||
pTargetScore.setScore(this.apply(pTargetScore.getScore(), pSourceScore.getScore()));
|
||||
}
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.particles.ParticleOptions;
|
||||
import net.minecraft.core.particles.ParticleType;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
public class ParticleArgument implements ArgumentType<ParticleOptions> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "particle with options");
|
||||
public static final DynamicCommandExceptionType ERROR_UNKNOWN_PARTICLE = new DynamicCommandExceptionType((p_103941_) -> {
|
||||
return Component.translatable("particle.notFound", p_103941_);
|
||||
});
|
||||
private final HolderLookup<ParticleType<?>> particles;
|
||||
|
||||
public ParticleArgument(CommandBuildContext p_249844_) {
|
||||
this.particles = p_249844_.holderLookup(Registries.PARTICLE_TYPE);
|
||||
}
|
||||
|
||||
public static ParticleArgument particle(CommandBuildContext p_251304_) {
|
||||
return new ParticleArgument(p_251304_);
|
||||
}
|
||||
|
||||
public static ParticleOptions getParticle(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, ParticleOptions.class);
|
||||
}
|
||||
|
||||
public ParticleOptions parse(StringReader pReader) throws CommandSyntaxException {
|
||||
return readParticle(pReader, this.particles);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static ParticleOptions readParticle(StringReader pReader, HolderLookup<ParticleType<?>> pParticleTypeLookup) throws CommandSyntaxException {
|
||||
ParticleType<?> particletype = readParticleType(pReader, pParticleTypeLookup);
|
||||
return readParticle(pReader, particletype);
|
||||
}
|
||||
|
||||
private static ParticleType<?> readParticleType(StringReader pReader, HolderLookup<ParticleType<?>> pParticleTypeLookup) throws CommandSyntaxException {
|
||||
ResourceLocation resourcelocation = ResourceLocation.read(pReader);
|
||||
ResourceKey<ParticleType<?>> resourcekey = ResourceKey.create(Registries.PARTICLE_TYPE, resourcelocation);
|
||||
return pParticleTypeLookup.get(resourcekey).orElseThrow(() -> {
|
||||
return ERROR_UNKNOWN_PARTICLE.create(resourcelocation);
|
||||
}).value();
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserializes a particle once its type is known.
|
||||
*/
|
||||
private static <T extends ParticleOptions> T readParticle(StringReader pReader, ParticleType<T> pType) throws CommandSyntaxException {
|
||||
return pType.getDeserializer().fromCommand(pType, pReader);
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return SharedSuggestionProvider.suggestResource(this.particles.listElementIds().map(ResourceKey::location), pBuilder);
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import net.minecraft.advancements.critereon.MinMaxBounds;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
|
||||
public interface RangeArgument<T extends MinMaxBounds<?>> extends ArgumentType<T> {
|
||||
/**
|
||||
* Note: this class is missing several fields and methods due to them not being used in particular FloatRange has no
|
||||
* way of being created.
|
||||
*/
|
||||
static RangeArgument.Ints intRange() {
|
||||
return new RangeArgument.Ints();
|
||||
}
|
||||
|
||||
static RangeArgument.Floats floatRange() {
|
||||
return new RangeArgument.Floats();
|
||||
}
|
||||
|
||||
public static class Floats implements RangeArgument<MinMaxBounds.Doubles> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("0..5.2", "0", "-5.4", "-100.76..", "..100");
|
||||
|
||||
public static MinMaxBounds.Doubles getRange(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, MinMaxBounds.Doubles.class);
|
||||
}
|
||||
|
||||
public MinMaxBounds.Doubles parse(StringReader pReader) throws CommandSyntaxException {
|
||||
return MinMaxBounds.Doubles.fromReader(pReader);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Ints implements RangeArgument<MinMaxBounds.Ints> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("0..5", "0", "-5", "-100..", "..100");
|
||||
|
||||
public static MinMaxBounds.Ints getRange(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, MinMaxBounds.Ints.class);
|
||||
}
|
||||
|
||||
public MinMaxBounds.Ints parse(StringReader pReader) throws CommandSyntaxException {
|
||||
return MinMaxBounds.Ints.fromReader(pReader);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.Dynamic3CommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.effect.MobEffect;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.ai.attributes.Attribute;
|
||||
import net.minecraft.world.item.enchantment.Enchantment;
|
||||
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
|
||||
public class ResourceArgument<T> implements ArgumentType<Holder.Reference<T>> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "012");
|
||||
private static final DynamicCommandExceptionType ERROR_NOT_SUMMONABLE_ENTITY = new DynamicCommandExceptionType((p_248875_) -> {
|
||||
return Component.translatable("entity.not_summonable", p_248875_);
|
||||
});
|
||||
public static final Dynamic2CommandExceptionType ERROR_UNKNOWN_RESOURCE = new Dynamic2CommandExceptionType((p_248525_, p_251552_) -> {
|
||||
return Component.translatable("argument.resource.not_found", p_248525_, p_251552_);
|
||||
});
|
||||
public static final Dynamic3CommandExceptionType ERROR_INVALID_RESOURCE_TYPE = new Dynamic3CommandExceptionType((p_250883_, p_249983_, p_249882_) -> {
|
||||
return Component.translatable("argument.resource.invalid_type", p_250883_, p_249983_, p_249882_);
|
||||
});
|
||||
final ResourceKey<? extends Registry<T>> registryKey;
|
||||
private final HolderLookup<T> registryLookup;
|
||||
|
||||
public ResourceArgument(CommandBuildContext pContext, ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
this.registryKey = pRegistryKey;
|
||||
this.registryLookup = pContext.holderLookup(pRegistryKey);
|
||||
}
|
||||
|
||||
public static <T> ResourceArgument<T> resource(CommandBuildContext pContext, ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
return new ResourceArgument<>(pContext, pRegistryKey);
|
||||
}
|
||||
|
||||
public static <T> Holder.Reference<T> getResource(CommandContext<CommandSourceStack> pContext, String pArgument, ResourceKey<Registry<T>> pRegistryKey) throws CommandSyntaxException {
|
||||
Holder.Reference<T> reference = pContext.getArgument(pArgument, Holder.Reference.class);
|
||||
ResourceKey<?> resourcekey = reference.key();
|
||||
if (resourcekey.isFor(pRegistryKey)) {
|
||||
return reference;
|
||||
} else {
|
||||
throw ERROR_INVALID_RESOURCE_TYPE.create(resourcekey.location(), resourcekey.registry(), pRegistryKey.location());
|
||||
}
|
||||
}
|
||||
|
||||
public static Holder.Reference<Attribute> getAttribute(CommandContext<CommandSourceStack> pContext, String pArgument) throws CommandSyntaxException {
|
||||
return getResource(pContext, pArgument, Registries.ATTRIBUTE);
|
||||
}
|
||||
|
||||
public static Holder.Reference<ConfiguredFeature<?, ?>> getConfiguredFeature(CommandContext<CommandSourceStack> pContext, String pArgument) throws CommandSyntaxException {
|
||||
return getResource(pContext, pArgument, Registries.CONFIGURED_FEATURE);
|
||||
}
|
||||
|
||||
public static Holder.Reference<Structure> getStructure(CommandContext<CommandSourceStack> pContext, String pArgument) throws CommandSyntaxException {
|
||||
return getResource(pContext, pArgument, Registries.STRUCTURE);
|
||||
}
|
||||
|
||||
public static Holder.Reference<EntityType<?>> getEntityType(CommandContext<CommandSourceStack> pContext, String pArgument) throws CommandSyntaxException {
|
||||
return getResource(pContext, pArgument, Registries.ENTITY_TYPE);
|
||||
}
|
||||
|
||||
public static Holder.Reference<EntityType<?>> getSummonableEntityType(CommandContext<CommandSourceStack> pContext, String pArgument) throws CommandSyntaxException {
|
||||
Holder.Reference<EntityType<?>> reference = getResource(pContext, pArgument, Registries.ENTITY_TYPE);
|
||||
if (!reference.value().canSummon()) {
|
||||
throw ERROR_NOT_SUMMONABLE_ENTITY.create(reference.key().location().toString());
|
||||
} else {
|
||||
return reference;
|
||||
}
|
||||
}
|
||||
|
||||
public static Holder.Reference<MobEffect> getMobEffect(CommandContext<CommandSourceStack> pContext, String pArgument) throws CommandSyntaxException {
|
||||
return getResource(pContext, pArgument, Registries.MOB_EFFECT);
|
||||
}
|
||||
|
||||
public static Holder.Reference<Enchantment> getEnchantment(CommandContext<CommandSourceStack> pContext, String pArgument) throws CommandSyntaxException {
|
||||
return getResource(pContext, pArgument, Registries.ENCHANTMENT);
|
||||
}
|
||||
|
||||
public Holder.Reference<T> parse(StringReader pBuilder) throws CommandSyntaxException {
|
||||
ResourceLocation resourcelocation = ResourceLocation.read(pBuilder);
|
||||
ResourceKey<T> resourcekey = ResourceKey.create(this.registryKey, resourcelocation);
|
||||
return this.registryLookup.get(resourcekey).orElseThrow(() -> {
|
||||
return ERROR_UNKNOWN_RESOURCE.create(resourcelocation, this.registryKey.location());
|
||||
});
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_249391_, SuggestionsBuilder p_251197_) {
|
||||
return SharedSuggestionProvider.suggestResource(this.registryLookup.listElementIds().map(ResourceKey::location), p_251197_);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static class Info<T> implements ArgumentTypeInfo<ResourceArgument<T>, ResourceArgument.Info<T>.Template> {
|
||||
public void serializeToNetwork(ResourceArgument.Info<T>.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
pBuffer.writeResourceLocation(pTemplate.registryKey.location());
|
||||
}
|
||||
|
||||
public ResourceArgument.Info<T>.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
ResourceLocation resourcelocation = pBuffer.readResourceLocation();
|
||||
return new ResourceArgument.Info.Template(ResourceKey.createRegistryKey(resourcelocation));
|
||||
}
|
||||
|
||||
public void serializeToJson(ResourceArgument.Info<T>.Template pTemplate, JsonObject pJson) {
|
||||
pJson.addProperty("registry", pTemplate.registryKey.location().toString());
|
||||
}
|
||||
|
||||
public ResourceArgument.Info<T>.Template unpack(ResourceArgument<T> pArgument) {
|
||||
return new ResourceArgument.Info.Template(pArgument.registryKey);
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<ResourceArgument<T>> {
|
||||
final ResourceKey<? extends Registry<T>> registryKey;
|
||||
|
||||
Template(ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
this.registryKey = pRegistryKey;
|
||||
}
|
||||
|
||||
public ResourceArgument<T> instantiate(CommandBuildContext pContext) {
|
||||
return new ResourceArgument<>(pContext, this.registryKey);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<ResourceArgument<T>, ?> type() {
|
||||
return Info.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool;
|
||||
|
||||
public class ResourceKeyArgument<T> implements ArgumentType<ResourceKey<T>> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "012");
|
||||
private static final DynamicCommandExceptionType ERROR_INVALID_FEATURE = new DynamicCommandExceptionType((p_212392_) -> {
|
||||
return Component.translatable("commands.place.feature.invalid", p_212392_);
|
||||
});
|
||||
private static final DynamicCommandExceptionType ERROR_INVALID_STRUCTURE = new DynamicCommandExceptionType((p_212385_) -> {
|
||||
return Component.translatable("commands.place.structure.invalid", p_212385_);
|
||||
});
|
||||
private static final DynamicCommandExceptionType ERROR_INVALID_TEMPLATE_POOL = new DynamicCommandExceptionType((p_233264_) -> {
|
||||
return Component.translatable("commands.place.jigsaw.invalid", p_233264_);
|
||||
});
|
||||
final ResourceKey<? extends Registry<T>> registryKey;
|
||||
|
||||
public ResourceKeyArgument(ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
this.registryKey = pRegistryKey;
|
||||
}
|
||||
|
||||
public static <T> ResourceKeyArgument<T> key(ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
return new ResourceKeyArgument<>(pRegistryKey);
|
||||
}
|
||||
|
||||
private static <T> ResourceKey<T> getRegistryKey(CommandContext<CommandSourceStack> pContext, String pArgument, ResourceKey<Registry<T>> pRegistryKey, DynamicCommandExceptionType pException) throws CommandSyntaxException {
|
||||
ResourceKey<?> resourcekey = pContext.getArgument(pArgument, ResourceKey.class);
|
||||
Optional<ResourceKey<T>> optional = resourcekey.cast(pRegistryKey);
|
||||
return optional.orElseThrow(() -> {
|
||||
return pException.create(resourcekey);
|
||||
});
|
||||
}
|
||||
|
||||
private static <T> Registry<T> getRegistry(CommandContext<CommandSourceStack> pContext, ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
return pContext.getSource().getServer().registryAccess().registryOrThrow(pRegistryKey);
|
||||
}
|
||||
|
||||
private static <T> Holder.Reference<T> resolveKey(CommandContext<CommandSourceStack> pContext, String pArgument, ResourceKey<Registry<T>> pRegistryKey, DynamicCommandExceptionType pException) throws CommandSyntaxException {
|
||||
ResourceKey<T> resourcekey = getRegistryKey(pContext, pArgument, pRegistryKey, pException);
|
||||
return getRegistry(pContext, pRegistryKey).getHolder(resourcekey).orElseThrow(() -> {
|
||||
return pException.create(resourcekey.location());
|
||||
});
|
||||
}
|
||||
|
||||
public static Holder.Reference<ConfiguredFeature<?, ?>> getConfiguredFeature(CommandContext<CommandSourceStack> pContext, String pArgument) throws CommandSyntaxException {
|
||||
return resolveKey(pContext, pArgument, Registries.CONFIGURED_FEATURE, ERROR_INVALID_FEATURE);
|
||||
}
|
||||
|
||||
public static Holder.Reference<Structure> getStructure(CommandContext<CommandSourceStack> pContext, String pArgument) throws CommandSyntaxException {
|
||||
return resolveKey(pContext, pArgument, Registries.STRUCTURE, ERROR_INVALID_STRUCTURE);
|
||||
}
|
||||
|
||||
public static Holder.Reference<StructureTemplatePool> getStructureTemplatePool(CommandContext<CommandSourceStack> pContext, String pArgument) throws CommandSyntaxException {
|
||||
return resolveKey(pContext, pArgument, Registries.TEMPLATE_POOL, ERROR_INVALID_TEMPLATE_POOL);
|
||||
}
|
||||
|
||||
public ResourceKey<T> parse(StringReader pReader) throws CommandSyntaxException {
|
||||
ResourceLocation resourcelocation = ResourceLocation.read(pReader);
|
||||
return ResourceKey.create(this.registryKey, resourcelocation);
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
Object object = pContext.getSource();
|
||||
if (object instanceof SharedSuggestionProvider sharedsuggestionprovider) {
|
||||
return sharedsuggestionprovider.suggestRegistryElements(this.registryKey, SharedSuggestionProvider.ElementSuggestionType.ELEMENTS, pBuilder, pContext);
|
||||
} else {
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static class Info<T> implements ArgumentTypeInfo<ResourceKeyArgument<T>, ResourceKeyArgument.Info<T>.Template> {
|
||||
public void serializeToNetwork(ResourceKeyArgument.Info<T>.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
pBuffer.writeResourceLocation(pTemplate.registryKey.location());
|
||||
}
|
||||
|
||||
public ResourceKeyArgument.Info<T>.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
ResourceLocation resourcelocation = pBuffer.readResourceLocation();
|
||||
return new ResourceKeyArgument.Info.Template(ResourceKey.createRegistryKey(resourcelocation));
|
||||
}
|
||||
|
||||
public void serializeToJson(ResourceKeyArgument.Info<T>.Template pTemplate, JsonObject pJson) {
|
||||
pJson.addProperty("registry", pTemplate.registryKey.location().toString());
|
||||
}
|
||||
|
||||
public ResourceKeyArgument.Info<T>.Template unpack(ResourceKeyArgument<T> pArgument) {
|
||||
return new ResourceKeyArgument.Info.Template(pArgument.registryKey);
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<ResourceKeyArgument<T>> {
|
||||
final ResourceKey<? extends Registry<T>> registryKey;
|
||||
|
||||
Template(ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
this.registryKey = pRegistryKey;
|
||||
}
|
||||
|
||||
public ResourceKeyArgument<T> instantiate(CommandBuildContext pContext) {
|
||||
return new ResourceKeyArgument<>(this.registryKey);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<ResourceKeyArgument<T>, ?> type() {
|
||||
return Info.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import net.minecraft.advancements.Advancement;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.crafting.Recipe;
|
||||
import net.minecraft.world.item.crafting.RecipeManager;
|
||||
import net.minecraft.world.level.storage.loot.LootDataManager;
|
||||
import net.minecraft.world.level.storage.loot.LootDataType;
|
||||
import net.minecraft.world.level.storage.loot.functions.LootItemFunction;
|
||||
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
|
||||
|
||||
public class ResourceLocationArgument implements ArgumentType<ResourceLocation> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "012");
|
||||
private static final DynamicCommandExceptionType ERROR_UNKNOWN_ADVANCEMENT = new DynamicCommandExceptionType((p_107010_) -> {
|
||||
return Component.translatable("advancement.advancementNotFound", p_107010_);
|
||||
});
|
||||
private static final DynamicCommandExceptionType ERROR_UNKNOWN_RECIPE = new DynamicCommandExceptionType((p_107005_) -> {
|
||||
return Component.translatable("recipe.notFound", p_107005_);
|
||||
});
|
||||
private static final DynamicCommandExceptionType ERROR_UNKNOWN_PREDICATE = new DynamicCommandExceptionType((p_106998_) -> {
|
||||
return Component.translatable("predicate.unknown", p_106998_);
|
||||
});
|
||||
private static final DynamicCommandExceptionType ERROR_UNKNOWN_ITEM_MODIFIER = new DynamicCommandExceptionType((p_106991_) -> {
|
||||
return Component.translatable("item_modifier.unknown", p_106991_);
|
||||
});
|
||||
|
||||
public static ResourceLocationArgument id() {
|
||||
return new ResourceLocationArgument();
|
||||
}
|
||||
|
||||
public static Advancement getAdvancement(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
ResourceLocation resourcelocation = getId(pContext, pName);
|
||||
Advancement advancement = pContext.getSource().getAdvancement(resourcelocation);
|
||||
if (advancement == null) {
|
||||
throw ERROR_UNKNOWN_ADVANCEMENT.create(resourcelocation);
|
||||
} else {
|
||||
return advancement;
|
||||
}
|
||||
}
|
||||
|
||||
public static Recipe<?> getRecipe(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
RecipeManager recipemanager = pContext.getSource().getRecipeManager();
|
||||
ResourceLocation resourcelocation = getId(pContext, pName);
|
||||
return recipemanager.byKey(resourcelocation).orElseThrow(() -> {
|
||||
return ERROR_UNKNOWN_RECIPE.create(resourcelocation);
|
||||
});
|
||||
}
|
||||
|
||||
public static LootItemCondition getPredicate(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
ResourceLocation resourcelocation = getId(pContext, pName);
|
||||
LootDataManager lootdatamanager = pContext.getSource().getServer().getLootData();
|
||||
LootItemCondition lootitemcondition = lootdatamanager.getElement(LootDataType.PREDICATE, resourcelocation);
|
||||
if (lootitemcondition == null) {
|
||||
throw ERROR_UNKNOWN_PREDICATE.create(resourcelocation);
|
||||
} else {
|
||||
return lootitemcondition;
|
||||
}
|
||||
}
|
||||
|
||||
public static LootItemFunction getItemModifier(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
ResourceLocation resourcelocation = getId(pContext, pName);
|
||||
LootDataManager lootdatamanager = pContext.getSource().getServer().getLootData();
|
||||
LootItemFunction lootitemfunction = lootdatamanager.getElement(LootDataType.MODIFIER, resourcelocation);
|
||||
if (lootitemfunction == null) {
|
||||
throw ERROR_UNKNOWN_ITEM_MODIFIER.create(resourcelocation);
|
||||
} else {
|
||||
return lootitemfunction;
|
||||
}
|
||||
}
|
||||
|
||||
public static ResourceLocation getId(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, ResourceLocation.class);
|
||||
}
|
||||
|
||||
public ResourceLocation parse(StringReader pReader) throws CommandSyntaxException {
|
||||
return ResourceLocation.read(pReader);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.Dynamic3CommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
|
||||
public class ResourceOrTagArgument<T> implements ArgumentType<ResourceOrTagArgument.Result<T>> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "012", "#skeletons", "#minecraft:skeletons");
|
||||
private static final Dynamic2CommandExceptionType ERROR_UNKNOWN_TAG = new Dynamic2CommandExceptionType((p_250953_, p_249704_) -> {
|
||||
return Component.translatable("argument.resource_tag.not_found", p_250953_, p_249704_);
|
||||
});
|
||||
private static final Dynamic3CommandExceptionType ERROR_INVALID_TAG_TYPE = new Dynamic3CommandExceptionType((p_250188_, p_252173_, p_251453_) -> {
|
||||
return Component.translatable("argument.resource_tag.invalid_type", p_250188_, p_252173_, p_251453_);
|
||||
});
|
||||
private final HolderLookup<T> registryLookup;
|
||||
final ResourceKey<? extends Registry<T>> registryKey;
|
||||
|
||||
public ResourceOrTagArgument(CommandBuildContext pContext, ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
this.registryKey = pRegistryKey;
|
||||
this.registryLookup = pContext.holderLookup(pRegistryKey);
|
||||
}
|
||||
|
||||
public static <T> ResourceOrTagArgument<T> resourceOrTag(CommandBuildContext pContext, ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
return new ResourceOrTagArgument<>(pContext, pRegistryKey);
|
||||
}
|
||||
|
||||
public static <T> ResourceOrTagArgument.Result<T> getResourceOrTag(CommandContext<CommandSourceStack> pContext, String pArgument, ResourceKey<Registry<T>> pRegistryKey) throws CommandSyntaxException {
|
||||
ResourceOrTagArgument.Result<?> result = pContext.getArgument(pArgument, ResourceOrTagArgument.Result.class);
|
||||
Optional<ResourceOrTagArgument.Result<T>> optional = result.cast(pRegistryKey);
|
||||
return optional.orElseThrow(() -> {
|
||||
return result.unwrap().map((p_252340_) -> {
|
||||
ResourceKey<?> resourcekey = p_252340_.key();
|
||||
return ResourceArgument.ERROR_INVALID_RESOURCE_TYPE.create(resourcekey.location(), resourcekey.registry(), pRegistryKey.location());
|
||||
}, (p_250301_) -> {
|
||||
TagKey<?> tagkey = p_250301_.key();
|
||||
return ERROR_INVALID_TAG_TYPE.create(tagkey.location(), tagkey.registry(), pRegistryKey.location());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public ResourceOrTagArgument.Result<T> parse(StringReader pReader) throws CommandSyntaxException {
|
||||
if (pReader.canRead() && pReader.peek() == '#') {
|
||||
int i = pReader.getCursor();
|
||||
|
||||
try {
|
||||
pReader.skip();
|
||||
ResourceLocation resourcelocation1 = ResourceLocation.read(pReader);
|
||||
TagKey<T> tagkey = TagKey.create(this.registryKey, resourcelocation1);
|
||||
HolderSet.Named<T> named = this.registryLookup.get(tagkey).orElseThrow(() -> {
|
||||
return ERROR_UNKNOWN_TAG.create(resourcelocation1, this.registryKey.location());
|
||||
});
|
||||
return new ResourceOrTagArgument.TagResult<>(named);
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
pReader.setCursor(i);
|
||||
throw commandsyntaxexception;
|
||||
}
|
||||
} else {
|
||||
ResourceLocation resourcelocation = ResourceLocation.read(pReader);
|
||||
ResourceKey<T> resourcekey = ResourceKey.create(this.registryKey, resourcelocation);
|
||||
Holder.Reference<T> reference = this.registryLookup.get(resourcekey).orElseThrow(() -> {
|
||||
return ResourceArgument.ERROR_UNKNOWN_RESOURCE.create(resourcelocation, this.registryKey.location());
|
||||
});
|
||||
return new ResourceOrTagArgument.ResourceResult<>(reference);
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_250223_, SuggestionsBuilder p_252354_) {
|
||||
SharedSuggestionProvider.suggestResource(this.registryLookup.listTagIds().map(TagKey::location), p_252354_, "#");
|
||||
return SharedSuggestionProvider.suggestResource(this.registryLookup.listElementIds().map(ResourceKey::location), p_252354_);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static class Info<T> implements ArgumentTypeInfo<ResourceOrTagArgument<T>, ResourceOrTagArgument.Info<T>.Template> {
|
||||
public void serializeToNetwork(ResourceOrTagArgument.Info<T>.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
pBuffer.writeResourceLocation(pTemplate.registryKey.location());
|
||||
}
|
||||
|
||||
public ResourceOrTagArgument.Info<T>.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
ResourceLocation resourcelocation = pBuffer.readResourceLocation();
|
||||
return new ResourceOrTagArgument.Info.Template(ResourceKey.createRegistryKey(resourcelocation));
|
||||
}
|
||||
|
||||
public void serializeToJson(ResourceOrTagArgument.Info<T>.Template pTemplate, JsonObject pJson) {
|
||||
pJson.addProperty("registry", pTemplate.registryKey.location().toString());
|
||||
}
|
||||
|
||||
public ResourceOrTagArgument.Info<T>.Template unpack(ResourceOrTagArgument<T> pArgument) {
|
||||
return new ResourceOrTagArgument.Info.Template(pArgument.registryKey);
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<ResourceOrTagArgument<T>> {
|
||||
final ResourceKey<? extends Registry<T>> registryKey;
|
||||
|
||||
Template(ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
this.registryKey = pRegistryKey;
|
||||
}
|
||||
|
||||
public ResourceOrTagArgument<T> instantiate(CommandBuildContext pContext) {
|
||||
return new ResourceOrTagArgument<>(pContext, this.registryKey);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<ResourceOrTagArgument<T>, ?> type() {
|
||||
return Info.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static record ResourceResult<T>(Holder.Reference<T> value) implements ResourceOrTagArgument.Result<T> {
|
||||
public Either<Holder.Reference<T>, HolderSet.Named<T>> unwrap() {
|
||||
return Either.left(this.value);
|
||||
}
|
||||
|
||||
public <E> Optional<ResourceOrTagArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> pRegistryKey) {
|
||||
return this.value.key().isFor(pRegistryKey) ? Optional.of((ResourceOrTagArgument.Result) this) : Optional.empty();
|
||||
}
|
||||
|
||||
public boolean test(Holder<T> pHolder) {
|
||||
return pHolder.equals(this.value);
|
||||
}
|
||||
|
||||
public String asPrintable() {
|
||||
return this.value.key().location().toString();
|
||||
}
|
||||
}
|
||||
|
||||
public interface Result<T> extends Predicate<Holder<T>> {
|
||||
Either<Holder.Reference<T>, HolderSet.Named<T>> unwrap();
|
||||
|
||||
<E> Optional<ResourceOrTagArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> pRegistryKey);
|
||||
|
||||
String asPrintable();
|
||||
}
|
||||
|
||||
static record TagResult<T>(HolderSet.Named<T> tag) implements ResourceOrTagArgument.Result<T> {
|
||||
public Either<Holder.Reference<T>, HolderSet.Named<T>> unwrap() {
|
||||
return Either.right(this.tag);
|
||||
}
|
||||
|
||||
public <E> Optional<ResourceOrTagArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> pRegistryKey) {
|
||||
return this.tag.key().isFor(pRegistryKey) ? Optional.of((ResourceOrTagArgument.Result) this) : Optional.empty();
|
||||
}
|
||||
|
||||
public boolean test(Holder<T> pHolder) {
|
||||
return this.tag.contains(pHolder);
|
||||
}
|
||||
|
||||
public String asPrintable() {
|
||||
return "#" + this.tag.key().location();
|
||||
}
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
|
||||
public class ResourceOrTagKeyArgument<T> implements ArgumentType<ResourceOrTagKeyArgument.Result<T>> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "012", "#skeletons", "#minecraft:skeletons");
|
||||
final ResourceKey<? extends Registry<T>> registryKey;
|
||||
|
||||
public ResourceOrTagKeyArgument(ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
this.registryKey = pRegistryKey;
|
||||
}
|
||||
|
||||
public static <T> ResourceOrTagKeyArgument<T> resourceOrTagKey(ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
return new ResourceOrTagKeyArgument<>(pRegistryKey);
|
||||
}
|
||||
|
||||
public static <T> ResourceOrTagKeyArgument.Result<T> getResourceOrTagKey(CommandContext<CommandSourceStack> pContext, String pArgument, ResourceKey<Registry<T>> pRegistryKey, DynamicCommandExceptionType p_251387_) throws CommandSyntaxException {
|
||||
ResourceOrTagKeyArgument.Result<?> result = pContext.getArgument(pArgument, ResourceOrTagKeyArgument.Result.class);
|
||||
Optional<ResourceOrTagKeyArgument.Result<T>> optional = result.cast(pRegistryKey);
|
||||
return optional.orElseThrow(() -> {
|
||||
return p_251387_.create(result);
|
||||
});
|
||||
}
|
||||
|
||||
public ResourceOrTagKeyArgument.Result<T> parse(StringReader pReader) throws CommandSyntaxException {
|
||||
if (pReader.canRead() && pReader.peek() == '#') {
|
||||
int i = pReader.getCursor();
|
||||
|
||||
try {
|
||||
pReader.skip();
|
||||
ResourceLocation resourcelocation1 = ResourceLocation.read(pReader);
|
||||
return new ResourceOrTagKeyArgument.TagResult<>(TagKey.create(this.registryKey, resourcelocation1));
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
pReader.setCursor(i);
|
||||
throw commandsyntaxexception;
|
||||
}
|
||||
} else {
|
||||
ResourceLocation resourcelocation = ResourceLocation.read(pReader);
|
||||
return new ResourceOrTagKeyArgument.ResourceResult<>(ResourceKey.create(this.registryKey, resourcelocation));
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
Object object = pContext.getSource();
|
||||
if (object instanceof SharedSuggestionProvider sharedsuggestionprovider) {
|
||||
return sharedsuggestionprovider.suggestRegistryElements(this.registryKey, SharedSuggestionProvider.ElementSuggestionType.ALL, pBuilder, pContext);
|
||||
} else {
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static class Info<T> implements ArgumentTypeInfo<ResourceOrTagKeyArgument<T>, ResourceOrTagKeyArgument.Info<T>.Template> {
|
||||
public void serializeToNetwork(ResourceOrTagKeyArgument.Info<T>.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
pBuffer.writeResourceLocation(pTemplate.registryKey.location());
|
||||
}
|
||||
|
||||
public ResourceOrTagKeyArgument.Info<T>.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
ResourceLocation resourcelocation = pBuffer.readResourceLocation();
|
||||
return new ResourceOrTagKeyArgument.Info.Template(ResourceKey.createRegistryKey(resourcelocation));
|
||||
}
|
||||
|
||||
public void serializeToJson(ResourceOrTagKeyArgument.Info<T>.Template pTemplate, JsonObject pJson) {
|
||||
pJson.addProperty("registry", pTemplate.registryKey.location().toString());
|
||||
}
|
||||
|
||||
public ResourceOrTagKeyArgument.Info<T>.Template unpack(ResourceOrTagKeyArgument<T> pArgument) {
|
||||
return new ResourceOrTagKeyArgument.Info.Template(pArgument.registryKey);
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<ResourceOrTagKeyArgument<T>> {
|
||||
final ResourceKey<? extends Registry<T>> registryKey;
|
||||
|
||||
Template(ResourceKey<? extends Registry<T>> pRegistryKey) {
|
||||
this.registryKey = pRegistryKey;
|
||||
}
|
||||
|
||||
public ResourceOrTagKeyArgument<T> instantiate(CommandBuildContext pContext) {
|
||||
return new ResourceOrTagKeyArgument<>(this.registryKey);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<ResourceOrTagKeyArgument<T>, ?> type() {
|
||||
return Info.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static record ResourceResult<T>(ResourceKey<T> key) implements ResourceOrTagKeyArgument.Result<T> {
|
||||
public Either<ResourceKey<T>, TagKey<T>> unwrap() {
|
||||
return Either.left(this.key);
|
||||
}
|
||||
|
||||
public <E> Optional<ResourceOrTagKeyArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> p_251369_) {
|
||||
return this.key.cast(p_251369_).map(ResourceOrTagKeyArgument.ResourceResult::new);
|
||||
}
|
||||
|
||||
public boolean test(Holder<T> p_250257_) {
|
||||
return p_250257_.is(this.key);
|
||||
}
|
||||
|
||||
public String asPrintable() {
|
||||
return this.key.location().toString();
|
||||
}
|
||||
}
|
||||
|
||||
public interface Result<T> extends Predicate<Holder<T>> {
|
||||
Either<ResourceKey<T>, TagKey<T>> unwrap();
|
||||
|
||||
<E> Optional<ResourceOrTagKeyArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> p_251612_);
|
||||
|
||||
String asPrintable();
|
||||
}
|
||||
|
||||
static record TagResult<T>(TagKey<T> key) implements ResourceOrTagKeyArgument.Result<T> {
|
||||
public Either<ResourceKey<T>, TagKey<T>> unwrap() {
|
||||
return Either.right(this.key);
|
||||
}
|
||||
|
||||
public <E> Optional<ResourceOrTagKeyArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> p_251833_) {
|
||||
return this.key.cast(p_251833_).map(ResourceOrTagKeyArgument.TagResult::new);
|
||||
}
|
||||
|
||||
public boolean test(Holder<T> p_252238_) {
|
||||
return p_252238_.is(this.key);
|
||||
}
|
||||
|
||||
public String asPrintable() {
|
||||
return "#" + this.key.location();
|
||||
}
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.SuggestionProvider;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelector;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
|
||||
public class ScoreHolderArgument implements ArgumentType<ScoreHolderArgument.Result> {
|
||||
public static final SuggestionProvider<CommandSourceStack> SUGGEST_SCORE_HOLDERS = (p_108221_, p_108222_) -> {
|
||||
StringReader stringreader = new StringReader(p_108222_.getInput());
|
||||
stringreader.setCursor(p_108222_.getStart());
|
||||
EntitySelectorParser entityselectorparser = new EntitySelectorParser(stringreader);
|
||||
|
||||
try {
|
||||
entityselectorparser.parse();
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
}
|
||||
|
||||
return entityselectorparser.fillSuggestions(p_108222_, (p_171606_) -> {
|
||||
SharedSuggestionProvider.suggest(p_108221_.getSource().getOnlinePlayerNames(), p_171606_);
|
||||
});
|
||||
};
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("Player", "0123", "*", "@e");
|
||||
private static final SimpleCommandExceptionType ERROR_NO_RESULTS = new SimpleCommandExceptionType(Component.translatable("argument.scoreHolder.empty"));
|
||||
final boolean multiple;
|
||||
|
||||
public ScoreHolderArgument(boolean pMultiple) {
|
||||
this.multiple = pMultiple;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a single score holder, with no objectives list.
|
||||
*/
|
||||
public static String getName(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return getNames(pContext, pName).iterator().next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one or more score holders, with no objectives list.
|
||||
*/
|
||||
public static Collection<String> getNames(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return getNames(pContext, pName, Collections::emptyList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one or more score holders, using the server's complete list of objectives.
|
||||
*/
|
||||
public static Collection<String> getNamesWithDefaultWildcard(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return getNames(pContext, pName, pContext.getSource().getServer().getScoreboard()::getTrackedPlayers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one or more score holders.
|
||||
*/
|
||||
public static Collection<String> getNames(CommandContext<CommandSourceStack> pContext, String pName, Supplier<Collection<String>> pObjectives) throws CommandSyntaxException {
|
||||
Collection<String> collection = pContext.getArgument(pName, ScoreHolderArgument.Result.class).getNames(pContext.getSource(), pObjectives);
|
||||
if (collection.isEmpty()) {
|
||||
throw EntityArgument.NO_ENTITIES_FOUND.create();
|
||||
} else {
|
||||
return collection;
|
||||
}
|
||||
}
|
||||
|
||||
public static ScoreHolderArgument scoreHolder() {
|
||||
return new ScoreHolderArgument(false);
|
||||
}
|
||||
|
||||
public static ScoreHolderArgument scoreHolders() {
|
||||
return new ScoreHolderArgument(true);
|
||||
}
|
||||
|
||||
public ScoreHolderArgument.Result parse(StringReader pReader) throws CommandSyntaxException {
|
||||
if (pReader.canRead() && pReader.peek() == '@') {
|
||||
EntitySelectorParser entityselectorparser = new EntitySelectorParser(pReader);
|
||||
EntitySelector entityselector = entityselectorparser.parse();
|
||||
if (!this.multiple && entityselector.getMaxResults() > 1) {
|
||||
throw EntityArgument.ERROR_NOT_SINGLE_ENTITY.create();
|
||||
} else {
|
||||
return new ScoreHolderArgument.SelectorResult(entityselector);
|
||||
}
|
||||
} else {
|
||||
int i = pReader.getCursor();
|
||||
|
||||
while(pReader.canRead() && pReader.peek() != ' ') {
|
||||
pReader.skip();
|
||||
}
|
||||
|
||||
String s = pReader.getString().substring(i, pReader.getCursor());
|
||||
if (s.equals("*")) {
|
||||
return (p_108231_, p_108232_) -> {
|
||||
Collection<String> collection1 = p_108232_.get();
|
||||
if (collection1.isEmpty()) {
|
||||
throw ERROR_NO_RESULTS.create();
|
||||
} else {
|
||||
return collection1;
|
||||
}
|
||||
};
|
||||
} else {
|
||||
Collection<String> collection = Collections.singleton(s);
|
||||
return (p_108237_, p_108238_) -> {
|
||||
return collection;
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public static class Info implements ArgumentTypeInfo<ScoreHolderArgument, ScoreHolderArgument.Info.Template> {
|
||||
private static final byte FLAG_MULTIPLE = 1;
|
||||
|
||||
public void serializeToNetwork(ScoreHolderArgument.Info.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
int i = 0;
|
||||
if (pTemplate.multiple) {
|
||||
i |= 1;
|
||||
}
|
||||
|
||||
pBuffer.writeByte(i);
|
||||
}
|
||||
|
||||
public ScoreHolderArgument.Info.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
byte b0 = pBuffer.readByte();
|
||||
boolean flag = (b0 & 1) != 0;
|
||||
return new ScoreHolderArgument.Info.Template(flag);
|
||||
}
|
||||
|
||||
public void serializeToJson(ScoreHolderArgument.Info.Template pTemplate, JsonObject pJson) {
|
||||
pJson.addProperty("amount", pTemplate.multiple ? "multiple" : "single");
|
||||
}
|
||||
|
||||
public ScoreHolderArgument.Info.Template unpack(ScoreHolderArgument pArgument) {
|
||||
return new ScoreHolderArgument.Info.Template(pArgument.multiple);
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<ScoreHolderArgument> {
|
||||
final boolean multiple;
|
||||
|
||||
Template(boolean pMultiple) {
|
||||
this.multiple = pMultiple;
|
||||
}
|
||||
|
||||
public ScoreHolderArgument instantiate(CommandBuildContext pContext) {
|
||||
return new ScoreHolderArgument(this.multiple);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<ScoreHolderArgument, ?> type() {
|
||||
return Info.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Result {
|
||||
Collection<String> getNames(CommandSourceStack pSource, Supplier<Collection<String>> pObjectives) throws CommandSyntaxException;
|
||||
}
|
||||
|
||||
public static class SelectorResult implements ScoreHolderArgument.Result {
|
||||
private final EntitySelector selector;
|
||||
|
||||
public SelectorResult(EntitySelector pSelector) {
|
||||
this.selector = pSelector;
|
||||
}
|
||||
|
||||
public Collection<String> getNames(CommandSourceStack pSource, Supplier<Collection<String>> pObjectives) throws CommandSyntaxException {
|
||||
List<? extends Entity> list = this.selector.findEntities(pSource);
|
||||
if (list.isEmpty()) {
|
||||
throw EntityArgument.NO_ENTITIES_FOUND.create();
|
||||
} else {
|
||||
List<String> list1 = Lists.newArrayList();
|
||||
|
||||
for(Entity entity : list) {
|
||||
list1.add(entity.getScoreboardName());
|
||||
}
|
||||
|
||||
return list1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.scores.Scoreboard;
|
||||
|
||||
public class ScoreboardSlotArgument implements ArgumentType<Integer> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("sidebar", "foo.bar");
|
||||
public static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType((p_109203_) -> {
|
||||
return Component.translatable("argument.scoreboardDisplaySlot.invalid", p_109203_);
|
||||
});
|
||||
|
||||
private ScoreboardSlotArgument() {
|
||||
}
|
||||
|
||||
public static ScoreboardSlotArgument displaySlot() {
|
||||
return new ScoreboardSlotArgument();
|
||||
}
|
||||
|
||||
public static int getDisplaySlot(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, Integer.class);
|
||||
}
|
||||
|
||||
public Integer parse(StringReader pReader) throws CommandSyntaxException {
|
||||
String s = pReader.readUnquotedString();
|
||||
int i = Scoreboard.getDisplaySlotByName(s);
|
||||
if (i == -1) {
|
||||
throw ERROR_INVALID_VALUE.create(s);
|
||||
} else {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return SharedSuggestionProvider.suggest(Scoreboard.getDisplaySlotNames(), pBuilder);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
|
||||
public interface SignedArgument<T> extends ArgumentType<T> {
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
|
||||
public class SlotArgument implements ArgumentType<Integer> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("container.5", "12", "weapon");
|
||||
private static final DynamicCommandExceptionType ERROR_UNKNOWN_SLOT = new DynamicCommandExceptionType((p_111283_) -> {
|
||||
return Component.translatable("slot.unknown", p_111283_);
|
||||
});
|
||||
private static final Map<String, Integer> SLOTS = Util.make(Maps.newHashMap(), (p_111285_) -> {
|
||||
for(int i = 0; i < 54; ++i) {
|
||||
p_111285_.put("container." + i, i);
|
||||
}
|
||||
|
||||
for(int j = 0; j < 9; ++j) {
|
||||
p_111285_.put("hotbar." + j, j);
|
||||
}
|
||||
|
||||
for(int k = 0; k < 27; ++k) {
|
||||
p_111285_.put("inventory." + k, 9 + k);
|
||||
}
|
||||
|
||||
for(int l = 0; l < 27; ++l) {
|
||||
p_111285_.put("enderchest." + l, 200 + l);
|
||||
}
|
||||
|
||||
for(int i1 = 0; i1 < 8; ++i1) {
|
||||
p_111285_.put("villager." + i1, 300 + i1);
|
||||
}
|
||||
|
||||
for(int j1 = 0; j1 < 15; ++j1) {
|
||||
p_111285_.put("horse." + j1, 500 + j1);
|
||||
}
|
||||
|
||||
p_111285_.put("weapon", EquipmentSlot.MAINHAND.getIndex(98));
|
||||
p_111285_.put("weapon.mainhand", EquipmentSlot.MAINHAND.getIndex(98));
|
||||
p_111285_.put("weapon.offhand", EquipmentSlot.OFFHAND.getIndex(98));
|
||||
p_111285_.put("armor.head", EquipmentSlot.HEAD.getIndex(100));
|
||||
p_111285_.put("armor.chest", EquipmentSlot.CHEST.getIndex(100));
|
||||
p_111285_.put("armor.legs", EquipmentSlot.LEGS.getIndex(100));
|
||||
p_111285_.put("armor.feet", EquipmentSlot.FEET.getIndex(100));
|
||||
p_111285_.put("horse.saddle", 400);
|
||||
p_111285_.put("horse.armor", 401);
|
||||
p_111285_.put("horse.chest", 499);
|
||||
});
|
||||
|
||||
public static SlotArgument slot() {
|
||||
return new SlotArgument();
|
||||
}
|
||||
|
||||
public static int getSlot(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, Integer.class);
|
||||
}
|
||||
|
||||
public Integer parse(StringReader pReader) throws CommandSyntaxException {
|
||||
String s = pReader.readUnquotedString();
|
||||
if (!SLOTS.containsKey(s)) {
|
||||
throw ERROR_UNKNOWN_SLOT.create(s);
|
||||
} else {
|
||||
return SLOTS.get(s);
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return SharedSuggestionProvider.suggest(SLOTS.keySet(), pBuilder);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.util.StringRepresentable;
|
||||
|
||||
public class StringRepresentableArgument<T extends Enum<T> & StringRepresentable> implements ArgumentType<T> {
|
||||
private static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType((p_234071_) -> {
|
||||
return Component.translatable("argument.enum.invalid", p_234071_);
|
||||
});
|
||||
private final Codec<T> codec;
|
||||
private final Supplier<T[]> values;
|
||||
|
||||
protected StringRepresentableArgument(Codec<T> pCodec, Supplier<T[]> pValues) {
|
||||
this.codec = pCodec;
|
||||
this.values = pValues;
|
||||
}
|
||||
|
||||
public T parse(StringReader pStringReader) throws CommandSyntaxException {
|
||||
String s = pStringReader.readUnquotedString();
|
||||
return this.codec.parse(JsonOps.INSTANCE, new JsonPrimitive(s)).result().orElseThrow(() -> {
|
||||
return ERROR_INVALID_VALUE.create(s);
|
||||
});
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return SharedSuggestionProvider.suggest(Arrays.<Enum>stream((Enum[])this.values.get()).map((p_234069_) -> {
|
||||
return ((StringRepresentable)p_234069_).getSerializedName();
|
||||
}).map(this::convertId).collect(Collectors.toList()), pBuilder);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return Arrays.<Enum>stream((Enum[])this.values.get()).map((p_234065_) -> {
|
||||
return ((StringRepresentable)p_234065_).getSerializedName();
|
||||
}).map(this::convertId).limit(2L).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
protected String convertId(String p_275436_) {
|
||||
return p_275436_;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.scores.PlayerTeam;
|
||||
import net.minecraft.world.scores.Scoreboard;
|
||||
|
||||
public class TeamArgument implements ArgumentType<String> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "123");
|
||||
private static final DynamicCommandExceptionType ERROR_TEAM_NOT_FOUND = new DynamicCommandExceptionType((p_112095_) -> {
|
||||
return Component.translatable("team.notFound", p_112095_);
|
||||
});
|
||||
|
||||
public static TeamArgument team() {
|
||||
return new TeamArgument();
|
||||
}
|
||||
|
||||
public static PlayerTeam getTeam(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
String s = pContext.getArgument(pName, String.class);
|
||||
Scoreboard scoreboard = pContext.getSource().getScoreboard();
|
||||
PlayerTeam playerteam = scoreboard.getPlayerTeam(s);
|
||||
if (playerteam == null) {
|
||||
throw ERROR_TEAM_NOT_FOUND.create(s);
|
||||
} else {
|
||||
return playerteam;
|
||||
}
|
||||
}
|
||||
|
||||
public String parse(StringReader pReader) throws CommandSyntaxException {
|
||||
return pReader.readUnquotedString();
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return pContext.getSource() instanceof SharedSuggestionProvider ? SharedSuggestionProvider.suggest(((SharedSuggestionProvider)pContext.getSource()).getAllTeams(), pBuilder) : Suggestions.empty();
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.world.level.block.Mirror;
|
||||
|
||||
public class TemplateMirrorArgument extends StringRepresentableArgument<Mirror> {
|
||||
private TemplateMirrorArgument() {
|
||||
super(Mirror.CODEC, Mirror::values);
|
||||
}
|
||||
|
||||
public static StringRepresentableArgument<Mirror> templateMirror() {
|
||||
return new TemplateMirrorArgument();
|
||||
}
|
||||
|
||||
public static Mirror getMirror(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, Mirror.class);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.world.level.block.Rotation;
|
||||
|
||||
public class TemplateRotationArgument extends StringRepresentableArgument<Rotation> {
|
||||
private TemplateRotationArgument() {
|
||||
super(Rotation.CODEC, Rotation::values);
|
||||
}
|
||||
|
||||
public static TemplateRotationArgument templateRotation() {
|
||||
return new TemplateRotationArgument();
|
||||
}
|
||||
|
||||
public static Rotation getRotation(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, Rotation.class);
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public class TimeArgument implements ArgumentType<Integer> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("0d", "0s", "0t", "0");
|
||||
private static final SimpleCommandExceptionType ERROR_INVALID_UNIT = new SimpleCommandExceptionType(Component.translatable("argument.time.invalid_unit"));
|
||||
private static final Dynamic2CommandExceptionType ERROR_TICK_COUNT_TOO_LOW = new Dynamic2CommandExceptionType((p_264715_, p_264716_) -> {
|
||||
return Component.translatable("argument.time.tick_count_too_low", p_264716_, p_264715_);
|
||||
});
|
||||
private static final Object2IntMap<String> UNITS = new Object2IntOpenHashMap<>();
|
||||
final int minimum;
|
||||
|
||||
private TimeArgument(int pMinimum) {
|
||||
this.minimum = pMinimum;
|
||||
}
|
||||
|
||||
public static TimeArgument time() {
|
||||
return new TimeArgument(0);
|
||||
}
|
||||
|
||||
public static TimeArgument time(int pMinimum) {
|
||||
return new TimeArgument(pMinimum);
|
||||
}
|
||||
|
||||
public Integer parse(StringReader pReader) throws CommandSyntaxException {
|
||||
float f = pReader.readFloat();
|
||||
String s = pReader.readUnquotedString();
|
||||
int i = UNITS.getOrDefault(s, 0);
|
||||
if (i == 0) {
|
||||
throw ERROR_INVALID_UNIT.create();
|
||||
} else {
|
||||
int j = Math.round(f * (float)i);
|
||||
if (j < this.minimum) {
|
||||
throw ERROR_TICK_COUNT_TOO_LOW.create(j, this.minimum);
|
||||
} else {
|
||||
return j;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
StringReader stringreader = new StringReader(pBuilder.getRemaining());
|
||||
|
||||
try {
|
||||
stringreader.readFloat();
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
|
||||
return SharedSuggestionProvider.suggest(UNITS.keySet(), pBuilder.createOffset(pBuilder.getStart() + stringreader.getCursor()));
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
static {
|
||||
UNITS.put("d", 24000);
|
||||
UNITS.put("s", 20);
|
||||
UNITS.put("t", 1);
|
||||
UNITS.put("", 1);
|
||||
}
|
||||
|
||||
public static class Info implements ArgumentTypeInfo<TimeArgument, TimeArgument.Info.Template> {
|
||||
public void serializeToNetwork(TimeArgument.Info.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
pBuffer.writeInt(pTemplate.min);
|
||||
}
|
||||
|
||||
public TimeArgument.Info.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
int i = pBuffer.readInt();
|
||||
return new TimeArgument.Info.Template(i);
|
||||
}
|
||||
|
||||
public void serializeToJson(TimeArgument.Info.Template pTemplate, JsonObject pJson) {
|
||||
pJson.addProperty("min", pTemplate.min);
|
||||
}
|
||||
|
||||
public TimeArgument.Info.Template unpack(TimeArgument pArgument) {
|
||||
return new TimeArgument.Info.Template(pArgument.minimum);
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<TimeArgument> {
|
||||
final int min;
|
||||
|
||||
Template(int pMin) {
|
||||
this.min = pMin;
|
||||
}
|
||||
|
||||
public TimeArgument instantiate(CommandBuildContext pContext) {
|
||||
return TimeArgument.time(this.min);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<TimeArgument, ?> type() {
|
||||
return Info.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public class UuidArgument implements ArgumentType<UUID> {
|
||||
public static final SimpleCommandExceptionType ERROR_INVALID_UUID = new SimpleCommandExceptionType(Component.translatable("argument.uuid.invalid"));
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("dd12be42-52a9-4a91-a8a1-11c01849e498");
|
||||
private static final Pattern ALLOWED_CHARACTERS = Pattern.compile("^([-A-Fa-f0-9]+)");
|
||||
|
||||
public static UUID getUuid(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, UUID.class);
|
||||
}
|
||||
|
||||
public static UuidArgument uuid() {
|
||||
return new UuidArgument();
|
||||
}
|
||||
|
||||
public UUID parse(StringReader pReader) throws CommandSyntaxException {
|
||||
String s = pReader.getRemaining();
|
||||
Matcher matcher = ALLOWED_CHARACTERS.matcher(s);
|
||||
if (matcher.find()) {
|
||||
String s1 = matcher.group(1);
|
||||
|
||||
try {
|
||||
UUID uuid = UUID.fromString(s1);
|
||||
pReader.setCursor(pReader.getCursor() + s1.length());
|
||||
return uuid;
|
||||
} catch (IllegalArgumentException illegalargumentexception) {
|
||||
}
|
||||
}
|
||||
|
||||
throw ERROR_INVALID_UUID.create();
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package net.minecraft.commands.arguments.blocks;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.NbtUtils;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
|
||||
public class BlockInput implements Predicate<BlockInWorld> {
|
||||
private final BlockState state;
|
||||
private final Set<Property<?>> properties;
|
||||
@Nullable
|
||||
private final CompoundTag tag;
|
||||
|
||||
public BlockInput(BlockState pState, Set<Property<?>> pProperties, @Nullable CompoundTag pTag) {
|
||||
this.state = pState;
|
||||
this.properties = pProperties;
|
||||
this.tag = pTag;
|
||||
}
|
||||
|
||||
public BlockState getState() {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
public Set<Property<?>> getDefinedProperties() {
|
||||
return this.properties;
|
||||
}
|
||||
|
||||
public boolean test(BlockInWorld pBlock) {
|
||||
BlockState blockstate = pBlock.getState();
|
||||
if (!blockstate.is(this.state.getBlock())) {
|
||||
return false;
|
||||
} else {
|
||||
for(Property<?> property : this.properties) {
|
||||
if (blockstate.getValue(property) != this.state.getValue(property)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.tag == null) {
|
||||
return true;
|
||||
} else {
|
||||
BlockEntity blockentity = pBlock.getEntity();
|
||||
return blockentity != null && NbtUtils.compareNbt(this.tag, blockentity.saveWithFullMetadata(), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean test(ServerLevel pLevel, BlockPos pPos) {
|
||||
return this.test(new BlockInWorld(pLevel, pPos, false));
|
||||
}
|
||||
|
||||
public boolean place(ServerLevel pLevel, BlockPos pPos, int pFlags) {
|
||||
BlockState blockstate = Block.updateFromNeighbourShapes(this.state, pLevel, pPos);
|
||||
if (blockstate.isAir()) {
|
||||
blockstate = this.state;
|
||||
}
|
||||
|
||||
if (!pLevel.setBlock(pPos, blockstate, pFlags)) {
|
||||
return false;
|
||||
} else {
|
||||
if (this.tag != null) {
|
||||
BlockEntity blockentity = pLevel.getBlockEntity(pPos);
|
||||
if (blockentity != null) {
|
||||
blockentity.load(this.tag);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package net.minecraft.commands.arguments.blocks;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Predicate;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.NbtUtils;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
|
||||
public class BlockPredicateArgument implements ArgumentType<BlockPredicateArgument.Result> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("stone", "minecraft:stone", "stone[foo=bar]", "#stone", "#stone[foo=bar]{baz=nbt}");
|
||||
private final HolderLookup<Block> blocks;
|
||||
|
||||
public BlockPredicateArgument(CommandBuildContext pContext) {
|
||||
this.blocks = pContext.holderLookup(Registries.BLOCK);
|
||||
}
|
||||
|
||||
public static BlockPredicateArgument blockPredicate(CommandBuildContext pContext) {
|
||||
return new BlockPredicateArgument(pContext);
|
||||
}
|
||||
|
||||
public BlockPredicateArgument.Result parse(StringReader pReader) throws CommandSyntaxException {
|
||||
return parse(this.blocks, pReader);
|
||||
}
|
||||
|
||||
public static BlockPredicateArgument.Result parse(HolderLookup<Block> pLookup, StringReader pReader) throws CommandSyntaxException {
|
||||
return BlockStateParser.parseForTesting(pLookup, pReader, true).map((p_234630_) -> {
|
||||
return new BlockPredicateArgument.BlockPredicate(p_234630_.blockState(), p_234630_.properties().keySet(), p_234630_.nbt());
|
||||
}, (p_234632_) -> {
|
||||
return new BlockPredicateArgument.TagPredicate(p_234632_.tag(), p_234632_.vagueProperties(), p_234632_.nbt());
|
||||
});
|
||||
}
|
||||
|
||||
public static Predicate<BlockInWorld> getBlockPredicate(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return pContext.getArgument(pName, BlockPredicateArgument.Result.class);
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return BlockStateParser.fillSuggestions(this.blocks, pBuilder, true, true);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
static class BlockPredicate implements BlockPredicateArgument.Result {
|
||||
private final BlockState state;
|
||||
private final Set<Property<?>> properties;
|
||||
@Nullable
|
||||
private final CompoundTag nbt;
|
||||
|
||||
public BlockPredicate(BlockState pState, Set<Property<?>> pProperties, @Nullable CompoundTag pNbt) {
|
||||
this.state = pState;
|
||||
this.properties = pProperties;
|
||||
this.nbt = pNbt;
|
||||
}
|
||||
|
||||
public boolean test(BlockInWorld pBlock) {
|
||||
BlockState blockstate = pBlock.getState();
|
||||
if (!blockstate.is(this.state.getBlock())) {
|
||||
return false;
|
||||
} else {
|
||||
for(Property<?> property : this.properties) {
|
||||
if (blockstate.getValue(property) != this.state.getValue(property)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.nbt == null) {
|
||||
return true;
|
||||
} else {
|
||||
BlockEntity blockentity = pBlock.getEntity();
|
||||
return blockentity != null && NbtUtils.compareNbt(this.nbt, blockentity.saveWithFullMetadata(), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean requiresNbt() {
|
||||
return this.nbt != null;
|
||||
}
|
||||
}
|
||||
|
||||
public interface Result extends Predicate<BlockInWorld> {
|
||||
boolean requiresNbt();
|
||||
}
|
||||
|
||||
static class TagPredicate implements BlockPredicateArgument.Result {
|
||||
private final HolderSet<Block> tag;
|
||||
@Nullable
|
||||
private final CompoundTag nbt;
|
||||
private final Map<String, String> vagueProperties;
|
||||
|
||||
TagPredicate(HolderSet<Block> pTag, Map<String, String> pVagueProperties, @Nullable CompoundTag pNbt) {
|
||||
this.tag = pTag;
|
||||
this.vagueProperties = pVagueProperties;
|
||||
this.nbt = pNbt;
|
||||
}
|
||||
|
||||
public boolean test(BlockInWorld pBlock) {
|
||||
BlockState blockstate = pBlock.getState();
|
||||
if (!blockstate.is(this.tag)) {
|
||||
return false;
|
||||
} else {
|
||||
for(Map.Entry<String, String> entry : this.vagueProperties.entrySet()) {
|
||||
Property<?> property = blockstate.getBlock().getStateDefinition().getProperty(entry.getKey());
|
||||
if (property == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Comparable<?> comparable = (Comparable)property.getValue(entry.getValue()).orElse(null);
|
||||
if (comparable == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (blockstate.getValue(property) != comparable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.nbt == null) {
|
||||
return true;
|
||||
} else {
|
||||
BlockEntity blockentity = pBlock.getEntity();
|
||||
return blockentity != null && NbtUtils.compareNbt(this.nbt, blockentity.saveWithFullMetadata(), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean requiresNbt() {
|
||||
return this.nbt != null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package net.minecraft.commands.arguments.blocks;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
|
||||
public class BlockStateArgument implements ArgumentType<BlockInput> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("stone", "minecraft:stone", "stone[foo=bar]", "foo{bar=baz}");
|
||||
private final HolderLookup<Block> blocks;
|
||||
|
||||
public BlockStateArgument(CommandBuildContext p_234649_) {
|
||||
this.blocks = p_234649_.holderLookup(Registries.BLOCK);
|
||||
}
|
||||
|
||||
public static BlockStateArgument block(CommandBuildContext p_234651_) {
|
||||
return new BlockStateArgument(p_234651_);
|
||||
}
|
||||
|
||||
public BlockInput parse(StringReader pReader) throws CommandSyntaxException {
|
||||
BlockStateParser.BlockResult blockstateparser$blockresult = BlockStateParser.parseForBlock(this.blocks, pReader, true);
|
||||
return new BlockInput(blockstateparser$blockresult.blockState(), blockstateparser$blockresult.properties().keySet(), blockstateparser$blockresult.nbt());
|
||||
}
|
||||
|
||||
public static BlockInput getBlock(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, BlockInput.class);
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return BlockStateParser.fillSuggestions(this.blocks, pBuilder, false, true);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+541
@@ -0,0 +1,541 @@
|
||||
package net.minecraft.commands.arguments.blocks;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.Dynamic3CommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.TagParser;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.StateDefinition;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
|
||||
public class BlockStateParser {
|
||||
public static final SimpleCommandExceptionType ERROR_NO_TAGS_ALLOWED = new SimpleCommandExceptionType(Component.translatable("argument.block.tag.disallowed"));
|
||||
public static final DynamicCommandExceptionType ERROR_UNKNOWN_BLOCK = new DynamicCommandExceptionType((p_116790_) -> {
|
||||
return Component.translatable("argument.block.id.invalid", p_116790_);
|
||||
});
|
||||
public static final Dynamic2CommandExceptionType ERROR_UNKNOWN_PROPERTY = new Dynamic2CommandExceptionType((p_116820_, p_116821_) -> {
|
||||
return Component.translatable("argument.block.property.unknown", p_116820_, p_116821_);
|
||||
});
|
||||
public static final Dynamic2CommandExceptionType ERROR_DUPLICATE_PROPERTY = new Dynamic2CommandExceptionType((p_116813_, p_116814_) -> {
|
||||
return Component.translatable("argument.block.property.duplicate", p_116814_, p_116813_);
|
||||
});
|
||||
public static final Dynamic3CommandExceptionType ERROR_INVALID_VALUE = new Dynamic3CommandExceptionType((p_116795_, p_116796_, p_116797_) -> {
|
||||
return Component.translatable("argument.block.property.invalid", p_116795_, p_116797_, p_116796_);
|
||||
});
|
||||
public static final Dynamic2CommandExceptionType ERROR_EXPECTED_VALUE = new Dynamic2CommandExceptionType((p_116792_, p_116793_) -> {
|
||||
return Component.translatable("argument.block.property.novalue", p_116792_, p_116793_);
|
||||
});
|
||||
public static final SimpleCommandExceptionType ERROR_EXPECTED_END_OF_PROPERTIES = new SimpleCommandExceptionType(Component.translatable("argument.block.property.unclosed"));
|
||||
public static final DynamicCommandExceptionType ERROR_UNKNOWN_TAG = new DynamicCommandExceptionType((p_234709_) -> {
|
||||
return Component.translatable("arguments.block.tag.unknown", p_234709_);
|
||||
});
|
||||
private static final char SYNTAX_START_PROPERTIES = '[';
|
||||
private static final char SYNTAX_START_NBT = '{';
|
||||
private static final char SYNTAX_END_PROPERTIES = ']';
|
||||
private static final char SYNTAX_EQUALS = '=';
|
||||
private static final char SYNTAX_PROPERTY_SEPARATOR = ',';
|
||||
private static final char SYNTAX_TAG = '#';
|
||||
private static final Function<SuggestionsBuilder, CompletableFuture<Suggestions>> SUGGEST_NOTHING = SuggestionsBuilder::buildFuture;
|
||||
private final HolderLookup<Block> blocks;
|
||||
private final StringReader reader;
|
||||
private final boolean forTesting;
|
||||
private final boolean allowNbt;
|
||||
private final Map<Property<?>, Comparable<?>> properties = Maps.newHashMap();
|
||||
private final Map<String, String> vagueProperties = Maps.newHashMap();
|
||||
private ResourceLocation id = new ResourceLocation("");
|
||||
@Nullable
|
||||
private StateDefinition<Block, BlockState> definition;
|
||||
@Nullable
|
||||
private BlockState state;
|
||||
@Nullable
|
||||
private CompoundTag nbt;
|
||||
@Nullable
|
||||
private HolderSet<Block> tag;
|
||||
private Function<SuggestionsBuilder, CompletableFuture<Suggestions>> suggestions = SUGGEST_NOTHING;
|
||||
|
||||
private BlockStateParser(HolderLookup<Block> pBlocks, StringReader pReader, boolean pForTesting, boolean pAllowNbt) {
|
||||
this.blocks = pBlocks;
|
||||
this.reader = pReader;
|
||||
this.forTesting = pForTesting;
|
||||
this.allowNbt = pAllowNbt;
|
||||
}
|
||||
|
||||
public static BlockStateParser.BlockResult parseForBlock(HolderLookup<Block> pLookup, String pInput, boolean pAllowNbt) throws CommandSyntaxException {
|
||||
return parseForBlock(pLookup, new StringReader(pInput), pAllowNbt);
|
||||
}
|
||||
|
||||
public static BlockStateParser.BlockResult parseForBlock(HolderLookup<Block> pLookup, StringReader pReader, boolean pAllowNbt) throws CommandSyntaxException {
|
||||
int i = pReader.getCursor();
|
||||
|
||||
try {
|
||||
BlockStateParser blockstateparser = new BlockStateParser(pLookup, pReader, false, pAllowNbt);
|
||||
blockstateparser.parse();
|
||||
return new BlockStateParser.BlockResult(blockstateparser.state, blockstateparser.properties, blockstateparser.nbt);
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
pReader.setCursor(i);
|
||||
throw commandsyntaxexception;
|
||||
}
|
||||
}
|
||||
|
||||
public static Either<BlockStateParser.BlockResult, BlockStateParser.TagResult> parseForTesting(HolderLookup<Block> pLookup, String pInput, boolean pAllowNbt) throws CommandSyntaxException {
|
||||
return parseForTesting(pLookup, new StringReader(pInput), pAllowNbt);
|
||||
}
|
||||
|
||||
public static Either<BlockStateParser.BlockResult, BlockStateParser.TagResult> parseForTesting(HolderLookup<Block> pLookup, StringReader pReader, boolean pAllowNbt) throws CommandSyntaxException {
|
||||
int i = pReader.getCursor();
|
||||
|
||||
try {
|
||||
BlockStateParser blockstateparser = new BlockStateParser(pLookup, pReader, true, pAllowNbt);
|
||||
blockstateparser.parse();
|
||||
return blockstateparser.tag != null ? Either.right(new BlockStateParser.TagResult(blockstateparser.tag, blockstateparser.vagueProperties, blockstateparser.nbt)) : Either.left(new BlockStateParser.BlockResult(blockstateparser.state, blockstateparser.properties, blockstateparser.nbt));
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
pReader.setCursor(i);
|
||||
throw commandsyntaxexception;
|
||||
}
|
||||
}
|
||||
|
||||
public static CompletableFuture<Suggestions> fillSuggestions(HolderLookup<Block> pLookup, SuggestionsBuilder pBuilder, boolean pForTesting, boolean pAllowNbt) {
|
||||
StringReader stringreader = new StringReader(pBuilder.getInput());
|
||||
stringreader.setCursor(pBuilder.getStart());
|
||||
BlockStateParser blockstateparser = new BlockStateParser(pLookup, stringreader, pForTesting, pAllowNbt);
|
||||
|
||||
try {
|
||||
blockstateparser.parse();
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
}
|
||||
|
||||
return blockstateparser.suggestions.apply(pBuilder.createOffset(stringreader.getCursor()));
|
||||
}
|
||||
|
||||
private void parse() throws CommandSyntaxException {
|
||||
if (this.forTesting) {
|
||||
this.suggestions = this::suggestBlockIdOrTag;
|
||||
} else {
|
||||
this.suggestions = this::suggestItem;
|
||||
}
|
||||
|
||||
if (this.reader.canRead() && this.reader.peek() == '#') {
|
||||
this.readTag();
|
||||
this.suggestions = this::suggestOpenVaguePropertiesOrNbt;
|
||||
if (this.reader.canRead() && this.reader.peek() == '[') {
|
||||
this.readVagueProperties();
|
||||
this.suggestions = this::suggestOpenNbt;
|
||||
}
|
||||
} else {
|
||||
this.readBlock();
|
||||
this.suggestions = this::suggestOpenPropertiesOrNbt;
|
||||
if (this.reader.canRead() && this.reader.peek() == '[') {
|
||||
this.readProperties();
|
||||
this.suggestions = this::suggestOpenNbt;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.allowNbt && this.reader.canRead() && this.reader.peek() == '{') {
|
||||
this.suggestions = SUGGEST_NOTHING;
|
||||
this.readNbt();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestPropertyNameOrEnd(SuggestionsBuilder p_234684_) {
|
||||
if (p_234684_.getRemaining().isEmpty()) {
|
||||
p_234684_.suggest(String.valueOf(']'));
|
||||
}
|
||||
|
||||
return this.suggestPropertyName(p_234684_);
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestVaguePropertyNameOrEnd(SuggestionsBuilder p_234715_) {
|
||||
if (p_234715_.getRemaining().isEmpty()) {
|
||||
p_234715_.suggest(String.valueOf(']'));
|
||||
}
|
||||
|
||||
return this.suggestVaguePropertyName(p_234715_);
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestPropertyName(SuggestionsBuilder p_234729_) {
|
||||
String s = p_234729_.getRemaining().toLowerCase(Locale.ROOT);
|
||||
|
||||
for(Property<?> property : this.state.getProperties()) {
|
||||
if (!this.properties.containsKey(property) && property.getName().startsWith(s)) {
|
||||
p_234729_.suggest(property.getName() + "=");
|
||||
}
|
||||
}
|
||||
|
||||
return p_234729_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestVaguePropertyName(SuggestionsBuilder p_234731_) {
|
||||
String s = p_234731_.getRemaining().toLowerCase(Locale.ROOT);
|
||||
if (this.tag != null) {
|
||||
for(Holder<Block> holder : this.tag) {
|
||||
for(Property<?> property : holder.value().getStateDefinition().getProperties()) {
|
||||
if (!this.vagueProperties.containsKey(property.getName()) && property.getName().startsWith(s)) {
|
||||
p_234731_.suggest(property.getName() + "=");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return p_234731_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestOpenNbt(SuggestionsBuilder p_234733_) {
|
||||
if (p_234733_.getRemaining().isEmpty() && this.hasBlockEntity()) {
|
||||
p_234733_.suggest(String.valueOf('{'));
|
||||
}
|
||||
|
||||
return p_234733_.buildFuture();
|
||||
}
|
||||
|
||||
private boolean hasBlockEntity() {
|
||||
if (this.state != null) {
|
||||
return this.state.hasBlockEntity();
|
||||
} else {
|
||||
if (this.tag != null) {
|
||||
for(Holder<Block> holder : this.tag) {
|
||||
if (holder.value().defaultBlockState().hasBlockEntity()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestEquals(SuggestionsBuilder p_234735_) {
|
||||
if (p_234735_.getRemaining().isEmpty()) {
|
||||
p_234735_.suggest(String.valueOf('='));
|
||||
}
|
||||
|
||||
return p_234735_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestNextPropertyOrEnd(SuggestionsBuilder p_234737_) {
|
||||
if (p_234737_.getRemaining().isEmpty()) {
|
||||
p_234737_.suggest(String.valueOf(']'));
|
||||
}
|
||||
|
||||
if (p_234737_.getRemaining().isEmpty() && this.properties.size() < this.state.getProperties().size()) {
|
||||
p_234737_.suggest(String.valueOf(','));
|
||||
}
|
||||
|
||||
return p_234737_.buildFuture();
|
||||
}
|
||||
|
||||
private static <T extends Comparable<T>> SuggestionsBuilder addSuggestions(SuggestionsBuilder pBuilder, Property<T> pProperty) {
|
||||
for(T t : pProperty.getPossibleValues()) {
|
||||
if (t instanceof Integer integer) {
|
||||
pBuilder.suggest(integer);
|
||||
} else {
|
||||
pBuilder.suggest(pProperty.getName(t));
|
||||
}
|
||||
}
|
||||
|
||||
return pBuilder;
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestVaguePropertyValue(SuggestionsBuilder pBuilder, String pPropertyName) {
|
||||
boolean flag = false;
|
||||
if (this.tag != null) {
|
||||
for(Holder<Block> holder : this.tag) {
|
||||
Block block = holder.value();
|
||||
Property<?> property = block.getStateDefinition().getProperty(pPropertyName);
|
||||
if (property != null) {
|
||||
addSuggestions(pBuilder, property);
|
||||
}
|
||||
|
||||
if (!flag) {
|
||||
for(Property<?> property1 : block.getStateDefinition().getProperties()) {
|
||||
if (!this.vagueProperties.containsKey(property1.getName())) {
|
||||
flag = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (flag) {
|
||||
pBuilder.suggest(String.valueOf(','));
|
||||
}
|
||||
|
||||
pBuilder.suggest(String.valueOf(']'));
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestOpenVaguePropertiesOrNbt(SuggestionsBuilder p_234739_) {
|
||||
if (p_234739_.getRemaining().isEmpty() && this.tag != null) {
|
||||
boolean flag = false;
|
||||
boolean flag1 = false;
|
||||
|
||||
for(Holder<Block> holder : this.tag) {
|
||||
Block block = holder.value();
|
||||
flag |= !block.getStateDefinition().getProperties().isEmpty();
|
||||
flag1 |= block.defaultBlockState().hasBlockEntity();
|
||||
if (flag && flag1) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (flag) {
|
||||
p_234739_.suggest(String.valueOf('['));
|
||||
}
|
||||
|
||||
if (flag1) {
|
||||
p_234739_.suggest(String.valueOf('{'));
|
||||
}
|
||||
}
|
||||
|
||||
return p_234739_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestOpenPropertiesOrNbt(SuggestionsBuilder p_234741_) {
|
||||
if (p_234741_.getRemaining().isEmpty()) {
|
||||
if (!this.definition.getProperties().isEmpty()) {
|
||||
p_234741_.suggest(String.valueOf('['));
|
||||
}
|
||||
|
||||
if (this.state.hasBlockEntity()) {
|
||||
p_234741_.suggest(String.valueOf('{'));
|
||||
}
|
||||
}
|
||||
|
||||
return p_234741_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestTag(SuggestionsBuilder p_234743_) {
|
||||
return SharedSuggestionProvider.suggestResource(this.blocks.listTagIds().map(TagKey::location), p_234743_, String.valueOf('#'));
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestItem(SuggestionsBuilder p_234745_) {
|
||||
return SharedSuggestionProvider.suggestResource(this.blocks.listElementIds().map(ResourceKey::location), p_234745_);
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestBlockIdOrTag(SuggestionsBuilder p_234747_) {
|
||||
this.suggestTag(p_234747_);
|
||||
this.suggestItem(p_234747_);
|
||||
return p_234747_.buildFuture();
|
||||
}
|
||||
|
||||
private void readBlock() throws CommandSyntaxException {
|
||||
int i = this.reader.getCursor();
|
||||
this.id = ResourceLocation.read(this.reader);
|
||||
Block block = this.blocks.get(ResourceKey.create(Registries.BLOCK, this.id)).orElseThrow(() -> {
|
||||
this.reader.setCursor(i);
|
||||
return ERROR_UNKNOWN_BLOCK.createWithContext(this.reader, this.id.toString());
|
||||
}).value();
|
||||
this.definition = block.getStateDefinition();
|
||||
this.state = block.defaultBlockState();
|
||||
}
|
||||
|
||||
private void readTag() throws CommandSyntaxException {
|
||||
if (!this.forTesting) {
|
||||
throw ERROR_NO_TAGS_ALLOWED.createWithContext(this.reader);
|
||||
} else {
|
||||
int i = this.reader.getCursor();
|
||||
this.reader.expect('#');
|
||||
this.suggestions = this::suggestTag;
|
||||
ResourceLocation resourcelocation = ResourceLocation.read(this.reader);
|
||||
this.tag = this.blocks.get(TagKey.create(Registries.BLOCK, resourcelocation)).orElseThrow(() -> {
|
||||
this.reader.setCursor(i);
|
||||
return ERROR_UNKNOWN_TAG.createWithContext(this.reader, resourcelocation.toString());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void readProperties() throws CommandSyntaxException {
|
||||
this.reader.skip();
|
||||
this.suggestions = this::suggestPropertyNameOrEnd;
|
||||
this.reader.skipWhitespace();
|
||||
|
||||
while(true) {
|
||||
if (this.reader.canRead() && this.reader.peek() != ']') {
|
||||
this.reader.skipWhitespace();
|
||||
int i = this.reader.getCursor();
|
||||
String s = this.reader.readString();
|
||||
Property<?> property = this.definition.getProperty(s);
|
||||
if (property == null) {
|
||||
this.reader.setCursor(i);
|
||||
throw ERROR_UNKNOWN_PROPERTY.createWithContext(this.reader, this.id.toString(), s);
|
||||
}
|
||||
|
||||
if (this.properties.containsKey(property)) {
|
||||
this.reader.setCursor(i);
|
||||
throw ERROR_DUPLICATE_PROPERTY.createWithContext(this.reader, this.id.toString(), s);
|
||||
}
|
||||
|
||||
this.reader.skipWhitespace();
|
||||
this.suggestions = this::suggestEquals;
|
||||
if (!this.reader.canRead() || this.reader.peek() != '=') {
|
||||
throw ERROR_EXPECTED_VALUE.createWithContext(this.reader, this.id.toString(), s);
|
||||
}
|
||||
|
||||
this.reader.skip();
|
||||
this.reader.skipWhitespace();
|
||||
this.suggestions = (p_234690_) -> {
|
||||
return addSuggestions(p_234690_, property).buildFuture();
|
||||
};
|
||||
int j = this.reader.getCursor();
|
||||
this.setValue(property, this.reader.readString(), j);
|
||||
this.suggestions = this::suggestNextPropertyOrEnd;
|
||||
this.reader.skipWhitespace();
|
||||
if (!this.reader.canRead()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.reader.peek() == ',') {
|
||||
this.reader.skip();
|
||||
this.suggestions = this::suggestPropertyName;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.reader.peek() != ']') {
|
||||
throw ERROR_EXPECTED_END_OF_PROPERTIES.createWithContext(this.reader);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.reader.canRead()) {
|
||||
this.reader.skip();
|
||||
return;
|
||||
}
|
||||
|
||||
throw ERROR_EXPECTED_END_OF_PROPERTIES.createWithContext(this.reader);
|
||||
}
|
||||
}
|
||||
|
||||
private void readVagueProperties() throws CommandSyntaxException {
|
||||
this.reader.skip();
|
||||
this.suggestions = this::suggestVaguePropertyNameOrEnd;
|
||||
int i = -1;
|
||||
this.reader.skipWhitespace();
|
||||
|
||||
while(true) {
|
||||
if (this.reader.canRead() && this.reader.peek() != ']') {
|
||||
this.reader.skipWhitespace();
|
||||
int j = this.reader.getCursor();
|
||||
String s = this.reader.readString();
|
||||
if (this.vagueProperties.containsKey(s)) {
|
||||
this.reader.setCursor(j);
|
||||
throw ERROR_DUPLICATE_PROPERTY.createWithContext(this.reader, this.id.toString(), s);
|
||||
}
|
||||
|
||||
this.reader.skipWhitespace();
|
||||
if (!this.reader.canRead() || this.reader.peek() != '=') {
|
||||
this.reader.setCursor(j);
|
||||
throw ERROR_EXPECTED_VALUE.createWithContext(this.reader, this.id.toString(), s);
|
||||
}
|
||||
|
||||
this.reader.skip();
|
||||
this.reader.skipWhitespace();
|
||||
this.suggestions = (p_234712_) -> {
|
||||
return this.suggestVaguePropertyValue(p_234712_, s);
|
||||
};
|
||||
i = this.reader.getCursor();
|
||||
String s1 = this.reader.readString();
|
||||
this.vagueProperties.put(s, s1);
|
||||
this.reader.skipWhitespace();
|
||||
if (!this.reader.canRead()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
i = -1;
|
||||
if (this.reader.peek() == ',') {
|
||||
this.reader.skip();
|
||||
this.suggestions = this::suggestVaguePropertyName;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.reader.peek() != ']') {
|
||||
throw ERROR_EXPECTED_END_OF_PROPERTIES.createWithContext(this.reader);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.reader.canRead()) {
|
||||
this.reader.skip();
|
||||
return;
|
||||
}
|
||||
|
||||
if (i >= 0) {
|
||||
this.reader.setCursor(i);
|
||||
}
|
||||
|
||||
throw ERROR_EXPECTED_END_OF_PROPERTIES.createWithContext(this.reader);
|
||||
}
|
||||
}
|
||||
|
||||
private void readNbt() throws CommandSyntaxException {
|
||||
this.nbt = (new TagParser(this.reader)).readStruct();
|
||||
}
|
||||
|
||||
private <T extends Comparable<T>> void setValue(Property<T> pProperty, String pValue, int pValuePosition) throws CommandSyntaxException {
|
||||
Optional<T> optional = pProperty.getValue(pValue);
|
||||
if (optional.isPresent()) {
|
||||
this.state = this.state.setValue(pProperty, optional.get());
|
||||
this.properties.put(pProperty, optional.get());
|
||||
} else {
|
||||
this.reader.setCursor(pValuePosition);
|
||||
throw ERROR_INVALID_VALUE.createWithContext(this.reader, this.id.toString(), pProperty.getName(), pValue);
|
||||
}
|
||||
}
|
||||
|
||||
public static String serialize(BlockState pState) {
|
||||
StringBuilder stringbuilder = new StringBuilder(pState.getBlockHolder().unwrapKey().map((p_234682_) -> {
|
||||
return p_234682_.location().toString();
|
||||
}).orElse("air"));
|
||||
if (!pState.getProperties().isEmpty()) {
|
||||
stringbuilder.append('[');
|
||||
boolean flag = false;
|
||||
|
||||
for(Map.Entry<Property<?>, Comparable<?>> entry : pState.getValues().entrySet()) {
|
||||
if (flag) {
|
||||
stringbuilder.append(',');
|
||||
}
|
||||
|
||||
appendProperty(stringbuilder, entry.getKey(), entry.getValue());
|
||||
flag = true;
|
||||
}
|
||||
|
||||
stringbuilder.append(']');
|
||||
}
|
||||
|
||||
return stringbuilder.toString();
|
||||
}
|
||||
|
||||
private static <T extends Comparable<T>> void appendProperty(StringBuilder pBuilder, Property<T> pProperty, Comparable<?> pValue) {
|
||||
pBuilder.append(pProperty.getName());
|
||||
pBuilder.append('=');
|
||||
pBuilder.append(pProperty.getName((T)pValue));
|
||||
}
|
||||
|
||||
public static record BlockResult(BlockState blockState, Map<Property<?>, Comparable<?>> properties, @Nullable CompoundTag nbt) {
|
||||
}
|
||||
|
||||
public static record TagResult(HolderSet<Block> tag, Map<String, String> vagueProperties, @Nullable CompoundTag nbt) {
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
@FieldsAreNonnullByDefault
|
||||
package net.minecraft.commands.arguments.blocks;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.FieldsAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package net.minecraft.commands.arguments.coordinates;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.level.Level;
|
||||
|
||||
public class BlockPosArgument implements ArgumentType<Coordinates> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("0 0 0", "~ ~ ~", "^ ^ ^", "^1 ^ ^-5", "~0.5 ~1 ~-5");
|
||||
public static final SimpleCommandExceptionType ERROR_NOT_LOADED = new SimpleCommandExceptionType(Component.translatable("argument.pos.unloaded"));
|
||||
public static final SimpleCommandExceptionType ERROR_OUT_OF_WORLD = new SimpleCommandExceptionType(Component.translatable("argument.pos.outofworld"));
|
||||
public static final SimpleCommandExceptionType ERROR_OUT_OF_BOUNDS = new SimpleCommandExceptionType(Component.translatable("argument.pos.outofbounds"));
|
||||
|
||||
public static BlockPosArgument blockPos() {
|
||||
return new BlockPosArgument();
|
||||
}
|
||||
|
||||
public static BlockPos getLoadedBlockPos(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
ServerLevel serverlevel = pContext.getSource().getLevel();
|
||||
return getLoadedBlockPos(pContext, serverlevel, pName);
|
||||
}
|
||||
|
||||
public static BlockPos getLoadedBlockPos(CommandContext<CommandSourceStack> pContext, ServerLevel pLevel, String pName) throws CommandSyntaxException {
|
||||
BlockPos blockpos = getBlockPos(pContext, pName);
|
||||
if (!pContext.getSource().getUnsidedLevel().hasChunkAt(blockpos)) {
|
||||
throw ERROR_NOT_LOADED.create();
|
||||
} else if (!pContext.getSource().getUnsidedLevel().isInWorldBounds(blockpos)) {
|
||||
throw ERROR_OUT_OF_WORLD.create();
|
||||
} else {
|
||||
return blockpos;
|
||||
}
|
||||
}
|
||||
|
||||
public static BlockPos getBlockPos(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, Coordinates.class).getBlockPos(pContext.getSource());
|
||||
}
|
||||
|
||||
public static BlockPos getSpawnablePos(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
BlockPos blockpos = getBlockPos(pContext, pName);
|
||||
if (!Level.isInSpawnableBounds(blockpos)) {
|
||||
throw ERROR_OUT_OF_BOUNDS.create();
|
||||
} else {
|
||||
return blockpos;
|
||||
}
|
||||
}
|
||||
|
||||
public Coordinates parse(StringReader p_118241_) throws CommandSyntaxException {
|
||||
return (Coordinates)(p_118241_.canRead() && p_118241_.peek() == '^' ? LocalCoordinates.parse(p_118241_) : WorldCoordinates.parseInt(p_118241_));
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
if (!(pContext.getSource() instanceof SharedSuggestionProvider)) {
|
||||
return Suggestions.empty();
|
||||
} else {
|
||||
String s = pBuilder.getRemaining();
|
||||
Collection<SharedSuggestionProvider.TextCoordinates> collection;
|
||||
if (!s.isEmpty() && s.charAt(0) == '^') {
|
||||
collection = Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_LOCAL);
|
||||
} else {
|
||||
collection = ((SharedSuggestionProvider)pContext.getSource()).getRelevantCoordinates();
|
||||
}
|
||||
|
||||
return SharedSuggestionProvider.suggestCoordinates(s, collection, pBuilder, Commands.createValidator(this::parse));
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package net.minecraft.commands.arguments.coordinates;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ColumnPos;
|
||||
|
||||
public class ColumnPosArgument implements ArgumentType<Coordinates> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("0 0", "~ ~", "~1 ~-2", "^ ^", "^-1 ^0");
|
||||
public static final SimpleCommandExceptionType ERROR_NOT_COMPLETE = new SimpleCommandExceptionType(Component.translatable("argument.pos2d.incomplete"));
|
||||
|
||||
public static ColumnPosArgument columnPos() {
|
||||
return new ColumnPosArgument();
|
||||
}
|
||||
|
||||
public static ColumnPos getColumnPos(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
BlockPos blockpos = pContext.getArgument(pName, Coordinates.class).getBlockPos(pContext.getSource());
|
||||
return new ColumnPos(blockpos.getX(), blockpos.getZ());
|
||||
}
|
||||
|
||||
public Coordinates parse(StringReader p_118991_) throws CommandSyntaxException {
|
||||
int i = p_118991_.getCursor();
|
||||
if (!p_118991_.canRead()) {
|
||||
throw ERROR_NOT_COMPLETE.createWithContext(p_118991_);
|
||||
} else {
|
||||
WorldCoordinate worldcoordinate = WorldCoordinate.parseInt(p_118991_);
|
||||
if (p_118991_.canRead() && p_118991_.peek() == ' ') {
|
||||
p_118991_.skip();
|
||||
WorldCoordinate worldcoordinate1 = WorldCoordinate.parseInt(p_118991_);
|
||||
return new WorldCoordinates(worldcoordinate, new WorldCoordinate(true, 0.0D), worldcoordinate1);
|
||||
} else {
|
||||
p_118991_.setCursor(i);
|
||||
throw ERROR_NOT_COMPLETE.createWithContext(p_118991_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
if (!(pContext.getSource() instanceof SharedSuggestionProvider)) {
|
||||
return Suggestions.empty();
|
||||
} else {
|
||||
String s = pBuilder.getRemaining();
|
||||
Collection<SharedSuggestionProvider.TextCoordinates> collection;
|
||||
if (!s.isEmpty() && s.charAt(0) == '^') {
|
||||
collection = Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_LOCAL);
|
||||
} else {
|
||||
collection = ((SharedSuggestionProvider)pContext.getSource()).getRelevantCoordinates();
|
||||
}
|
||||
|
||||
return SharedSuggestionProvider.suggest2DCoordinates(s, collection, pBuilder, Commands.createValidator(this::parse));
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package net.minecraft.commands.arguments.coordinates;
|
||||
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.phys.Vec2;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public interface Coordinates {
|
||||
Vec3 getPosition(CommandSourceStack pSource);
|
||||
|
||||
Vec2 getRotation(CommandSourceStack pSource);
|
||||
|
||||
default BlockPos getBlockPos(CommandSourceStack pSource) {
|
||||
return BlockPos.containing(this.getPosition(pSource));
|
||||
}
|
||||
|
||||
boolean isXRelative();
|
||||
|
||||
boolean isYRelative();
|
||||
|
||||
boolean isZRelative();
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package net.minecraft.commands.arguments.coordinates;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import java.util.Objects;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.phys.Vec2;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class LocalCoordinates implements Coordinates {
|
||||
public static final char PREFIX_LOCAL_COORDINATE = '^';
|
||||
private final double left;
|
||||
private final double up;
|
||||
private final double forwards;
|
||||
|
||||
public LocalCoordinates(double pLeft, double pUp, double pForwards) {
|
||||
this.left = pLeft;
|
||||
this.up = pUp;
|
||||
this.forwards = pForwards;
|
||||
}
|
||||
|
||||
public Vec3 getPosition(CommandSourceStack pSource) {
|
||||
Vec2 vec2 = pSource.getRotation();
|
||||
Vec3 vec3 = pSource.getAnchor().apply(pSource);
|
||||
float f = Mth.cos((vec2.y + 90.0F) * ((float)Math.PI / 180F));
|
||||
float f1 = Mth.sin((vec2.y + 90.0F) * ((float)Math.PI / 180F));
|
||||
float f2 = Mth.cos(-vec2.x * ((float)Math.PI / 180F));
|
||||
float f3 = Mth.sin(-vec2.x * ((float)Math.PI / 180F));
|
||||
float f4 = Mth.cos((-vec2.x + 90.0F) * ((float)Math.PI / 180F));
|
||||
float f5 = Mth.sin((-vec2.x + 90.0F) * ((float)Math.PI / 180F));
|
||||
Vec3 vec31 = new Vec3((double)(f * f2), (double)f3, (double)(f1 * f2));
|
||||
Vec3 vec32 = new Vec3((double)(f * f4), (double)f5, (double)(f1 * f4));
|
||||
Vec3 vec33 = vec31.cross(vec32).scale(-1.0D);
|
||||
double d0 = vec31.x * this.forwards + vec32.x * this.up + vec33.x * this.left;
|
||||
double d1 = vec31.y * this.forwards + vec32.y * this.up + vec33.y * this.left;
|
||||
double d2 = vec31.z * this.forwards + vec32.z * this.up + vec33.z * this.left;
|
||||
return new Vec3(vec3.x + d0, vec3.y + d1, vec3.z + d2);
|
||||
}
|
||||
|
||||
public Vec2 getRotation(CommandSourceStack pSource) {
|
||||
return Vec2.ZERO;
|
||||
}
|
||||
|
||||
public boolean isXRelative() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isYRelative() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isZRelative() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static LocalCoordinates parse(StringReader pReader) throws CommandSyntaxException {
|
||||
int i = pReader.getCursor();
|
||||
double d0 = readDouble(pReader, i);
|
||||
if (pReader.canRead() && pReader.peek() == ' ') {
|
||||
pReader.skip();
|
||||
double d1 = readDouble(pReader, i);
|
||||
if (pReader.canRead() && pReader.peek() == ' ') {
|
||||
pReader.skip();
|
||||
double d2 = readDouble(pReader, i);
|
||||
return new LocalCoordinates(d0, d1, d2);
|
||||
} else {
|
||||
pReader.setCursor(i);
|
||||
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(pReader);
|
||||
}
|
||||
} else {
|
||||
pReader.setCursor(i);
|
||||
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(pReader);
|
||||
}
|
||||
}
|
||||
|
||||
private static double readDouble(StringReader pReader, int pStart) throws CommandSyntaxException {
|
||||
if (!pReader.canRead()) {
|
||||
throw WorldCoordinate.ERROR_EXPECTED_DOUBLE.createWithContext(pReader);
|
||||
} else if (pReader.peek() != '^') {
|
||||
pReader.setCursor(pStart);
|
||||
throw Vec3Argument.ERROR_MIXED_TYPE.createWithContext(pReader);
|
||||
} else {
|
||||
pReader.skip();
|
||||
return pReader.canRead() && pReader.peek() != ' ' ? pReader.readDouble() : 0.0D;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean equals(Object pOther) {
|
||||
if (this == pOther) {
|
||||
return true;
|
||||
} else if (!(pOther instanceof LocalCoordinates)) {
|
||||
return false;
|
||||
} else {
|
||||
LocalCoordinates localcoordinates = (LocalCoordinates)pOther;
|
||||
return this.left == localcoordinates.left && this.up == localcoordinates.up && this.forwards == localcoordinates.forwards;
|
||||
}
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return Objects.hash(this.left, this.up, this.forwards);
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package net.minecraft.commands.arguments.coordinates;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public class RotationArgument implements ArgumentType<Coordinates> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("0 0", "~ ~", "~-5 ~5");
|
||||
public static final SimpleCommandExceptionType ERROR_NOT_COMPLETE = new SimpleCommandExceptionType(Component.translatable("argument.rotation.incomplete"));
|
||||
|
||||
public static RotationArgument rotation() {
|
||||
return new RotationArgument();
|
||||
}
|
||||
|
||||
public static Coordinates getRotation(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, Coordinates.class);
|
||||
}
|
||||
|
||||
public Coordinates parse(StringReader pReader) throws CommandSyntaxException {
|
||||
int i = pReader.getCursor();
|
||||
if (!pReader.canRead()) {
|
||||
throw ERROR_NOT_COMPLETE.createWithContext(pReader);
|
||||
} else {
|
||||
WorldCoordinate worldcoordinate = WorldCoordinate.parseDouble(pReader, false);
|
||||
if (pReader.canRead() && pReader.peek() == ' ') {
|
||||
pReader.skip();
|
||||
WorldCoordinate worldcoordinate1 = WorldCoordinate.parseDouble(pReader, false);
|
||||
return new WorldCoordinates(worldcoordinate1, worldcoordinate, new WorldCoordinate(true, 0.0D));
|
||||
} else {
|
||||
pReader.setCursor(i);
|
||||
throw ERROR_NOT_COMPLETE.createWithContext(pReader);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package net.minecraft.commands.arguments.coordinates;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.EnumSet;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public class SwizzleArgument implements ArgumentType<EnumSet<Direction.Axis>> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("xyz", "x");
|
||||
private static final SimpleCommandExceptionType ERROR_INVALID = new SimpleCommandExceptionType(Component.translatable("arguments.swizzle.invalid"));
|
||||
|
||||
public static SwizzleArgument swizzle() {
|
||||
return new SwizzleArgument();
|
||||
}
|
||||
|
||||
public static EnumSet<Direction.Axis> getSwizzle(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, EnumSet.class);
|
||||
}
|
||||
|
||||
public EnumSet<Direction.Axis> parse(StringReader pReader) throws CommandSyntaxException {
|
||||
EnumSet<Direction.Axis> enumset = EnumSet.noneOf(Direction.Axis.class);
|
||||
|
||||
while(pReader.canRead() && pReader.peek() != ' ') {
|
||||
char c0 = pReader.read();
|
||||
Direction.Axis direction$axis;
|
||||
switch (c0) {
|
||||
case 'x':
|
||||
direction$axis = Direction.Axis.X;
|
||||
break;
|
||||
case 'y':
|
||||
direction$axis = Direction.Axis.Y;
|
||||
break;
|
||||
case 'z':
|
||||
direction$axis = Direction.Axis.Z;
|
||||
break;
|
||||
default:
|
||||
throw ERROR_INVALID.create();
|
||||
}
|
||||
|
||||
if (enumset.contains(direction$axis)) {
|
||||
throw ERROR_INVALID.create();
|
||||
}
|
||||
|
||||
enumset.add(direction$axis);
|
||||
}
|
||||
|
||||
return enumset;
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package net.minecraft.commands.arguments.coordinates;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.phys.Vec2;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class Vec2Argument implements ArgumentType<Coordinates> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("0 0", "~ ~", "0.1 -0.5", "~1 ~-2");
|
||||
public static final SimpleCommandExceptionType ERROR_NOT_COMPLETE = new SimpleCommandExceptionType(Component.translatable("argument.pos2d.incomplete"));
|
||||
private final boolean centerCorrect;
|
||||
|
||||
public Vec2Argument(boolean pCenterCorrect) {
|
||||
this.centerCorrect = pCenterCorrect;
|
||||
}
|
||||
|
||||
public static Vec2Argument vec2() {
|
||||
return new Vec2Argument(true);
|
||||
}
|
||||
|
||||
public static Vec2Argument vec2(boolean pCenterCorrect) {
|
||||
return new Vec2Argument(pCenterCorrect);
|
||||
}
|
||||
|
||||
public static Vec2 getVec2(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
Vec3 vec3 = pContext.getArgument(pName, Coordinates.class).getPosition(pContext.getSource());
|
||||
return new Vec2((float)vec3.x, (float)vec3.z);
|
||||
}
|
||||
|
||||
public Coordinates parse(StringReader p_120824_) throws CommandSyntaxException {
|
||||
int i = p_120824_.getCursor();
|
||||
if (!p_120824_.canRead()) {
|
||||
throw ERROR_NOT_COMPLETE.createWithContext(p_120824_);
|
||||
} else {
|
||||
WorldCoordinate worldcoordinate = WorldCoordinate.parseDouble(p_120824_, this.centerCorrect);
|
||||
if (p_120824_.canRead() && p_120824_.peek() == ' ') {
|
||||
p_120824_.skip();
|
||||
WorldCoordinate worldcoordinate1 = WorldCoordinate.parseDouble(p_120824_, this.centerCorrect);
|
||||
return new WorldCoordinates(worldcoordinate, new WorldCoordinate(true, 0.0D), worldcoordinate1);
|
||||
} else {
|
||||
p_120824_.setCursor(i);
|
||||
throw ERROR_NOT_COMPLETE.createWithContext(p_120824_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
if (!(pContext.getSource() instanceof SharedSuggestionProvider)) {
|
||||
return Suggestions.empty();
|
||||
} else {
|
||||
String s = pBuilder.getRemaining();
|
||||
Collection<SharedSuggestionProvider.TextCoordinates> collection;
|
||||
if (!s.isEmpty() && s.charAt(0) == '^') {
|
||||
collection = Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_LOCAL);
|
||||
} else {
|
||||
collection = ((SharedSuggestionProvider)pContext.getSource()).getAbsoluteCoordinates();
|
||||
}
|
||||
|
||||
return SharedSuggestionProvider.suggest2DCoordinates(s, collection, pBuilder, Commands.createValidator(this::parse));
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package net.minecraft.commands.arguments.coordinates;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class Vec3Argument implements ArgumentType<Coordinates> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("0 0 0", "~ ~ ~", "^ ^ ^", "^1 ^ ^-5", "0.1 -0.5 .9", "~0.5 ~1 ~-5");
|
||||
public static final SimpleCommandExceptionType ERROR_NOT_COMPLETE = new SimpleCommandExceptionType(Component.translatable("argument.pos3d.incomplete"));
|
||||
public static final SimpleCommandExceptionType ERROR_MIXED_TYPE = new SimpleCommandExceptionType(Component.translatable("argument.pos.mixed"));
|
||||
private final boolean centerCorrect;
|
||||
|
||||
public Vec3Argument(boolean pCenterCorrect) {
|
||||
this.centerCorrect = pCenterCorrect;
|
||||
}
|
||||
|
||||
public static Vec3Argument vec3() {
|
||||
return new Vec3Argument(true);
|
||||
}
|
||||
|
||||
public static Vec3Argument vec3(boolean pCenterCorrect) {
|
||||
return new Vec3Argument(pCenterCorrect);
|
||||
}
|
||||
|
||||
public static Vec3 getVec3(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, Coordinates.class).getPosition(pContext.getSource());
|
||||
}
|
||||
|
||||
public static Coordinates getCoordinates(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, Coordinates.class);
|
||||
}
|
||||
|
||||
public Coordinates parse(StringReader p_120843_) throws CommandSyntaxException {
|
||||
return (Coordinates)(p_120843_.canRead() && p_120843_.peek() == '^' ? LocalCoordinates.parse(p_120843_) : WorldCoordinates.parseDouble(p_120843_, this.centerCorrect));
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
if (!(pContext.getSource() instanceof SharedSuggestionProvider)) {
|
||||
return Suggestions.empty();
|
||||
} else {
|
||||
String s = pBuilder.getRemaining();
|
||||
Collection<SharedSuggestionProvider.TextCoordinates> collection;
|
||||
if (!s.isEmpty() && s.charAt(0) == '^') {
|
||||
collection = Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_LOCAL);
|
||||
} else {
|
||||
collection = ((SharedSuggestionProvider)pContext.getSource()).getAbsoluteCoordinates();
|
||||
}
|
||||
|
||||
return SharedSuggestionProvider.suggestCoordinates(s, collection, pBuilder, Commands.createValidator(this::parse));
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package net.minecraft.commands.arguments.coordinates;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public class WorldCoordinate {
|
||||
private static final char PREFIX_RELATIVE = '~';
|
||||
public static final SimpleCommandExceptionType ERROR_EXPECTED_DOUBLE = new SimpleCommandExceptionType(Component.translatable("argument.pos.missing.double"));
|
||||
public static final SimpleCommandExceptionType ERROR_EXPECTED_INT = new SimpleCommandExceptionType(Component.translatable("argument.pos.missing.int"));
|
||||
private final boolean relative;
|
||||
private final double value;
|
||||
|
||||
public WorldCoordinate(boolean pRelative, double pValue) {
|
||||
this.relative = pRelative;
|
||||
this.value = pValue;
|
||||
}
|
||||
|
||||
public double get(double pCoord) {
|
||||
return this.relative ? this.value + pCoord : this.value;
|
||||
}
|
||||
|
||||
public static WorldCoordinate parseDouble(StringReader pReader, boolean pCenterCorrect) throws CommandSyntaxException {
|
||||
if (pReader.canRead() && pReader.peek() == '^') {
|
||||
throw Vec3Argument.ERROR_MIXED_TYPE.createWithContext(pReader);
|
||||
} else if (!pReader.canRead()) {
|
||||
throw ERROR_EXPECTED_DOUBLE.createWithContext(pReader);
|
||||
} else {
|
||||
boolean flag = isRelative(pReader);
|
||||
int i = pReader.getCursor();
|
||||
double d0 = pReader.canRead() && pReader.peek() != ' ' ? pReader.readDouble() : 0.0D;
|
||||
String s = pReader.getString().substring(i, pReader.getCursor());
|
||||
if (flag && s.isEmpty()) {
|
||||
return new WorldCoordinate(true, 0.0D);
|
||||
} else {
|
||||
if (!s.contains(".") && !flag && pCenterCorrect) {
|
||||
d0 += 0.5D;
|
||||
}
|
||||
|
||||
return new WorldCoordinate(flag, d0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static WorldCoordinate parseInt(StringReader pReader) throws CommandSyntaxException {
|
||||
if (pReader.canRead() && pReader.peek() == '^') {
|
||||
throw Vec3Argument.ERROR_MIXED_TYPE.createWithContext(pReader);
|
||||
} else if (!pReader.canRead()) {
|
||||
throw ERROR_EXPECTED_INT.createWithContext(pReader);
|
||||
} else {
|
||||
boolean flag = isRelative(pReader);
|
||||
double d0;
|
||||
if (pReader.canRead() && pReader.peek() != ' ') {
|
||||
d0 = flag ? pReader.readDouble() : (double)pReader.readInt();
|
||||
} else {
|
||||
d0 = 0.0D;
|
||||
}
|
||||
|
||||
return new WorldCoordinate(flag, d0);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isRelative(StringReader pReader) {
|
||||
boolean flag;
|
||||
if (pReader.peek() == '~') {
|
||||
flag = true;
|
||||
pReader.skip();
|
||||
} else {
|
||||
flag = false;
|
||||
}
|
||||
|
||||
return flag;
|
||||
}
|
||||
|
||||
public boolean equals(Object pOther) {
|
||||
if (this == pOther) {
|
||||
return true;
|
||||
} else if (!(pOther instanceof WorldCoordinate)) {
|
||||
return false;
|
||||
} else {
|
||||
WorldCoordinate worldcoordinate = (WorldCoordinate)pOther;
|
||||
if (this.relative != worldcoordinate.relative) {
|
||||
return false;
|
||||
} else {
|
||||
return Double.compare(worldcoordinate.value, this.value) == 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
int i = this.relative ? 1 : 0;
|
||||
long j = Double.doubleToLongBits(this.value);
|
||||
return 31 * i + (int)(j ^ j >>> 32);
|
||||
}
|
||||
|
||||
public boolean isRelative() {
|
||||
return this.relative;
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package net.minecraft.commands.arguments.coordinates;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.world.phys.Vec2;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class WorldCoordinates implements Coordinates {
|
||||
private final WorldCoordinate x;
|
||||
private final WorldCoordinate y;
|
||||
private final WorldCoordinate z;
|
||||
|
||||
public WorldCoordinates(WorldCoordinate pX, WorldCoordinate pY, WorldCoordinate pZ) {
|
||||
this.x = pX;
|
||||
this.y = pY;
|
||||
this.z = pZ;
|
||||
}
|
||||
|
||||
public Vec3 getPosition(CommandSourceStack pSource) {
|
||||
Vec3 vec3 = pSource.getPosition();
|
||||
return new Vec3(this.x.get(vec3.x), this.y.get(vec3.y), this.z.get(vec3.z));
|
||||
}
|
||||
|
||||
public Vec2 getRotation(CommandSourceStack pSource) {
|
||||
Vec2 vec2 = pSource.getRotation();
|
||||
return new Vec2((float)this.x.get((double)vec2.x), (float)this.y.get((double)vec2.y));
|
||||
}
|
||||
|
||||
public boolean isXRelative() {
|
||||
return this.x.isRelative();
|
||||
}
|
||||
|
||||
public boolean isYRelative() {
|
||||
return this.y.isRelative();
|
||||
}
|
||||
|
||||
public boolean isZRelative() {
|
||||
return this.z.isRelative();
|
||||
}
|
||||
|
||||
public boolean equals(Object pOther) {
|
||||
if (this == pOther) {
|
||||
return true;
|
||||
} else if (!(pOther instanceof WorldCoordinates)) {
|
||||
return false;
|
||||
} else {
|
||||
WorldCoordinates worldcoordinates = (WorldCoordinates)pOther;
|
||||
if (!this.x.equals(worldcoordinates.x)) {
|
||||
return false;
|
||||
} else {
|
||||
return !this.y.equals(worldcoordinates.y) ? false : this.z.equals(worldcoordinates.z);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static WorldCoordinates parseInt(StringReader pReader) throws CommandSyntaxException {
|
||||
int i = pReader.getCursor();
|
||||
WorldCoordinate worldcoordinate = WorldCoordinate.parseInt(pReader);
|
||||
if (pReader.canRead() && pReader.peek() == ' ') {
|
||||
pReader.skip();
|
||||
WorldCoordinate worldcoordinate1 = WorldCoordinate.parseInt(pReader);
|
||||
if (pReader.canRead() && pReader.peek() == ' ') {
|
||||
pReader.skip();
|
||||
WorldCoordinate worldcoordinate2 = WorldCoordinate.parseInt(pReader);
|
||||
return new WorldCoordinates(worldcoordinate, worldcoordinate1, worldcoordinate2);
|
||||
} else {
|
||||
pReader.setCursor(i);
|
||||
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(pReader);
|
||||
}
|
||||
} else {
|
||||
pReader.setCursor(i);
|
||||
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(pReader);
|
||||
}
|
||||
}
|
||||
|
||||
public static WorldCoordinates parseDouble(StringReader pReader, boolean pCenterCorrect) throws CommandSyntaxException {
|
||||
int i = pReader.getCursor();
|
||||
WorldCoordinate worldcoordinate = WorldCoordinate.parseDouble(pReader, pCenterCorrect);
|
||||
if (pReader.canRead() && pReader.peek() == ' ') {
|
||||
pReader.skip();
|
||||
WorldCoordinate worldcoordinate1 = WorldCoordinate.parseDouble(pReader, false);
|
||||
if (pReader.canRead() && pReader.peek() == ' ') {
|
||||
pReader.skip();
|
||||
WorldCoordinate worldcoordinate2 = WorldCoordinate.parseDouble(pReader, pCenterCorrect);
|
||||
return new WorldCoordinates(worldcoordinate, worldcoordinate1, worldcoordinate2);
|
||||
} else {
|
||||
pReader.setCursor(i);
|
||||
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(pReader);
|
||||
}
|
||||
} else {
|
||||
pReader.setCursor(i);
|
||||
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(pReader);
|
||||
}
|
||||
}
|
||||
|
||||
public static WorldCoordinates absolute(double pX, double pY, double pZ) {
|
||||
return new WorldCoordinates(new WorldCoordinate(false, pX), new WorldCoordinate(false, pY), new WorldCoordinate(false, pZ));
|
||||
}
|
||||
|
||||
public static WorldCoordinates absolute(Vec2 pVector) {
|
||||
return new WorldCoordinates(new WorldCoordinate(false, (double)pVector.x), new WorldCoordinate(false, (double)pVector.y), new WorldCoordinate(true, 0.0D));
|
||||
}
|
||||
|
||||
/**
|
||||
* A location with a delta of 0 for all values (equivalent to <code>~ ~ ~</code> or <code>~0 ~0 ~0</code>)
|
||||
*/
|
||||
public static WorldCoordinates current() {
|
||||
return new WorldCoordinates(new WorldCoordinate(true, 0.0D), new WorldCoordinate(true, 0.0D), new WorldCoordinate(true, 0.0D));
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
int i = this.x.hashCode();
|
||||
i = 31 * i + this.y.hashCode();
|
||||
return 31 * i + this.z.hashCode();
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
@FieldsAreNonnullByDefault
|
||||
package net.minecraft.commands.arguments.coordinates;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.FieldsAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package net.minecraft.commands.arguments.item;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import com.mojang.datafixers.util.Pair;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import net.minecraft.commands.CommandFunction;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
public class FunctionArgument implements ArgumentType<FunctionArgument.Result> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "#foo");
|
||||
private static final DynamicCommandExceptionType ERROR_UNKNOWN_TAG = new DynamicCommandExceptionType((p_120927_) -> {
|
||||
return Component.translatable("arguments.function.tag.unknown", p_120927_);
|
||||
});
|
||||
private static final DynamicCommandExceptionType ERROR_UNKNOWN_FUNCTION = new DynamicCommandExceptionType((p_120917_) -> {
|
||||
return Component.translatable("arguments.function.unknown", p_120917_);
|
||||
});
|
||||
|
||||
public static FunctionArgument functions() {
|
||||
return new FunctionArgument();
|
||||
}
|
||||
|
||||
public FunctionArgument.Result parse(StringReader pReader) throws CommandSyntaxException {
|
||||
if (pReader.canRead() && pReader.peek() == '#') {
|
||||
pReader.skip();
|
||||
final ResourceLocation resourcelocation1 = ResourceLocation.read(pReader);
|
||||
return new FunctionArgument.Result() {
|
||||
public Collection<CommandFunction> create(CommandContext<CommandSourceStack> p_120943_) throws CommandSyntaxException {
|
||||
return FunctionArgument.getFunctionTag(p_120943_, resourcelocation1);
|
||||
}
|
||||
|
||||
public Pair<ResourceLocation, Either<CommandFunction, Collection<CommandFunction>>> unwrap(CommandContext<CommandSourceStack> p_120945_) throws CommandSyntaxException {
|
||||
return Pair.of(resourcelocation1, Either.right(FunctionArgument.getFunctionTag(p_120945_, resourcelocation1)));
|
||||
}
|
||||
};
|
||||
} else {
|
||||
final ResourceLocation resourcelocation = ResourceLocation.read(pReader);
|
||||
return new FunctionArgument.Result() {
|
||||
public Collection<CommandFunction> create(CommandContext<CommandSourceStack> p_120952_) throws CommandSyntaxException {
|
||||
return Collections.singleton(FunctionArgument.getFunction(p_120952_, resourcelocation));
|
||||
}
|
||||
|
||||
public Pair<ResourceLocation, Either<CommandFunction, Collection<CommandFunction>>> unwrap(CommandContext<CommandSourceStack> p_120954_) throws CommandSyntaxException {
|
||||
return Pair.of(resourcelocation, Either.left(FunctionArgument.getFunction(p_120954_, resourcelocation)));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
static CommandFunction getFunction(CommandContext<CommandSourceStack> pContext, ResourceLocation pId) throws CommandSyntaxException {
|
||||
return pContext.getSource().getServer().getFunctions().get(pId).orElseThrow(() -> {
|
||||
return ERROR_UNKNOWN_FUNCTION.create(pId.toString());
|
||||
});
|
||||
}
|
||||
|
||||
static Collection<CommandFunction> getFunctionTag(CommandContext<CommandSourceStack> pContext, ResourceLocation pId) throws CommandSyntaxException {
|
||||
Collection<CommandFunction> collection = pContext.getSource().getServer().getFunctions().getTag(pId);
|
||||
if (collection == null) {
|
||||
throw ERROR_UNKNOWN_TAG.create(pId.toString());
|
||||
} else {
|
||||
return collection;
|
||||
}
|
||||
}
|
||||
|
||||
public static Collection<CommandFunction> getFunctions(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return pContext.getArgument(pName, FunctionArgument.Result.class).create(pContext);
|
||||
}
|
||||
|
||||
public static Pair<ResourceLocation, Either<CommandFunction, Collection<CommandFunction>>> getFunctionOrTag(CommandContext<CommandSourceStack> pContext, String pName) throws CommandSyntaxException {
|
||||
return pContext.getArgument(pName, FunctionArgument.Result.class).unwrap(pContext);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
public interface Result {
|
||||
Collection<CommandFunction> create(CommandContext<CommandSourceStack> pContext) throws CommandSyntaxException;
|
||||
|
||||
Pair<ResourceLocation, Either<CommandFunction, Collection<CommandFunction>>> unwrap(CommandContext<CommandSourceStack> pContext) throws CommandSyntaxException;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package net.minecraft.commands.arguments.item;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.world.item.Item;
|
||||
|
||||
public class ItemArgument implements ArgumentType<ItemInput> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("stick", "minecraft:stick", "stick{foo=bar}");
|
||||
private final HolderLookup<Item> items;
|
||||
|
||||
public ItemArgument(CommandBuildContext pContext) {
|
||||
this.items = pContext.holderLookup(Registries.ITEM);
|
||||
}
|
||||
|
||||
public static ItemArgument item(CommandBuildContext pContext) {
|
||||
return new ItemArgument(pContext);
|
||||
}
|
||||
|
||||
public ItemInput parse(StringReader pReader) throws CommandSyntaxException {
|
||||
ItemParser.ItemResult itemparser$itemresult = ItemParser.parseForItem(this.items, pReader);
|
||||
return new ItemInput(itemparser$itemresult.item(), itemparser$itemresult.nbt());
|
||||
}
|
||||
|
||||
public static <S> ItemInput getItem(CommandContext<S> pContext, String pName) {
|
||||
return pContext.getArgument(pName, ItemInput.class);
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return ItemParser.fillSuggestions(this.items, pBuilder, false);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package net.minecraft.commands.arguments.item;
|
||||
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
|
||||
import java.util.function.Predicate;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.NbtUtils;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
|
||||
public class ItemInput implements Predicate<ItemStack> {
|
||||
private static final Dynamic2CommandExceptionType ERROR_STACK_TOO_BIG = new Dynamic2CommandExceptionType((p_120986_, p_120987_) -> {
|
||||
return Component.translatable("arguments.item.overstacked", p_120986_, p_120987_);
|
||||
});
|
||||
private final Holder<Item> item;
|
||||
@Nullable
|
||||
private final CompoundTag tag;
|
||||
|
||||
public ItemInput(Holder<Item> pItem, @Nullable CompoundTag pTag) {
|
||||
this.item = pItem;
|
||||
this.tag = pTag;
|
||||
}
|
||||
|
||||
public Item getItem() {
|
||||
return this.item.value();
|
||||
}
|
||||
|
||||
public boolean test(ItemStack pStack) {
|
||||
return pStack.is(this.item) && NbtUtils.compareNbt(this.tag, pStack.getTag(), true);
|
||||
}
|
||||
|
||||
public ItemStack createItemStack(int pCount, boolean pAllowOversizedStacks) throws CommandSyntaxException {
|
||||
ItemStack itemstack = new ItemStack(this.item, pCount);
|
||||
if (this.tag != null) {
|
||||
itemstack.setTag(this.tag);
|
||||
}
|
||||
|
||||
if (pAllowOversizedStacks && pCount > itemstack.getMaxStackSize()) {
|
||||
throw ERROR_STACK_TOO_BIG.create(this.getItemName(), itemstack.getMaxStackSize());
|
||||
} else {
|
||||
return itemstack;
|
||||
}
|
||||
}
|
||||
|
||||
public String serialize() {
|
||||
StringBuilder stringbuilder = new StringBuilder(this.getItemName());
|
||||
if (this.tag != null) {
|
||||
stringbuilder.append((Object)this.tag);
|
||||
}
|
||||
|
||||
return stringbuilder.toString();
|
||||
}
|
||||
|
||||
private String getItemName() {
|
||||
return this.item.unwrapKey().<Object>map(ResourceKey::location).orElseGet(() -> {
|
||||
return "unknown[" + this.item + "]";
|
||||
}).toString();
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
package net.minecraft.commands.arguments.item;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.TagParser;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.item.Item;
|
||||
|
||||
public class ItemParser {
|
||||
private static final SimpleCommandExceptionType ERROR_NO_TAGS_ALLOWED = new SimpleCommandExceptionType(Component.translatable("argument.item.tag.disallowed"));
|
||||
private static final DynamicCommandExceptionType ERROR_UNKNOWN_ITEM = new DynamicCommandExceptionType((p_121013_) -> {
|
||||
return Component.translatable("argument.item.id.invalid", p_121013_);
|
||||
});
|
||||
private static final DynamicCommandExceptionType ERROR_UNKNOWN_TAG = new DynamicCommandExceptionType((p_235313_) -> {
|
||||
return Component.translatable("arguments.item.tag.unknown", p_235313_);
|
||||
});
|
||||
private static final char SYNTAX_START_NBT = '{';
|
||||
private static final char SYNTAX_TAG = '#';
|
||||
private static final Function<SuggestionsBuilder, CompletableFuture<Suggestions>> SUGGEST_NOTHING = SuggestionsBuilder::buildFuture;
|
||||
private final HolderLookup<Item> items;
|
||||
private final StringReader reader;
|
||||
private final boolean allowTags;
|
||||
private Either<Holder<Item>, HolderSet<Item>> result;
|
||||
@Nullable
|
||||
private CompoundTag nbt;
|
||||
/** Builder to be used when creating a list of suggestions */
|
||||
private Function<SuggestionsBuilder, CompletableFuture<Suggestions>> suggestions = SUGGEST_NOTHING;
|
||||
|
||||
private ItemParser(HolderLookup<Item> pItems, StringReader pReader, boolean pAllowTags) {
|
||||
this.items = pItems;
|
||||
this.reader = pReader;
|
||||
this.allowTags = pAllowTags;
|
||||
}
|
||||
|
||||
public static ItemParser.ItemResult parseForItem(HolderLookup<Item> pLookup, StringReader pReader) throws CommandSyntaxException {
|
||||
int i = pReader.getCursor();
|
||||
|
||||
try {
|
||||
ItemParser itemparser = new ItemParser(pLookup, pReader, false);
|
||||
itemparser.parse();
|
||||
Holder<Item> holder = itemparser.result.left().orElseThrow(() -> {
|
||||
return new IllegalStateException("Parser returned unexpected tag name");
|
||||
});
|
||||
return new ItemParser.ItemResult(holder, itemparser.nbt);
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
pReader.setCursor(i);
|
||||
throw commandsyntaxexception;
|
||||
}
|
||||
}
|
||||
|
||||
public static Either<ItemParser.ItemResult, ItemParser.TagResult> parseForTesting(HolderLookup<Item> pLookup, StringReader pReader) throws CommandSyntaxException {
|
||||
int i = pReader.getCursor();
|
||||
|
||||
try {
|
||||
ItemParser itemparser = new ItemParser(pLookup, pReader, true);
|
||||
itemparser.parse();
|
||||
return itemparser.result.mapBoth((p_235301_) -> {
|
||||
return new ItemParser.ItemResult(p_235301_, itemparser.nbt);
|
||||
}, (p_235304_) -> {
|
||||
return new ItemParser.TagResult(p_235304_, itemparser.nbt);
|
||||
});
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
pReader.setCursor(i);
|
||||
throw commandsyntaxexception;
|
||||
}
|
||||
}
|
||||
|
||||
public static CompletableFuture<Suggestions> fillSuggestions(HolderLookup<Item> pLookup, SuggestionsBuilder pBuilder, boolean pAllowTags) {
|
||||
StringReader stringreader = new StringReader(pBuilder.getInput());
|
||||
stringreader.setCursor(pBuilder.getStart());
|
||||
ItemParser itemparser = new ItemParser(pLookup, stringreader, pAllowTags);
|
||||
|
||||
try {
|
||||
itemparser.parse();
|
||||
} catch (CommandSyntaxException commandsyntaxexception) {
|
||||
}
|
||||
|
||||
return itemparser.suggestions.apply(pBuilder.createOffset(stringreader.getCursor()));
|
||||
}
|
||||
|
||||
private void readItem() throws CommandSyntaxException {
|
||||
int i = this.reader.getCursor();
|
||||
ResourceLocation resourcelocation = ResourceLocation.read(this.reader);
|
||||
Optional<? extends Holder<Item>> optional = this.items.get(ResourceKey.create(Registries.ITEM, resourcelocation));
|
||||
this.result = Either.left(optional.orElseThrow(() -> {
|
||||
this.reader.setCursor(i);
|
||||
return ERROR_UNKNOWN_ITEM.createWithContext(this.reader, resourcelocation);
|
||||
}));
|
||||
}
|
||||
|
||||
private void readTag() throws CommandSyntaxException {
|
||||
if (!this.allowTags) {
|
||||
throw ERROR_NO_TAGS_ALLOWED.createWithContext(this.reader);
|
||||
} else {
|
||||
int i = this.reader.getCursor();
|
||||
this.reader.expect('#');
|
||||
this.suggestions = this::suggestTag;
|
||||
ResourceLocation resourcelocation = ResourceLocation.read(this.reader);
|
||||
Optional<? extends HolderSet<Item>> optional = this.items.get(TagKey.create(Registries.ITEM, resourcelocation));
|
||||
this.result = Either.right(optional.orElseThrow(() -> {
|
||||
this.reader.setCursor(i);
|
||||
return ERROR_UNKNOWN_TAG.createWithContext(this.reader, resourcelocation);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
private void readNbt() throws CommandSyntaxException {
|
||||
this.nbt = (new TagParser(this.reader)).readStruct();
|
||||
}
|
||||
|
||||
private void parse() throws CommandSyntaxException {
|
||||
if (this.allowTags) {
|
||||
this.suggestions = this::suggestItemIdOrTag;
|
||||
} else {
|
||||
this.suggestions = this::suggestItem;
|
||||
}
|
||||
|
||||
if (this.reader.canRead() && this.reader.peek() == '#') {
|
||||
this.readTag();
|
||||
} else {
|
||||
this.readItem();
|
||||
}
|
||||
|
||||
this.suggestions = this::suggestOpenNbt;
|
||||
if (this.reader.canRead() && this.reader.peek() == '{') {
|
||||
this.suggestions = SUGGEST_NOTHING;
|
||||
this.readNbt();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestOpenNbt(SuggestionsBuilder p_235298_) {
|
||||
if (p_235298_.getRemaining().isEmpty()) {
|
||||
p_235298_.suggest(String.valueOf('{'));
|
||||
}
|
||||
|
||||
return p_235298_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestTag(SuggestionsBuilder p_235318_) {
|
||||
return SharedSuggestionProvider.suggestResource(this.items.listTagIds().map(TagKey::location), p_235318_, String.valueOf('#'));
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestItem(SuggestionsBuilder p_235323_) {
|
||||
return SharedSuggestionProvider.suggestResource(this.items.listElementIds().map(ResourceKey::location), p_235323_);
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestItemIdOrTag(SuggestionsBuilder p_235326_) {
|
||||
this.suggestTag(p_235326_);
|
||||
return this.suggestItem(p_235326_);
|
||||
}
|
||||
|
||||
public static record ItemResult(Holder<Item> item, @Nullable CompoundTag nbt) {
|
||||
}
|
||||
|
||||
public static record TagResult(HolderSet<Item> tag, @Nullable CompoundTag nbt) {
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package net.minecraft.commands.arguments.item;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Predicate;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.NbtUtils;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
|
||||
public class ItemPredicateArgument implements ArgumentType<ItemPredicateArgument.Result> {
|
||||
private static final Collection<String> EXAMPLES = Arrays.asList("stick", "minecraft:stick", "#stick", "#stick{foo=bar}");
|
||||
private final HolderLookup<Item> items;
|
||||
|
||||
public ItemPredicateArgument(CommandBuildContext pContext) {
|
||||
this.items = pContext.holderLookup(Registries.ITEM);
|
||||
}
|
||||
|
||||
public static ItemPredicateArgument itemPredicate(CommandBuildContext pContext) {
|
||||
return new ItemPredicateArgument(pContext);
|
||||
}
|
||||
|
||||
public ItemPredicateArgument.Result parse(StringReader pReader) throws CommandSyntaxException {
|
||||
Either<ItemParser.ItemResult, ItemParser.TagResult> either = ItemParser.parseForTesting(this.items, pReader);
|
||||
return either.map((p_235356_) -> {
|
||||
return createResult((p_235359_) -> {
|
||||
return p_235359_ == p_235356_.item();
|
||||
}, p_235356_.nbt());
|
||||
}, (p_235361_) -> {
|
||||
return createResult(p_235361_.tag()::contains, p_235361_.nbt());
|
||||
});
|
||||
}
|
||||
|
||||
public static Predicate<ItemStack> getItemPredicate(CommandContext<CommandSourceStack> pContext, String pName) {
|
||||
return pContext.getArgument(pName, ItemPredicateArgument.Result.class);
|
||||
}
|
||||
|
||||
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> pContext, SuggestionsBuilder pBuilder) {
|
||||
return ItemParser.fillSuggestions(this.items, pBuilder, true);
|
||||
}
|
||||
|
||||
public Collection<String> getExamples() {
|
||||
return EXAMPLES;
|
||||
}
|
||||
|
||||
private static ItemPredicateArgument.Result createResult(Predicate<Holder<Item>> pItemPredicate, @Nullable CompoundTag pNbt) {
|
||||
return pNbt != null ? (p_235371_) -> {
|
||||
return p_235371_.is(pItemPredicate) && NbtUtils.compareNbt(pNbt, p_235371_.getTag(), true);
|
||||
} : (p_235364_) -> {
|
||||
return p_235364_.is(pItemPredicate);
|
||||
};
|
||||
}
|
||||
|
||||
public interface Result extends Predicate<ItemStack> {
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
@FieldsAreNonnullByDefault
|
||||
package net.minecraft.commands.arguments.item;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.FieldsAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
@FieldsAreNonnullByDefault
|
||||
package net.minecraft.commands.arguments;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.FieldsAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
package net.minecraft.commands.arguments.selector;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.advancements.critereon.MinMaxBounds;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.arguments.EntityArgument;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.ComponentUtils;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.level.entity.EntityTypeTest;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class EntitySelector {
|
||||
public static final int INFINITE = Integer.MAX_VALUE;
|
||||
public static final BiConsumer<Vec3, List<? extends Entity>> ORDER_ARBITRARY = (p_261404_, p_261405_) -> {
|
||||
};
|
||||
private static final EntityTypeTest<Entity, ?> ANY_TYPE = new EntityTypeTest<Entity, Entity>() {
|
||||
public Entity tryCast(Entity p_175109_) {
|
||||
return p_175109_;
|
||||
}
|
||||
|
||||
public Class<? extends Entity> getBaseClass() {
|
||||
return Entity.class;
|
||||
}
|
||||
};
|
||||
private final int maxResults;
|
||||
private final boolean includesEntities;
|
||||
private final boolean worldLimited;
|
||||
private final Predicate<Entity> predicate;
|
||||
private final MinMaxBounds.Doubles range;
|
||||
private final Function<Vec3, Vec3> position;
|
||||
@Nullable
|
||||
private final AABB aabb;
|
||||
private final BiConsumer<Vec3, List<? extends Entity>> order;
|
||||
private final boolean currentEntity;
|
||||
@Nullable
|
||||
private final String playerName;
|
||||
@Nullable
|
||||
private final UUID entityUUID;
|
||||
private final EntityTypeTest<Entity, ?> type;
|
||||
private final boolean usesSelector;
|
||||
|
||||
public EntitySelector(int pMaxResults, boolean pIncludeEntities, boolean pWorldLimited, Predicate<Entity> pPredicate, MinMaxBounds.Doubles pRange, Function<Vec3, Vec3> pPositions, @Nullable AABB pAabb, BiConsumer<Vec3, List<? extends Entity>> pOrder, boolean pCurrentEntity, @Nullable String pPlayerName, @Nullable UUID pEntityUUID, @Nullable EntityType<?> pType, boolean pUsesSelector) {
|
||||
this.maxResults = pMaxResults;
|
||||
this.includesEntities = pIncludeEntities;
|
||||
this.worldLimited = pWorldLimited;
|
||||
this.predicate = pPredicate;
|
||||
this.range = pRange;
|
||||
this.position = pPositions;
|
||||
this.aabb = pAabb;
|
||||
this.order = pOrder;
|
||||
this.currentEntity = pCurrentEntity;
|
||||
this.playerName = pPlayerName;
|
||||
this.entityUUID = pEntityUUID;
|
||||
this.type = (EntityTypeTest<Entity, ?>)(pType == null ? ANY_TYPE : pType);
|
||||
this.usesSelector = pUsesSelector;
|
||||
}
|
||||
|
||||
public int getMaxResults() {
|
||||
return this.maxResults;
|
||||
}
|
||||
|
||||
public boolean includesEntities() {
|
||||
return this.includesEntities;
|
||||
}
|
||||
|
||||
public boolean isSelfSelector() {
|
||||
return this.currentEntity;
|
||||
}
|
||||
|
||||
public boolean isWorldLimited() {
|
||||
return this.worldLimited;
|
||||
}
|
||||
|
||||
public boolean usesSelector() {
|
||||
return this.usesSelector;
|
||||
}
|
||||
|
||||
private void checkPermissions(CommandSourceStack pSource) throws CommandSyntaxException {
|
||||
if (this.usesSelector && !net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(pSource)) {
|
||||
throw EntityArgument.ERROR_SELECTORS_NOT_ALLOWED.create();
|
||||
}
|
||||
}
|
||||
|
||||
public Entity findSingleEntity(CommandSourceStack pSource) throws CommandSyntaxException {
|
||||
this.checkPermissions(pSource);
|
||||
List<? extends Entity> list = this.findEntities(pSource);
|
||||
if (list.isEmpty()) {
|
||||
throw EntityArgument.NO_ENTITIES_FOUND.create();
|
||||
} else if (list.size() > 1) {
|
||||
throw EntityArgument.ERROR_NOT_SINGLE_ENTITY.create();
|
||||
} else {
|
||||
return list.get(0);
|
||||
}
|
||||
}
|
||||
|
||||
public List<? extends Entity> findEntities(CommandSourceStack pSource) throws CommandSyntaxException {
|
||||
return this.findEntitiesRaw(pSource).stream().filter((p_247981_) -> {
|
||||
return p_247981_.getType().isEnabled(pSource.enabledFeatures());
|
||||
}).toList();
|
||||
}
|
||||
|
||||
private List<? extends Entity> findEntitiesRaw(CommandSourceStack p_251934_) throws CommandSyntaxException {
|
||||
this.checkPermissions(p_251934_);
|
||||
if (!this.includesEntities) {
|
||||
return this.findPlayers(p_251934_);
|
||||
} else if (this.playerName != null) {
|
||||
ServerPlayer serverplayer = p_251934_.getServer().getPlayerList().getPlayerByName(this.playerName);
|
||||
return (List<? extends Entity>)(serverplayer == null ? Collections.emptyList() : Lists.newArrayList(serverplayer));
|
||||
} else if (this.entityUUID != null) {
|
||||
for(ServerLevel serverlevel1 : p_251934_.getServer().getAllLevels()) {
|
||||
Entity entity = serverlevel1.getEntity(this.entityUUID);
|
||||
if (entity != null) {
|
||||
return Lists.newArrayList(entity);
|
||||
}
|
||||
}
|
||||
|
||||
return Collections.emptyList();
|
||||
} else {
|
||||
Vec3 vec3 = this.position.apply(p_251934_.getPosition());
|
||||
Predicate<Entity> predicate = this.getPredicate(vec3);
|
||||
if (this.currentEntity) {
|
||||
return (List<? extends Entity>)(p_251934_.getEntity() != null && predicate.test(p_251934_.getEntity()) ? Lists.newArrayList(p_251934_.getEntity()) : Collections.emptyList());
|
||||
} else {
|
||||
List<Entity> list = Lists.newArrayList();
|
||||
if (this.isWorldLimited()) {
|
||||
this.addEntities(list, p_251934_.getLevel(), vec3, predicate);
|
||||
} else {
|
||||
for(ServerLevel serverlevel : p_251934_.getServer().getAllLevels()) {
|
||||
this.addEntities(list, serverlevel, vec3, predicate);
|
||||
}
|
||||
}
|
||||
|
||||
return this.sortAndLimit(vec3, list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all entities matching this selector, and adds them to the passed list.
|
||||
*/
|
||||
private void addEntities(List<Entity> pResult, ServerLevel pLevel, Vec3 pPos, Predicate<Entity> pPredicate) {
|
||||
int i = this.getResultLimit();
|
||||
if (pResult.size() < i) {
|
||||
if (this.aabb != null) {
|
||||
pLevel.getEntities(this.type, this.aabb.move(pPos), pPredicate, pResult, i);
|
||||
} else {
|
||||
pLevel.getEntities(this.type, pPredicate, pResult, i);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private int getResultLimit() {
|
||||
return this.order == ORDER_ARBITRARY ? this.maxResults : Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
public ServerPlayer findSinglePlayer(CommandSourceStack pSource) throws CommandSyntaxException {
|
||||
this.checkPermissions(pSource);
|
||||
List<ServerPlayer> list = this.findPlayers(pSource);
|
||||
if (list.size() != 1) {
|
||||
throw EntityArgument.NO_PLAYERS_FOUND.create();
|
||||
} else {
|
||||
return list.get(0);
|
||||
}
|
||||
}
|
||||
|
||||
public List<ServerPlayer> findPlayers(CommandSourceStack pSource) throws CommandSyntaxException {
|
||||
this.checkPermissions(pSource);
|
||||
if (this.playerName != null) {
|
||||
ServerPlayer serverplayer2 = pSource.getServer().getPlayerList().getPlayerByName(this.playerName);
|
||||
return (List<ServerPlayer>)(serverplayer2 == null ? Collections.emptyList() : Lists.newArrayList(serverplayer2));
|
||||
} else if (this.entityUUID != null) {
|
||||
ServerPlayer serverplayer1 = pSource.getServer().getPlayerList().getPlayer(this.entityUUID);
|
||||
return (List<ServerPlayer>)(serverplayer1 == null ? Collections.emptyList() : Lists.newArrayList(serverplayer1));
|
||||
} else {
|
||||
Vec3 vec3 = this.position.apply(pSource.getPosition());
|
||||
Predicate<Entity> predicate = this.getPredicate(vec3);
|
||||
if (this.currentEntity) {
|
||||
if (pSource.getEntity() instanceof ServerPlayer) {
|
||||
ServerPlayer serverplayer3 = (ServerPlayer)pSource.getEntity();
|
||||
if (predicate.test(serverplayer3)) {
|
||||
return Lists.newArrayList(serverplayer3);
|
||||
}
|
||||
}
|
||||
|
||||
return Collections.emptyList();
|
||||
} else {
|
||||
int i = this.getResultLimit();
|
||||
List<ServerPlayer> list;
|
||||
if (this.isWorldLimited()) {
|
||||
list = pSource.getLevel().getPlayers(predicate, i);
|
||||
} else {
|
||||
list = Lists.newArrayList();
|
||||
|
||||
for(ServerPlayer serverplayer : pSource.getServer().getPlayerList().getPlayers()) {
|
||||
if (predicate.test(serverplayer)) {
|
||||
list.add(serverplayer);
|
||||
if (list.size() >= i) {
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this.sortAndLimit(vec3, list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a modified version of the predicate on this selector that also checks the AABB and distance.
|
||||
*/
|
||||
private Predicate<Entity> getPredicate(Vec3 pPos) {
|
||||
Predicate<Entity> predicate = this.predicate;
|
||||
if (this.aabb != null) {
|
||||
AABB aabb = this.aabb.move(pPos);
|
||||
predicate = predicate.and((p_121143_) -> {
|
||||
return aabb.intersects(p_121143_.getBoundingBox());
|
||||
});
|
||||
}
|
||||
|
||||
if (!this.range.isAny()) {
|
||||
predicate = predicate.and((p_121148_) -> {
|
||||
return this.range.matchesSqr(p_121148_.distanceToSqr(pPos));
|
||||
});
|
||||
}
|
||||
|
||||
return predicate;
|
||||
}
|
||||
|
||||
private <T extends Entity> List<T> sortAndLimit(Vec3 pPos, List<T> pEntities) {
|
||||
if (pEntities.size() > 1) {
|
||||
this.order.accept(pPos, pEntities);
|
||||
}
|
||||
|
||||
return pEntities.subList(0, Math.min(this.maxResults, pEntities.size()));
|
||||
}
|
||||
|
||||
public static Component joinNames(List<? extends Entity> pNames) {
|
||||
return ComponentUtils.formatList(pNames, Entity::getDisplayName);
|
||||
}
|
||||
}
|
||||
+639
@@ -0,0 +1,639 @@
|
||||
package net.minecraft.commands.arguments.selector;
|
||||
|
||||
import com.google.common.primitives.Doubles;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.ToDoubleFunction;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.advancements.critereon.MinMaxBounds;
|
||||
import net.minecraft.advancements.critereon.WrappedMinMaxBounds;
|
||||
import net.minecraft.commands.arguments.selector.options.EntitySelectorOptions;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class EntitySelectorParser {
|
||||
public static final char SYNTAX_SELECTOR_START = '@';
|
||||
private static final char SYNTAX_OPTIONS_START = '[';
|
||||
private static final char SYNTAX_OPTIONS_END = ']';
|
||||
public static final char SYNTAX_OPTIONS_KEY_VALUE_SEPARATOR = '=';
|
||||
private static final char SYNTAX_OPTIONS_SEPARATOR = ',';
|
||||
public static final char SYNTAX_NOT = '!';
|
||||
public static final char SYNTAX_TAG = '#';
|
||||
private static final char SELECTOR_NEAREST_PLAYER = 'p';
|
||||
private static final char SELECTOR_ALL_PLAYERS = 'a';
|
||||
private static final char SELECTOR_RANDOM_PLAYERS = 'r';
|
||||
private static final char SELECTOR_CURRENT_ENTITY = 's';
|
||||
private static final char SELECTOR_ALL_ENTITIES = 'e';
|
||||
public static final SimpleCommandExceptionType ERROR_INVALID_NAME_OR_UUID = new SimpleCommandExceptionType(Component.translatable("argument.entity.invalid"));
|
||||
public static final DynamicCommandExceptionType ERROR_UNKNOWN_SELECTOR_TYPE = new DynamicCommandExceptionType((p_121301_) -> {
|
||||
return Component.translatable("argument.entity.selector.unknown", p_121301_);
|
||||
});
|
||||
public static final SimpleCommandExceptionType ERROR_SELECTORS_NOT_ALLOWED = new SimpleCommandExceptionType(Component.translatable("argument.entity.selector.not_allowed"));
|
||||
public static final SimpleCommandExceptionType ERROR_MISSING_SELECTOR_TYPE = new SimpleCommandExceptionType(Component.translatable("argument.entity.selector.missing"));
|
||||
public static final SimpleCommandExceptionType ERROR_EXPECTED_END_OF_OPTIONS = new SimpleCommandExceptionType(Component.translatable("argument.entity.options.unterminated"));
|
||||
public static final DynamicCommandExceptionType ERROR_EXPECTED_OPTION_VALUE = new DynamicCommandExceptionType((p_121267_) -> {
|
||||
return Component.translatable("argument.entity.options.valueless", p_121267_);
|
||||
});
|
||||
public static final BiConsumer<Vec3, List<? extends Entity>> ORDER_NEAREST = (p_121313_, p_121314_) -> {
|
||||
p_121314_.sort((p_175140_, p_175141_) -> {
|
||||
return Doubles.compare(p_175140_.distanceToSqr(p_121313_), p_175141_.distanceToSqr(p_121313_));
|
||||
});
|
||||
};
|
||||
public static final BiConsumer<Vec3, List<? extends Entity>> ORDER_FURTHEST = (p_121298_, p_121299_) -> {
|
||||
p_121299_.sort((p_175131_, p_175132_) -> {
|
||||
return Doubles.compare(p_175132_.distanceToSqr(p_121298_), p_175131_.distanceToSqr(p_121298_));
|
||||
});
|
||||
};
|
||||
public static final BiConsumer<Vec3, List<? extends Entity>> ORDER_RANDOM = (p_121264_, p_121265_) -> {
|
||||
Collections.shuffle(p_121265_);
|
||||
};
|
||||
public static final BiFunction<SuggestionsBuilder, Consumer<SuggestionsBuilder>, CompletableFuture<Suggestions>> SUGGEST_NOTHING = (p_121363_, p_121364_) -> {
|
||||
return p_121363_.buildFuture();
|
||||
};
|
||||
private final StringReader reader;
|
||||
private final boolean allowSelectors;
|
||||
private int maxResults;
|
||||
private boolean includesEntities;
|
||||
private boolean worldLimited;
|
||||
private MinMaxBounds.Doubles distance = MinMaxBounds.Doubles.ANY;
|
||||
private MinMaxBounds.Ints level = MinMaxBounds.Ints.ANY;
|
||||
@Nullable
|
||||
private Double x;
|
||||
@Nullable
|
||||
private Double y;
|
||||
@Nullable
|
||||
private Double z;
|
||||
@Nullable
|
||||
private Double deltaX;
|
||||
@Nullable
|
||||
private Double deltaY;
|
||||
@Nullable
|
||||
private Double deltaZ;
|
||||
private WrappedMinMaxBounds rotX = WrappedMinMaxBounds.ANY;
|
||||
private WrappedMinMaxBounds rotY = WrappedMinMaxBounds.ANY;
|
||||
private Predicate<Entity> predicate = (p_121321_) -> {
|
||||
return true;
|
||||
};
|
||||
private BiConsumer<Vec3, List<? extends Entity>> order = EntitySelector.ORDER_ARBITRARY;
|
||||
private boolean currentEntity;
|
||||
@Nullable
|
||||
private String playerName;
|
||||
private int startPosition;
|
||||
@Nullable
|
||||
private UUID entityUUID;
|
||||
private BiFunction<SuggestionsBuilder, Consumer<SuggestionsBuilder>, CompletableFuture<Suggestions>> suggestions = SUGGEST_NOTHING;
|
||||
private boolean hasNameEquals;
|
||||
private boolean hasNameNotEquals;
|
||||
private boolean isLimited;
|
||||
private boolean isSorted;
|
||||
private boolean hasGamemodeEquals;
|
||||
private boolean hasGamemodeNotEquals;
|
||||
private boolean hasTeamEquals;
|
||||
private boolean hasTeamNotEquals;
|
||||
@Nullable
|
||||
private EntityType<?> type;
|
||||
private boolean typeInverse;
|
||||
private boolean hasScores;
|
||||
private boolean hasAdvancements;
|
||||
private boolean usesSelectors;
|
||||
|
||||
public EntitySelectorParser(StringReader pReader) {
|
||||
this(pReader, true);
|
||||
}
|
||||
|
||||
public EntitySelectorParser(StringReader pReader, boolean pAllowSelectors) {
|
||||
this.reader = pReader;
|
||||
this.allowSelectors = pAllowSelectors;
|
||||
}
|
||||
|
||||
public EntitySelector getSelector() {
|
||||
AABB aabb;
|
||||
if (this.deltaX == null && this.deltaY == null && this.deltaZ == null) {
|
||||
if (this.distance.getMax() != null) {
|
||||
double d0 = this.distance.getMax();
|
||||
aabb = new AABB(-d0, -d0, -d0, d0 + 1.0D, d0 + 1.0D, d0 + 1.0D);
|
||||
} else {
|
||||
aabb = null;
|
||||
}
|
||||
} else {
|
||||
aabb = this.createAabb(this.deltaX == null ? 0.0D : this.deltaX, this.deltaY == null ? 0.0D : this.deltaY, this.deltaZ == null ? 0.0D : this.deltaZ);
|
||||
}
|
||||
|
||||
Function<Vec3, Vec3> function;
|
||||
if (this.x == null && this.y == null && this.z == null) {
|
||||
function = (p_121292_) -> {
|
||||
return p_121292_;
|
||||
};
|
||||
} else {
|
||||
function = (p_121258_) -> {
|
||||
return new Vec3(this.x == null ? p_121258_.x : this.x, this.y == null ? p_121258_.y : this.y, this.z == null ? p_121258_.z : this.z);
|
||||
};
|
||||
}
|
||||
|
||||
return new EntitySelector(this.maxResults, this.includesEntities, this.worldLimited, this.predicate, this.distance, function, aabb, this.order, this.currentEntity, this.playerName, this.entityUUID, this.type, this.usesSelectors);
|
||||
}
|
||||
|
||||
private AABB createAabb(double pSizeX, double pSizeY, double pSizeZ) {
|
||||
boolean flag = pSizeX < 0.0D;
|
||||
boolean flag1 = pSizeY < 0.0D;
|
||||
boolean flag2 = pSizeZ < 0.0D;
|
||||
double d0 = flag ? pSizeX : 0.0D;
|
||||
double d1 = flag1 ? pSizeY : 0.0D;
|
||||
double d2 = flag2 ? pSizeZ : 0.0D;
|
||||
double d3 = (flag ? 0.0D : pSizeX) + 1.0D;
|
||||
double d4 = (flag1 ? 0.0D : pSizeY) + 1.0D;
|
||||
double d5 = (flag2 ? 0.0D : pSizeZ) + 1.0D;
|
||||
return new AABB(d0, d1, d2, d3, d4, d5);
|
||||
}
|
||||
|
||||
public void finalizePredicates() {
|
||||
if (this.rotX != WrappedMinMaxBounds.ANY) {
|
||||
this.predicate = this.predicate.and(this.createRotationPredicate(this.rotX, Entity::getXRot));
|
||||
}
|
||||
|
||||
if (this.rotY != WrappedMinMaxBounds.ANY) {
|
||||
this.predicate = this.predicate.and(this.createRotationPredicate(this.rotY, Entity::getYRot));
|
||||
}
|
||||
|
||||
if (!this.level.isAny()) {
|
||||
this.predicate = this.predicate.and((p_287322_) -> {
|
||||
return !(p_287322_ instanceof ServerPlayer) ? false : this.level.matches(((ServerPlayer)p_287322_).experienceLevel);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private Predicate<Entity> createRotationPredicate(WrappedMinMaxBounds pAngleBounds, ToDoubleFunction<Entity> pAngleFunction) {
|
||||
double d0 = (double)Mth.wrapDegrees(pAngleBounds.getMin() == null ? 0.0F : pAngleBounds.getMin());
|
||||
double d1 = (double)Mth.wrapDegrees(pAngleBounds.getMax() == null ? 359.0F : pAngleBounds.getMax());
|
||||
return (p_175137_) -> {
|
||||
double d2 = Mth.wrapDegrees(pAngleFunction.applyAsDouble(p_175137_));
|
||||
if (d0 > d1) {
|
||||
return d2 >= d0 || d2 <= d1;
|
||||
} else {
|
||||
return d2 >= d0 && d2 <= d1;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected void parseSelector() throws CommandSyntaxException {
|
||||
this.usesSelectors = true;
|
||||
this.suggestions = this::suggestSelector;
|
||||
if (!this.reader.canRead()) {
|
||||
throw ERROR_MISSING_SELECTOR_TYPE.createWithContext(this.reader);
|
||||
} else {
|
||||
int i = this.reader.getCursor();
|
||||
char c0 = this.reader.read();
|
||||
if (c0 == 'p') {
|
||||
this.maxResults = 1;
|
||||
this.includesEntities = false;
|
||||
this.order = ORDER_NEAREST;
|
||||
this.limitToType(EntityType.PLAYER);
|
||||
} else if (c0 == 'a') {
|
||||
this.maxResults = Integer.MAX_VALUE;
|
||||
this.includesEntities = false;
|
||||
this.order = EntitySelector.ORDER_ARBITRARY;
|
||||
this.limitToType(EntityType.PLAYER);
|
||||
} else if (c0 == 'r') {
|
||||
this.maxResults = 1;
|
||||
this.includesEntities = false;
|
||||
this.order = ORDER_RANDOM;
|
||||
this.limitToType(EntityType.PLAYER);
|
||||
} else if (c0 == 's') {
|
||||
this.maxResults = 1;
|
||||
this.includesEntities = true;
|
||||
this.currentEntity = true;
|
||||
} else {
|
||||
if (c0 != 'e') {
|
||||
this.reader.setCursor(i);
|
||||
throw ERROR_UNKNOWN_SELECTOR_TYPE.createWithContext(this.reader, "@" + String.valueOf(c0));
|
||||
}
|
||||
|
||||
this.maxResults = Integer.MAX_VALUE;
|
||||
this.includesEntities = true;
|
||||
this.order = EntitySelector.ORDER_ARBITRARY;
|
||||
this.predicate = Entity::isAlive;
|
||||
}
|
||||
|
||||
this.suggestions = this::suggestOpenOptions;
|
||||
if (this.reader.canRead() && this.reader.peek() == '[') {
|
||||
this.reader.skip();
|
||||
this.suggestions = this::suggestOptionsKeyOrClose;
|
||||
this.parseOptions();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
protected void parseNameOrUUID() throws CommandSyntaxException {
|
||||
if (this.reader.canRead()) {
|
||||
this.suggestions = this::suggestName;
|
||||
}
|
||||
|
||||
int i = this.reader.getCursor();
|
||||
String s = this.reader.readString();
|
||||
|
||||
try {
|
||||
this.entityUUID = UUID.fromString(s);
|
||||
this.includesEntities = true;
|
||||
} catch (IllegalArgumentException illegalargumentexception) {
|
||||
if (s.isEmpty() || s.length() > 16) {
|
||||
this.reader.setCursor(i);
|
||||
throw ERROR_INVALID_NAME_OR_UUID.createWithContext(this.reader);
|
||||
}
|
||||
|
||||
this.includesEntities = false;
|
||||
this.playerName = s;
|
||||
}
|
||||
|
||||
this.maxResults = 1;
|
||||
}
|
||||
|
||||
public void parseOptions() throws CommandSyntaxException {
|
||||
this.suggestions = this::suggestOptionsKey;
|
||||
this.reader.skipWhitespace();
|
||||
|
||||
while(true) {
|
||||
if (this.reader.canRead() && this.reader.peek() != ']') {
|
||||
this.reader.skipWhitespace();
|
||||
int i = this.reader.getCursor();
|
||||
String s = this.reader.readString();
|
||||
EntitySelectorOptions.Modifier entityselectoroptions$modifier = EntitySelectorOptions.get(this, s, i);
|
||||
this.reader.skipWhitespace();
|
||||
if (!this.reader.canRead() || this.reader.peek() != '=') {
|
||||
this.reader.setCursor(i);
|
||||
throw ERROR_EXPECTED_OPTION_VALUE.createWithContext(this.reader, s);
|
||||
}
|
||||
|
||||
this.reader.skip();
|
||||
this.reader.skipWhitespace();
|
||||
this.suggestions = SUGGEST_NOTHING;
|
||||
entityselectoroptions$modifier.handle(this);
|
||||
this.reader.skipWhitespace();
|
||||
this.suggestions = this::suggestOptionsNextOrClose;
|
||||
if (!this.reader.canRead()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.reader.peek() == ',') {
|
||||
this.reader.skip();
|
||||
this.suggestions = this::suggestOptionsKey;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.reader.peek() != ']') {
|
||||
throw ERROR_EXPECTED_END_OF_OPTIONS.createWithContext(this.reader);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.reader.canRead()) {
|
||||
this.reader.skip();
|
||||
this.suggestions = SUGGEST_NOTHING;
|
||||
return;
|
||||
}
|
||||
|
||||
throw ERROR_EXPECTED_END_OF_OPTIONS.createWithContext(this.reader);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean shouldInvertValue() {
|
||||
this.reader.skipWhitespace();
|
||||
if (this.reader.canRead() && this.reader.peek() == '!') {
|
||||
this.reader.skip();
|
||||
this.reader.skipWhitespace();
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isTag() {
|
||||
this.reader.skipWhitespace();
|
||||
if (this.reader.canRead() && this.reader.peek() == '#') {
|
||||
this.reader.skip();
|
||||
this.reader.skipWhitespace();
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public StringReader getReader() {
|
||||
return this.reader;
|
||||
}
|
||||
|
||||
public void addPredicate(Predicate<Entity> pPredicate) {
|
||||
this.predicate = this.predicate.and(pPredicate);
|
||||
}
|
||||
|
||||
public void setWorldLimited() {
|
||||
this.worldLimited = true;
|
||||
}
|
||||
|
||||
public MinMaxBounds.Doubles getDistance() {
|
||||
return this.distance;
|
||||
}
|
||||
|
||||
public void setDistance(MinMaxBounds.Doubles pDistance) {
|
||||
this.distance = pDistance;
|
||||
}
|
||||
|
||||
public MinMaxBounds.Ints getLevel() {
|
||||
return this.level;
|
||||
}
|
||||
|
||||
public void setLevel(MinMaxBounds.Ints pLevel) {
|
||||
this.level = pLevel;
|
||||
}
|
||||
|
||||
public WrappedMinMaxBounds getRotX() {
|
||||
return this.rotX;
|
||||
}
|
||||
|
||||
public void setRotX(WrappedMinMaxBounds pRotX) {
|
||||
this.rotX = pRotX;
|
||||
}
|
||||
|
||||
public WrappedMinMaxBounds getRotY() {
|
||||
return this.rotY;
|
||||
}
|
||||
|
||||
public void setRotY(WrappedMinMaxBounds pRotY) {
|
||||
this.rotY = pRotY;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Double getX() {
|
||||
return this.x;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Double getY() {
|
||||
return this.y;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Double getZ() {
|
||||
return this.z;
|
||||
}
|
||||
|
||||
public void setX(double pX) {
|
||||
this.x = pX;
|
||||
}
|
||||
|
||||
public void setY(double pY) {
|
||||
this.y = pY;
|
||||
}
|
||||
|
||||
public void setZ(double pZ) {
|
||||
this.z = pZ;
|
||||
}
|
||||
|
||||
public void setDeltaX(double pDeltaX) {
|
||||
this.deltaX = pDeltaX;
|
||||
}
|
||||
|
||||
public void setDeltaY(double pDeltaY) {
|
||||
this.deltaY = pDeltaY;
|
||||
}
|
||||
|
||||
public void setDeltaZ(double pDeltaZ) {
|
||||
this.deltaZ = pDeltaZ;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Double getDeltaX() {
|
||||
return this.deltaX;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Double getDeltaY() {
|
||||
return this.deltaY;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Double getDeltaZ() {
|
||||
return this.deltaZ;
|
||||
}
|
||||
|
||||
public void setMaxResults(int pMaxResults) {
|
||||
this.maxResults = pMaxResults;
|
||||
}
|
||||
|
||||
public void setIncludesEntities(boolean pIncludesEntities) {
|
||||
this.includesEntities = pIncludesEntities;
|
||||
}
|
||||
|
||||
public BiConsumer<Vec3, List<? extends Entity>> getOrder() {
|
||||
return this.order;
|
||||
}
|
||||
|
||||
public void setOrder(BiConsumer<Vec3, List<? extends Entity>> pOrder) {
|
||||
this.order = pOrder;
|
||||
}
|
||||
|
||||
public EntitySelector parse() throws CommandSyntaxException {
|
||||
this.startPosition = this.reader.getCursor();
|
||||
this.suggestions = this::suggestNameOrSelector;
|
||||
if (this.reader.canRead() && this.reader.peek() == '@') {
|
||||
if (!this.allowSelectors) {
|
||||
throw ERROR_SELECTORS_NOT_ALLOWED.createWithContext(this.reader);
|
||||
}
|
||||
|
||||
this.reader.skip();
|
||||
EntitySelector forgeSelector = net.minecraftforge.common.command.EntitySelectorManager.parseSelector(this);
|
||||
if (forgeSelector != null)
|
||||
return forgeSelector;
|
||||
this.parseSelector();
|
||||
} else {
|
||||
this.parseNameOrUUID();
|
||||
}
|
||||
|
||||
this.finalizePredicates();
|
||||
return this.getSelector();
|
||||
}
|
||||
|
||||
private static void fillSelectorSuggestions(SuggestionsBuilder pBuilder) {
|
||||
pBuilder.suggest("@p", Component.translatable("argument.entity.selector.nearestPlayer"));
|
||||
pBuilder.suggest("@a", Component.translatable("argument.entity.selector.allPlayers"));
|
||||
pBuilder.suggest("@r", Component.translatable("argument.entity.selector.randomPlayer"));
|
||||
pBuilder.suggest("@s", Component.translatable("argument.entity.selector.self"));
|
||||
pBuilder.suggest("@e", Component.translatable("argument.entity.selector.allEntities"));
|
||||
net.minecraftforge.common.command.EntitySelectorManager.fillSelectorSuggestions(pBuilder);
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestNameOrSelector(SuggestionsBuilder p_121287_, Consumer<SuggestionsBuilder> p_121288_) {
|
||||
p_121288_.accept(p_121287_);
|
||||
if (this.allowSelectors) {
|
||||
fillSelectorSuggestions(p_121287_);
|
||||
}
|
||||
|
||||
return p_121287_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestName(SuggestionsBuilder p_121310_, Consumer<SuggestionsBuilder> p_121311_) {
|
||||
SuggestionsBuilder suggestionsbuilder = p_121310_.createOffset(this.startPosition);
|
||||
p_121311_.accept(suggestionsbuilder);
|
||||
return p_121310_.add(suggestionsbuilder).buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestSelector(SuggestionsBuilder p_121323_, Consumer<SuggestionsBuilder> p_121324_) {
|
||||
SuggestionsBuilder suggestionsbuilder = p_121323_.createOffset(p_121323_.getStart() - 1);
|
||||
fillSelectorSuggestions(suggestionsbuilder);
|
||||
p_121323_.add(suggestionsbuilder);
|
||||
return p_121323_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestOpenOptions(SuggestionsBuilder p_121334_, Consumer<SuggestionsBuilder> p_121335_) {
|
||||
p_121334_.suggest(String.valueOf('['));
|
||||
return p_121334_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestOptionsKeyOrClose(SuggestionsBuilder p_121342_, Consumer<SuggestionsBuilder> p_121343_) {
|
||||
p_121342_.suggest(String.valueOf(']'));
|
||||
EntitySelectorOptions.suggestNames(this, p_121342_);
|
||||
return p_121342_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestOptionsKey(SuggestionsBuilder p_121348_, Consumer<SuggestionsBuilder> p_121349_) {
|
||||
EntitySelectorOptions.suggestNames(this, p_121348_);
|
||||
return p_121348_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestOptionsNextOrClose(SuggestionsBuilder p_121354_, Consumer<SuggestionsBuilder> p_121355_) {
|
||||
p_121354_.suggest(String.valueOf(','));
|
||||
p_121354_.suggest(String.valueOf(']'));
|
||||
return p_121354_.buildFuture();
|
||||
}
|
||||
|
||||
private CompletableFuture<Suggestions> suggestEquals(SuggestionsBuilder pBuilder, Consumer<SuggestionsBuilder> pConsumer) {
|
||||
pBuilder.suggest(String.valueOf('='));
|
||||
return pBuilder.buildFuture();
|
||||
}
|
||||
|
||||
public boolean isCurrentEntity() {
|
||||
return this.currentEntity;
|
||||
}
|
||||
|
||||
public void setSuggestions(BiFunction<SuggestionsBuilder, Consumer<SuggestionsBuilder>, CompletableFuture<Suggestions>> pSuggestionHandler) {
|
||||
this.suggestions = pSuggestionHandler;
|
||||
}
|
||||
|
||||
public CompletableFuture<Suggestions> fillSuggestions(SuggestionsBuilder pBuilder, Consumer<SuggestionsBuilder> pConsumer) {
|
||||
return this.suggestions.apply(pBuilder.createOffset(this.reader.getCursor()), pConsumer);
|
||||
}
|
||||
|
||||
public boolean hasNameEquals() {
|
||||
return this.hasNameEquals;
|
||||
}
|
||||
|
||||
public void setHasNameEquals(boolean pHasNameEquals) {
|
||||
this.hasNameEquals = pHasNameEquals;
|
||||
}
|
||||
|
||||
public boolean hasNameNotEquals() {
|
||||
return this.hasNameNotEquals;
|
||||
}
|
||||
|
||||
public void setHasNameNotEquals(boolean pHasNameNotEquals) {
|
||||
this.hasNameNotEquals = pHasNameNotEquals;
|
||||
}
|
||||
|
||||
public boolean isLimited() {
|
||||
return this.isLimited;
|
||||
}
|
||||
|
||||
public void setLimited(boolean pIsLimited) {
|
||||
this.isLimited = pIsLimited;
|
||||
}
|
||||
|
||||
public boolean isSorted() {
|
||||
return this.isSorted;
|
||||
}
|
||||
|
||||
public void setSorted(boolean pIsSorted) {
|
||||
this.isSorted = pIsSorted;
|
||||
}
|
||||
|
||||
public boolean hasGamemodeEquals() {
|
||||
return this.hasGamemodeEquals;
|
||||
}
|
||||
|
||||
public void setHasGamemodeEquals(boolean pHasGamemodeEquals) {
|
||||
this.hasGamemodeEquals = pHasGamemodeEquals;
|
||||
}
|
||||
|
||||
public boolean hasGamemodeNotEquals() {
|
||||
return this.hasGamemodeNotEquals;
|
||||
}
|
||||
|
||||
public void setHasGamemodeNotEquals(boolean pHasGamemodeNotEquals) {
|
||||
this.hasGamemodeNotEquals = pHasGamemodeNotEquals;
|
||||
}
|
||||
|
||||
public boolean hasTeamEquals() {
|
||||
return this.hasTeamEquals;
|
||||
}
|
||||
|
||||
public void setHasTeamEquals(boolean pHasTeamEquals) {
|
||||
this.hasTeamEquals = pHasTeamEquals;
|
||||
}
|
||||
|
||||
public boolean hasTeamNotEquals() {
|
||||
return this.hasTeamNotEquals;
|
||||
}
|
||||
|
||||
public void setHasTeamNotEquals(boolean pHasTeamNotEquals) {
|
||||
this.hasTeamNotEquals = pHasTeamNotEquals;
|
||||
}
|
||||
|
||||
public void limitToType(EntityType<?> pType) {
|
||||
this.type = pType;
|
||||
}
|
||||
|
||||
public void setTypeLimitedInversely() {
|
||||
this.typeInverse = true;
|
||||
}
|
||||
|
||||
public boolean isTypeLimited() {
|
||||
return this.type != null;
|
||||
}
|
||||
|
||||
public boolean isTypeLimitedInversely() {
|
||||
return this.typeInverse;
|
||||
}
|
||||
|
||||
public boolean hasScores() {
|
||||
return this.hasScores;
|
||||
}
|
||||
|
||||
public void setHasScores(boolean pHasScores) {
|
||||
this.hasScores = pHasScores;
|
||||
}
|
||||
|
||||
public boolean hasAdvancements() {
|
||||
return this.hasAdvancements;
|
||||
}
|
||||
|
||||
public void setHasAdvancements(boolean pHasAdvancements) {
|
||||
this.hasAdvancements = pHasAdvancements;
|
||||
}
|
||||
}
|
||||
+566
@@ -0,0 +1,566 @@
|
||||
package net.minecraft.commands.arguments.selector.options;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.advancements.Advancement;
|
||||
import net.minecraft.advancements.AdvancementProgress;
|
||||
import net.minecraft.advancements.CriterionProgress;
|
||||
import net.minecraft.advancements.critereon.MinMaxBounds;
|
||||
import net.minecraft.advancements.critereon.WrappedMinMaxBounds;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelector;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.NbtUtils;
|
||||
import net.minecraft.nbt.TagParser;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.PlayerAdvancements;
|
||||
import net.minecraft.server.ServerAdvancementManager;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.level.storage.loot.LootContext;
|
||||
import net.minecraft.world.level.storage.loot.LootDataType;
|
||||
import net.minecraft.world.level.storage.loot.LootParams;
|
||||
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
|
||||
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
|
||||
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
|
||||
import net.minecraft.world.scores.Objective;
|
||||
import net.minecraft.world.scores.Score;
|
||||
import net.minecraft.world.scores.Scoreboard;
|
||||
import net.minecraft.world.scores.Team;
|
||||
|
||||
public class EntitySelectorOptions {
|
||||
private static final Map<String, EntitySelectorOptions.Option> OPTIONS = Maps.newHashMap();
|
||||
public static final DynamicCommandExceptionType ERROR_UNKNOWN_OPTION = new DynamicCommandExceptionType((p_121520_) -> {
|
||||
return Component.translatable("argument.entity.options.unknown", p_121520_);
|
||||
});
|
||||
public static final DynamicCommandExceptionType ERROR_INAPPLICABLE_OPTION = new DynamicCommandExceptionType((p_121516_) -> {
|
||||
return Component.translatable("argument.entity.options.inapplicable", p_121516_);
|
||||
});
|
||||
public static final SimpleCommandExceptionType ERROR_RANGE_NEGATIVE = new SimpleCommandExceptionType(Component.translatable("argument.entity.options.distance.negative"));
|
||||
public static final SimpleCommandExceptionType ERROR_LEVEL_NEGATIVE = new SimpleCommandExceptionType(Component.translatable("argument.entity.options.level.negative"));
|
||||
public static final SimpleCommandExceptionType ERROR_LIMIT_TOO_SMALL = new SimpleCommandExceptionType(Component.translatable("argument.entity.options.limit.toosmall"));
|
||||
public static final DynamicCommandExceptionType ERROR_SORT_UNKNOWN = new DynamicCommandExceptionType((p_121508_) -> {
|
||||
return Component.translatable("argument.entity.options.sort.irreversible", p_121508_);
|
||||
});
|
||||
public static final DynamicCommandExceptionType ERROR_GAME_MODE_INVALID = new DynamicCommandExceptionType((p_121493_) -> {
|
||||
return Component.translatable("argument.entity.options.mode.invalid", p_121493_);
|
||||
});
|
||||
public static final DynamicCommandExceptionType ERROR_ENTITY_TYPE_INVALID = new DynamicCommandExceptionType((p_121452_) -> {
|
||||
return Component.translatable("argument.entity.options.type.invalid", p_121452_);
|
||||
});
|
||||
|
||||
public static void register(String pId, EntitySelectorOptions.Modifier pHandler, Predicate<EntitySelectorParser> pPredicate, Component pTooltip) {
|
||||
OPTIONS.put(pId, new EntitySelectorOptions.Option(pHandler, pPredicate, pTooltip));
|
||||
}
|
||||
|
||||
public static void bootStrap() {
|
||||
if (OPTIONS.isEmpty()) {
|
||||
register("name", (p_121425_) -> {
|
||||
int i = p_121425_.getReader().getCursor();
|
||||
boolean flag = p_121425_.shouldInvertValue();
|
||||
String s = p_121425_.getReader().readString();
|
||||
if (p_121425_.hasNameNotEquals() && !flag) {
|
||||
p_121425_.getReader().setCursor(i);
|
||||
throw ERROR_INAPPLICABLE_OPTION.createWithContext(p_121425_.getReader(), "name");
|
||||
} else {
|
||||
if (flag) {
|
||||
p_121425_.setHasNameNotEquals(true);
|
||||
} else {
|
||||
p_121425_.setHasNameEquals(true);
|
||||
}
|
||||
|
||||
p_121425_.addPredicate((p_175209_) -> {
|
||||
return p_175209_.getName().getString().equals(s) != flag;
|
||||
});
|
||||
}
|
||||
}, (p_121423_) -> {
|
||||
return !p_121423_.hasNameEquals();
|
||||
}, Component.translatable("argument.entity.options.name.description"));
|
||||
register("distance", (p_121421_) -> {
|
||||
int i = p_121421_.getReader().getCursor();
|
||||
MinMaxBounds.Doubles minmaxbounds$doubles = MinMaxBounds.Doubles.fromReader(p_121421_.getReader());
|
||||
if ((minmaxbounds$doubles.getMin() == null || !(minmaxbounds$doubles.getMin() < 0.0D)) && (minmaxbounds$doubles.getMax() == null || !(minmaxbounds$doubles.getMax() < 0.0D))) {
|
||||
p_121421_.setDistance(minmaxbounds$doubles);
|
||||
p_121421_.setWorldLimited();
|
||||
} else {
|
||||
p_121421_.getReader().setCursor(i);
|
||||
throw ERROR_RANGE_NEGATIVE.createWithContext(p_121421_.getReader());
|
||||
}
|
||||
}, (p_121419_) -> {
|
||||
return p_121419_.getDistance().isAny();
|
||||
}, Component.translatable("argument.entity.options.distance.description"));
|
||||
register("level", (p_121417_) -> {
|
||||
int i = p_121417_.getReader().getCursor();
|
||||
MinMaxBounds.Ints minmaxbounds$ints = MinMaxBounds.Ints.fromReader(p_121417_.getReader());
|
||||
if ((minmaxbounds$ints.getMin() == null || minmaxbounds$ints.getMin() >= 0) && (minmaxbounds$ints.getMax() == null || minmaxbounds$ints.getMax() >= 0)) {
|
||||
p_121417_.setLevel(minmaxbounds$ints);
|
||||
p_121417_.setIncludesEntities(false);
|
||||
} else {
|
||||
p_121417_.getReader().setCursor(i);
|
||||
throw ERROR_LEVEL_NEGATIVE.createWithContext(p_121417_.getReader());
|
||||
}
|
||||
}, (p_121415_) -> {
|
||||
return p_121415_.getLevel().isAny();
|
||||
}, Component.translatable("argument.entity.options.level.description"));
|
||||
register("x", (p_121413_) -> {
|
||||
p_121413_.setWorldLimited();
|
||||
p_121413_.setX(p_121413_.getReader().readDouble());
|
||||
}, (p_121411_) -> {
|
||||
return p_121411_.getX() == null;
|
||||
}, Component.translatable("argument.entity.options.x.description"));
|
||||
register("y", (p_121409_) -> {
|
||||
p_121409_.setWorldLimited();
|
||||
p_121409_.setY(p_121409_.getReader().readDouble());
|
||||
}, (p_121407_) -> {
|
||||
return p_121407_.getY() == null;
|
||||
}, Component.translatable("argument.entity.options.y.description"));
|
||||
register("z", (p_121405_) -> {
|
||||
p_121405_.setWorldLimited();
|
||||
p_121405_.setZ(p_121405_.getReader().readDouble());
|
||||
}, (p_121403_) -> {
|
||||
return p_121403_.getZ() == null;
|
||||
}, Component.translatable("argument.entity.options.z.description"));
|
||||
register("dx", (p_121401_) -> {
|
||||
p_121401_.setWorldLimited();
|
||||
p_121401_.setDeltaX(p_121401_.getReader().readDouble());
|
||||
}, (p_121399_) -> {
|
||||
return p_121399_.getDeltaX() == null;
|
||||
}, Component.translatable("argument.entity.options.dx.description"));
|
||||
register("dy", (p_121397_) -> {
|
||||
p_121397_.setWorldLimited();
|
||||
p_121397_.setDeltaY(p_121397_.getReader().readDouble());
|
||||
}, (p_121395_) -> {
|
||||
return p_121395_.getDeltaY() == null;
|
||||
}, Component.translatable("argument.entity.options.dy.description"));
|
||||
register("dz", (p_121562_) -> {
|
||||
p_121562_.setWorldLimited();
|
||||
p_121562_.setDeltaZ(p_121562_.getReader().readDouble());
|
||||
}, (p_121560_) -> {
|
||||
return p_121560_.getDeltaZ() == null;
|
||||
}, Component.translatable("argument.entity.options.dz.description"));
|
||||
register("x_rotation", (p_121558_) -> {
|
||||
p_121558_.setRotX(WrappedMinMaxBounds.fromReader(p_121558_.getReader(), true, Mth::wrapDegrees));
|
||||
}, (p_121556_) -> {
|
||||
return p_121556_.getRotX() == WrappedMinMaxBounds.ANY;
|
||||
}, Component.translatable("argument.entity.options.x_rotation.description"));
|
||||
register("y_rotation", (p_121554_) -> {
|
||||
p_121554_.setRotY(WrappedMinMaxBounds.fromReader(p_121554_.getReader(), true, Mth::wrapDegrees));
|
||||
}, (p_121552_) -> {
|
||||
return p_121552_.getRotY() == WrappedMinMaxBounds.ANY;
|
||||
}, Component.translatable("argument.entity.options.y_rotation.description"));
|
||||
register("limit", (p_121550_) -> {
|
||||
int i = p_121550_.getReader().getCursor();
|
||||
int j = p_121550_.getReader().readInt();
|
||||
if (j < 1) {
|
||||
p_121550_.getReader().setCursor(i);
|
||||
throw ERROR_LIMIT_TOO_SMALL.createWithContext(p_121550_.getReader());
|
||||
} else {
|
||||
p_121550_.setMaxResults(j);
|
||||
p_121550_.setLimited(true);
|
||||
}
|
||||
}, (p_121548_) -> {
|
||||
return !p_121548_.isCurrentEntity() && !p_121548_.isLimited();
|
||||
}, Component.translatable("argument.entity.options.limit.description"));
|
||||
register("sort", (p_247983_) -> {
|
||||
int i = p_247983_.getReader().getCursor();
|
||||
String s = p_247983_.getReader().readUnquotedString();
|
||||
p_247983_.setSuggestions((p_175153_, p_175154_) -> {
|
||||
return SharedSuggestionProvider.suggest(Arrays.asList("nearest", "furthest", "random", "arbitrary"), p_175153_);
|
||||
});
|
||||
BiConsumer biconsumer;
|
||||
switch (s) {
|
||||
case "nearest":
|
||||
biconsumer = EntitySelectorParser.ORDER_NEAREST;
|
||||
break;
|
||||
case "furthest":
|
||||
biconsumer = EntitySelectorParser.ORDER_FURTHEST;
|
||||
break;
|
||||
case "random":
|
||||
biconsumer = EntitySelectorParser.ORDER_RANDOM;
|
||||
break;
|
||||
case "arbitrary":
|
||||
biconsumer = EntitySelector.ORDER_ARBITRARY;
|
||||
break;
|
||||
default:
|
||||
p_247983_.getReader().setCursor(i);
|
||||
throw ERROR_SORT_UNKNOWN.createWithContext(p_247983_.getReader(), s);
|
||||
}
|
||||
|
||||
p_247983_.setOrder(biconsumer);
|
||||
p_247983_.setSorted(true);
|
||||
}, (p_121544_) -> {
|
||||
return !p_121544_.isCurrentEntity() && !p_121544_.isSorted();
|
||||
}, Component.translatable("argument.entity.options.sort.description"));
|
||||
register("gamemode", (p_121542_) -> {
|
||||
p_121542_.setSuggestions((p_175193_, p_175194_) -> {
|
||||
String s1 = p_175193_.getRemaining().toLowerCase(Locale.ROOT);
|
||||
boolean flag1 = !p_121542_.hasGamemodeNotEquals();
|
||||
boolean flag2 = true;
|
||||
if (!s1.isEmpty()) {
|
||||
if (s1.charAt(0) == '!') {
|
||||
flag1 = false;
|
||||
s1 = s1.substring(1);
|
||||
} else {
|
||||
flag2 = false;
|
||||
}
|
||||
}
|
||||
|
||||
for(GameType gametype1 : GameType.values()) {
|
||||
if (gametype1.getName().toLowerCase(Locale.ROOT).startsWith(s1)) {
|
||||
if (flag2) {
|
||||
p_175193_.suggest("!" + gametype1.getName());
|
||||
}
|
||||
|
||||
if (flag1) {
|
||||
p_175193_.suggest(gametype1.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return p_175193_.buildFuture();
|
||||
});
|
||||
int i = p_121542_.getReader().getCursor();
|
||||
boolean flag = p_121542_.shouldInvertValue();
|
||||
if (p_121542_.hasGamemodeNotEquals() && !flag) {
|
||||
p_121542_.getReader().setCursor(i);
|
||||
throw ERROR_INAPPLICABLE_OPTION.createWithContext(p_121542_.getReader(), "gamemode");
|
||||
} else {
|
||||
String s = p_121542_.getReader().readUnquotedString();
|
||||
GameType gametype = GameType.byName(s, (GameType)null);
|
||||
if (gametype == null) {
|
||||
p_121542_.getReader().setCursor(i);
|
||||
throw ERROR_GAME_MODE_INVALID.createWithContext(p_121542_.getReader(), s);
|
||||
} else {
|
||||
p_121542_.setIncludesEntities(false);
|
||||
p_121542_.addPredicate((p_175190_) -> {
|
||||
if (!(p_175190_ instanceof ServerPlayer)) {
|
||||
return false;
|
||||
} else {
|
||||
GameType gametype1 = ((ServerPlayer)p_175190_).gameMode.getGameModeForPlayer();
|
||||
return flag ? gametype1 != gametype : gametype1 == gametype;
|
||||
}
|
||||
});
|
||||
if (flag) {
|
||||
p_121542_.setHasGamemodeNotEquals(true);
|
||||
} else {
|
||||
p_121542_.setHasGamemodeEquals(true);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}, (p_121540_) -> {
|
||||
return !p_121540_.hasGamemodeEquals();
|
||||
}, Component.translatable("argument.entity.options.gamemode.description"));
|
||||
register("team", (p_121538_) -> {
|
||||
boolean flag = p_121538_.shouldInvertValue();
|
||||
String s = p_121538_.getReader().readUnquotedString();
|
||||
p_121538_.addPredicate((p_175198_) -> {
|
||||
if (!(p_175198_ instanceof LivingEntity)) {
|
||||
return false;
|
||||
} else {
|
||||
Team team = p_175198_.getTeam();
|
||||
String s1 = team == null ? "" : team.getName();
|
||||
return s1.equals(s) != flag;
|
||||
}
|
||||
});
|
||||
if (flag) {
|
||||
p_121538_.setHasTeamNotEquals(true);
|
||||
} else {
|
||||
p_121538_.setHasTeamEquals(true);
|
||||
}
|
||||
|
||||
}, (p_121536_) -> {
|
||||
return !p_121536_.hasTeamEquals();
|
||||
}, Component.translatable("argument.entity.options.team.description"));
|
||||
register("type", (p_121534_) -> {
|
||||
p_121534_.setSuggestions((p_258162_, p_258163_) -> {
|
||||
SharedSuggestionProvider.suggestResource(BuiltInRegistries.ENTITY_TYPE.keySet(), p_258162_, String.valueOf('!'));
|
||||
SharedSuggestionProvider.suggestResource(BuiltInRegistries.ENTITY_TYPE.getTagNames().map(TagKey::location), p_258162_, "!#");
|
||||
if (!p_121534_.isTypeLimitedInversely()) {
|
||||
SharedSuggestionProvider.suggestResource(BuiltInRegistries.ENTITY_TYPE.keySet(), p_258162_);
|
||||
SharedSuggestionProvider.suggestResource(BuiltInRegistries.ENTITY_TYPE.getTagNames().map(TagKey::location), p_258162_, String.valueOf('#'));
|
||||
}
|
||||
|
||||
return p_258162_.buildFuture();
|
||||
});
|
||||
int i = p_121534_.getReader().getCursor();
|
||||
boolean flag = p_121534_.shouldInvertValue();
|
||||
if (p_121534_.isTypeLimitedInversely() && !flag) {
|
||||
p_121534_.getReader().setCursor(i);
|
||||
throw ERROR_INAPPLICABLE_OPTION.createWithContext(p_121534_.getReader(), "type");
|
||||
} else {
|
||||
if (flag) {
|
||||
p_121534_.setTypeLimitedInversely();
|
||||
}
|
||||
|
||||
if (p_121534_.isTag()) {
|
||||
TagKey<EntityType<?>> tagkey = TagKey.create(Registries.ENTITY_TYPE, ResourceLocation.read(p_121534_.getReader()));
|
||||
p_121534_.addPredicate((p_205691_) -> {
|
||||
return p_205691_.getType().is(tagkey) != flag;
|
||||
});
|
||||
} else {
|
||||
ResourceLocation resourcelocation = ResourceLocation.read(p_121534_.getReader());
|
||||
EntityType<?> entitytype = BuiltInRegistries.ENTITY_TYPE.getOptional(resourcelocation).orElseThrow(() -> {
|
||||
p_121534_.getReader().setCursor(i);
|
||||
return ERROR_ENTITY_TYPE_INVALID.createWithContext(p_121534_.getReader(), resourcelocation.toString());
|
||||
});
|
||||
if (Objects.equals(EntityType.PLAYER, entitytype) && !flag) {
|
||||
p_121534_.setIncludesEntities(false);
|
||||
}
|
||||
|
||||
p_121534_.addPredicate((p_175151_) -> {
|
||||
return Objects.equals(entitytype, p_175151_.getType()) != flag;
|
||||
});
|
||||
if (!flag) {
|
||||
p_121534_.limitToType(entitytype);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}, (p_121532_) -> {
|
||||
return !p_121532_.isTypeLimited();
|
||||
}, Component.translatable("argument.entity.options.type.description"));
|
||||
register("tag", (p_121530_) -> {
|
||||
boolean flag = p_121530_.shouldInvertValue();
|
||||
String s = p_121530_.getReader().readUnquotedString();
|
||||
p_121530_.addPredicate((p_175166_) -> {
|
||||
if ("".equals(s)) {
|
||||
return p_175166_.getTags().isEmpty() != flag;
|
||||
} else {
|
||||
return p_175166_.getTags().contains(s) != flag;
|
||||
}
|
||||
});
|
||||
}, (p_121528_) -> {
|
||||
return true;
|
||||
}, Component.translatable("argument.entity.options.tag.description"));
|
||||
register("nbt", (p_121526_) -> {
|
||||
boolean flag = p_121526_.shouldInvertValue();
|
||||
CompoundTag compoundtag = (new TagParser(p_121526_.getReader())).readStruct();
|
||||
p_121526_.addPredicate((p_175176_) -> {
|
||||
CompoundTag compoundtag1 = p_175176_.saveWithoutId(new CompoundTag());
|
||||
if (p_175176_ instanceof ServerPlayer) {
|
||||
ItemStack itemstack = ((ServerPlayer)p_175176_).getInventory().getSelected();
|
||||
if (!itemstack.isEmpty()) {
|
||||
compoundtag1.put("SelectedItem", itemstack.save(new CompoundTag()));
|
||||
}
|
||||
}
|
||||
|
||||
return NbtUtils.compareNbt(compoundtag, compoundtag1, true) != flag;
|
||||
});
|
||||
}, (p_121524_) -> {
|
||||
return true;
|
||||
}, Component.translatable("argument.entity.options.nbt.description"));
|
||||
register("scores", (p_121522_) -> {
|
||||
StringReader stringreader = p_121522_.getReader();
|
||||
Map<String, MinMaxBounds.Ints> map = Maps.newHashMap();
|
||||
stringreader.expect('{');
|
||||
stringreader.skipWhitespace();
|
||||
|
||||
while(stringreader.canRead() && stringreader.peek() != '}') {
|
||||
stringreader.skipWhitespace();
|
||||
String s = stringreader.readUnquotedString();
|
||||
stringreader.skipWhitespace();
|
||||
stringreader.expect('=');
|
||||
stringreader.skipWhitespace();
|
||||
MinMaxBounds.Ints minmaxbounds$ints = MinMaxBounds.Ints.fromReader(stringreader);
|
||||
map.put(s, minmaxbounds$ints);
|
||||
stringreader.skipWhitespace();
|
||||
if (stringreader.canRead() && stringreader.peek() == ',') {
|
||||
stringreader.skip();
|
||||
}
|
||||
}
|
||||
|
||||
stringreader.expect('}');
|
||||
if (!map.isEmpty()) {
|
||||
p_121522_.addPredicate((p_175201_) -> {
|
||||
Scoreboard scoreboard = p_175201_.getServer().getScoreboard();
|
||||
String s1 = p_175201_.getScoreboardName();
|
||||
|
||||
for(Map.Entry<String, MinMaxBounds.Ints> entry : map.entrySet()) {
|
||||
Objective objective = scoreboard.getObjective(entry.getKey());
|
||||
if (objective == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!scoreboard.hasPlayerScore(s1, objective)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Score score = scoreboard.getOrCreatePlayerScore(s1, objective);
|
||||
int i = score.getScore();
|
||||
if (!entry.getValue().matches(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
p_121522_.setHasScores(true);
|
||||
}, (p_121518_) -> {
|
||||
return !p_121518_.hasScores();
|
||||
}, Component.translatable("argument.entity.options.scores.description"));
|
||||
register("advancements", (p_121514_) -> {
|
||||
StringReader stringreader = p_121514_.getReader();
|
||||
Map<ResourceLocation, Predicate<AdvancementProgress>> map = Maps.newHashMap();
|
||||
stringreader.expect('{');
|
||||
stringreader.skipWhitespace();
|
||||
|
||||
while(stringreader.canRead() && stringreader.peek() != '}') {
|
||||
stringreader.skipWhitespace();
|
||||
ResourceLocation resourcelocation = ResourceLocation.read(stringreader);
|
||||
stringreader.skipWhitespace();
|
||||
stringreader.expect('=');
|
||||
stringreader.skipWhitespace();
|
||||
if (stringreader.canRead() && stringreader.peek() == '{') {
|
||||
Map<String, Predicate<CriterionProgress>> map1 = Maps.newHashMap();
|
||||
stringreader.skipWhitespace();
|
||||
stringreader.expect('{');
|
||||
stringreader.skipWhitespace();
|
||||
|
||||
while(stringreader.canRead() && stringreader.peek() != '}') {
|
||||
stringreader.skipWhitespace();
|
||||
String s = stringreader.readUnquotedString();
|
||||
stringreader.skipWhitespace();
|
||||
stringreader.expect('=');
|
||||
stringreader.skipWhitespace();
|
||||
boolean flag1 = stringreader.readBoolean();
|
||||
map1.put(s, (p_175186_) -> {
|
||||
return p_175186_.isDone() == flag1;
|
||||
});
|
||||
stringreader.skipWhitespace();
|
||||
if (stringreader.canRead() && stringreader.peek() == ',') {
|
||||
stringreader.skip();
|
||||
}
|
||||
}
|
||||
|
||||
stringreader.skipWhitespace();
|
||||
stringreader.expect('}');
|
||||
stringreader.skipWhitespace();
|
||||
map.put(resourcelocation, (p_175169_) -> {
|
||||
for(Map.Entry<String, Predicate<CriterionProgress>> entry : map1.entrySet()) {
|
||||
CriterionProgress criterionprogress = p_175169_.getCriterion(entry.getKey());
|
||||
if (criterionprogress == null || !entry.getValue().test(criterionprogress)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
} else {
|
||||
boolean flag = stringreader.readBoolean();
|
||||
map.put(resourcelocation, (p_175183_) -> {
|
||||
return p_175183_.isDone() == flag;
|
||||
});
|
||||
}
|
||||
|
||||
stringreader.skipWhitespace();
|
||||
if (stringreader.canRead() && stringreader.peek() == ',') {
|
||||
stringreader.skip();
|
||||
}
|
||||
}
|
||||
|
||||
stringreader.expect('}');
|
||||
if (!map.isEmpty()) {
|
||||
p_121514_.addPredicate((p_175172_) -> {
|
||||
if (!(p_175172_ instanceof ServerPlayer serverplayer)) {
|
||||
return false;
|
||||
} else {
|
||||
PlayerAdvancements playeradvancements = serverplayer.getAdvancements();
|
||||
ServerAdvancementManager serveradvancementmanager = serverplayer.getServer().getAdvancements();
|
||||
|
||||
for(Map.Entry<ResourceLocation, Predicate<AdvancementProgress>> entry : map.entrySet()) {
|
||||
Advancement advancement = serveradvancementmanager.getAdvancement(entry.getKey());
|
||||
if (advancement == null || !entry.getValue().test(playeradvancements.getOrStartProgress(advancement))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
});
|
||||
p_121514_.setIncludesEntities(false);
|
||||
}
|
||||
|
||||
p_121514_.setHasAdvancements(true);
|
||||
}, (p_121506_) -> {
|
||||
return !p_121506_.hasAdvancements();
|
||||
}, Component.translatable("argument.entity.options.advancements.description"));
|
||||
register("predicate", (p_121487_) -> {
|
||||
boolean flag = p_121487_.shouldInvertValue();
|
||||
ResourceLocation resourcelocation = ResourceLocation.read(p_121487_.getReader());
|
||||
p_121487_.addPredicate((p_287325_) -> {
|
||||
if (!(p_287325_.level() instanceof ServerLevel)) {
|
||||
return false;
|
||||
} else {
|
||||
ServerLevel serverlevel = (ServerLevel)p_287325_.level();
|
||||
LootItemCondition lootitemcondition = serverlevel.getServer().getLootData().getElement(LootDataType.PREDICATE, resourcelocation);
|
||||
if (lootitemcondition == null) {
|
||||
return false;
|
||||
} else {
|
||||
LootParams lootparams = (new LootParams.Builder(serverlevel)).withParameter(LootContextParams.THIS_ENTITY, p_287325_).withParameter(LootContextParams.ORIGIN, p_287325_.position()).create(LootContextParamSets.SELECTOR);
|
||||
LootContext lootcontext = (new LootContext.Builder(lootparams)).create((ResourceLocation)null);
|
||||
lootcontext.pushVisitedElement(LootContext.createVisitedEntry(lootitemcondition));
|
||||
return flag ^ lootitemcondition.test(lootcontext);
|
||||
}
|
||||
}
|
||||
});
|
||||
}, (p_121435_) -> {
|
||||
return true;
|
||||
}, Component.translatable("argument.entity.options.predicate.description"));
|
||||
}
|
||||
}
|
||||
|
||||
public static EntitySelectorOptions.Modifier get(EntitySelectorParser pParser, String pId, int pCursor) throws CommandSyntaxException {
|
||||
EntitySelectorOptions.Option entityselectoroptions$option = OPTIONS.get(pId);
|
||||
if (entityselectoroptions$option != null) {
|
||||
if (entityselectoroptions$option.canUse.test(pParser)) {
|
||||
return entityselectoroptions$option.modifier;
|
||||
} else {
|
||||
throw ERROR_INAPPLICABLE_OPTION.createWithContext(pParser.getReader(), pId);
|
||||
}
|
||||
} else {
|
||||
pParser.getReader().setCursor(pCursor);
|
||||
throw ERROR_UNKNOWN_OPTION.createWithContext(pParser.getReader(), pId);
|
||||
}
|
||||
}
|
||||
|
||||
public static void suggestNames(EntitySelectorParser pParser, SuggestionsBuilder pBuilder) {
|
||||
String s = pBuilder.getRemaining().toLowerCase(Locale.ROOT);
|
||||
|
||||
for(Map.Entry<String, EntitySelectorOptions.Option> entry : OPTIONS.entrySet()) {
|
||||
if ((entry.getValue()).canUse.test(pParser) && entry.getKey().toLowerCase(Locale.ROOT).startsWith(s)) {
|
||||
pBuilder.suggest((String)entry.getKey() + "=", (entry.getValue()).description);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public interface Modifier {
|
||||
void handle(EntitySelectorParser pParser) throws CommandSyntaxException;
|
||||
}
|
||||
|
||||
static record Option(EntitySelectorOptions.Modifier modifier, Predicate<EntitySelectorParser> canUse, Component description) {
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
@FieldsAreNonnullByDefault
|
||||
package net.minecraft.commands.arguments.selector.options;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.FieldsAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
@FieldsAreNonnullByDefault
|
||||
package net.minecraft.commands.arguments.selector;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.FieldsAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
@FieldsAreNonnullByDefault
|
||||
package net.minecraft.commands;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.FieldsAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package net.minecraft.commands.synchronization;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
|
||||
public interface ArgumentTypeInfo<A extends ArgumentType<?>, T extends ArgumentTypeInfo.Template<A>> {
|
||||
void serializeToNetwork(T pTemplate, FriendlyByteBuf pBuffer);
|
||||
|
||||
T deserializeFromNetwork(FriendlyByteBuf pBuffer);
|
||||
|
||||
void serializeToJson(T pTemplate, JsonObject pJson);
|
||||
|
||||
T unpack(A pArgument);
|
||||
|
||||
public interface Template<A extends ArgumentType<?>> {
|
||||
A instantiate(CommandBuildContext pContext);
|
||||
|
||||
ArgumentTypeInfo<A, ?> type();
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
package net.minecraft.commands.synchronization;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.arguments.BoolArgumentType;
|
||||
import com.mojang.brigadier.arguments.DoubleArgumentType;
|
||||
import com.mojang.brigadier.arguments.FloatArgumentType;
|
||||
import com.mojang.brigadier.arguments.IntegerArgumentType;
|
||||
import com.mojang.brigadier.arguments.LongArgumentType;
|
||||
import com.mojang.brigadier.arguments.StringArgumentType;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.commands.arguments.AngleArgument;
|
||||
import net.minecraft.commands.arguments.ColorArgument;
|
||||
import net.minecraft.commands.arguments.ComponentArgument;
|
||||
import net.minecraft.commands.arguments.CompoundTagArgument;
|
||||
import net.minecraft.commands.arguments.DimensionArgument;
|
||||
import net.minecraft.commands.arguments.EntityAnchorArgument;
|
||||
import net.minecraft.commands.arguments.EntityArgument;
|
||||
import net.minecraft.commands.arguments.GameModeArgument;
|
||||
import net.minecraft.commands.arguments.GameProfileArgument;
|
||||
import net.minecraft.commands.arguments.HeightmapTypeArgument;
|
||||
import net.minecraft.commands.arguments.MessageArgument;
|
||||
import net.minecraft.commands.arguments.NbtPathArgument;
|
||||
import net.minecraft.commands.arguments.NbtTagArgument;
|
||||
import net.minecraft.commands.arguments.ObjectiveArgument;
|
||||
import net.minecraft.commands.arguments.ObjectiveCriteriaArgument;
|
||||
import net.minecraft.commands.arguments.OperationArgument;
|
||||
import net.minecraft.commands.arguments.ParticleArgument;
|
||||
import net.minecraft.commands.arguments.RangeArgument;
|
||||
import net.minecraft.commands.arguments.ResourceArgument;
|
||||
import net.minecraft.commands.arguments.ResourceKeyArgument;
|
||||
import net.minecraft.commands.arguments.ResourceLocationArgument;
|
||||
import net.minecraft.commands.arguments.ResourceOrTagArgument;
|
||||
import net.minecraft.commands.arguments.ResourceOrTagKeyArgument;
|
||||
import net.minecraft.commands.arguments.ScoreHolderArgument;
|
||||
import net.minecraft.commands.arguments.ScoreboardSlotArgument;
|
||||
import net.minecraft.commands.arguments.SlotArgument;
|
||||
import net.minecraft.commands.arguments.TeamArgument;
|
||||
import net.minecraft.commands.arguments.TemplateMirrorArgument;
|
||||
import net.minecraft.commands.arguments.TemplateRotationArgument;
|
||||
import net.minecraft.commands.arguments.TimeArgument;
|
||||
import net.minecraft.commands.arguments.UuidArgument;
|
||||
import net.minecraft.commands.arguments.blocks.BlockPredicateArgument;
|
||||
import net.minecraft.commands.arguments.blocks.BlockStateArgument;
|
||||
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
|
||||
import net.minecraft.commands.arguments.coordinates.ColumnPosArgument;
|
||||
import net.minecraft.commands.arguments.coordinates.RotationArgument;
|
||||
import net.minecraft.commands.arguments.coordinates.SwizzleArgument;
|
||||
import net.minecraft.commands.arguments.coordinates.Vec2Argument;
|
||||
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
|
||||
import net.minecraft.commands.arguments.item.FunctionArgument;
|
||||
import net.minecraft.commands.arguments.item.ItemArgument;
|
||||
import net.minecraft.commands.arguments.item.ItemPredicateArgument;
|
||||
import net.minecraft.commands.synchronization.brigadier.DoubleArgumentInfo;
|
||||
import net.minecraft.commands.synchronization.brigadier.FloatArgumentInfo;
|
||||
import net.minecraft.commands.synchronization.brigadier.IntegerArgumentInfo;
|
||||
import net.minecraft.commands.synchronization.brigadier.LongArgumentInfo;
|
||||
import net.minecraft.commands.synchronization.brigadier.StringArgumentSerializer;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.gametest.framework.TestClassNameArgument;
|
||||
import net.minecraft.gametest.framework.TestFunctionArgument;
|
||||
|
||||
public class ArgumentTypeInfos {
|
||||
private static final Map<Class<?>, ArgumentTypeInfo<?, ?>> BY_CLASS = Maps.newHashMap();
|
||||
|
||||
/**
|
||||
* Forge: Use this in conjunction with a
|
||||
* {@link net.minecraftforge.registries.DeferredRegister#register(String, java.util.function.Supplier) DeferredRegister#register(String, Supplier)}
|
||||
* call to both populate the {@code BY_CLASS} map and register the argument type info so it can be used in commands.
|
||||
*
|
||||
* @param infoClass the class type of the argument type info
|
||||
* @param argumentTypeInfo the argument type info instance
|
||||
* @return the provided argument type info instance for chaining
|
||||
*/
|
||||
public static synchronized <A extends ArgumentType<?>, T extends ArgumentTypeInfo.Template<A>, I extends ArgumentTypeInfo<A, T>> I registerByClass(Class<A> infoClass, I argumentTypeInfo) {
|
||||
BY_CLASS.put(infoClass, argumentTypeInfo);
|
||||
return argumentTypeInfo;
|
||||
}
|
||||
|
||||
private static <A extends ArgumentType<?>, T extends ArgumentTypeInfo.Template<A>> ArgumentTypeInfo<A, T> register(Registry<ArgumentTypeInfo<?, ?>> pRegistry, String pId, Class<? extends A> pArgumentClass, ArgumentTypeInfo<A, T> pInfo) {
|
||||
BY_CLASS.put(pArgumentClass, pInfo);
|
||||
return Registry.register(pRegistry, pId, pInfo);
|
||||
}
|
||||
|
||||
public static ArgumentTypeInfo<?, ?> bootstrap(Registry<ArgumentTypeInfo<?, ?>> pRegistry) {
|
||||
register(pRegistry, "brigadier:bool", BoolArgumentType.class, SingletonArgumentInfo.contextFree(BoolArgumentType::bool));
|
||||
register(pRegistry, "brigadier:float", FloatArgumentType.class, new FloatArgumentInfo());
|
||||
register(pRegistry, "brigadier:double", DoubleArgumentType.class, new DoubleArgumentInfo());
|
||||
register(pRegistry, "brigadier:integer", IntegerArgumentType.class, new IntegerArgumentInfo());
|
||||
register(pRegistry, "brigadier:long", LongArgumentType.class, new LongArgumentInfo());
|
||||
register(pRegistry, "brigadier:string", StringArgumentType.class, new StringArgumentSerializer());
|
||||
register(pRegistry, "entity", EntityArgument.class, new EntityArgument.Info());
|
||||
register(pRegistry, "game_profile", GameProfileArgument.class, SingletonArgumentInfo.contextFree(GameProfileArgument::gameProfile));
|
||||
register(pRegistry, "block_pos", BlockPosArgument.class, SingletonArgumentInfo.contextFree(BlockPosArgument::blockPos));
|
||||
register(pRegistry, "column_pos", ColumnPosArgument.class, SingletonArgumentInfo.contextFree(ColumnPosArgument::columnPos));
|
||||
register(pRegistry, "vec3", Vec3Argument.class, SingletonArgumentInfo.contextFree(Vec3Argument::vec3));
|
||||
register(pRegistry, "vec2", Vec2Argument.class, SingletonArgumentInfo.contextFree(Vec2Argument::vec2));
|
||||
register(pRegistry, "block_state", BlockStateArgument.class, SingletonArgumentInfo.contextAware(BlockStateArgument::block));
|
||||
register(pRegistry, "block_predicate", BlockPredicateArgument.class, SingletonArgumentInfo.contextAware(BlockPredicateArgument::blockPredicate));
|
||||
register(pRegistry, "item_stack", ItemArgument.class, SingletonArgumentInfo.contextAware(ItemArgument::item));
|
||||
register(pRegistry, "item_predicate", ItemPredicateArgument.class, SingletonArgumentInfo.contextAware(ItemPredicateArgument::itemPredicate));
|
||||
register(pRegistry, "color", ColorArgument.class, SingletonArgumentInfo.contextFree(ColorArgument::color));
|
||||
register(pRegistry, "component", ComponentArgument.class, SingletonArgumentInfo.contextFree(ComponentArgument::textComponent));
|
||||
register(pRegistry, "message", MessageArgument.class, SingletonArgumentInfo.contextFree(MessageArgument::message));
|
||||
register(pRegistry, "nbt_compound_tag", CompoundTagArgument.class, SingletonArgumentInfo.contextFree(CompoundTagArgument::compoundTag));
|
||||
register(pRegistry, "nbt_tag", NbtTagArgument.class, SingletonArgumentInfo.contextFree(NbtTagArgument::nbtTag));
|
||||
register(pRegistry, "nbt_path", NbtPathArgument.class, SingletonArgumentInfo.contextFree(NbtPathArgument::nbtPath));
|
||||
register(pRegistry, "objective", ObjectiveArgument.class, SingletonArgumentInfo.contextFree(ObjectiveArgument::objective));
|
||||
register(pRegistry, "objective_criteria", ObjectiveCriteriaArgument.class, SingletonArgumentInfo.contextFree(ObjectiveCriteriaArgument::criteria));
|
||||
register(pRegistry, "operation", OperationArgument.class, SingletonArgumentInfo.contextFree(OperationArgument::operation));
|
||||
register(pRegistry, "particle", ParticleArgument.class, SingletonArgumentInfo.contextAware(ParticleArgument::particle));
|
||||
register(pRegistry, "angle", AngleArgument.class, SingletonArgumentInfo.contextFree(AngleArgument::angle));
|
||||
register(pRegistry, "rotation", RotationArgument.class, SingletonArgumentInfo.contextFree(RotationArgument::rotation));
|
||||
register(pRegistry, "scoreboard_slot", ScoreboardSlotArgument.class, SingletonArgumentInfo.contextFree(ScoreboardSlotArgument::displaySlot));
|
||||
register(pRegistry, "score_holder", ScoreHolderArgument.class, new ScoreHolderArgument.Info());
|
||||
register(pRegistry, "swizzle", SwizzleArgument.class, SingletonArgumentInfo.contextFree(SwizzleArgument::swizzle));
|
||||
register(pRegistry, "team", TeamArgument.class, SingletonArgumentInfo.contextFree(TeamArgument::team));
|
||||
register(pRegistry, "item_slot", SlotArgument.class, SingletonArgumentInfo.contextFree(SlotArgument::slot));
|
||||
register(pRegistry, "resource_location", ResourceLocationArgument.class, SingletonArgumentInfo.contextFree(ResourceLocationArgument::id));
|
||||
register(pRegistry, "function", FunctionArgument.class, SingletonArgumentInfo.contextFree(FunctionArgument::functions));
|
||||
register(pRegistry, "entity_anchor", EntityAnchorArgument.class, SingletonArgumentInfo.contextFree(EntityAnchorArgument::anchor));
|
||||
register(pRegistry, "int_range", RangeArgument.Ints.class, SingletonArgumentInfo.contextFree(RangeArgument::intRange));
|
||||
register(pRegistry, "float_range", RangeArgument.Floats.class, SingletonArgumentInfo.contextFree(RangeArgument::floatRange));
|
||||
register(pRegistry, "dimension", DimensionArgument.class, SingletonArgumentInfo.contextFree(DimensionArgument::dimension));
|
||||
register(pRegistry, "gamemode", GameModeArgument.class, SingletonArgumentInfo.contextFree(GameModeArgument::gameMode));
|
||||
register(pRegistry, "time", TimeArgument.class, new TimeArgument.Info());
|
||||
register(pRegistry, "resource_or_tag", fixClassType(ResourceOrTagArgument.class), new ResourceOrTagArgument.Info<Object>());
|
||||
register(pRegistry, "resource_or_tag_key", fixClassType(ResourceOrTagKeyArgument.class), new ResourceOrTagKeyArgument.Info<Object>());
|
||||
register(pRegistry, "resource", fixClassType(ResourceArgument.class), new ResourceArgument.Info<Object>());
|
||||
register(pRegistry, "resource_key", fixClassType(ResourceKeyArgument.class), new ResourceKeyArgument.Info<Object>());
|
||||
register(pRegistry, "template_mirror", TemplateMirrorArgument.class, SingletonArgumentInfo.contextFree(TemplateMirrorArgument::templateMirror));
|
||||
register(pRegistry, "template_rotation", TemplateRotationArgument.class, SingletonArgumentInfo.contextFree(TemplateRotationArgument::templateRotation));
|
||||
register(pRegistry, "heightmap", HeightmapTypeArgument.class, SingletonArgumentInfo.contextFree(HeightmapTypeArgument::heightmap));
|
||||
// Forge: Register before gametest arguments to provide forge server <-> vanilla client interop and matching int ids
|
||||
var uuidInfo = register(pRegistry, "uuid", UuidArgument.class, SingletonArgumentInfo.contextFree(UuidArgument::uuid));
|
||||
if (true) { // Forge: Always register gametest arguments to prevent issues when connecting from gametest-enabled client/server to non-gametest-enabled client/server
|
||||
register(pRegistry, "test_argument", TestFunctionArgument.class, SingletonArgumentInfo.contextFree(TestFunctionArgument::testFunctionArgument));
|
||||
register(pRegistry, "test_class", TestClassNameArgument.class, SingletonArgumentInfo.contextFree(TestClassNameArgument::testClassName));
|
||||
}
|
||||
|
||||
return uuidInfo;
|
||||
}
|
||||
|
||||
private static <T extends ArgumentType<?>> Class<T> fixClassType(Class<? super T> pType) {
|
||||
return (Class<T>)pType;
|
||||
}
|
||||
|
||||
public static boolean isClassRecognized(Class<?> pClazz) {
|
||||
return BY_CLASS.containsKey(pClazz);
|
||||
}
|
||||
|
||||
public static <A extends ArgumentType<?>> ArgumentTypeInfo<A, ?> byClass(A pArgument) {
|
||||
ArgumentTypeInfo<?, ?> argumenttypeinfo = BY_CLASS.get(pArgument.getClass());
|
||||
if (argumenttypeinfo == null) {
|
||||
throw new IllegalArgumentException(String.format(Locale.ROOT, "Unrecognized argument type %s (%s)", pArgument, pArgument.getClass()));
|
||||
} else {
|
||||
return (ArgumentTypeInfo<A, ?>)argumenttypeinfo;
|
||||
}
|
||||
}
|
||||
|
||||
public static <A extends ArgumentType<?>> ArgumentTypeInfo.Template<A> unpack(A pArgument) {
|
||||
return byClass(pArgument).unpack(pArgument);
|
||||
}
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
package net.minecraft.commands.synchronization;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.CommandDispatcher;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.tree.ArgumentCommandNode;
|
||||
import com.mojang.brigadier.tree.CommandNode;
|
||||
import com.mojang.brigadier.tree.LiteralCommandNode;
|
||||
import com.mojang.brigadier.tree.RootCommandNode;
|
||||
import com.mojang.logging.LogUtils;
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
public class ArgumentUtils {
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
private static final byte NUMBER_FLAG_MIN = 1;
|
||||
private static final byte NUMBER_FLAG_MAX = 2;
|
||||
|
||||
public static int createNumberFlags(boolean pMin, boolean pMax) {
|
||||
int i = 0;
|
||||
if (pMin) {
|
||||
i |= 1;
|
||||
}
|
||||
|
||||
if (pMax) {
|
||||
i |= 2;
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
public static boolean numberHasMin(byte pNumber) {
|
||||
return (pNumber & 1) != 0;
|
||||
}
|
||||
|
||||
public static boolean numberHasMax(byte pNumber) {
|
||||
return (pNumber & 2) != 0;
|
||||
}
|
||||
|
||||
private static <A extends ArgumentType<?>> void serializeCap(JsonObject pJson, ArgumentTypeInfo.Template<A> pTemplate) {
|
||||
serializeCap(pJson, pTemplate.type(), pTemplate);
|
||||
}
|
||||
|
||||
private static <A extends ArgumentType<?>, T extends ArgumentTypeInfo.Template<A>> void serializeCap(JsonObject pJson, ArgumentTypeInfo<A, T> pArgumentTypeInfo, ArgumentTypeInfo.Template<A> pTemplate) {
|
||||
pArgumentTypeInfo.serializeToJson((T)pTemplate, pJson);
|
||||
}
|
||||
|
||||
private static <T extends ArgumentType<?>> void serializeArgumentToJson(JsonObject pJson, T pType) {
|
||||
ArgumentTypeInfo.Template<T> template = ArgumentTypeInfos.unpack(pType);
|
||||
pJson.addProperty("type", "argument");
|
||||
pJson.addProperty("parser", BuiltInRegistries.COMMAND_ARGUMENT_TYPE.getKey(template.type()).toString());
|
||||
JsonObject jsonobject = new JsonObject();
|
||||
serializeCap(jsonobject, template);
|
||||
if (jsonobject.size() > 0) {
|
||||
pJson.add("properties", jsonobject);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static <S> JsonObject serializeNodeToJson(CommandDispatcher<S> pDispatcher, CommandNode<S> pNode) {
|
||||
JsonObject jsonobject = new JsonObject();
|
||||
if (pNode instanceof RootCommandNode) {
|
||||
jsonobject.addProperty("type", "root");
|
||||
} else if (pNode instanceof LiteralCommandNode) {
|
||||
jsonobject.addProperty("type", "literal");
|
||||
} else if (pNode instanceof ArgumentCommandNode) {
|
||||
ArgumentCommandNode<?, ?> argumentcommandnode = (ArgumentCommandNode)pNode;
|
||||
serializeArgumentToJson(jsonobject, argumentcommandnode.getType());
|
||||
} else {
|
||||
LOGGER.error("Could not serialize node {} ({})!", pNode, pNode.getClass());
|
||||
jsonobject.addProperty("type", "unknown");
|
||||
}
|
||||
|
||||
JsonObject jsonobject1 = new JsonObject();
|
||||
|
||||
for(CommandNode<S> commandnode : pNode.getChildren()) {
|
||||
jsonobject1.add(commandnode.getName(), serializeNodeToJson(pDispatcher, commandnode));
|
||||
}
|
||||
|
||||
if (jsonobject1.size() > 0) {
|
||||
jsonobject.add("children", jsonobject1);
|
||||
}
|
||||
|
||||
if (pNode.getCommand() != null) {
|
||||
jsonobject.addProperty("executable", true);
|
||||
}
|
||||
|
||||
if (pNode.getRedirect() != null) {
|
||||
Collection<String> collection = pDispatcher.getPath(pNode.getRedirect());
|
||||
if (!collection.isEmpty()) {
|
||||
JsonArray jsonarray = new JsonArray();
|
||||
|
||||
for(String s : collection) {
|
||||
jsonarray.add(s);
|
||||
}
|
||||
|
||||
jsonobject.add("redirect", jsonarray);
|
||||
}
|
||||
}
|
||||
|
||||
return jsonobject;
|
||||
}
|
||||
|
||||
public static <T> Set<ArgumentType<?>> findUsedArgumentTypes(CommandNode<T> pNode) {
|
||||
Set<CommandNode<T>> set = Sets.newIdentityHashSet();
|
||||
Set<ArgumentType<?>> set1 = Sets.newHashSet();
|
||||
findUsedArgumentTypes(pNode, set1, set);
|
||||
return set1;
|
||||
}
|
||||
|
||||
private static <T> void findUsedArgumentTypes(CommandNode<T> pNode, Set<ArgumentType<?>> pTypes, Set<CommandNode<T>> p_235422_) {
|
||||
if (p_235422_.add(pNode)) {
|
||||
if (pNode instanceof ArgumentCommandNode) {
|
||||
ArgumentCommandNode<?, ?> argumentcommandnode = (ArgumentCommandNode)pNode;
|
||||
pTypes.add(argumentcommandnode.getType());
|
||||
}
|
||||
|
||||
pNode.getChildren().forEach((p_235426_) -> {
|
||||
findUsedArgumentTypes(p_235426_, pTypes, p_235422_);
|
||||
});
|
||||
CommandNode<T> commandnode = pNode.getRedirect();
|
||||
if (commandnode != null) {
|
||||
findUsedArgumentTypes(commandnode, pTypes, p_235422_);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package net.minecraft.commands.synchronization;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
|
||||
public class SingletonArgumentInfo<A extends ArgumentType<?>> implements ArgumentTypeInfo<A, SingletonArgumentInfo<A>.Template> {
|
||||
private final SingletonArgumentInfo<A>.Template template;
|
||||
|
||||
private SingletonArgumentInfo(Function<CommandBuildContext, A> pConstructor) {
|
||||
this.template = new SingletonArgumentInfo.Template(pConstructor);
|
||||
}
|
||||
|
||||
public static <T extends ArgumentType<?>> SingletonArgumentInfo<T> contextFree(Supplier<T> pArgumentTypeSupplier) {
|
||||
return new SingletonArgumentInfo<>((p_235455_) -> {
|
||||
return pArgumentTypeSupplier.get();
|
||||
});
|
||||
}
|
||||
|
||||
public static <T extends ArgumentType<?>> SingletonArgumentInfo<T> contextAware(Function<CommandBuildContext, T> pArgumentType) {
|
||||
return new SingletonArgumentInfo<>(pArgumentType);
|
||||
}
|
||||
|
||||
public void serializeToNetwork(SingletonArgumentInfo<A>.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
}
|
||||
|
||||
public void serializeToJson(SingletonArgumentInfo<A>.Template pTemplate, JsonObject pJson) {
|
||||
}
|
||||
|
||||
public SingletonArgumentInfo<A>.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
return this.template;
|
||||
}
|
||||
|
||||
public SingletonArgumentInfo<A>.Template unpack(A pArgument) {
|
||||
return this.template;
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<A> {
|
||||
private final Function<CommandBuildContext, A> constructor;
|
||||
|
||||
public Template(Function<CommandBuildContext, A> pConstructor) {
|
||||
this.constructor = pConstructor;
|
||||
}
|
||||
|
||||
public A instantiate(CommandBuildContext pContext) {
|
||||
return this.constructor.apply(pContext);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<A, ?> type() {
|
||||
return SingletonArgumentInfo.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package net.minecraft.commands.synchronization;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.suggestion.SuggestionProvider;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
|
||||
public class SuggestionProviders {
|
||||
private static final Map<ResourceLocation, SuggestionProvider<SharedSuggestionProvider>> PROVIDERS_BY_NAME = Maps.newHashMap();
|
||||
private static final ResourceLocation DEFAULT_NAME = new ResourceLocation("ask_server");
|
||||
public static final SuggestionProvider<SharedSuggestionProvider> ASK_SERVER = register(DEFAULT_NAME, (p_121673_, p_121674_) -> {
|
||||
return p_121673_.getSource().customSuggestion(p_121673_);
|
||||
});
|
||||
public static final SuggestionProvider<CommandSourceStack> ALL_RECIPES = register(new ResourceLocation("all_recipes"), (p_121670_, p_121671_) -> {
|
||||
return SharedSuggestionProvider.suggestResource(p_121670_.getSource().getRecipeNames(), p_121671_);
|
||||
});
|
||||
public static final SuggestionProvider<CommandSourceStack> AVAILABLE_SOUNDS = register(new ResourceLocation("available_sounds"), (p_121667_, p_121668_) -> {
|
||||
return SharedSuggestionProvider.suggestResource(p_121667_.getSource().getAvailableSounds(), p_121668_);
|
||||
});
|
||||
public static final SuggestionProvider<CommandSourceStack> SUMMONABLE_ENTITIES = register(new ResourceLocation("summonable_entities"), (p_258164_, p_258165_) -> {
|
||||
return SharedSuggestionProvider.suggestResource(BuiltInRegistries.ENTITY_TYPE.stream().filter((p_247987_) -> {
|
||||
return p_247987_.isEnabled(p_258164_.getSource().enabledFeatures()) && p_247987_.canSummon();
|
||||
}), p_258165_, EntityType::getKey, (p_212436_) -> {
|
||||
return Component.translatable(Util.makeDescriptionId("entity", EntityType.getKey(p_212436_)));
|
||||
});
|
||||
});
|
||||
|
||||
public static <S extends SharedSuggestionProvider> SuggestionProvider<S> register(ResourceLocation pName, SuggestionProvider<SharedSuggestionProvider> pProvider) {
|
||||
if (PROVIDERS_BY_NAME.containsKey(pName)) {
|
||||
throw new IllegalArgumentException("A command suggestion provider is already registered with the name " + pName);
|
||||
} else {
|
||||
PROVIDERS_BY_NAME.put(pName, pProvider);
|
||||
return (SuggestionProvider<S>)new SuggestionProviders.Wrapper(pName, pProvider);
|
||||
}
|
||||
}
|
||||
|
||||
public static SuggestionProvider<SharedSuggestionProvider> getProvider(ResourceLocation pName) {
|
||||
return PROVIDERS_BY_NAME.getOrDefault(pName, ASK_SERVER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the ID for the given provider. If the provider is not a wrapped one created via {@link #register}, then it
|
||||
* returns {@link #ASK_SERVER_ID} instead, as there is no known ID but ASK_SERVER always works.
|
||||
*/
|
||||
public static ResourceLocation getName(SuggestionProvider<SharedSuggestionProvider> pProvider) {
|
||||
return pProvider instanceof SuggestionProviders.Wrapper ? ((SuggestionProviders.Wrapper)pProvider).name : DEFAULT_NAME;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to make sure that the given suggestion provider is a wrapped one that was created via {@link #register}. If
|
||||
* not, returns {@link #ASK_SERVER}. Needed because custom providers don't have a known ID to send to the client, but
|
||||
* ASK_SERVER always works.
|
||||
*/
|
||||
public static SuggestionProvider<SharedSuggestionProvider> safelySwap(SuggestionProvider<SharedSuggestionProvider> pProvider) {
|
||||
return pProvider instanceof SuggestionProviders.Wrapper ? pProvider : ASK_SERVER;
|
||||
}
|
||||
|
||||
protected static class Wrapper implements SuggestionProvider<SharedSuggestionProvider> {
|
||||
private final SuggestionProvider<SharedSuggestionProvider> delegate;
|
||||
final ResourceLocation name;
|
||||
|
||||
public Wrapper(ResourceLocation pName, SuggestionProvider<SharedSuggestionProvider> pDelegate) {
|
||||
this.delegate = pDelegate;
|
||||
this.name = pName;
|
||||
}
|
||||
|
||||
public CompletableFuture<Suggestions> getSuggestions(CommandContext<SharedSuggestionProvider> pContext, SuggestionsBuilder pBuilder) throws CommandSyntaxException {
|
||||
return this.delegate.getSuggestions(pContext, pBuilder);
|
||||
}
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package net.minecraft.commands.synchronization.brigadier;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.arguments.DoubleArgumentType;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.commands.synchronization.ArgumentUtils;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
|
||||
public class DoubleArgumentInfo implements ArgumentTypeInfo<DoubleArgumentType, DoubleArgumentInfo.Template> {
|
||||
public void serializeToNetwork(DoubleArgumentInfo.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
boolean flag = pTemplate.min != -Double.MAX_VALUE;
|
||||
boolean flag1 = pTemplate.max != Double.MAX_VALUE;
|
||||
pBuffer.writeByte(ArgumentUtils.createNumberFlags(flag, flag1));
|
||||
if (flag) {
|
||||
pBuffer.writeDouble(pTemplate.min);
|
||||
}
|
||||
|
||||
if (flag1) {
|
||||
pBuffer.writeDouble(pTemplate.max);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public DoubleArgumentInfo.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
byte b0 = pBuffer.readByte();
|
||||
double d0 = ArgumentUtils.numberHasMin(b0) ? pBuffer.readDouble() : -Double.MAX_VALUE;
|
||||
double d1 = ArgumentUtils.numberHasMax(b0) ? pBuffer.readDouble() : Double.MAX_VALUE;
|
||||
return new DoubleArgumentInfo.Template(d0, d1);
|
||||
}
|
||||
|
||||
public void serializeToJson(DoubleArgumentInfo.Template pTemplate, JsonObject pJson) {
|
||||
if (pTemplate.min != -Double.MAX_VALUE) {
|
||||
pJson.addProperty("min", pTemplate.min);
|
||||
}
|
||||
|
||||
if (pTemplate.max != Double.MAX_VALUE) {
|
||||
pJson.addProperty("max", pTemplate.max);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public DoubleArgumentInfo.Template unpack(DoubleArgumentType pArgument) {
|
||||
return new DoubleArgumentInfo.Template(pArgument.getMinimum(), pArgument.getMaximum());
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<DoubleArgumentType> {
|
||||
final double min;
|
||||
final double max;
|
||||
|
||||
Template(double pMin, double pMax) {
|
||||
this.min = pMin;
|
||||
this.max = pMax;
|
||||
}
|
||||
|
||||
public DoubleArgumentType instantiate(CommandBuildContext pContext) {
|
||||
return DoubleArgumentType.doubleArg(this.min, this.max);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<DoubleArgumentType, ?> type() {
|
||||
return DoubleArgumentInfo.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package net.minecraft.commands.synchronization.brigadier;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.arguments.FloatArgumentType;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.commands.synchronization.ArgumentUtils;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
|
||||
public class FloatArgumentInfo implements ArgumentTypeInfo<FloatArgumentType, FloatArgumentInfo.Template> {
|
||||
public void serializeToNetwork(FloatArgumentInfo.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
boolean flag = pTemplate.min != -Float.MAX_VALUE;
|
||||
boolean flag1 = pTemplate.max != Float.MAX_VALUE;
|
||||
pBuffer.writeByte(ArgumentUtils.createNumberFlags(flag, flag1));
|
||||
if (flag) {
|
||||
pBuffer.writeFloat(pTemplate.min);
|
||||
}
|
||||
|
||||
if (flag1) {
|
||||
pBuffer.writeFloat(pTemplate.max);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public FloatArgumentInfo.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
byte b0 = pBuffer.readByte();
|
||||
float f = ArgumentUtils.numberHasMin(b0) ? pBuffer.readFloat() : -Float.MAX_VALUE;
|
||||
float f1 = ArgumentUtils.numberHasMax(b0) ? pBuffer.readFloat() : Float.MAX_VALUE;
|
||||
return new FloatArgumentInfo.Template(f, f1);
|
||||
}
|
||||
|
||||
public void serializeToJson(FloatArgumentInfo.Template pTemplate, JsonObject pJson) {
|
||||
if (pTemplate.min != -Float.MAX_VALUE) {
|
||||
pJson.addProperty("min", pTemplate.min);
|
||||
}
|
||||
|
||||
if (pTemplate.max != Float.MAX_VALUE) {
|
||||
pJson.addProperty("max", pTemplate.max);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public FloatArgumentInfo.Template unpack(FloatArgumentType pArgument) {
|
||||
return new FloatArgumentInfo.Template(pArgument.getMinimum(), pArgument.getMaximum());
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<FloatArgumentType> {
|
||||
final float min;
|
||||
final float max;
|
||||
|
||||
Template(float pMin, float pMax) {
|
||||
this.min = pMin;
|
||||
this.max = pMax;
|
||||
}
|
||||
|
||||
public FloatArgumentType instantiate(CommandBuildContext pContext) {
|
||||
return FloatArgumentType.floatArg(this.min, this.max);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<FloatArgumentType, ?> type() {
|
||||
return FloatArgumentInfo.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package net.minecraft.commands.synchronization.brigadier;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.arguments.IntegerArgumentType;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.commands.synchronization.ArgumentUtils;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
|
||||
public class IntegerArgumentInfo implements ArgumentTypeInfo<IntegerArgumentType, IntegerArgumentInfo.Template> {
|
||||
public void serializeToNetwork(IntegerArgumentInfo.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
boolean flag = pTemplate.min != Integer.MIN_VALUE;
|
||||
boolean flag1 = pTemplate.max != Integer.MAX_VALUE;
|
||||
pBuffer.writeByte(ArgumentUtils.createNumberFlags(flag, flag1));
|
||||
if (flag) {
|
||||
pBuffer.writeInt(pTemplate.min);
|
||||
}
|
||||
|
||||
if (flag1) {
|
||||
pBuffer.writeInt(pTemplate.max);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public IntegerArgumentInfo.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
byte b0 = pBuffer.readByte();
|
||||
int i = ArgumentUtils.numberHasMin(b0) ? pBuffer.readInt() : Integer.MIN_VALUE;
|
||||
int j = ArgumentUtils.numberHasMax(b0) ? pBuffer.readInt() : Integer.MAX_VALUE;
|
||||
return new IntegerArgumentInfo.Template(i, j);
|
||||
}
|
||||
|
||||
public void serializeToJson(IntegerArgumentInfo.Template pTemplate, JsonObject pJson) {
|
||||
if (pTemplate.min != Integer.MIN_VALUE) {
|
||||
pJson.addProperty("min", pTemplate.min);
|
||||
}
|
||||
|
||||
if (pTemplate.max != Integer.MAX_VALUE) {
|
||||
pJson.addProperty("max", pTemplate.max);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public IntegerArgumentInfo.Template unpack(IntegerArgumentType pArgument) {
|
||||
return new IntegerArgumentInfo.Template(pArgument.getMinimum(), pArgument.getMaximum());
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<IntegerArgumentType> {
|
||||
final int min;
|
||||
final int max;
|
||||
|
||||
Template(int pMin, int pMax) {
|
||||
this.min = pMin;
|
||||
this.max = pMax;
|
||||
}
|
||||
|
||||
public IntegerArgumentType instantiate(CommandBuildContext pContext) {
|
||||
return IntegerArgumentType.integer(this.min, this.max);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<IntegerArgumentType, ?> type() {
|
||||
return IntegerArgumentInfo.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package net.minecraft.commands.synchronization.brigadier;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.arguments.LongArgumentType;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.commands.synchronization.ArgumentUtils;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
|
||||
public class LongArgumentInfo implements ArgumentTypeInfo<LongArgumentType, LongArgumentInfo.Template> {
|
||||
public void serializeToNetwork(LongArgumentInfo.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
boolean flag = pTemplate.min != Long.MIN_VALUE;
|
||||
boolean flag1 = pTemplate.max != Long.MAX_VALUE;
|
||||
pBuffer.writeByte(ArgumentUtils.createNumberFlags(flag, flag1));
|
||||
if (flag) {
|
||||
pBuffer.writeLong(pTemplate.min);
|
||||
}
|
||||
|
||||
if (flag1) {
|
||||
pBuffer.writeLong(pTemplate.max);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public LongArgumentInfo.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
byte b0 = pBuffer.readByte();
|
||||
long i = ArgumentUtils.numberHasMin(b0) ? pBuffer.readLong() : Long.MIN_VALUE;
|
||||
long j = ArgumentUtils.numberHasMax(b0) ? pBuffer.readLong() : Long.MAX_VALUE;
|
||||
return new LongArgumentInfo.Template(i, j);
|
||||
}
|
||||
|
||||
public void serializeToJson(LongArgumentInfo.Template pTemplate, JsonObject pJson) {
|
||||
if (pTemplate.min != Long.MIN_VALUE) {
|
||||
pJson.addProperty("min", pTemplate.min);
|
||||
}
|
||||
|
||||
if (pTemplate.max != Long.MAX_VALUE) {
|
||||
pJson.addProperty("max", pTemplate.max);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public LongArgumentInfo.Template unpack(LongArgumentType pArgument) {
|
||||
return new LongArgumentInfo.Template(pArgument.getMinimum(), pArgument.getMaximum());
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<LongArgumentType> {
|
||||
final long min;
|
||||
final long max;
|
||||
|
||||
Template(long pMin, long pMax) {
|
||||
this.min = pMin;
|
||||
this.max = pMax;
|
||||
}
|
||||
|
||||
public LongArgumentType instantiate(CommandBuildContext pContext) {
|
||||
return LongArgumentType.longArg(this.min, this.max);
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<LongArgumentType, ?> type() {
|
||||
return LongArgumentInfo.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package net.minecraft.commands.synchronization.brigadier;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.brigadier.arguments.StringArgumentType;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
|
||||
public class StringArgumentSerializer implements ArgumentTypeInfo<StringArgumentType, StringArgumentSerializer.Template> {
|
||||
public void serializeToNetwork(StringArgumentSerializer.Template pTemplate, FriendlyByteBuf pBuffer) {
|
||||
pBuffer.writeEnum(pTemplate.type);
|
||||
}
|
||||
|
||||
public StringArgumentSerializer.Template deserializeFromNetwork(FriendlyByteBuf pBuffer) {
|
||||
StringArgumentType.StringType stringtype = pBuffer.readEnum(StringArgumentType.StringType.class);
|
||||
return new StringArgumentSerializer.Template(stringtype);
|
||||
}
|
||||
|
||||
public void serializeToJson(StringArgumentSerializer.Template pTemplate, JsonObject pJson) {
|
||||
String s;
|
||||
switch (pTemplate.type) {
|
||||
case SINGLE_WORD:
|
||||
s = "word";
|
||||
break;
|
||||
case QUOTABLE_PHRASE:
|
||||
s = "phrase";
|
||||
break;
|
||||
case GREEDY_PHRASE:
|
||||
s = "greedy";
|
||||
break;
|
||||
default:
|
||||
throw new IncompatibleClassChangeError();
|
||||
}
|
||||
|
||||
pJson.addProperty("type", s);
|
||||
}
|
||||
|
||||
public StringArgumentSerializer.Template unpack(StringArgumentType pArgument) {
|
||||
return new StringArgumentSerializer.Template(pArgument.getType());
|
||||
}
|
||||
|
||||
public final class Template implements ArgumentTypeInfo.Template<StringArgumentType> {
|
||||
final StringArgumentType.StringType type;
|
||||
|
||||
public Template(StringArgumentType.StringType pType) {
|
||||
this.type = pType;
|
||||
}
|
||||
|
||||
public StringArgumentType instantiate(CommandBuildContext pContext) {
|
||||
StringArgumentType stringargumenttype;
|
||||
switch (this.type) {
|
||||
case SINGLE_WORD:
|
||||
stringargumenttype = StringArgumentType.word();
|
||||
break;
|
||||
case QUOTABLE_PHRASE:
|
||||
stringargumenttype = StringArgumentType.string();
|
||||
break;
|
||||
case GREEDY_PHRASE:
|
||||
stringargumenttype = StringArgumentType.greedyString();
|
||||
break;
|
||||
default:
|
||||
throw new IncompatibleClassChangeError();
|
||||
}
|
||||
|
||||
return stringargumenttype;
|
||||
}
|
||||
|
||||
public ArgumentTypeInfo<StringArgumentType, ?> type() {
|
||||
return StringArgumentSerializer.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
@FieldsAreNonnullByDefault
|
||||
package net.minecraft.commands.synchronization.brigadier;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.FieldsAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
@FieldsAreNonnullByDefault
|
||||
package net.minecraft.commands.synchronization;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.FieldsAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
Reference in new issue
Block a user