org.spongepowered.api.util.Direction Java Examples

The following examples show how to use org.spongepowered.api.util.Direction. 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: BlockUtils.java    From GriefPrevention with MIT License 6 votes vote down vote up
private static int directionToIndex(Direction direction) {
    switch (direction) {
        case NORTH:
        case NORTHEAST:
        case NORTHWEST:
            return 0;
        case SOUTH:
        case SOUTHEAST:
        case SOUTHWEST:
            return 1;
        case EAST:
            return 2;
        case WEST:
            return 3;
        default:
            throw new IllegalArgumentException("Unexpected direction");
    }
}
 
Example #2
Source File: BlockUtils.java    From GriefPrevention with MIT License 6 votes vote down vote up
private static void chunkLoadPostProcess(Chunk chunk) {
    if (chunk != null) {
        WorldServer world = (WorldServer) chunk.getWorld();
        world.getChunkProvider().id2ChunkMap.put(ChunkPos.asLong(chunk.x, chunk.z), chunk);

        org.spongepowered.api.world.Chunk spongeChunk = (org.spongepowered.api.world.Chunk) chunk;
        for (Direction direction : CARDINAL_SET) {
            Vector3i neighborPosition = spongeChunk.getPosition().add(direction.asBlockOffset());
            ChunkProviderBridge spongeChunkProvider = (ChunkProviderBridge) world.getChunkProvider();
            net.minecraft.world.chunk.Chunk neighbor = spongeChunkProvider.bridge$getLoadedChunkWithoutMarkingActive(neighborPosition.getX(), neighborPosition.getZ());
            if (neighbor != null) {
                int neighborIndex = directionToIndex(direction);
                int oppositeNeighborIndex = directionToIndex(direction.getOpposite());
                ((ChunkBridge) spongeChunk).bridge$setNeighborChunk(neighborIndex, neighbor);
                ((ChunkBridge) neighbor).bridge$setNeighborChunk(oppositeNeighborIndex, (net.minecraft.world.chunk.Chunk)(Object) chunk);
            }
        }

        chunk.populate(world.getChunkProvider(), world.getChunkProvider().chunkGenerator);
    }
}
 
Example #3
Source File: BlockEventHandler.java    From GriefDefender with MIT License 5 votes vote down vote up
private boolean checkSurroundings(org.spongepowered.api.event.Event event, Location<World> location, Player player, GDPlayerData playerData, GDClaim targetClaim) {
    if (playerData == null) {
        return true;
    }
    // Don't allow players to break blocks next to land they do not own
    if (!playerData.canIgnoreClaim(targetClaim)) {
        // check surrounding blocks for access
        for (Direction direction : BlockUtil.CARDINAL_SET) {
            Location<World> loc = location.getBlockRelative(direction);
            if (!(loc.getTileEntity().isPresent())) {
                continue;
            }
            final GDClaim claim = this.dataStore.getClaimAt(loc, targetClaim);
            if (!claim.isWilderness() && !targetClaim.equals(claim)) {
                Tristate result = GDPermissionManager.getInstance().getFinalPermission(event, loc, claim, Flags.BLOCK_BREAK, player, loc.getBlock(), player, TrustTypes.BUILDER, true);
                if (result != Tristate.TRUE) {
                    final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.PERMISSION_BUILD_NEAR_CLAIM,
                            ImmutableMap.of(
                            "player", claim.getOwnerName()));
                    GriefDefenderPlugin.sendClaimDenyMessage(claim, player, message);
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #4
Source File: BlockListener.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onBlockBreak(ChangeBlockEvent.Break e, @First Player p) {
    RedProtect.get().logger.debug(LogLevel.BLOCKS, "BlockListener - Is ChangeBlockEvent.Break event!");

    BlockSnapshot b = e.getTransactions().get(0).getOriginal();
    Location<World> bloc = b.getLocation().get();

    boolean antih = RedProtect.get().config.configRoot().region_settings.anti_hopper;
    Region r = RedProtect.get().rm.getTopRegion(bloc, this.getClass().getName());

    if (!RedProtect.get().ph.hasPerm(p, "redprotect.bypass")) {
        BlockSnapshot ib = bloc.getBlockRelative(Direction.UP).createSnapshot();
        if ((antih && !cont.canBreak(p, ib)) || !cont.canBreak(p, b)) {
            RedProtect.get().lang.sendMessage(p, "blocklistener.container.breakinside");
            e.setCancelled(true);
            return;
        }
    }

    if (r == null && canBreakList(p.getWorld(), b.getState().getType().getName())) {
        return;
    }

    if (r != null && b.getState().getType().equals(BlockTypes.MOB_SPAWNER) && r.allowSpawner(p)) {
        return;
    }

    if (r != null && r.canBuild(p) && b.getState().getType().getName().equalsIgnoreCase("sign")) {
        Sign s = (Sign) b.getLocation().get().getTileEntity().get();
        if (s.lines().get(0).toPlain().equalsIgnoreCase("[flag]")) {
            RedProtect.get().config.removeSign(r.getID(), b.getLocation().get());
            return;
        }
    }

    if (r != null && !r.canBuild(p) && !r.canTree(b) && !r.canMining(b) && !r.canCrops(b) && !r.canBreak(b)) {
        RedProtect.get().lang.sendMessage(p, "blocklistener.region.cantbuild");
        e.setCancelled(true);
    }
}
 
Example #5
Source File: DoorManager.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public static void ChangeDoor(BlockSnapshot b, Region r) {
    if ((!r.flagExists("smart-door") && !RedProtect.get().config.configRoot().flags.get("smart-door")) || !r.getFlagBool("smart-door")) {
        return;
    }

    Location<World> loc = b.getLocation().get();
    World w = loc.getExtent();

    if (isDoor(b)) {
        boolean iron = b.getState().getType() == BlockTypes.IRON_DOOR;
        if (iron) {
            changeDoorState(b);
            if (getDoorState(b)) {
                w.playSound(SoundTypes.BLOCK_IRON_DOOR_OPEN, loc.getPosition(), 1);
            } else {
                w.playSound(SoundTypes.BLOCK_IRON_DOOR_CLOSE, loc.getPosition(), 1);
            }
        }

        if (loc.getRelative(Direction.DOWN).getBlock().getType() == b.getState().getType() && loc.get(Keys.PORTION_TYPE).get() == PortionTypes.TOP) {
            loc = loc.getRelative(Direction.DOWN);
        }

        //check side block if is door
        BlockSnapshot[] block = new BlockSnapshot[4];
        block[0] = loc.getRelative(Direction.EAST).createSnapshot();
        block[1] = loc.getRelative(Direction.WEST).createSnapshot();
        block[2] = loc.getRelative(Direction.NORTH).createSnapshot();
        block[3] = loc.getRelative(Direction.SOUTH).createSnapshot();

        for (BlockSnapshot b2 : block) {
            if (b.getState().getType() == b2.getState().getType()) {
                changeDoorState(b2);
                break;
            }
        }
    }
}
 
Example #6
Source File: ContainerManager.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public boolean canOpen(BlockSnapshot b, Player p) {
    if (!RedProtect.get().config.configRoot().private_cat.use || p.hasPermission("redprotect.bypass")) {
        return true;
    }

    List<Direction> dirs = Arrays.asList(Direction.EAST, Direction.NORTH, Direction.SOUTH, Direction.WEST);
    String blocktype = b.getState().getType().getName();
    Location<World> loc = b.getLocation().get();
    List<String> blocks = RedProtect.get().config.configRoot().private_cat.allowed_blocks;
    boolean deny = true;
    if (blocks.stream().anyMatch(blocktype::matches)) {
        for (Direction dir : dirs) {
            Location<World> loc1 = loc.getBlockRelative(dir);
            if (isSign(loc1.createSnapshot())) {
                deny = false;
                if (validateOpenBlock(loc1.createSnapshot(), p)) {
                    return true;
                }
            }

            if (blocks.stream().anyMatch(loc1.getBlockType().getName()::matches) && loc1.getBlockType().equals(b.getState().getType())) {
                for (Direction dir2 : dirs) {
                    Location<World> loc3 = loc1.getBlockRelative(dir2);
                    if (isSign(loc3.createSnapshot())) {
                        deny = false;
                        if (validateOpenBlock(loc3.createSnapshot(), p)) {
                            return true;
                        }
                    }
                }
            }
        }
    }
    return deny;
}
 
Example #7
Source File: RedProtectUtil.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public Transform<World> DenyEnterPlayer(World wFrom, Transform<World> from, Transform<World> to, Region r, boolean checkSec) {
    Location<World> setFrom = from.getLocation();
    for (int i = 0; i < r.getArea() + 10; i++) {
        Region r1 = RedProtect.get().rm.getTopRegion(wFrom.getName(), setFrom.getBlockX() + i, setFrom.getBlockY(), setFrom.getBlockZ(), RedProtectUtil.class.getName());
        Region r2 = RedProtect.get().rm.getTopRegion(wFrom.getName(), setFrom.getBlockX() - i, setFrom.getBlockY(), setFrom.getBlockZ(), RedProtectUtil.class.getName());
        Region r3 = RedProtect.get().rm.getTopRegion(wFrom.getName(), setFrom.getBlockX(), setFrom.getBlockY(), setFrom.getBlockZ() + i, RedProtectUtil.class.getName());
        Region r4 = RedProtect.get().rm.getTopRegion(wFrom.getName(), setFrom.getBlockX(), setFrom.getBlockY(), setFrom.getBlockZ() - i, RedProtectUtil.class.getName());
        Region r5 = RedProtect.get().rm.getTopRegion(wFrom.getName(), setFrom.getBlockX() + i, setFrom.getBlockY(), setFrom.getBlockZ() + i, RedProtectUtil.class.getName());
        Region r6 = RedProtect.get().rm.getTopRegion(wFrom.getName(), setFrom.getBlockX() - i, setFrom.getBlockY(), setFrom.getBlockZ() - i, RedProtectUtil.class.getName());
        if (r1 != r) {
            to = new Transform<>(setFrom.add(+i, 0, 0)).setRotation(from.getRotation());
            break;
        }
        if (r2 != r) {
            to = new Transform<>(setFrom.add(-i, 0, 0)).setRotation(from.getRotation());
            break;
        }
        if (r3 != r) {
            to = new Transform<>(setFrom.add(0, 0, +i)).setRotation(from.getRotation());
            break;
        }
        if (r4 != r) {
            to = new Transform<>(setFrom.add(0, 0, -i)).setRotation(from.getRotation());
            break;
        }
        if (r5 != r) {
            to = new Transform<>(setFrom.add(+i, 0, +i)).setRotation(from.getRotation());
            break;
        }
        if (r6 != r) {
            to = new Transform<>(setFrom.add(-i, 0, -i)).setRotation(from.getRotation());
            break;
        }
    }
    if (checkSec && !isSecure(to.getLocation())) {
        RedProtect.get().getVersionHelper().setBlock(to.getLocation().getBlockRelative(Direction.DOWN), BlockTypes.GRASS.getDefaultState());
    }
    return to;
}
 
Example #8
Source File: DirectionExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player player = (Player) src;
		// Credit to kenzierocks for the following line. =D
		player.sendMessage(Text.of(TextColors.GOLD, "You are facing: ", TextColors.GRAY, Direction.getClosest(player.getTransform().getRotationAsQuaternion().getDirection()).toString()));
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be an in-game player to use /direction!"));
	}
	
	return CommandResult.success();
}
 
Example #9
Source File: BlockUtils.java    From GriefPrevention with MIT License 5 votes vote down vote up
private static boolean unloadChunk(net.minecraft.world.chunk.Chunk chunk) {
    net.minecraft.world.World mcWorld = chunk.getWorld();
    ChunkProviderServer chunkProviderServer = (ChunkProviderServer) chunk.getWorld().getChunkProvider();

    boolean saveChunk = false;
    if (chunk.needsSaving(true)) {
        saveChunk = true;
    }

    for (ClassInheritanceMultiMap<Entity> classinheritancemultimap : chunk.getEntityLists())
    {
        chunk.getWorld().unloadEntities(classinheritancemultimap);
    }

    if (saveChunk) {
        saveChunkData(chunkProviderServer, chunk);
    }

    chunkProviderServer.id2ChunkMap.remove(ChunkPos.asLong(chunk.x, chunk.z));
    ((ChunkBridge) chunk).bridge$setScheduledForUnload(-1);
    org.spongepowered.api.world.Chunk spongeChunk = (org.spongepowered.api.world.Chunk) chunk;
    for (Direction direction : CARDINAL_SET) {
        Vector3i neighborPosition = spongeChunk.getPosition().add(direction.asBlockOffset());
        ChunkProviderBridge spongeChunkProvider = (ChunkProviderBridge) mcWorld.getChunkProvider();
        net.minecraft.world.chunk.Chunk neighbor = spongeChunkProvider.bridge$getLoadedChunkWithoutMarkingActive(neighborPosition.getX(),
            neighborPosition.getZ());
        if (neighbor != null) {
            int neighborIndex = directionToIndex(direction);
            int oppositeNeighborIndex = directionToIndex(direction.getOpposite());
            ((ChunkBridge) spongeChunk).bridge$setNeighborChunk(neighborIndex, null);
            ((ChunkBridge) neighbor).bridge$setNeighborChunk(oppositeNeighborIndex, null);
        }
    }

    return true;
}
 
Example #10
Source File: Visualization.java    From GriefPrevention with MIT License 5 votes vote down vote up
private static Location<World> getVisibleLocation(World world, int x, int y, int z, boolean waterIsTransparent) {
    Location<World> location = world.getLocation(x, y, z);
    Direction direction = (isTransparent(location.getBlock(), waterIsTransparent)) ? Direction.DOWN : Direction.UP;

    while (location.getPosition().getY() >= 1 &&
            location.getPosition().getY() < world.getDimension().getBuildHeight() - 1 &&
            (!isTransparent(location.getBlockRelative(Direction.UP).getBlock(), waterIsTransparent)
                    || isTransparent(location.getBlock(), waterIsTransparent))) {
        location = location.getBlockRelative(direction);
    }

    return location;
}
 
Example #11
Source File: PlayerUtil.java    From GriefDefender with MIT License 5 votes vote down vote up
public Direction getBlockFace(String param) {
    Direction face = null;
    try {
        face = Direction.valueOf(param.toUpperCase());
    } catch (IllegalArgumentException e) {
        // ignore
    }
    return face;
}
 
Example #12
Source File: BlockUtils.java    From GriefPrevention with MIT License 4 votes vote down vote up
public static boolean createFillerChunk(GPPlayerData playerData, WorldServer world, int chunkX, int chunkZ) {
    ChunkProviderServer chunkProviderServer = world.getChunkProvider();
    Chunk chunk = ((ChunkProviderBridge) chunkProviderServer).bridge$getLoadedChunkWithoutMarkingActive(chunkX, chunkZ);
    if (chunk == null) {
        return false;
    }

    unloadChunk(chunk);
    org.spongepowered.api.world.Chunk fillerChunk = (org.spongepowered.api.world.Chunk) chunkProviderServer.chunkGenerator.generateChunk(chunk.x, chunk.z);
    int maxBuildHeight = fillerChunk.getWorld().getDimension().getBuildHeight() - 1;
    BlockSnapshot[][][] snapshots = new BlockSnapshot[18][maxBuildHeight][18];
    BlockSnapshot startBlock = fillerChunk.createSnapshot(0, 0, 0);
    Location<World> startLocation =
            new Location<World>(fillerChunk.getWorld(), startBlock.getPosition().getX() - 1, 0, startBlock.getPosition().getZ() - 1);
    for (int x = 0; x < snapshots.length; x++) {
        for (int z = 0; z < snapshots[0][0].length; z++) {
            for (int y = 0; y < snapshots[0].length; y++) {
                snapshots[x][y][z] = fillerChunk.getWorld()
                        .createSnapshot(startLocation.getBlockX() + x, startLocation.getBlockY() + y, startLocation.getBlockZ() + z);
            }
        }
    }
    fillerChunk = null;
    playerData.fillerBlocks = snapshots;
    if (chunk != null) {
        world.getChunkProvider().id2ChunkMap.put(ChunkPos.asLong(chunk.x, chunk.z), chunk);

        org.spongepowered.api.world.Chunk spongeChunk = (org.spongepowered.api.world.Chunk) chunk;
        for (Direction direction : CARDINAL_SET) {
            Vector3i neighborPosition = spongeChunk.getPosition().add(direction.asBlockOffset());
            ChunkProviderBridge spongeChunkProvider = (ChunkProviderBridge) world.getChunkProvider();
            net.minecraft.world.chunk.Chunk neighbor = spongeChunkProvider.bridge$getLoadedChunkWithoutMarkingActive(neighborPosition.getX(),
                neighborPosition.getZ());
            if (neighbor != null) {
                int neighborIndex = directionToIndex(direction);
                int oppositeNeighborIndex = directionToIndex(direction.getOpposite());
                ((ChunkBridge) spongeChunk).bridge$setNeighborChunk(neighborIndex, neighbor);
                ((ChunkBridge) neighbor).bridge$setNeighborChunk(oppositeNeighborIndex, (net.minecraft.world.chunk.Chunk)(Object) chunk);
            }
        }
    }
    return true;
}
 
Example #13
Source File: RestoreNatureExecutionTask.java    From GriefPrevention with MIT License 4 votes vote down vote up
@Override
public void run() {
    // apply changes to the world, but ONLY to unclaimed blocks
    // note that the edge of the results is not applied (the 1-block-wide
    // band around the outside of the chunk)
    // those data were sent to the processing thread for reference
    // purposes, but aren't part of the area selected for restoration
    for (int x = 1; x < this.snapshots.length - 1; x++) {
        for (int z = 1; z < this.snapshots[0][0].length - 1; z++) {
            for (int y = this.miny; y < this.snapshots[0].length; y++) {
                BlockSnapshot blockUpdate = this.snapshots[x][y][z];
                BlockState currentBlock = blockUpdate.getLocation().get().getBlock();
                int originalMeta = BlockUtils.getBlockStateMeta(blockUpdate.getState());
                int newMeta = BlockUtils.getBlockStateMeta(currentBlock);
                if (!blockUpdate.getState().getType().equals(currentBlock.getType()) || originalMeta != newMeta) {
                    blockUpdate.restore(true, BlockChangeFlags.PHYSICS);
                }
            }
        }
    }

    // clean up any entities in the chunk, ensure no players are suffocated
    Optional<Chunk> chunk = this.lesserCorner.getExtent().getChunk(this.lesserCorner.getBlockX() >> 4, 0, this.lesserCorner.getBlockZ() >> 4);
    if (chunk.isPresent()) {
        try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
            Sponge.getCauseStackManager().pushCause(GriefPreventionPlugin.instance);
            for (Entity entity : chunk.get().getEntities()) {
                if (!(entity instanceof Player || entity instanceof Animal)) {
                    // hanging entities (paintings, item frames) are protected when they're in land claims
                    if (!(entity instanceof Hanging)
                        || GriefPreventionPlugin.instance.dataStore.getClaimAt(entity.getLocation()) == null) {
                        // everything else is removed
                        entity.remove();
                    }
                }

                // for players, always ensure there's air where the player is standing
                else {
                    entity.getLocation().setBlock(BlockTypes.AIR.getDefaultState());
                    entity.getLocation().getBlockRelative(Direction.UP).setBlock(BlockTypes.AIR.getDefaultState());
                }
            }
        }
    }

    // show visualization to player who started the restoration
    if (player != null) {
        GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
        GPClaim claim = new GPClaim(this.lesserCorner, this.greaterCorner, ClaimType.BASIC, false);
        // TODO
        claim.getVisualizer().resetVisuals();
        claim.getVisualizer().createClaimBlockVisuals(player.getLocation().getBlockY(), player.getLocation(), playerData);
        claim.getVisualizer().apply(player);
    }
}
 
Example #14
Source File: JumpExecutor.java    From EssentialCmds with MIT License 4 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player player = (Player) src;

		BlockRay<World> playerBlockRay = BlockRay.from(player).blockLimit(350).build();

		BlockRayHit<World> finalHitRay = null;

		while (playerBlockRay.hasNext())
		{
			BlockRayHit<World> currentHitRay = playerBlockRay.next();

			if (!player.getWorld().getBlockType(currentHitRay.getBlockPosition()).equals(BlockTypes.AIR))
			{
				finalHitRay = currentHitRay;
				break;
			}
		}

		if (finalHitRay == null)
		{
			player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Could not find the block you're looking at within range!"));
		}
		else
		{
			boolean safely = false;
			// If not passable, then it is a solid block
			if (!finalHitRay.getLocation().getProperty(PassableProperty.class).get().getValue())
			{
				safely = player.setLocationSafely(finalHitRay.getLocation().add(0, 1, 0));
			}
			else
			{
				// If the block below this is tall grass or a tall flower, then teleport down to that
				if (finalHitRay.getLocation().getRelative(Direction.DOWN).getProperty(PassableProperty.class).get().getValue())
				{
					safely = player.setLocationSafely(finalHitRay.getLocation().sub(0, 1, 0));
				}
				else
				{
					// If not then we found our location
					safely = player.setLocationSafely(finalHitRay.getLocation());
				}
			}
			if (safely)
			{
				player.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Jumped to the block you were looking at."));
			}
			else
			{
				player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Couldn't safely put you where you are looking."));
			}
		}
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Must be an in-game player to use /jump!"));
	}

	return CommandResult.success();
}
 
Example #15
Source File: ContainerManager.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
public boolean canBreak(Player p, BlockSnapshot b) {
    if (!RedProtect.get().config.configRoot().private_cat.use) {
        return true;
    }

    Region reg = RedProtect.get().rm.getTopRegion(b.getLocation().get(), this.getClass().getName());
    if (reg == null && !RedProtect.get().config.configRoot().private_cat.allow_outside) {
        return true;
    }

    List<Direction> dirs = Arrays.asList(Direction.EAST, Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.UP, Direction.DOWN);
    String blocktype = b.getState().getType().getName();
    Location<World> loc = b.getLocation().get();
    List<String> blocks = RedProtect.get().config.configRoot().private_cat.allowed_blocks;

    boolean deny = true;

    if (isSign(loc.createSnapshot()) && validatePrivateSign(b)) {
        deny = false;
        if (validateBreakSign(loc.createSnapshot(), p)) {
            return true;
        }
    }

    if (blocks.stream().anyMatch(blocktype::matches)) {
        for (Direction dir : dirs) {
            Location<World> loc1 = loc.getBlockRelative(dir);
            if (isSign(loc1.createSnapshot())) {
                deny = false;
                if (validateBreakSign(loc1.createSnapshot(), p)) {
                    return true;
                }
            }

            if (blocks.stream().anyMatch(loc1.getBlockType().getName()::matches) && loc1.getBlockType().equals(b.getState().getType())) {
                for (Direction dir2 : dirs) {
                    Location<World> loc3 = loc1.getBlockRelative(dir2);
                    if (isSign(loc3.createSnapshot())) {
                        deny = false;
                        if (validateBreakSign(loc3.createSnapshot(), p)) {
                            return true;
                        }
                    }
                }
            }
        }
    }
    return deny;
}
 
Example #16
Source File: PlayerUtil.java    From GriefDefender with MIT License 4 votes vote down vote up
public Direction getBlockFace(Player player) {
    return faces[Math.round((int) player.getTransform().getYaw() / 90f) & 0x3].getOpposite();
}
 
Example #17
Source File: WEHook.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
public static Region pasteWithWE(Player p, File file) {
    Location<World> loc = p.getLocation();
    Region r = null;

    if (p.getLocation().getBlockRelative(Direction.DOWN).getBlock().getType().equals(BlockTypes.WATER) ||
            p.getLocation().getBlockRelative(Direction.DOWN).getBlock().getType().equals(BlockTypes.FLOWING_WATER)) {
        RedProtect.get().lang.sendMessage(p, "playerlistener.region.needground");
        return null;
    }

    SpongePlayer sp = SpongeWorldEdit.inst().wrapPlayer(p);
    SpongeWorld ws = SpongeWorldEdit.inst().getWorld(p.getWorld());

    LocalSession session = SpongeWorldEdit.inst().getSession(p);

    Closer closer = Closer.create();
    try {
        ClipboardFormat format = ClipboardFormat.findByAlias("schematic");
        FileInputStream fis = closer.register(new FileInputStream(file));
        BufferedInputStream bis = closer.register(new BufferedInputStream(fis));
        ClipboardReader reader = format.getReader(bis);

        WorldData worldData = ws.getWorldData();
        Clipboard clipboard = reader.read(ws.getWorldData());
        session.setClipboard(new ClipboardHolder(clipboard, worldData));

        Vector bmin = clipboard.getMinimumPoint();
        Vector bmax = clipboard.getMaximumPoint();

        Location<World> min = loc.add(bmin.getX(), bmin.getY(), bmin.getZ());
        Location<World> max = loc.add(bmax.getX(), bmax.getY(), bmax.getZ());

        PlayerRegion leader = new PlayerRegion(p.getUniqueId().toString(), p.getName());
        RegionBuilder rb2 = new DefineRegionBuilder(p, min, max, "", leader, new HashSet<>(), false);
        if (rb2.ready()) {
            r = rb2.build();
        }

        ClipboardHolder holder = session.getClipboard();

        Operation op = holder.createPaste(session.createEditSession(sp), ws.getWorldData()).to(session.getPlacementPosition(sp)).build();
        Operations.completeLegacy(op);
    } catch (IOException | EmptyClipboardException | IncompleteRegionException | MaxChangedBlocksException e) {
        CoreUtil.printJarVersion();
        e.printStackTrace();
    }

    return r;
}
 
Example #18
Source File: BlockEventHandler.java    From GriefDefender with MIT License 4 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onBlockNotify(NotifyNeighborBlockEvent event) {
    LocatableBlock locatableBlock = event.getCause().first(LocatableBlock.class).orElse(null);
    TileEntity tileEntity = event.getCause().first(TileEntity.class).orElse(null);
    Location<World> sourceLocation = locatableBlock != null ? locatableBlock.getLocation() : tileEntity != null ? tileEntity.getLocation() : null;
    GDClaim sourceClaim = null;
    GDPlayerData playerData = null;
    if (sourceLocation != null) {
        if (GriefDefenderPlugin.isSourceIdBlacklisted("block-notify", event.getSource(), sourceLocation.getExtent().getProperties())) {
            return;
        }
    }

    final User user = CauseContextHelper.getEventUser(event);
    if (user == null) {
        return;
    }
    if (sourceLocation == null) {
        Player player = event.getCause().first(Player.class).orElse(null);
        if (player == null) {
            return;
        }

        sourceLocation = player.getLocation();
        playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
        sourceClaim = this.dataStore.getClaimAtPlayer(playerData, player.getLocation());
    } else {
        playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(sourceLocation.getExtent(), user.getUniqueId());
        sourceClaim = this.dataStore.getClaimAt(sourceLocation);
    }

    if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(sourceLocation.getExtent().getUniqueId())) {
        return;
    }

    GDTimings.BLOCK_NOTIFY_EVENT.startTimingIfSync();
    Iterator<Direction> iterator = event.getNeighbors().keySet().iterator();
    GDClaim targetClaim = null;
    while (iterator.hasNext()) {
        Direction direction = iterator.next();
        Location<World> location = sourceLocation.getBlockRelative(direction);
        Vector3i pos = location.getBlockPosition();
        targetClaim = this.dataStore.getClaimAt(location, targetClaim);
        if (sourceClaim.isWilderness() && targetClaim.isWilderness()) {
            if (playerData != null) {
                playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE);
            }
            continue;
        } else if (!sourceClaim.isWilderness() && targetClaim.isWilderness()) {
            if (playerData != null) {
                playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE);
            }
            continue;
        } else if (sourceClaim.getUniqueId().equals(targetClaim.getUniqueId())) {
            if (playerData != null) {
                playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE);
            }
            continue;
        } else {
            if (playerData.eventResultCache != null && playerData.eventResultCache.checkEventResultCache(targetClaim, "block-notify") == Tristate.TRUE) {
                continue;
            }
            // Needed to handle levers notifying doors to open etc.
            if (targetClaim.isUserTrusted(user, TrustTypes.ACCESSOR)) {
                if (playerData != null) {
                    playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE, TrustTypes.ACCESSOR.getName().toLowerCase());
                }
                continue;
            }
        }

        // no claim crossing unless trusted
        iterator.remove();
    }
    GDTimings.BLOCK_NOTIFY_EVENT.stopTimingIfSync();
}