com.sk89q.worldedit.function.operation.Operations Java Examples

The following examples show how to use com.sk89q.worldedit.function.operation.Operations. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SchematicHelper.java    From FunnyGuilds with Apache License 2.0 8 votes vote down vote up
public static boolean pasteSchematic(File schematicFile, Location location, boolean withAir) {
    try {
        Vector pasteLocation = new Vector(location.getX(), location.getY(), location.getZ());
        World pasteWorld = new BukkitWorld(location.getWorld());
        WorldData pasteWorldData = pasteWorld.getWorldData();

        Clipboard clipboard = ClipboardFormat.SCHEMATIC.getReader(new FileInputStream(schematicFile)).read(pasteWorldData);
        ClipboardHolder clipboardHolder = new ClipboardHolder(clipboard, pasteWorldData);

        EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(pasteWorld, -1);

        Operation operation = clipboardHolder
                .createPaste(editSession, pasteWorldData)
                .to(pasteLocation)
                .ignoreAirBlocks(!withAir)
                .build();

        Operations.completeLegacy(operation);
        return true;
    }
    catch (IOException | MaxChangedBlocksException e) {
        FunnyGuilds.getInstance().getPluginLogger().error("Could not paste schematic: " + schematicFile.getAbsolutePath(), e);
        return false;
    }
}
 
Example #2
Source File: Schematic.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
public void paste(Extent extent, WorldData worldData, Vector to, boolean pasteAir, Transform transform) {
    checkNotNull(transform);
    Region region = clipboard.getRegion();
    Extent source = clipboard;
    if (worldData != null && transform != null) {
        source = new BlockTransformExtent(clipboard, transform, worldData.getBlockRegistry());
    }
    ForwardExtentCopy copy = new ForwardExtentCopy(source, clipboard.getRegion(), clipboard.getOrigin(), extent, to);
    if (transform != null) {
        copy.setTransform(transform);
    }
    copy.setCopyBiomes(!(clipboard instanceof BlockArrayClipboard) || ((BlockArrayClipboard) clipboard).IMP.hasBiomes());
    if (extent instanceof EditSession) {
        EditSession editSession = (EditSession) extent;
        Mask sourceMask = editSession.getSourceMask();
        if (sourceMask != null) {
            new MaskTraverser(sourceMask).reset(extent);
            copy.setSourceMask(sourceMask);
            editSession.setSourceMask(null);
        }
    }
    if (!pasteAir) {
        copy.setSourceMask(new ExistingBlockMask(clipboard));
    }
    Operations.completeBlindly(copy);
}
 
Example #3
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Fills an area recursively in the X/Z directions.
 *
 * @param origin    the location to start from
 * @param pattern     the block to fill with
 * @param radius    the radius of the spherical area to fill
 * @param depth     the maximum depth, starting from the origin
 * @param direction the direction to fill
 * @return number of blocks affected
 * @throws MaxChangedBlocksException thrown if too many blocks are changed
 */
public int fillDirection(final Vector origin, final Pattern pattern, final double radius, final int depth, Vector direction) {
    checkNotNull(origin);
    checkNotNull(pattern);
    checkArgument(radius >= 0, "radius >= 0");
    checkArgument(depth >= 1, "depth >= 1");
    if (direction.equals(new Vector(0, -1, 0))) {
        return fillXZ(origin, pattern, radius, depth, false);
    }
    final MaskIntersection mask = new MaskIntersection(new RegionMask(new EllipsoidRegion(null, origin, new Vector(radius, radius, radius))), Masks.negate(new ExistingBlockMask(EditSession.this)));

    // Want to replace blocks
    final BlockReplace replace = new BlockReplace(EditSession.this, pattern);

    // Pick how we're going to visit blocks
    RecursiveVisitor visitor = new DirectionalVisitor(mask, replace, origin, direction, (int) (radius * 2 + 1), this);

    // Start at the origin
    visitor.visit(origin);

    // Execute
    Operations.completeBlindly(visitor);
    return this.changes = visitor.getAffected();
}
 
Example #4
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sets all the blocks inside a region to a given block type.
 *
 * @param region the region
 * @param block  the block
 * @return number of blocks affected
 * @throws MaxChangedBlocksException thrown if too many blocks are changed
 */
@SuppressWarnings("deprecation")
public int setBlocks(final Region region, final BaseBlock block) {
    checkNotNull(region);
    checkNotNull(block);
    if (canBypassAll(region, false, true) && !block.hasNbtData()) {
        return changes = queue.setBlocks((CuboidRegion) region, block.getId(), block.getData());
    }
    try {
        if (hasExtraExtents()) {
            RegionVisitor visitor = new RegionVisitor(region, new BlockReplace(extent, (block)), this);
            Operations.completeBlindly(visitor);
            this.changes += visitor.getAffected();
        } else {
            Iterator<BlockVector> iter = region.iterator();
            while (iter.hasNext()) {
                if (this.extent.setBlock(iter.next(), block)) {
                    changes++;
                }
            }
        }
    } catch (final WorldEditException e) {
        throw new RuntimeException("Unexpected exception", e);
    }
    return changes;
}
 
Example #5
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sets all the blocks inside a region to a given pattern.
 *
 * @param region  the region
 * @param pattern the pattern that provides the replacement block
 * @return number of blocks affected
 * @throws MaxChangedBlocksException thrown if too many blocks are changed
 */
@SuppressWarnings("deprecation")
public int setBlocks(final Region region, final Pattern pattern) {
    checkNotNull(region);
    checkNotNull(pattern);
    if (pattern instanceof BlockPattern) {
        return setBlocks(region, ((BlockPattern) pattern).getBlock());
    }
    if (pattern instanceof BaseBlock) {
        return setBlocks(region, (BaseBlock) pattern);
    }
    final BlockReplace replace = new BlockReplace(EditSession.this, pattern);
    final RegionVisitor visitor = new RegionVisitor(region, replace, queue instanceof MappedFaweQueue ? (MappedFaweQueue) queue : null);
    Operations.completeBlindly(visitor);
    return this.changes = visitor.getAffected();
}
 
Example #6
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Stack a cuboid region.
 *
 * @param region  the region to stack
 * @param dir     the direction to stack
 * @param count   the number of times to stack
 * @param copyAir true to also copy air blocks
 * @return number of blocks affected
 * @throws MaxChangedBlocksException thrown if too many blocks are changed
 */
public int stackCuboidRegion(final Region region, final Vector dir, final int count, final boolean copyAir, boolean copyEntities, boolean copyBiomes) {
    checkNotNull(region);
    checkNotNull(dir);
    checkArgument(count >= 1, "count >= 1 required");
    final Vector size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1);
    final Vector to = region.getMinimumPoint();
    final ForwardExtentCopy copy = new ForwardExtentCopy(EditSession.this, region, EditSession.this, to);
    copy.setCopyEntities(copyEntities);
    copy.setCopyBiomes(copyBiomes);
    copy.setRepetitions(count);
    copy.setTransform(new AffineTransform().translate(dir.multiply(size)));
    Mask sourceMask = getSourceMask();
    if (sourceMask != null) {
        new MaskTraverser(sourceMask).reset(EditSession.this);
        copy.setSourceMask(sourceMask);
        setSourceMask(null);
    }
    if (!copyAir) {
        copy.setSourceMask(new ExistingBlockMask(EditSession.this));
    }
    Operations.completeBlindly(copy);
    return this.changes = copy.getAffected();
}
 
Example #7
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Makes pumpkin patches randomly in an area around the given position.
 *
 * @param position the base position
 * @param apothem  the apothem of the (square) area
 * @return number of patches created
 * @throws MaxChangedBlocksException thrown if too many blocks are changed
 */
public int makePumpkinPatches(final Vector position, final int apothem) {
    // We want to generate pumpkins
    final GardenPatchGenerator generator = new GardenPatchGenerator(EditSession.this);
    generator.setPlant(GardenPatchGenerator.getPumpkinPattern());

    // In a region of the given radius
    final FlatRegion region = new CuboidRegion(EditSession.this.getWorld(), // Causes clamping of Y range
            position.add(-apothem, -5, -apothem), position.add(apothem, 10, apothem));
    final double density = 0.02;

    final GroundFunction ground = new GroundFunction(new ExistingBlockMask(EditSession.this), generator);
    final LayerVisitor visitor = new LayerVisitor(region, minimumBlockY(region), maximumBlockY(region), ground);
    visitor.setMask(new NoiseFilter2D(new RandomNoise(), density));
    Operations.completeBlindly(visitor);
    return this.changes = ground.getAffected();
}
 
Example #8
Source File: RegionCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
@Command(
        aliases = {"/forest"},
        usage = "[type] [density]",
        desc = "Make a forest within the region",
        min = 0,
        max = 2
)
@CommandPermissions("worldedit.region.forest")
@Logging(REGION)
public void forest(FawePlayer player, EditSession editSession, @Selection Region region, @Optional("tree") TreeType type,
                   @Optional("5") @Range(min = 0, max = 100) double density,
                   CommandContext context) throws WorldEditException {
    player.checkConfirmationRegion(() -> {
        ForestGenerator generator = new ForestGenerator(editSession, new TreeGenerator(type));
        GroundFunction ground = new GroundFunction(new ExistingBlockMask(editSession), generator);
        LayerVisitor visitor = new LayerVisitor(asFlatRegion(region), minimumBlockY(region), maximumBlockY(region), ground);
        visitor.setMask(new NoiseFilter2D(new RandomNoise(), density / 100));
        Operations.completeLegacy(visitor);

        BBC.COMMAND_TREE.send(player, ground.getAffected());
    }, getArguments(context), region, context);
}
 
Example #9
Source File: RegionCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
@Command(
        aliases = {"/flora"},
        usage = "[density]",
        desc = "Make flora within the region",
        min = 0,
        max = 1
)
@CommandPermissions("worldedit.region.flora")
@Logging(REGION)
public void flora(FawePlayer player, EditSession editSession, @Selection Region region, @Optional("10") @Range(min = 0, max = 100) double density, CommandContext context) throws WorldEditException {
    player.checkConfirmationRegion(() -> {
        FloraGenerator generator = new FloraGenerator(editSession);
        GroundFunction ground = new GroundFunction(new ExistingBlockMask(editSession), generator);
        LayerVisitor visitor = new LayerVisitor(asFlatRegion(region), minimumBlockY(region), maximumBlockY(region), ground);
        visitor.setMask(new NoiseFilter2D(new RandomNoise(), density / 100));
        Operations.completeLegacy(visitor);

        BBC.COMMAND_FLORA.send(player, ground.getAffected());
    }, getArguments(context), region, context);
}
 
Example #10
Source File: DefaultFloorRegenerator.java    From HeavySpleef with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void regenerate(Floor floor, EditSession session, RegenerationCause cause) {
	Clipboard clipboard = floor.getClipboard();
	
	Region region = clipboard.getRegion();
	World world = region.getWorld();
	WorldData data = world.getWorldData();
	
	ClipboardHolder holder = new ClipboardHolder(clipboard, data);
	
	Operation pasteOperation = holder.createPaste(session, data)
			.to(region.getMinimumPoint())
			.ignoreAirBlocks(true)
			.build();
	
	try {
		Operations.complete(pasteOperation);
	} catch (WorldEditException e) {
		throw new RuntimeException(e);
	}
}
 
Example #11
Source File: FaweChunkManager.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean copyRegion(final Location pos1, final Location pos2, final Location pos3, final Runnable whenDone) {
    TaskManager.IMP.async(new Runnable() {
        @Override
        public void run() {
            synchronized (FaweChunkManager.class) {
                EditSession from = new EditSessionBuilder(pos1.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build();
                EditSession to = new EditSessionBuilder(pos3.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build();
                CuboidRegion region = new CuboidRegion(new Vector(pos1.getX(), pos1.getY(), pos1.getZ()), new Vector(pos2.getX(), pos2.getY(), pos2.getZ()));
                ForwardExtentCopy copy = new ForwardExtentCopy(from, region, to, new Vector(pos3.getX(), pos3.getY(), pos3.getZ()));
                try {
                    Operations.completeLegacy(copy);
                    to.flushQueue();
                } catch (MaxChangedBlocksException e) {
                    e.printStackTrace();
                }
            }
            TaskManager.IMP.task(whenDone);
        }
    });
    return true;
}
 
Example #12
Source File: FaweChunkManager.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void swap(final Location pos1, final Location pos2, final Location pos3, final Location pos4, final Runnable whenDone) {
    TaskManager.IMP.async(new Runnable() {
        @Override
        public void run() {
            synchronized (FaweChunkManager.class) {
                EditSession sessionA = new EditSessionBuilder(pos1.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build();
                EditSession sessionB = new EditSessionBuilder(pos3.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build();
                CuboidRegion regionA = new CuboidRegion(new Vector(pos1.getX(), pos1.getY(), pos1.getZ()), new Vector(pos2.getX(), pos2.getY(), pos2.getZ()));
                CuboidRegion regionB = new CuboidRegion(new Vector(pos3.getX(), pos3.getY(), pos3.getZ()), new Vector(pos4.getX(), pos4.getY(), pos4.getZ()));
                ForwardExtentCopy copyA = new ForwardExtentCopy(sessionA, regionA, sessionB, regionB.getMinimumPoint());
                ForwardExtentCopy copyB = new ForwardExtentCopy(sessionB, regionB, sessionA, regionA.getMinimumPoint());
                try {
                    Operations.completeLegacy(copyA);
                    Operations.completeLegacy(copyB);
                    sessionA.flushQueue();
                    sessionB.flushQueue();
                } catch (MaxChangedBlocksException e) {
                    e.printStackTrace();
                }
                TaskManager.IMP.task(whenDone);
            }
        }
    });
}
 
Example #13
Source File: SimpleClipboardFloor.java    From HeavySpleef with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Deprecated
public void generate(EditSession session) {
	Region region = floorClipboard.getRegion();
	World world = region.getWorld();
	WorldData data = world.getWorldData();
	
	ClipboardHolder holder = new ClipboardHolder(floorClipboard, data);
	
	Operation pasteOperation = holder.createPaste(session, data)
			.to(region.getMinimumPoint())
			.ignoreAirBlocks(true)
			.build();
	
	try {
		Operations.complete(pasteOperation);
	} catch (WorldEditException e) {
		throw new RuntimeException(e);
	}
}
 
Example #14
Source File: WorldEditHandler.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
public static void loadIslandSchematic(final File file, final Location origin, PlayerPerk playerPerk) {
    log.finer("Trying to load schematic " + file);
    if (file == null || !file.exists() || !file.canRead()) {
        LogUtil.log(Level.WARNING, "Unable to load schematic " + file);
    }
    boolean noAir = false;
    BlockVector3 to = BlockVector3.at(origin.getBlockX(), origin.getBlockY(), origin.getBlockZ());
    EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(new BukkitWorld(origin.getWorld()), -1);
    editSession.setFastMode(true);
    ProtectedRegion region = WorldGuardHandler.getIslandRegionAt(origin);
    if (region != null) {
        editSession.setMask(new RegionMask(getRegion(origin.getWorld(), region)));
    }
    try {
        ClipboardFormat clipboardFormat = ClipboardFormats.findByFile(file);
        try (InputStream in = new FileInputStream(file)) {
            Clipboard clipboard = clipboardFormat.getReader(in).read();
            Operation operation = new ClipboardHolder(clipboard)
                    .createPaste(editSession)
                    .to(to)
                    .ignoreAirBlocks(noAir)
                    .build();
            Operations.completeBlindly(operation);
        }
        editSession.flushSession();
    } catch (IOException e) {
        log.log(Level.INFO, "Unable to paste schematic " + file, e);
    }
}
 
Example #15
Source File: RecursivePickaxe.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) {
    World world = (World) clicked.getExtent();
    final Vector pos = clicked.toVector();

    EditSession editSession = session.createEditSession(player);

    BaseBlock block = editSession.getBlock(pos);
    int initialType = block.getType();

    if (initialType == BlockID.AIR || (initialType == BlockID.BEDROCK && !player.canDestroyBedrock())) {
        editSession.flushQueue();
        return true;
    }

    editSession.getSurvivalExtent().setToolUse(config.superPickaxeManyDrop);

    final int radius = (int) range;
    final BlockReplace replace = new BlockReplace(editSession, (editSession.nullBlock));
    editSession.setMask((Mask) null);
    RecursiveVisitor visitor = new RecursiveVisitor(new IdMask(editSession), replace, radius, editSession);
    visitor.visit(pos);
    Operations.completeBlindly(visitor);

    editSession.flushQueue();
    session.remember(editSession);

    return true;
}
 
Example #16
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
public int deformRegion(final Region region, final Vector zero, final Vector unit, final String expressionString) throws ExpressionException, MaxChangedBlocksException {
    final Expression expression = Expression.compile(expressionString, "x", "y", "z");
    expression.optimize();
    final RValue x = expression.getVariable("x", false).optimize();
    final RValue y = expression.getVariable("y", false).optimize();
    final RValue z = expression.getVariable("z", false).optimize();
    final WorldEditExpressionEnvironment environment = new WorldEditExpressionEnvironment(this, unit, zero);
    expression.setEnvironment(environment);
    final Vector zero2 = zero.add(0.5, 0.5, 0.5);

    RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() {

        private MutableBlockVector mutable = new MutableBlockVector();

        @Override
        public boolean apply(Vector position) throws WorldEditException {
            try {
                // offset, scale
                double sx = (position.getX() - zero.getX()) / unit.getX();
                double sy = (position.getY() - zero.getY()) / unit.getY();
                double sz = (position.getZ() - zero.getZ()) / unit.getZ();
                // transform
                expression.evaluate(sx, sy, sz);
                int xv = (int) (x.getValue() * unit.getX() + zero2.getX());
                int yv = (int) (y.getValue() * unit.getY() + zero2.getY());
                int zv = (int) (z.getValue() * unit.getZ() + zero2.getZ());
                // read block from world
                BaseBlock material = FaweCache.CACHE_BLOCK[queue.getCombinedId4DataDebug(xv, yv, zv, 0, EditSession.this)];
                // queue operation
                return setBlockFast(position, material);
            } catch (EvaluationException e) {
                throw new RuntimeException(e);
            }
        }
    }, this);
    Operations.completeBlindly(visitor);
    changes += visitor.getAffected();
    return changes;
}
 
Example #17
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Count the number of blocks of a list of types in a region.
 *
 * @param region       the region
 * @param searchBlocks the list of blocks to search
 * @return the number of blocks that matched the pattern
 */
public int countBlocks(final Region region, final Set<BaseBlock> searchBlocks) {
    final BlockMask mask = new BlockMask(extent, searchBlocks);
    RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() {
        @Override
        public boolean apply(Vector position) throws WorldEditException {
            return mask.test(position);
        }
    }, this);
    Operations.completeBlindly(visitor);
    return visitor.getAffected();
}
 
Example #18
Source File: PasteSchematicEvent.java    From BetonQuest with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Void execute(String playerID) throws QuestRuntimeException {
    try {
        Location location = loc.getLocation(playerID);
        ClipboardFormat format = ClipboardFormats.findByFile(file);
        if (format == null) {
            throw new IOException("Unknown Schematic Format");
        }

        Clipboard clipboard;
        try (ClipboardReader reader = format.getReader(new FileInputStream(file))) {
            clipboard = reader.read();
        }


        try (EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(BukkitAdapter.adapt(location.getWorld()), -1)) {
            Operation operation = new ClipboardHolder(clipboard)
                    .createPaste(editSession)
                    .to(BukkitAdapter.asBlockVector(location))
                    .ignoreAirBlocks(noAir)
                    .build();

            Operations.complete(operation);
        }
    } catch (IOException | WorldEditException e) {
        LogUtils.getLogger().log(Level.WARNING, "Error while pasting a schematic: " + e.getMessage());
        LogUtils.logThrowable(e);
    }
    return null;
}
 
Example #19
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
     * Drain nearby pools of water or lava.
     *
     * @param origin the origin to drain from, which will search a 3x3 area
     * @param radius the radius of the removal, where a value should be 0 or greater
     * @return number of blocks affected
     * @throws MaxChangedBlocksException thrown if too many blocks are changed
     */
    public int drainArea(final Vector origin, final double radius) {
        checkNotNull(origin);
        checkArgument(radius >= 0, "radius >= 0 required");
        Mask liquidMask;
        // Not thread safe, use hardcoded liquidmask
//        if (getWorld() != null) {
//            liquidMask = getWorld().createLiquidMask();
//        } else {
        liquidMask = new BlockMask(this,
                new BaseBlock(BlockID.STATIONARY_LAVA, -1),
                new BaseBlock(BlockID.LAVA, -1),
                new BaseBlock(BlockID.STATIONARY_WATER, -1),
                new BaseBlock(BlockID.WATER, -1));
//        }
        final MaskIntersection mask = new MaskIntersection(
                new BoundedHeightMask(0, EditSession.this.getMaximumPoint().getBlockY()),
                new RegionMask(
                        new EllipsoidRegion(null, origin,
                                new Vector(radius, radius, radius))), liquidMask);

        final BlockReplace replace = new BlockReplace(EditSession.this, new BaseBlock(BlockID.AIR));
        final RecursiveVisitor visitor = new RecursiveVisitor(mask, replace, (int) (radius * 2 + 1), this);

        // Around the origin in a 3x3 block
        for (final BlockVector position : CuboidRegion.fromCenter(origin, 1)) {
            if (mask.test(position)) {
                visitor.visit(position);
            }
        }

        Operations.completeBlindly(visitor);
        return this.changes = visitor.getAffected();
    }
 
Example #20
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
public int moveRegion(final Region region, final Vector dir, final int distance, final boolean copyAir, final boolean copyEntities, final boolean copyBiomes, Pattern replacement) {
    checkNotNull(region);
    checkNotNull(dir);
    checkArgument(distance >= 1, "distance >= 1 required");
    final Vector displace = dir.multiply(distance);

    final Vector size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1);
    final Vector to = region.getMinimumPoint().add(dir.multiply(distance));

    Vector disAbs = displace.positive();

    if (disAbs.getBlockX() < size.getBlockX() && disAbs.getBlockY() < size.getBlockY() && disAbs.getBlockZ() < size.getBlockZ()) {
        // Buffer if overlapping
        queue.dequeue();
    }

    final ForwardExtentCopy copy = new ForwardExtentCopy(EditSession.this, region, EditSession.this, to);

    if (replacement == null) replacement = nullBlock;
    final BlockReplace remove = replacement instanceof ExistingPattern ? null : new BlockReplace(EditSession.this, replacement);

    copy.setCopyBiomes(copyBiomes);
    copy.setCopyEntities(copyEntities);
    copy.setSourceFunction(remove);
    copy.setRepetitions(1);
    Mask sourceMask = getSourceMask();
    if (sourceMask != null) {
        new MaskTraverser(sourceMask).reset(EditSession.this);
        copy.setSourceMask(sourceMask);
        setSourceMask(null);
    }
    if (!copyAir) {
        copy.setSourceMask(new ExistingBlockMask(EditSession.this));
    }
    Operations.completeBlindly(copy);
    return this.changes = copy.getAffected();
}
 
Example #21
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Turns the first 3 layers into dirt/grass and the bottom layers
 * into rock, like a natural Minecraft mountain.
 *
 * @param region the region to affect
 * @return number of blocks affected
 * @throws MaxChangedBlocksException thrown if too many blocks are changed
 */
public int naturalizeCuboidBlocks(final Region region) {
    checkNotNull(region);
    final Naturalizer naturalizer = new Naturalizer(EditSession.this);
    final FlatRegion flatRegion = Regions.asFlatRegion(region);
    final LayerVisitor visitor = new LayerVisitor(flatRegion, minimumBlockY(region), maximumBlockY(region), naturalizer);
    Operations.completeBlindly(visitor);
    return this.changes = naturalizer.getAffected();
}
 
Example #22
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Places a layer of blocks on top of ground blocks in the given region
 * (as if it were a cuboid).
 *
 * @param region  the region
 * @param pattern the placed block pattern
 * @return number of blocks affected
 * @throws MaxChangedBlocksException thrown if too many blocks are changed
 */
@SuppressWarnings("deprecation")
public int overlayCuboidBlocks(final Region region, final Pattern pattern) {
    checkNotNull(region);
    checkNotNull(pattern);
    final BlockReplace replace = new BlockReplace(EditSession.this, pattern);
    final RegionOffset offset = new RegionOffset(new Vector(0, 1, 0), replace);
    int minY = region.getMinimumPoint().getBlockY();
    int maxY = Math.min(getMaximumPoint().getBlockY(), region.getMaximumPoint().getBlockY() + 1);
    SurfaceRegionFunction surface = new SurfaceRegionFunction(this, offset, minY, maxY);
    FlatRegionVisitor visitor = new FlatRegionVisitor(asFlatRegion(region), surface, this);
    Operations.completeBlindly(visitor);
    return this.changes = visitor.getAffected();
}
 
Example #23
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Replaces all the blocks matching a given mask, within a given region, to a block
 * returned by a given pattern.
 *
 * @param region  the region to replace the blocks within
 * @param mask    the mask that blocks must match
 * @param pattern the pattern that provides the new blocks
 * @return number of blocks affected
 * @throws MaxChangedBlocksException thrown if too many blocks are changed
 */
@SuppressWarnings("deprecation")
public int replaceBlocks(final Region region, final Mask mask, final Pattern pattern) {
    checkNotNull(region);
    checkNotNull(mask);
    checkNotNull(pattern);
    final BlockReplace replace = new BlockReplace(EditSession.this, pattern);
    final RegionMaskingFilter filter = new RegionMaskingFilter(mask, replace);
    final RegionVisitor visitor = new RegionVisitor(region, filter, queue instanceof MappedFaweQueue ? (MappedFaweQueue) queue : null);
    Operations.completeBlindly(visitor);
    return this.changes = visitor.getAffected();
}
 
Example #24
Source File: EditSession.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fills an area recursively in the X/Z directions.
 *
 * @param origin    the origin to start the fill from
 * @param pattern   the pattern to fill with
 * @param radius    the radius of the spherical area to fill, with 0 as the smallest radius
 * @param depth     the maximum depth, starting from the origin, with 1 as the smallest depth
 * @param recursive whether a breadth-first search should be performed
 * @return number of blocks affected
 * @throws MaxChangedBlocksException thrown if too many blocks are changed
 */
@SuppressWarnings("deprecation")
public int fillXZ(final Vector origin, final Pattern pattern, final double radius, final int depth, final boolean recursive) {
    checkNotNull(origin);
    checkNotNull(pattern);
    checkArgument(radius >= 0, "radius >= 0");
    checkArgument(depth >= 1, "depth >= 1");
    final MaskIntersection mask = new MaskIntersection(new RegionMask(new EllipsoidRegion(null, origin, new Vector(radius, radius, radius))), new BoundedHeightMask(Math.max(
            (origin.getBlockY() - depth) + 1, getMinimumPoint().getBlockY()), Math.min(getMaximumPoint().getBlockY(), origin.getBlockY())), Masks.negate(new ExistingBlockMask(EditSession.this)));

    // Want to replace blocks
    final BlockReplace replace = new BlockReplace(EditSession.this, pattern);

    // Pick how we're going to visit blocks
    RecursiveVisitor visitor;
    if (recursive) {
        visitor = new RecursiveVisitor(mask, replace, (int) (radius * 2 + 1), this);
    } else {
        visitor = new DownwardVisitor(mask, replace, origin.getBlockY(), (int) (radius * 2 + 1), this);
    }

    // Start at the origin
    visitor.visit(origin);

    // Execute
    Operations.completeBlindly(visitor);
    return this.changes = visitor.getAffected();
}
 
Example #25
Source File: WorldEdit7.java    From IridiumSkyblock with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void paste(File file, Location location, Island island) {
    try {
        ClipboardFormat format = ClipboardFormats.findByFile(file);
        ClipboardReader reader = format.getReader(new FileInputStream(file));
        Clipboard clipboard = reader.read();
        try (EditSession editSession = com.sk89q.worldedit.WorldEdit.getInstance().getEditSessionFactory().getEditSession(new BukkitWorld(location.getWorld()), -1)) {
            Operation operation = new ClipboardHolder(clipboard)
                    .createPaste(editSession)
                    .to(BlockVector3.at(location.getX(), location.getY(), location.getZ()))
                    .copyEntities(true)
                    .ignoreAirBlocks(true)
                    .build();
            Operations.complete(operation);
        }
    } catch (Exception e) {
        IridiumSkyblock.getInstance().getLogger().warning("Failed to paste schematic using worldedit");
        IridiumSkyblock.schematic.paste(file, location, island);
    }
}
 
Example #26
Source File: SchematicHandler13.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
public static ArrayList<Integer> pasteSchematic(Location loc, String path) throws Exception{
	Bukkit.getLogger().info("[UhcCore] Pasting "+path);
	File schematic = new File(path);
       World world = BukkitAdapter.adapt(loc.getWorld());

       ClipboardFormat format = ClipboardFormats.findByFile(schematic);
       ClipboardReader reader = format.getReader(new FileInputStream(schematic));
       Clipboard clipboard = reader.read();

       EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(world, -1);

       enableWatchdog(editSession);

       Operation operation = new ClipboardHolder(clipboard)
               .createPaste(editSession)
               .to(BlockVector3.at(loc.getX(), loc.getY(), loc.getZ()))
               .ignoreAirBlocks(false)
               .build();

       Operations.complete(operation);
       editSession.flushSession();

	ArrayList<Integer> dimensions = new ArrayList<>();
	dimensions.add(clipboard.getDimensions().getY());
	dimensions.add(clipboard.getDimensions().getX());
	dimensions.add(clipboard.getDimensions().getZ());
	
	Bukkit.getLogger().info("[UhcCore] Successfully pasted '"+path+"' at "+loc.getBlockX()+" "+loc.getBlockY()+" "+loc.getBlockZ());
	return dimensions;
}
 
Example #27
Source File: FullClipboardPattern.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean apply(Extent extent, Vector setPosition, Vector getPosition) throws WorldEditException {
    Region region = clipboard.getRegion();
    ForwardExtentCopy copy = new ForwardExtentCopy(clipboard, clipboard.getRegion(), clipboard.getOrigin(), extent, setPosition);
    copy.setSourceMask(new ExistingBlockMask(clipboard));
    Operations.completeBlindly(copy);
    return true;
}
 
Example #28
Source File: FuzzyRegion.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
public void select(int x, int y, int z) {
    RecursiveVisitor search = new RecursiveVisitor(mask, new RegionFunction() {
        @Override
        public boolean apply(Vector p) throws WorldEditException {
            setMinMax(p.getBlockX(), p.getBlockY(), p.getBlockZ());
            return true;
        }
    }, 256, extent instanceof HasFaweQueue ? (HasFaweQueue) extent : null);
    search.setVisited(set);
    search.visit(new Vector(x, y, z));
    Operations.completeBlindly(search);
}
 
Example #29
Source File: SurfaceSphereBrush.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException {
    SurfaceMask surface = new SurfaceMask(editSession);
    final SolidBlockMask solid = new SolidBlockMask(editSession);
    final RadiusMask radius = new RadiusMask(0, (int) size);
    RecursiveVisitor visitor = new RecursiveVisitor(vector -> surface.test(vector) && radius.test(vector), vector -> editSession.setBlock(vector, pattern));
    visitor.visit(position);
    visitor.setDirections(Arrays.asList(BreadthFirstSearch.DIAGONAL_DIRECTIONS));
    Operations.completeBlindly(visitor);
}
 
Example #30
Source File: ClipboardSpline.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected int pasteBlocks(Vector target, Vector offset, double angle) throws MaxChangedBlocksException {
    RoundedTransform transform = new RoundedTransform(new AffineTransform()
            .translate(offset)
            .rotateY(angle));
    if (!this.transform.isIdentity()) {
        transform = transform.combine(this.transform);
    }
    if (!originalTransform.isIdentity()) {
        transform = transform.combine(originalTransform);
    }

    // Pasting
    Clipboard clipboard = clipboardHolder.getClipboard();
    clipboard.setOrigin(center.subtract(centerOffset).round());
    clipboardHolder.setTransform(transform);

    Vector functionOffset = target.subtract(clipboard.getOrigin());
    final int offX = functionOffset.getBlockX();
    final int offY = functionOffset.getBlockY();
    final int offZ = functionOffset.getBlockZ();

    Operation operation = clipboardHolder
            .createPaste(editSession, editSession.getWorldData())
            .to(target)
            .ignoreAirBlocks(true)
            .filter(v -> buffer.add(v.getBlockX() + offX, v.getBlockY() + offY, v.getBlockZ() + offZ))
            .build();
    Operations.completeLegacy(operation);

    // Cleanup
    clipboardHolder.setTransform(originalTransform);
    clipboard.setOrigin(originalOrigin);

    return operation instanceof ForwardExtentCopy ? ((ForwardExtentCopy) operation).getAffected() : 0;
}