Search in sources :

Example 26 with InputParseException

use of com.sk89q.worldedit.extension.input.InputParseException in project FastAsyncWorldEdit by IntellectualSites.

the class SpongeSchematicReader method readVersion1.

private BlockArrayClipboard readVersion1(CompoundTag schematicTag) throws IOException {
    BlockVector3 origin;
    Region region;
    Map<String, Tag> schematic = schematicTag.getValue();
    int width = requireTag(schematic, "Width", ShortTag.class).getValue();
    int height = requireTag(schematic, "Height", ShortTag.class).getValue();
    int length = requireTag(schematic, "Length", ShortTag.class).getValue();
    IntArrayTag offsetTag = getTag(schematic, "Offset", IntArrayTag.class);
    int[] offsetParts;
    if (offsetTag != null) {
        offsetParts = offsetTag.getValue();
        if (offsetParts.length != 3) {
            throw new IOException("Invalid offset specified in schematic.");
        }
    } else {
        offsetParts = new int[] { 0, 0, 0 };
    }
    BlockVector3 min = BlockVector3.at(offsetParts[0], offsetParts[1], offsetParts[2]);
    CompoundTag metadataTag = getTag(schematic, "Metadata", CompoundTag.class);
    if (metadataTag != null && metadataTag.containsKey("WEOffsetX")) {
        // We appear to have WorldEdit Metadata
        Map<String, Tag> metadata = metadataTag.getValue();
        int offsetX = requireTag(metadata, "WEOffsetX", IntTag.class).getValue();
        int offsetY = requireTag(metadata, "WEOffsetY", IntTag.class).getValue();
        int offsetZ = requireTag(metadata, "WEOffsetZ", IntTag.class).getValue();
        BlockVector3 offset = BlockVector3.at(offsetX, offsetY, offsetZ);
        origin = min.subtract(offset);
        region = new CuboidRegion(min, min.add(width, height, length).subtract(BlockVector3.ONE));
    } else {
        origin = min;
        region = new CuboidRegion(origin, origin.add(width, height, length).subtract(BlockVector3.ONE));
    }
    IntTag paletteMaxTag = getTag(schematic, "PaletteMax", IntTag.class);
    Map<String, Tag> paletteObject = requireTag(schematic, "Palette", CompoundTag.class).getValue();
    if (paletteMaxTag != null && paletteObject.size() != paletteMaxTag.getValue()) {
        throw new IOException("Block palette size does not match expected size.");
    }
    Map<Integer, BlockState> palette = new HashMap<>();
    ParserContext parserContext = new ParserContext();
    parserContext.setRestricted(false);
    parserContext.setTryLegacy(false);
    parserContext.setPreferringWildcard(false);
    for (String palettePart : paletteObject.keySet()) {
        int id = requireTag(paletteObject, palettePart, IntTag.class).getValue();
        if (fixer != null) {
            palettePart = fixer.fixUp(DataFixer.FixTypes.BLOCK_STATE, palettePart, dataVersion);
        }
        BlockState state;
        try {
            state = WorldEdit.getInstance().getBlockFactory().parseFromInput(palettePart, parserContext).toImmutableState();
        } catch (InputParseException e) {
            LOGGER.warn("Invalid BlockState in palette: " + palettePart + ". Block will be replaced with air.");
            state = BlockTypes.AIR.getDefaultState();
        }
        palette.put(id, state);
    }
    byte[] blocks = requireTag(schematic, "BlockData", ByteArrayTag.class).getValue();
    Map<BlockVector3, Map<String, Tag>> tileEntitiesMap = new HashMap<>();
    ListTag tileEntities = getTag(schematic, "BlockEntities", ListTag.class);
    if (tileEntities == null) {
        tileEntities = getTag(schematic, "TileEntities", ListTag.class);
    }
    if (tileEntities != null) {
        List<Map<String, Tag>> tileEntityTags = tileEntities.getValue().stream().map(tag -> (CompoundTag) tag).map(CompoundTag::getValue).collect(Collectors.toList());
        for (Map<String, Tag> tileEntity : tileEntityTags) {
            int[] pos = requireTag(tileEntity, "Pos", IntArrayTag.class).getValue();
            final BlockVector3 pt = BlockVector3.at(pos[0], pos[1], pos[2]);
            Map<String, Tag> values = Maps.newHashMap(tileEntity);
            values.put("x", new IntTag(pt.getBlockX()));
            values.put("y", new IntTag(pt.getBlockY()));
            values.put("z", new IntTag(pt.getBlockZ()));
            // FAWE start - support old, corrupt schematics
            Tag id = values.get("Id");
            if (id == null) {
                id = values.get("id");
            }
            if (id == null) {
                continue;
            }
            // FAWE end
            values.put("id", values.get("Id"));
            values.remove("Id");
            values.remove("Pos");
            if (fixer != null) {
                // FAWE start - BinaryTag
                tileEntity = ((CompoundTag) AdventureNBTConverter.fromAdventure(fixer.fixUp(DataFixer.FixTypes.BLOCK_ENTITY, new CompoundTag(values).asBinaryTag(), dataVersion))).getValue();
            // FAWE end
            } else {
                tileEntity = values;
            }
            tileEntitiesMap.put(pt, tileEntity);
        }
    }
    BlockArrayClipboard clipboard = new BlockArrayClipboard(region);
    clipboard.setOrigin(origin);
    int index = 0;
    int i = 0;
    int value;
    int varintLength;
    while (i < blocks.length) {
        value = 0;
        varintLength = 0;
        while (true) {
            value |= (blocks[i] & 127) << (varintLength++ * 7);
            if (varintLength > 5) {
                throw new IOException("VarInt too big (probably corrupted data)");
            }
            if ((blocks[i] & 128) != 128) {
                i++;
                break;
            }
            i++;
        }
        // index = (y * length * width) + (z * width) + x
        int y = index / (width * length);
        int z = (index % (width * length)) / width;
        int x = (index % (width * length)) % width;
        BlockState state = palette.get(value);
        BlockVector3 pt = BlockVector3.at(x, y, z);
        try {
            if (tileEntitiesMap.containsKey(pt)) {
                clipboard.setBlock(clipboard.getMinimumPoint().add(pt), state.toBaseBlock(new CompoundTag(tileEntitiesMap.get(pt))));
            } else {
                clipboard.setBlock(clipboard.getMinimumPoint().add(pt), state);
            }
        } catch (WorldEditException e) {
            throw new IOException("Failed to load a block in the schematic");
        }
        index++;
    }
    return clipboard;
}
Also used : HashMap(java.util.HashMap) CuboidRegion(com.sk89q.worldedit.regions.CuboidRegion) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) CompoundTag(com.sk89q.jnbt.CompoundTag) IntTag(com.sk89q.jnbt.IntTag) IntArrayTag(com.sk89q.jnbt.IntArrayTag) BlockArrayClipboard(com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard) IOException(java.io.IOException) BlockVector3(com.sk89q.worldedit.math.BlockVector3) ListTag(com.sk89q.jnbt.ListTag) ShortTag(com.sk89q.jnbt.ShortTag) BlockState(com.sk89q.worldedit.world.block.BlockState) CuboidRegion(com.sk89q.worldedit.regions.CuboidRegion) Region(com.sk89q.worldedit.regions.Region) StringTag(com.sk89q.jnbt.StringTag) ShortTag(com.sk89q.jnbt.ShortTag) IntArrayTag(com.sk89q.jnbt.IntArrayTag) ListTag(com.sk89q.jnbt.ListTag) IntTag(com.sk89q.jnbt.IntTag) NamedTag(com.sk89q.jnbt.NamedTag) ByteArrayTag(com.sk89q.jnbt.ByteArrayTag) CompoundTag(com.sk89q.jnbt.CompoundTag) Tag(com.sk89q.jnbt.Tag) ParserContext(com.sk89q.worldedit.extension.input.ParserContext) WorldEditException(com.sk89q.worldedit.WorldEditException) HashMap(java.util.HashMap) Map(java.util.Map) ByteArrayTag(com.sk89q.jnbt.ByteArrayTag)

Example 27 with InputParseException

use of com.sk89q.worldedit.extension.input.InputParseException in project FastAsyncWorldEdit by IntellectualSites.

the class LegacyMapper method loadFromResource.

/**
 * Attempt to load the data from file.
 *
 * @throws IOException thrown on I/O error
 */
private void loadFromResource() throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Vector3.class, new VectorAdapter());
    Gson gson = gsonBuilder.disableHtmlEscaping().create();
    URL url = resourceLoader.getResource(LegacyMapper.class, "legacy.json");
    if (url == null) {
        throw new IOException("Could not find legacy.json");
    }
    String data = Resources.toString(url, Charset.defaultCharset());
    LegacyDataFile dataFile = gson.fromJson(data, new TypeToken<LegacyDataFile>() {
    }.getType());
    DataFixer fixer = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).getDataFixer();
    ParserContext parserContext = new ParserContext();
    parserContext.setPreferringWildcard(false);
    parserContext.setRestricted(false);
    // This is legacy. Don't match itself.
    parserContext.setTryLegacy(false);
    for (Map.Entry<String, String> blockEntry : dataFile.blocks.entrySet()) {
        String id = blockEntry.getKey();
        final String value = blockEntry.getValue();
        // FAWE start
        Integer combinedId = getCombinedId(blockEntry.getKey());
        blockEntries.put(id, value);
        // FAWE end
        BlockState state = null;
        // FAWE start
        try {
            state = BlockState.get(null, blockEntry.getValue());
            BlockType type = state.getBlockType();
            if (type.hasProperty(PropertyKey.WATERLOGGED)) {
                state = state.with(PropertyKey.WATERLOGGED, false);
            }
        } catch (InputParseException f) {
            BlockFactory blockFactory = WorldEdit.getInstance().getBlockFactory();
            // if fixer is available, try using that first, as some old blocks that were renamed share names with new blocks
            if (fixer != null) {
                try {
                    String newEntry = fixer.fixUp(DataFixer.FixTypes.BLOCK_STATE, value, Constants.DATA_VERSION_MC_1_13_2);
                    state = blockFactory.parseFromInput(newEntry, parserContext).toImmutableState();
                } catch (InputParseException ignored) {
                }
            }
            // if it's still null, the fixer was unavailable or failed
            if (state == null) {
                try {
                    state = blockFactory.parseFromInput(value, parserContext).toImmutableState();
                } catch (InputParseException ignored) {
                }
            }
            // if it's still null, both fixer and default failed
            if (state == null) {
                LOGGER.error("Unknown block: {}. Neither the DataFixer nor defaulting worked to recognize this block.", value);
            } else {
                // it's not null so one of them succeeded, now use it
                blockToStringMap.put(state, id);
                stringToBlockMap.put(id, state);
            }
        }
        // FAWE start
        if (state != null) {
            blockArr[combinedId] = state.getInternalId();
            blockStateToLegacyId4Data.put(state.getInternalId(), combinedId);
            blockStateToLegacyId4Data.putIfAbsent(state.getInternalBlockTypeId(), combinedId);
        }
    }
    for (int id = 0; id < 256; id++) {
        int combinedId = id << 4;
        int base = blockArr[combinedId];
        if (base != 0) {
            for (int data_ = 0; data_ < 16; data_++, combinedId++) {
                if (blockArr[combinedId] == 0) {
                    blockArr[combinedId] = base;
                }
            }
        }
    }
    for (Map.Entry<String, String> itemEntry : dataFile.items.entrySet()) {
        String id = itemEntry.getKey();
        String value = itemEntry.getValue();
        ItemType type = ItemTypes.get(value);
        if (type == null && fixer != null) {
            value = fixer.fixUp(DataFixer.FixTypes.ITEM_TYPE, value, Constants.DATA_VERSION_MC_1_13_2);
            type = ItemTypes.get(value);
        }
        if (type == null) {
            LOGGER.error("Unknown item: {}. Neither the DataFixer nor defaulting worked to recognize this item.", value);
        } else {
            try {
                itemMap.put(getCombinedId(id), type);
            } catch (Exception ignored) {
            }
        }
    }
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) BlockFactory(com.sk89q.worldedit.extension.factory.BlockFactory) VectorAdapter(com.sk89q.worldedit.util.gson.VectorAdapter) ItemType(com.sk89q.worldedit.world.item.ItemType) Gson(com.google.gson.Gson) IOException(java.io.IOException) URL(java.net.URL) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) IOException(java.io.IOException) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) BlockState(com.sk89q.worldedit.world.block.BlockState) BlockType(com.sk89q.worldedit.world.block.BlockType) TypeToken(com.google.gson.reflect.TypeToken) DataFixer(com.sk89q.worldedit.world.DataFixer) ParserContext(com.sk89q.worldedit.extension.input.ParserContext) HashMap(java.util.HashMap) Map(java.util.Map) BiMap(com.google.common.collect.BiMap) HashBiMap(com.google.common.collect.HashBiMap) Int2ObjectArrayMap(it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap)

Example 28 with InputParseException

use of com.sk89q.worldedit.extension.input.InputParseException in project bteConoSurCore by BTEConoSur.

the class Tree method place.

// PLACE
public EditSession place(Vector loc, Player player, EditSession editSession) {
    if (editSession == null) {
        editSession = getEditSession(player);
    }
    com.sk89q.worldedit.entity.Player actor = new BukkitPlayer((WorldEditPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldEdit"), ((WorldEditPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldEdit")).getServerInterface(), player);
    LocalSession localSession = WorldEdit.getInstance().getSessionManager().get(actor);
    Clipboard clipboard;
    ClipboardFormat format = ClipboardFormat.SCHEMATIC;
    try {
        ClipboardReader reader = format.getReader(new FileInputStream(schematic));
        clipboard = reader.read(actor.getWorld().getWorldData());
        clipboard.setOrigin(new Vector(xOffset, yOffset, zOffset));
        Region region = clipboard.getRegion();
        // PASTE SCHEMATIC
        // Get Maxs and Mins
        int xMax = clipboard.getMaximumPoint().getBlockX();
        int yMax = clipboard.getMaximumPoint().getBlockY();
        int zMax = clipboard.getMaximumPoint().getBlockZ();
        // MASK
        Mask mask = localSession.getMask();
        if (mask == null) {
            ParserContext parserContext = new ParserContext();
            parserContext.setActor(actor);
            Extent extent = actor.getExtent();
            if (extent instanceof World) {
                parserContext.setWorld((World) extent);
            }
            parserContext.setSession(WorldEdit.getInstance().getSessionManager().get(actor));
            mask = WorldEdit.getInstance().getMaskFactory().parseFromInput("0", parserContext);
        }
        // ROTATION
        int degrees = new Random().nextInt(4);
        // ORIGEN
        int xOg = loc.getBlockX();
        int zOg = loc.getBlockZ();
        for (BlockVector p : region) {
            if (clipboard.getBlock(p).getType() != 0) {
                int x = loc.getBlockX() + p.getBlockX() - xMax + xOffset;
                int y = loc.getBlockY() + p.getBlockY() - yMax + yOffset;
                int z = loc.getBlockZ() + p.getBlockZ() - zMax + zOffset;
                int x0 = x - xOg;
                int z0 = z - zOg;
                if (degrees == 1) {
                    x = z0 + xOg;
                    z = -x0 + zOg;
                } else if (degrees == 2) {
                    x = -x0 + xOg;
                    z = -z0 + zOg;
                } else if (degrees == 3) {
                    x = -z0 + xOg;
                    z = x0 + zOg;
                }
                Vector newVector = new Vector(x, y + clipboard.getDimensions().getBlockY() - 1, z);
                if (mask.test(newVector) && getWorldGuard().canBuild(player, mainWorld.getBlockAt(newVector.getBlockX(), newVector.getBlockY(), newVector.getBlockZ()))) {
                    editSession.setBlock(newVector, clipboard.getBlock(p));
                }
            }
        }
        return editSession;
    } catch (IOException | MaxChangedBlocksException | InputParseException e) {
        e.printStackTrace();
        return null;
    }
}
Also used : Extent(com.sk89q.worldedit.extent.Extent) Mask(com.sk89q.worldedit.function.mask.Mask) IOException(java.io.IOException) BteConoSur.mainWorld(pizzaaxx.bteconosur.BteConoSur.mainWorld) World(com.sk89q.worldedit.world.World) ClipboardFormat(com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat) FileInputStream(java.io.FileInputStream) BukkitPlayer(com.sk89q.worldedit.bukkit.BukkitPlayer) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) Random(java.util.Random) Region(com.sk89q.worldedit.regions.Region) Clipboard(com.sk89q.worldedit.extent.clipboard.Clipboard) ClipboardReader(com.sk89q.worldedit.extent.clipboard.io.ClipboardReader) ParserContext(com.sk89q.worldedit.extension.input.ParserContext)

Example 29 with InputParseException

use of com.sk89q.worldedit.extension.input.InputParseException in project bteConoSurCore by BTEConoSur.

the class Polywall method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (command.getName().equals("/polywalls")) {
        if (sender instanceof Player) {
            Player p = (Player) sender;
            // 
            // GET REGION
            Region region = null;
            try {
                region = getSelection(p);
            } catch (IncompleteRegionException e) {
                p.sendMessage(wePrefix + "Selecciona un área primero.");
                return true;
            }
            if (args.length > 0) {
                // PARSE PATTERN
                com.sk89q.worldedit.entity.Player actor = new BukkitPlayer((WorldEditPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldEdit"), ((WorldEditPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldEdit")).getServerInterface(), p);
                LocalSession localSession = WorldEdit.getInstance().getSessionManager().get(actor);
                Mask mask = localSession.getMask();
                ParserContext parserContext = new ParserContext();
                parserContext.setActor(actor);
                Extent extent = ((Entity) actor).getExtent();
                if (extent instanceof World) {
                    parserContext.setWorld((World) extent);
                }
                parserContext.setSession(WorldEdit.getInstance().getSessionManager().get(actor));
                Pattern pattern;
                try {
                    pattern = WorldEdit.getInstance().getPatternFactory().parseFromInput(args[0], parserContext);
                } catch (InputParseException e) {
                    p.sendMessage(wePrefix + "Patrón inválido.");
                    return true;
                }
                // GET POINTS
                List<BlockVector2D> points = new ArrayList<>();
                int maxY;
                int minY;
                if (region instanceof CuboidRegion) {
                    CuboidRegion cuboidRegion = (CuboidRegion) region;
                    Vector first = cuboidRegion.getPos1();
                    Vector second = cuboidRegion.getPos2();
                    maxY = cuboidRegion.getMaximumY();
                    minY = cuboidRegion.getMinimumY();
                    points.add(new BlockVector2D(first.getX(), first.getZ()));
                    points.add(new BlockVector2D(second.getX(), first.getZ()));
                    points.add(new BlockVector2D(second.getX(), second.getZ()));
                    points.add(new BlockVector2D(first.getX(), second.getZ()));
                } else if (region instanceof Polygonal2DRegion) {
                    maxY = ((Polygonal2DRegion) region).getMaximumY();
                    minY = ((Polygonal2DRegion) region).getMinimumY();
                    points = ((Polygonal2DRegion) region).getPoints();
                } else {
                    p.sendMessage(wePrefix + "Debes seleccionar una region cúbica o poligonal.");
                    return true;
                }
                if (points.size() < 3) {
                    p.sendMessage(wePrefix + "Selecciona un área primero.");
                    return true;
                }
                List<BlockVector2D> pointsFinal = new ArrayList<>(points);
                pointsFinal.add(points.get(0));
                EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession((World) new BukkitWorld(mainWorld), WorldEdit.getInstance().getSessionManager().get(actor).getBlockChangeLimit());
                for (int i = minY; i <= maxY; i++) {
                    for (int j = 0; j < pointsFinal.size() - 1; j++) {
                        BlockVector2D v1 = pointsFinal.get(j);
                        BlockVector2D v2 = pointsFinal.get(j + 1);
                        setBlocksInLine(p, actor, editSession, pattern, mask, v1.toVector(i), v2.toVector(i));
                    }
                }
                p.sendMessage(wePrefix + "Paredes de la selección creadas.");
            } else {
                p.sendMessage(wePrefix + "Introduce un patrón de bloques.");
            }
        }
    }
    return true;
}
Also used : Entity(com.sk89q.worldedit.entity.Entity) Pattern(com.sk89q.worldedit.function.pattern.Pattern) BukkitPlayer(com.sk89q.worldedit.bukkit.BukkitPlayer) Player(org.bukkit.entity.Player) Extent(com.sk89q.worldedit.extent.Extent) Mask(com.sk89q.worldedit.function.mask.Mask) ArrayList(java.util.ArrayList) BukkitWorld(com.sk89q.worldedit.bukkit.BukkitWorld) CuboidRegion(com.sk89q.worldedit.regions.CuboidRegion) BteConoSur.mainWorld(pizzaaxx.bteconosur.BteConoSur.mainWorld) World(com.sk89q.worldedit.world.World) BukkitWorld(com.sk89q.worldedit.bukkit.BukkitWorld) BukkitPlayer(com.sk89q.worldedit.bukkit.BukkitPlayer) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) Polygonal2DRegion(com.sk89q.worldedit.regions.Polygonal2DRegion) Polygonal2DRegion(com.sk89q.worldedit.regions.Polygonal2DRegion) CuboidRegion(com.sk89q.worldedit.regions.CuboidRegion) Region(com.sk89q.worldedit.regions.Region) ParserContext(com.sk89q.worldedit.extension.input.ParserContext)

Aggregations

InputParseException (com.sk89q.worldedit.extension.input.InputParseException)29 ParserContext (com.sk89q.worldedit.extension.input.ParserContext)11 NoMatchException (com.sk89q.worldedit.extension.input.NoMatchException)7 Extent (com.sk89q.worldedit.extent.Extent)7 Pattern (com.sk89q.worldedit.function.pattern.Pattern)7 Map (java.util.Map)7 Actor (com.sk89q.worldedit.extension.platform.Actor)5 IOException (java.io.IOException)5 HashMap (java.util.HashMap)5 BlanketBaseBlock (com.fastasyncworldedit.core.world.block.BlanketBaseBlock)4 CompoundTag (com.sk89q.jnbt.CompoundTag)4 WorldEdit (com.sk89q.worldedit.WorldEdit)4 WorldEditException (com.sk89q.worldedit.WorldEditException)4 BlockVector3 (com.sk89q.worldedit.math.BlockVector3)4 World (com.sk89q.worldedit.world.World)4 BaseBlock (com.sk89q.worldedit.world.block.BaseBlock)4 List (java.util.List)4 Stream (java.util.stream.Stream)4 SuggestInputParseException (com.fastasyncworldedit.core.command.SuggestInputParseException)3 Caption (com.fastasyncworldedit.core.configuration.Caption)3