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;
}
}
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;
}
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();
}
}
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));
}
}));
}
}
}
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;
}
Aggregations