Search in sources :

Example 11 with Pattern

use of com.sk89q.worldedit.function.pattern.Pattern in project FastAsyncWorldEdit by IntellectualSites.

the class RichPatternParser method parseFromInput.

@Override
public Pattern parseFromInput(String input, ParserContext context) throws InputParseException {
    if (input.isEmpty()) {
        throw new SuggestInputParseException("No input provided", "", () -> Stream.concat(Stream.of("#", ",", "&"), BlockTypes.getNameSpaces().stream().map(n -> n + ":")).collect(Collectors.toList()));
    }
    List<Double> chances = new ArrayList<>();
    List<Pattern> patterns = new ArrayList<>();
    final CommandLocals locals = new CommandLocals();
    Actor actor = context != null ? context.getActor() : null;
    if (actor != null) {
        locals.put(Actor.class, actor);
    }
    try {
        for (Map.Entry<ParseEntry, List<String>> entry : parse(input)) {
            ParseEntry pe = entry.getKey();
            final String command = pe.getInput();
            String full = pe.getFull();
            Pattern pattern = null;
            double chance = 1;
            if (command.isEmpty()) {
                pattern = parseFromInput(StringMan.join(entry.getValue(), ','), context);
            } else if (!worldEdit.getPatternFactory().containsAlias(command)) {
                // Legacy patterns
                char char0 = command.charAt(0);
                boolean charPattern = input.length() > 1 && input.charAt(1) != '[';
                if (charPattern && input.charAt(0) == '=') {
                    pattern = parseFromInput(char0 + "[" + input.substring(1) + "]", context);
                }
                if (char0 == '#' && command.length() > 1 && command.charAt(1) != '#') {
                    throw new SuggestInputParseException(new NoMatchException(Caption.of("fawe.error.parse.unknown-pattern", full, TextComponent.of("https://intellectualsites.github.io/fastasyncworldedit-documentation/patterns/patterns").clickEvent(ClickEvent.openUrl("https://intellectualsites.github.io/fastasyncworldedit-documentation/patterns/patterns")))), full, () -> {
                        if (full.length() == 1) {
                            return new ArrayList<>(worldEdit.getPatternFactory().getSuggestions(""));
                        }
                        return new ArrayList<>(worldEdit.getPatternFactory().getSuggestions(command.toLowerCase(Locale.ROOT)));
                    });
                }
                if (charPattern) {
                    if (char0 == '$' || char0 == '^' || char0 == '*' || (char0 == '#' && input.charAt(1) == '#')) {
                        pattern = worldEdit.getPatternFactory().parseWithoutRich(full, context);
                    }
                }
                if (pattern == null) {
                    if (command.startsWith("[")) {
                        int end = command.lastIndexOf(']');
                        pattern = parseFromInput(command.substring(1, end == -1 ? command.length() : end), context);
                    } else {
                        int percentIndex = command.indexOf('%');
                        if (percentIndex != -1 && percentPatternRegex.matcher(command).matches()) {
                            // Legacy percent pattern
                            chance = Expression.compile(command.substring(0, percentIndex)).evaluate();
                            String value = command.substring(percentIndex + 1);
                            if (!entry.getValue().isEmpty()) {
                                boolean addBrackets = !value.isEmpty();
                                if (addBrackets) {
                                    value += "[";
                                }
                                value += StringMan.join(entry.getValue(), " ");
                                if (addBrackets) {
                                    value += "]";
                                }
                            }
                            pattern = parseFromInput(value, context);
                        } else {
                            // legacy block pattern
                            try {
                                pattern = worldEdit.getBlockFactory().parseFromInput(pe.getFull(), context);
                            } catch (NoMatchException e) {
                                throw new NoMatchException(Caption.of("fawe.error.parse.unknown-pattern", full, TextComponent.of("https://intellectualsites.github.io/fastasyncworldedit-documentation/patterns/patterns").clickEvent(com.sk89q.worldedit.util.formatting.text.event.ClickEvent.openUrl("https://intellectualsites.github.io/fastasyncworldedit-documentation/patterns/patterns"))));
                            }
                        }
                    }
                }
            } else {
                List<String> args = entry.getValue();
                try {
                    pattern = worldEdit.getPatternFactory().parseWithoutRich(full, context);
                } catch (InputParseException rethrow) {
                    throw rethrow;
                } catch (Throwable e) {
                    throw SuggestInputParseException.of(e, full, () -> {
                        try {
                            String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " "));
                            List<Substring> split = CommandArgParser.forArgString(cmdArgs).parseArgs().toList();
                            List<String> argStrings = split.stream().map(Substring::getSubstring).collect(Collectors.toList());
                            MemoizingValueAccess access = getPlatform().initializeInjectedValues(() -> cmdArgs, actor, null, true);
                            List<String> suggestions = getPlatform().getCommandManager().getSuggestions(access, argStrings).stream().map(Suggestion::getSuggestion).collect(Collectors.toUnmodifiableList());
                            List<String> result = new ArrayList<>();
                            if (suggestions.size() <= 2) {
                                for (int i = 0; i < suggestions.size(); i++) {
                                    String suggestion = suggestions.get(i);
                                    if (suggestion.indexOf(' ') != 0) {
                                        String[] splitSuggestion = suggestion.split(" ");
                                        suggestion = "[" + StringMan.join(splitSuggestion, "][") + "]";
                                        result.set(i, suggestion);
                                    }
                                }
                            }
                            return result;
                        } catch (Throwable e2) {
                            e2.printStackTrace();
                            throw new InputParseException(TextComponent.of(e2.getMessage()));
                        }
                    });
                }
            }
            if (pattern != null) {
                patterns.add(pattern);
                chances.add(chance);
            }
        }
    } catch (InputParseException rethrow) {
        throw rethrow;
    } catch (Throwable e) {
        e.printStackTrace();
        throw new InputParseException(TextComponent.of(e.getMessage()), e);
    }
    if (patterns.isEmpty()) {
        return null;
    }
    if (patterns.size() == 1) {
        return patterns.get(0);
    }
    RandomPattern random = new RandomPattern(new TrueRandom());
    for (int i = 0; i < patterns.size(); i++) {
        random.add(patterns.get(i), chances.get(i));
    }
    return random;
}
Also used : SuggestInputParseException(com.fastasyncworldedit.core.command.SuggestInputParseException) BlockTypes(com.sk89q.worldedit.world.block.BlockTypes) Suggestion(org.enginehub.piston.suggestion.Suggestion) Caption(com.fastasyncworldedit.core.configuration.Caption) MemoizingValueAccess(org.enginehub.piston.inject.MemoizingValueAccess) ParserContext(com.sk89q.worldedit.extension.input.ParserContext) FaweParser(com.fastasyncworldedit.core.extension.factory.parser.FaweParser) TrueRandom(com.fastasyncworldedit.core.math.random.TrueRandom) StringMan(com.fastasyncworldedit.core.util.StringMan) ArrayList(java.util.ArrayList) CommandLocals(com.sk89q.minecraft.util.commands.CommandLocals) Substring(com.sk89q.worldedit.internal.util.Substring) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) Locale(java.util.Locale) ClickEvent(com.sk89q.worldedit.util.formatting.text.event.ClickEvent) Map(java.util.Map) WorldEdit(com.sk89q.worldedit.WorldEdit) NoMatchException(com.sk89q.worldedit.extension.input.NoMatchException) CommandArgParser(com.sk89q.worldedit.internal.command.CommandArgParser) TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) Expression(com.sk89q.worldedit.internal.expression.Expression) RandomPattern(com.sk89q.worldedit.function.pattern.RandomPattern) Collectors(java.util.stream.Collectors) Actor(com.sk89q.worldedit.extension.platform.Actor) List(java.util.List) Stream(java.util.stream.Stream) Pattern(com.sk89q.worldedit.function.pattern.Pattern) Collections(java.util.Collections) ArrayList(java.util.ArrayList) SuggestInputParseException(com.fastasyncworldedit.core.command.SuggestInputParseException) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) Actor(com.sk89q.worldedit.extension.platform.Actor) TrueRandom(com.fastasyncworldedit.core.math.random.TrueRandom) ArrayList(java.util.ArrayList) List(java.util.List) Substring(com.sk89q.worldedit.internal.util.Substring) RandomPattern(com.sk89q.worldedit.function.pattern.RandomPattern) Pattern(com.sk89q.worldedit.function.pattern.Pattern) MemoizingValueAccess(org.enginehub.piston.inject.MemoizingValueAccess) SuggestInputParseException(com.fastasyncworldedit.core.command.SuggestInputParseException) CommandLocals(com.sk89q.minecraft.util.commands.CommandLocals) RandomPattern(com.sk89q.worldedit.function.pattern.RandomPattern) NoMatchException(com.sk89q.worldedit.extension.input.NoMatchException) Map(java.util.Map)

Example 12 with Pattern

use of com.sk89q.worldedit.function.pattern.Pattern in project FastAsyncWorldEdit by IntellectualSites.

the class FaweDelegateRegionManager method handleClear.

public boolean handleClear(@Nonnull Plot plot, @Nullable Runnable whenDone, @Nonnull PlotManager manager) {
    TaskManager.taskManager().async(() -> {
        synchronized (FaweDelegateRegionManager.class) {
            final HybridPlotWorld hybridPlotWorld = ((HybridPlotManager) manager).getHybridPlotWorld();
            World world = BukkitAdapter.adapt(getWorld(hybridPlotWorld.getWorldName()));
            EditSession editSession = WorldEdit.getInstance().newEditSessionBuilder().world(world).checkMemory(false).fastMode(true).limitUnlimited().changeSetNull().build();
            if (!hybridPlotWorld.PLOT_SCHEMATIC || !Settings.Schematics.PASTE_ON_TOP) {
                final BlockType bedrock;
                final BlockType air = BlockTypes.AIR;
                if (hybridPlotWorld.PLOT_BEDROCK) {
                    bedrock = BlockTypes.BEDROCK;
                } else {
                    bedrock = air;
                }
                final Pattern filling = hybridPlotWorld.MAIN_BLOCK.toPattern();
                final Pattern plotfloor = hybridPlotWorld.TOP_BLOCK.toPattern();
                final BiomeType biome = hybridPlotWorld.getPlotBiome();
                BlockVector3 pos1 = plot.getBottomAbs().getBlockVector3();
                BlockVector3 pos2 = pos1.add(BlockVector3.at(hybridPlotWorld.PLOT_WIDTH - 1, hybridPlotWorld.getMaxGenHeight(), hybridPlotWorld.PLOT_WIDTH - 1));
                if (hybridPlotWorld.PLOT_BEDROCK) {
                    Region bedrockRegion = new CuboidRegion(pos1, pos2.withY(hybridPlotWorld.getMinGenHeight()));
                    editSession.setBlocks(bedrockRegion, bedrock);
                }
                Region fillingRegion = new CuboidRegion(pos1.withY(hybridPlotWorld.getMinGenHeight() + 1), pos2.withY(hybridPlotWorld.PLOT_HEIGHT - 1));
                Region floorRegion = new CuboidRegion(pos1.withY(hybridPlotWorld.PLOT_HEIGHT), pos2.withY(hybridPlotWorld.PLOT_HEIGHT));
                Region airRegion = new CuboidRegion(pos1.withY(hybridPlotWorld.PLOT_HEIGHT + 1), pos2.withY(hybridPlotWorld.getMaxGenHeight()));
                editSession.setBlocks(fillingRegion, filling);
                editSession.setBlocks(floorRegion, plotfloor);
                editSession.setBlocks(airRegion, air);
            }
            if (hybridPlotWorld.PLOT_SCHEMATIC) {
                // We cannot reuse the editsession
                EditSession scheditsession = !Settings.Schematics.PASTE_ON_TOP ? editSession : WorldEdit.getInstance().newEditSessionBuilder().world(world).checkMemory(false).fastMode(true).limitUnlimited().changeSetNull().build();
                File schematicFile = new File(hybridPlotWorld.getRoot(), "plot.schem");
                if (!schematicFile.exists()) {
                    schematicFile = new File(hybridPlotWorld.getRoot(), "plot.schematic");
                }
                BlockVector3 to = plot.getBottomAbs().getBlockVector3().withY(Settings.Schematics.PASTE_ON_TOP ? hybridPlotWorld.SCHEM_Y : hybridPlotWorld.getMinBuildHeight());
                try {
                    Clipboard clip = ClipboardFormats.findByFile(schematicFile).getReader(new FileInputStream(schematicFile)).read();
                    clip.paste(scheditsession, to, true, true, true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // Be verbose in editsession flushing
                scheditsession.flushQueue();
            }
            editSession.flushQueue();
            FaweAPI.fixLighting(world, new CuboidRegion(plot.getBottomAbs().getBlockVector3(), plot.getTopAbs().getBlockVector3()), null, RelightMode.valueOf(com.fastasyncworldedit.core.configuration.Settings.settings().LIGHTING.MODE));
            if (whenDone != null) {
                TaskManager.taskManager().task(whenDone);
            }
        }
    });
    return true;
}
Also used : Pattern(com.sk89q.worldedit.function.pattern.Pattern) HybridPlotWorld(com.plotsquared.core.generator.HybridPlotWorld) CuboidRegion(com.sk89q.worldedit.regions.CuboidRegion) IOException(java.io.IOException) World(com.sk89q.worldedit.world.World) Bukkit.getWorld(org.bukkit.Bukkit.getWorld) HybridPlotWorld(com.plotsquared.core.generator.HybridPlotWorld) BlockVector3(com.sk89q.worldedit.math.BlockVector3) FileInputStream(java.io.FileInputStream) BiomeType(com.sk89q.worldedit.world.biome.BiomeType) BlockType(com.sk89q.worldedit.world.block.BlockType) HybridPlotManager(com.plotsquared.core.generator.HybridPlotManager) CuboidRegion(com.sk89q.worldedit.regions.CuboidRegion) Region(com.sk89q.worldedit.regions.Region) EditSession(com.sk89q.worldedit.EditSession) Clipboard(com.sk89q.worldedit.extent.clipboard.Clipboard) File(java.io.File)

Example 13 with Pattern

use of com.sk89q.worldedit.function.pattern.Pattern in project FastAsyncWorldEdit by IntellectualSites.

the class SplatterBrush method apply.

@Override
public void apply(final EditSession editSession, final LocalBlockVectorSet placed, final BlockVector3 position, Pattern p, double size) throws MaxChangedBlocksException {
    final Pattern finalPattern;
    if (solid) {
        finalPattern = p.applyBlock(position);
    } else {
        finalPattern = p;
    }
    final int size2 = (int) (size * size);
    SurfaceMask surface = new SurfaceMask(editSession);
    RecursiveVisitor visitor = new RecursiveVisitor(new SplatterBrushMask(editSession, position, size2, surface, placed), vector -> editSession.setBlock(vector, finalPattern), recursion, editSession.getMinY(), editSession.getMaxY());
    visitor.setMaxBranch(2);
    visitor.setDirections(Arrays.asList(BreadthFirstSearch.DIAGONAL_DIRECTIONS));
    visitor.visit(position);
    Operations.completeBlindly(visitor);
}
Also used : Pattern(com.sk89q.worldedit.function.pattern.Pattern) RecursiveVisitor(com.sk89q.worldedit.function.visitor.RecursiveVisitor) SplatterBrushMask(com.fastasyncworldedit.core.function.mask.SplatterBrushMask) SurfaceMask(com.fastasyncworldedit.core.function.mask.SurfaceMask)

Example 14 with Pattern

use of com.sk89q.worldedit.function.pattern.Pattern in project FastAsyncWorldEdit by IntellectualSites.

the class LayerBrush method build.

@Override
public void build(EditSession editSession, BlockVector3 position, Pattern ignore, double size) throws MaxChangedBlocksException {
    final AdjacentAnyMask adjacent = new AdjacentAnyMask(new BlockMask(editSession).add(BlockTypes.AIR, BlockTypes.CAVE_AIR, BlockTypes.VOID_AIR), editSession.getMinY(), editSession.getMaxY());
    final SolidBlockMask solid = new SolidBlockMask(editSession);
    final RadiusMask radius = new RadiusMask(0, (int) size);
    visitor = new RecursiveVisitor(new MaskIntersection(adjacent, solid, radius), funcion -> true, Integer.MAX_VALUE, editSession.getMinY(), editSession.getMaxY());
    visitor.visit(position);
    visitor.setDirections(Arrays.asList(BreadthFirstSearch.DIAGONAL_DIRECTIONS));
    Operations.completeBlindly(visitor);
    BlockVectorSet visited = visitor.getVisited();
    visitor = new RecursiveVisitor(new LayerBrushMask(editSession, visitor, layers, adjacent), pos -> {
        int depth = visitor.getDepth();
        Pattern currentPattern = layers[depth];
        return currentPattern.apply(editSession, pos, pos);
    }, layers.length - 1, editSession.getMinY(), editSession.getMaxY());
    for (BlockVector3 pos : visited) {
        visitor.visit(pos);
    }
    Operations.completeBlindly(visitor);
    visitor = null;
}
Also used : BlockVectorSet(com.fastasyncworldedit.core.math.BlockVectorSet) EditSession(com.sk89q.worldedit.EditSession) Arrays(java.util.Arrays) BlockTypes(com.sk89q.worldedit.world.block.BlockTypes) BlockVector3(com.sk89q.worldedit.math.BlockVector3) RecursiveVisitor(com.sk89q.worldedit.function.visitor.RecursiveVisitor) SolidBlockMask(com.sk89q.worldedit.function.mask.SolidBlockMask) MaxChangedBlocksException(com.sk89q.worldedit.MaxChangedBlocksException) AdjacentAnyMask(com.fastasyncworldedit.core.function.mask.AdjacentAnyMask) BlockMask(com.sk89q.worldedit.function.mask.BlockMask) RadiusMask(com.fastasyncworldedit.core.function.mask.RadiusMask) BreadthFirstSearch(com.sk89q.worldedit.function.visitor.BreadthFirstSearch) LayerBrushMask(com.fastasyncworldedit.core.function.mask.LayerBrushMask) MaskIntersection(com.sk89q.worldedit.function.mask.MaskIntersection) Brush(com.sk89q.worldedit.command.tool.brush.Brush) Operations(com.sk89q.worldedit.function.operation.Operations) BlockState(com.sk89q.worldedit.world.block.BlockState) Pattern(com.sk89q.worldedit.function.pattern.Pattern) Pattern(com.sk89q.worldedit.function.pattern.Pattern) MaskIntersection(com.sk89q.worldedit.function.mask.MaskIntersection) SolidBlockMask(com.sk89q.worldedit.function.mask.SolidBlockMask) BlockMask(com.sk89q.worldedit.function.mask.BlockMask) RadiusMask(com.fastasyncworldedit.core.function.mask.RadiusMask) LayerBrushMask(com.fastasyncworldedit.core.function.mask.LayerBrushMask) SolidBlockMask(com.sk89q.worldedit.function.mask.SolidBlockMask) RecursiveVisitor(com.sk89q.worldedit.function.visitor.RecursiveVisitor) BlockVector3(com.sk89q.worldedit.math.BlockVector3) AdjacentAnyMask(com.fastasyncworldedit.core.function.mask.AdjacentAnyMask) BlockVectorSet(com.fastasyncworldedit.core.math.BlockVectorSet)

Example 15 with Pattern

use of com.sk89q.worldedit.function.pattern.Pattern in project FastAsyncWorldEdit by IntellectualSites.

the class NoisePatternParser method parseFromInput.

@Override
protected Pattern parseFromInput(@Nonnull String[] arguments, ParserContext context) {
    if (arguments.length != 2) {
        throw new InputParseException(Caption.of("fawe.error.command.syntax", TextComponent.of(getPrefix() + "[scale][pattern] (e.g. " + getPrefix() + "[5][dirt,stone])")));
    }
    double scale = parseScale(arguments[0]);
    Pattern inner = worldEdit.getPatternFactory().parseFromInput(arguments[1], context);
    if (inner instanceof RandomPattern) {
        return new RandomPattern(new NoiseRandom(this.generatorSupplier.get(), scale), (RandomPattern) inner);
    } else if (inner instanceof BlockStateHolder) {
        // single blocks won't have any impact on how a noise behaves
        return inner;
    } else {
        throw new InputParseException(TextComponent.of("Pattern " + inner.getClass().getSimpleName() + " cannot be used with #" + this.name));
    }
}
Also used : RandomPattern(com.sk89q.worldedit.function.pattern.RandomPattern) Pattern(com.sk89q.worldedit.function.pattern.Pattern) NoiseRandom(com.fastasyncworldedit.core.math.random.NoiseRandom) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) BlockStateHolder(com.sk89q.worldedit.world.block.BlockStateHolder) RandomPattern(com.sk89q.worldedit.function.pattern.RandomPattern)

Aggregations

Pattern (com.sk89q.worldedit.function.pattern.Pattern)23 RandomPattern (com.sk89q.worldedit.function.pattern.RandomPattern)11 EditSession (com.sk89q.worldedit.EditSession)7 CuboidRegion (com.sk89q.worldedit.regions.CuboidRegion)7 Region (com.sk89q.worldedit.regions.Region)7 InputParseException (com.sk89q.worldedit.extension.input.InputParseException)6 BlockVector3 (com.sk89q.worldedit.math.BlockVector3)6 ParserContext (com.sk89q.worldedit.extension.input.ParserContext)4 World (com.sk89q.worldedit.world.World)4 IOException (java.io.IOException)4 MineData (me.untouchedodin0.privatemines.mine.data.MineData)4 File (java.io.File)3 ArrayList (java.util.ArrayList)3 Caption (com.fastasyncworldedit.core.configuration.Caption)2 MaxChangedBlocksException (com.sk89q.worldedit.MaxChangedBlocksException)2 WorldEdit (com.sk89q.worldedit.WorldEdit)2 BukkitWorld (com.sk89q.worldedit.bukkit.BukkitWorld)2 NoMatchException (com.sk89q.worldedit.extension.input.NoMatchException)2 Extent (com.sk89q.worldedit.extent.Extent)2 Clipboard (com.sk89q.worldedit.extent.clipboard.Clipboard)2