Search in sources :

Example 6 with Actor

use of com.sk89q.worldedit.extension.platform.Actor in project FastAsyncWorldEdit by IntellectualSites.

the class FabricPlatform method getConnectedUsers.

@Override
public Collection<Actor> getConnectedUsers() {
    List<Actor> users = new ArrayList<>();
    PlayerManager scm = server.getPlayerManager();
    for (ServerPlayerEntity entity : scm.getPlayerList()) {
        if (entity != null) {
            users.add(new FabricPlayer(entity));
        }
    }
    return users;
}
Also used : PlayerManager(net.minecraft.server.PlayerManager) Actor(com.sk89q.worldedit.extension.platform.Actor) ArrayList(java.util.ArrayList) ServerPlayerEntity(net.minecraft.server.network.ServerPlayerEntity)

Example 7 with Actor

use of com.sk89q.worldedit.extension.platform.Actor in project FastAsyncWorldEdit by IntellectualSites.

the class CopyPastaBrush method build.

@Override
public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException {
    Actor actor = editSession.getActor();
    if (!(actor instanceof Player)) {
        throw FaweCache.PLAYER_ONLY;
    }
    Player player = (Player) actor;
    ClipboardHolder clipboard = session.getExistingClipboard();
    if (clipboard == null) {
        Mask mask = editSession.getMask();
        if (mask == null) {
            mask = Masks.alwaysTrue();
        }
        final ResizableClipboardBuilder builder = new ResizableClipboardBuilder(editSession.getWorld());
        final int minY = position.getBlockY();
        mask = new AbstractDelegateMask(mask) {

            @Override
            public boolean test(BlockVector3 vector) {
                if (super.test(vector) && vector.getBlockY() >= minY) {
                    BaseBlock block = editSession.getFullBlock(vector);
                    if (!block.getBlockType().getMaterial().isAir()) {
                        builder.add(vector, BlockTypes.AIR.getDefaultState().toBaseBlock(), block);
                        return true;
                    }
                }
                return false;
            }
        };
        // Add origin
        mask.test(position);
        RecursiveVisitor visitor = new RecursiveVisitor(mask, new NullRegionFunction(), (int) size, editSession.getMinY(), editSession.getMaxY());
        visitor.visit(position);
        Operations.completeBlindly(visitor);
        // Build the clipboard
        Clipboard newClipboard = builder.build();
        newClipboard.setOrigin(position);
        ClipboardHolder holder = new ClipboardHolder(newClipboard);
        session.setClipboard(holder);
        int blocks = builder.size();
        player.print(Caption.of("fawe.worldedit.copy.command.copy", blocks));
    } else {
        AffineTransform transform = null;
        if (randomRotate) {
            transform = new AffineTransform();
            int rotate = 90 * ThreadLocalRandom.current().nextInt(4);
            transform = transform.rotateY(rotate);
        }
        if (autoRotate) {
            if (transform == null) {
                transform = new AffineTransform();
            }
            Location loc = player.getLocation();
            float yaw = loc.getYaw();
            float pitch = loc.getPitch();
            transform = transform.rotateY(-yaw % 360);
            transform = transform.rotateX(pitch - 90);
        }
        if (transform != null && !transform.isIdentity()) {
            clipboard.setTransform(transform);
        }
        Operation operation = clipboard.createPaste(editSession).to(position.add(0, 1, 0)).ignoreAirBlocks(true).build();
        Operations.completeLegacy(operation);
        editSession.flushQueue();
    }
}
Also used : Player(com.sk89q.worldedit.entity.Player) ClipboardHolder(com.sk89q.worldedit.session.ClipboardHolder) AbstractDelegateMask(com.fastasyncworldedit.core.function.mask.AbstractDelegateMask) Mask(com.sk89q.worldedit.function.mask.Mask) RecursiveVisitor(com.sk89q.worldedit.function.visitor.RecursiveVisitor) Operation(com.sk89q.worldedit.function.operation.Operation) BlockVector3(com.sk89q.worldedit.math.BlockVector3) BaseBlock(com.sk89q.worldedit.world.block.BaseBlock) NullRegionFunction(com.fastasyncworldedit.core.function.NullRegionFunction) Actor(com.sk89q.worldedit.extension.platform.Actor) AffineTransform(com.sk89q.worldedit.math.transform.AffineTransform) ResizableClipboardBuilder(com.fastasyncworldedit.core.extent.clipboard.ResizableClipboardBuilder) Clipboard(com.sk89q.worldedit.extent.clipboard.Clipboard) AbstractDelegateMask(com.fastasyncworldedit.core.function.mask.AbstractDelegateMask) Location(com.sk89q.worldedit.util.Location)

Example 8 with Actor

use of com.sk89q.worldedit.extension.platform.Actor in project FastAsyncWorldEdit by IntellectualSites.

the class DefaultBlockParser method parseLogic.

private BaseBlock parseLogic(String input, ParserContext context) throws InputParseException {
    // FAWE start
    String[] blockAndExtraData = input.trim().split("\\|", 2);
    blockAndExtraData[0] = woolMapper(blockAndExtraData[0]);
    Map<Property<?>, Object> blockStates = new HashMap<>();
    // FAWE end
    BlockState state = null;
    // Legacy matcher
    if (context.isTryingLegacy()) {
        try {
            String[] split = blockAndExtraData[0].split(":", 2);
            if (split.length == 0) {
                throw new InputParseException(Caption.of("worldedit.error.parser.invalid-colon"));
            } else if (split.length == 1) {
                state = LegacyMapper.getInstance().getBlockFromLegacy(Integer.parseInt(split[0]));
            } else if (MathMan.isInteger(split[0])) {
                int id = Integer.parseInt(split[0]);
                int data = Integer.parseInt(split[1]);
                // FAWE start
                if (data < 0 || data >= 16) {
                    throw new InputParseException(Caption.of("fawe.error.parser.invalid-data", TextComponent.of(data)));
                }
                state = LegacyMapper.getInstance().getBlockFromLegacy(id, data);
            } else {
                BlockType type = BlockTypes.get(split[0].toLowerCase(Locale.ROOT));
                if (type != null) {
                    int data = Integer.parseInt(split[1]);
                    if (data < 0 || data >= 16) {
                        throw new InputParseException(Caption.of("fawe.error.parser.invalid-data", TextComponent.of(data)));
                    }
                    state = LegacyMapper.getInstance().getBlockFromLegacy(type.getLegacyCombinedId() >> 4, data);
                }
            }
        } catch (NumberFormatException ignored) {
        }
    }
    CompoundTag nbt = null;
    // FAWE end
    if (state == null) {
        String typeString;
        String stateString = null;
        int stateStart = blockAndExtraData[0].indexOf('[');
        if (stateStart == -1) {
            typeString = blockAndExtraData[0];
        } else {
            typeString = blockAndExtraData[0].substring(0, stateStart);
            if (stateStart + 1 >= blockAndExtraData[0].length()) {
                throw new InputParseException(Caption.of("worldedit.error.parser.hanging-lbracket", TextComponent.of(stateStart)));
            }
            int stateEnd = blockAndExtraData[0].lastIndexOf(']');
            if (stateEnd < 0) {
                throw new InputParseException(Caption.of("worldedit.error.parser.missing-rbracket"));
            }
            stateString = blockAndExtraData[0].substring(stateStart + 1, blockAndExtraData[0].length() - 1);
        }
        String[] stateProperties = EMPTY_STRING_ARRAY;
        if (stateString != null) {
            stateProperties = stateString.split(",");
        }
        if (typeString.isEmpty()) {
            throw new InputParseException(Caption.of("worldedit.error.parser.bad-state-format", TextComponent.of(blockAndExtraData[0])));
        }
        if ("hand".equalsIgnoreCase(typeString)) {
            // Get the block type from the item in the user's hand.
            final BaseBlock blockInHand = getBlockInHand(context.requireActor(), HandSide.MAIN_HAND);
            // FAWE start
            state = blockInHand.toBlockState();
            nbt = blockInHand.getNbtData();
        // FAWE end
        } else if ("offhand".equalsIgnoreCase(typeString)) {
            // Get the block type from the item in the user's off hand.
            final BaseBlock blockInHand = getBlockInHand(context.requireActor(), HandSide.OFF_HAND);
            // FAWE start
            state = blockInHand.toBlockState();
            nbt = blockInHand.getNbtData();
        // FAWE end
        } else if (typeString.matches("pos[0-9]+")) {
            int index = Integer.parseInt(typeString.replaceAll("[a-z]+", ""));
            // Get the block type from the "primary position"
            final World world = context.requireWorld();
            final BlockVector3 primaryPosition;
            try {
                primaryPosition = context.requireSession().getRegionSelector(world).getVertices().get(index - 1);
            } catch (IncompleteRegionException e) {
                throw new InputParseException(Caption.of("worldedit.error.incomplete-region"));
            }
            state = world.getBlock(primaryPosition);
            nbt = state.getNbtData();
        // FAWE start
        } else if (typeString.matches("slot[0-9]+")) {
            int slot = Integer.parseInt(typeString.substring(4)) - 1;
            Actor actor = context.requireActor();
            if (!(actor instanceof Player)) {
                throw new InputParseException(Caption.of("worldedit.command.player-only"));
            }
            Player player = (Player) actor;
            BlockBag bag = player.getInventoryBlockBag();
            if (!(bag instanceof SlottableBlockBag)) {
                throw new InputParseException(Caption.of("fawe.error.unsupported"));
            }
            SlottableBlockBag slottable = (SlottableBlockBag) bag;
            BaseItem item = slottable.getItem(slot);
            if (!item.getType().hasBlockType()) {
                throw new InputParseException(Caption.of("worldedit.error.not-a-block"));
            }
            state = item.getType().getBlockType().getDefaultState();
            nbt = item.getNbtData();
        } else {
            BlockType type = BlockTypes.parse(typeString.toLowerCase(Locale.ROOT));
            if (type != null) {
                state = type.getDefaultState();
            }
            if (state == null) {
                throw new NoMatchException(Caption.of("fawe.error.invalid-block-type", TextComponent.of(input)));
            }
        }
        // FAWE end
        // FAWE start -  Not null if nullNotError false.
        blockStates.putAll(parseProperties(state.getBlockType(), stateProperties, context, false));
        // FAWE end
        if (context.isPreferringWildcard()) {
            if (stateString == null || stateString.isEmpty()) {
                state = new FuzzyBlockState(state);
            } else {
                FuzzyBlockState.Builder fuzzyBuilder = FuzzyBlockState.builder();
                fuzzyBuilder.type(state.getBlockType());
                for (Map.Entry<Property<?>, Object> blockState : blockStates.entrySet()) {
                    @SuppressWarnings("unchecked") Property<Object> objProp = (Property<Object>) blockState.getKey();
                    fuzzyBuilder.withProperty(objProp, blockState.getValue());
                }
                state = fuzzyBuilder.build();
            }
        } else {
            for (Map.Entry<Property<?>, Object> blockState : blockStates.entrySet()) {
                @SuppressWarnings("unchecked") Property<Object> objProp = (Property<Object>) blockState.getKey();
                state = state.with(objProp, blockState.getValue());
            }
        }
    }
    // this should be impossible but IntelliJ isn't that smart
    if (state == null) {
        throw new NoMatchException(Caption.of("worldedit.error.unknown-block", TextComponent.of(input)));
    }
    // FAWE start
    if (blockAndExtraData.length > 1 && blockAndExtraData[1].startsWith("{")) {
        String joined = StringMan.join(Arrays.copyOfRange(blockAndExtraData, 1, blockAndExtraData.length), "|");
        try {
            nbt = JSON2NBT.getTagFromJson(joined);
        } catch (NBTException e) {
            throw new NoMatchException(TextComponent.of(e.getMessage()));
        }
    }
    // FAWE end
    // Check if the item is allowed
    BlockType blockType = state.getBlockType();
    if (context.isRestricted()) {
        Actor actor = context.requireActor();
        // FAWE start - per-limit disallowed blocks
        if (actor != null) {
            if (!actor.hasPermission("worldedit.anyblock") && worldEdit.getConfiguration().disallowedBlocks.contains(blockType.getId().toLowerCase(Locale.ROOT))) {
                throw new DisallowedUsageException(Caption.of("worldedit.error.disallowed-block", TextComponent.of(blockType.getId())));
            }
            FaweLimit limit = actor.getLimit();
            if (!limit.isUnlimited()) {
                // during contains.
                if (limit.DISALLOWED_BLOCKS.contains(blockType.getId().toLowerCase(Locale.ROOT))) {
                    throw new DisallowedUsageException(Caption.of("fawe.error.limit.disallowed-block", TextComponent.of(blockType.getId())));
                }
            }
        }
    // FAWE end
    }
    if (nbt != null) {
        BaseBlock result = blockStates.size() > 0 ? state.toBaseBlock(nbt) : new BlanketBaseBlock(state, nbt);
        return validate(context, result);
    }
    if (blockType == BlockTypes.SIGN || blockType == BlockTypes.WALL_SIGN || BlockCategories.SIGNS.contains(blockType)) {
        // Allow special sign text syntax
        String[] text = new String[4];
        text[0] = blockAndExtraData.length > 1 ? blockAndExtraData[1] : "";
        text[1] = blockAndExtraData.length > 2 ? blockAndExtraData[2] : "";
        text[2] = blockAndExtraData.length > 3 ? blockAndExtraData[3] : "";
        text[3] = blockAndExtraData.length > 4 ? blockAndExtraData[4] : "";
        return validate(context, new SignBlock(state, text));
    } else if (blockType == BlockTypes.SPAWNER) {
        // Allow setting mob spawn type
        if (blockAndExtraData.length > 1) {
            String mobName = blockAndExtraData[1];
            EntityType ent = EntityTypes.get(mobName.toLowerCase(Locale.ROOT));
            if (ent == null) {
                throw new NoMatchException(Caption.of("worldedit.error.unknown-entity", TextComponent.of(mobName)));
            }
            mobName = ent.getId();
            if (!worldEdit.getPlatformManager().queryCapability(Capability.USER_COMMANDS).isValidMobType(mobName)) {
                throw new NoMatchException(Caption.of("worldedit.error.unknown-mob", TextComponent.of(mobName)));
            }
            return validate(context, new MobSpawnerBlock(state, mobName));
        } else {
            // noinspection ConstantConditions
            return validate(context, new MobSpawnerBlock(state, EntityTypes.PIG.getId()));
        }
    } else if (blockType == BlockTypes.PLAYER_HEAD || blockType == BlockTypes.PLAYER_WALL_HEAD) {
        // allow setting type/player/rotation
        if (blockAndExtraData.length <= 1) {
            return validate(context, new SkullBlock(state));
        }
        String type = blockAndExtraData[1];
        // valid MC usernames
        return validate(context, new SkullBlock(state, type.replace(" ", "_")));
    } else {
        // FAWE start
        nbt = state.getNbtData();
        BaseBlock result;
        if (nbt != null) {
            result = blockStates.size() > 0 ? state.toBaseBlock(nbt) : new BlanketBaseBlock(state, nbt);
        } else {
            result = blockStates.size() > 0 ? new BaseBlock(state) : state.toBaseBlock();
        }
        return validate(context, result);
    // FAWE end
    }
}
Also used : SkullBlock(com.sk89q.worldedit.blocks.SkullBlock) HashMap(java.util.HashMap) SignBlock(com.sk89q.worldedit.blocks.SignBlock) IncompleteRegionException(com.sk89q.worldedit.IncompleteRegionException) World(com.sk89q.worldedit.world.World) BlanketBaseBlock(com.fastasyncworldedit.core.world.block.BlanketBaseBlock) BaseBlock(com.sk89q.worldedit.world.block.BaseBlock) BlanketBaseBlock(com.fastasyncworldedit.core.world.block.BlanketBaseBlock) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) FaweLimit(com.fastasyncworldedit.core.limit.FaweLimit) MobSpawnerBlock(com.sk89q.worldedit.blocks.MobSpawnerBlock) Actor(com.sk89q.worldedit.extension.platform.Actor) Property(com.sk89q.worldedit.registry.state.Property) BaseItem(com.sk89q.worldedit.blocks.BaseItem) CompoundTag(com.sk89q.jnbt.CompoundTag) Player(com.sk89q.worldedit.entity.Player) BlockBag(com.sk89q.worldedit.extent.inventory.BlockBag) SlottableBlockBag(com.fastasyncworldedit.core.extent.inventory.SlottableBlockBag) FuzzyBlockState(com.sk89q.worldedit.world.block.FuzzyBlockState) BlockVector3(com.sk89q.worldedit.math.BlockVector3) EntityType(com.sk89q.worldedit.world.entity.EntityType) DisallowedUsageException(com.sk89q.worldedit.extension.input.DisallowedUsageException) FuzzyBlockState(com.sk89q.worldedit.world.block.FuzzyBlockState) BlockState(com.sk89q.worldedit.world.block.BlockState) BlockType(com.sk89q.worldedit.world.block.BlockType) SlottableBlockBag(com.fastasyncworldedit.core.extent.inventory.SlottableBlockBag) NoMatchException(com.sk89q.worldedit.extension.input.NoMatchException) Map(java.util.Map) HashMap(java.util.HashMap) NBTException(com.fastasyncworldedit.core.jnbt.NBTException)

Example 9 with Actor

use of com.sk89q.worldedit.extension.platform.Actor in project FastAsyncWorldEdit by IntellectualSites.

the class CommandLoggingHandler method beforeCall.

@Override
public void beforeCall(Method method, CommandParameters parameters) {
    Logging loggingAnnotation = method.getAnnotation(Logging.class);
    Logging.LogMode logMode;
    StringBuilder builder = new StringBuilder();
    if (loggingAnnotation == null) {
        logMode = null;
    } else {
        logMode = loggingAnnotation.value();
    }
    Optional<Actor> actorOpt = parameters.injectedValue(Key.of(Actor.class));
    if (!actorOpt.isPresent()) {
        return;
    }
    Actor actor = actorOpt.get();
    World world;
    try {
        Optional<World> worldOpt = parameters.injectedValue(Key.of(World.class));
        if (!worldOpt.isPresent()) {
            return;
        }
        world = worldOpt.get();
    } catch (CommandException ex) {
        return;
    }
    builder.append("WorldEdit: ").append(actor.getName());
    builder.append(" (in \"").append(world.getName()).append("\")");
    builder.append(": ").append(parameters.getMetadata().getCalledName());
    builder.append(": ").append(Stream.concat(Stream.of(parameters.getMetadata().getCalledName()), parameters.getMetadata().getArguments().stream()).collect(Collectors.joining(" ")));
    if (logMode != null && actor instanceof Player) {
        Player player = (Player) actor;
        Vector3 position = player.getLocation().toVector();
        LocalSession session = worldEdit.getSessionManager().get(actor);
        switch(logMode) {
            case PLACEMENT:
                try {
                    position = session.getPlacementPosition(actor).toVector3();
                } catch (IncompleteRegionException e) {
                    break;
                }
            case POSITION:
                builder.append(" - Position: ").append(position);
                break;
            case ALL:
                builder.append(" - Position: ").append(position);
            case ORIENTATION_REGION:
                builder.append(" - Orientation: ").append(player.getCardinalDirection().name());
            case REGION:
                try {
                    builder.append(" - Region: ").append(session.getSelection(world));
                } catch (IncompleteRegionException e) {
                    break;
                }
                break;
        }
    }
    logger.info(builder.toString());
}
Also used : Logging(com.sk89q.worldedit.command.util.Logging) Player(com.sk89q.worldedit.entity.Player) Actor(com.sk89q.worldedit.extension.platform.Actor) LocalSession(com.sk89q.worldedit.LocalSession) IncompleteRegionException(com.sk89q.worldedit.IncompleteRegionException) Vector3(com.sk89q.worldedit.math.Vector3) CommandException(org.enginehub.piston.exception.CommandException) World(com.sk89q.worldedit.world.World)

Example 10 with Actor

use of com.sk89q.worldedit.extension.platform.Actor 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)

Aggregations

Actor (com.sk89q.worldedit.extension.platform.Actor)25 World (com.sk89q.worldedit.world.World)10 List (java.util.List)8 Player (com.sk89q.worldedit.entity.Player)6 BlockVector3 (com.sk89q.worldedit.math.BlockVector3)6 Subscribe (com.sk89q.worldedit.util.eventbus.Subscribe)6 ArrayList (java.util.ArrayList)6 WorldEdit (com.sk89q.worldedit.WorldEdit)5 Location (com.sk89q.worldedit.util.Location)5 TextComponent (com.sk89q.worldedit.util.formatting.text.TextComponent)5 Collectors (java.util.stream.Collectors)5 Caption (com.fastasyncworldedit.core.configuration.Caption)4 LocalSession (com.sk89q.worldedit.LocalSession)4 InputParseException (com.sk89q.worldedit.extension.input.InputParseException)4 Capability (com.sk89q.worldedit.extension.platform.Capability)4 Locatable (com.sk89q.worldedit.extension.platform.Locatable)4 Mask (com.sk89q.worldedit.function.mask.Mask)4 ResettableExtent (com.fastasyncworldedit.core.extent.ResettableExtent)3 NoMatchException (com.sk89q.worldedit.extension.input.NoMatchException)3 Region (com.sk89q.worldedit.regions.Region)3