| 1 | package net.minecraft.server.commands;
|
| 2 |
|
| 3 | import com.google.common.annotations.VisibleForTesting;
|
| 4 | import com.google.common.collect.Lists;
|
| 5 | import com.mojang.brigadier.Command;
|
| 6 | import com.mojang.brigadier.CommandDispatcher;
|
| 7 | import com.mojang.brigadier.RedirectModifier;
|
| 8 | import com.mojang.brigadier.arguments.DoubleArgumentType;
|
| 9 | import com.mojang.brigadier.builder.ArgumentBuilder;
|
| 10 | import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
| 11 | import com.mojang.brigadier.context.CommandContext;
|
| 12 | import com.mojang.brigadier.context.ContextChain;
|
| 13 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 14 | import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
|
| 15 | import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
| 16 | import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
| 17 | import com.mojang.brigadier.tree.CommandNode;
|
| 18 | import com.mojang.brigadier.tree.LiteralCommandNode;
|
| 19 | import com.mojang.logging.LogUtils;
|
| 20 | import java.util.ArrayList;
|
| 21 | import java.util.Collection;
|
| 22 | import java.util.Collections;
|
| 23 | import java.util.List;
|
| 24 | import java.util.Optional;
|
| 25 | import java.util.OptionalInt;
|
| 26 | import java.util.function.Function;
|
| 27 | import java.util.function.IntFunction;
|
| 28 | import java.util.function.IntPredicate;
|
| 29 | import java.util.function.Predicate;
|
| 30 | import java.util.stream.Stream;
|
| 31 | import net.minecraft.advancements.predicates.MinMaxBounds;
|
| 32 | import net.minecraft.commands.CommandBuildContext;
|
| 33 | import net.minecraft.commands.CommandResultCallback;
|
| 34 | import net.minecraft.commands.CommandSourceStack;
|
| 35 | import net.minecraft.commands.Commands;
|
| 36 | import net.minecraft.commands.ExecutionCommandSource;
|
| 37 | import net.minecraft.commands.FunctionInstantiationException;
|
| 38 | import net.minecraft.commands.arguments.DimensionArgument;
|
| 39 | import net.minecraft.commands.arguments.EntityAnchorArgument;
|
| 40 | import net.minecraft.commands.arguments.EntityArgument;
|
| 41 | import net.minecraft.commands.arguments.HeightmapTypeArgument;
|
| 42 | import net.minecraft.commands.arguments.IdentifierArgument;
|
| 43 | import net.minecraft.commands.arguments.NbtPathArgument;
|
| 44 | import net.minecraft.commands.arguments.ObjectiveArgument;
|
| 45 | import net.minecraft.commands.arguments.RangeArgument;
|
| 46 | import net.minecraft.commands.arguments.ResourceArgument;
|
| 47 | import net.minecraft.commands.arguments.ResourceOrIdArgument;
|
| 48 | import net.minecraft.commands.arguments.ResourceOrTagArgument;
|
| 49 | import net.minecraft.commands.arguments.ScoreHolderArgument;
|
| 50 | import net.minecraft.commands.arguments.SlotSourceArgument;
|
| 51 | import net.minecraft.commands.arguments.blocks.BlockPredicateArgument;
|
| 52 | import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
|
| 53 | import net.minecraft.commands.arguments.coordinates.RotationArgument;
|
| 54 | import net.minecraft.commands.arguments.coordinates.SwizzleArgument;
|
| 55 | import net.minecraft.commands.arguments.coordinates.Vec3Argument;
|
| 56 | import net.minecraft.commands.arguments.item.FunctionArgument;
|
| 57 | import net.minecraft.commands.arguments.item.ItemPredicateArgument;
|
| 58 | import net.minecraft.commands.execution.ChainModifiers;
|
| 59 | import net.minecraft.commands.execution.CustomModifierExecutor;
|
| 60 | import net.minecraft.commands.execution.ExecutionControl;
|
| 61 | import net.minecraft.commands.execution.tasks.BuildContexts;
|
| 62 | import net.minecraft.commands.execution.tasks.CallFunction;
|
| 63 | import net.minecraft.commands.execution.tasks.FallthroughTask;
|
| 64 | import net.minecraft.commands.execution.tasks.IsolatedCall;
|
| 65 | import net.minecraft.commands.functions.CommandFunction;
|
| 66 | import net.minecraft.commands.functions.InstantiatedFunction;
|
| 67 | import net.minecraft.commands.synchronization.SuggestionProviders;
|
| 68 | import net.minecraft.core.BlockPos;
|
| 69 | import net.minecraft.core.Holder;
|
| 70 | import net.minecraft.core.RegistryAccess;
|
| 71 | import net.minecraft.core.SectionPos;
|
| 72 | import net.minecraft.core.registries.Registries;
|
| 73 | import net.minecraft.nbt.ByteTag;
|
| 74 | import net.minecraft.nbt.CompoundTag;
|
| 75 | import net.minecraft.nbt.DoubleTag;
|
| 76 | import net.minecraft.nbt.FloatTag;
|
| 77 | import net.minecraft.nbt.IntTag;
|
| 78 | import net.minecraft.nbt.LongTag;
|
| 79 | import net.minecraft.nbt.ShortTag;
|
| 80 | import net.minecraft.nbt.Tag;
|
| 81 | import net.minecraft.network.chat.Component;
|
| 82 | import net.minecraft.resources.Identifier;
|
| 83 | import net.minecraft.server.bossevents.CustomBossEvent;
|
| 84 | import net.minecraft.server.commands.data.DataAccessor;
|
| 85 | import net.minecraft.server.commands.data.DataCommands;
|
| 86 | import net.minecraft.server.commands.item.ItemAccessor;
|
| 87 | import net.minecraft.server.commands.item.ItemCommands;
|
| 88 | import net.minecraft.server.level.FullChunkStatus;
|
| 89 | import net.minecraft.server.level.ServerLevel;
|
| 90 | import net.minecraft.util.Mth;
|
| 91 | import net.minecraft.util.ProblemReporter;
|
| 92 | import net.minecraft.world.Stopwatch;
|
| 93 | import net.minecraft.world.Stopwatches;
|
| 94 | import net.minecraft.world.entity.Attackable;
|
| 95 | import net.minecraft.world.entity.Entity;
|
| 96 | import net.minecraft.world.entity.EntityType;
|
| 97 | import net.minecraft.world.entity.Leashable;
|
| 98 | import net.minecraft.world.entity.OwnableEntity;
|
| 99 | import net.minecraft.world.entity.Targeting;
|
| 100 | import net.minecraft.world.entity.TraceableEntity;
|
| 101 | import net.minecraft.world.item.ItemStack;
|
| 102 | import net.minecraft.world.item.slot.SlotCollection;
|
| 103 | import net.minecraft.world.level.ChunkPos;
|
| 104 | import net.minecraft.world.level.block.Blocks;
|
| 105 | import net.minecraft.world.level.block.entity.BlockEntity;
|
| 106 | import net.minecraft.world.level.block.state.BlockState;
|
| 107 | import net.minecraft.world.level.block.state.pattern.BlockInWorld;
|
| 108 | import net.minecraft.world.level.chunk.LevelChunk;
|
| 109 | import net.minecraft.world.level.levelgen.structure.BoundingBox;
|
| 110 | import net.minecraft.world.level.storage.TagValueOutput;
|
| 111 | import net.minecraft.world.level.storage.loot.LootContext;
|
| 112 | import net.minecraft.world.level.storage.loot.LootParams;
|
| 113 | import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
|
| 114 | import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
|
| 115 | import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
|
| 116 | import net.minecraft.world.phys.Vec3;
|
| 117 | import net.minecraft.world.scores.Objective;
|
| 118 | import net.minecraft.world.scores.ReadOnlyScoreInfo;
|
| 119 | import net.minecraft.world.scores.ScoreAccess;
|
| 120 | import net.minecraft.world.scores.ScoreHolder;
|
| 121 | import net.minecraft.world.scores.Scoreboard;
|
| 122 | import org.jspecify.annotations.Nullable;
|
| 123 | import org.slf4j.Logger;
|
| 124 |
|
| 125 | public class ExecuteCommand {
|
| 126 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 127 | private static final int MAX_TEST_AREA = 32768;
|
| 128 | private static final Dynamic2CommandExceptionType ERROR_AREA_TOO_LARGE = new Dynamic2CommandExceptionType(
|
| 129 | (max, count) -> Component.translatableEscape("commands.execute.blocks.toobig", max, count)
|
| 130 | );
|
| 131 | private static final SimpleCommandExceptionType ERROR_CONDITIONAL_FAILED = new SimpleCommandExceptionType(
|
| 132 | Component.translatable("commands.execute.conditional.fail")
|
| 133 | );
|
| 134 | private static final DynamicCommandExceptionType ERROR_CONDITIONAL_FAILED_COUNT = new DynamicCommandExceptionType(
|
| 135 | count -> Component.translatableEscape("commands.execute.conditional.fail_count", count)
|
| 136 | );
|
| 137 | @VisibleForTesting
|
| 138 | public static final Dynamic2CommandExceptionType ERROR_FUNCTION_CONDITION_INSTANTATION_FAILURE = new Dynamic2CommandExceptionType(
|
| 139 | (id, reason) -> Component.translatableEscape("commands.execute.function.instantiationFailure", id, reason)
|
| 140 | );
|
| 141 |
|
| 142 | public static void register(final CommandDispatcher<CommandSourceStack> dispatcher, final CommandBuildContext context) {
|
| 143 | LiteralCommandNode<CommandSourceStack> execute = dispatcher.register(Commands.literal("execute").requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS)));
|
| 144 | dispatcher.register(
|
| 145 | Commands.literal("execute")
|
| 146 | .requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS))
|
| 147 | .then(Commands.literal("run").redirect(dispatcher.getRoot()))
|
| 148 | .then(addConditionals(execute, Commands.literal("if"), true, context))
|
| 149 | .then(addConditionals(execute, Commands.literal("unless"), false, context))
|
| 150 | .then(Commands.literal("as").then(Commands.argument("targets", EntityArgument.entities()).fork(execute, c -> {
|
| 151 | List<CommandSourceStack> result = Lists.newArrayList();
|
| 152 |
|
| 153 | for (Entity entity : EntityArgument.getOptionalEntities(c, "targets")) {
|
| 154 | result.add(c.getSource().withEntity(entity));
|
| 155 | }
|
| 156 |
|
| 157 | return result;
|
| 158 | })))
|
| 159 | .then(Commands.literal("at").then(Commands.argument("targets", EntityArgument.entities()).fork(execute, c -> {
|
| 160 | List<CommandSourceStack> result = Lists.newArrayList();
|
| 161 |
|
| 162 | for (Entity entity : EntityArgument.getOptionalEntities(c, "targets")) {
|
| 163 | result.add(c.getSource().withLevel((ServerLevel)entity.level()).withPosition(entity.position()).withRotation(entity.getRotationVector()));
|
| 164 | }
|
| 165 |
|
| 166 | return result;
|
| 167 | })))
|
| 168 | .then(Commands.literal("store").then(wrapStores(execute, Commands.literal("result"), true)).then(wrapStores(execute, Commands.literal("success"), false)))
|
| 169 | .then(
|
| 170 | Commands.literal("positioned")
|
| 171 | .then(
|
| 172 | Commands.argument("pos", Vec3Argument.vec3())
|
| 173 | .redirect(execute, c -> c.getSource().withPosition(Vec3Argument.getVec3(c, "pos")).withAnchor(EntityAnchorArgument.Anchor.FEET))
|
| 174 | )
|
| 175 | .then(Commands.literal("as").then(Commands.argument("targets", EntityArgument.entities()).fork(execute, c -> {
|
| 176 | List<CommandSourceStack> result = Lists.newArrayList();
|
| 177 |
|
| 178 | for (Entity entity : EntityArgument.getOptionalEntities(c, "targets")) {
|
| 179 | result.add(c.getSource().withPosition(entity.position()));
|
| 180 | }
|
| 181 |
|
| 182 | return result;
|
| 183 | })))
|
| 184 | .then(Commands.literal("over").then(Commands.argument("heightmap", HeightmapTypeArgument.heightmap()).redirect(execute, c -> {
|
| 185 | Vec3 position = c.getSource().getPosition();
|
| 186 | ServerLevel level = c.getSource().getLevel();
|
| 187 | double x = position.x();
|
| 188 | double z = position.z();
|
| 189 | if (!level.hasChunk(SectionPos.blockToSectionCoord(x), SectionPos.blockToSectionCoord(z))) {
|
| 190 | throw BlockPosArgument.ERROR_NOT_LOADED.create();
|
| 191 | }
|
| 192 |
|
| 193 | int height = level.getHeight(HeightmapTypeArgument.getHeightmap(c, "heightmap"), Mth.floor(x), Mth.floor(z));
|
| 194 | return c.getSource().withPosition(new Vec3(x, height, z));
|
| 195 | })))
|
| 196 | )
|
| 197 | .then(
|
| 198 | Commands.literal("rotated")
|
| 199 | .then(
|
| 200 | Commands.argument("rot", RotationArgument.rotation())
|
| 201 | .redirect(execute, c -> c.getSource().withRotation(RotationArgument.getRotation(c, "rot").getRotation(c.getSource())))
|
| 202 | )
|
| 203 | .then(Commands.literal("as").then(Commands.argument("targets", EntityArgument.entities()).fork(execute, c -> {
|
| 204 | List<CommandSourceStack> result = Lists.newArrayList();
|
| 205 |
|
| 206 | for (Entity entity : EntityArgument.getOptionalEntities(c, "targets")) {
|
| 207 | result.add(c.getSource().withRotation(entity.getRotationVector()));
|
| 208 | }
|
| 209 |
|
| 210 | return result;
|
| 211 | })))
|
| 212 | )
|
| 213 | .then(
|
| 214 | Commands.literal("facing")
|
| 215 | .then(
|
| 216 | Commands.literal("entity")
|
| 217 | .then(Commands.argument("targets", EntityArgument.entities()).then(Commands.argument("anchor", EntityAnchorArgument.anchor()).fork(execute, c -> {
|
| 218 | List<CommandSourceStack> result = Lists.newArrayList();
|
| 219 | EntityAnchorArgument.Anchor anchor = EntityAnchorArgument.getAnchor(c, "anchor");
|
| 220 |
|
| 221 | for (Entity entity : EntityArgument.getOptionalEntities(c, "targets")) {
|
| 222 | result.add(c.getSource().facing(entity, anchor));
|
| 223 | }
|
| 224 |
|
| 225 | return result;
|
| 226 | })))
|
| 227 | )
|
| 228 | .then(Commands.argument("pos", Vec3Argument.vec3()).redirect(execute, c -> c.getSource().facing(Vec3Argument.getVec3(c, "pos"))))
|
| 229 | )
|
| 230 | .then(
|
| 231 | Commands.literal("align")
|
| 232 | .then(
|
| 233 | Commands.argument("axes", SwizzleArgument.swizzle())
|
| 234 | .redirect(execute, c -> c.getSource().withPosition(c.getSource().getPosition().align(SwizzleArgument.getSwizzle(c, "axes"))))
|
| 235 | )
|
| 236 | )
|
| 237 | .then(
|
| 238 | Commands.literal("anchored")
|
| 239 | .then(
|
| 240 | Commands.argument("anchor", EntityAnchorArgument.anchor()).redirect(execute, c -> c.getSource().withAnchor(EntityAnchorArgument.getAnchor(c, "anchor")))
|
| 241 | )
|
| 242 | )
|
| 243 | .then(
|
| 244 | Commands.literal("in")
|
| 245 | .then(
|
| 246 | Commands.argument("dimension", DimensionArgument.dimension())
|
| 247 | .redirect(execute, c -> c.getSource().withLevel(DimensionArgument.getDimension(c, "dimension")))
|
| 248 | )
|
| 249 | )
|
| 250 | .then(
|
| 251 | Commands.literal("summon")
|
| 252 | .then(
|
| 253 | Commands.argument("entity", ResourceArgument.resource(context, Registries.ENTITY_TYPE))
|
| 254 | .suggests(SuggestionProviders.cast(SuggestionProviders.SUMMONABLE_ENTITIES))
|
| 255 | .redirect(execute, c -> spawnEntityAndRedirect(c.getSource(), ResourceArgument.getSummonableEntityType(c, "entity")))
|
| 256 | )
|
| 257 | )
|
| 258 | .then(createRelationOperations(execute, Commands.literal("on")))
|
| 259 | );
|
| 260 | }
|
| 261 |
|
| 262 | private static ArgumentBuilder<CommandSourceStack, ?> wrapStores(
|
| 263 | final LiteralCommandNode<CommandSourceStack> execute, final LiteralArgumentBuilder<CommandSourceStack> literal, final boolean storeResult
|
| 264 | ) {
|
| 265 | literal.then(
|
| 266 | Commands.literal("score")
|
| 267 | .then(
|
| 268 | Commands.argument("targets", ScoreHolderArgument.scoreHolders())
|
| 269 | .suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS)
|
| 270 | .then(
|
| 271 | Commands.argument("objective", ObjectiveArgument.objective())
|
| 272 | .redirect(
|
| 273 | execute,
|
| 274 | c -> storeValue(
|
| 275 | c.getSource(), ScoreHolderArgument.getNamesWithDefaultWildcard(c, "targets"), ObjectiveArgument.getObjective(c, "objective"), storeResult
|
| 276 | )
|
| 277 | )
|
| 278 | )
|
| 279 | )
|
| 280 | );
|
| 281 | literal.then(
|
| 282 | Commands.literal("bossbar")
|
| 283 | .then(
|
| 284 | Commands.argument("id", IdentifierArgument.id())
|
| 285 | .suggests(BossBarCommands.SUGGEST_BOSS_BAR)
|
| 286 | .then(Commands.literal("value").redirect(execute, c -> storeValue(c.getSource(), BossBarCommands.getBossBar(c), true, storeResult)))
|
| 287 | .then(Commands.literal("max").redirect(execute, c -> storeValue(c.getSource(), BossBarCommands.getBossBar(c), false, storeResult)))
|
| 288 | )
|
| 289 | );
|
| 290 |
|
| 291 | for (ArgProvider<DataAccessor> provider : DataCommands.TARGET_PROVIDERS) {
|
| 292 | provider.wrap(
|
| 293 | literal,
|
| 294 | p -> p.then(
|
| 295 | Commands.argument("path", NbtPathArgument.nbtPath())
|
| 296 | .then(
|
| 297 | Commands.literal("int")
|
| 298 | .then(
|
| 299 | Commands.argument("scale", DoubleArgumentType.doubleArg())
|
| 300 | .redirect(
|
| 301 | execute,
|
| 302 | c -> storeData(
|
| 303 | c.getSource(),
|
| 304 | provider.access(c),
|
| 305 | NbtPathArgument.getPath(c, "path"),
|
| 306 | v -> IntTag.valueOf((int)(v * DoubleArgumentType.getDouble(c, "scale"))),
|
| 307 | storeResult
|
| 308 | )
|
| 309 | )
|
| 310 | )
|
| 311 | )
|
| 312 | .then(
|
| 313 | Commands.literal("float")
|
| 314 | .then(
|
| 315 | Commands.argument("scale", DoubleArgumentType.doubleArg())
|
| 316 | .redirect(
|
| 317 | execute,
|
| 318 | c -> storeData(
|
| 319 | c.getSource(),
|
| 320 | provider.access(c),
|
| 321 | NbtPathArgument.getPath(c, "path"),
|
| 322 | v -> FloatTag.valueOf((float)(v * DoubleArgumentType.getDouble(c, "scale"))),
|
| 323 | storeResult
|
| 324 | )
|
| 325 | )
|
| 326 | )
|
| 327 | )
|
| 328 | .then(
|
| 329 | Commands.literal("short")
|
| 330 | .then(
|
| 331 | Commands.argument("scale", DoubleArgumentType.doubleArg())
|
| 332 | .redirect(
|
| 333 | execute,
|
| 334 | c -> storeData(
|
| 335 | c.getSource(),
|
| 336 | provider.access(c),
|
| 337 | NbtPathArgument.getPath(c, "path"),
|
| 338 | v -> ShortTag.valueOf((short)(v * DoubleArgumentType.getDouble(c, "scale"))),
|
| 339 | storeResult
|
| 340 | )
|
| 341 | )
|
| 342 | )
|
| 343 | )
|
| 344 | .then(
|
| 345 | Commands.literal("long")
|
| 346 | .then(
|
| 347 | Commands.argument("scale", DoubleArgumentType.doubleArg())
|
| 348 | .redirect(
|
| 349 | execute,
|
| 350 | c -> storeData(
|
| 351 | c.getSource(),
|
| 352 | provider.access(c),
|
| 353 | NbtPathArgument.getPath(c, "path"),
|
| 354 | v -> LongTag.valueOf((long)(v * DoubleArgumentType.getDouble(c, "scale"))),
|
| 355 | storeResult
|
| 356 | )
|
| 357 | )
|
| 358 | )
|
| 359 | )
|
| 360 | .then(
|
| 361 | Commands.literal("double")
|
| 362 | .then(
|
| 363 | Commands.argument("scale", DoubleArgumentType.doubleArg())
|
| 364 | .redirect(
|
| 365 | execute,
|
| 366 | c -> storeData(
|
| 367 | c.getSource(),
|
| 368 | provider.access(c),
|
| 369 | NbtPathArgument.getPath(c, "path"),
|
| 370 | v -> DoubleTag.valueOf(v * DoubleArgumentType.getDouble(c, "scale")),
|
| 371 | storeResult
|
| 372 | )
|
| 373 | )
|
| 374 | )
|
| 375 | )
|
| 376 | .then(
|
| 377 | Commands.literal("byte")
|
| 378 | .then(
|
| 379 | Commands.argument("scale", DoubleArgumentType.doubleArg())
|
| 380 | .redirect(
|
| 381 | execute,
|
| 382 | c -> storeData(
|
| 383 | c.getSource(),
|
| 384 | provider.access(c),
|
| 385 | NbtPathArgument.getPath(c, "path"),
|
| 386 | v -> ByteTag.valueOf((byte)(v * DoubleArgumentType.getDouble(c, "scale"))),
|
| 387 | storeResult
|
| 388 | )
|
| 389 | )
|
| 390 | )
|
| 391 | )
|
| 392 | )
|
| 393 | );
|
| 394 | }
|
| 395 |
|
| 396 | return literal;
|
| 397 | }
|
| 398 |
|
| 399 | private static CommandSourceStack storeValue(
|
| 400 | final CommandSourceStack source, final Collection<ScoreHolder> names, final Objective objective, final boolean storeResult
|
| 401 | ) {
|
| 402 | Scoreboard scoreboard = source.getServer().getScoreboard();
|
| 403 | return source.withCallback((success, result) -> {
|
| 404 | for (ScoreHolder name : names) {
|
| 405 | ScoreAccess score = scoreboard.getOrCreatePlayerScore(name, objective);
|
| 406 | int value = storeResult ? result : (success ? 1 : 0);
|
| 407 | score.set(value);
|
| 408 | }
|
| 409 | }, CommandResultCallback::chain);
|
| 410 | }
|
| 411 |
|
| 412 | private static CommandSourceStack storeValue(
|
| 413 | final CommandSourceStack source, final CustomBossEvent event, final boolean storeIntoValue, final boolean storeResult
|
| 414 | ) {
|
| 415 | return source.withCallback((success, result) -> {
|
| 416 | int value = storeResult ? result : (success ? 1 : 0);
|
| 417 | if (storeIntoValue) {
|
| 418 | event.setValue(value);
|
| 419 | } else {
|
| 420 | event.setMax(value);
|
| 421 | }
|
| 422 | }, CommandResultCallback::chain);
|
| 423 | }
|
| 424 |
|
| 425 | private static CommandSourceStack storeData(
|
| 426 | final CommandSourceStack source,
|
| 427 | final DataAccessor accessor,
|
| 428 | final NbtPathArgument.NbtPath path,
|
| 429 | final IntFunction<Tag> constructor,
|
| 430 | final boolean storeResult
|
| 431 | ) {
|
| 432 | return source.withCallback((success, result) -> {
|
| 433 | try {
|
| 434 | CompoundTag data = accessor.getData();
|
| 435 | int value = storeResult ? result : (success ? 1 : 0);
|
| 436 | path.set(data, constructor.apply(value));
|
| 437 | accessor.setData(data);
|
| 438 | } catch (CommandSyntaxException var8) {
|
| 439 | }
|
| 440 | }, CommandResultCallback::chain);
|
| 441 | }
|
| 442 |
|
| 443 | private static boolean isChunkLoaded(final ServerLevel level, final BlockPos pos) {
|
| 444 | ChunkPos chunkPos = ChunkPos.containing(pos);
|
| 445 | LevelChunk chunk = level.getChunkSource().getChunkNow(chunkPos.x(), chunkPos.z());
|
| 446 | return chunk == null ? false : chunk.getFullStatus() == FullChunkStatus.ENTITY_TICKING && level.areEntitiesLoaded(chunkPos.pack());
|
| 447 | }
|
| 448 |
|
| 449 | private static ArgumentBuilder<CommandSourceStack, ?> addConditionals(
|
| 450 | final CommandNode<CommandSourceStack> execute,
|
| 451 | final LiteralArgumentBuilder<CommandSourceStack> parent,
|
| 452 | final boolean expected,
|
| 453 | final CommandBuildContext context
|
| 454 | ) {
|
| 455 | parent.then(
|
| 456 | Commands.literal("block")
|
| 457 | .then(
|
| 458 | Commands.argument("pos", BlockPosArgument.blockPos())
|
| 459 | .then(
|
| 460 | addConditional(
|
| 461 | execute,
|
| 462 | Commands.argument("block", BlockPredicateArgument.blockPredicate(context)),
|
| 463 | expected,
|
| 464 | c -> BlockPredicateArgument.getBlockPredicate(c, "block")
|
| 465 | .test(new BlockInWorld(c.getSource().getLevel(), BlockPosArgument.getLoadedBlockPos(c, "pos"), true))
|
| 466 | )
|
| 467 | )
|
| 468 | )
|
| 469 | )
|
| 470 | .then(
|
| 471 | Commands.literal("biome")
|
| 472 | .then(
|
| 473 | Commands.argument("pos", BlockPosArgument.blockPos())
|
| 474 | .then(
|
| 475 | addConditional(
|
| 476 | execute,
|
| 477 | Commands.argument("biome", ResourceOrTagArgument.resourceOrTag(context, Registries.BIOME)),
|
| 478 | expected,
|
| 479 | c -> ResourceOrTagArgument.getResourceOrTag(c, "biome", Registries.BIOME)
|
| 480 | .test(c.getSource().getLevel().getBiome(BlockPosArgument.getLoadedBlockPos(c, "pos")))
|
| 481 | )
|
| 482 | )
|
| 483 | )
|
| 484 | )
|
| 485 | .then(
|
| 486 | Commands.literal("loaded")
|
| 487 | .then(
|
| 488 | addConditional(
|
| 489 | execute,
|
| 490 | Commands.argument("pos", BlockPosArgument.blockPos()),
|
| 491 | expected,
|
| 492 | c -> isChunkLoaded(c.getSource().getLevel(), BlockPosArgument.getBlockPos(c, "pos"))
|
| 493 | )
|
| 494 | )
|
| 495 | )
|
| 496 | .then(
|
| 497 | Commands.literal("dimension")
|
| 498 | .then(
|
| 499 | addConditional(
|
| 500 | execute,
|
| 501 | Commands.argument("dimension", DimensionArgument.dimension()),
|
| 502 | expected,
|
| 503 | c -> DimensionArgument.getDimension(c, "dimension") == c.getSource().getLevel()
|
| 504 | )
|
| 505 | )
|
| 506 | )
|
| 507 | .then(
|
| 508 | Commands.literal("score")
|
| 509 | .then(
|
| 510 | Commands.argument("target", ScoreHolderArgument.scoreHolder())
|
| 511 | .suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS)
|
| 512 | .then(
|
| 513 | Commands.argument("targetObjective", ObjectiveArgument.objective())
|
| 514 | .then(
|
| 515 | Commands.literal("=")
|
| 516 | .then(
|
| 517 | Commands.argument("source", ScoreHolderArgument.scoreHolder())
|
| 518 | .suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS)
|
| 519 | .then(addConditional(execute, Commands.argument("sourceObjective", ObjectiveArgument.objective()), expected, c -> checkScore(c, (a, b) -> a == b)))
|
| 520 | )
|
| 521 | )
|
| 522 | .then(
|
| 523 | Commands.literal("<")
|
| 524 | .then(
|
| 525 | Commands.argument("source", ScoreHolderArgument.scoreHolder())
|
| 526 | .suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS)
|
| 527 | .then(addConditional(execute, Commands.argument("sourceObjective", ObjectiveArgument.objective()), expected, c -> checkScore(c, (a, b) -> a < b)))
|
| 528 | )
|
| 529 | )
|
| 530 | .then(
|
| 531 | Commands.literal("<=")
|
| 532 | .then(
|
| 533 | Commands.argument("source", ScoreHolderArgument.scoreHolder())
|
| 534 | .suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS)
|
| 535 | .then(addConditional(execute, Commands.argument("sourceObjective", ObjectiveArgument.objective()), expected, c -> checkScore(c, (a, b) -> a <= b)))
|
| 536 | )
|
| 537 | )
|
| 538 | .then(
|
| 539 | Commands.literal(">")
|
| 540 | .then(
|
| 541 | Commands.argument("source", ScoreHolderArgument.scoreHolder())
|
| 542 | .suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS)
|
| 543 | .then(addConditional(execute, Commands.argument("sourceObjective", ObjectiveArgument.objective()), expected, c -> checkScore(c, (a, b) -> a > b)))
|
| 544 | )
|
| 545 | )
|
| 546 | .then(
|
| 547 | Commands.literal(">=")
|
| 548 | .then(
|
| 549 | Commands.argument("source", ScoreHolderArgument.scoreHolder())
|
| 550 | .suggests(ScoreHolderArgument.SUGGEST_SCORE_HOLDERS)
|
| 551 | .then(addConditional(execute, Commands.argument("sourceObjective", ObjectiveArgument.objective()), expected, c -> checkScore(c, (a, b) -> a >= b)))
|
| 552 | )
|
| 553 | )
|
| 554 | .then(
|
| 555 | Commands.literal("matches")
|
| 556 | .then(
|
| 557 | addConditional(execute, Commands.argument("range", RangeArgument.intRange()), expected, c -> checkScore(c, RangeArgument.Ints.getRange(c, "range")))
|
| 558 | )
|
| 559 | )
|
| 560 | )
|
| 561 | )
|
| 562 | )
|
| 563 | .then(
|
| 564 | Commands.literal("blocks")
|
| 565 | .then(
|
| 566 | Commands.argument("start", BlockPosArgument.blockPos())
|
| 567 | .then(
|
| 568 | Commands.argument("end", BlockPosArgument.blockPos())
|
| 569 | .then(
|
| 570 | Commands.argument("destination", BlockPosArgument.blockPos())
|
| 571 | .then(addIfBlocksConditional(execute, Commands.literal("all"), expected, false))
|
| 572 | .then(addIfBlocksConditional(execute, Commands.literal("masked"), expected, true))
|
| 573 | )
|
| 574 | )
|
| 575 | )
|
| 576 | )
|
| 577 | .then(
|
| 578 | Commands.literal("entity")
|
| 579 | .then(
|
| 580 | Commands.argument("entities", EntityArgument.entities())
|
| 581 | .fork(execute, c -> expect(c, expected, !EntityArgument.getOptionalEntities(c, "entities").isEmpty()))
|
| 582 | .executes(createNumericConditionalHandler(expected, c -> EntityArgument.getOptionalEntities(c, "entities").size()))
|
| 583 | )
|
| 584 | )
|
| 585 | .then(
|
| 586 | Commands.literal("predicate")
|
| 587 | .then(
|
| 588 | addConditional(
|
| 589 | execute,
|
| 590 | Commands.argument("predicate", ResourceOrIdArgument.lootPredicate(context)),
|
| 591 | expected,
|
| 592 | c -> checkCustomPredicate(c.getSource(), ResourceOrIdArgument.getLootPredicate(c, "predicate"))
|
| 593 | )
|
| 594 | )
|
| 595 | )
|
| 596 | .then(
|
| 597 | Commands.literal("function")
|
| 598 | .then(
|
| 599 | Commands.argument("name", FunctionArgument.functions())
|
| 600 | .suggests(FunctionCommand.SUGGEST_FUNCTION)
|
| 601 | .fork(execute, new ExecuteCommand.ExecuteIfFunctionCustomModifier(expected))
|
| 602 | )
|
| 603 | )
|
| 604 | .then(
|
| 605 | Commands.literal("stopwatch")
|
| 606 | .then(
|
| 607 | Commands.argument("id", IdentifierArgument.id())
|
| 608 | .suggests(StopwatchCommand.SUGGEST_STOPWATCHES)
|
| 609 | .then(
|
| 610 | addConditional(
|
| 611 | execute, Commands.argument("range", RangeArgument.floatRange()), expected, c -> checkStopwatch(c, RangeArgument.Floats.getRange(c, "range"))
|
| 612 | )
|
| 613 | )
|
| 614 | )
|
| 615 | );
|
| 616 |
|
| 617 | for (ArgProvider<DataAccessor> provider : DataCommands.SOURCE_PROVIDERS) {
|
| 618 | parent.then(
|
| 619 | provider.wrap(
|
| 620 | Commands.literal("data"),
|
| 621 | p -> p.then(
|
| 622 | Commands.argument("path", NbtPathArgument.nbtPath())
|
| 623 | .fork(execute, c -> expect(c, expected, checkMatchingData(provider.access(c), NbtPathArgument.getPath(c, "path")) > 0))
|
| 624 | .executes(createNumericConditionalHandler(expected, c -> checkMatchingData(provider.access(c), NbtPathArgument.getPath(c, "path"))))
|
| 625 | )
|
| 626 | )
|
| 627 | );
|
| 628 | }
|
| 629 |
|
| 630 | for (ArgProvider<ItemAccessor<?>> provider : ItemCommands.SOURCE_PROVIDERS) {
|
| 631 | parent.then(
|
| 632 | provider.wrap(
|
| 633 | Commands.literal("items"),
|
| 634 | p -> p.then(
|
| 635 | Commands.argument("slots", SlotSourceArgument.slotSource(context))
|
| 636 | .then(
|
| 637 | Commands.argument("item_predicate", ItemPredicateArgument.itemPredicate(context))
|
| 638 | .fork(
|
| 639 | execute,
|
| 640 | c -> expect(
|
| 641 | c,
|
| 642 | expected,
|
| 643 | countItems(
|
| 644 | c.getSource(), provider.access(c), SlotSourceArgument.getSlotSource(c, "slots"), ItemPredicateArgument.getItemPredicate(c, "item_predicate")
|
| 645 | )
|
| 646 | > 0
|
| 647 | )
|
| 648 | )
|
| 649 | .executes(
|
| 650 | createNumericConditionalHandler(
|
| 651 | expected,
|
| 652 | c -> countItems(
|
| 653 | c.getSource(), provider.access(c), SlotSourceArgument.getSlotSource(c, "slots"), ItemPredicateArgument.getItemPredicate(c, "item_predicate")
|
| 654 | )
|
| 655 | )
|
| 656 | )
|
| 657 | )
|
| 658 | )
|
| 659 | )
|
| 660 | )
|
| 661 | .then(
|
| 662 | provider.wrap(
|
| 663 | Commands.literal("slots"),
|
| 664 | p -> p.then(
|
| 665 | Commands.argument("slots", SlotSourceArgument.slotSource(context))
|
| 666 | .fork(execute, c -> expect(c, expected, countSlots(c.getSource(), provider.access(c), SlotSourceArgument.getSlotSource(c, "slots")) > 0))
|
| 667 | .executes(createNumericConditionalHandler(expected, c -> countSlots(c.getSource(), provider.access(c), SlotSourceArgument.getSlotSource(c, "slots"))))
|
| 668 | )
|
| 669 | )
|
| 670 | );
|
| 671 | }
|
| 672 |
|
| 673 | return parent;
|
| 674 | }
|
| 675 |
|
| 676 | private static int countItems(
|
| 677 | final CommandSourceStack source, final ItemAccessor<?> accessor, final SlotSourceArgument.Result slotSource, final Predicate<ItemStack> predicate
|
| 678 | ) throws CommandSyntaxException {
|
| 679 | SlotCollection slots = accessor.getSlots(source, slotSource.value());
|
| 680 | return slots.itemCopies().filter(predicate).mapToInt(ItemStack::getCount).sum();
|
| 681 | }
|
| 682 |
|
| 683 | private static int countSlots(final CommandSourceStack source, final ItemAccessor<?> accessor, final SlotSourceArgument.Result slotSource) throws CommandSyntaxException {
|
| 684 | SlotCollection slots = accessor.getSlots(source, slotSource.value());
|
| 685 | return slots.size();
|
| 686 | }
|
| 687 |
|
| 688 | private static Command<CommandSourceStack> createNumericConditionalHandler(final boolean expected, final ExecuteCommand.CommandNumericPredicate condition) {
|
| 689 | return expected ? c -> {
|
| 690 | int count = condition.test(c);
|
| 691 | if (count > 0) {
|
| 692 | c.getSource().sendSuccess(() -> Component.translatable("commands.execute.conditional.pass_count", count), false);
|
| 693 | return count;
|
| 694 | } else {
|
| 695 | throw ERROR_CONDITIONAL_FAILED.create();
|
| 696 | }
|
| 697 | } : c -> {
|
| 698 | int count = condition.test(c);
|
| 699 | if (count == 0) {
|
| 700 | c.getSource().sendSuccess(() -> Component.translatable("commands.execute.conditional.pass"), false);
|
| 701 | return 1;
|
| 702 | } else {
|
| 703 | throw ERROR_CONDITIONAL_FAILED_COUNT.create(count);
|
| 704 | }
|
| 705 | };
|
| 706 | }
|
| 707 |
|
| 708 | private static int checkMatchingData(final DataAccessor accessor, final NbtPathArgument.NbtPath path) throws CommandSyntaxException {
|
| 709 | return path.countMatching(accessor.getData());
|
| 710 | }
|
| 711 |
|
| 712 | private static boolean checkScore(final CommandContext<CommandSourceStack> context, final ExecuteCommand.IntBiPredicate operation) throws CommandSyntaxException {
|
| 713 | ScoreHolder target = ScoreHolderArgument.getName(context, "target");
|
| 714 | Objective targetObjective = ObjectiveArgument.getObjective(context, "targetObjective");
|
| 715 | ScoreHolder source = ScoreHolderArgument.getName(context, "source");
|
| 716 | Objective sourceObjective = ObjectiveArgument.getObjective(context, "sourceObjective");
|
| 717 | Scoreboard scoreboard = context.getSource().getServer().getScoreboard();
|
| 718 | ReadOnlyScoreInfo a = scoreboard.getPlayerScoreInfo(target, targetObjective);
|
| 719 | ReadOnlyScoreInfo b = scoreboard.getPlayerScoreInfo(source, sourceObjective);
|
| 720 | return a != null && b != null ? operation.test(a.value(), b.value()) : false;
|
| 721 | }
|
| 722 |
|
| 723 | private static boolean checkScore(final CommandContext<CommandSourceStack> context, final MinMaxBounds.Ints range) throws CommandSyntaxException {
|
| 724 | ScoreHolder target = ScoreHolderArgument.getName(context, "target");
|
| 725 | Objective targetObjective = ObjectiveArgument.getObjective(context, "targetObjective");
|
| 726 | Scoreboard scoreboard = context.getSource().getServer().getScoreboard();
|
| 727 | ReadOnlyScoreInfo scoreInfo = scoreboard.getPlayerScoreInfo(target, targetObjective);
|
| 728 | return scoreInfo == null ? false : range.matches(scoreInfo.value());
|
| 729 | }
|
| 730 |
|
| 731 | private static boolean checkStopwatch(final CommandContext<CommandSourceStack> context, final MinMaxBounds.Doubles range) throws CommandSyntaxException {
|
| 732 | Identifier id = IdentifierArgument.getId(context, "id");
|
| 733 | Stopwatches stopwatches = context.getSource().getServer().getStopwatches();
|
| 734 | Stopwatch stopwatch = stopwatches.get(id);
|
| 735 | if (stopwatch == null) {
|
| 736 | throw StopwatchCommand.ERROR_DOES_NOT_EXIST.create(id);
|
| 737 | }
|
| 738 |
|
| 739 | long currentTime = Stopwatches.currentTime();
|
| 740 | double elapsedSeconds = stopwatch.elapsedSeconds(currentTime);
|
| 741 | return range.matches(elapsedSeconds);
|
| 742 | }
|
| 743 |
|
| 744 | private static boolean checkCustomPredicate(final CommandSourceStack source, final Holder<LootItemCondition> predicate) {
|
| 745 | ServerLevel level = source.getLevel();
|
| 746 | LootParams lootParams = new LootParams.Builder(level)
|
| 747 | .withParameter(LootContextParams.ORIGIN, source.getPosition())
|
| 748 | .withOptionalParameter(LootContextParams.THIS_ENTITY, source.getEntity())
|
| 749 | .create(LootContextParamSets.COMMAND);
|
| 750 | LootContext context = new LootContext.Builder(lootParams).create(Optional.empty());
|
| 751 | context.pushVisitedElement(LootContext.createVisitedEntry(predicate.value()));
|
| 752 | return predicate.value().test(context);
|
| 753 | }
|
| 754 |
|
| 755 | private static Collection<CommandSourceStack> expect(final CommandContext<CommandSourceStack> context, final boolean expected, final boolean result) {
|
| 756 | return result == expected ? Collections.singleton(context.getSource()) : Collections.emptyList();
|
| 757 | }
|
| 758 |
|
| 759 | private static ArgumentBuilder<CommandSourceStack, ?> addConditional(
|
| 760 | final CommandNode<CommandSourceStack> root,
|
| 761 | final ArgumentBuilder<CommandSourceStack, ?> argument,
|
| 762 | final boolean expected,
|
| 763 | final ExecuteCommand.CommandPredicate predicate
|
| 764 | ) {
|
| 765 | return argument.fork(root, c -> expect(c, expected, predicate.test(c))).executes(c -> {
|
| 766 | if (expected == predicate.test(c)) {
|
| 767 | c.getSource().sendSuccess(() -> Component.translatable("commands.execute.conditional.pass"), false);
|
| 768 | return 1;
|
| 769 | } else {
|
| 770 | throw ERROR_CONDITIONAL_FAILED.create();
|
| 771 | }
|
| 772 | });
|
| 773 | }
|
| 774 |
|
| 775 | private static ArgumentBuilder<CommandSourceStack, ?> addIfBlocksConditional(
|
| 776 | final CommandNode<CommandSourceStack> root, final ArgumentBuilder<CommandSourceStack, ?> argument, final boolean expected, final boolean skipAir
|
| 777 | ) {
|
| 778 | return argument.fork(root, c -> expect(c, expected, checkRegions(c, skipAir).isPresent()))
|
| 779 | .executes(expected ? c -> checkIfRegions(c, skipAir) : c -> checkUnlessRegions(c, skipAir));
|
| 780 | }
|
| 781 |
|
| 782 | private static int checkIfRegions(final CommandContext<CommandSourceStack> context, final boolean skipAir) throws CommandSyntaxException {
|
| 783 | OptionalInt count = checkRegions(context, skipAir);
|
| 784 | if (count.isPresent()) {
|
| 785 | context.getSource().sendSuccess(() -> Component.translatable("commands.execute.conditional.pass_count", count.getAsInt()), false);
|
| 786 | return count.getAsInt();
|
| 787 | } else {
|
| 788 | throw ERROR_CONDITIONAL_FAILED.create();
|
| 789 | }
|
| 790 | }
|
| 791 |
|
| 792 | private static int checkUnlessRegions(final CommandContext<CommandSourceStack> context, final boolean skipAir) throws CommandSyntaxException {
|
| 793 | OptionalInt count = checkRegions(context, skipAir);
|
| 794 | if (count.isPresent()) {
|
| 795 | throw ERROR_CONDITIONAL_FAILED_COUNT.create(count.getAsInt());
|
| 796 | }
|
| 797 |
|
| 798 | context.getSource().sendSuccess(() -> Component.translatable("commands.execute.conditional.pass"), false);
|
| 799 | return 1;
|
| 800 | }
|
| 801 |
|
| 802 | private static OptionalInt checkRegions(final CommandContext<CommandSourceStack> context, final boolean skipAir) throws CommandSyntaxException {
|
| 803 | return checkRegions(
|
| 804 | context.getSource().getLevel(),
|
| 805 | BlockPosArgument.getLoadedBlockPos(context, "start"),
|
| 806 | BlockPosArgument.getLoadedBlockPos(context, "end"),
|
| 807 | BlockPosArgument.getLoadedBlockPos(context, "destination"),
|
| 808 | skipAir
|
| 809 | );
|
| 810 | }
|
| 811 |
|
| 812 | private static OptionalInt checkRegions(final ServerLevel level, final BlockPos startPos, final BlockPos endPos, final BlockPos destPos, final boolean skipAir) throws CommandSyntaxException {
|
| 813 | BoundingBox from = BoundingBox.fromCorners(startPos, endPos);
|
| 814 | BoundingBox destination = BoundingBox.fromCorners(destPos, destPos.offset(from.getLength()));
|
| 815 | BlockPos offset = new BlockPos(destination.minX() - from.minX(), destination.minY() - from.minY(), destination.minZ() - from.minZ());
|
| 816 | long area = (long)from.getXSpan() * from.getYSpan() * from.getZSpan();
|
| 817 | if (area > 32768L) {
|
| 818 | throw ERROR_AREA_TOO_LARGE.create(32768, area);
|
| 819 | }
|
| 820 |
|
| 821 | int count = 0;
|
| 822 | RegistryAccess registryAccess = level.registryAccess();
|
| 823 |
|
| 824 | try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(LOGGER)) {
|
| 825 | for (int z = from.minZ(); z <= from.maxZ(); z++) {
|
| 826 | for (int y = from.minY(); y <= from.maxY(); y++) {
|
| 827 | for (int x = from.minX(); x <= from.maxX(); x++) {
|
| 828 | BlockPos sourcePos = new BlockPos(x, y, z);
|
| 829 | BlockPos destinationPos = sourcePos.offset(offset);
|
| 830 | BlockState sourceBlock = level.getBlockState(sourcePos);
|
| 831 | if (!skipAir || !sourceBlock.is(Blocks.AIR)) {
|
| 832 | if (sourceBlock != level.getBlockState(destinationPos)) {
|
| 833 | return OptionalInt.empty();
|
| 834 | }
|
| 835 |
|
| 836 | BlockEntity sourceBlockEntity = level.getBlockEntity(sourcePos);
|
| 837 | BlockEntity destinationBlockEntity = level.getBlockEntity(destinationPos);
|
| 838 | if (sourceBlockEntity != null) {
|
| 839 | if (destinationBlockEntity == null) {
|
| 840 | return OptionalInt.empty();
|
| 841 | }
|
| 842 |
|
| 843 | if (destinationBlockEntity.getType() != sourceBlockEntity.getType()) {
|
| 844 | return OptionalInt.empty();
|
| 845 | }
|
| 846 |
|
| 847 | if (!sourceBlockEntity.components().equals(destinationBlockEntity.components())) {
|
| 848 | return OptionalInt.empty();
|
| 849 | }
|
| 850 |
|
| 851 | TagValueOutput sourceOutput = TagValueOutput.createWithContext(reporter.forChild(sourceBlockEntity.problemPath()), registryAccess);
|
| 852 | sourceBlockEntity.saveCustomOnly(sourceOutput);
|
| 853 | CompoundTag sourceTag = sourceOutput.buildResult();
|
| 854 | TagValueOutput destinationOutput = TagValueOutput.createWithContext(reporter.forChild(destinationBlockEntity.problemPath()), registryAccess);
|
| 855 | destinationBlockEntity.saveCustomOnly(destinationOutput);
|
| 856 | CompoundTag destinationTag = destinationOutput.buildResult();
|
| 857 | if (!sourceTag.equals(destinationTag)) {
|
| 858 | return OptionalInt.empty();
|
| 859 | }
|
| 860 | }
|
| 861 |
|
| 862 | count++;
|
| 863 | }
|
| 864 | }
|
| 865 | }
|
| 866 | }
|
| 867 | }
|
| 868 |
|
| 869 | return OptionalInt.of(count);
|
| 870 | }
|
| 871 |
|
| 872 | private static RedirectModifier<CommandSourceStack> expandOneToOneEntityRelation(final Function<Entity, Optional<Entity>> unpacker) {
|
| 873 | return context -> {
|
| 874 | CommandSourceStack source = context.getSource();
|
| 875 | Entity entity = source.getEntity();
|
| 876 | return entity == null ? List.of() : unpacker.apply(entity).filter(e -> !e.isRemoved()).map(e -> List.of(source.withEntity(e))).orElse(List.of());
|
| 877 | };
|
| 878 | }
|
| 879 |
|
| 880 | private static RedirectModifier<CommandSourceStack> expandOneToManyEntityRelation(final Function<Entity, Stream<Entity>> unpacker) {
|
| 881 | return context -> {
|
| 882 | CommandSourceStack source = context.getSource();
|
| 883 | Entity entity = source.getEntity();
|
| 884 | return entity == null ? List.of() : unpacker.apply(entity).filter(e -> !e.isRemoved()).map(source::withEntity).toList();
|
| 885 | };
|
| 886 | }
|
| 887 |
|
| 888 | private static LiteralArgumentBuilder<CommandSourceStack> createRelationOperations(
|
| 889 | final CommandNode<CommandSourceStack> execute, final LiteralArgumentBuilder<CommandSourceStack> on
|
| 890 | ) {
|
| 891 | return on.then(
|
| 892 | Commands.literal("owner")
|
| 893 | .fork(
|
| 894 | execute, expandOneToOneEntityRelation(e -> e instanceof OwnableEntity ownableEntity ? Optional.ofNullable(ownableEntity.getOwner()) : Optional.empty())
|
| 895 | )
|
| 896 | )
|
| 897 | .then(
|
| 898 | Commands.literal("leasher")
|
| 899 | .fork(execute, expandOneToOneEntityRelation(e -> e instanceof Leashable leashable ? Optional.ofNullable(leashable.getLeashHolder()) : Optional.empty()))
|
| 900 | )
|
| 901 | .then(
|
| 902 | Commands.literal("target")
|
| 903 | .fork(execute, expandOneToOneEntityRelation(e -> e instanceof Targeting targeting ? Optional.ofNullable(targeting.getTarget()) : Optional.empty()))
|
| 904 | )
|
| 905 | .then(
|
| 906 | Commands.literal("attacker")
|
| 907 | .fork(
|
| 908 | execute, expandOneToOneEntityRelation(e -> e instanceof Attackable attackable ? Optional.ofNullable(attackable.getLastAttacker()) : Optional.empty())
|
| 909 | )
|
| 910 | )
|
| 911 | .then(Commands.literal("vehicle").fork(execute, expandOneToOneEntityRelation(e -> Optional.ofNullable(e.getVehicle()))))
|
| 912 | .then(Commands.literal("controller").fork(execute, expandOneToOneEntityRelation(e -> Optional.ofNullable(e.getControllingPassenger()))))
|
| 913 | .then(
|
| 914 | Commands.literal("origin")
|
| 915 | .fork(execute, expandOneToOneEntityRelation(e -> e instanceof TraceableEntity traceable ? Optional.ofNullable(traceable.getOwner()) : Optional.empty()))
|
| 916 | )
|
| 917 | .then(Commands.literal("passengers").fork(execute, expandOneToManyEntityRelation(e -> e.getPassengers().stream())));
|
| 918 | }
|
| 919 |
|
| 920 | private static CommandSourceStack spawnEntityAndRedirect(final CommandSourceStack source, final Holder.Reference<EntityType<?>> type) throws CommandSyntaxException {
|
| 921 | Entity entity = SummonCommand.createEntity(source, type, source.getPosition(), new CompoundTag(), true);
|
| 922 | return source.withEntity(entity);
|
| 923 | }
|
| 924 |
|
| 925 | public static <T extends ExecutionCommandSource<T>> void scheduleFunctionConditionsAndTest(
|
| 926 | final T originalSource,
|
| 927 | final List<T> currentSources,
|
| 928 | final Function<T, T> functionContextModifier,
|
| 929 | final IntPredicate check,
|
| 930 | final ContextChain<T> currentStep,
|
| 931 | final @Nullable CompoundTag parameters,
|
| 932 | final ExecutionControl<T> output,
|
| 933 | final InCommandFunction<CommandContext<T>, Collection<CommandFunction<T>>> functionGetter,
|
| 934 | final ChainModifiers modifiers
|
| 935 | ) {
|
| 936 | List<T> filteredSources = new ArrayList<>(currentSources.size());
|
| 937 |
|
| 938 | Collection<CommandFunction<T>> functionsToRun;
|
| 939 | try {
|
| 940 | functionsToRun = functionGetter.apply(currentStep.getTopContext().copyFor(originalSource));
|
| 941 | } catch (CommandSyntaxException e) {
|
| 942 | originalSource.handleError(e, modifiers.isForked(), output.tracer());
|
| 943 | return;
|
| 944 | }
|
| 945 |
|
| 946 | int functionCount = functionsToRun.size();
|
| 947 | if (functionCount != 0) {
|
| 948 | List<InstantiatedFunction<T>> instantiatedFunctions = new ArrayList<>(functionCount);
|
| 949 |
|
| 950 | try {
|
| 951 | for (CommandFunction<T> function : functionsToRun) {
|
| 952 | try {
|
| 953 | instantiatedFunctions.add(function.instantiate(parameters, originalSource.dispatcher()));
|
| 954 | } catch (FunctionInstantiationException e) {
|
| 955 | throw ERROR_FUNCTION_CONDITION_INSTANTATION_FAILURE.create(function.id(), e.messageComponent());
|
| 956 | }
|
| 957 | }
|
| 958 | } catch (CommandSyntaxException e) {
|
| 959 | originalSource.handleError(e, modifiers.isForked(), output.tracer());
|
| 960 | }
|
| 961 |
|
| 962 | for (T source : currentSources) {
|
| 963 | T newFunctionContext = (T)functionContextModifier.apply(source.clearCallbacks());
|
| 964 | CommandResultCallback functionCallback = (success, result) -> {
|
| 965 | if (check.test(result)) {
|
| 966 | filteredSources.add(source);
|
| 967 | }
|
| 968 | };
|
| 969 | output.queueNext(new IsolatedCall<>(o -> {
|
| 970 | for (InstantiatedFunction<T> function : instantiatedFunctions) {
|
| 971 | o.queueNext(new CallFunction<>(function, o.currentFrame().returnValueConsumer(), true).bind(newFunctionContext));
|
| 972 | }
|
| 973 |
|
| 974 | o.queueNext(FallthroughTask.instance());
|
| 975 | }, functionCallback));
|
| 976 | }
|
| 977 |
|
| 978 | ContextChain<T> nextStage = currentStep.nextStage();
|
| 979 | String input = currentStep.getTopContext().getInput();
|
| 980 | output.queueNext(new BuildContexts.Continuation<>(input, nextStage, modifiers, originalSource, filteredSources));
|
| 981 | }
|
| 982 | }
|
| 983 |
|
| 984 | @FunctionalInterface
|
| 985 | private interface CommandNumericPredicate {
|
| 986 | int test(CommandContext<CommandSourceStack> c) throws CommandSyntaxException;
|
| 987 | }
|
| 988 |
|
| 989 | @FunctionalInterface
|
| 990 | private interface CommandPredicate {
|
| 991 | boolean test(CommandContext<CommandSourceStack> c) throws CommandSyntaxException;
|
| 992 | }
|
| 993 |
|
| 994 | private static class ExecuteIfFunctionCustomModifier implements CustomModifierExecutor.ModifierAdapter<CommandSourceStack> {
|
| 995 | private final IntPredicate check;
|
| 996 |
|
| 997 | private ExecuteIfFunctionCustomModifier(final boolean check) {
|
| 998 | this.check = check ? value -> value != 0 : value -> value == 0;
|
| 999 | }
|
| 1000 |
|
| 1001 | public void apply(
|
| 1002 | final CommandSourceStack originalSource,
|
| 1003 | final List<CommandSourceStack> currentSources,
|
| 1004 | final ContextChain<CommandSourceStack> currentStep,
|
| 1005 | final ChainModifiers modifiers,
|
| 1006 | final ExecutionControl<CommandSourceStack> output
|
| 1007 | ) {
|
| 1008 | ExecuteCommand.scheduleFunctionConditionsAndTest(
|
| 1009 | originalSource,
|
| 1010 | currentSources,
|
| 1011 | FunctionCommand::modifySenderForExecution,
|
| 1012 | this.check,
|
| 1013 | currentStep,
|
| 1014 | null,
|
| 1015 | output,
|
| 1016 | c -> FunctionArgument.getFunctions(c, "name"),
|
| 1017 | modifiers
|
| 1018 | );
|
| 1019 | }
|
| 1020 | }
|
| 1021 |
|
| 1022 | @FunctionalInterface
|
| 1023 | private interface IntBiPredicate {
|
| 1024 | boolean test(int a, int b);
|
| 1025 | }
|
| 1026 | }
|
| 1027 |
|