org.spongepowered.api.world.World Java Examples

The following examples show how to use org.spongepowered.api.world.World. 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: BlockListener.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onFrameAndBoatBrake(DamageEntityEvent e) {
    RedProtect.get().logger.debug(LogLevel.BLOCKS, "Is BlockListener - DamageEntityEvent event");

    Entity ent = e.getTargetEntity();
    Location<World> l = e.getTargetEntity().getLocation();

    Region r = RedProtect.get().rm.getTopRegion(l, this.getClass().getName());
    if (r == null) return;

    if (ent instanceof Hanging && e.getCause().first(Monster.class).isPresent()) {
        if (!r.canFire()) {
            e.setCancelled(true);
            return;
        }
    }

    if ((ent instanceof Boat || ent instanceof Minecart) && e.getCause().first(Player.class).isPresent()) {
        Player p = e.getCause().first(Player.class).get();
        if (!r.canMinecart(p)) {
            RedProtect.get().lang.sendMessage(p, "blocklistener.region.cantbreak");
            e.setCancelled(true);
        }
    }
}
 
Example #2
Source File: ClaimCommand.java    From EagleFactions with MIT License 6 votes vote down vote up
private CommandResult preformAdminClaim(final Player player, final Faction faction, final Vector3i chunk) throws CommandException
{
    final World world = player.getWorld();
    final boolean safeZoneWorld = this.protectionConfig.getSafeZoneWorldNames().contains(world.getName());
    final boolean warZoneWorld = this.protectionConfig.getWarZoneWorldNames().contains(world.getName());

    //Even admin cannot claim territories in safezone nor warzone world.
    if (safeZoneWorld || warZoneWorld)
        throw new CommandException(PluginInfo.ERROR_PREFIX.concat(Text.of(TextColors.RED, Messages.YOU_CANNOT_CLAIM_TERRITORIES_IN_THIS_WORLD)));

    boolean isCancelled = EventRunner.runFactionClaimEvent(player, faction, player.getWorld(), chunk);
    if (isCancelled)
        return CommandResult.empty();

    super.getPlugin().getFactionLogic().addClaim(faction, new Claim(player.getWorld().getUniqueId(), chunk));
    player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, Messages.LAND + " ", TextColors.GOLD, chunk.toString(), TextColors.WHITE, " " + Messages.HAS_BEEN_SUCCESSFULLY + " ", TextColors.GOLD, Messages.CLAIMED, TextColors.WHITE, "!"));
    return CommandResult.success();
}
 
Example #3
Source File: MCClansEventHandler.java    From GriefPrevention with MIT License 6 votes vote down vote up
public void onClanCreate(ClanCreateEvent event) {
    if (!GriefPreventionPlugin.getGlobalConfig().getConfig().town.clanRequireTown) {
        return;
    }

    final Player player = Sponge.getServer().getPlayer(event.getOwner().getUUID()).orElse(null);
    if (player == null) {
        return;
    }

    final World world = player.getWorld();
    if (!GriefPreventionPlugin.instance.claimsEnabledForWorld(world.getProperties())) {
        return;
    }

    final GPPlayerData playerData  = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(world, player.getUniqueId());
    for (Claim claim : playerData.getInternalClaims()) {
        if (claim.isTown()) {
            return;
        }
    }
    event.setCancelledWithMessage("You must own a town in order to create a clan.");
}
 
Example #4
Source File: NightTimeCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    World world;
    if (!args.hasAny("world")) {
        checkIfPlayer(sender);
        world = ((Player) sender).getWorld();
    } else {
        world = args.<World>getOne("world").get();
    }

    //Players can enter their bed at 12541 ticks
    Long ticks = 12541 - (world.getProperties().getWorldTime() % 24000);
    world.getProperties().setWorldTime(world.getProperties().getWorldTime() + ticks);
    Messages.send(sender, "time.command.time.set.night");
    return CommandResult.success();
}
 
Example #5
Source File: SpongeCommands.java    From BlueMap with MIT License 6 votes vote down vote up
@Override
public List<String> getSuggestions(CommandSource source, String arguments, Location<World> targetPosition) throws CommandException {
	String command = label;
	if (!arguments.isEmpty()) {
		command += " " + arguments;
	}

	List<String> completions = new ArrayList<>();

	try {
		Suggestions suggestions = dispatcher.getCompletionSuggestions(dispatcher.parse(command, source)).get(100, TimeUnit.MILLISECONDS);
		for (Suggestion suggestion : suggestions.getList()) {
			String text = suggestion.getText();
	
			if (text.indexOf(' ') == -1) {
				completions.add(text);
			}
		}
	} catch (InterruptedException | ExecutionException | TimeoutException ignore) {}

	completions.sort((s1, s2) -> s1.compareToIgnoreCase(s2));
	return completions;
}
 
Example #6
Source File: MCClansEventHandler.java    From GriefDefender with MIT License 6 votes vote down vote up
public void onClanSetHome(ClanSetHomeEvent event) {
    final World world = event.getLocation().getExtent();
    if (!GriefDefenderPlugin.getGlobalConfig().getConfig().town.clanRequireTown || !GriefDefenderPlugin.getInstance().claimsEnabledForWorld(world.getUniqueId())) {
        return;
    }

    final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAt(event.getLocation());
    if (!claim.isInTown()) {
        event.setCancelledWithMessage("You must be in a town in order to set your clan home.");
        return;
    }
    if (!claim.getOwnerUniqueId().equals(event.getClan().getOwner().getUUID())) {
        event.setCancelledWithMessage("You do not own this town.");
        return;
    }
}
 
Example #7
Source File: RTPExecutor.java    From EssentialCmds with MIT License 6 votes vote down vote up
private Optional<Location<World>> randomLocation(Player player, int searchDiameter){
	Location<World> playerLocation = player.getLocation();
	//Adding world border support, otherwise you could murder players by using a location within the border.
	WorldBorder border = player.getWorld().getWorldBorder();
	Vector3d center = border.getCenter();
	double diameter = Math.min(border.getDiameter(), searchDiameter);
	double radius = border.getDiameter() / 2;
	Random rand = new Random();
	int x = (int) (rand.nextInt((int) (center.getX()+diameter)) - radius);
	int y = rand.nextInt(256);
	int z = rand.nextInt((int) (rand.nextInt((int) (center.getZ()+diameter)) - radius));

	Location<World> randLocation = new Location<World>(playerLocation.getExtent(), x, y, z);
	TeleportHelper teleportHelper = Sponge.getGame().getTeleportHelper();
	return teleportHelper.getSafeLocation(randLocation);
}
 
Example #8
Source File: GlobalListener.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onChangeWeather(ChangeWorldWeatherEvent e) {
    RedProtect.get().logger.debug(LogLevel.BLOCKS, "GlobalListener - Is onChangeWeather event");

    World w = e.getTargetWorld();
    if (!RedProtect.get().config.globalFlagsRoot().worlds.get(e.getTargetWorld().getName()).weather.allow_weather) {
        int attempts = RedProtect.get().config.globalFlagsRoot().worlds.get(w.getName()).weather.attempts_before_rain;
        if (!e.getWeather().equals(Weathers.CLEAR)) {
            if (!rainCounter.containsKey(w)) {
                rainCounter.put(w, attempts);
                e.setCancelled(true);
            } else {
                int acTry = rainCounter.get(w);
                if (acTry - 1 <= 0) {
                    Sponge.getScheduler().createSyncExecutor(RedProtect.get().container).schedule(() -> w.setWeather(e.getWeather(), RedProtect.get().config.globalFlagsRoot().worlds.get(w.getName()).weather.rain_time), RedProtect.get().config.globalFlagsRoot().worlds.get(w.getName()).weather.rain_time, TimeUnit.SECONDS);
                    rainCounter.put(w, attempts);
                } else {
                    rainCounter.put(w, acTry - 1);
                    e.setCancelled(true);
                }
            }
        }
    }
}
 
Example #9
Source File: BiomeTeleportCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    checkIfPlayer(src);
    Player p = (Player) src;
    BiomeType type = args.<BiomeType>getOne("biome").get();

    //Find location
    Location<World> loc = BiomeFindHandler.findBiome(p, type).orElse(null);
    if (loc == null) {
        throw Messages.error(src, "teleport.command.biometeleport.fail", "%biome%", type.getName());
    }

    //Found suitable location
    Teleportation request = UltimateCore.get().getTeleportService().createTeleportation(p, Arrays.asList(p), new Transform<>(loc, p.getRotation(), p.getScale()), teleportRequest -> {
        //Complete
        Messages.send(p, "teleport.command.biometeleport.success", "%biome%", type.getName());
    }, (teleportRequest, reason) -> {
    }, true, false);
    request.start();
    return CommandResult.success();
}
 
Example #10
Source File: ChunkServlet.java    From Web-API with MIT License 6 votes vote down vote up
@GET
@ExplicitDetails
@Path("/{world}")
@Permission("list")
@ApiOperation(
        value = "List chunks",
        notes = "Gets a list of all the loaded chunks for the specified world.")
public List<CachedChunk> listChunks(
        @PathParam("world") @ApiParam("The uuid of the for which to get all chunks") CachedWorld world) {
    return WebAPI.runOnMain(() -> {
        Optional<World> optWorld = world.getLive();
        if (!optWorld.isPresent())
            throw new InternalServerErrorException("Could not get live world");

        World live = optWorld.get();
        List<CachedChunk> chunks = new ArrayList<>();

        Iterable<Chunk> iterable = live.getLoadedChunks();
        iterable.forEach(c -> chunks.add(new CachedChunk(c)));

        return chunks;
    });
}
 
Example #11
Source File: Utils.java    From EssentialCmds with MIT License 6 votes vote down vote up
public static void teleportPlayerToJail(Player player, int number)
{
	UUID worldUuid = UUID.fromString(Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "world").getString());
	double x = Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "X").getDouble();
	double y = Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "Y").getDouble();
	double z = Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "Z").getDouble();
	World world = Sponge.getServer().getWorld(worldUuid).orElse(null);

	if (world != null)
	{
		Location<World> location = new Location<World>(world, x, y, z);

		if (player.getWorld().getUniqueId().equals(worldUuid))
		{
			player.setLocation(location);
		}
		else
		{
			player.transferToWorld(world.getUniqueId(), location.getPosition());
		}
	}
}
 
Example #12
Source File: PlayerEventHandler.java    From GriefDefender with MIT License 6 votes vote down vote up
@Listener(order = Order.LAST, beforeModifications = true)
public void onPlayerPickupItem(ChangeInventoryEvent.Pickup.Pre event, @Root Player player) {
    if (!GDFlags.ITEM_PICKUP || !GriefDefenderPlugin.getInstance().claimsEnabledForWorld(player.getWorld().getUniqueId())) {
        return;
    }
    if (GriefDefenderPlugin.isTargetIdBlacklisted(Flags.ITEM_PICKUP.getName(), event.getTargetEntity(), player.getWorld().getProperties())) {
        return;
    }

    GDTimings.PLAYER_PICKUP_ITEM_EVENT.startTimingIfSync();
    final World world = player.getWorld();
    GDPlayerData playerData = this.dataStore.getOrCreatePlayerData(world, player.getUniqueId());
    Location<World> location = player.getLocation();
    GDClaim claim = this.dataStore.getClaimAtPlayer(playerData, location);
    if (GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.ITEM_PICKUP, player, event.getTargetEntity(), player, true) == Tristate.FALSE) {
        event.setCancelled(true);
    }

    GDTimings.PLAYER_PICKUP_ITEM_EVENT.stopTimingIfSync();
}
 
Example #13
Source File: PlayerEventHandler.java    From GriefDefender with MIT License 6 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPlayerUseItem(UseItemStackEvent.Start event, @First Player player) {
    if (!GDFlags.ITEM_USE || !GriefDefenderPlugin.getInstance().claimsEnabledForWorld(player.getWorld().getUniqueId())) {
        return;
    }
    if (GriefDefenderPlugin.isTargetIdBlacklisted(Flags.ITEM_USE.getName(), event.getItemStackInUse().getType(), player.getWorld().getProperties())) {
        return;
    }

    GDTimings.PLAYER_USE_ITEM_EVENT.startTimingIfSync();
    Location<World> location = player.getLocation();
    GDPlayerData playerData = this.dataStore.getOrCreatePlayerData(location.getExtent(), player.getUniqueId());
    GDClaim claim = this.dataStore.getClaimAtPlayer(playerData, location);

    final Tristate result = GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.ITEM_USE, player, event.getItemStackInUse().getType(), player, TrustTypes.ACCESSOR, true);
    if (result == Tristate.FALSE) {
        final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.PERMISSION_ITEM_USE,
                ImmutableMap.of(
                "item", event.getItemStackInUse().getType().getId()));
        GriefDefenderPlugin.sendClaimDenyMessage(claim, player,  message);
        event.setCancelled(true);
    }
    GDTimings.PLAYER_USE_ITEM_EVENT.stopTimingIfSync();
}
 
Example #14
Source File: RedProtectUtil.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
public int simuleTotalRegionSize(String player, Region r2) {
    int total = 0;
    int regs = 0;
    for (Location<World> loc : r2.get4Points(r2.getCenterY())) {
        Map<Integer, Region> pregs = RedProtect.get().rm.getGroupRegion(loc.getExtent().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
        pregs.remove(r2.getPrior());
        Region other;
        if (pregs.size() > 0) {
            other = pregs.get(Collections.max(pregs.keySet()));
        } else {
            continue;
        }
        if (!r2.getID().equals(other.getID()) && r2.getPrior() > other.getPrior() && other.isLeader(player)) {
            regs++;
        }
    }
    if (regs != 4) {
        total += r2.getArea();
    }
    return total;
}
 
Example #15
Source File: PlayerDataMigrator.java    From GriefDefender with MIT License 5 votes vote down vote up
private static PlayerStorageData createPlayerStorageData(World world, UUID playerUniqueId) {
    Path playerFilePath = null;
    if (BaseStorage.USE_GLOBAL_PLAYER_STORAGE) {
        playerFilePath = BaseStorage.globalPlayerDataPath.resolve(playerUniqueId.toString());
    } else {
        playerFilePath = BaseStorage.worldConfigMap.get(world.getUniqueId()).getPath().getParent().resolve("PlayerData").resolve(playerUniqueId.toString());
    }

    PlayerStorageData playerStorage = new PlayerStorageData(playerFilePath);
    return playerStorage;
}
 
Example #16
Source File: SetpvpWorldCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    World w = args.<World>getOne("world").get();
    Boolean state = args.<Boolean>getOne("state").get();
    w.getProperties().setPVPEnabled(state);
    Messages.send(src, "world.command.world.setpvp.success", "%world%", w.getName(), "%state%", state ? Messages.getFormatted(src, "world.enabled") : Messages.getFormatted(src, "world.disabled"));
    return CommandResult.success();
}
 
Example #17
Source File: Utils.java    From EssentialCmds with MIT License 5 votes vote down vote up
public static void setWarp(Transform<World> transform, String warpName)
{
	Configs.getConfig(warpsConfig).getNode("warps", warpName, "world").setValue(transform.getExtent().getUniqueId().toString());
	Configs.getConfig(warpsConfig).getNode("warps", warpName, "X").setValue(transform.getLocation().getX());
	Configs.getConfig(warpsConfig).getNode("warps", warpName, "Y").setValue(transform.getLocation().getY());
	Configs.getConfig(warpsConfig).getNode("warps", warpName, "Z").setValue(transform.getLocation().getZ());
	Configs.getConfig(warpsConfig).getNode("warps", warpName, "transform", "pitch").setValue(transform.getRotation().getX());
	Configs.getConfig(warpsConfig).getNode("warps", warpName, "transform", "yaw").setValue(transform.getRotation().getY());
	Configs.getConfig(warpsConfig).getNode("warps", warpName, "transform", "roll").setValue(transform.getRotation().getZ());

	Configs.saveConfig(warpsConfig);
}
 
Example #18
Source File: CachedTransform.java    From Web-API with MIT License 5 votes vote down vote up
public CachedTransform(Transform<World> transform) {
    super(null);

    this.world = cacheService.getWorld(transform.getExtent());
    this.position = transform.getPosition().clone();
    this.rotation = transform.getRotation().clone();
    this.scale = transform.getScale().clone();
}
 
Example #19
Source File: RedProtectUtil.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public void addProps(CommentedConfigurationNode fileDB, Region r) {
    String rname = r.getName();
    fileDB.getNode(rname, "name").setValue(rname);
    fileDB.getNode(rname, "lastvisit").setValue(r.getDate());
    fileDB.getNode(rname, "leaders").setValue(r.getLeaders().stream().map(t -> t.getUUID() + "@" + t.getPlayerName()).collect(Collectors.toList()));
    fileDB.getNode(rname, "admins").setValue(r.getAdmins().stream().map(t -> t.getUUID() + "@" + t.getPlayerName()).collect(Collectors.toList()));
    fileDB.getNode(rname, "members").setValue(r.getMembers().stream().map(t -> t.getUUID() + "@" + t.getPlayerName()).collect(Collectors.toList()));
    fileDB.getNode(rname, "priority").setValue(r.getPrior());
    fileDB.getNode(rname, "welcome").setValue(r.getWelcome());
    fileDB.getNode(rname, "world").setValue(r.getWorld());
    fileDB.getNode(rname, "maxX").setValue(r.getMaxMbrX());
    fileDB.getNode(rname, "maxZ").setValue(r.getMaxMbrZ());
    fileDB.getNode(rname, "minX").setValue(r.getMinMbrX());
    fileDB.getNode(rname, "minZ").setValue(r.getMinMbrZ());
    fileDB.getNode(rname, "maxY").setValue(r.getMaxY());
    fileDB.getNode(rname, "minY").setValue(r.getMinY());
    fileDB.getNode(rname, "candelete").setValue(r.canDelete());
    for (Map.Entry<String, Object> flag : r.getFlags().entrySet()) {
        fileDB.getNode(rname, "flags", flag.getKey()).setValue(flag.getValue());
    }
    fileDB.getNode(rname, "value").setValue(r.getValue());

    Location<World> loc = r.getTPPoint();
    if (loc != null) {
        int x = loc.getBlockX();
        int y = loc.getBlockY();
        int z = loc.getBlockZ();
        //float yaw = loc.getYaw();
        //float pitch = loc.getPitch();
        fileDB.getNode(rname, "tppoint").setValue(x + "," + y + "," + z/*+","+yaw+","+pitch*/);
    } else {
        fileDB.getNode(rname, "tppoint").setValue("");
    }
}
 
Example #20
Source File: BlockEventHandler.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onProjectileImpactBlock(CollideBlockEvent.Impact event) {
    if (!GPFlags.PROJECTILE_IMPACT_BLOCK || !(event.getSource() instanceof Entity)) {
        return;
    }

    final Entity source = (Entity) event.getSource();
    if (GriefPreventionPlugin.isSourceIdBlacklisted(ClaimFlag.PROJECTILE_IMPACT_BLOCK.toString(), source.getType().getId(), source.getWorld().getProperties())) {
        return;
    }

    final User user = CauseContextHelper.getEventUser(event);
    if (user == null) {
        return;
    }

    if (!GriefPreventionPlugin.instance.claimsEnabledForWorld(event.getImpactPoint().getExtent().getProperties())) {
        return;
    }

    GPTimings.PROJECTILE_IMPACT_BLOCK_EVENT.startTimingIfSync();
    Location<World> impactPoint = event.getImpactPoint();
    GPClaim targetClaim = null;
    GPPlayerData playerData = null;
    if (user instanceof Player) {
        playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(event.getTargetLocation().getExtent(), user.getUniqueId());
        targetClaim = this.dataStore.getClaimAtPlayer(playerData, impactPoint);
    } else {
        targetClaim = this.dataStore.getClaimAt(impactPoint);
    }

    Tristate result = GPPermissionHandler.getClaimPermission(event, impactPoint, targetClaim, GPPermissions.PROJECTILE_IMPACT_BLOCK, source, event.getTargetBlock(), user, TrustType.ACCESSOR, true);
    if (result == Tristate.FALSE) {
        event.setCancelled(true);
        GPTimings.PROJECTILE_IMPACT_BLOCK_EVENT.stopTimingIfSync();
        return;
    }

    GPTimings.PROJECTILE_IMPACT_BLOCK_EVENT.stopTimingIfSync();
}
 
Example #21
Source File: ExpandVertCommand.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public CommandSpec register() {
    return CommandSpec.builder()
            .description(Text.of("Command to expand a region from bedrock to sky."))
            .arguments(
                    GenericArguments.optional(GenericArguments.string(Text.of("regionName"))),
                    GenericArguments.optional(GenericArguments.world(Text.of("world")))
            )
            .permission("redprotect.command.expand-vert")
            .executor((src, args) -> {
                if (!(src instanceof Player)) {
                    HandleHelpPage(src, 1);
                } else {
                    Player player = (Player) src;
                    Region r = RedProtect.get().rm.getTopRegion(player.getLocation(), this.getClass().getName());

                    if (args.hasAny("regionName")) {
                        r = RedProtect.get().rm.getRegion(args.<String>getOne("regionName").get(), player.getWorld().getName());
                    }

                    if (args.hasAny("world")) {
                        r = RedProtect.get().rm.getRegion(args.<String>getOne("regionName").get(), args.<World>getOne("world").get().getName());
                    }

                    if (r == null) {
                        RedProtect.get().lang.sendMessage(player, "cmdmanager.region.todo.that");
                        return CommandResult.success();
                    }

                    if (!RedProtect.get().ph.hasRegionPermAdmin(player, "expand-vert", r)) {
                        RedProtect.get().lang.sendMessage(player, "no.permission");
                        return CommandResult.success();
                    }

                    r.setMaxY(Sponge.getServer().getWorld(r.getWorld()).get().getDimension().getHeight());
                    r.setMinY(0);
                }
                return CommandResult.success();
            }).build();
}
 
Example #22
Source File: ThunderCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkPermission(sender, WeatherPermissions.UC_WEATHER_WEATHER_SUN);
    World world;
    if (sender instanceof Locatable) {
        world = ((Locatable) sender).getWorld();
    } else {
        throw new ErrorMessageException(Messages.getFormatted(sender, "core.noplayer"));
    }
    world.setWeather(Weathers.THUNDER_STORM);
    Messages.send(sender, "weather.command.weather.success", "%weather%", "thunder", "%world%", world.getName());
    return CommandResult.success();
}
 
Example #23
Source File: EconomyManager.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public static long getRegionValue(Region r) {
    long regionCost = 0;
    World w = RedProtect.get().getServer().getWorld(r.getWorld()).get();
    int maxX = r.getMaxMbrX();
    int minX = r.getMinMbrX();
    int maxZ = r.getMaxMbrZ();
    int minZ = r.getMinMbrZ();
    for (int x = minX; x < maxX; x++) {
        for (int y = 0; y < 256; y++) {
            for (int z = minZ; z < maxZ; z++) {

                BlockSnapshot b = w.createSnapshot(x, y, z);
                if (b.getState().getType().equals(BlockTypes.AIR)) {
                    continue;
                }

                if (b.getLocation().get().getTileEntity().isPresent()) {
                    TileEntity invTile = b.getLocation().get().getTileEntity().get();
                    if (invTile instanceof TileEntityInventory) {
                        TileEntityInventory<?> inv = (TileEntityInventory<?>) invTile;
                        regionCost += getInvValue(inv.slots());
                    }
                } else {
                    regionCost += RedProtect.get().config.ecoRoot().items.values.get(b.getState().getType().getName());
                }
            }
        }
    }
    r.setValue(regionCost);
    return regionCost;
}
 
Example #24
Source File: BaseStorage.java    From GriefDefender with MIT License 5 votes vote down vote up
public GDClaimManager getClaimWorldManager(UUID worldUniqueId) {
    GDClaimManager claimWorldManager = null;
    if (worldUniqueId == null) {
        worldUniqueId = Sponge.getServer().getDefaultWorld().get().getUniqueId();
    }
    claimWorldManager = this.claimWorldManagers.get(worldUniqueId);

    if (claimWorldManager == null) {
        final WorldProperties defaultWorldProperties = Sponge.getServer().getDefaultWorld().get();
        final World world = Sponge.getServer().getWorld(worldUniqueId).orElse(Sponge.getServer().getWorld(defaultWorldProperties.getUniqueId()).get());
        registerWorld(world);
        claimWorldManager = this.claimWorldManagers.get(world.getUniqueId());
    }
    return claimWorldManager;
}
 
Example #25
Source File: GPApiProvider.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Override
public List<Claim> getAllPlayerClaims(UUID playerUniqueId) {
    List<Claim> claimList = new ArrayList<>();
    for (World world : Sponge.getServer().getWorlds()) {
        claimList.addAll(this.getClaimManager(world).getPlayerClaims(playerUniqueId));
    }

    return ImmutableList.copyOf(claimList);
}
 
Example #26
Source File: EnableTimeCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    World world;
    if (!args.hasAny("world")) {
        checkIfPlayer(sender);
        world = ((Player) sender).getWorld();
    } else {
        world = args.<World>getOne("world").get();
    }

    world.getProperties().setGameRule("doDaylightCycle", "true");
    Messages.send(sender, "time.command.time.enable");
    return CommandResult.success();
}
 
Example #27
Source File: ParticlesUtil.java    From EagleFactions with MIT License 5 votes vote down vote up
public static void spawnClaimParticles(final Claim claim)
{
	final Optional<World> optionalWorld = Sponge.getServer().getWorld(claim.getWorldUUID());
	if(!optionalWorld.isPresent())
		return;

	final World world = optionalWorld.get();
	final Vector3d position = getChunkCenter(world, claim.getChunkPosition());
	world.spawnParticles(ParticleEffect.builder().type(ParticleTypes.END_ROD).option(ParticleOptions.VELOCITY, new Vector3d(0, 0.15, 0)).quantity(400).offset(new Vector3d(8, 1, 8)).build(), position);
	world.playSound(SoundTypes.BLOCK_ENDERCHEST_OPEN, position, 5, -20);
}
 
Example #28
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 #29
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 #30
Source File: GDSpongeClaimSchematic.java    From GriefDefender with MIT License 5 votes vote down vote up
@Override
public Optional<ClaimSchematic> build() {
    checkNotNull(this.claim);
    checkNotNull(this.name);

    if (this.origin == null) {
        this.origin = new Vector3i(0, 0, 0);
    }

    final World world = ((GDClaim) this.claim).getWorld();
    final ArchetypeVolume volume = world.createArchetypeVolume(this.claim.getLesserBoundaryCorner(), this.claim.getGreaterBoundaryCorner(), this.origin);
    final Schematic schematic = Schematic.builder()
            .metaValue(Schematic.METADATA_NAME, this.name)
            .metaValue(Schematic.METADATA_DATE, Instant.now().toString())
            .metaValue("UUID", this.claim.getUniqueId().toString())
            .volume(volume)
            .build();
    this.schematic = schematic;
    DataContainer schematicData = DataTranslators.SCHEMATIC.translate(schematic);
    final Path schematicPath = GriefDefenderPlugin.getInstance().getSchematicWorldMap().get(world.getUniqueId()).resolve(this.claim.getUniqueId().toString());
    try {
        Files.createDirectories(schematicPath);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    File outputFile = schematicPath.resolve(this.name + ".schematic").toFile();
    try {
        DataFormats.NBT.writeTo(new GZIPOutputStream(new FileOutputStream(outputFile)), schematicData);
    } catch (Exception e) {
        e.printStackTrace();
        return Optional.empty();
    }

    final GDSpongeClaimSchematic claimSchematic = new GDSpongeClaimSchematic(this.claim, this.schematic, this.name, this.origin);
    ((GDClaim) this.claim).schematics.put(this.name, claimSchematic);
    return Optional.of(claimSchematic);
}