Search in sources :

Example 6 with CommandSourceStack

use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.

the class CommandsMixin method impl$preventPutIntoMapIfNodeIsComplex.

@SuppressWarnings("unchecked")
@Redirect(method = "fillUsableCommands", at = @At(value = "INVOKE", target = "Ljava/util/Map;put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", remap = false))
private <K, V> V impl$preventPutIntoMapIfNodeIsComplex(final Map<K, V> map, final K key, final V value, final CommandNode<CommandSourceStack> rootCommandSource, final CommandNode<SharedSuggestionProvider> rootSuggestion, final CommandSourceStack source, final Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> commandNodeToSuggestionNode) {
    if (!map.containsKey(key)) {
        // done here because this check is applicable
        final ServerPlayer e = (ServerPlayer) source.getEntity();
        final Map<CommandNode<CommandSourceStack>, List<CommandNode<SharedSuggestionProvider>>> playerNodes = this.impl$playerNodeCache.get(e);
        if (!playerNodes.containsKey(key)) {
            final List<CommandNode<SharedSuggestionProvider>> children = new ArrayList<>();
            children.add((CommandNode<SharedSuggestionProvider>) value);
            playerNodes.put((CommandNode<CommandSourceStack>) key, children);
        }
        // we need to swap it out.
        if (value instanceof ArgumentCommandNode && CommandUtil.checkForCustomSuggestions(rootSuggestion)) {
            rootSuggestion.addChild(this.impl$cloneArgumentCommandNodeWithoutSuggestions((ArgumentCommandNode<SharedSuggestionProvider, ?>) value));
        } else {
            rootSuggestion.addChild((CommandNode<SharedSuggestionProvider>) value);
        }
        return map.put(key, value);
    }
    // it's ignored anyway.
    return null;
}
Also used : ArgumentCommandNode(com.mojang.brigadier.tree.ArgumentCommandNode) SpongeArgumentCommandNode(org.spongepowered.common.command.brigadier.tree.SpongeArgumentCommandNode) ArgumentCommandNode(com.mojang.brigadier.tree.ArgumentCommandNode) RootCommandNode(com.mojang.brigadier.tree.RootCommandNode) SpongeArgumentCommandNode(org.spongepowered.common.command.brigadier.tree.SpongeArgumentCommandNode) CommandNode(com.mojang.brigadier.tree.CommandNode) ServerPlayer(net.minecraft.server.level.ServerPlayer) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) SharedSuggestionProvider(net.minecraft.commands.SharedSuggestionProvider) CommandSourceStack(net.minecraft.commands.CommandSourceStack) Redirect(org.spongepowered.asm.mixin.injection.Redirect)

Example 7 with CommandSourceStack

use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.

the class CommandSourceStackMixin method impl$updateCauseOnWithPosition.

@Inject(method = "withPosition", at = @At("RETURN"))
private void impl$updateCauseOnWithPosition(final Vec3 pos, final CallbackInfoReturnable<CommandSourceStack> cir) {
    if (cir.getReturnValue() != (Object) this) {
        final org.spongepowered.math.vector.Vector3d position = VecHelper.toVector3d(pos);
        final ServerLocation location = this.impl$cause.context().get(EventContextKeys.LOCATION).map(x -> ServerLocation.of(x.world(), position)).orElseGet(() -> ServerLocation.of((org.spongepowered.api.world.server.ServerWorld) cir.getReturnValue().getLevel(), position));
        ((CommandSourceStackBridge) cir.getReturnValue()).bridge$setCause(this.impl$applyToCause(EventContextKeys.LOCATION, location));
    }
}
Also used : EventContextKey(org.spongepowered.api.event.EventContextKey) CommandSourceStackAccessor(org.spongepowered.common.accessor.commands.CommandSourceStackAccessor) EventContextKeys(org.spongepowered.api.event.EventContextKeys) CommandSourceStack(net.minecraft.commands.CommandSourceStack) Inject(org.spongepowered.asm.mixin.injection.Inject) HashMap(java.util.HashMap) ServerLevel(net.minecraft.server.level.ServerLevel) EventContext(org.spongepowered.api.event.EventContext) Supplier(java.util.function.Supplier) EntityAnchorArgument(net.minecraft.commands.arguments.EntityAnchorArgument) CallbackInfoReturnable(org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable) CallbackInfo(org.spongepowered.asm.mixin.injection.callback.CallbackInfo) MinecraftServer(net.minecraft.server.MinecraftServer) Mixin(org.spongepowered.asm.mixin.Mixin) CommandSourceStackBridge(org.spongepowered.common.bridge.commands.CommandSourceStackBridge) Map(java.util.Map) EntityAccessor(org.spongepowered.common.accessor.world.entity.EntityAccessor) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Nullable(org.checkerframework.checker.nullness.qual.Nullable) At(org.spongepowered.asm.mixin.injection.At) Mutable(org.spongepowered.asm.mixin.Mutable) Component(net.minecraft.network.chat.Component) Sponge(org.spongepowered.api.Sponge) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) Final(org.spongepowered.asm.mixin.Final) SpongePermissions(org.spongepowered.common.service.server.permission.SpongePermissions) CommandSourceBridge(org.spongepowered.common.bridge.commands.CommandSourceBridge) Cause(org.spongepowered.api.event.Cause) CommandCause(org.spongepowered.api.command.CommandCause) Entity(net.minecraft.world.entity.Entity) Vec2(net.minecraft.world.phys.Vec2) Vec3(net.minecraft.world.phys.Vec3) VecHelper(org.spongepowered.common.util.VecHelper) Shadow(org.spongepowered.asm.mixin.Shadow) CommandSource(net.minecraft.commands.CommandSource) ResultConsumer(com.mojang.brigadier.ResultConsumer) ServerLocation(org.spongepowered.api.world.server.ServerLocation) ServerLocation(org.spongepowered.api.world.server.ServerLocation) CommandSourceStackBridge(org.spongepowered.common.bridge.commands.CommandSourceStackBridge) Inject(org.spongepowered.asm.mixin.injection.Inject)

Example 8 with CommandSourceStack

use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.

the class DifficultyCommandMixin method setDifficulty.

// @formatter:on
/**
 * @author Zidane
 * @reason Only apply difficulty for the world the command was ran in (as in Sponge, all worlds have difficulties)
 */
@Overwrite
public static int setDifficulty(CommandSourceStack source, Difficulty difficulty) throws CommandSyntaxException {
    if (source.getLevel().getDifficulty() == difficulty) {
        throw DifficultyCommandMixin.ERROR_ALREADY_DIFFICULT.create(difficulty.getKey());
    } else {
        final LevelData levelData = source.getLevel().getLevelData();
        ((ServerWorldProperties) levelData).setDifficulty((org.spongepowered.api.world.difficulty.Difficulty) (Object) difficulty);
        source.getLevel().setSpawnSettings(((MinecraftServerAccessor) SpongeCommon.server()).invoker$isSpawningMonsters(), SpongeCommon.server().isSpawningAnimals());
        source.getLevel().getPlayers(p -> true).forEach(p -> p.connection.send(new ClientboundChangeDifficultyPacket(levelData.getDifficulty(), levelData.isDifficultyLocked())));
        source.sendSuccess(new TranslatableComponent("commands.difficulty.success", difficulty.getDisplayName()), true);
        return 0;
    }
}
Also used : CommandSourceStack(net.minecraft.commands.CommandSourceStack) MinecraftServerAccessor(org.spongepowered.common.accessor.server.MinecraftServerAccessor) Overwrite(org.spongepowered.asm.mixin.Overwrite) SpongeCommon(org.spongepowered.common.SpongeCommon) Final(org.spongepowered.asm.mixin.Final) ServerWorldProperties(org.spongepowered.api.world.server.storage.ServerWorldProperties) LevelData(net.minecraft.world.level.storage.LevelData) Mixin(org.spongepowered.asm.mixin.Mixin) DynamicCommandExceptionType(com.mojang.brigadier.exceptions.DynamicCommandExceptionType) Shadow(org.spongepowered.asm.mixin.Shadow) ClientboundChangeDifficultyPacket(net.minecraft.network.protocol.game.ClientboundChangeDifficultyPacket) DifficultyCommand(net.minecraft.server.commands.DifficultyCommand) CommandSyntaxException(com.mojang.brigadier.exceptions.CommandSyntaxException) Difficulty(net.minecraft.world.Difficulty) TranslatableComponent(net.minecraft.network.chat.TranslatableComponent) ServerWorldProperties(org.spongepowered.api.world.server.storage.ServerWorldProperties) TranslatableComponent(net.minecraft.network.chat.TranslatableComponent) ClientboundChangeDifficultyPacket(net.minecraft.network.protocol.game.ClientboundChangeDifficultyPacket) LevelData(net.minecraft.world.level.storage.LevelData) Overwrite(org.spongepowered.asm.mixin.Overwrite)

Example 9 with CommandSourceStack

use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.

the class ForgeCommandManager method processCommand.

@Override
protected CommandResult processCommand(final CommandCause cause, final CommandMapping mapping, final String original, final String command, final String args) throws Throwable {
    final CommandRegistrar<?> registrar = mapping.registrar();
    final boolean isBrig = registrar instanceof BrigadierBasedRegistrar;
    final ParseResults<CommandSourceStack> parseResults;
    if (isBrig) {
        parseResults = this.getDispatcher().parse(original, (CommandSourceStack) cause);
    } else {
        // We have a non Brig registrar, so we just create a dummy result for mods to inspect.
        final CommandContextBuilder<CommandSourceStack> contextBuilder = new CommandContextBuilder<>(this.getDispatcher(), (CommandSourceStack) cause, this.getDispatcher().getRoot(), 0);
        contextBuilder.withCommand(ctx -> 1);
        if (!args.isEmpty()) {
            contextBuilder.withArgument("parsed", new ParsedArgument<>(command.length(), original.length(), args));
        }
        parseResults = new ParseResults<>(contextBuilder, new SpongeStringReader(original), Collections.emptyMap());
    }
    // Relocated from Commands (injection short circuits it there)
    final CommandEvent event = new CommandEvent(parseResults);
    if (MinecraftForge.EVENT_BUS.post(event)) {
        if (event.getException() != null) {
            Throwables.throwIfUnchecked(event.getException());
        }
        // As per Forge, we just treat it as a zero success, and do nothing with it.
        return CommandResult.builder().result(0).build();
    }
    if (isBrig) {
        return CommandResult.builder().result(this.getDispatcher().execute(parseResults)).build();
    } else {
        return mapping.registrar().process(cause, mapping, command, args);
    }
}
Also used : SpongeStringReader(org.spongepowered.common.command.brigadier.SpongeStringReader) CommandContextBuilder(com.mojang.brigadier.context.CommandContextBuilder) CommandEvent(net.minecraftforge.event.CommandEvent) BrigadierBasedRegistrar(org.spongepowered.common.command.registrar.BrigadierBasedRegistrar) CommandSourceStack(net.minecraft.commands.CommandSourceStack)

Example 10 with CommandSourceStack

use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.

the class SpongeCommandCauseFactory method create.

@Override
@NonNull
public CommandCause create() {
    try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) {
        final Cause cause = frame.currentCause();
        final CommandSource iCommandSource = cause.first(CommandSource.class).orElseGet(() -> SpongeCommon.game().systemSubject());
        final CommandSourceStack commandSource;
        if (iCommandSource instanceof CommandSourceProviderBridge) {
            // We know about this one so we can create it using the factory method on the source.
            commandSource = ((CommandSourceProviderBridge) iCommandSource).bridge$getCommandSource(cause);
        } else {
            // try to create a command cause from the given ICommandSource, but as Mojang did not see fit to
            // put any identifying characteristics on the object, we have to go it alone...
            final EventContext context = cause.context();
            @Nullable final Locatable locatable = iCommandSource instanceof Locatable ? (Locatable) iCommandSource : null;
            final Component displayName;
            if (iCommandSource instanceof Entity) {
                displayName = ((Entity) iCommandSource).get(Keys.DISPLAY_NAME).map(SpongeAdventure::asVanilla).orElseGet(() -> new TextComponent(iCommandSource instanceof Nameable ? ((Nameable) iCommandSource).name() : iCommandSource.getClass().getSimpleName()));
            } else {
                displayName = new TextComponent(iCommandSource instanceof Nameable ? ((Nameable) iCommandSource).name() : iCommandSource.getClass().getSimpleName());
            }
            final String name = displayName.getString();
            commandSource = new CommandSourceStack(iCommandSource, context.get(EventContextKeys.LOCATION).map(x -> VecHelper.toVanillaVector3d(x.position())).orElseGet(() -> locatable == null ? Vec3.ZERO : VecHelper.toVanillaVector3d(locatable.location().position())), context.get(EventContextKeys.ROTATION).map(rot -> new Vec2((float) rot.x(), (float) rot.y())).orElse(Vec2.ZERO), context.get(EventContextKeys.LOCATION).map(x -> (ServerLevel) x.world()).orElseGet(() -> locatable == null ? SpongeCommon.server().getLevel(Level.OVERWORLD) : (ServerLevel) locatable.serverLocation().world()), 4, name, displayName, SpongeCommon.server(), iCommandSource instanceof Entity ? (net.minecraft.world.entity.Entity) iCommandSource : null);
        }
        // We don't want the command source to have altered the cause here (unless there is the special case of the
        // server), so we reset it back to what it was (in the ctor of CommandSource, it will add the current source
        // to the cause - that's for if the source is created elsewhere, not here)
        ((CommandSourceStackBridge) commandSource).bridge$setCause(frame.currentCause());
        return (CommandCause) commandSource;
    }
}
Also used : TextComponent(net.minecraft.network.chat.TextComponent) NonNull(org.checkerframework.checker.nullness.qual.NonNull) EventContextKeys(org.spongepowered.api.event.EventContextKeys) CommandSourceStack(net.minecraft.commands.CommandSourceStack) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) CommandSourceProviderBridge(org.spongepowered.common.bridge.commands.CommandSourceProviderBridge) ServerLevel(net.minecraft.server.level.ServerLevel) EventContext(org.spongepowered.api.event.EventContext) Locatable(org.spongepowered.api.world.Locatable) CommandSourceStackBridge(org.spongepowered.common.bridge.commands.CommandSourceStackBridge) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Nameable(org.spongepowered.api.util.Nameable) Nullable(org.checkerframework.checker.nullness.qual.Nullable) Component(net.minecraft.network.chat.Component) SpongeCommon(org.spongepowered.common.SpongeCommon) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) Entity(org.spongepowered.api.entity.Entity) Cause(org.spongepowered.api.event.Cause) CommandCause(org.spongepowered.api.command.CommandCause) TextComponent(net.minecraft.network.chat.TextComponent) Keys(org.spongepowered.api.data.Keys) Vec2(net.minecraft.world.phys.Vec2) Vec3(net.minecraft.world.phys.Vec3) VecHelper(org.spongepowered.common.util.VecHelper) CommandSource(net.minecraft.commands.CommandSource) Level(net.minecraft.world.level.Level) Entity(org.spongepowered.api.entity.Entity) ServerLevel(net.minecraft.server.level.ServerLevel) CommandSourceStackBridge(org.spongepowered.common.bridge.commands.CommandSourceStackBridge) CommandSource(net.minecraft.commands.CommandSource) CommandCause(org.spongepowered.api.command.CommandCause) CommandSourceStack(net.minecraft.commands.CommandSourceStack) EventContext(org.spongepowered.api.event.EventContext) Nameable(org.spongepowered.api.util.Nameable) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Vec2(net.minecraft.world.phys.Vec2) Cause(org.spongepowered.api.event.Cause) CommandCause(org.spongepowered.api.command.CommandCause) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) CommandSourceProviderBridge(org.spongepowered.common.bridge.commands.CommandSourceProviderBridge) Component(net.minecraft.network.chat.Component) TextComponent(net.minecraft.network.chat.TextComponent) Nullable(org.checkerframework.checker.nullness.qual.Nullable) Locatable(org.spongepowered.api.world.Locatable) NonNull(org.checkerframework.checker.nullness.qual.NonNull)

Aggregations

CommandSourceStack (net.minecraft.commands.CommandSourceStack)23 CommandNode (com.mojang.brigadier.tree.CommandNode)6 ArrayList (java.util.ArrayList)6 CommandSyntaxException (com.mojang.brigadier.exceptions.CommandSyntaxException)5 LiteralCommandNode (com.mojang.brigadier.tree.LiteralCommandNode)5 Map (java.util.Map)5 TextComponent (net.minecraft.network.chat.TextComponent)5 Suggestions (com.mojang.brigadier.suggestion.Suggestions)4 HashMap (java.util.HashMap)4 List (java.util.List)4 ServerLevel (net.minecraft.server.level.ServerLevel)4 ResultConsumer (com.mojang.brigadier.ResultConsumer)3 StringReader (com.mojang.brigadier.StringReader)3 CommandContext (com.mojang.brigadier.context.CommandContext)3 Collectors (java.util.stream.Collectors)3 CommandSource (net.minecraft.commands.CommandSource)3 Component (net.minecraft.network.chat.Component)3 Vec2 (net.minecraft.world.phys.Vec2)3 CauseStackManager (org.spongepowered.api.event.CauseStackManager)3 EventContextKeys (org.spongepowered.api.event.EventContextKeys)3