Search in sources :

Example 21 with Cause

use of org.spongepowered.api.event.Cause in project SpongeCommon by SpongePowered.

the class EnderMan_EndermanLeaveBlockGoalMixin method impl$onPlaceBlockCancel.

/**
 * @reason Makes Endermen check for block changes before they can place their blocks.
 * This allows plugins to cancel the event regardless without issue.
 */
@Redirect(method = "canPlaceBlock(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/BlockPos;)Z", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockState;isCollisionShapeFullBlock(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;)Z"))
private boolean impl$onPlaceBlockCancel(BlockState blockState, BlockGetter blockReaderIn, BlockPos blockPosIn) {
    if (blockState.isCollisionShapeFullBlock(blockReaderIn, blockPosIn)) {
        // Sponge start
        if (ShouldFire.CHANGE_BLOCK_EVENT_PRE) {
            final ServerLocation location = ServerLocation.of((ServerWorld) blockReaderIn, blockPosIn.getX(), blockPosIn.getY(), blockPosIn.getZ());
            final List<ServerLocation> list = new ArrayList<>(1);
            list.add(location);
            final Cause cause = PhaseTracker.getCauseStackManager().currentCause();
            final ChangeBlockEvent.Pre event = SpongeEventFactory.createChangeBlockEventPre(cause, list, ((ServerWorld) this.enderman.level));
            return !SpongeCommon.post(event);
        }
        // Sponge end
        return true;
    }
    return false;
}
Also used : ChangeBlockEvent(org.spongepowered.api.event.block.ChangeBlockEvent) ServerWorld(org.spongepowered.api.world.server.ServerWorld) ServerLocation(org.spongepowered.api.world.server.ServerLocation) Cause(org.spongepowered.api.event.Cause) ArrayList(java.util.ArrayList) Redirect(org.spongepowered.asm.mixin.injection.Redirect)

Example 22 with Cause

use of org.spongepowered.api.event.Cause 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)

Example 23 with Cause

use of org.spongepowered.api.event.Cause in project SpongeCommon by SpongePowered.

the class SpongeCommandManager method prettyPrintThrowableError.

private void prettyPrintThrowableError(final Throwable thr, final String commandNoArgs, final String args, final CommandCause cause) {
    final String commandString;
    if (args != null && !args.isEmpty()) {
        commandString = commandNoArgs + " " + args;
    } else {
        commandString = commandNoArgs;
    }
    final SpongeCommandMapping mapping = this.commandMappings.get(commandNoArgs.toLowerCase());
    final PrettyPrinter prettyPrinter = new PrettyPrinter(100).add("Unexpected error occurred while executing command '%s'", commandString).centre().hr().addWrapped("While trying to run '%s', an error occurred that the command processor was not expecting. " + "This usually indicates an error in the plugin that owns this command. Report this error " + "to the plugin developer first - this is usually not a Sponge error.", commandString).hr().add().add("Command: %s", commandString).add("Owning Plugin: %s", mapping.plugin().map(x -> x.metadata().id()).orElse("unknown")).add("Owning Registrar: %s", mapping.registrar().getClass().getName()).add().add("Exception Details: ");
    if (thr instanceof SpongeCommandSyntaxException) {
        // we know the inner exception was wrapped by us.
        prettyPrinter.add(thr.getCause());
    } else {
        prettyPrinter.add(thr);
    }
    prettyPrinter.add().add("CommandCause details: ").addWrapped(cause.cause().toString()).log(SpongeCommon.logger(), Level.ERROR);
}
Also used : LiteralCommandNode(com.mojang.brigadier.tree.LiteralCommandNode) Object2BooleanMap(it.unimi.dsi.fastutil.objects.Object2BooleanMap) SpongeCommandDispatcher(org.spongepowered.common.command.brigadier.dispatcher.SpongeCommandDispatcher) Arrays(java.util.Arrays) Game(org.spongepowered.api.Game) Inject(com.google.inject.Inject) Level(org.apache.logging.log4j.Level) CommandFailedRegistrationException(org.spongepowered.api.command.manager.CommandFailedRegistrationException) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) CommandPhaseContext(org.spongepowered.common.event.tracking.phase.general.CommandPhaseContext) MinecraftServer(net.minecraft.server.MinecraftServer) HashMultimap(com.google.common.collect.HashMultimap) Locale(java.util.Locale) Map(java.util.Map) RootCommandTreeNode(org.spongepowered.common.command.registrar.tree.builder.RootCommandTreeNode) TransactionalCaptureSupplier(org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier) Subject(org.spongepowered.api.service.permission.Subject) Object2BooleanOpenHashMap(it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap) PrintWriter(java.io.PrintWriter) SpongeCommandCompletion(org.spongepowered.common.command.SpongeCommandCompletion) ImmutableSet(com.google.common.collect.ImmutableSet) CommandCompletion(org.spongepowered.api.command.CommandCompletion) Collection(java.util.Collection) Launch(org.spongepowered.common.launch.Launch) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) SpongeCommandResult(org.spongepowered.common.command.result.SpongeCommandResult) TypeToken(io.leangen.geantyref.TypeToken) Collectors(java.util.stream.Collectors) LiteralArgumentBuilder(com.mojang.brigadier.builder.LiteralArgumentBuilder) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) SpongeParameterizedCommandRegistrar(org.spongepowered.common.command.registrar.SpongeParameterizedCommandRegistrar) Player(net.minecraft.world.entity.player.Player) Objects(java.util.Objects) ExecuteCommandEvent(org.spongepowered.api.event.command.ExecuteCommandEvent) List(java.util.List) PhaseContext(org.spongepowered.common.event.tracking.PhaseContext) Optional(java.util.Optional) HoverEvent(net.kyori.adventure.text.event.HoverEvent) CommandManager(org.spongepowered.api.command.manager.CommandManager) SpongePaginationService(org.spongepowered.common.service.game.pagination.SpongePaginationService) CommandRegistrar(org.spongepowered.api.command.registrar.CommandRegistrar) NonNull(org.checkerframework.checker.nullness.qual.NonNull) EventContextKeys(org.spongepowered.api.event.EventContextKeys) ComponentMessageThrowable(net.kyori.adventure.util.ComponentMessageThrowable) SharedSuggestionProvider(net.minecraft.commands.SharedSuggestionProvider) CommandSourceStack(net.minecraft.commands.CommandSourceStack) Constants(org.spongepowered.common.util.Constants) Command(com.mojang.brigadier.Command) CommandsBridge(org.spongepowered.common.bridge.commands.CommandsBridge) PrettyPrinter(org.spongepowered.common.util.PrettyPrinter) HashMap(java.util.HashMap) BrigadierCommandRegistrar(org.spongepowered.common.command.registrar.BrigadierCommandRegistrar) Multimap(com.google.common.collect.Multimap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) SpongeCommand(org.spongepowered.common.command.sponge.SpongeCommand) Component(net.kyori.adventure.text.Component) CallbackCommand(org.spongepowered.common.adventure.CallbackCommand) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Nullable(org.checkerframework.checker.nullness.qual.Nullable) GeneralPhase(org.spongepowered.common.event.tracking.phase.general.GeneralPhase) CommandResult(org.spongepowered.api.command.CommandResult) SpongeCommandSyntaxException(org.spongepowered.common.command.exception.SpongeCommandSyntaxException) RegisterCommandEventImpl(org.spongepowered.common.event.lifecycle.RegisterCommandEventImpl) Parameterized(org.spongepowered.api.command.Command.Parameterized) Identity(net.kyori.adventure.identity.Identity) CommandTreeNode(org.spongepowered.api.command.registrar.tree.CommandTreeNode) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) StringWriter(java.io.StringWriter) CommandRegistrarType(org.spongepowered.api.command.registrar.CommandRegistrarType) SpongeCommon(org.spongepowered.common.SpongeCommon) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) PaginationService(org.spongepowered.api.service.pagination.PaginationService) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) Cause(org.spongepowered.api.event.Cause) CommandCause(org.spongepowered.api.command.CommandCause) CommandMapping(org.spongepowered.api.command.manager.CommandMapping) Provider(com.google.inject.Provider) PluginContainer(org.spongepowered.plugin.PluginContainer) Audience(net.kyori.adventure.audience.Audience) SpongeConfigs(org.spongepowered.common.applaunch.config.core.SpongeConfigs) CommandNode(com.mojang.brigadier.tree.CommandNode) GenericTypeReflector(io.leangen.geantyref.GenericTypeReflector) CommandSyntaxException(com.mojang.brigadier.exceptions.CommandSyntaxException) Collections(java.util.Collections) CommandException(org.spongepowered.api.command.exception.CommandException) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) PrettyPrinter(org.spongepowered.common.util.PrettyPrinter) SpongeCommandSyntaxException(org.spongepowered.common.command.exception.SpongeCommandSyntaxException)

Example 24 with Cause

use of org.spongepowered.api.event.Cause in project SpongeCommon by SpongePowered.

the class SpongeScoreCriterionProgress method set.

@Override
public Optional<Instant> set(final int score) {
    checkState(score >= 0 && score <= this.goal(), "Score cannot be negative or greater than the goal.");
    int lastScore = this.score();
    if (lastScore == score) {
        return this.get();
    }
    final CriterionEvent.Score.Change event;
    final Cause cause = PhaseTracker.getCauseStackManager().currentCause();
    final Advancement advancement = this.progress.advancement();
    final ServerPlayer player = ((PlayerAdvancementsBridge) ((AdvancementProgressBridge) this.progress).bridge$getPlayerAdvancements()).bridge$getPlayer();
    if (lastScore == this.goal()) {
        event = SpongeEventFactory.createCriterionEventScoreRevoke(cause, advancement, this.criterion(), player, lastScore, score);
    } else if (score == this.goal()) {
        event = SpongeEventFactory.createCriterionEventScoreGrant(cause, advancement, this.criterion(), player, Instant.now(), lastScore, score);
    } else {
        event = SpongeEventFactory.createCriterionEventScoreChange(cause, advancement, this.criterion(), player, lastScore, score);
    }
    if (SpongeCommon.post(event)) {
        return this.get();
    }
    SpongeScoreCriterion.BYPASS_EVENT = true;
    // This is the only case a instant will be returned
    if (score == this.goal()) {
        Instant instant = null;
        for (final AdvancementCriterion criterion : this.criterion.internalCriteria) {
            final org.spongepowered.api.advancement.criteria.CriterionProgress progress = this.progress.get(criterion).get();
            if (!progress.achieved()) {
                instant = progress.grant();
            }
        }
        this.score = score;
        return Optional.of(instant == null ? Instant.now() : instant);
    }
    for (final AdvancementCriterion criterion : this.criterion.internalCriteria) {
        final org.spongepowered.api.advancement.criteria.CriterionProgress progress = this.progress.get(criterion).get();
        // We don't have enough score, grant more criteria
        if (lastScore < score && !progress.achieved()) {
            progress.grant();
            lastScore++;
        // We have too much score, revoke more criteria
        } else if (lastScore > score && progress.achieved()) {
            progress.revoke();
            lastScore--;
        }
        // We reached the target score
        if (lastScore == score) {
            break;
        }
    }
    this.score = score;
    SpongeScoreCriterion.BYPASS_EVENT = false;
    return Optional.empty();
}
Also used : PlayerAdvancementsBridge(org.spongepowered.common.bridge.server.PlayerAdvancementsBridge) Instant(java.time.Instant) ScoreAdvancementCriterion(org.spongepowered.api.advancement.criteria.ScoreAdvancementCriterion) AdvancementCriterion(org.spongepowered.api.advancement.criteria.AdvancementCriterion) Cause(org.spongepowered.api.event.Cause) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Advancement(org.spongepowered.api.advancement.Advancement)

Example 25 with Cause

use of org.spongepowered.api.event.Cause in project SpongeCommon by SpongePowered.

the class SpongeCriterionTrigger method bridge$trigger.

@Override
public void bridge$trigger(final ServerPlayer player) {
    final PlayerAdvancements playerAdvancements = ((net.minecraft.server.level.ServerPlayer) player).getAdvancements();
    final Cause cause = PhaseTracker.getCauseStackManager().currentCause();
    // correct type verified in builder
    @SuppressWarnings("unchecked") final TypeToken<FilteredTriggerConfiguration> typeToken = (TypeToken<FilteredTriggerConfiguration>) TypeToken.get(this.triggerConfigurationType);
    for (final Listener listener : new ArrayList<>(this.listeners.get(playerAdvancements))) {
        final CriterionTrigger_ListenerAccessor mixinListener = (CriterionTrigger_ListenerAccessor) listener;
        final Advancement advancement = (Advancement) mixinListener.accessor$advancement();
        final AdvancementCriterion advancementCriterion = (AdvancementCriterion) ((net.minecraft.advancements.Advancement) advancement).getCriteria().get(mixinListener.accessor$criterion());
        final CriterionEvent.Trigger event = SpongeEventFactory.createCriterionEventTrigger(cause, advancement, advancementCriterion, typeToken, player, (FilteredTrigger) listener.getTriggerInstance(), this.eventHandler == null);
        if (this.eventHandler != null) {
            this.eventHandler.accept(event);
            if (!event.result()) {
                continue;
            }
        }
        SpongeCommon.post(event);
        if (event.result()) {
            listener.run(playerAdvancements);
        }
    }
}
Also used : CriterionEvent(org.spongepowered.api.event.advancement.CriterionEvent) ArrayList(java.util.ArrayList) AdvancementCriterion(org.spongepowered.api.advancement.criteria.AdvancementCriterion) PlayerAdvancements(net.minecraft.server.PlayerAdvancements) TypeToken(io.leangen.geantyref.TypeToken) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Cause(org.spongepowered.api.event.Cause) FilteredTriggerConfiguration(org.spongepowered.api.advancement.criteria.trigger.FilteredTriggerConfiguration) CriterionTrigger_ListenerAccessor(org.spongepowered.common.accessor.advancements.CriterionTrigger_ListenerAccessor) Advancement(org.spongepowered.api.advancement.Advancement)

Aggregations

Cause (org.spongepowered.api.event.Cause)55 ItemStackSnapshot (org.spongepowered.api.item.inventory.ItemStackSnapshot)19 ServerWorld (org.spongepowered.api.world.server.ServerWorld)18 Inject (org.spongepowered.asm.mixin.injection.Inject)18 ArrayList (java.util.ArrayList)16 BlockPos (net.minecraft.core.BlockPos)15 CauseStackManager (org.spongepowered.api.event.CauseStackManager)15 List (java.util.List)13 Optional (java.util.Optional)12 ServerLocation (org.spongepowered.api.world.server.ServerLocation)12 Entity (net.minecraft.world.entity.Entity)11 Player (net.minecraft.world.entity.player.Player)11 Collections (java.util.Collections)10 Collection (java.util.Collection)9 Map (java.util.Map)9 LivingEntity (net.minecraft.world.entity.LivingEntity)9 EventContext (org.spongepowered.api.event.EventContext)9 HashMap (java.util.HashMap)8 BlockState (net.minecraft.world.level.block.state.BlockState)8 ServerPlayer (org.spongepowered.api.entity.living.player.server.ServerPlayer)8