Search in sources :

Example 6 with ServerPlayer

use of org.spongepowered.api.entity.living.player.server.ServerPlayer in project SpongeCommon by SpongePowered.

the class SpongeCommandManager method process.

public CommandResult process(final CommandCause cause, final String arguments) throws CommandException, CommandSyntaxException {
    final String[] splitArg = arguments.split(" ", 2);
    final String originalCommand = splitArg[0];
    final String originalArgs = splitArg.length == 2 ? splitArg[1] : "";
    final String command;
    final String args;
    final ExecuteCommandEvent.Pre preEvent = SpongeEventFactory.createExecuteCommandEventPre(cause.cause(), originalArgs, originalArgs, originalCommand, originalCommand, cause, Optional.empty(), false);
    if (this.game.eventManager().post(preEvent)) {
        return preEvent.result().orElse(SpongeCommandManager.UNKNOWN_ERROR);
    }
    command = preEvent.command();
    args = preEvent.arguments();
    final SpongeCommandMapping mapping = this.commandMappings.get(command.toLowerCase());
    if (mapping == null) {
        throw new CommandException(Component.text("Unknown command. Type /help for a list of commands."));
    }
    final Object source = cause.cause().root();
    final CommandResult result;
    try (final CommandPhaseContext context = GeneralPhase.State.COMMAND.createPhaseContext(PhaseTracker.getInstance()).source(source).command(args).commandMapping(mapping)) {
        if (source instanceof ServerPlayer) {
            final ServerPlayer serverPlayer = (ServerPlayer) source;
            context.creator(serverPlayer.uniqueId());
            context.notifier(serverPlayer.uniqueId());
        }
        context.buildAndSwitch();
        try {
            result = this.processCommand(cause, mapping, arguments, command, args);
        } catch (final CommandException exception) {
            final CommandResult errorResult = CommandResult.builder().result(0).error(exception.componentMessage()).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, errorResult);
            if (SpongeCommandManager.ALWAYS_PRINT_STACKTRACES) {
                this.prettyPrintThrowableError(exception, command, args, cause);
            }
            throw exception;
        } catch (final CommandSyntaxException cse) {
            final CommandResult errorResult = CommandResult.builder().result(0).error(SpongeAdventure.asAdventure(cse.getRawMessage())).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, errorResult);
            if (SpongeCommandManager.ALWAYS_PRINT_STACKTRACES) {
                this.prettyPrintThrowableError(cse, command, args, cause);
            }
            throw cse;
        } catch (final net.minecraft.commands.CommandRuntimeException ex) {
            final CommandResult errorResult = CommandResult.builder().result(0).error(SpongeAdventure.asAdventure(ex.getComponent())).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, errorResult);
            if (SpongeCommandManager.ALWAYS_PRINT_STACKTRACES) {
                this.prettyPrintThrowableError(ex, command, args, cause);
            }
            throw ex;
        } catch (final Throwable thr) {
            this.prettyPrintThrowableError(thr, command, args, cause);
            Component excBuilder;
            if (thr instanceof ComponentMessageThrowable) {
                final Component text = ((ComponentMessageThrowable) thr).componentMessage();
                excBuilder = text == null ? Component.text("null") : text;
            } else {
                excBuilder = Component.text(String.valueOf(thr.getMessage()));
            }
            if (cause.hasPermission(Constants.Permissions.DEBUG_HOVER_STACKTRACE)) {
                final StringWriter writer = new StringWriter();
                thr.printStackTrace(new PrintWriter(writer));
                excBuilder = excBuilder.hoverEvent(HoverEvent.showText(Component.text(writer.toString().replace("\t", "    ").replace("\r\n", "\n").replace("\r", // I mean I guess somebody could be running this on like OS 9?
                "\n"))));
            }
            final Component error = Component.text().content("Unexpected error occurred while executing command: ").append(excBuilder).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, CommandResult.error(error));
            throw new CommandException(error, thr);
        }
        this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, result);
        if (!result.isSuccess()) {
            cause.sendMessage(Identity.nil(), result.errorMessage().map(x -> x.colorIfAbsent(NamedTextColor.RED)).orElseGet(() -> Component.text().content(String.format("An empty error result was returned while executing the command \"%s\"", arguments)).color(NamedTextColor.RED).build()));
        }
        return result;
    }
}
Also used : ExecuteCommandEvent(org.spongepowered.api.event.command.ExecuteCommandEvent) CommandException(org.spongepowered.api.command.exception.CommandException) SpongeCommandResult(org.spongepowered.common.command.result.SpongeCommandResult) CommandResult(org.spongepowered.api.command.CommandResult) ComponentMessageThrowable(net.kyori.adventure.util.ComponentMessageThrowable) StringWriter(java.io.StringWriter) CommandPhaseContext(org.spongepowered.common.event.tracking.phase.general.CommandPhaseContext) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) ComponentMessageThrowable(net.kyori.adventure.util.ComponentMessageThrowable) Component(net.kyori.adventure.text.Component) SpongeCommandSyntaxException(org.spongepowered.common.command.exception.SpongeCommandSyntaxException) CommandSyntaxException(com.mojang.brigadier.exceptions.CommandSyntaxException) PrintWriter(java.io.PrintWriter)

Example 7 with ServerPlayer

use of org.spongepowered.api.entity.living.player.server.ServerPlayer in project SpongeCommon by SpongePowered.

the class AdvancementProgressMixin method impl$revokeCriterion.

private boolean impl$revokeCriterion(String rawCriterion) {
    final net.minecraft.advancements.CriterionProgress criterionProgress = this.criteria.get(rawCriterion);
    if (criterionProgress == null || !criterionProgress.isDone()) {
        return false;
    }
    if (SpongeScoreCriterion.BYPASS_EVENT) {
        criterionProgress.revoke();
        return true;
    }
    final Cause cause = PhaseTracker.getCauseStackManager().currentCause();
    final ServerPlayer player = ((PlayerAdvancementsBridge) this.impl$playerAdvancements).bridge$getPlayer();
    final CriterionProgress progress = (CriterionProgress) criterionProgress;
    final AdvancementCriterion criterion = progress.criterion();
    final CriterionBridge criterionBridge = (CriterionBridge) criterion;
    // The score criterion needs special care
    final SpongeScoreCriterion scoreCriterion = criterionBridge.bridge$getScoreCriterion();
    final CriterionEvent event;
    final Advancement advancement = ((org.spongepowered.api.advancement.AdvancementProgress) this).advancement();
    if (scoreCriterion != null) {
        final SpongeScoreCriterionProgress scoreProgress = (SpongeScoreCriterionProgress) this.impl$progressMap.get(scoreCriterion.name());
        final int lastScore = scoreProgress.score();
        final int score = lastScore + 1;
        if (lastScore == scoreCriterion.goal()) {
            event = SpongeEventFactory.createCriterionEventScoreRevoke(cause, advancement, scoreCriterion, player, lastScore, score);
        } else if (score == scoreCriterion.goal()) {
            event = SpongeEventFactory.createCriterionEventScoreGrant(cause, advancement, scoreCriterion, player, Instant.now(), lastScore, score);
        } else {
            event = SpongeEventFactory.createCriterionEventScoreChange(cause, advancement, scoreCriterion, player, lastScore, score);
        }
    } else {
        event = SpongeEventFactory.createCriterionEventRevoke(cause, advancement, criterion, player);
    }
    if (SpongeCommon.post(event)) {
        return false;
    }
    criterionProgress.revoke();
    return true;
}
Also used : AdvancementProgress(net.minecraft.advancements.AdvancementProgress) CriterionEvent(org.spongepowered.api.event.advancement.CriterionEvent) PlayerAdvancementsBridge(org.spongepowered.common.bridge.server.PlayerAdvancementsBridge) AdvancementCriterion(org.spongepowered.api.advancement.criteria.AdvancementCriterion) SpongeScoreCriterion(org.spongepowered.common.advancement.criterion.SpongeScoreCriterion) SpongeScoreCriterionProgress(org.spongepowered.common.advancement.criterion.SpongeScoreCriterionProgress) Cause(org.spongepowered.api.event.Cause) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Advancement(org.spongepowered.api.advancement.Advancement) SpongeAndCriterionProgress(org.spongepowered.common.advancement.criterion.SpongeAndCriterionProgress) SpongeOrCriterionProgress(org.spongepowered.common.advancement.criterion.SpongeOrCriterionProgress) SpongeScoreCriterionProgress(org.spongepowered.common.advancement.criterion.SpongeScoreCriterionProgress) ImplementationBackedCriterionProgress(org.spongepowered.common.advancement.criterion.ImplementationBackedCriterionProgress) CriterionProgress(org.spongepowered.api.advancement.criteria.CriterionProgress) CriterionBridge(org.spongepowered.common.bridge.advancements.CriterionBridge)

Example 8 with ServerPlayer

use of org.spongepowered.api.entity.living.player.server.ServerPlayer in project SpongeCommon by SpongePowered.

the class CriterionTrigger_ListenerMixin method impl$callEvents.

// @formatter:on
@SuppressWarnings({ "unchecked", "rawtypes" })
@Inject(method = "run", at = @At("HEAD"), cancellable = true)
private void impl$callEvents(PlayerAdvancements playerAdvancements, CallbackInfo ci) {
    final org.spongepowered.api.advancement.Advancement advancement = (org.spongepowered.api.advancement.Advancement) this.advancement;
    AdvancementCriterion advancementCriterion = (AdvancementCriterion) this.advancement.getCriteria().get(this.criterion);
    final CriterionBridge criterionBridge = (CriterionBridge) advancementCriterion;
    if (criterionBridge.bridge$getScoreCriterion() != null) {
        advancementCriterion = criterionBridge.bridge$getScoreCriterion();
    }
    if (!PlatformHooks.INSTANCE.getGeneralHooks().onServerThread()) {
        // Some mods do advancement granting on async threads, and we can't allow for the spam to be thrown.
        return;
    }
    // Sponge filters are always handled in the trigger method
    if (!(this.trigger instanceof SpongeFilteredTrigger)) {
        final FilteredTrigger<FilteredTriggerConfiguration> filteredTrigger = (FilteredTrigger) this.trigger;
        if (filteredTrigger.type() instanceof SpongeCriterionTrigger) {
            final Cause cause = PhaseTracker.getCauseStackManager().currentCause();
            final ServerPlayer player = ((PlayerAdvancementsBridge) playerAdvancements).bridge$getPlayer();
            final TypeToken<FilteredTriggerConfiguration> typeToken = (TypeToken) TypeToken.get(filteredTrigger.type().configurationType());
            final CriterionEvent.Trigger event = SpongeEventFactory.createCriterionEventTrigger(cause, advancement, advancementCriterion, typeToken, player, filteredTrigger, true);
            SpongeCommon.post(event);
            if (!event.result()) {
                ci.cancel();
                return;
            }
        }
    }
    PhaseTracker.getCauseStackManager().pushCause(this.trigger);
    // the score be increased by one.
    if (advancementCriterion instanceof ScoreAdvancementCriterion) {
        ((PlayerAdvancementsBridge) playerAdvancements).bridge$getPlayer().progress(advancement).get((ScoreAdvancementCriterion) advancementCriterion).get().add(1);
        ci.cancel();
        PhaseTracker.getCauseStackManager().popCause();
    }
}
Also used : ScoreAdvancementCriterion(org.spongepowered.api.advancement.criteria.ScoreAdvancementCriterion) SpongeFilteredTrigger(org.spongepowered.common.advancement.SpongeFilteredTrigger) CriterionEvent(org.spongepowered.api.event.advancement.CriterionEvent) PlayerAdvancementsBridge(org.spongepowered.common.bridge.server.PlayerAdvancementsBridge) ScoreAdvancementCriterion(org.spongepowered.api.advancement.criteria.ScoreAdvancementCriterion) AdvancementCriterion(org.spongepowered.api.advancement.criteria.AdvancementCriterion) SpongeFilteredTrigger(org.spongepowered.common.advancement.SpongeFilteredTrigger) FilteredTrigger(org.spongepowered.api.advancement.criteria.trigger.FilteredTrigger) SpongeCriterionTrigger(org.spongepowered.common.advancement.SpongeCriterionTrigger) TypeToken(io.leangen.geantyref.TypeToken) Cause(org.spongepowered.api.event.Cause) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) FilteredTriggerConfiguration(org.spongepowered.api.advancement.criteria.trigger.FilteredTriggerConfiguration) Advancement(net.minecraft.advancements.Advancement) CriterionBridge(org.spongepowered.common.bridge.advancements.CriterionBridge) Inject(org.spongepowered.asm.mixin.injection.Inject)

Example 9 with ServerPlayer

use of org.spongepowered.api.entity.living.player.server.ServerPlayer in project SpongeCommon by SpongePowered.

the class ServerGamePacketListenerImplMixin_Vanilla method vanilla$onProcessChatMessage.

@Inject(method = "handleChat(Ljava/lang/String;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/players/PlayerList;broadcastMessage(Lnet/minecraft/network/chat/Component;Lnet/minecraft/network/chat/ChatType;Ljava/util/UUID;)V"), cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD)
private void vanilla$onProcessChatMessage(String var1, CallbackInfo ci, net.minecraft.network.chat.Component component) {
    ChatFormatter.formatChatComponent((net.minecraft.network.chat.TranslatableComponent) component);
    final ServerPlayer player = (ServerPlayer) this.player;
    final PlayerChatFormatter chatFormatter = player.chatFormatter();
    final TextComponent rawMessage = Component.text(var1);
    try (CauseStackManager.StackFrame frame = PhaseTracker.SERVER.pushCauseFrame()) {
        frame.pushCause(this.player);
        final Audience audience = (Audience) this.server;
        final PlayerChatEvent event = SpongeEventFactory.createPlayerChatEvent(frame.currentCause(), audience, Optional.of(audience), chatFormatter, Optional.of(chatFormatter), rawMessage, rawMessage);
        if (SpongeCommon.post(event)) {
            ci.cancel();
        } else {
            event.chatFormatter().ifPresent(formatter -> event.audience().map(SpongeAdventure::unpackAudiences).ifPresent(targets -> {
                for (Audience target : targets) {
                    formatter.format(player, target, event.message(), event.originalMessage()).ifPresent(formattedMessage -> target.sendMessage(player, formattedMessage));
                }
            }));
        }
    }
}
Also used : TextComponent(net.kyori.adventure.text.TextComponent) Inventory(org.spongepowered.api.item.inventory.Inventory) NonNull(org.checkerframework.checker.nullness.qual.NonNull) RecipeBookMenu(net.minecraft.world.inventory.RecipeBookMenu) Inject(org.spongepowered.asm.mixin.injection.Inject) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) EffectTransactor(org.spongepowered.common.event.tracking.context.transaction.EffectTransactor) PlayerList(net.minecraft.server.players.PlayerList) CallbackInfo(org.spongepowered.asm.mixin.injection.callback.CallbackInfo) MinecraftServer(net.minecraft.server.MinecraftServer) Mixin(org.spongepowered.asm.mixin.Mixin) Component(net.kyori.adventure.text.Component) ServerboundCustomPayloadPacket(net.minecraft.network.protocol.game.ServerboundCustomPayloadPacket) CauseStackManager(org.spongepowered.api.event.CauseStackManager) TransactionalCaptureSupplier(org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier) ServerGamePacketListener(net.minecraft.network.protocol.game.ServerGamePacketListener) LocalCapture(org.spongepowered.asm.mixin.injection.callback.LocalCapture) At(org.spongepowered.asm.mixin.injection.At) TextComponent(net.kyori.adventure.text.TextComponent) Redirect(org.spongepowered.asm.mixin.injection.Redirect) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) EngineConnection(org.spongepowered.api.network.EngineConnection) Sponge(org.spongepowered.api.Sponge) PlayerChatEvent(org.spongepowered.api.event.message.PlayerChatEvent) SpongeChannelManager(org.spongepowered.common.network.channel.SpongeChannelManager) Group(org.spongepowered.asm.mixin.injection.Group) ChatType(net.minecraft.network.chat.ChatType) SpongeCommon(org.spongepowered.common.SpongeCommon) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) UUID(java.util.UUID) Final(org.spongepowered.asm.mixin.Final) QueryTypes(org.spongepowered.api.item.inventory.query.QueryTypes) ServerGamePacketListenerImpl(net.minecraft.server.network.ServerGamePacketListenerImpl) PlayerChatFormatter(org.spongepowered.api.entity.living.player.PlayerChatFormatter) Audience(net.kyori.adventure.audience.Audience) Recipe(net.minecraft.world.item.crafting.Recipe) PhaseContext(org.spongepowered.common.event.tracking.PhaseContext) CraftingInventory(org.spongepowered.api.item.inventory.crafting.CraftingInventory) ServerboundCustomPayloadPacketAccessor(org.spongepowered.common.accessor.network.protocol.game.ServerboundCustomPayloadPacketAccessor) ChatFormatter(org.spongepowered.vanilla.chat.ChatFormatter) Shadow(org.spongepowered.asm.mixin.Shadow) Optional(java.util.Optional) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) PlayerChatEvent(org.spongepowered.api.event.message.PlayerChatEvent) Audience(net.kyori.adventure.audience.Audience) CauseStackManager(org.spongepowered.api.event.CauseStackManager) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) PlayerChatFormatter(org.spongepowered.api.entity.living.player.PlayerChatFormatter) Inject(org.spongepowered.asm.mixin.injection.Inject)

Example 10 with ServerPlayer

use of org.spongepowered.api.entity.living.player.server.ServerPlayer in project SpongeCommon by SpongePowered.

the class SpongeCommonEventFactory method callPlaySoundAtEntityEvent.

@SuppressWarnings("ConstantConditions")
public static PlaySoundEvent.AtEntity callPlaySoundAtEntityEvent(final Cause cause, final net.minecraft.world.entity.player.@Nullable Player entity, final LevelBridge worldMixin, final double x, final double y, final double z, final net.minecraft.sounds.SoundSource category, final SoundEvent name, final float pitch, final float volume) {
    final ServerLocation location = ServerLocation.of((ServerWorld) worldMixin, x, y, z);
    final PlaySoundEvent.AtEntity event = SpongeEventFactory.createPlaySoundEventAtEntity(cause, location, Optional.ofNullable((ServerPlayer) entity), SpongeAdventure.asAdventure(category), (SoundType) name, pitch, volume);
    SpongeCommon.post(event);
    return event;
}
Also used : ServerLocation(org.spongepowered.api.world.server.ServerLocation) PlaySoundEvent(org.spongepowered.api.event.sound.PlaySoundEvent) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer)

Aggregations

ServerPlayer (org.spongepowered.api.entity.living.player.server.ServerPlayer)32 Component (net.kyori.adventure.text.Component)13 Cause (org.spongepowered.api.event.Cause)9 Listener (org.spongepowered.api.event.Listener)8 Sponge (org.spongepowered.api.Sponge)7 Inject (org.spongepowered.asm.mixin.injection.Inject)7 TypeToken (io.leangen.geantyref.TypeToken)6 RegistryTypes (org.spongepowered.api.registry.RegistryTypes)6 Inject (com.google.inject.Inject)5 UUID (java.util.UUID)5 Identity (net.kyori.adventure.identity.Identity)5 NamedTextColor (net.kyori.adventure.text.format.NamedTextColor)5 BlockPos (net.minecraft.core.BlockPos)5 AdvancementCriterion (org.spongepowered.api.advancement.criteria.AdvancementCriterion)5 CommandResult (org.spongepowered.api.command.CommandResult)5 CommandException (org.spongepowered.api.command.exception.CommandException)5 CommandContext (org.spongepowered.api.command.parameter.CommandContext)5 Map (java.util.Map)4 Command (org.spongepowered.api.command.Command)4 Parameter (org.spongepowered.api.command.parameter.Parameter)4