| 1 | package net.minecraft.server.commands;
|
| 2 |
|
| 3 | import com.google.common.annotations.VisibleForTesting;
|
| 4 | import com.mojang.brigadier.CommandDispatcher;
|
| 5 | import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
| 6 | import com.mojang.brigadier.context.CommandContext;
|
| 7 | import com.mojang.brigadier.context.ContextChain;
|
| 8 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 9 | import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
|
| 10 | import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
| 11 | import com.mojang.brigadier.suggestion.SuggestionProvider;
|
| 12 | import com.mojang.datafixers.util.Pair;
|
| 13 | import java.util.Collection;
|
| 14 | import net.minecraft.commands.CommandResultCallback;
|
| 15 | import net.minecraft.commands.CommandSourceStack;
|
| 16 | import net.minecraft.commands.Commands;
|
| 17 | import net.minecraft.commands.ExecutionCommandSource;
|
| 18 | import net.minecraft.commands.FunctionInstantiationException;
|
| 19 | import net.minecraft.commands.SharedSuggestionProvider;
|
| 20 | import net.minecraft.commands.arguments.CompoundTagArgument;
|
| 21 | import net.minecraft.commands.arguments.NbtPathArgument;
|
| 22 | import net.minecraft.commands.arguments.item.FunctionArgument;
|
| 23 | import net.minecraft.commands.execution.ChainModifiers;
|
| 24 | import net.minecraft.commands.execution.CustomCommandExecutor;
|
| 25 | import net.minecraft.commands.execution.ExecutionControl;
|
| 26 | import net.minecraft.commands.execution.tasks.CallFunction;
|
| 27 | import net.minecraft.commands.execution.tasks.FallthroughTask;
|
| 28 | import net.minecraft.commands.functions.CommandFunction;
|
| 29 | import net.minecraft.commands.functions.InstantiatedFunction;
|
| 30 | import net.minecraft.nbt.CompoundTag;
|
| 31 | import net.minecraft.nbt.Tag;
|
| 32 | import net.minecraft.network.chat.Component;
|
| 33 | import net.minecraft.network.chat.ComponentUtils;
|
| 34 | import net.minecraft.resources.Identifier;
|
| 35 | import net.minecraft.server.ServerFunctionManager;
|
| 36 | import net.minecraft.server.commands.data.DataAccessor;
|
| 37 | import net.minecraft.server.commands.data.DataCommands;
|
| 38 | import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
| 39 | import org.jspecify.annotations.Nullable;
|
| 40 |
|
| 41 | public class FunctionCommand {
|
| 42 | private static final DynamicCommandExceptionType ERROR_ARGUMENT_NOT_COMPOUND = new DynamicCommandExceptionType(
|
| 43 | type -> Component.translatableEscape("commands.function.error.argument_not_compound", type)
|
| 44 | );
|
| 45 | private static final DynamicCommandExceptionType ERROR_NO_FUNCTIONS = new DynamicCommandExceptionType(
|
| 46 | name -> Component.translatableEscape("commands.function.scheduled.no_functions", name)
|
| 47 | );
|
| 48 | @VisibleForTesting
|
| 49 | public static final Dynamic2CommandExceptionType ERROR_FUNCTION_INSTANTATION_FAILURE = new Dynamic2CommandExceptionType(
|
| 50 | (id, reason) -> Component.translatableEscape("commands.function.instantiationFailure", id, reason)
|
| 51 | );
|
| 52 | public static final SuggestionProvider<CommandSourceStack> SUGGEST_FUNCTION = (c, p) -> {
|
| 53 | ServerFunctionManager manager = c.getSource().getServer().getFunctions();
|
| 54 | SharedSuggestionProvider.suggestResource(manager.getTagNames(), p, "#");
|
| 55 | return SharedSuggestionProvider.suggestResource(manager.getFunctionNames(), p);
|
| 56 | };
|
| 57 | private static final FunctionCommand.Callbacks<CommandSourceStack> FULL_CONTEXT_CALLBACKS = new FunctionCommand.Callbacks<CommandSourceStack>() {
|
| 58 | public void signalResult(final CommandSourceStack originalSource, final Identifier id, final int newValue) {
|
| 59 | originalSource.sendSuccess(() -> Component.translatable("commands.function.result", Component.translationArg(id), newValue), true);
|
| 60 | }
|
| 61 | };
|
| 62 |
|
| 63 | public static void register(final CommandDispatcher<CommandSourceStack> dispatcher) {
|
| 64 | LiteralArgumentBuilder<CommandSourceStack> sources = Commands.literal("with");
|
| 65 |
|
| 66 | for (ArgProvider<DataAccessor> provider : DataCommands.SOURCE_PROVIDERS) {
|
| 67 | provider.wrap(sources, p -> p.executes(new FunctionCommand.FunctionCustomExecutor() {
|
| 68 | @Override
|
| 69 | protected CompoundTag arguments(final CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
|
| 70 | return provider.access(context).getData();
|
| 71 | }
|
| 72 | }).then(Commands.argument("path", NbtPathArgument.nbtPath()).executes(new FunctionCommand.FunctionCustomExecutor() {
|
| 73 | @Override
|
| 74 | protected CompoundTag arguments(final CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
|
| 75 | return FunctionCommand.getArgumentTag(NbtPathArgument.getPath(context, "path"), provider.access(context));
|
| 76 | }
|
| 77 | })));
|
| 78 | }
|
| 79 |
|
| 80 | dispatcher.register(
|
| 81 | Commands.literal("function")
|
| 82 | .requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS))
|
| 83 | .then(Commands.argument("name", FunctionArgument.functions()).suggests(SUGGEST_FUNCTION).executes(new FunctionCommand.FunctionCustomExecutor() {
|
| 84 | @Override
|
| 85 | protected @Nullable CompoundTag arguments(final CommandContext<CommandSourceStack> context) {
|
| 86 | return null;
|
| 87 | }
|
| 88 | }).then(Commands.argument("arguments", CompoundTagArgument.compoundTag()).executes(new FunctionCommand.FunctionCustomExecutor() {
|
| 89 | @Override
|
| 90 | protected CompoundTag arguments(final CommandContext<CommandSourceStack> context) {
|
| 91 | return CompoundTagArgument.getCompoundTag(context, "arguments");
|
| 92 | }
|
| 93 | })).then(sources))
|
| 94 | );
|
| 95 | }
|
| 96 |
|
| 97 | private static CompoundTag getArgumentTag(final NbtPathArgument.NbtPath path, final DataAccessor accessor) throws CommandSyntaxException {
|
| 98 | Tag tag = DataCommands.getSingleTag(path, accessor);
|
| 99 | if (tag instanceof CompoundTag compoundTag) {
|
| 100 | return compoundTag;
|
| 101 | } else {
|
| 102 | throw ERROR_ARGUMENT_NOT_COMPOUND.create(tag.getType().getName());
|
| 103 | }
|
| 104 | }
|
| 105 |
|
| 106 | public static CommandSourceStack modifySenderForExecution(final CommandSourceStack sender) {
|
| 107 | return sender.withSuppressedOutput().withMaximumPermission(LevelBasedPermissionSet.GAMEMASTER);
|
| 108 | }
|
| 109 |
|
| 110 | public static <T extends ExecutionCommandSource<T>> void queueFunctions(
|
| 111 | final Collection<CommandFunction<T>> functions,
|
| 112 | final @Nullable CompoundTag arguments,
|
| 113 | final T originalSource,
|
| 114 | final T functionSource,
|
| 115 | final ExecutionControl<T> output,
|
| 116 | final FunctionCommand.Callbacks<T> callbacks,
|
| 117 | final ChainModifiers modifiers
|
| 118 | ) throws CommandSyntaxException {
|
| 119 | if (modifiers.isReturn()) {
|
| 120 | queueFunctionsAsReturn(functions, arguments, originalSource, functionSource, output, callbacks);
|
| 121 | } else {
|
| 122 | queueFunctionsNoReturn(functions, arguments, originalSource, functionSource, output, callbacks);
|
| 123 | }
|
| 124 | }
|
| 125 |
|
| 126 | private static <T extends ExecutionCommandSource<T>> void instantiateAndQueueFunctions(
|
| 127 | final @Nullable CompoundTag arguments,
|
| 128 | final ExecutionControl<T> output,
|
| 129 | final CommandDispatcher<T> dispatcher,
|
| 130 | final T noCallbackSource,
|
| 131 | final CommandFunction<T> function,
|
| 132 | final Identifier id,
|
| 133 | final CommandResultCallback functionResultCollector,
|
| 134 | final boolean returnParentFrame
|
| 135 | ) throws CommandSyntaxException {
|
| 136 | try {
|
| 137 | InstantiatedFunction<T> instantiatedFunction = function.instantiate(arguments, dispatcher);
|
| 138 | output.queueNext(new CallFunction<>(instantiatedFunction, functionResultCollector, returnParentFrame).bind(noCallbackSource));
|
| 139 | } catch (FunctionInstantiationException exception) {
|
| 140 | throw ERROR_FUNCTION_INSTANTATION_FAILURE.create(id, exception.messageComponent());
|
| 141 | }
|
| 142 | }
|
| 143 |
|
| 144 | private static <T extends ExecutionCommandSource<T>> CommandResultCallback decorateOutputIfNeeded(
|
| 145 | final T originalSource, final FunctionCommand.Callbacks<T> callbacks, final Identifier id, final CommandResultCallback callback
|
| 146 | ) {
|
| 147 | return originalSource.isSilent() ? callback : (success, result) -> {
|
| 148 | callbacks.signalResult(originalSource, id, result);
|
| 149 | callback.onResult(success, result);
|
| 150 | };
|
| 151 | }
|
| 152 |
|
| 153 | private static <T extends ExecutionCommandSource<T>> void queueFunctionsAsReturn(
|
| 154 | final Collection<CommandFunction<T>> functions,
|
| 155 | final @Nullable CompoundTag arguments,
|
| 156 | final T originalSource,
|
| 157 | final T functionSource,
|
| 158 | final ExecutionControl<T> output,
|
| 159 | final FunctionCommand.Callbacks<T> callbacks
|
| 160 | ) throws CommandSyntaxException {
|
| 161 | CommandDispatcher<T> dispatcher = originalSource.dispatcher();
|
| 162 | T noCallbackSource = functionSource.clearCallbacks();
|
| 163 | CommandResultCallback functionCommandOutputCallback = CommandResultCallback.chain(originalSource.callback(), output.currentFrame().returnValueConsumer());
|
| 164 |
|
| 165 | for (CommandFunction<T> function : functions) {
|
| 166 | Identifier id = function.id();
|
| 167 | CommandResultCallback functionResultCollector = decorateOutputIfNeeded(originalSource, callbacks, id, functionCommandOutputCallback);
|
| 168 | instantiateAndQueueFunctions(arguments, output, dispatcher, noCallbackSource, function, id, functionResultCollector, true);
|
| 169 | }
|
| 170 |
|
| 171 | output.queueNext(FallthroughTask.instance());
|
| 172 | }
|
| 173 |
|
| 174 | private static <T extends ExecutionCommandSource<T>> void queueFunctionsNoReturn(
|
| 175 | final Collection<CommandFunction<T>> functions,
|
| 176 | final @Nullable CompoundTag arguments,
|
| 177 | final T originalSource,
|
| 178 | final T functionSource,
|
| 179 | final ExecutionControl<T> output,
|
| 180 | final FunctionCommand.Callbacks<T> callbacks
|
| 181 | ) throws CommandSyntaxException {
|
| 182 | CommandDispatcher<T> dispatcher = originalSource.dispatcher();
|
| 183 | T noCallbackSource = functionSource.clearCallbacks();
|
| 184 | CommandResultCallback originalCallback = originalSource.callback();
|
| 185 | if (!functions.isEmpty()) {
|
| 186 | if (functions.size() == 1) {
|
| 187 | CommandFunction<T> function = functions.iterator().next();
|
| 188 | Identifier id = function.id();
|
| 189 | CommandResultCallback functionResultCollector = decorateOutputIfNeeded(originalSource, callbacks, id, originalCallback);
|
| 190 | instantiateAndQueueFunctions(arguments, output, dispatcher, noCallbackSource, function, id, functionResultCollector, false);
|
| 191 | } else if (originalCallback == CommandResultCallback.EMPTY) {
|
| 192 | for (CommandFunction<T> function : functions) {
|
| 193 | Identifier id = function.id();
|
| 194 | CommandResultCallback functionResultCollector = decorateOutputIfNeeded(originalSource, callbacks, id, originalCallback);
|
| 195 | instantiateAndQueueFunctions(arguments, output, dispatcher, noCallbackSource, function, id, functionResultCollector, false);
|
| 196 | }
|
| 197 | } else {
|
| 198 | class Accumulator {
|
| 199 | private boolean anyResult;
|
| 200 | private int sum;
|
| 201 |
|
| 202 | public void add(final int result) {
|
| 203 | this.anyResult = true;
|
| 204 | this.sum += result;
|
| 205 | }
|
| 206 | }
|
| 207 |
|
| 208 | Accumulator accumulator = new Accumulator();
|
| 209 | CommandResultCallback partialResultCallback = (success, result) -> accumulator.add(result);
|
| 210 |
|
| 211 | for (CommandFunction<T> function : functions) {
|
| 212 | Identifier id = function.id();
|
| 213 | CommandResultCallback functionResultCollector = decorateOutputIfNeeded(originalSource, callbacks, id, partialResultCallback);
|
| 214 | instantiateAndQueueFunctions(arguments, output, dispatcher, noCallbackSource, function, id, functionResultCollector, false);
|
| 215 | }
|
| 216 |
|
| 217 | output.queueNext((context, frame) -> {
|
| 218 | if (accumulator.anyResult) {
|
| 219 | originalCallback.onSuccess(accumulator.sum);
|
| 220 | }
|
| 221 | });
|
| 222 | }
|
| 223 | }
|
| 224 | }
|
| 225 |
|
| 226 | public interface Callbacks<T> {
|
| 227 | void signalResult(T originalSource, Identifier functionId, int newValue);
|
| 228 | }
|
| 229 |
|
| 230 | private abstract static class FunctionCustomExecutor
|
| 231 | extends CustomCommandExecutor.WithErrorHandling<CommandSourceStack>
|
| 232 | implements CustomCommandExecutor.CommandAdapter<CommandSourceStack> {
|
| 233 | protected abstract @Nullable CompoundTag arguments(final CommandContext<CommandSourceStack> context) throws CommandSyntaxException;
|
| 234 |
|
| 235 | public void runGuarded(
|
| 236 | final CommandSourceStack sender,
|
| 237 | final ContextChain<CommandSourceStack> currentStep,
|
| 238 | final ChainModifiers modifiers,
|
| 239 | final ExecutionControl<CommandSourceStack> output
|
| 240 | ) throws CommandSyntaxException {
|
| 241 | CommandContext<CommandSourceStack> currentContext = currentStep.getTopContext().copyFor(sender);
|
| 242 | Pair<Identifier, Collection<CommandFunction<CommandSourceStack>>> nameAndFunctions = FunctionArgument.getFunctionCollection(currentContext, "name");
|
| 243 | Collection<CommandFunction<CommandSourceStack>> functions = nameAndFunctions.getSecond();
|
| 244 | if (functions.isEmpty()) {
|
| 245 | throw FunctionCommand.ERROR_NO_FUNCTIONS.create(Component.translationArg(nameAndFunctions.getFirst()));
|
| 246 | }
|
| 247 |
|
| 248 | CompoundTag arguments = this.arguments(currentContext);
|
| 249 | CommandSourceStack commonFunctionContext = FunctionCommand.modifySenderForExecution(sender);
|
| 250 | if (functions.size() == 1) {
|
| 251 | sender.sendSuccess(() -> Component.translatable("commands.function.scheduled.single", Component.translationArg(functions.iterator().next().id())), true);
|
| 252 | } else {
|
| 253 | sender.sendSuccess(
|
| 254 | () -> Component.translatable(
|
| 255 | "commands.function.scheduled.multiple", ComponentUtils.formatList(functions.stream().map(CommandFunction::id).toList(), Component::translationArg)
|
| 256 | ),
|
| 257 | true
|
| 258 | );
|
| 259 | }
|
| 260 |
|
| 261 | FunctionCommand.queueFunctions(functions, arguments, sender, commonFunctionContext, output, FunctionCommand.FULL_CONTEXT_CALLBACKS, modifiers);
|
| 262 | }
|
| 263 | }
|
| 264 | }
|
| 265 |
|