Search in sources :

Example 1 with CommandException

use of org.spongepowered.api.command.exception.CommandException in project SpongeCommon by SpongePowered.

the class VolumeStreamTest method onGamePreInitialization.

@Listener
public void onGamePreInitialization(final RegisterCommandEvent<Command.Parameterized> event) throws IOException, CommandException {
    this.schematicsDir = this.config.resolve("schematics");
    Files.createDirectories(this.config);
    final Parameter.Value<Biome> biomeKey = Parameter.registryElement(TypeToken.get(Biome.class), ImmutableList.of(VariableValueParameters.RegistryEntryBuilder.WORLD_FROM_LOCATABLE_HOLDER_PROVIDER, VariableValueParameters.RegistryEntryBuilder.WORLD_FROM_CAUSE_HOLDER_PROVIDER), RegistryTypes.BIOME, "minecraft").key("format").build();
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Sets the biome in a selected region")).permission(this.plugin.metadata().id() + ".command.setbiome").addParameter(biomeKey).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        if (data.getPos1() == null || data.getPos2() == null) {
            player.sendMessage(Identity.nil(), Component.text("You must set both positions before copying", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Vector3i min = data.getPos1().min(data.getPos2());
        final Vector3i max = data.getPos1().max(data.getPos2());
        final Biome target = src.requireOne(biomeKey);
        player.world().biomeStream(min, max, StreamOptions.forceLoadedAndCopied()).map((world, biome, x, y, z) -> target).apply(VolumeCollectors.of(player.world(), VolumePositionTranslators.identity(), VolumeApplicators.applyBiomes()));
        return CommandResult.success();
    }).build(), "setBiome");
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Copies a region of the world to your clipboard")).permission(this.plugin.metadata().id() + ".command.copy").executor(src -> {
        if (!(src.cause().root() instanceof Player)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Player player = (Player) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        if (data.getPos1() == null || data.getPos2() == null) {
            player.sendMessage(Identity.nil(), Component.text("You must set both positions before copying", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Vector3i min = data.getPos1().min(data.getPos2());
        final Vector3i max = data.getPos1().max(data.getPos2());
        data.setOrigin(player.blockPosition());
        final ArchetypeVolume archetypeVolume = player.world().createArchetypeVolume(min, max, player.blockPosition());
        data.setClipboard(archetypeVolume);
        player.sendMessage(Identity.nil(), Component.text("Saved to clipboard.", VolumeStreamTest.GREEN));
        return CommandResult.success();
    }).build(), "copy");
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Pastes your clipboard to where you are standing")).permission(this.plugin.metadata().id() + ".command.paste").executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        final ArchetypeVolume volume = data.getClipboard();
        if (volume == null) {
            player.sendMessage(Identity.nil(), Component.text("You must copy something before pasting", NamedTextColor.RED));
            return CommandResult.success();
        }
        try (final CauseStackManager.StackFrame frame = Sponge.server().causeStackManager().pushCauseFrame()) {
            frame.pushCause(this.plugin);
            volume.applyToWorld(player.world(), player.blockPosition(), SpawnTypes.PLACEMENT::get);
        }
        src.sendMessage(Identity.nil(), Component.text("Pasted clipboard into world.", VolumeStreamTest.GREEN));
        return CommandResult.success();
    }).build(), "paste");
    final Parameter.Value<String> fileName = Parameter.string().key("fileName").build();
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Pastes your clipboard to where you are standing")).permission(this.plugin.metadata().id() + ".command.paste").addParameter(fileName).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final String file = src.requireOne(fileName);
        final Path desiredFilePath = this.schematicsDir.resolve(file + VolumeStreamTest.FILE_ENDING);
        if (Files.exists(desiredFilePath)) {
            throw new CommandException(Component.text(file + " already exists, please delete the file first", NamedTextColor.RED));
        }
        if (Files.isDirectory(desiredFilePath)) {
            throw new CommandException(Component.text(file + "is a directory, please use a file name", NamedTextColor.RED));
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        final ArchetypeVolume volume = data.getClipboard();
        if (volume == null) {
            player.sendMessage(Identity.nil(), Component.text("You must copy something before pasting", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Schematic schematic = Schematic.builder().volume(data.getClipboard()).metaValue(Schematic.METADATA_AUTHOR, player.name()).metaValue(Schematic.METADATA_NAME, file).build();
        final DataContainer schematicData = Sponge.dataManager().translator(Schematic.class).orElseThrow(() -> new IllegalStateException("Sponge doesn't have a DataTranslator for Schematics!")).translate(schematic);
        try {
            final Path output = Files.createFile(desiredFilePath);
            DataFormats.NBT.get().writeTo(new GZIPOutputStream(Files.newOutputStream(output)), schematicData);
            player.sendMessage(Identity.nil(), Component.text("Saved schematic to " + output.toAbsolutePath(), VolumeStreamTest.SAVE));
        } catch (final Exception e) {
            e.printStackTrace();
            final StringWriter writer = new StringWriter();
            e.printStackTrace(new PrintWriter(writer));
            final Component errorText = Component.text(writer.toString().replace("\t", "    ").replace("\r\n", "\n").replace("\r", "\n"));
            final TextComponent text = Component.text("Error saving schematic: " + e.getMessage(), NamedTextColor.RED).hoverEvent(HoverEvent.showText(errorText));
            return CommandResult.builder().error(text).build();
        }
        return CommandResult.success();
    }).build(), "save");
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Load a schematic from file")).permission(this.plugin.metadata().id() + ".command.load").addParameter(fileName).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final String file = src.requireOne(fileName);
        final Path desiredFilePath = this.schematicsDir.resolve(file + VolumeStreamTest.FILE_ENDING);
        if (!Files.isRegularFile(desiredFilePath)) {
            throw new CommandException(Component.text("File " + file + " was not a normal schemaic file"));
        }
        final Schematic schematic;
        final DataContainer schematicContainer;
        try (final GZIPInputStream stream = new GZIPInputStream(Files.newInputStream(desiredFilePath))) {
            schematicContainer = DataFormats.NBT.get().readFrom(stream);
        } catch (IOException e) {
            e.printStackTrace();
            final StringWriter writer = new StringWriter();
            e.printStackTrace(new PrintWriter(writer));
            final Component errorText = Component.text(writer.toString().replace("\t", "    ").replace("\r\n", "\n").replace("\r", "\n"));
            final TextComponent text = Component.text("Error loading schematic: " + e.getMessage(), NamedTextColor.RED).hoverEvent(HoverEvent.showText(errorText));
            return CommandResult.builder().error(text).build();
        }
        schematic = Sponge.dataManager().translator(Schematic.class).orElseThrow(() -> new IllegalStateException("Expected a DataTranslator for a Schematic")).translate(schematicContainer);
        src.sendMessage(Identity.nil(), Component.text("Loaded schematic from " + file, TextColor.color(0x003434)));
        final PlayerData data = VolumeStreamTest.get(player);
        data.setClipboard(schematic);
        data.setOrigin(player.blockPosition());
        return CommandResult.success();
    }).build(), "load");
    final Parameter.Value<Rotation> rotation = Parameter.registryElement(TypeToken.get(Rotation.class), RegistryTypes.ROTATION).key("rotation").build();
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Rotate clipboard")).permission(this.plugin.metadata().id() + ".command.rotate").addParameter(rotation).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final Rotation desiredRotation = src.requireOne(rotation);
        final Schematic schematic;
        final PlayerData data = VolumeStreamTest.get(player);
        if (data.clipboard == null) {
            throw new CommandException(Component.text("Load a clipboard first before trying to rotate it"));
        }
        final ArchetypeVolume newClipboard = data.clipboard.transform(Transformation.builder().origin(data.clipboard.min().toDouble().add(data.clipboard.size().toDouble().div(2))).rotate(desiredRotation).build());
        src.sendMessage(Identity.nil(), Component.text("Rotated clipboard " + desiredRotation.angle().degrees() + " degrees"));
        data.setClipboard(newClipboard);
        return CommandResult.success();
    }).build(), "rotate");
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) Command(org.spongepowered.api.command.Command) Inject(com.google.inject.Inject) Level(org.apache.logging.log4j.Level) VolumeApplicators(org.spongepowered.api.world.volume.stream.VolumeApplicators) Biome(org.spongepowered.api.world.biome.Biome) Map(java.util.Map) ArchetypeVolume(org.spongepowered.api.world.volume.archetype.ArchetypeVolume) Path(java.nio.file.Path) PrintWriter(java.io.PrintWriter) TextComponent(net.kyori.adventure.text.TextComponent) Plugin(org.spongepowered.plugin.builtin.jvm.Plugin) TextColor(net.kyori.adventure.text.format.TextColor) Sponge(org.spongepowered.api.Sponge) StreamOptions(org.spongepowered.api.world.volume.stream.StreamOptions) StoppingEngineEvent(org.spongepowered.api.event.lifecycle.StoppingEngineEvent) UUID(java.util.UUID) TypeToken(io.leangen.geantyref.TypeToken) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) Root(org.spongepowered.api.event.filter.cause.Root) Transformation(org.spongepowered.api.util.transformation.Transformation) Logger(org.apache.logging.log4j.Logger) Cancellable(org.spongepowered.api.event.Cancellable) GZIPOutputStream(java.util.zip.GZIPOutputStream) Player(org.spongepowered.api.entity.living.player.Player) VolumeCollectors(org.spongepowered.api.world.volume.stream.VolumeCollectors) HoverEvent(net.kyori.adventure.text.event.HoverEvent) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) NonNull(org.checkerframework.checker.nullness.qual.NonNull) DataContainer(org.spongepowered.api.data.persistence.DataContainer) EventContextKeys(org.spongepowered.api.event.EventContextKeys) Schematic(org.spongepowered.api.world.schematic.Schematic) ItemTypes(org.spongepowered.api.item.ItemTypes) HashMap(java.util.HashMap) Rotation(org.spongepowered.api.util.rotation.Rotation) ImmutableList(com.google.common.collect.ImmutableList) Parameter(org.spongepowered.api.command.parameter.Parameter) DataFormats(org.spongepowered.api.data.persistence.DataFormats) Component(net.kyori.adventure.text.Component) Server(org.spongepowered.api.Server) InteractBlockEvent(org.spongepowered.api.event.block.InteractBlockEvent) CauseStackManager(org.spongepowered.api.event.CauseStackManager) RegisterCommandEvent(org.spongepowered.api.event.lifecycle.RegisterCommandEvent) CommandResult(org.spongepowered.api.command.CommandResult) LoadableModule(org.spongepowered.test.LoadableModule) VolumePositionTranslators(org.spongepowered.api.world.volume.stream.VolumePositionTranslators) Files(java.nio.file.Files) Identity(net.kyori.adventure.identity.Identity) StringWriter(java.io.StringWriter) ConfigDir(org.spongepowered.api.config.ConfigDir) IOException(java.io.IOException) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) VariableValueParameters(org.spongepowered.api.command.parameter.managed.standard.VariableValueParameters) PluginContainer(org.spongepowered.plugin.PluginContainer) CommandContext(org.spongepowered.api.command.parameter.CommandContext) Listener(org.spongepowered.api.event.Listener) SpawnTypes(org.spongepowered.api.event.cause.entity.SpawnTypes) CommandException(org.spongepowered.api.command.exception.CommandException) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Vector3i(org.spongepowered.math.vector.Vector3i) GZIPInputStream(java.util.zip.GZIPInputStream) DataContainer(org.spongepowered.api.data.persistence.DataContainer) Biome(org.spongepowered.api.world.biome.Biome) StringWriter(java.io.StringWriter) GZIPOutputStream(java.util.zip.GZIPOutputStream) CauseStackManager(org.spongepowered.api.event.CauseStackManager) TextComponent(net.kyori.adventure.text.TextComponent) Component(net.kyori.adventure.text.Component) PrintWriter(java.io.PrintWriter) Path(java.nio.file.Path) TextComponent(net.kyori.adventure.text.TextComponent) Player(org.spongepowered.api.entity.living.player.Player) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) CommandException(org.spongepowered.api.command.exception.CommandException) IOException(java.io.IOException) Rotation(org.spongepowered.api.util.rotation.Rotation) IOException(java.io.IOException) CommandException(org.spongepowered.api.command.exception.CommandException) ArchetypeVolume(org.spongepowered.api.world.volume.archetype.ArchetypeVolume) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Vector3i(org.spongepowered.math.vector.Vector3i) Parameter(org.spongepowered.api.command.parameter.Parameter) Schematic(org.spongepowered.api.world.schematic.Schematic) Listener(org.spongepowered.api.event.Listener)

Example 2 with CommandException

use of org.spongepowered.api.command.exception.CommandException in project SpongeCommon by SpongePowered.

the class MapTest method testMapShades.

private CommandResult testMapShades(final CommandContext ctx) throws CommandException {
    final Player player = this.requirePlayer(ctx);
    final Collection<RegistryEntry<MapShade>> mapShades = Sponge.game().registry(RegistryTypes.MAP_SHADE).streamEntries().collect(Collectors.toList());
    for (final RegistryEntry<MapShade> entry : mapShades) {
        final MapColor mapColor = MapColor.of(MapColorTypes.COLOR_GREEN.get(), entry.value());
        final MapCanvas mapCanvas = MapCanvas.builder().paintAll(mapColor).build();
        final MapInfo mapInfo = Sponge.server().mapStorage().createNewMapInfo().orElseThrow(() -> new CommandException(Component.text("Unable to create new map!")));
        mapInfo.offer(Keys.MAP_LOCKED, true);
        mapInfo.offer(Keys.MAP_CANVAS, mapCanvas);
        final ItemStack itemStack = ItemStack.of(ItemTypes.FILLED_MAP);
        itemStack.offer(Keys.MAP_INFO, mapInfo);
        itemStack.offer(Keys.CUSTOM_NAME, Component.text(entry.key().formatted()));
        player.inventory().primary().offer(itemStack);
    }
    return CommandResult.success();
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) MapCanvas(org.spongepowered.api.map.MapCanvas) MapShade(org.spongepowered.api.map.color.MapShade) MapInfo(org.spongepowered.api.map.MapInfo) CommandException(org.spongepowered.api.command.exception.CommandException) ItemStack(org.spongepowered.api.item.inventory.ItemStack) RegistryEntry(org.spongepowered.api.registry.RegistryEntry) MapColor(org.spongepowered.api.map.color.MapColor)

Example 3 with CommandException

use of org.spongepowered.api.command.exception.CommandException in project SpongeCommon by SpongePowered.

the class MapTest method printMapData.

private CommandResult printMapData(final CommandContext ctx) throws CommandException {
    final Player player = this.requirePlayer(ctx);
    final ItemStack itemStack = player.itemInHand(HandTypes.MAIN_HAND);
    if (itemStack.type() != ItemTypes.FILLED_MAP.get()) {
        throw new CommandException(Component.text("You must hold a map in your hand"));
    }
    final MapInfo mapInfo = itemStack.require(Keys.MAP_INFO);
    final Audience console = Sponge.systemSubject();
    console.sendMessage(Component.text("the mapdata contains: " + mapInfo.toContainer()));
    console.sendMessage(Component.text("the map contains nbt: " + itemStack.toContainer()));
    // player.sendMessage(Text.of("the map contains vanilla nbt: " + itemStack.get().toContainer().get(DataQuery.of("UnsafeData")).get()));
    return CommandResult.success();
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) Audience(net.kyori.adventure.audience.Audience) MapInfo(org.spongepowered.api.map.MapInfo) CommandException(org.spongepowered.api.command.exception.CommandException) ItemStack(org.spongepowered.api.item.inventory.ItemStack)

Example 4 with CommandException

use of org.spongepowered.api.command.exception.CommandException in project SpongeCommon by SpongePowered.

the class MapTest method setMapWorld.

private CommandResult setMapWorld(final CommandContext ctx) throws CommandException {
    final Player player = this.requirePlayer(ctx);
    final ItemStack heldMap = player.itemInHand(HandTypes.MAIN_HAND);
    if (heldMap.type() != ItemTypes.FILLED_MAP.get()) {
        throw new CommandException(Component.text("You must hold a map in your hand"));
    }
    final MapInfo mapInfo = heldMap.require(Keys.MAP_INFO);
    final ServerWorld serverWorld = (ServerWorld) player.location().world();
    mapInfo.offer(Keys.MAP_WORLD, serverWorld.key());
    player.sendMessage(Component.text("New map world: " + mapInfo.require(Keys.MAP_WORLD)));
    return CommandResult.success();
}
Also used : ServerWorld(org.spongepowered.api.world.server.ServerWorld) Player(org.spongepowered.api.entity.living.player.Player) MapInfo(org.spongepowered.api.map.MapInfo) CommandException(org.spongepowered.api.command.exception.CommandException) ItemStack(org.spongepowered.api.item.inventory.ItemStack)

Example 5 with CommandException

use of org.spongepowered.api.command.exception.CommandException in project SpongeCommon by SpongePowered.

the class MapTest method addWorldBanner.

private CommandResult addWorldBanner(final CommandContext ctx) throws CommandException {
    final Player player = this.requirePlayer(ctx);
    final ItemStack heldMap = player.itemInHand(HandTypes.MAIN_HAND);
    if (heldMap.type() != ItemTypes.FILLED_MAP.get()) {
        throw new CommandException(Component.text("You must hold a map in your hand"));
    }
    final MapInfo mapInfo = heldMap.require(Keys.MAP_INFO);
    final RayTraceResult<LocatableBlock> hit = RayTrace.block().sourcePosition(player).direction(player).world(player.serverLocation().world()).continueWhileBlock(RayTrace.onlyAir()).limit(100).select(a -> a.location().blockEntity().filter(entity -> entity instanceof Banner).isPresent()).execute().orElseThrow(() -> new CommandException(Component.text("You must look at a banner")));
    mapInfo.addBannerDecoration(hit.selectedObject().serverLocation());
    return CommandResult.success();
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) Banner(org.spongepowered.api.block.entity.Banner) MapInfo(org.spongepowered.api.map.MapInfo) LocatableBlock(org.spongepowered.api.world.LocatableBlock) CommandException(org.spongepowered.api.command.exception.CommandException) ItemStack(org.spongepowered.api.item.inventory.ItemStack)

Aggregations

CommandException (org.spongepowered.api.command.exception.CommandException)26 Player (org.spongepowered.api.entity.living.player.Player)19 ItemStack (org.spongepowered.api.item.inventory.ItemStack)17 MapInfo (org.spongepowered.api.map.MapInfo)10 Component (net.kyori.adventure.text.Component)8 Audience (net.kyori.adventure.audience.Audience)6 CommandResult (org.spongepowered.api.command.CommandResult)5 ServerPlayer (org.spongepowered.api.entity.living.player.server.ServerPlayer)5 Inject (com.google.inject.Inject)4 UUID (java.util.UUID)4 Identity (net.kyori.adventure.identity.Identity)4 NamedTextColor (net.kyori.adventure.text.format.NamedTextColor)4 Sponge (org.spongepowered.api.Sponge)4 Command (org.spongepowered.api.command.Command)4 Listener (org.spongepowered.api.event.Listener)4 RegisterCommandEvent (org.spongepowered.api.event.lifecycle.RegisterCommandEvent)4 PluginContainer (org.spongepowered.plugin.PluginContainer)4 Plugin (org.spongepowered.plugin.builtin.jvm.Plugin)4 IOException (java.io.IOException)3 Collection (java.util.Collection)3