Merge branch 'v6' into feature/v6/json

# Conflicts:
#	Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java
#	Core/src/main/java/com/plotsquared/core/PlotSquared.java
#	Core/src/main/java/com/plotsquared/core/command/Add.java
#	Core/src/main/java/com/plotsquared/core/command/Auto.java
#	Core/src/main/java/com/plotsquared/core/command/Buy.java
#	Core/src/main/java/com/plotsquared/core/command/Template.java
#	Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java
#	Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java
#	Core/src/main/java/com/plotsquared/core/listener/PlotListener.java
#	Core/src/main/java/com/plotsquared/core/location/Location.java
#	Core/src/main/java/com/plotsquared/core/plot/Plot.java
#	Core/src/main/java/com/plotsquared/core/plot/PlotArea.java
#	Core/src/main/java/com/plotsquared/core/plot/PlotCluster.java
#	Core/src/main/java/com/plotsquared/core/plot/PlotId.java
#	Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java
#	Core/src/main/java/com/plotsquared/core/plot/flag/implementations/KeepFlag.java
#	Core/src/main/java/com/plotsquared/core/util/MainUtil.java
#	Core/src/main/java/com/plotsquared/core/util/PlayerManager.java
#	Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java
#	Core/src/main/java/com/plotsquared/core/util/query/PlotQuery.java
#	Core/src/main/java/com/plotsquared/core/util/query/SearchPlotProvider.java
This commit is contained in:
Alexander Söderberg 2020-07-19 14:32:31 +02:00
commit ed3eedd238
66 changed files with 1520 additions and 1405 deletions

View File

@ -48,6 +48,7 @@ import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.BukkitWorld; import com.plotsquared.bukkit.util.BukkitWorld;
import com.plotsquared.bukkit.util.SetGenCB; import com.plotsquared.bukkit.util.SetGenCB;
import com.plotsquared.bukkit.util.UpdateUtility; import com.plotsquared.bukkit.util.UpdateUtility;
import com.plotsquared.bukkit.util.task.BukkitTaskManager;
import com.plotsquared.bukkit.util.task.PaperTimeConverter; import com.plotsquared.bukkit.util.task.PaperTimeConverter;
import com.plotsquared.bukkit.util.task.SpigotTimeConverter; import com.plotsquared.bukkit.util.task.SpigotTimeConverter;
import com.plotsquared.bukkit.uuid.BungeePermsUUIDService; import com.plotsquared.bukkit.uuid.BungeePermsUUIDService;
@ -66,6 +67,7 @@ import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.ChatFormatter; import com.plotsquared.core.configuration.ChatFormatter;
import com.plotsquared.core.configuration.ConfigurationNode; import com.plotsquared.core.configuration.ConfigurationNode;
import com.plotsquared.core.configuration.ConfigurationSection; import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.ConfigurationUtil;
import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.configuration.file.YamlConfiguration; import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.database.DBFunc; import com.plotsquared.core.database.DBFunc;
@ -87,6 +89,8 @@ import com.plotsquared.core.plot.PlotAreaTerrainType;
import com.plotsquared.core.plot.PlotAreaType; import com.plotsquared.core.plot.PlotAreaType;
import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.comment.CommentManager; import com.plotsquared.core.plot.comment.CommentManager;
import com.plotsquared.core.plot.flag.implementations.ServerPlotFlag;
import com.plotsquared.core.plot.message.PlainChatManager;
import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.plot.world.SinglePlotArea; import com.plotsquared.core.plot.world.SinglePlotArea;
import com.plotsquared.core.plot.world.SinglePlotAreaManager; import com.plotsquared.core.plot.world.SinglePlotAreaManager;
@ -96,7 +100,7 @@ import com.plotsquared.core.setup.SettingsNodesWrapper;
import com.plotsquared.core.util.ConsoleColors; import com.plotsquared.core.util.ConsoleColors;
import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.util.PermHandler; import com.plotsquared.core.util.PermHandler;
import com.plotsquared.core.util.PlatformWorldManager; import com.plotsquared.core.util.PlatformWorldManager;
import com.plotsquared.core.util.PremiumVerification; import com.plotsquared.core.util.PremiumVerification;
@ -402,8 +406,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass;
final SQLiteUUIDService sqLiteUUIDService = new SQLiteUUIDService("user_cache.db"); final SQLiteUUIDService sqLiteUUIDService = new SQLiteUUIDService("user_cache.db");
final SQLiteUUIDService legacyUUIDService; final SQLiteUUIDService legacyUUIDService;
if (Settings.UUID.LEGACY_DATABASE_SUPPORT && MainUtil if (Settings.UUID.LEGACY_DATABASE_SUPPORT &&
.getFile(PlotSquared.platform().getDirectory(), "usercache.db").exists()) { FileUtils.getFile(PlotSquared.platform().getDirectory(), "usercache.db").exists()) {
legacyUUIDService = new SQLiteUUIDService("usercache.db"); legacyUUIDService = new SQLiteUUIDService("usercache.db");
} else { } else {
legacyUUIDService = null; legacyUUIDService = null;
@ -563,7 +567,7 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass;
} }
final Plot plot = area.getOwnedPlot(id); final Plot plot = area.getOwnedPlot(id);
if (plot != null) { if (plot != null) {
if (!MainUtil.isServerOwned(plot) || PlotPlayer.wrap(plot.getOwner()) == null) { if (!plot.getFlag(ServerPlotFlag.class) || PlotPlayer.wrap(plot.getOwner()) == null) {
if (world.getKeepSpawnInMemory()) { if (world.getKeepSpawnInMemory()) {
world.setKeepSpawnInMemory(false); world.setKeepSpawnInMemory(false);
return; return;
@ -826,7 +830,7 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass;
BukkitUtil.adapt(entity.getLocation()); BukkitUtil.adapt(entity.getLocation());
PlotArea area = pLoc.getPlotArea(); PlotArea area = pLoc.getPlotArea();
if (area != null) { if (area != null) {
PlotId currentPlotId = PlotId.of(area.getPlotAbs(pLoc)); PlotId currentPlotId = area.getPlotAbs(pLoc).getId();
if (!originalPlotId.equals(currentPlotId) && ( if (!originalPlotId.equals(currentPlotId) && (
currentPlotId == null || !area currentPlotId == null || !area
.getPlot(originalPlotId) .getPlot(originalPlotId)
@ -845,7 +849,7 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass;
BukkitUtil.adapt(entity.getLocation()); BukkitUtil.adapt(entity.getLocation());
PlotArea area = pLoc.getPlotArea(); PlotArea area = pLoc.getPlotArea();
if (area != null) { if (area != null) {
PlotId currentPlotId = PlotId.of(area.getPlotAbs(pLoc)); PlotId currentPlotId = area.getPlotAbs(pLoc).getId();
if (currentPlotId != null) { if (currentPlotId != null) {
entity.setMetadata("shulkerPlot", entity.setMetadata("shulkerPlot",
new FixedMetadataValue( new FixedMetadataValue(
@ -1043,8 +1047,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass;
String manager = worldConfig.getString("generator.plugin", getPluginName()); String manager = worldConfig.getString("generator.plugin", getPluginName());
PlotAreaBuilder builder = PlotAreaBuilder.newBuilder().plotManager(manager) PlotAreaBuilder builder = PlotAreaBuilder.newBuilder().plotManager(manager)
.generatorName(worldConfig.getString("generator.init", manager)) .generatorName(worldConfig.getString("generator.init", manager))
.plotAreaType(MainUtil.getType(worldConfig)) .plotAreaType(ConfigurationUtil.getType(worldConfig))
.terrainType(MainUtil.getTerrain(worldConfig)) .terrainType(ConfigurationUtil.getTerrain(worldConfig))
.settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null)) .settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null))
.worldName(worldName); .worldName(worldName);
getInjector().getInstance(SetupUtils.class).setupWorld(builder); getInjector().getInstance(SetupUtils.class).setupWorld(builder);

View File

@ -152,17 +152,17 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
this.stack = item.getItemStack(); this.stack = item.getItemStack();
return; return;
case "ITEM_FRAME": case "ITEM_FRAME":
this.x = Math.floor(this.x); this.x = Math.floor(this.getX());
this.y = Math.floor(this.y); this.y = Math.floor(this.getY());
this.z = Math.floor(this.z); this.z = Math.floor(this.getZ());
ItemFrame itemFrame = (ItemFrame) entity; ItemFrame itemFrame = (ItemFrame) entity;
this.dataByte = getOrdinal(Rotation.values(), itemFrame.getRotation()); this.dataByte = getOrdinal(Rotation.values(), itemFrame.getRotation());
this.stack = itemFrame.getItem().clone(); this.stack = itemFrame.getItem().clone();
return; return;
case "PAINTING": case "PAINTING":
this.x = Math.floor(this.x); this.x = Math.floor(this.getX());
this.y = Math.floor(this.y); this.y = Math.floor(this.getY());
this.z = Math.floor(this.z); this.z = Math.floor(this.getZ());
Painting painting = (Painting) entity; Painting painting = (Painting) entity;
Art art = painting.getArt(); Art art = painting.getArt();
this.dataByte = getOrdinal(BlockFace.values(), painting.getFacing()); this.dataByte = getOrdinal(BlockFace.values(), painting.getFacing());
@ -407,9 +407,9 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
this.lived.leashed = lived.isLeashed(); this.lived.leashed = lived.isLeashed();
if (this.lived.leashed) { if (this.lived.leashed) {
Location location = lived.getLeashHolder().getLocation(); Location location = lived.getLeashHolder().getLocation();
this.lived.leashX = (short) (this.x - location.getBlockX()); this.lived.leashX = (short) (this.getX() - location.getBlockX());
this.lived.leashY = (short) (this.y - location.getBlockY()); this.lived.leashY = (short) (this.getY() - location.getBlockY());
this.lived.leashZ = (short) (this.z - location.getBlockZ()); this.lived.leashZ = (short) (this.getZ() - location.getBlockZ());
} }
EntityEquipment equipment = lived.getEquipment(); EntityEquipment equipment = lived.getEquipment();
this.lived.equipped = equipment != null; this.lived.equipped = equipment != null;
@ -460,7 +460,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
} }
@Override public Entity spawn(World world, int xOffset, int zOffset) { @Override public Entity spawn(World world, int xOffset, int zOffset) {
Location location = new Location(world, this.x + xOffset, this.y, this.z + zOffset); Location location = new Location(world, this.getX() + xOffset, this.getY(), this.z + zOffset);
location.setYaw(this.yaw); location.setYaw(this.yaw);
location.setPitch(this.pitch); location.setPitch(this.pitch);
if (!this.getType().isSpawnable()) { if (!this.getType().isSpawnable()) {

View File

@ -67,9 +67,9 @@ public class TeleportEntityWrapper extends EntityWrapper {
// To account for offsets in the chunk manager // To account for offsets in the chunk manager
this.oldLocation = oldLocation.clone(); this.oldLocation = oldLocation.clone();
this.oldLocation.setX(this.x); this.oldLocation.setX(this.getX());
this.oldLocation.setY(this.y); this.oldLocation.setY(this.getY());
this.oldLocation.setZ(this.z); this.oldLocation.setZ(this.getZ());
this.gravityOld = this.getEntity().hasGravity(); this.gravityOld = this.getEntity().hasGravity();
this.getEntity().setGravity(false); this.getEntity().setGravity(false);

View File

@ -1005,7 +1005,7 @@ import java.util.regex.Pattern;
} }
} }
String partial = ChatColor.translateAlternateColorCodes('&', String partial = ChatColor.translateAlternateColorCodes('&',
format.replace("%plot_id%", id.x + ";" + id.y).replace("%sender%", sender)); format.replace("%plot_id%", id.getX() + ";" + id.getY()).replace("%sender%", sender));
if (plotPlayer.hasPermission("plots.chat.color")) { if (plotPlayer.hasPermission("plots.chat.color")) {
message = Captions.color(message); message = Captions.color(message);
} }
@ -1015,7 +1015,7 @@ import java.util.regex.Pattern;
} }
if (!spies.isEmpty()) { if (!spies.isEmpty()) {
String spyMessage = Captions.PLOT_CHAT_SPY_FORMAT.getTranslated() String spyMessage = Captions.PLOT_CHAT_SPY_FORMAT.getTranslated()
.replace("%plot_id%", id.x + ";" + id.y).replace("%sender%", sender) .replace("%plot_id%", id.getX() + ";" + id.getY()).replace("%sender%", sender)
.replace("%msg%", message); .replace("%msg%", message);
for (Player player : spies) { for (Player player : spies) {
player.sendMessage(spyMessage); player.sendMessage(spyMessage);

View File

@ -30,7 +30,7 @@ import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.flag.GlobalFlagContainer; import com.plotsquared.core.plot.flag.GlobalFlagContainer;
import com.plotsquared.core.plot.flag.PlotFlag; import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.PlayerManager;
import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.PlaceholderAPIPlugin;
import me.clip.placeholderapi.expansion.PlaceholderExpansion; import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -122,7 +122,7 @@ public class Placeholders extends PlaceholderExpansion {
} }
try { try {
return MainUtil.getName(plotOwner, false); return PlayerManager.getName(plotOwner, false);
} catch (final Exception ignored) {} } catch (final Exception ignored) {}
final String name = Bukkit.getOfflinePlayer(plotOwner).getName(); final String name = Bukkit.getOfflinePlayer(plotOwner).getName();

View File

@ -38,9 +38,9 @@ import com.plotsquared.core.plot.PlotManager;
import com.plotsquared.core.queue.LocalBlockQueue; import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.queue.ScopedLocalBlockQueue; import com.plotsquared.core.queue.ScopedLocalBlockQueue;
import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.RegionUtil; import com.plotsquared.core.util.RegionUtil;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.entity.EntityCategories; import com.plotsquared.core.util.entity.EntityCategories;
import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
@ -484,7 +484,7 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE;
@Override public void run(int[] value) { @Override public void run(int[] value) {
BlockVector2 loc = BlockVector2.at(value[0], value[1]); BlockVector2 loc = BlockVector2.at(value[0], value[1]);
PlotSquared.platform().getChunkManager().loadChunk(world, loc, false).thenRun(() -> { PlotSquared.platform().getChunkManager().loadChunk(world, loc, false).thenRun(() -> {
MainUtil.setBiome(world, value[2], value[3], value[4], value[5], biome); WorldUtil.setBiome(world, value[2], value[3], value[4], value[5], biome);
queue.refreshChunk(value[0], value[1]); queue.refreshChunk(value[0], value[1]);
}); });
} }

View File

@ -27,7 +27,7 @@ package com.plotsquared.bukkit.uuid;
import com.plotsquared.core.PlotSquared; import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.database.SQLite; import com.plotsquared.core.database.SQLite;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.uuid.UUIDMapping; import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService; import com.plotsquared.core.uuid.UUIDService;
@ -51,7 +51,7 @@ public class SQLiteUUIDService implements UUIDService, Consumer<List<UUIDMapping
public SQLiteUUIDService(final String fileName) { public SQLiteUUIDService(final String fileName) {
this.sqlite = this.sqlite =
new SQLite(MainUtil.getFile(PlotSquared.platform().getDirectory(), fileName)); new SQLite(FileUtils.getFile(PlotSquared.platform().getDirectory(), fileName));
try { try {
this.sqlite.openConnection(); this.sqlite.openConnection();
} catch (ClassNotFoundException | SQLException e) { } catch (ClassNotFoundException | SQLException e) {

View File

@ -61,8 +61,8 @@ import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.plot.world.SinglePlotArea; import com.plotsquared.core.plot.world.SinglePlotArea;
import com.plotsquared.core.plot.world.SinglePlotAreaManager; import com.plotsquared.core.plot.world.SinglePlotAreaManager;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.util.LegacyConverter; import com.plotsquared.core.util.LegacyConverter;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.ReflectionUtils; import com.plotsquared.core.util.ReflectionUtils;
import com.plotsquared.core.util.query.PlotQuery; import com.plotsquared.core.util.query.PlotQuery;
@ -512,7 +512,7 @@ public class PlotSquared {
} else { } else {
extra.add(plot); extra.add(plot);
} }
} else if (Math.abs(plot.getId().x) > 15446 || Math.abs(plot.getId().y) > 15446) { } else if (Math.abs(plot.getId().getX()) > 15446 || Math.abs(plot.getId().getY()) > 15446) {
extra.add(plot); extra.add(plot);
} else { } else {
overflow.add(plot); overflow.add(plot);
@ -587,7 +587,7 @@ public class PlotSquared {
} else { } else {
extra.add(plot); extra.add(plot);
} }
} else if (Math.abs(plot.getId().x) > 15446 || Math.abs(plot.getId().y) > 15446) { } else if (Math.abs(plot.getId().getX()) > 15446 || Math.abs(plot.getId().getY()) > 15446) {
extra.add(plot); extra.add(plot);
} else { } else {
overflow.add(plot); overflow.add(plot);
@ -727,8 +727,8 @@ public class PlotSquared {
} }
if (plot.getArea().removePlot(plot.getId())) { if (plot.getArea().removePlot(plot.getId())) {
PlotId last = (PlotId) plot.getArea().getMeta("lastPlot"); PlotId last = (PlotId) plot.getArea().getMeta("lastPlot");
int last_max = Math.max(Math.abs(last.x), Math.abs(last.y)); int last_max = Math.max(Math.abs(last.getX()), Math.abs(last.getY()));
int this_max = Math.max(Math.abs(plot.getId().x), Math.abs(plot.getId().y)); int this_max = Math.max(Math.abs(plot.getId().getX()), Math.abs(plot.getId().getY()));
if (this_max < last_max) { if (this_max < last_max) {
plot.getArea().setMeta("lastPlot", plot.getId()); plot.getArea().setMeta("lastPlot", plot.getId());
} }
@ -770,7 +770,7 @@ public class PlotSquared {
ConfigurationSection worldSection = this.worldConfiguration.getConfigurationSection(path); ConfigurationSection worldSection = this.worldConfiguration.getConfigurationSection(path);
PlotAreaType type; PlotAreaType type;
if (worldSection != null) { if (worldSection != null) {
type = MainUtil.getType(worldSection); type = ConfigurationUtil.getType(worldSection);
} else { } else {
type = PlotAreaType.NORMAL; type = PlotAreaType.NORMAL;
} }
@ -1117,7 +1117,7 @@ public class PlotSquared {
if (!output.exists()) { if (!output.exists()) {
output.mkdirs(); output.mkdirs();
} }
File newFile = MainUtil.getFile(output, folder + File.separator + file); File newFile = FileUtils.getFile(output, folder + File.separator + file);
if (newFile.exists()) { if (newFile.exists()) {
return; return;
} }
@ -1234,7 +1234,7 @@ public class PlotSquared {
database = new MySQL(Storage.MySQL.HOST, Storage.MySQL.PORT, Storage.MySQL.DATABASE, database = new MySQL(Storage.MySQL.HOST, Storage.MySQL.PORT, Storage.MySQL.DATABASE,
Storage.MySQL.USER, Storage.MySQL.PASSWORD); Storage.MySQL.USER, Storage.MySQL.PASSWORD);
} else if (Storage.SQLite.USE) { } else if (Storage.SQLite.USE) {
File file = MainUtil.getFile(platform.getDirectory(), Storage.SQLite.DB + ".db"); File file = FileUtils.getFile(platform.getDirectory(), Storage.SQLite.DB + ".db");
database = new SQLite(file); database = new SQLite(file);
} else { } else {
logger.error("[P2] No storage type is set. Disabling PlotSquared"); logger.error("[P2] No storage type is set. Disabling PlotSquared");

View File

@ -34,6 +34,7 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.TabCompletions; import com.plotsquared.core.util.TabCompletions;
import com.plotsquared.core.util.task.RunnableVal2; import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3; import com.plotsquared.core.util.task.RunnableVal3;
@ -74,7 +75,7 @@ public class Add extends Command {
checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage()); checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage());
final CompletableFuture<Boolean> future = new CompletableFuture<>(); final CompletableFuture<Boolean> future = new CompletableFuture<>();
MainUtil.getUUIDsFromString(args[0], (uuids, throwable) -> { PlayerManager.getUUIDsFromString(args[0], (uuids, throwable) -> {
if (throwable != null) { if (throwable != null) {
if (throwable instanceof TimeoutException) { if (throwable instanceof TimeoutException) {
player.sendMessage(TranslatableCaption.of("players.fetching_players_timeout")); player.sendMessage(TranslatableCaption.of("players.fetching_players_timeout"));
@ -95,19 +96,19 @@ public class Add extends Command {
Permissions.hasPermission(player, Captions.PERMISSION_TRUST_EVERYONE) || Permissions Permissions.hasPermission(player, Captions.PERMISSION_TRUST_EVERYONE) || Permissions
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST))) { .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST))) {
player.sendMessage(TranslatableCaption.of("errors.invalid_player"), player.sendMessage(TranslatableCaption.of("errors.invalid_player"),
Template.of("value", MainUtil.getName(uuid))); Template.of("value", PlayerManager.getName(uuid)));
iterator.remove(); iterator.remove();
continue; continue;
} }
if (plot.isOwner(uuid)) { if (plot.isOwner(uuid)) {
player.sendMessage(TranslatableCaption.of("member.already_added"), player.sendMessage(TranslatableCaption.of("member.already_added"),
Template.of("player", MainUtil.getName(uuid))); Template.of("player", PlayerManager.getName(uuid)));
iterator.remove(); iterator.remove();
continue; continue;
} }
if (plot.getMembers().contains(uuid)) { if (plot.getMembers().contains(uuid)) {
player.sendMessage(TranslatableCaption.of("member.already_added"), player.sendMessage(TranslatableCaption.of("member.already_added"),
Template.of("player", MainUtil.getName(uuid))); Template.of("player", PlayerManager.getName(uuid)));
iterator.remove(); iterator.remove();
continue; continue;
} }

View File

@ -48,6 +48,7 @@ import com.plotsquared.core.plot.PlotAreaType;
import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.setup.PlotAreaBuilder; import com.plotsquared.core.setup.PlotAreaBuilder;
import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
@ -172,7 +173,7 @@ public class Area extends SubCommand {
BlockVector3.at(playerSelectionMin.getX(), 0, playerSelectionMin.getZ()), BlockVector3.at(playerSelectionMin.getX(), 0, playerSelectionMin.getZ()),
BlockVector3.at(playerSelectionMax.getX(), 255, playerSelectionMax.getZ())); BlockVector3.at(playerSelectionMax.getX(), 255, playerSelectionMax.getZ()));
// There's only one plot in the area... // There's only one plot in the area...
final PlotId plotId = new PlotId(1, 1); final PlotId plotId = PlotId.of(1, 1);
final HybridPlotWorld hybridPlotWorld = this.hybridPlotWorldFactory.create(player.getLocation().getWorldName(), args[1], final HybridPlotWorld hybridPlotWorld = this.hybridPlotWorldFactory.create(player.getLocation().getWorldName(), args[1],
Objects.requireNonNull(PlotSquared.platform()).getDefaultGenerator(), plotId, plotId); Objects.requireNonNull(PlotSquared.platform()).getDefaultGenerator(), plotId, plotId);
// Plot size is the same as the region width // Plot size is the same as the region width
@ -189,7 +190,7 @@ public class Area extends SubCommand {
hybridPlotWorld.PLOT_HEIGHT = hybridPlotWorld.ROAD_HEIGHT = hybridPlotWorld.WALL_HEIGHT = playerSelectionMin.getBlockY(); hybridPlotWorld.PLOT_HEIGHT = hybridPlotWorld.ROAD_HEIGHT = hybridPlotWorld.WALL_HEIGHT = playerSelectionMin.getBlockY();
// No sign plz // No sign plz
hybridPlotWorld.setAllowSigns(false); hybridPlotWorld.setAllowSigns(false);
final File parentFile = MainUtil.getFile(PlotSquared.platform().getDirectory(), "schematics" + File.separator + final File parentFile = FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics" + File.separator +
"GEN_ROAD_SCHEMATIC" + File.separator + hybridPlotWorld.getWorldName() + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + hybridPlotWorld.getWorldName() + File.separator +
hybridPlotWorld.getId()); hybridPlotWorld.getId());
if (!parentFile.exists() && !parentFile.mkdirs()) { if (!parentFile.exists() && !parentFile.mkdirs()) {
@ -317,8 +318,8 @@ public class Area extends SubCommand {
PlotAreaBuilder builder = PlotAreaBuilder.ofPlotArea(area) PlotAreaBuilder builder = PlotAreaBuilder.ofPlotArea(area)
.plotManager(PlotSquared.platform().getPluginName()) .plotManager(PlotSquared.platform().getPluginName())
.generatorName(PlotSquared.platform().getPluginName()) .generatorName(PlotSquared.platform().getPluginName())
.minimumId(new PlotId(1, 1)) .minimumId(PlotId.of(1, 1))
.maximumId(new PlotId(numX, numZ)); .maximumId(PlotId.of(numX, numZ));
final String path = final String path =
"worlds." + area.getWorldName() + ".areas." + area.getId() + '-' "worlds." + area.getWorldName() + ".areas." + area.getId() + '-'
+ builder.minimumId() + '-' + builder.maximumId(); + builder.minimumId() + '-' + builder.maximumId();
@ -548,7 +549,7 @@ public class Area extends SubCommand {
PlotId min = area.getMin(); PlotId min = area.getMin();
PlotId max = area.getMax(); PlotId max = area.getMax();
name = area.getWorldName() + ';' + area.getId() + ';' + min + ';' + max; name = area.getWorldName() + ';' + area.getId() + ';' + min + ';' + max;
int size = (max.x - min.x + 1) * (max.y - min.y + 1); int size = (max.getX() - min.getX() + 1) * (max.getY() - min.getY() + 1);
percent = claimed == 0 ? 0 : size / (double) claimed; percent = claimed == 0 ? 0 : size / (double) claimed;
region = area.getRegion().toString(); region = area.getRegion().toString();
} else { } else {
@ -602,7 +603,7 @@ public class Area extends SubCommand {
PlotId max = area.getMax(); PlotId max = area.getMax();
name = area.getWorldName() + ';' + area.getId() + ';' + min + ';' name = area.getWorldName() + ';' + area.getId() + ';' + min + ';'
+ max; + max;
int size = (max.x - min.x + 1) * (max.y - min.y + 1); int size = (max.getX() - min.getX() + 1) * (max.getY() - min.getY() + 1);
percent = claimed == 0 ? 0 : size / (double) claimed; percent = claimed == 0 ? 0 : size / (double) claimed;
region = area.getRegion().toString(); region = area.getRegion().toString();
} else { } else {

View File

@ -64,7 +64,7 @@ public abstract class Argument<T> {
} }
}; };
public static final Argument<PlotId> PlotID = public static final Argument<PlotId> PlotID =
new Argument<PlotId>("PlotID", new PlotId(-6, 3)) { new Argument<PlotId>("PlotID", PlotId.of(-6, 3)) {
@Override public PlotId parse(String in) { @Override public PlotId parse(String in) {
return PlotId.fromString(in); return PlotId.fromString(in);
} }

View File

@ -25,6 +25,7 @@
*/ */
package com.plotsquared.core.command; package com.plotsquared.core.command;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints; import com.google.common.primitives.Ints;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared; import com.plotsquared.core.PlotSquared;
@ -55,7 +56,7 @@ import net.kyori.adventure.text.minimessage.Template;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.ArrayList; import java.util.List;
import java.util.Set; import java.util.Set;
@CommandDeclaration(command = "auto", @CommandDeclaration(command = "auto",
@ -79,10 +80,6 @@ public class Auto extends SubCommand {
this.econHandler = econHandler; this.econHandler = econHandler;
} }
@Deprecated public static PlotId getNextPlotId(PlotId id, int step) {
return id.getNextId(step);
}
public static boolean checkAllowedPlots(PlotPlayer player, PlotArea plotarea, public static boolean checkAllowedPlots(PlotPlayer player, PlotArea plotarea,
@Nullable Integer allowedPlots, int sizeX, int sizeZ) { @Nullable Integer allowedPlots, int sizeX, int sizeZ) {
if (allowedPlots == null) { if (allowedPlots == null) {
@ -303,21 +300,21 @@ public class Auto extends SubCommand {
return false; return false;
} }
while (true) { while (true) {
PlotId start = plotarea.getMeta("lastPlot", new PlotId(0, 0)).getNextId(1); PlotId start = plotarea.getMeta("lastPlot", PlotId.of(0, 0)).getNextId();
PlotId end = new PlotId(start.x + size_x - 1, start.y + size_z - 1); PlotId end = PlotId.of(start.getX() + size_x - 1, start.getY() + size_z - 1);
if (plotarea.canClaim(player, start, end)) { if (plotarea.canClaim(player, start, end)) {
plotarea.setMeta("lastPlot", start); plotarea.setMeta("lastPlot", start);
for (int i = start.x; i <= end.x; i++) {
for (int j = start.y; j <= end.y; j++) { for (final PlotId plotId : PlotId.PlotRangeIterator.range(start, end)) {
Plot plot = plotarea.getPlotAbs(new PlotId(i, j)); final Plot plot = plotarea.getPlot(plotId);
boolean teleport = i == end.x && j == end.y; if (plot == null) {
if (plot == null) { return false;
return false;
}
plot.claim(player, teleport, null);
} }
plot.claim(player, plotId.equals(end), null);
} }
ArrayList<PlotId> plotIds = MainUtil.getPlotSelectionIds(start, end);
final List<PlotId> plotIds = Lists.newArrayList((Iterable<? extends PlotId>)
PlotId.PlotRangeIterator.range(start, end));
final PlotId pos1 = plotIds.get(0); final PlotId pos1 = plotIds.get(0);
final PlotAutoMergeEvent mergeEvent = this.eventDispatcher final PlotAutoMergeEvent mergeEvent = this.eventDispatcher
.callAutoMerge(plotarea.getPlotAbs(pos1), plotIds); .callAutoMerge(plotarea.getPlotAbs(pos1), plotIds);

View File

@ -37,7 +37,6 @@ import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.plot.flag.implementations.PriceFlag; import com.plotsquared.core.plot.flag.implementations.PriceFlag;
import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.task.RunnableVal2; import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3; import com.plotsquared.core.util.task.RunnableVal3;
import net.kyori.adventure.text.minimessage.Template; import net.kyori.adventure.text.minimessage.Template;
@ -77,7 +76,7 @@ public class Buy extends Command {
sendUsage(player); sendUsage(player);
return CompletableFuture.completedFuture(false); return CompletableFuture.completedFuture(false);
} }
plot = check(MainUtil.getPlotFromString(player, args[0], true), null); plot = check(Plot.getPlotFromString(player, args[0], true), null);
} else { } else {
plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT); plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT);
} }

View File

@ -137,9 +137,9 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(player, Captions.ALIAS_IS_TAKEN); MainUtil.sendMessage(player, Captions.ALIAS_IS_TAKEN);
return false; return false;
} }
if (pos2.x < pos1.x || pos2.y < pos1.y) { if (pos2.getX() < pos1.getX() || pos2.getY() < pos1.getY()) {
PlotId tmp = new PlotId(Math.min(pos1.x, pos2.x), Math.min(pos1.y, pos2.y)); PlotId tmp = PlotId.of(Math.min(pos1.getX(), pos2.getX()), Math.min(pos1.getY(), pos2.getY()));
pos2 = new PlotId(Math.max(pos1.x, pos2.x), Math.max(pos1.y, pos2.y)); pos2 = PlotId.of(Math.max(pos1.getX(), pos2.getX()), Math.max(pos1.getY(), pos2.getY()));
pos1 = tmp; pos1 = tmp;
} }
//check if overlap //check if overlap
@ -265,9 +265,9 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID); MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID);
return false; return false;
} }
if (pos2.x < pos1.x || pos2.y < pos1.y) { if (pos2.getX() < pos1.getX() || pos2.getY() < pos1.getY()) {
pos1 = new PlotId(Math.min(pos1.x, pos2.x), Math.min(pos1.y, pos2.y)); pos1 = PlotId.of(Math.min(pos1.getX(), pos2.getX()), Math.min(pos1.getY(), pos2.getY()));
pos2 = new PlotId(Math.max(pos1.x, pos2.x), Math.max(pos1.y, pos2.y)); pos2 = PlotId.of(Math.max(pos1.getX(), pos2.getX()), Math.max(pos1.getY(), pos2.getY()));
} }
// check if in cluster // check if in cluster
PlotArea area = player.getApplicablePlotArea(); PlotArea area = player.getApplicablePlotArea();
@ -326,7 +326,7 @@ public class Cluster extends SubCommand {
} else { } else {
current = player.getPlayerClusterCount(player.getLocation().getWorldName()); current = player.getPlayerClusterCount(player.getLocation().getWorldName());
} }
current -= cluster.getArea() + (1 + pos2.x - pos1.x) * (1 + pos2.y - pos1.y); current -= cluster.getArea() + (1 + pos2.getX() - pos1.getX()) * (1 + pos2.getY() - pos1.getY());
int allowed = Permissions.hasPermissionRange(player, Captions.PERMISSION_CLUSTER, int allowed = Permissions.hasPermissionRange(player, Captions.PERMISSION_CLUSTER,
Settings.Limit.MAX_PLOTS); Settings.Limit.MAX_PLOTS);
if (current + cluster.getArea() > allowed) { if (current + cluster.getArea() > allowed) {
@ -454,7 +454,7 @@ public class Cluster extends SubCommand {
cluster.getName()); cluster.getName());
} }
for (final Plot plot : PlotQuery.newQuery().inWorld(player2.getLocation() for (final Plot plot : PlotQuery.newQuery().inWorld(player2.getLocation()
.getWorldName()).ownedBy(uuid).asCollection()) { .getWorldName()).ownedBy(uuid)) {
PlotCluster current = plot.getCluster(); PlotCluster current = plot.getCluster();
if (current != null && current.equals(cluster)) { if (current != null && current.equals(cluster)) {
plot.unclaim(); plot.unclaim();
@ -513,7 +513,7 @@ public class Cluster extends SubCommand {
DBFunc.removeInvited(cluster, uuid); DBFunc.removeInvited(cluster, uuid);
MainUtil.sendMessage(player, Captions.CLUSTER_REMOVED, cluster.getName()); MainUtil.sendMessage(player, Captions.CLUSTER_REMOVED, cluster.getName());
for (final Plot plot : PlotQuery.newQuery().inWorld(player.getLocation().getWorldName()) for (final Plot plot : PlotQuery.newQuery().inWorld(player.getLocation().getWorldName())
.ownedBy(uuid).asCollection()) { .ownedBy(uuid)) {
PlotCluster current = plot.getCluster(); PlotCluster current = plot.getCluster();
if (current != null && current.equals(cluster)) { if (current != null && current.equals(cluster)) {
plot.unclaim(); plot.unclaim();
@ -648,8 +648,8 @@ public class Cluster extends SubCommand {
owner = username; owner = username;
} }
String name = cluster.getName(); String name = cluster.getName();
String size = (cluster.getP2().x - cluster.getP1().x + 1) + "x" + ( String size = (cluster.getP2().getX() - cluster.getP1().getX() + 1) + "x" + (
cluster.getP2().y - cluster.getP1().y + 1); cluster.getP2().getY() - cluster.getP1().getY() + 1);
String rights = cluster.isAdded(player.getUUID()) + ""; String rights = cluster.isAdded(player.getUUID()) + "";
String message = Captions.CLUSTER_INFO.getTranslated(); String message = Captions.CLUSTER_INFO.getTranslated();
message = message.replaceAll("%id%", id); message = message.replaceAll("%id%", id);

View File

@ -56,7 +56,7 @@ public class Comment extends SubCommand {
// Attempt to extract a plot out of the first argument // Attempt to extract a plot out of the first argument
Plot plot = null; Plot plot = null;
if (!CommentManager.inboxes.containsKey(args[0].toLowerCase(Locale.ENGLISH))) { if (!CommentManager.inboxes.containsKey(args[0].toLowerCase(Locale.ENGLISH))) {
plot = MainUtil.getPlotFromString(player, args[0], false); plot = Plot.getPlotFromString(player, args[0], false);
} }
int index; int index;

View File

@ -137,13 +137,13 @@ public class Condense extends SubCommand {
} }
List<PlotId> toMove = new ArrayList<>(getPlots(allPlots, radius)); List<PlotId> toMove = new ArrayList<>(getPlots(allPlots, radius));
final List<PlotId> free = new ArrayList<>(); final List<PlotId> free = new ArrayList<>();
PlotId start = new PlotId(0, 0); PlotId start = PlotId.of(0, 0);
while (start.x <= minimumRadius && start.y <= minimumRadius) { while (start.getX() <= minimumRadius && start.getY() <= minimumRadius) {
Plot plot = area.getPlotAbs(start); Plot plot = area.getPlotAbs(start);
if (plot != null && !plot.hasOwner()) { if (plot != null && !plot.hasOwner()) {
free.add(plot.getId()); free.add(plot.getId());
} }
start = Auto.getNextPlotId(start, 1); start = start.getNextId();
} }
if (free.isEmpty() || toMove.isEmpty()) { if (free.isEmpty() || toMove.isEmpty()) {
MainUtil.sendMessage(player, "NO FREE PLOTS FOUND"); MainUtil.sendMessage(player, "NO FREE PLOTS FOUND");
@ -248,8 +248,8 @@ public class Condense extends SubCommand {
public Set<PlotId> getPlots(Collection<Plot> plots, int radius) { public Set<PlotId> getPlots(Collection<Plot> plots, int radius) {
HashSet<PlotId> outside = new HashSet<>(); HashSet<PlotId> outside = new HashSet<>();
for (Plot plot : plots) { for (Plot plot : plots) {
if (plot.getId().x > radius || plot.getId().x < -radius || plot.getId().y > radius if (plot.getId().getX() > radius || plot.getId().getX() < -radius || plot.getId().getY() > radius
|| plot.getId().y < -radius) { || plot.getId().getY() < -radius) {
outside.add(plot.getId()); outside.add(plot.getId());
} }
} }

View File

@ -58,7 +58,7 @@ public class Copy extends SubCommand {
sendUsage(player); sendUsage(player);
return false; return false;
} }
Plot plot2 = MainUtil.getPlotFromString(player, args[0], true); Plot plot2 = Plot.getPlotFromString(player, args[0], true);
if (plot2 == null) { if (plot2 == null) {
return false; return false;
} }

View File

@ -42,6 +42,7 @@ import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.plot.world.SinglePlotArea; import com.plotsquared.core.plot.world.SinglePlotArea;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.query.PlotQuery; import com.plotsquared.core.util.query.PlotQuery;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
@ -125,7 +126,7 @@ public class DatabaseCommand extends SubCommand {
.sendMessage(player, "/plot database import <sqlite file> [prefix]"); .sendMessage(player, "/plot database import <sqlite file> [prefix]");
return false; return false;
} }
File file = MainUtil.getFile(PlotSquared.platform().getDirectory(), File file = FileUtils.getFile(PlotSquared.platform().getDirectory(),
args[1].endsWith(".db") ? args[1] : args[1] + ".db"); args[1].endsWith(".db") ? args[1] : args[1] + ".db");
if (!file.exists()) { if (!file.exists()) {
MainUtil.sendMessage(player, "&6Database does not exist: " + file); MainUtil.sendMessage(player, "&6Database does not exist: " + file);
@ -158,9 +159,7 @@ public class DatabaseCommand extends SubCommand {
newId.toCommaSeparatedString()); newId.toCommaSeparatedString());
worldFile.renameTo(newFile); worldFile.renameTo(newFile);
} }
id.x = newId.x; plot.setId(newId.copy());
id.y = newId.y;
id.recalculateHash();
plot.setArea(pa); plot.setArea(pa);
plots.add(plot); plots.add(plot);
continue; continue;
@ -202,7 +201,7 @@ public class DatabaseCommand extends SubCommand {
return MainUtil.sendMessage(player, "/plot database sqlite [file]"); return MainUtil.sendMessage(player, "/plot database sqlite [file]");
} }
File sqliteFile = File sqliteFile =
MainUtil.getFile(PlotSquared.platform().getDirectory(), args[1] + ".db"); FileUtils.getFile(PlotSquared.platform().getDirectory(), args[1] + ".db");
implementation = new SQLite(sqliteFile); implementation = new SQLite(sqliteFile);
break; break;
default: default:

View File

@ -50,6 +50,7 @@ import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.SchematicHandler; import com.plotsquared.core.util.SchematicHandler;
@ -327,7 +328,7 @@ public class DebugExec extends SubCommand {
return false; return false;
case "addcmd": case "addcmd":
try { try {
final String cmd = StringMan.join(Files.readLines(MainUtil.getFile(new File( final String cmd = StringMan.join(Files.readLines(FileUtils.getFile(new File(
PlotSquared.platform().getDirectory() + File.separator PlotSquared.platform().getDirectory() + File.separator
+ Settings.Paths.SCRIPTS), args[1]), StandardCharsets.UTF_8), + Settings.Paths.SCRIPTS), args[1]), StandardCharsets.UTF_8),
System.getProperty("line.separator")); System.getProperty("line.separator"));
@ -359,7 +360,7 @@ public class DebugExec extends SubCommand {
async = true; async = true;
case "run": case "run":
try { try {
script = StringMan.join(Files.readLines(MainUtil.getFile(new File( script = StringMan.join(Files.readLines(FileUtils.getFile(new File(
PlotSquared.platform().getDirectory() + File.separator PlotSquared.platform().getDirectory() + File.separator
+ Settings.Paths.SCRIPTS), args[1]), StandardCharsets.UTF_8), + Settings.Paths.SCRIPTS), args[1]), StandardCharsets.UTF_8),
System.getProperty("line.separator")); System.getProperty("line.separator"));

View File

@ -70,7 +70,7 @@ public class DebugImportWorlds extends Command {
return CompletableFuture.completedFuture(false); return CompletableFuture.completedFuture(false);
} }
SinglePlotArea area = ((SinglePlotAreaManager) this.plotAreaManager).getArea(); SinglePlotArea area = ((SinglePlotAreaManager) this.plotAreaManager).getArea();
PlotId id = new PlotId(0, 0); PlotId id = PlotId.of(0, 0);
File container = PlotSquared.platform().getWorldContainer(); File container = PlotSquared.platform().getWorldContainer();
if (container.equals(new File("."))) { if (container.equals(new File("."))) {
player.sendMessage( player.sendMessage(
@ -92,7 +92,7 @@ public class DebugImportWorlds extends Command {
UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8));
} }
while (new File(container, id.toCommaSeparatedString()).exists()) { while (new File(container, id.toCommaSeparatedString()).exists()) {
id = Auto.getNextPlotId(id, 1); id = id.getNextId();
} }
File newDir = new File(container, id.toCommaSeparatedString()); File newDir = new File(container, id.toCommaSeparatedString());
if (folder.renameTo(newDir)) { if (folder.renameTo(newDir)) {

View File

@ -37,6 +37,7 @@ import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.TabCompletions; import com.plotsquared.core.util.TabCompletions;
import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.WorldUtil;
import com.sk89q.worldedit.world.gamemode.GameModes; import com.sk89q.worldedit.world.gamemode.GameModes;
@ -86,7 +87,7 @@ public class Deny extends SubCommand {
return true; return true;
} }
MainUtil.getUUIDsFromString(args[0], (uuids, throwable) -> { PlayerManager.getUUIDsFromString(args[0], (uuids, throwable) -> {
if (throwable instanceof TimeoutException) { if (throwable instanceof TimeoutException) {
MainUtil.sendMessage(player, Captions.FETCHING_PLAYERS_TIMEOUT); MainUtil.sendMessage(player, Captions.FETCHING_PLAYERS_TIMEOUT);
} else if (throwable != null || uuids.isEmpty()) { } else if (throwable != null || uuids.isEmpty()) {
@ -96,12 +97,12 @@ public class Deny extends SubCommand {
if (uuid == DBFunc.EVERYONE && !( if (uuid == DBFunc.EVERYONE && !(
Permissions.hasPermission(player, Captions.PERMISSION_DENY_EVERYONE) || Permissions Permissions.hasPermission(player, Captions.PERMISSION_DENY_EVERYONE) || Permissions
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DENY))) { .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DENY))) {
MainUtil.sendMessage(player, Captions.INVALID_PLAYER, MainUtil.getName(uuid)); MainUtil.sendMessage(player, Captions.INVALID_PLAYER, PlayerManager.getName(uuid));
} else if (plot.isOwner(uuid)) { } else if (plot.isOwner(uuid)) {
MainUtil.sendMessage(player, Captions.CANT_REMOVE_OWNER, MainUtil.getName(uuid)); MainUtil.sendMessage(player, Captions.CANT_REMOVE_OWNER, PlayerManager.getName(uuid));
return; return;
} else if (plot.getDenied().contains(uuid)) { } else if (plot.getDenied().contains(uuid)) {
MainUtil.sendMessage(player, Captions.ALREADY_ADDED, MainUtil.getName(uuid)); MainUtil.sendMessage(player, Captions.ALREADY_ADDED, PlayerManager.getName(uuid));
return; return;
} else { } else {
if (uuid != DBFunc.EVERYONE) { if (uuid != DBFunc.EVERYONE) {

View File

@ -33,13 +33,16 @@ import com.plotsquared.core.database.DBFunc;
import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.RunnableVal2; import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3; import com.plotsquared.core.util.task.RunnableVal3;
import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
@CommandDeclaration(command = "grant", @CommandDeclaration(command = "grant",
category = CommandCategory.CLAIMING, category = CommandCategory.CLAIMING,
@ -70,44 +73,51 @@ public class Grant extends Command {
if (args.length > 2) { if (args.length > 2) {
break; break;
} }
MainUtil.getUUIDsFromString(args[1], (uuids, throwable) -> { PlayerManager.getUUIDsFromString(args[1], (uuids, throwable) -> {
if (throwable instanceof TimeoutException) { if (throwable instanceof TimeoutException) {
MainUtil.sendMessage(player, Captions.FETCHING_PLAYERS_TIMEOUT); MainUtil.sendMessage(player, Captions.FETCHING_PLAYERS_TIMEOUT);
} else if (throwable != null || uuids.size() != 1) { } else if (throwable != null || uuids.size() != 1) {
MainUtil.sendMessage(player, Captions.INVALID_PLAYER); MainUtil.sendMessage(player, Captions.INVALID_PLAYER);
} else { } else {
final UUID uuid = uuids.toArray(new UUID[0])[0]; final UUID uuid = uuids.toArray(new UUID[0])[0];
MainUtil.getPersistentMeta(uuid, final Consumer<byte[]> result = array -> {
"grantedPlots", new RunnableVal<byte[]>() { if (arg0.equals("check")) { // check
@Override public void run(byte[] array) { int granted;
if (arg0.equals("check")) { // check if (array == null) {
int granted; granted = 0;
if (array == null) { } else {
granted = 0; granted = Ints.fromByteArray(array);
} else { }
granted = Ints.fromByteArray(array); Captions.GRANTED_PLOTS.send(player, granted);
} } else { // add
Captions.GRANTED_PLOTS.send(player, granted); int amount;
} else { // add if (array == null) {
int amount; amount = 1;
if (array == null) { } else {
amount = 1; amount = 1 + Ints.fromByteArray(array);
} else { }
amount = 1 + Ints.fromByteArray(array); boolean replace = array != null;
} String key = "grantedPlots";
boolean replace = array != null; byte[] rawData = Ints.toByteArray(amount);
String key = "grantedPlots";
byte[] rawData = Ints.toByteArray(amount);
PlotPlayer online = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); PlotPlayer online = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid);
if (online != null) { if (online != null) {
online.setPersistentMeta(key, rawData); online.setPersistentMeta(key, rawData);
} else { } else {
DBFunc.addPersistentMeta(uuid, key, rawData, replace); DBFunc.addPersistentMeta(uuid, key, rawData, replace);
}
} }
} }
}); };
PlotPlayer<?> pp = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid);
if (pp != null) {
result.accept(player.getPersistentMeta("grantedPlots"));
} else {
DBFunc.getPersistentMeta(uuid, new RunnableVal<Map<String, byte[]>>() {
@Override public void run(Map<String, byte[]> value) {
result.accept(value.get("grantedPlots"));
}
});
}
} }
}); });
return CompletableFuture.completedFuture(true); return CompletableFuture.completedFuture(true);

View File

@ -127,7 +127,7 @@ public class HomeCommand extends Command {
break; break;
} }
// either plot id or alias // either plot id or alias
Plot fromId = MainUtil.getPlotFromString(player, identifier, false); Plot fromId = Plot.getPlotFromString(player, identifier, false);
if (fromId != null && fromId.isOwner(player.getUUID())) { if (fromId != null && fromId.isOwner(player.getUUID())) {
// it was a valid plot id // it was a valid plot id
basePlotOnly = false; basePlotOnly = false;

View File

@ -32,7 +32,6 @@ import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.flag.implementations.HideInfoFlag; import com.plotsquared.core.plot.flag.implementations.HideInfoFlag;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.task.RunnableVal;
@CommandDeclaration(command = "info", @CommandDeclaration(command = "info",
aliases = "i", aliases = "i",
@ -60,10 +59,10 @@ public class Info extends SubCommand {
case "owner": case "owner":
case "rating": case "rating":
case "likes": case "likes":
plot = MainUtil.getPlotFromString(player, null, false); plot = Plot.getPlotFromString(player, null, false);
break; break;
default: default:
plot = MainUtil.getPlotFromString(player, arg, false); plot = Plot.getPlotFromString(player, arg, false);
if (args.length == 2) { if (args.length == 2) {
arg = args[1]; arg = args[1];
} else { } else {
@ -118,7 +117,7 @@ public class Info extends SubCommand {
// Unclaimed? // Unclaimed?
if (!hasOwner && !containsEveryone && !trustedEveryone) { if (!hasOwner && !containsEveryone && !trustedEveryone) {
MainUtil.sendMessage(player, Captions.PLOT_INFO_UNCLAIMED, MainUtil.sendMessage(player, Captions.PLOT_INFO_UNCLAIMED,
plot.getId().x + ";" + plot.getId().y); plot.getId().getX() + ";" + plot.getId().getY());
return true; return true;
} }
String info = Captions.PLOT_INFO_FORMAT.getTranslated(); String info = Captions.PLOT_INFO_FORMAT.getTranslated();
@ -141,13 +140,9 @@ public class Info extends SubCommand {
} else { } else {
full = false; full = false;
} }
MainUtil.format(info, plot, player, full, new RunnableVal<String>() { plot.format(info, player, full).thenAcceptAsync(value ->
@Override public void run(String value) { player.sendMessage(Captions.PLOT_INFO_HEADER.getTranslated() + '\n' + value + '\n'
MainUtil.sendMessage(player, + Captions.PLOT_INFO_FOOTER.getTranslated()));
Captions.PLOT_INFO_HEADER.getTranslated() + '\n' + value + '\n'
+ Captions.PLOT_INFO_FOOTER.getTranslated(), false);
}
});
return true; return true;
} }

View File

@ -36,6 +36,7 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.TabCompletions; import com.plotsquared.core.util.TabCompletions;
import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.WorldUtil;
@ -79,7 +80,7 @@ public class Kick extends SubCommand {
return false; return false;
} }
MainUtil.getUUIDsFromString(args[0], (uuids, throwable) -> { PlayerManager.getUUIDsFromString(args[0], (uuids, throwable) -> {
if (throwable instanceof TimeoutException) { if (throwable instanceof TimeoutException) {
MainUtil.sendMessage(player, Captions.FETCHING_PLAYERS_TIMEOUT); MainUtil.sendMessage(player, Captions.FETCHING_PLAYERS_TIMEOUT);
} else if (throwable != null || uuids.isEmpty()) { } else if (throwable != null || uuids.isEmpty()) {

View File

@ -42,6 +42,7 @@ import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.StringComparison; import com.plotsquared.core.util.StringComparison;
import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.StringMan;
import com.plotsquared.core.util.TabCompletions; import com.plotsquared.core.util.TabCompletions;
@ -373,11 +374,11 @@ public class ListCmd extends SubCommand {
} }
PlotMessage trusted = new PlotMessage().text(Captions.color( PlotMessage trusted = new PlotMessage().text(Captions.color(
Captions.PLOT_INFO_TRUSTED.getTranslated() Captions.PLOT_INFO_TRUSTED.getTranslated()
.replaceAll("%trusted%", MainUtil.getPlayerList(plot.getTrusted())))) .replaceAll("%trusted%", PlayerManager.getPlayerList(plot.getTrusted()))))
.color("$1"); .color("$1");
PlotMessage members = new PlotMessage().text(Captions.color( PlotMessage members = new PlotMessage().text(Captions.color(
Captions.PLOT_INFO_MEMBERS.getTranslated() Captions.PLOT_INFO_MEMBERS.getTranslated()
.replaceAll("%members%", MainUtil.getPlayerList(plot.getMembers())))) .replaceAll("%members%", PlayerManager.getPlayerList(plot.getMembers()))))
.color("$1"); .color("$1");
message.text("[").color("$3").text(i + "") message.text("[").color("$3").text(i + "")
.command("/plot visit " + plot.getArea() + ";" + plot.getId()) .command("/plot visit " + plot.getArea() + ";" + plot.getId())

View File

@ -82,7 +82,7 @@ public class Move extends SubCommand {
PlotArea area = this.plotAreaManager.getPlotAreaByString(args[0]); PlotArea area = this.plotAreaManager.getPlotAreaByString(args[0]);
Plot plot2; Plot plot2;
if (area == null) { if (area == null) {
plot2 = MainUtil.getPlotFromString(player, args[0], true); plot2 = Plot.getPlotFromString(player, args[0], true);
if (plot2 == null) { if (plot2 == null) {
return CompletableFuture.completedFuture(false); return CompletableFuture.completedFuture(false);
} }

View File

@ -38,6 +38,7 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import net.kyori.adventure.text.minimessage.Template; import net.kyori.adventure.text.minimessage.Template;
@ -108,9 +109,9 @@ public class Owner extends SetCommand {
MainUtil.sendMessage(player, Captions.SET_OWNER); MainUtil.sendMessage(player, Captions.SET_OWNER);
return; return;
} }
final PlotPlayer other = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); final PlotPlayer<?> other = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid);
if (plot.isOwner(uuid)) { if (plot.isOwner(uuid)) {
Captions.ALREADY_OWNER.send(player, MainUtil.getName(uuid)); Captions.ALREADY_OWNER.send(player, PlayerManager.getName(uuid));
return; return;
} }
if (!force && !Permissions if (!force && !Permissions

View File

@ -35,6 +35,7 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.TabCompletions; import com.plotsquared.core.util.TabCompletions;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
@ -76,7 +77,7 @@ public class Remove extends SubCommand {
return true; return true;
} }
MainUtil.getUUIDsFromString(args[0], (uuids, throwable) -> { PlayerManager.getUUIDsFromString(args[0], (uuids, throwable) -> {
int count = 0; int count = 0;
if (throwable instanceof TimeoutException) { if (throwable instanceof TimeoutException) {
MainUtil.sendMessage(player, Captions.FETCHING_PLAYERS_TIMEOUT); MainUtil.sendMessage(player, Captions.FETCHING_PLAYERS_TIMEOUT);

View File

@ -96,7 +96,7 @@ public class Save extends SubCommand {
PlotId id = plot.getId(); PlotId id = plot.getId();
String world1 = plot.getArea().toString().replaceAll(";", "-") String world1 = plot.getArea().toString().replaceAll(";", "-")
.replaceAll("[^A-Za-z0-9]", ""); .replaceAll("[^A-Za-z0-9]", "");
final String file = time + '_' + world1 + '_' + id.x + '_' + id.y + '_' + size; final String file = time + '_' + world1 + '_' + id.getX() + '_' + id.getY() + '_' + size;
UUID uuid = player.getUUID(); UUID uuid = player.getUUID();
schematicHandler.upload(value, uuid, file, new RunnableVal<URL>() { schematicHandler.upload(value, uuid, file, new RunnableVal<URL>() {
@Override public void run(URL url) { @Override public void run(URL url) {

View File

@ -63,7 +63,7 @@ public class Swap extends SubCommand {
sendUsage(player); sendUsage(player);
return CompletableFuture.completedFuture(false); return CompletableFuture.completedFuture(false);
} }
Plot plot2 = MainUtil.getPlotFromString(player, args[0], true); Plot plot2 = Plot.getPlotFromString(player, args[0], true);
if (plot2 == null) { if (plot2 == null) {
return CompletableFuture.completedFuture(false); return CompletableFuture.completedFuture(false);
} }

View File

@ -58,7 +58,7 @@ public class Target extends SubCommand {
Plot target = null; Plot target = null;
if (StringMan.isEqualIgnoreCaseToAny(args[0], "near", "nearest")) { if (StringMan.isEqualIgnoreCaseToAny(args[0], "near", "nearest")) {
int distance = Integer.MAX_VALUE; int distance = Integer.MAX_VALUE;
for (Plot plot : PlotQuery.newQuery().inWorld(location.getWorldName()).asCollection()) { for (Plot plot : PlotQuery.newQuery().inWorld(location.getWorldName())) {
double current = plot.getCenterSynchronous().getEuclideanDistanceSquared(location); double current = plot.getCenterSynchronous().getEuclideanDistanceSquared(location);
if (current < distance) { if (current < distance) {
distance = (int) current; distance = (int) current;
@ -69,7 +69,7 @@ public class Target extends SubCommand {
MainUtil.sendMessage(player, Captions.FOUND_NO_PLOTS); MainUtil.sendMessage(player, Captions.FOUND_NO_PLOTS);
return false; return false;
} }
} else if ((target = MainUtil.getPlotFromString(player, args[0], true)) == null) { } else if ((target = Plot.getPlotFromString(player, args[0], true)) == null) {
return false; return false;
} }
target.getCenter(player::setCompassTarget); target.getCenter(player::setCompassTarget);

View File

@ -27,6 +27,9 @@ package com.plotsquared.core.command;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared; import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.ConfigurationUtil;
import com.plotsquared.core.inject.annotations.WorldConfig;
import com.plotsquared.core.inject.annotations.WorldFile;
import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.ConfigurationNode; import com.plotsquared.core.configuration.ConfigurationNode;
import com.plotsquared.core.configuration.ConfigurationSection; import com.plotsquared.core.configuration.ConfigurationSection;
@ -44,6 +47,7 @@ import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.setup.PlotAreaBuilder; import com.plotsquared.core.setup.PlotAreaBuilder;
import com.plotsquared.core.setup.SettingsNodesWrapper; import com.plotsquared.core.setup.SettingsNodesWrapper;
import com.plotsquared.core.util.FileBytes; import com.plotsquared.core.util.FileBytes;
import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.SetupUtils; import com.plotsquared.core.util.SetupUtils;
import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.WorldUtil;
@ -90,7 +94,7 @@ public class Template extends SubCommand {
public static boolean extractAllFiles(String world, String template) { public static boolean extractAllFiles(String world, String template) {
try { try {
File folder = File folder =
MainUtil.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.TEMPLATES); FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.TEMPLATES);
if (!folder.exists()) { if (!folder.exists()) {
return false; return false;
} }
@ -144,8 +148,7 @@ public class Template extends SubCommand {
} }
public static void zipAll(String world, Set<FileBytes> files) throws IOException { public static void zipAll(String world, Set<FileBytes> files) throws IOException {
File output = File output = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.TEMPLATES);
MainUtil.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.TEMPLATES);
output.mkdirs(); output.mkdirs();
try (FileOutputStream fos = new FileOutputStream( try (FileOutputStream fos = new FileOutputStream(
output + File.separator + world + ".template"); output + File.separator + world + ".template");
@ -194,7 +197,7 @@ public class Template extends SubCommand {
.sendMessage(player, "&cInvalid template file: " + args[2] + ".template"); .sendMessage(player, "&cInvalid template file: " + args[2] + ".template");
return false; return false;
} }
File worldFile = MainUtil.getFile(PlotSquared.platform().getDirectory(), File worldFile = FileUtils.getFile(PlotSquared.platform().getDirectory(),
Settings.Paths.TEMPLATES + File.separator + "tmp-data.yml"); Settings.Paths.TEMPLATES + File.separator + "tmp-data.yml");
YamlConfiguration worldConfig = YamlConfiguration.loadConfiguration(worldFile); YamlConfiguration worldConfig = YamlConfiguration.loadConfiguration(worldFile);
this.worldConfiguration.set("worlds." + world, worldConfig.get("")); this.worldConfiguration.set("worlds." + world, worldConfig.get(""));
@ -208,8 +211,8 @@ public class Template extends SubCommand {
worldConfig.getString("generator.plugin", PlotSquared.platform().getPluginName()); worldConfig.getString("generator.plugin", PlotSquared.platform().getPluginName());
String generator = worldConfig.getString("generator.init", manager); String generator = worldConfig.getString("generator.init", manager);
PlotAreaBuilder builder = PlotAreaBuilder.newBuilder() PlotAreaBuilder builder = PlotAreaBuilder.newBuilder()
.plotAreaType(MainUtil.getType(worldConfig)) .plotAreaType(ConfigurationUtil.getType(worldConfig))
.terrainType(MainUtil.getTerrain(worldConfig)) .terrainType(ConfigurationUtil.getTerrain(worldConfig))
.plotManager(manager) .plotManager(manager)
.generatorName(generator) .generatorName(generator)
.settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null)) .settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null))

View File

@ -173,7 +173,7 @@ public class Trim extends SubCommand {
int bz = cbz << 4; int bz = cbz << 4;
CuboidRegion region = CuboidRegion region =
RegionUtil.createRegion(bx, bx + 511, bz, bz + 511); RegionUtil.createRegion(bx, bx + 511, bz, bz + 511);
for (Plot plot : PlotQuery.newQuery().inWorld(world).asCollection()) { for (Plot plot : PlotQuery.newQuery().inWorld(world)) {
Location bot = plot.getBottomAbs(); Location bot = plot.getBottomAbs();
Location top = plot.getExtendedTopAbs(); Location top = plot.getExtendedTopAbs();
CuboidRegion plotReg = RegionUtil CuboidRegion plotReg = RegionUtil

View File

@ -34,6 +34,7 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.TabCompletions; import com.plotsquared.core.util.TabCompletions;
import com.plotsquared.core.util.task.RunnableVal2; import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3; import com.plotsquared.core.util.task.RunnableVal3;
@ -76,7 +77,7 @@ public class Trust extends Command {
checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage()); checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage());
final CompletableFuture<Boolean> future = new CompletableFuture<>(); final CompletableFuture<Boolean> future = new CompletableFuture<>();
MainUtil.getUUIDsFromString(args[0], (uuids, throwable) -> { PlayerManager.getUUIDsFromString(args[0], (uuids, throwable) -> {
if (throwable != null) { if (throwable != null) {
if (throwable instanceof TimeoutException) { if (throwable instanceof TimeoutException) {
Captions.FETCHING_PLAYERS_TIMEOUT.send(player); Captions.FETCHING_PLAYERS_TIMEOUT.send(player);
@ -94,17 +95,17 @@ public class Trust extends Command {
if (uuid == DBFunc.EVERYONE && !( if (uuid == DBFunc.EVERYONE && !(
Permissions.hasPermission(player, Captions.PERMISSION_TRUST_EVERYONE) || Permissions Permissions.hasPermission(player, Captions.PERMISSION_TRUST_EVERYONE) || Permissions
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST))) { .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST))) {
MainUtil.sendMessage(player, Captions.INVALID_PLAYER, MainUtil.getName(uuid)); MainUtil.sendMessage(player, Captions.INVALID_PLAYER, PlayerManager.getName(uuid));
iterator.remove(); iterator.remove();
continue; continue;
} }
if (currentPlot.isOwner(uuid)) { if (currentPlot.isOwner(uuid)) {
MainUtil.sendMessage(player, Captions.ALREADY_ADDED, MainUtil.getName(uuid)); MainUtil.sendMessage(player, Captions.ALREADY_ADDED, PlayerManager.getName(uuid));
iterator.remove(); iterator.remove();
continue; continue;
} }
if (currentPlot.getTrusted().contains(uuid)) { if (currentPlot.getTrusted().contains(uuid)) {
MainUtil.sendMessage(player, Captions.ALREADY_ADDED, MainUtil.getName(uuid)); MainUtil.sendMessage(player, Captions.ALREADY_ADDED, PlayerManager.getName(uuid));
iterator.remove(); iterator.remove();
continue; continue;
} }

View File

@ -39,6 +39,7 @@ import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.TabCompletions; import com.plotsquared.core.util.TabCompletions;
import com.plotsquared.core.util.query.PlotQuery; import com.plotsquared.core.util.query.PlotQuery;
import com.plotsquared.core.util.query.SortingStrategy; import com.plotsquared.core.util.query.SortingStrategy;
@ -185,7 +186,7 @@ public class Visit extends Command {
final PlotArea finalSortByArea = sortByArea; final PlotArea finalSortByArea = sortByArea;
int finalPage1 = page; int finalPage1 = page;
MainUtil.getUUIDsFromString(args[0], (uuids, throwable) -> { PlayerManager.getUUIDsFromString(args[0], (uuids, throwable) -> {
if (throwable instanceof TimeoutException) { if (throwable instanceof TimeoutException) {
Captions.FETCHING_PLAYERS_TIMEOUT.send(player); Captions.FETCHING_PLAYERS_TIMEOUT.send(player);
} else if (throwable != null || uuids.size() != 1) { } else if (throwable != null || uuids.size() != 1) {
@ -227,7 +228,7 @@ public class Visit extends Command {
}); });
} else { } else {
// Try to parse a plot // Try to parse a plot
final Plot plot = MainUtil.getPlotFromString(player, finalArgs[0], true); final Plot plot = Plot.getPlotFromString(player, finalArgs[0], true);
if (plot != null) { if (plot != null) {
this.visit(player, PlotQuery.newQuery().withPlot(plot), null, confirm, whenDone, 1); this.visit(player, PlotQuery.newQuery().withPlot(plot), null, confirm, whenDone, 1);
} }

View File

@ -26,12 +26,19 @@
package com.plotsquared.core.configuration; package com.plotsquared.core.configuration;
import com.plotsquared.core.plot.BlockBucket; import com.plotsquared.core.plot.BlockBucket;
import com.plotsquared.core.plot.PlotAreaTerrainType;
import com.plotsquared.core.plot.PlotAreaType;
import com.plotsquared.core.util.MathMan;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes; import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Supplier;
/** /**
* Main Configuration Utility * Main Configuration Utility
@ -99,6 +106,29 @@ public class ConfigurationUtil {
} }
}; };
private static <T> T getValueFromConfig(ConfigurationSection config, String path,
IntFunction<Optional<T>> intParser, Function<String, Optional<T>> textualParser,
Supplier<T> defaultValue) {
String value = config.getString(path);
if (value == null) {
return defaultValue.get();
}
if (MathMan.isInteger(value)) {
return intParser.apply(Integer.parseInt(value)).orElseGet(defaultValue);
}
return textualParser.apply(value).orElseGet(defaultValue);
}
public static PlotAreaType getType(ConfigurationSection config) {
return getValueFromConfig(config, "generator.type", PlotAreaType::fromLegacyInt,
PlotAreaType::fromString, () -> PlotAreaType.NORMAL);
}
public static PlotAreaTerrainType getTerrain(ConfigurationSection config) {
return getValueFromConfig(config, "generator.terrain", PlotAreaTerrainType::fromLegacyInt,
PlotAreaTerrainType::fromString, () -> PlotAreaTerrainType.NONE);
}
public static final class UnknownBlockException extends IllegalArgumentException { public static final class UnknownBlockException extends IllegalArgumentException {

View File

@ -46,6 +46,7 @@ import com.plotsquared.core.plot.flag.GlobalFlagContainer;
import com.plotsquared.core.plot.flag.PlotFlag; import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.plot.flag.types.BlockTypeListFlag; import com.plotsquared.core.plot.flag.types.BlockTypeListFlag;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.HashUtil;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.StringMan;
import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.RunnableVal;
@ -572,8 +573,8 @@ public class SQLManager implements AbstractDB {
addPlotTask(plot, new UniqueStatement("setOwner") { addPlotTask(plot, new UniqueStatement("setOwner") {
@Override public void set(PreparedStatement statement) throws SQLException { @Override public void set(PreparedStatement statement) throws SQLException {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.setInt(2, plot.getId().x); statement.setInt(2, plot.getId().getX());
statement.setInt(3, plot.getId().y); statement.setInt(3, plot.getId().getY());
statement.setString(4, plot.getArea().toString()); statement.setString(4, plot.getArea().toString());
} }
@ -609,7 +610,7 @@ public class SQLManager implements AbstractDB {
int id = result.getInt("id"); int id = result.getInt("id");
int x = result.getInt("plot_id_x"); int x = result.getInt("plot_id_x");
int y = result.getInt("plot_id_z"); int y = result.getInt("plot_id_z");
PlotId plotId = new PlotId(x, y); PlotId plotId = PlotId.of(x, y);
Plot plot = plotMap.get(plotId); Plot plot = plotMap.get(plotId);
idMap.put(plotId, id); idMap.put(plotId, id);
if (plot != null) { if (plot != null) {
@ -758,8 +759,8 @@ public class SQLManager implements AbstractDB {
@Override public void setMySQL(PreparedStatement stmt, int i, Plot plot) @Override public void setMySQL(PreparedStatement stmt, int i, Plot plot)
throws SQLException { throws SQLException {
stmt.setInt(i * 5 + 1, plot.getId().x); stmt.setInt(i * 5 + 1, plot.getId().getX());
stmt.setInt(i * 5 + 2, plot.getId().y); stmt.setInt(i * 5 + 2, plot.getId().getY());
try { try {
stmt.setString(i * 5 + 3, plot.getOwnerAbs().toString()); stmt.setString(i * 5 + 3, plot.getOwnerAbs().toString());
} catch (SQLException ignored) { } catch (SQLException ignored) {
@ -772,8 +773,8 @@ public class SQLManager implements AbstractDB {
@Override public void setSQLite(PreparedStatement stmt, int i, Plot plot) @Override public void setSQLite(PreparedStatement stmt, int i, Plot plot)
throws SQLException { throws SQLException {
stmt.setNull(i * 6 + 1, 4); stmt.setNull(i * 6 + 1, 4);
stmt.setInt(i * 6 + 2, plot.getId().x); stmt.setInt(i * 6 + 2, plot.getId().getX());
stmt.setInt(i * 6 + 3, plot.getId().y); stmt.setInt(i * 6 + 3, plot.getId().getY());
try { try {
stmt.setString(i * 6 + 4, plot.getOwnerAbs().toString()); stmt.setString(i * 6 + 4, plot.getOwnerAbs().toString());
} catch (SQLException ignored) { } catch (SQLException ignored) {
@ -784,8 +785,8 @@ public class SQLManager implements AbstractDB {
} }
@Override public void setSQL(PreparedStatement stmt, Plot plot) throws SQLException { @Override public void setSQL(PreparedStatement stmt, Plot plot) throws SQLException {
stmt.setInt(1, plot.getId().x); stmt.setInt(1, plot.getId().getX());
stmt.setInt(2, plot.getId().y); stmt.setInt(2, plot.getId().getY());
stmt.setString(3, plot.getOwnerAbs().toString()); stmt.setString(3, plot.getOwnerAbs().toString());
stmt.setString(4, plot.getArea().toString()); stmt.setString(4, plot.getArea().toString());
stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); stmt.setTimestamp(5, new Timestamp(plot.getTimestamp()));
@ -933,7 +934,7 @@ public class SQLManager implements AbstractDB {
preparedStatement.setString(7, legacySettings.settings.getAlias()); preparedStatement.setString(7, legacySettings.settings.getAlias());
} }
boolean[] merged = legacySettings.settings.getMerged(); boolean[] merged = legacySettings.settings.getMerged();
int hash = MainUtil.hash(merged); int hash = HashUtil.hash(merged);
preparedStatement.setInt(8, hash); preparedStatement.setInt(8, hash);
BlockLoc loc = legacySettings.settings.getPosition(); BlockLoc loc = legacySettings.settings.getPosition();
String position; String position;
@ -1015,14 +1016,14 @@ public class SQLManager implements AbstractDB {
public void createPlotSafe(final Plot plot, final Runnable success, final Runnable failure) { public void createPlotSafe(final Plot plot, final Runnable success, final Runnable failure) {
addPlotTask(plot, new UniqueStatement("createPlotSafe_" + plot.hashCode()) { addPlotTask(plot, new UniqueStatement("createPlotSafe_" + plot.hashCode()) {
@Override public void set(PreparedStatement statement) throws SQLException { @Override public void set(PreparedStatement statement) throws SQLException {
statement.setInt(1, plot.getId().x); statement.setInt(1, plot.getId().getX());
statement.setInt(2, plot.getId().y); statement.setInt(2, plot.getId().getY());
statement.setString(3, plot.getOwnerAbs().toString()); statement.setString(3, plot.getOwnerAbs().toString());
statement.setString(4, plot.getArea().toString()); statement.setString(4, plot.getArea().toString());
statement.setTimestamp(5, new Timestamp(plot.getTimestamp())); statement.setTimestamp(5, new Timestamp(plot.getTimestamp()));
statement.setString(6, plot.getArea().toString()); statement.setString(6, plot.getArea().toString());
statement.setInt(7, plot.getId().x); statement.setInt(7, plot.getId().getX());
statement.setInt(8, plot.getId().y); statement.setInt(8, plot.getId().getY());
} }
@Override public PreparedStatement get() throws SQLException { @Override public PreparedStatement get() throws SQLException {
@ -1084,8 +1085,8 @@ public class SQLManager implements AbstractDB {
@Override public void createPlotAndSettings(final Plot plot, Runnable whenDone) { @Override public void createPlotAndSettings(final Plot plot, Runnable whenDone) {
addPlotTask(plot, new UniqueStatement("createPlotAndSettings_" + plot.hashCode()) { addPlotTask(plot, new UniqueStatement("createPlotAndSettings_" + plot.hashCode()) {
@Override public void set(PreparedStatement statement) throws SQLException { @Override public void set(PreparedStatement statement) throws SQLException {
statement.setInt(1, plot.getId().x); statement.setInt(1, plot.getId().getX());
statement.setInt(2, plot.getId().y); statement.setInt(2, plot.getId().getY());
statement.setString(3, plot.getOwnerAbs().toString()); statement.setString(3, plot.getOwnerAbs().toString());
statement.setString(4, plot.getArea().toString()); statement.setString(4, plot.getArea().toString());
statement.setTimestamp(5, new Timestamp(plot.getTimestamp())); statement.setTimestamp(5, new Timestamp(plot.getTimestamp()));
@ -1435,10 +1436,10 @@ public class SQLManager implements AbstractDB {
try (PreparedStatement stmt = this.connection.prepareStatement( try (PreparedStatement stmt = this.connection.prepareStatement(
"SELECT `id` FROM `" + this.prefix "SELECT `id` FROM `" + this.prefix
+ "cluster` WHERE `pos1_x` = ? AND `pos1_z` = ? AND `pos2_x` = ? AND `pos2_z` = ? AND `world` = ? ORDER BY `timestamp` ASC")) { + "cluster` WHERE `pos1_x` = ? AND `pos1_z` = ? AND `pos2_x` = ? AND `pos2_z` = ? AND `world` = ? ORDER BY `timestamp` ASC")) {
stmt.setInt(1, cluster.getP1().x); stmt.setInt(1, cluster.getP1().getX());
stmt.setInt(2, cluster.getP1().y); stmt.setInt(2, cluster.getP1().getY());
stmt.setInt(3, cluster.getP2().x); stmt.setInt(3, cluster.getP2().getX());
stmt.setInt(4, cluster.getP2().y); stmt.setInt(4, cluster.getP2().getY());
stmt.setString(5, cluster.area.toString()); stmt.setString(5, cluster.area.toString());
try (ResultSet resultSet = stmt.executeQuery()) { try (ResultSet resultSet = stmt.executeQuery()) {
c_id = Integer.MAX_VALUE; c_id = Integer.MAX_VALUE;
@ -1474,8 +1475,8 @@ public class SQLManager implements AbstractDB {
try (PreparedStatement statement = this.connection.prepareStatement( try (PreparedStatement statement = this.connection.prepareStatement(
"SELECT `id` FROM `" + this.prefix "SELECT `id` FROM `" + this.prefix
+ "plot` WHERE `plot_id_x` = ? AND `plot_id_z` = ? AND world = ? ORDER BY `timestamp` ASC")) { + "plot` WHERE `plot_id_x` = ? AND `plot_id_z` = ? AND world = ? ORDER BY `timestamp` ASC")) {
statement.setInt(1, plot.getId().x); statement.setInt(1, plot.getId().getX());
statement.setInt(2, plot.getId().y); statement.setInt(2, plot.getId().getY());
statement.setString(3, plot.getArea().toString()); statement.setString(3, plot.getArea().toString());
try (ResultSet resultSet = statement.executeQuery()) { try (ResultSet resultSet = statement.executeQuery()) {
id = Integer.MAX_VALUE; id = Integer.MAX_VALUE;
@ -1744,7 +1745,7 @@ public class SQLManager implements AbstractDB {
+ this.prefix + "plot`")) { + this.prefix + "plot`")) {
ArrayList<Integer> toDelete = new ArrayList<>(); ArrayList<Integer> toDelete = new ArrayList<>();
while (resultSet.next()) { while (resultSet.next()) {
PlotId plot_id = new PlotId(resultSet.getInt("plot_id_x"), PlotId plot_id = PlotId.of(resultSet.getInt("plot_id_x"),
resultSet.getInt("plot_id_z")); resultSet.getInt("plot_id_z"));
id = resultSet.getInt("id"); id = resultSet.getInt("id");
String areaID = resultSet.getString("world"); String areaID = resultSet.getString("world");
@ -2048,7 +2049,7 @@ public class SQLManager implements AbstractDB {
plot.getSettings().setMerged(merged); plot.getSettings().setMerged(merged);
addPlotTask(plot, new UniqueStatement("setMerged") { addPlotTask(plot, new UniqueStatement("setMerged") {
@Override public void set(PreparedStatement statement) throws SQLException { @Override public void set(PreparedStatement statement) throws SQLException {
int hash = MainUtil.hash(merged); int hash = HashUtil.hash(merged);
statement.setInt(1, hash); statement.setInt(1, hash);
statement.setInt(2, getId(plot)); statement.setInt(2, getId(plot));
} }
@ -2093,8 +2094,8 @@ public class SQLManager implements AbstractDB {
@Override public void movePlot(final Plot original, final Plot newPlot) { @Override public void movePlot(final Plot original, final Plot newPlot) {
addPlotTask(original, new UniqueStatement("movePlot") { addPlotTask(original, new UniqueStatement("movePlot") {
@Override public void set(PreparedStatement statement) throws SQLException { @Override public void set(PreparedStatement statement) throws SQLException {
statement.setInt(1, newPlot.getId().x); statement.setInt(1, newPlot.getId().getX());
statement.setInt(2, newPlot.getId().y); statement.setInt(2, newPlot.getId().getY());
statement.setString(3, newPlot.getArea().toString()); statement.setString(3, newPlot.getArea().toString());
statement.setInt(4, getId(original)); statement.setInt(4, getId(original));
} }
@ -2244,7 +2245,7 @@ public class SQLManager implements AbstractDB {
try (ResultSet r = stmt.executeQuery()) { try (ResultSet r = stmt.executeQuery()) {
ids = new HashSet<>(); ids = new HashSet<>();
while (r.next()) { while (r.next()) {
PlotId plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); PlotId plot_id = PlotId.of(r.getInt("plot_id_x"), r.getInt("plot_id_z"));
if (plots.contains(plot_id)) { if (plots.contains(plot_id)) {
ids.add(r.getInt("id")); ids.add(r.getInt("id"));
} }
@ -2258,7 +2259,7 @@ public class SQLManager implements AbstractDB {
for (Iterator<PlotId> iterator = plots.iterator(); iterator.hasNext(); ) { for (Iterator<PlotId> iterator = plots.iterator(); iterator.hasNext(); ) {
PlotId plotId = iterator.next(); PlotId plotId = iterator.next();
iterator.remove(); iterator.remove();
PlotId id = new PlotId(plotId.x, plotId.y); PlotId id = PlotId.of(plotId.getX(), plotId.getY());
area.removePlot(id); area.removePlot(id);
} }
}); });
@ -2694,9 +2695,9 @@ public class SQLManager implements AbstractDB {
int id; int id;
while (resultSet.next()) { while (resultSet.next()) {
PlotId pos1 = PlotId pos1 =
new PlotId(resultSet.getInt("pos1_x"), resultSet.getInt("pos1_z")); PlotId.of(resultSet.getInt("pos1_x"), resultSet.getInt("pos1_z"));
PlotId pos2 = PlotId pos2 =
new PlotId(resultSet.getInt("pos2_x"), resultSet.getInt("pos2_z")); PlotId.of(resultSet.getInt("pos2_x"), resultSet.getInt("pos2_z"));
id = resultSet.getInt("id"); id = resultSet.getInt("id");
String areaid = resultSet.getString("world"); String areaid = resultSet.getString("world");
if (!areas.contains(areaid)) { if (!areas.contains(areaid)) {
@ -2853,10 +2854,10 @@ public class SQLManager implements AbstractDB {
@Override public void createCluster(final PlotCluster cluster) { @Override public void createCluster(final PlotCluster cluster) {
addClusterTask(cluster, new UniqueStatement("createCluster_" + cluster.hashCode()) { addClusterTask(cluster, new UniqueStatement("createCluster_" + cluster.hashCode()) {
@Override public void set(PreparedStatement statement) throws SQLException { @Override public void set(PreparedStatement statement) throws SQLException {
statement.setInt(1, cluster.getP1().x); statement.setInt(1, cluster.getP1().getX());
statement.setInt(2, cluster.getP1().y); statement.setInt(2, cluster.getP1().getY());
statement.setInt(3, cluster.getP2().x); statement.setInt(3, cluster.getP2().getX());
statement.setInt(4, cluster.getP2().y); statement.setInt(4, cluster.getP2().getY());
statement.setString(5, cluster.owner.toString()); statement.setString(5, cluster.owner.toString());
statement.setString(6, cluster.area.toString()); statement.setString(6, cluster.area.toString());
} }
@ -2894,17 +2895,17 @@ public class SQLManager implements AbstractDB {
} }
@Override public void resizeCluster(final PlotCluster current, PlotId min, PlotId max) { @Override public void resizeCluster(final PlotCluster current, PlotId min, PlotId max) {
final PlotId pos1 = new PlotId(current.getP1().x, current.getP1().y); final PlotId pos1 = PlotId.of(current.getP1().getX(), current.getP1().getY());
final PlotId pos2 = new PlotId(current.getP2().x, current.getP2().y); final PlotId pos2 = PlotId.of(current.getP2().getX(), current.getP2().getY());
current.setP1(min); current.setP1(min);
current.setP2(max); current.setP2(max);
addClusterTask(current, new UniqueStatement("resizeCluster") { addClusterTask(current, new UniqueStatement("resizeCluster") {
@Override public void set(PreparedStatement statement) throws SQLException { @Override public void set(PreparedStatement statement) throws SQLException {
statement.setInt(1, pos1.x); statement.setInt(1, pos1.getX());
statement.setInt(2, pos1.y); statement.setInt(2, pos1.getY());
statement.setInt(3, pos2.x); statement.setInt(3, pos2.getX());
statement.setInt(4, pos2.y); statement.setInt(4, pos2.getY());
statement.setInt(5, getClusterId(current)); statement.setInt(5, getClusterId(current));
} }
@ -3140,10 +3141,10 @@ public class SQLManager implements AbstractDB {
+ "plot` SET `world` = ? WHERE `world` = ? AND `plot_id_x` BETWEEN ? AND ? AND `plot_id_z` BETWEEN ? AND ?")) { + "plot` SET `world` = ? WHERE `world` = ? AND `plot_id_x` BETWEEN ? AND ? AND `plot_id_z` BETWEEN ? AND ?")) {
stmt.setString(1, newWorld); stmt.setString(1, newWorld);
stmt.setString(2, oldWorld); stmt.setString(2, oldWorld);
stmt.setInt(3, min.x); stmt.setInt(3, min.getX());
stmt.setInt(4, max.x); stmt.setInt(4, max.getX());
stmt.setInt(5, min.y); stmt.setInt(5, min.getY());
stmt.setInt(6, max.y); stmt.setInt(6, max.getY());
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
@ -3153,10 +3154,10 @@ public class SQLManager implements AbstractDB {
+ "cluster` SET `world` = ? WHERE `world` = ? AND `pos1_x` <= ? AND `pos1_z` <= ? AND `pos2_x` >= ? AND `pos2_z` >= ?")) { + "cluster` SET `world` = ? WHERE `world` = ? AND `pos1_x` <= ? AND `pos1_z` <= ? AND `pos2_x` >= ? AND `pos2_z` >= ?")) {
stmt.setString(1, newWorld); stmt.setString(1, newWorld);
stmt.setString(2, oldWorld); stmt.setString(2, oldWorld);
stmt.setInt(3, max.x); stmt.setInt(3, max.getX());
stmt.setInt(4, max.y); stmt.setInt(4, max.getY());
stmt.setInt(5, min.x); stmt.setInt(5, min.getX());
stmt.setInt(6, min.y); stmt.setInt(6, min.getY());
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -37,9 +37,10 @@ import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.queue.LocalBlockQueue; import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.FileBytes; import com.plotsquared.core.util.FileBytes;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.RunnableVal;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
@ -52,6 +53,7 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.HashSet; import java.util.HashSet;
import java.util.Objects;
public class HybridPlotManager extends ClassicPlotManager { public class HybridPlotManager extends ClassicPlotManager {
@ -76,7 +78,7 @@ public class HybridPlotManager extends ClassicPlotManager {
.getWorldName() + File.separator; .getWorldName() + File.separator;
try { try {
File sideRoad = File sideRoad =
MainUtil.getFile(PlotSquared.platform().getDirectory(), dir + "sideroad.schem"); FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "sideroad.schem");
String newDir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator String newDir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator
+ "__TEMP_DIR__" + File.separator; + "__TEMP_DIR__" + File.separator;
if (sideRoad.exists()) { if (sideRoad.exists()) {
@ -84,12 +86,12 @@ public class HybridPlotManager extends ClassicPlotManager {
Files.readAllBytes(sideRoad.toPath()))); Files.readAllBytes(sideRoad.toPath())));
} }
File intersection = File intersection =
MainUtil.getFile(PlotSquared.platform().getDirectory(), dir + "intersection.schem"); FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "intersection.schem");
if (intersection.exists()) { if (intersection.exists()) {
files.add(new FileBytes(newDir + "intersection.schem", files.add(new FileBytes(newDir + "intersection.schem",
Files.readAllBytes(intersection.toPath()))); Files.readAllBytes(intersection.toPath())));
} }
File plot = MainUtil.getFile(PlotSquared.platform().getDirectory(), dir + "plot.schem"); File plot = FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "plot.schem");
if (plot.exists()) { if (plot.exists()) {
files.add(new FileBytes(newDir + "plot.schem", Files.readAllBytes(plot.toPath()))); files.add(new FileBytes(newDir + "plot.schem", Files.readAllBytes(plot.toPath())));
} }
@ -102,13 +104,13 @@ public class HybridPlotManager extends ClassicPlotManager {
@Override public boolean createRoadEast(Plot plot) { @Override public boolean createRoadEast(Plot plot) {
super.createRoadEast(plot); super.createRoadEast(plot);
PlotId id = plot.getId(); PlotId id = plot.getId();
PlotId id2 = new PlotId(id.x + 1, id.y); PlotId id2 = PlotId.of(id.getX() + 1, id.getY());
Location bot = getPlotBottomLocAbs(id2); Location bot = getPlotBottomLocAbs(id2);
Location top = getPlotTopLocAbs(id); Location top = getPlotTopLocAbs(id);
Location pos1 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, 0, bot.getZ() - 1); Location pos1 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, 0, bot.getZ() - 1);
Location pos2 = Location.at(hybridPlotWorld.getWorldName(), bot.getX(), Location pos2 = Location.at(hybridPlotWorld.getWorldName(), bot.getX(),
Math.min(getWorldHeight(), 255), top.getZ() + 1); Math.min(getWorldHeight(), 255), top.getZ() + 1);
MainUtil.resetBiome(hybridPlotWorld, pos1, pos2); this.resetBiome(hybridPlotWorld, pos1, pos2);
if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) {
return true; return true;
} }
@ -118,6 +120,17 @@ public class HybridPlotManager extends ClassicPlotManager {
return true; return true;
} }
private void resetBiome(@Nonnull final HybridPlotWorld hybridPlotWorld, @Nonnull final Location pos1,
@Nonnull final Location pos2) {
BiomeType biome = hybridPlotWorld.getPlotBiome();
if (!Objects.equals(PlotSquared.platform().getWorldUtil()
.getBiomeSynchronous(hybridPlotWorld.getWorldName(), (pos1.getX() + pos2.getX()) / 2,
(pos1.getZ() + pos2.getZ()) / 2), biome)) {
WorldUtil.setBiome(hybridPlotWorld.getWorldName(), pos1.getX(), pos1.getZ(), pos2.getX(), pos2.getZ(),
biome);
}
}
private void createSchemAbs(LocalBlockQueue queue, Location pos1, Location pos2, private void createSchemAbs(LocalBlockQueue queue, Location pos1, Location pos2,
boolean isRoad) { boolean isRoad) {
int size = hybridPlotWorld.SIZE; int size = hybridPlotWorld.SIZE;
@ -163,13 +176,13 @@ public class HybridPlotManager extends ClassicPlotManager {
@Override public boolean createRoadSouth(Plot plot) { @Override public boolean createRoadSouth(Plot plot) {
super.createRoadSouth(plot); super.createRoadSouth(plot);
PlotId id = plot.getId(); PlotId id = plot.getId();
PlotId id2 = new PlotId(id.x, id.y + 1); PlotId id2 = PlotId.of(id.getX(), id.getY() + 1);
Location bot = getPlotBottomLocAbs(id2); Location bot = getPlotBottomLocAbs(id2);
Location top = getPlotTopLocAbs(id); Location top = getPlotTopLocAbs(id);
Location pos1 = Location.at(hybridPlotWorld.getWorldName(), bot.getX() - 1, 0, top.getZ() + 1); Location pos1 = Location.at(hybridPlotWorld.getWorldName(), bot.getX() - 1, 0, top.getZ() + 1);
Location pos2 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, Location pos2 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1,
Math.min(getWorldHeight(), 255), bot.getZ()); Math.min(getWorldHeight(), 255), bot.getZ());
MainUtil.resetBiome(hybridPlotWorld, pos1, pos2); this.resetBiome(hybridPlotWorld, pos1, pos2);
if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) {
return true; return true;
} }
@ -182,7 +195,7 @@ public class HybridPlotManager extends ClassicPlotManager {
@Override public boolean createRoadSouthEast(Plot plot) { @Override public boolean createRoadSouthEast(Plot plot) {
super.createRoadSouthEast(plot); super.createRoadSouthEast(plot);
PlotId id = plot.getId(); PlotId id = plot.getId();
PlotId id2 = new PlotId(id.x + 1, id.y + 1); PlotId id2 = PlotId.of(id.getX() + 1, id.getY() + 1);
Location pos1 = getPlotTopLocAbs(id).add(1, 0, 1).withY(0); Location pos1 = getPlotTopLocAbs(id).add(1, 0, 1).withY(0);
Location pos2 = getPlotBottomLocAbs(id2).withY(Math.min(getWorldHeight(), 255)); Location pos2 = getPlotBottomLocAbs(id2).withY(Math.min(getWorldHeight(), 255));
LocalBlockQueue queue = hybridPlotWorld.getQueue(false); LocalBlockQueue queue = hybridPlotWorld.getQueue(false);
@ -237,7 +250,7 @@ public class HybridPlotManager extends ClassicPlotManager {
} }
/* Otherwise we need to set each component, as we don't want to regenerate the road or other plots that share the same chunk.*/ /* Otherwise we need to set each component, as we don't want to regenerate the road or other plots that share the same chunk.*/
// Set the biome // Set the biome
MainUtil.setBiome(world, value[2], value[3], value[4], value[5], biome); WorldUtil.setBiome(world, value[2], value[3], value[4], value[5], biome);
// These two locations are for each component (e.g. bedrock, main block, floor, air) // These two locations are for each component (e.g. bedrock, main block, floor, air)
Location bot = Location.at(world, value[2], 0, value[3]); Location bot = Location.at(world, value[2], 0, value[3]);
Location top = Location.at(world, value[4], 1, value[5]); Location top = Location.at(world, value[4], 1, value[5]);

View File

@ -39,7 +39,7 @@ import com.plotsquared.core.plot.PlotManager;
import com.plotsquared.core.plot.schematic.Schematic; import com.plotsquared.core.plot.schematic.Schematic;
import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.SchematicHandler; import com.plotsquared.core.util.SchematicHandler;
@ -218,9 +218,9 @@ public class HybridPlotWorld extends ClassicPlotWorld {
// Try to determine root. This means that plot areas can have separate schematic // Try to determine root. This means that plot areas can have separate schematic
// directories // directories
if (!(root = MainUtil.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" + if (!(root = FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" +
this.getWorldName() + "/" + this.getId())).exists()) { this.getWorldName() + "/" + this.getId())).exists()) {
root = MainUtil.getFile(PlotSquared.platform().getDirectory(), root = FileUtils.getFile(PlotSquared.platform().getDirectory(),
"schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName()); "schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName());
} }

View File

@ -30,7 +30,7 @@ import com.plotsquared.core.location.Location;
import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.HashUtil;
import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.RegionManager;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -77,8 +77,8 @@ public abstract class SquarePlotManager extends GridPlotManager {
} }
@Override public Location getPlotTopLocAbs(PlotId plotId) { @Override public Location getPlotTopLocAbs(PlotId plotId) {
int px = plotId.x; int px = plotId.getX();
int pz = plotId.y; int pz = plotId.getY();
int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH
+ squarePlotWorld.PLOT_WIDTH))) - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; + squarePlotWorld.PLOT_WIDTH))) - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2) - 1;
int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH
@ -126,7 +126,7 @@ public abstract class SquarePlotManager extends GridPlotManager {
if (z <= pathWidthLower || z > end || x <= pathWidthLower || x > end) { if (z <= pathWidthLower || z > end || x <= pathWidthLower || x > end) {
return null; return null;
} else { } else {
return new PlotId(idx, idz); return PlotId.of(idx, idz);
} }
} }
@ -151,7 +151,7 @@ public abstract class SquarePlotManager extends GridPlotManager {
} else { } else {
idz = (z / size) + 1; idz = (z / size) + 1;
} }
return new PlotId(idx, idz); return PlotId.of(idx, idz);
} }
@Override public PlotId getPlotId(int x, int y, int z) { @Override public PlotId getPlotId(int x, int y, int z) {
@ -190,10 +190,10 @@ public abstract class SquarePlotManager extends GridPlotManager {
dz = (z / size) + 1; dz = (z / size) + 1;
rz = z % size; rz = z % size;
} }
PlotId id = new PlotId(dx, dz); PlotId id = PlotId.of(dx, dz);
boolean[] merged = boolean[] merged =
new boolean[] {rz <= pathWidthLower, rx > end, rz > end, rx <= pathWidthLower}; new boolean[] {rz <= pathWidthLower, rx > end, rz > end, rx <= pathWidthLower};
int hash = MainUtil.hash(merged); int hash = HashUtil.hash(merged);
// Not merged, and no need to check if it is // Not merged, and no need to check if it is
if (hash == 0) { if (hash == 0) {
return id; return id;
@ -240,8 +240,8 @@ public abstract class SquarePlotManager extends GridPlotManager {
* Get the bottom plot loc (some basic math). * Get the bottom plot loc (some basic math).
*/ */
@Override public Location getPlotBottomLocAbs(PlotId plotId) { @Override public Location getPlotBottomLocAbs(PlotId plotId) {
int px = plotId.x; int px = plotId.getX();
int pz = plotId.y; int pz = plotId.getY();
int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH
+ squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH - (int) Math + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH - (int) Math
.floor(squarePlotWorld.ROAD_WIDTH / 2); .floor(squarePlotWorld.ROAD_WIDTH / 2);

View File

@ -60,8 +60,8 @@ import com.plotsquared.core.plot.flag.types.TimedFlag;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.StringMan;
import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import com.plotsquared.core.util.task.TaskTime; import com.plotsquared.core.util.task.TaskTime;
import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.gamemode.GameMode;
@ -157,12 +157,8 @@ public class PlotListener {
final String greeting = plot.getFlag(GreetingFlag.class); final String greeting = plot.getFlag(GreetingFlag.class);
if (!greeting.isEmpty()) { if (!greeting.isEmpty()) {
MainUtil.format(Captions.PREFIX_GREETING.getTranslated() + greeting, plot, player, plot.format(Captions.PREFIX_GREETING.getTranslated() + greeting, player, false)
false, new RunnableVal<String>() { .thenAcceptAsync(player::sendMessage);
@Override public void run(String value) {
MainUtil.sendMessage(player, value);
}
});
} }
if (plot.getFlag(NotifyEnterFlag.class)) { if (plot.getFlag(NotifyEnterFlag.class)) {
@ -329,12 +325,8 @@ public class PlotListener {
final String farewell = plot.getFlag(FarewellFlag.class); final String farewell = plot.getFlag(FarewellFlag.class);
if (!farewell.isEmpty()) { if (!farewell.isEmpty()) {
MainUtil.format(Captions.PREFIX_FAREWELL.getTranslated() + farewell, plot, player, plot.format(Captions.PREFIX_FAREWELL.getTranslated() + farewell, player, false)
false, new RunnableVal<String>() { .thenAcceptAsync(player::sendMessage);
@Override public void run(String value) {
MainUtil.sendMessage(player, value);
}
});
} }
if (plot.getFlag(NotifyLeaveFlag.class)) { if (plot.getFlag(NotifyLeaveFlag.class)) {

View File

@ -117,4 +117,5 @@ public class BlockLoc {
public float getPitch() { public float getPitch() {
return pitch; return pitch;
} }
} }

View File

@ -25,6 +25,7 @@
*/ */
package com.plotsquared.core.location; package com.plotsquared.core.location;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.plotsquared.core.PlotSquared; import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.Plot;
@ -41,7 +42,7 @@ import javax.annotation.Nullable;
* An unmodifiable 6-tuple (world,x,y,z,yaw,pitch) * An unmodifiable 6-tuple (world,x,y,z,yaw,pitch)
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class Location implements Comparable<Location> { public final class Location extends BlockLoc implements Comparable<Location> {
private final float yaw; private final float yaw;
private final float pitch; private final float pitch;
@ -50,6 +51,7 @@ public final class Location implements Comparable<Location> {
private Location(@Nonnull final World<?> world, @Nonnull final BlockVector3 blockVector3, private Location(@Nonnull final World<?> world, @Nonnull final BlockVector3 blockVector3,
final float yaw, final float pitch) { final float yaw, final float pitch) {
super(blockVector3.getX(), blockVector3.getY(), blockVector3.getZ(), yaw, pitch);
this.world = Preconditions.checkNotNull(world, "World may not be null"); this.world = Preconditions.checkNotNull(world, "World may not be null");
this.blockVector3 = Preconditions.checkNotNull(blockVector3, "Vector may not be null"); this.blockVector3 = Preconditions.checkNotNull(blockVector3, "Vector may not be null");
this.yaw = yaw; this.yaw = yaw;
@ -58,6 +60,7 @@ public final class Location implements Comparable<Location> {
private Location(@Nonnull final String worldName, @Nonnull final BlockVector3 blockVector3, private Location(@Nonnull final String worldName, @Nonnull final BlockVector3 blockVector3,
final float yaw, final float pitch) { final float yaw, final float pitch) {
super(blockVector3.getX(), blockVector3.getY(), blockVector3.getZ(), yaw, pitch);
Preconditions.checkNotNull(worldName, "World name may not be null"); Preconditions.checkNotNull(worldName, "World name may not be null");
if (worldName.isEmpty()) { if (worldName.isEmpty()) {
this.world = World.nullWorld(); this.world = World.nullWorld();
@ -444,6 +447,28 @@ public final class Location implements Comparable<Location> {
return 1; return 1;
} }
@Override public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
final Location location = (Location) o;
return Float.compare(location.getYaw(), getYaw()) == 0
&& Float.compare(location.getPitch(), getPitch()) == 0 && Objects
.equal(getBlockVector3(), location.getBlockVector3()) && Objects
.equal(getWorld(), location.getWorld());
}
@Override public int hashCode() {
return Objects
.hashCode(super.hashCode(), getYaw(), getPitch(), getBlockVector3(), getWorld());
}
@Override public String toString() { @Override public String toString() {
return "\"plotsquaredlocation\":{\"x\":" + this.getX() + ",\"y\":" + this.getY() + ",\"z\":" return "\"plotsquaredlocation\":{\"x\":" + this.getX() + ",\"y\":" + this.getY() + ",\"z\":"
+ this.getZ() + ",\"yaw\":" + this.yaw + ",\"pitch\":" + this.pitch + ",\"world\":\"" + this.getZ() + ",\"yaw\":" + this.yaw + ",\"pitch\":" + this.pitch + ",\"world\":\""

View File

@ -78,11 +78,11 @@ public final class PlotLoc {
} }
public int getX() { public int getX() {
return this.x; return this.getX();
} }
public int getY() { public int getY() {
return this.y; return this.getY();
} }
public int getZ() { public int getZ() {
@ -92,14 +92,14 @@ public final class PlotLoc {
@Override public int hashCode() { @Override public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = (prime * result) + this.x; result = (prime * result) + this.getX();
result = (prime * result) + this.y; result = (prime * result) + this.getY();
result = (prime * result) + this.z; result = (prime * result) + this.getZ();
return result; return result;
} }
@Override public String toString() { @Override public String toString() {
if (this.y == -1) { if (this.getY() == -1) {
return String.format("%d,%d", x, z); return String.format("%d,%d", x, z);
} }
return String.format("%d,%d,%d", x, y, z); return String.format("%d,%d,%d", x, y, z);
@ -113,6 +113,7 @@ public final class PlotLoc {
return false; return false;
} }
final PlotLoc other = (PlotLoc) obj; final PlotLoc other = (PlotLoc) obj;
return (this.x == other.x) && (this.y == other.y) && (this.z == other.z); return (this.getX() == other.getX()) && (this.getY() ==
other.getY()) && (this.getZ() == other.getZ());
} }
} }

View File

@ -589,8 +589,8 @@ public abstract class PlotPlayer<P> implements CommandCaller, OfflinePlotPlayer,
if (plot != null && Settings.Enabled_Components.PERSISTENT_META && plot if (plot != null && Settings.Enabled_Components.PERSISTENT_META && plot
.getArea() instanceof SinglePlotArea) { .getArea() instanceof SinglePlotArea) {
PlotId id = plot.getId(); PlotId id = plot.getId();
int x = id.x; int x = id.getX();
int z = id.y; int z = id.getY();
ByteBuffer buffer = ByteBuffer.allocate(13); ByteBuffer buffer = ByteBuffer.allocate(13);
buffer.putShort((short) x); buffer.putShort((short) x);
buffer.putShort((short) z); buffer.putShort((short) z);
@ -690,7 +690,7 @@ public abstract class PlotPlayer<P> implements CommandCaller, OfflinePlotPlayer,
ByteBuffer quitWorld = ByteBuffer.wrap(arr); ByteBuffer quitWorld = ByteBuffer.wrap(arr);
final int plotX = quitWorld.getShort(); final int plotX = quitWorld.getShort();
final int plotZ = quitWorld.getShort(); final int plotZ = quitWorld.getShort();
PlotId id = new PlotId(plotX, plotZ); PlotId id = PlotId.of(plotX, plotZ);
int x = quitWorld.getInt(); int x = quitWorld.getInt();
int y = quitWorld.get() & 0xFF; int y = quitWorld.get() & 0xFF;
int z = quitWorld.getInt(); int z = quitWorld.getInt();

View File

@ -26,9 +26,12 @@
package com.plotsquared.core.plot; package com.plotsquared.core.plot;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared; import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.command.Like;
import com.plotsquared.core.configuration.CaptionUtility;
import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.ConfigurationUtil; import com.plotsquared.core.configuration.ConfigurationUtil;
import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.configuration.Settings;
@ -46,6 +49,7 @@ import com.plotsquared.core.location.BlockLoc;
import com.plotsquared.core.location.Direction; import com.plotsquared.core.location.Direction;
import com.plotsquared.core.location.Location; import com.plotsquared.core.location.Location;
import com.plotsquared.core.location.PlotLoc; import com.plotsquared.core.location.PlotLoc;
import com.plotsquared.core.player.ConsolePlayer;
import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.comment.PlotComment; import com.plotsquared.core.plot.comment.PlotComment;
import com.plotsquared.core.plot.expiration.ExpireManager; import com.plotsquared.core.plot.expiration.ExpireManager;
@ -54,7 +58,10 @@ import com.plotsquared.core.plot.flag.FlagContainer;
import com.plotsquared.core.plot.flag.GlobalFlagContainer; import com.plotsquared.core.plot.flag.GlobalFlagContainer;
import com.plotsquared.core.plot.flag.InternalFlag; import com.plotsquared.core.plot.flag.InternalFlag;
import com.plotsquared.core.plot.flag.PlotFlag; import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.plot.flag.implementations.DescriptionFlag;
import com.plotsquared.core.plot.flag.implementations.KeepFlag; import com.plotsquared.core.plot.flag.implementations.KeepFlag;
import com.plotsquared.core.plot.flag.implementations.ServerPlotFlag;
import com.plotsquared.core.plot.flag.types.DoubleFlag;
import com.plotsquared.core.plot.schematic.Schematic; import com.plotsquared.core.plot.schematic.Schematic;
import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.LocalBlockQueue; import com.plotsquared.core.queue.LocalBlockQueue;
@ -62,9 +69,13 @@ import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.RegionUtil;
import com.plotsquared.core.util.SchematicHandler; import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.TimeUtil;
import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.query.PlotQuery;
import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import com.plotsquared.core.util.task.TaskTime; import com.plotsquared.core.util.task.TaskTime;
@ -87,6 +98,7 @@ import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import java.io.File; import java.io.File;
import java.net.URL; import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -123,24 +135,18 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE;
*/ */
public class Plot { public class Plot {
private static final Logger logger = LoggerFactory.getLogger("P2/" + Plot.class.getSimpleName());
public static final int MAX_HEIGHT = 256; public static final int MAX_HEIGHT = 256;
private static final Logger logger = LoggerFactory.getLogger("P2/" + Plot.class.getSimpleName());
private static final DecimalFormat FLAG_DECIMAL_FORMAT = new DecimalFormat("0");
static {
FLAG_DECIMAL_FORMAT.setMaximumFractionDigits(340);
}
private static Set<Plot> connected_cache; private static Set<Plot> connected_cache;
private static Set<CuboidRegion> regions_cache; private static Set<CuboidRegion> regions_cache;
@Nonnull private final PlotId id;
// These will be injected
@Inject private EventDispatcher eventDispatcher;
@Inject private PlotListener plotListener;
@Inject private RegionManager regionManager;
@Inject private GlobalBlockQueue blockQueue;
@Inject private WorldUtil worldUtil;
@Inject private SchematicHandler schematicHandler;
@Inject @ImpromptuPipeline private UUIDPipeline impromptuPipeline;
/** /**
* Plot flag container * Plot flag container
*/ */
@ -149,7 +155,6 @@ public class Plot {
* Has the plot changed since the last save cycle? * Has the plot changed since the last save cycle?
*/ */
public boolean countsTowardsMax = true; public boolean countsTowardsMax = true;
/** /**
* Represents whatever the database manager needs it to: <br> * Represents whatever the database manager needs it to: <br>
* - A value of -1 usually indicates the plot will not be stored in the DB<br> * - A value of -1 usually indicates the plot will not be stored in the DB<br>
@ -158,6 +163,15 @@ public class Plot {
* @deprecated magical * @deprecated magical
*/ */
@Deprecated public int temp; @Deprecated public int temp;
@Nonnull private PlotId id;
// These will be injected
@Inject private EventDispatcher eventDispatcher;
@Inject private PlotListener plotListener;
@Inject private RegionManager regionManager;
@Inject private GlobalBlockQueue blockQueue;
@Inject private WorldUtil worldUtil;
@Inject private SchematicHandler schematicHandler;
@Inject @ImpromptuPipeline private UUIDPipeline impromptuPipeline;
/** /**
* plot owner * plot owner
* (Merged plots can have multiple owners) * (Merged plots can have multiple owners)
@ -283,6 +297,72 @@ public class Plot {
PlotSquared.platform().getInjector().injectMembers(this); PlotSquared.platform().getInjector().injectMembers(this);
} }
/**
* Get the plot from a string.
*
* @param player Provides a context for what world to search in. Prefixing the term with 'world_name;' will override this context.
* @param arg The search term
* @param message If a message should be sent to the player if a plot cannot be found
* @return The plot if only 1 result is found, or null
*/
@Nullable public static Plot getPlotFromString(PlotPlayer<?> player, String arg,
boolean message) {
if (arg == null) {
if (player == null) {
if (message) {
logger.info("[P2] No plot area string was supplied");
}
return null;
}
return player.getCurrentPlot();
}
PlotArea area;
if (player != null) {
area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(arg);
if (area == null) {
area = player.getApplicablePlotArea();
}
} else {
area = ConsolePlayer.getConsole().getApplicablePlotArea();
}
String[] split = arg.split(";|,");
PlotId id;
if (split.length == 4) {
area = PlotSquared.get().getPlotAreaManager()
.getPlotAreaByString(split[0] + ';' + split[1]);
id = PlotId.fromString(split[2] + ';' + split[3]);
} else if (split.length == 3) {
area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(split[0]);
id = PlotId.fromString(split[1] + ';' + split[2]);
} else if (split.length == 2) {
id = PlotId.fromString(arg);
} else {
Collection<Plot> plots;
if (area == null) {
plots = PlotQuery.newQuery().allPlots().asList();
} else {
plots = area.getPlots();
}
for (Plot p : plots) {
String name = p.getAlias();
if (!name.isEmpty() && name.equalsIgnoreCase(arg)) {
return p;
}
}
if (message) {
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID);
}
return null;
}
if (area == null) {
if (message) {
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD);
}
return null;
}
return area.getPlotAbs(id);
}
/** /**
* Gets a plot from a string e.g. [area];[id] * Gets a plot from a string e.g. [area];[id]
* *
@ -328,6 +408,13 @@ public class Plot {
return null; return null;
} }
@Nonnull private static Location[] getCorners(@Nonnull final String world,
@Nonnull final CuboidRegion region) {
final BlockVector3 min = region.getMinimumPoint();
final BlockVector3 max = region.getMaximumPoint();
return new Location[] {Location.at(world, min), Location.at(world, max)};
}
/** /**
* Get the owner of this exact plot, as it is * Get the owner of this exact plot, as it is
* stored in the database. * stored in the database.
@ -470,7 +557,7 @@ public class Plot {
* @see #getOwnerAbs() getOwnerAbs() to get the owner as stored in the database * @see #getOwnerAbs() getOwnerAbs() to get the owner as stored in the database
*/ */
public UUID getOwner() { public UUID getOwner() {
if (MainUtil.isServerOwned(this)) { if (this.getFlag(ServerPlotFlag.class)) {
return DBFunc.SERVER; return DBFunc.SERVER;
} }
return this.getOwnerAbs(); return this.getOwnerAbs();
@ -577,6 +664,15 @@ public class Plot {
return this.id; return this.id;
} }
/**
* Change the plot ID
*
* @param id new plot ID
*/
public void setId(@Nonnull final PlotId id) {
this.id = id;
}
/** /**
* Gets the plot world object for this plot<br> * Gets the plot world object for this plot<br>
* - The generic PlotArea object can be casted to its respective class for more control (e.g. HybridPlotWorld) * - The generic PlotArea object can be casted to its respective class for more control (e.g. HybridPlotWorld)
@ -663,7 +759,7 @@ public class Plot {
this.origin = this; this.origin = this;
PlotId min = this.id; PlotId min = this.id;
for (Plot plot : this.getConnectedPlots()) { for (Plot plot : this.getConnectedPlots()) {
if (plot.id.y < min.y || plot.id.y == min.y && plot.id.x < min.x) { if (plot.id.getY() < min.getY() || plot.id.getY() == min.getY() && plot.id.getX() < min.getX()) {
this.origin = plot; this.origin = plot;
min = plot.id; min = plot.id;
} }
@ -732,8 +828,10 @@ public class Plot {
int i2 = 0; int i2 = 0;
if (this.getSettings().getMerged(i2)) { if (this.getSettings().getMerged(i2)) {
if (this.getSettings().getMerged(i)) { if (this.getSettings().getMerged(i)) {
if (this.area.getPlotAbs(this.id.getRelative(i)).getMerged(i2)) { if (this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i)))
return this.area.getPlotAbs(this.id.getRelative(i2)).getMerged(i); .getMerged(i2)) {
return this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2)))
.getMerged(i);
} }
} }
} }
@ -744,8 +842,9 @@ public class Plot {
i = dir - 4; i = dir - 4;
i2 = dir - 3; i2 = dir - 3;
return this.getSettings().getMerged(i2) && this.getSettings().getMerged(i) return this.getSettings().getMerged(i2) && this.getSettings().getMerged(i)
&& this.area.getPlotAbs(this.id.getRelative(i)).getMerged(i2) && this.area && this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i)))
.getPlotAbs(this.id.getRelative(i2)).getMerged(i); .getMerged(i2) && this.area
.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2))).getMerged(i);
} }
return false; return false;
@ -957,7 +1056,7 @@ public class Plot {
if (queue.isEmpty()) { if (queue.isEmpty()) {
Runnable run = () -> { Runnable run = () -> {
for (CuboidRegion region : regions) { for (CuboidRegion region : regions) {
Location[] corners = MainUtil.getCorners(getWorldName(), region); Location[] corners = getCorners(getWorldName(), region);
regionManager.clearAllEntities(corners[0], corners[1]); regionManager.clearAllEntities(corners[0], corners[1]);
} }
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
@ -1067,7 +1166,7 @@ public class Plot {
blockQueue.addEmptyTask(() -> { blockQueue.addEmptyTask(() -> {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(() -> {
for (Plot current : plots) { for (Plot current : plots) {
current.setSign(MainUtil.getName(current.getOwnerAbs())); current.setSign(PlayerManager.getName(current.getOwnerAbs()));
} }
}); });
}); });
@ -1857,6 +1956,8 @@ public class Plot {
return this.setComponent(component, parsed.toPattern()); return this.setComponent(component, parsed.toPattern());
} }
//TODO Better documentation needed.
/** /**
* Retrieve the biome of the plot. * Retrieve the biome of the plot.
*/ */
@ -1865,6 +1966,8 @@ public class Plot {
.getBiome(location.getWorldName(), location.getX(), location.getZ(), result)); .getBiome(location.getWorldName(), location.getX(), location.getZ(), result));
} }
//TODO Better documentation needed.
/** /**
* @deprecated May cause synchronous chunk loads * @deprecated May cause synchronous chunk loads
*/ */
@ -1874,8 +1977,6 @@ public class Plot {
.getBiomeSynchronous(location.getWorldName(), location.getX(), location.getZ()); .getBiomeSynchronous(location.getWorldName(), location.getX(), location.getZ());
} }
//TODO Better documentation needed.
/** /**
* Returns the top location for the plot. * Returns the top location for the plot.
*/ */
@ -1883,8 +1984,6 @@ public class Plot {
return this.getManager().getPlotTopLocAbs(this.id).withWorld(this.getWorldName()); return this.getManager().getPlotTopLocAbs(this.id).withWorld(this.getWorldName());
} }
//TODO Better documentation needed.
/** /**
* Returns the bottom location for the plot. * Returns the bottom location for the plot.
*/ */
@ -1911,15 +2010,11 @@ public class Plot {
return CompletableFuture.completedFuture(true); return CompletableFuture.completedFuture(true);
} }
// Swap cached // Swap cached
PlotId temp = new PlotId(this.getId().x, this.getId().y); final PlotId temp = PlotId.of(this.getId().getX(), this.getId().getY());
this.getId().x = plot.getId().x; this.id = plot.getId().copy();
this.getId().y = plot.getId().y; plot.id = temp.copy();
plot.getId().x = temp.x;
plot.getId().y = temp.y;
this.area.removePlot(this.getId()); this.area.removePlot(this.getId());
plot.area.removePlot(plot.getId()); plot.area.removePlot(plot.getId());
this.getId().recalculateHash();
plot.getId().recalculateHash();
this.area.addPlotAbs(this); this.area.addPlotAbs(this);
plot.area.addPlotAbs(plot); plot.area.addPlotAbs(plot);
// Swap database // Swap database
@ -1943,9 +2038,7 @@ public class Plot {
return false; return false;
} }
this.area.removePlot(this.id); this.area.removePlot(this.id);
this.getId().x = plot.getId().x; this.id = plot.getId().copy();
this.getId().y = plot.getId().y;
this.getId().recalculateHash();
this.area.addPlotAbs(this); this.area.addPlotAbs(this);
DBFunc.movePlot(this, plot); DBFunc.movePlot(this, plot);
TaskManager.runTaskLater(whenDone, TaskTime.ticks(1L)); TaskManager.runTaskLater(whenDone, TaskTime.ticks(1L));
@ -2005,7 +2098,7 @@ public class Plot {
if (!this.isMerged()) { if (!this.isMerged()) {
return new Location[] {this.getBottomAbs(), this.getTopAbs()}; return new Location[] {this.getBottomAbs(), this.getTopAbs()};
} }
return MainUtil.getCorners(this.getWorldName(), this.getRegions()); return RegionUtil.getCorners(this.getWorldName(), this.getRegions());
} }
/** /**
@ -2079,10 +2172,9 @@ public class Plot {
if (this.settings != null && this.settings.getAlias().length() > 1) { if (this.settings != null && this.settings.getAlias().length() > 1) {
return this.settings.getAlias(); return this.settings.getAlias();
} }
return this.area + ";" + this.id.x + ";" + this.id.y; return this.area + ";" + this.id.toString();
} }
/** /**
* Remove a denied player (use DBFunc as well)<br> * Remove a denied player (use DBFunc as well)<br>
* Using the * uuid will remove all users * Using the * uuid will remove all users
@ -2183,8 +2275,8 @@ public class Plot {
} }
} else { } else {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(() -> {
String name = Plot.this.id + "," + Plot.this.area + ',' + MainUtil String name = Plot.this.id + "," + Plot.this.area + ',' +
.getName(Plot.this.getOwnerAbs()); PlayerManager.getName(Plot.this.getOwnerAbs());
boolean result = schematicHandler.save(value, boolean result = schematicHandler.save(value,
Settings.Paths.SCHEMATICS + File.separator + name + ".schem"); Settings.Paths.SCHEMATICS + File.separator + name + ".schem");
if (whenDone != null) { if (whenDone != null) {
@ -2294,8 +2386,8 @@ public class Plot {
if (value) { if (value) {
Plot other = this.getRelative(direction).getBasePlot(false); Plot other = this.getRelative(direction).getBasePlot(false);
if (!other.equals(this.getBasePlot(false))) { if (!other.equals(this.getBasePlot(false))) {
Plot base = other.id.y < this.id.y Plot base = other.id.getY() < this.id.getY()
|| other.id.y == this.id.y && other.id.x < this.id.x ? other : this.origin; || other.id.getY() == this.id.getY() && other.id.getX() < this.id.getX() ? other : this.origin;
this.origin.origin = base; this.origin.origin = base;
other.origin = base; other.origin = base;
this.origin = base; this.origin = base;
@ -2584,36 +2676,21 @@ public class Plot {
* @return Plot * @return Plot
*/ */
public Plot getRelative(int x, int y) { public Plot getRelative(int x, int y) {
return this.area.getPlotAbs(this.id.getRelative(x, y)); return this.area.getPlotAbs(PlotId.of(this.id.getX() + x, this.id.getY() + y));
} }
public Plot getRelative(PlotArea area, int x, int y) { public Plot getRelative(PlotArea area, int x, int y) {
return area.getPlotAbs(this.id.getRelative(x, y)); return area.getPlotAbs(PlotId.of(this.id.getX() + x, this.id.getY() + y));
}
/**
* Gets the plot in a relative direction<br>
* 0 = north<br>
* 1 = east<br>
* 2 = south<br>
* 3 = west<br>
* Note: May be null if the partial plot area does not include the relative location
*
* @param direction
* @return
*/
@Deprecated public Plot getRelative(int direction) {
return this.area.getPlotAbs(this.id.getRelative(direction));
} }
/** /**
* Gets the plot in a relative direction * Gets the plot in a relative direction
* Note: May be null if the partial plot area does not include the relative location * Note: May be null if the partial plot area does not include the relative location
* *
* @param direction * @param direction Direction
* @return the plot relative to this one * @return the plot relative to this one
*/ */
public Plot getRelative(Direction direction) { @Nullable public Plot getRelative(@Nonnull Direction direction) {
return this.area.getPlotAbs(this.id.getRelative(direction)); return this.area.getPlotAbs(this.id.getRelative(direction));
} }
@ -2769,12 +2846,13 @@ public class Plot {
continue; continue;
} }
boolean merge = true; boolean merge = true;
PlotId bot = new PlotId(current.getId().x, current.getId().y); PlotId bot = PlotId.of(current.getId().getX(), current.getId().getY());
PlotId top = new PlotId(current.getId().x, current.getId().y); PlotId top = PlotId.of(current.getId().getX(), current.getId().getY());
while (merge) { while (merge) {
merge = false; merge = false;
ArrayList<PlotId> ids = MainUtil.getPlotSelectionIds(new PlotId(bot.x, bot.y - 1), List<PlotId> ids = Lists.newArrayList((Iterable<? extends PlotId>)
new PlotId(top.x, bot.y - 1)); PlotId.PlotRangeIterator.range(PlotId.of(bot.getX(), bot.getY() - 1),
PlotId.of(top.getX(), bot.getY() - 1)));
boolean tmp = true; boolean tmp = true;
for (PlotId id : ids) { for (PlotId id : ids) {
Plot plot = this.area.getPlotAbs(id); Plot plot = this.area.getPlotAbs(id);
@ -2785,10 +2863,11 @@ public class Plot {
} }
if (tmp) { if (tmp) {
merge = true; merge = true;
bot.y--; bot = PlotId.of(bot.getX(), bot.getY() - 1);
} }
ids = MainUtil.getPlotSelectionIds(new PlotId(top.x + 1, bot.y), ids = Lists.newArrayList((Iterable<? extends PlotId>)
new PlotId(top.x + 1, top.y)); PlotId.PlotRangeIterator.range(PlotId.of(top.getX() + 1, bot.getY()),
PlotId.of(top.getX() + 1, top.getY())));
tmp = true; tmp = true;
for (PlotId id : ids) { for (PlotId id : ids) {
Plot plot = this.area.getPlotAbs(id); Plot plot = this.area.getPlotAbs(id);
@ -2799,10 +2878,11 @@ public class Plot {
} }
if (tmp) { if (tmp) {
merge = true; merge = true;
top.x++; top = PlotId.of(top.getX() + 1, top.getY());
} }
ids = MainUtil.getPlotSelectionIds(new PlotId(bot.x, top.y + 1), ids = Lists.newArrayList((Iterable<? extends PlotId>)
new PlotId(top.x, top.y + 1)); PlotId.PlotRangeIterator.range(PlotId.of(bot.getX(), top.getY() + 1),
PlotId.of(top.getX(), top.getY() + 1)));
tmp = true; tmp = true;
for (PlotId id : ids) { for (PlotId id : ids) {
Plot plot = this.area.getPlotAbs(id); Plot plot = this.area.getPlotAbs(id);
@ -2813,10 +2893,11 @@ public class Plot {
} }
if (tmp) { if (tmp) {
merge = true; merge = true;
top.y++; top = PlotId.of(top.getX(), top.getY() + 1);
} }
ids = MainUtil.getPlotSelectionIds(new PlotId(bot.x - 1, bot.y), ids = Lists.newArrayList((Iterable<? extends PlotId>)
new PlotId(bot.x - 1, top.y)); PlotId.PlotRangeIterator.range(PlotId.of(bot.getX() - 1, bot.getY()),
PlotId.of(bot.getX() - 1, top.getY())));
tmp = true; tmp = true;
for (PlotId id : ids) { for (PlotId id : ids) {
Plot plot = this.area.getPlotAbs(id); Plot plot = this.area.getPlotAbs(id);
@ -2827,14 +2908,15 @@ public class Plot {
} }
if (tmp) { if (tmp) {
merge = true; merge = true;
bot.x--; bot = PlotId.of(bot.getX() - 1, bot.getX());
} }
} }
Location gtopabs = this.area.getPlotAbs(top).getTopAbs(); Location gtopabs = this.area.getPlotAbs(top).getTopAbs();
Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs(); Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs();
visited.addAll(MainUtil.getPlotSelectionIds(bot, top)); visited.addAll(Lists.newArrayList((Iterable<? extends PlotId>)
for (int x = bot.x; x <= top.x; x++) { PlotId.PlotRangeIterator.range(bot, top)));
Plot plot = this.area.getPlotAbs(new PlotId(x, top.y)); for (int x = bot.getX(); x <= top.getX(); x++) {
Plot plot = this.area.getPlotAbs(PlotId.of(x, top.getY()));
if (plot.getMerged(Direction.SOUTH)) { if (plot.getMerged(Direction.SOUTH)) {
// south wedge // south wedge
Location toploc = plot.getExtendedTopAbs(); Location toploc = plot.getExtendedTopAbs();
@ -2853,8 +2935,8 @@ public class Plot {
} }
} }
for (int y = bot.y; y <= top.y; y++) { for (int y = bot.getY(); y <= top.getY(); y++) {
Plot plot = this.area.getPlotAbs(new PlotId(top.x, y)); Plot plot = this.area.getPlotAbs(PlotId.of(top.getX(), y));
if (plot.getMerged(Direction.EAST)) { if (plot.getMerged(Direction.EAST)) {
// east wedge // east wedge
Location toploc = plot.getExtendedTopAbs(); Location toploc = plot.getExtendedTopAbs();
@ -3087,8 +3169,8 @@ public class Plot {
public void mergePlot(Plot lesserPlot, boolean removeRoads) { public void mergePlot(Plot lesserPlot, boolean removeRoads) {
Plot greaterPlot = this; Plot greaterPlot = this;
lesserPlot.removeSign(); lesserPlot.removeSign();
if (lesserPlot.getId().x == greaterPlot.getId().x) { if (lesserPlot.getId().getX() == greaterPlot.getId().getX()) {
if (lesserPlot.getId().y > greaterPlot.getId().y) { if (lesserPlot.getId().getY() > greaterPlot.getId().getY()) {
Plot tmp = lesserPlot; Plot tmp = lesserPlot;
lesserPlot = greaterPlot; lesserPlot = greaterPlot;
greaterPlot = tmp; greaterPlot = tmp;
@ -3113,7 +3195,7 @@ public class Plot {
} }
} }
} else { } else {
if (lesserPlot.getId().x > greaterPlot.getId().x) { if (lesserPlot.getId().getX() > greaterPlot.getId().getX()) {
Plot tmp = lesserPlot; Plot tmp = lesserPlot;
lesserPlot = greaterPlot; lesserPlot = greaterPlot;
greaterPlot = tmp; greaterPlot = tmp;
@ -3151,8 +3233,8 @@ public class Plot {
*/ */
public CompletableFuture<Boolean> move(final Plot destination, final Runnable whenDone, public CompletableFuture<Boolean> move(final Plot destination, final Runnable whenDone,
boolean allowSwap) { boolean allowSwap) {
final PlotId offset = new PlotId(destination.getId().x - this.getId().x, final PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(),
destination.getId().y - this.getId().y); destination.getId().getY() - this.getId().getY());
Location db = destination.getBottomAbs(); Location db = destination.getBottomAbs();
Location ob = this.getBottomAbs(); Location ob = this.getBottomAbs();
final int offsetX = db.getX() - ob.getX(); final int offsetX = db.getX() - ob.getX();
@ -3164,7 +3246,7 @@ public class Plot {
AtomicBoolean occupied = new AtomicBoolean(false); AtomicBoolean occupied = new AtomicBoolean(false);
Set<Plot> plots = this.getConnectedPlots(); Set<Plot> plots = this.getConnectedPlots();
for (Plot plot : plots) { for (Plot plot : plots) {
Plot other = plot.getRelative(destination.getArea(), offset.x, offset.y); Plot other = plot.getRelative(destination.getArea(), offset.getX(), offset.getY());
if (other.hasOwner()) { if (other.hasOwner()) {
if (!allowSwap) { if (!allowSwap) {
TaskManager.runTaskLater(whenDone, TaskTime.ticks(1L)); TaskManager.runTaskLater(whenDone, TaskTime.ticks(1L));
@ -3187,7 +3269,7 @@ public class Plot {
if (plotIterator.hasNext()) { if (plotIterator.hasNext()) {
while (plotIterator.hasNext()) { while (plotIterator.hasNext()) {
final Plot plot = plotIterator.next(); final Plot plot = plotIterator.next();
final Plot other = plot.getRelative(destination.getArea(), offset.x, offset.y); final Plot other = plot.getRelative(destination.getArea(), offset.getX(), offset.getY());
final CompletableFuture<Boolean> swapResult = plot.swapData(other); final CompletableFuture<Boolean> swapResult = plot.swapData(other);
if (future == null) { if (future == null) {
future = swapResult; future = swapResult;
@ -3215,7 +3297,7 @@ public class Plot {
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
} else { } else {
CuboidRegion region = regions.poll(); CuboidRegion region = regions.poll();
Location[] corners = MainUtil.getCorners(getWorldName(), region); Location[] corners = getCorners(getWorldName(), region);
Location pos1 = corners[0]; Location pos1 = corners[0];
Location pos2 = corners[1]; Location pos2 = corners[1];
Location pos3 = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); Location pos3 = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName());
@ -3230,7 +3312,7 @@ public class Plot {
if (regions.isEmpty()) { if (regions.isEmpty()) {
Plot plot = destination.getRelative(0, 0); Plot plot = destination.getRelative(0, 0);
Plot originPlot = originArea Plot originPlot = originArea
.getPlotAbs(new PlotId(plot.id.x - offset.x, plot.id.y - offset.y)); .getPlotAbs(PlotId.of(plot.id.getX() - offset.getX(), plot.id.getY() - offset.getY()));
final Runnable clearDone = () -> { final Runnable clearDone = () -> {
for (final Plot current : plot.getConnectedPlots()) { for (final Plot current : plot.getConnectedPlots()) {
getManager().claimPlot(current); getManager().claimPlot(current);
@ -3247,7 +3329,7 @@ public class Plot {
} }
final Runnable task = this; final Runnable task = this;
CuboidRegion region = regions.poll(); CuboidRegion region = regions.poll();
Location[] corners = MainUtil.getCorners(getWorldName(), region); Location[] corners = getCorners(getWorldName(), region);
final Location pos1 = corners[0]; final Location pos1 = corners[0];
final Location pos2 = corners[1]; final Location pos2 = corners[1];
Location newPos = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); Location newPos = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName());
@ -3267,8 +3349,8 @@ public class Plot {
* @return * @return
*/ */
public boolean copy(final Plot destination, final Runnable whenDone) { public boolean copy(final Plot destination, final Runnable whenDone) {
PlotId offset = new PlotId(destination.getId().x - this.getId().x, PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(),
destination.getId().y - this.getId().y); destination.getId().getY() - this.getId().getY());
Location db = destination.getBottomAbs(); Location db = destination.getBottomAbs();
Location ob = this.getBottomAbs(); Location ob = this.getBottomAbs();
final int offsetX = db.getX() - ob.getX(); final int offsetX = db.getX() - ob.getX();
@ -3279,7 +3361,7 @@ public class Plot {
} }
Set<Plot> plots = this.getConnectedPlots(); Set<Plot> plots = this.getConnectedPlots();
for (Plot plot : plots) { for (Plot plot : plots) {
Plot other = plot.getRelative(destination.getArea(), offset.x, offset.y); Plot other = plot.getRelative(destination.getArea(), offset.getX(), offset.getY());
if (other.hasOwner()) { if (other.hasOwner()) {
TaskManager.runTaskLater(whenDone, TaskTime.ticks(1L)); TaskManager.runTaskLater(whenDone, TaskTime.ticks(1L));
return false; return false;
@ -3289,7 +3371,7 @@ public class Plot {
destination.updateWorldBorder(); destination.updateWorldBorder();
// copy data // copy data
for (Plot plot : plots) { for (Plot plot : plots) {
Plot other = plot.getRelative(destination.getArea(), offset.x, offset.y); Plot other = plot.getRelative(destination.getArea(), offset.getX(), offset.getY());
other.create(plot.getOwner(), false); other.create(plot.getOwner(), false);
if (!plot.getFlagContainer().getFlagMap().isEmpty()) { if (!plot.getFlagContainer().getFlagMap().isEmpty()) {
final Collection<PlotFlag<?, ?>> existingFlags = other.getFlags(); final Collection<PlotFlag<?, ?>> existingFlags = other.getFlags();
@ -3341,7 +3423,7 @@ public class Plot {
return; return;
} }
CuboidRegion region = regions.poll(); CuboidRegion region = regions.poll();
Location[] corners = MainUtil.getCorners(getWorldName(), region); Location[] corners = getCorners(getWorldName(), region);
Location pos1 = corners[0]; Location pos1 = corners[0];
Location pos2 = corners[1]; Location pos2 = corners[1];
Location newPos = pos1 .add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); Location newPos = pos1 .add(offsetX, 0, offsetZ).withWorld(destination.getWorldName());
@ -3402,7 +3484,162 @@ public class Plot {
return FlagContainer.<T, V>castUnsafe(flagInstance).getValue(); return FlagContainer.<T, V>castUnsafe(flagInstance).getValue();
} }
public FlagContainer getFlagContainer() { public CompletableFuture<String> format(final String iInfo, PlotPlayer<?> player, final boolean full) {
final CompletableFuture<String> future = new CompletableFuture<>();
int num = this.getConnectedPlots().size();
String alias = !this.getAlias().isEmpty() ? this.getAlias() : Captions.NONE.getTranslated();
Location bot = this.getCorners()[0];
PlotSquared.platform().getWorldUtil()
.getBiome(this.getWorldName(), bot.getX(), bot.getZ(), biome -> {
String info = iInfo;
String trusted = PlayerManager.getPlayerList(this.getTrusted());
String members = PlayerManager.getPlayerList(this.getMembers());
String denied = PlayerManager.getPlayerList(this.getDenied());
String seen;
if (Settings.Enabled_Components.PLOT_EXPIRY && ExpireManager.IMP != null) {
if (this.isOnline()) {
seen = Captions.NOW.getTranslated();
} else {
int time = (int) (ExpireManager.IMP.getAge(this) / 1000);
if (time != 0) {
seen = TimeUtil.secToTime(time);
} else {
seen = Captions.UNKNOWN.getTranslated();
}
}
} else {
seen = Captions.NEVER.getTranslated();
}
String description = this.getFlag(DescriptionFlag.class);
if (description.isEmpty()) {
description = Captions.PLOT_NO_DESCRIPTION.getTranslated();
}
StringBuilder flags = new StringBuilder();
Collection<PlotFlag<?, ?>> flagCollection = this.getApplicableFlags(true);
if (flagCollection.isEmpty()) {
flags.append(Captions.NONE.getTranslated());
} else {
String prefix = " ";
for (final PlotFlag<?, ?> flag : flagCollection) {
Object value;
if (flag instanceof DoubleFlag && !Settings.General.SCIENTIFIC) {
value = FLAG_DECIMAL_FORMAT.format(flag.getValue());
} else {
value = flag.toString();
}
flags.append(prefix).append(CaptionUtility
.format(player, Captions.PLOT_FLAG_LIST.getTranslated(), flag.getName(),
CaptionUtility.formatRaw(player, value.toString(), "")));
prefix = ", ";
}
}
boolean build = this.isAdded(player.getUUID());
String owner = this.getOwners().isEmpty() ? "unowned" : PlayerManager.getPlayerList(this.getOwners());
if (this.getArea() != null) {
info = info.replace("%area%",
this.getArea().getWorldName() + (this.getArea().getId() == null ?
"" :
"(" + this.getArea().getId() + ")"));
} else {
info = info.replace("%area%", Captions.NONE.getTranslated());
}
info = info.replace("%id%", this.getId().toString());
info = info.replace("%alias%", alias);
info = info.replace("%num%", String.valueOf(num));
info = info.replace("%desc%", description);
info = info.replace("%biome%", biome.toString().toLowerCase());
info = info.replace("%owner%", owner);
info = info.replace("%members%", members);
info = info.replace("%player%", player.getName());
info = info.replace("%trusted%", trusted);
info = info.replace("%helpers%", members);
info = info.replace("%denied%", denied);
info = info.replace("%seen%", seen);
info = info.replace("%flags%", flags);
info = info.replace("%build%", String.valueOf(build));
if (info.contains("%rating%")) {
final String newInfo = info;
TaskManager.runTaskAsync(() -> {
String info1;
if (Settings.Ratings.USE_LIKES) {
info1 = newInfo.replaceAll("%rating%",
String.format("%.0f%%", Like.getLikesPercentage(this) * 100D));
} else {
int max = 10;
if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES
.isEmpty()) {
max = 8;
}
if (full && Settings.Ratings.CATEGORIES != null
&& Settings.Ratings.CATEGORIES.size() > 1) {
double[] ratings = this.getAverageRatings();
String rating = "";
String prefix = "";
for (int i = 0; i < ratings.length; i++) {
rating +=
prefix + Settings.Ratings.CATEGORIES.get(i) + '=' + String
.format("%.1f", ratings[i]);
prefix = ",";
}
info1 = newInfo.replaceAll("%rating%", rating);
} else {
info1 = newInfo.replaceAll("%rating%",
String.format("%.1f", this.getAverageRating()) + '/' + max);
}
}
future.complete(info1);
});
return;
}
future.complete(info);
});
return future;
}
/**
* If rating categories are enabled, get the average rating by category.<br>
* - The index corresponds to the index of the category in the config
*
* @return Average ratings in each category
*/
public double[] getAverageRatings() {
Map<UUID, Integer> rating;
if (this.getSettings().getRatings() != null) {
rating = this.getSettings().getRatings();
} else if (Settings.Enabled_Components.RATING_CACHE) {
rating = new HashMap<>();
} else {
rating = DBFunc.getRatings(this);
}
int size = 1;
if (!Settings.Ratings.CATEGORIES.isEmpty()) {
size = Math.max(1, Settings.Ratings.CATEGORIES.size());
}
double[] ratings = new double[size];
if (rating == null || rating.isEmpty()) {
return ratings;
}
for (Entry<UUID, Integer> entry : rating.entrySet()) {
int current = entry.getValue();
if (Settings.Ratings.CATEGORIES.isEmpty()) {
ratings[0] += current;
} else {
for (int i = 0; i < Settings.Ratings.CATEGORIES.size(); i++) {
ratings[i] += current % 10 - 1;
current /= 10;
}
}
}
for (int i = 0; i < size; i++) {
ratings[i] /= rating.size();
}
return ratings;
}
@Nonnull public FlagContainer getFlagContainer() {
return this.flagContainer; return this.flagContainer;
} }
} }

View File

@ -27,6 +27,7 @@ package com.plotsquared.core.plot;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.plotsquared.core.collection.QuadMap; import com.plotsquared.core.collection.QuadMap;
import com.plotsquared.core.configuration.CaptionUtility; import com.plotsquared.core.configuration.CaptionUtility;
import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Captions;
@ -51,7 +52,6 @@ import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.LocalBlockQueue; import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.Expression; import com.plotsquared.core.util.Expression;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.RegionUtil; import com.plotsquared.core.util.RegionUtil;
import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.StringMan;
@ -211,8 +211,8 @@ public abstract class PlotArea {
* *
* @return the minimum value for a {@link PlotId} * @return the minimum value for a {@link PlotId}
*/ */
public PlotId getMin() { @Nonnull public PlotId getMin() {
return this.min == null ? new PlotId(Integer.MIN_VALUE, Integer.MIN_VALUE) : this.min; return this.min == null ? PlotId.of(Integer.MIN_VALUE, Integer.MIN_VALUE) : this.min;
} }
/** /**
@ -220,8 +220,8 @@ public abstract class PlotArea {
* *
* @return the maximum value for a {@link PlotId} * @return the maximum value for a {@link PlotId}
*/ */
public PlotId getMax() { @Nonnull public PlotId getMax() {
return this.max == null ? new PlotId(Integer.MAX_VALUE, Integer.MAX_VALUE) : this.max; return this.max == null ? PlotId.of(Integer.MAX_VALUE, Integer.MAX_VALUE) : this.max;
} }
@Override public boolean equals(Object obj) { @Override public boolean equals(Object obj) {
@ -268,8 +268,8 @@ public abstract class PlotArea {
throw new IllegalArgumentException("Must extend GridPlotWorld to provide"); throw new IllegalArgumentException("Must extend GridPlotWorld to provide");
} }
if (config.contains("generator.terrain")) { if (config.contains("generator.terrain")) {
this.terrain = MainUtil.getTerrain(config); this.terrain = ConfigurationUtil.getTerrain(config);
this.type = MainUtil.getType(config); this.type = ConfigurationUtil.getType(config);
} }
this.mobSpawning = config.getBoolean("natural_mob_spawning"); this.mobSpawning = config.getBoolean("natural_mob_spawning");
this.miscSpawnUnowned = config.getBoolean("misc_spawn_unowned"); this.miscSpawnUnowned = config.getBoolean("misc_spawn_unowned");
@ -592,8 +592,8 @@ public abstract class PlotArea {
} }
public boolean contains(@Nonnull final PlotId id) { public boolean contains(@Nonnull final PlotId id) {
return this.min == null || (id.x >= this.min.x && id.x <= this.max.x && id.y >= this.min.y return this.min == null || (id.getX() >= this.min.getX() && id.getX() <= this.max.getX() &&
&& id.y <= this.max.y); id.getY() >= this.min.getY() && id.getY() <= this.max.getY());
} }
public boolean contains(@Nonnull final Location location) { public boolean contains(@Nonnull final Location location) {
@ -657,8 +657,8 @@ public abstract class PlotArea {
@Nullable public Plot getPlotAbs(@Nonnull final PlotId id) { @Nullable public Plot getPlotAbs(@Nonnull final PlotId id) {
Plot plot = getOwnedPlotAbs(id); Plot plot = getOwnedPlotAbs(id);
if (plot == null) { if (plot == null) {
if (this.min != null && (id.x < this.min.x || id.x > this.max.x || id.y < this.min.y if (this.min != null && (id.getX() < this.min.getX() || id.getX() > this.max.getX() || id.getY() < this.min.getY()
|| id.y > this.max.y)) { || id.getY() > this.max.getY())) {
return null; return null;
} }
return new Plot(this, id); return new Plot(this, id);
@ -669,8 +669,8 @@ public abstract class PlotArea {
@Nullable public Plot getPlot(@Nonnull final PlotId id) { @Nullable public Plot getPlot(@Nonnull final PlotId id) {
final Plot plot = getOwnedPlotAbs(id); final Plot plot = getOwnedPlotAbs(id);
if (plot == null) { if (plot == null) {
if (this.min != null && (id.x < this.min.x || id.x > this.max.x || id.y < this.min.y if (this.min != null && (id.getX() < this.min.getX() || id.getX() > this.max.getX() || id.getY() < this.min.getY()
|| id.y > this.max.y)) { || id.getY() > this.max.getY())) {
return null; return null;
} }
return new Plot(this, id); return new Plot(this, id);
@ -692,7 +692,7 @@ public abstract class PlotArea {
if (plot == null) { if (plot == null) {
return null; return null;
} }
return this.clusters != null ? this.clusters.get(plot.getId().x, plot.getId().y) : null; return this.clusters != null ? this.clusters.get(plot.getId().getX(), plot.getId().getY()) : null;
} }
@Nullable @Nullable
@ -710,7 +710,7 @@ public abstract class PlotArea {
} }
@Nullable PlotCluster getCluster(@Nonnull final PlotId id) { @Nullable PlotCluster getCluster(@Nonnull final PlotId id) {
return this.clusters != null ? this.clusters.get(id.x, id.y) : null; return this.clusters != null ? this.clusters.get(id.getX(), id.getY()) : null;
} }
/** /**
@ -796,22 +796,22 @@ public abstract class PlotArea {
PlotId min = getMin(); PlotId min = getMin();
PlotId max = getMax(); PlotId max = getMax();
if (getType() == PlotAreaType.PARTIAL) { if (getType() == PlotAreaType.PARTIAL) {
center = new PlotId(MathMan.average(min.x, max.x), MathMan.average(min.y, max.y)); center = PlotId.of(MathMan.average(min.getX(), max.getX()), MathMan.average(min.getY(), max.getY()));
plots = Math.max(max.x - min.x + 1, max.y - min.y + 1) + 1; plots = Math.max(max.getX() - min.getX() + 1, max.getY() - min.getY() + 1) + 1;
if (start != null) { if (start != null) {
start = new PlotId(start.x - center.x, start.y - center.y); start = PlotId.of(start.getX() - center.getX(), start.getY() - center.getY());
} }
} else { } else {
center = new PlotId(0, 0); center = PlotId.of(0, 0);
plots = Integer.MAX_VALUE; plots = Integer.MAX_VALUE;
} }
for (int i = 0; i < plots; i++) { for (int i = 0; i < plots; i++) {
if (start == null) { if (start == null) {
start = getMeta("lastPlot", new PlotId(0, 0)); start = getMeta("lastPlot", PlotId.of(0, 0));
} else { } else {
start = start.getNextId(1); start = start.getNextId();
} }
PlotId currentId = new PlotId(center.x + start.x, center.y + start.y); PlotId currentId = PlotId.of(center.getX() + start.getX(), center.getY() + start.getY());
Plot plot = getPlotAbs(currentId); Plot plot = getPlotAbs(currentId);
if (plot != null && plot.canClaim(player)) { if (plot != null && plot.canClaim(player)) {
setMeta("lastPlot", start); setMeta("lastPlot", start);
@ -884,7 +884,7 @@ public abstract class PlotArea {
public boolean canClaim(@Nullable final PlotPlayer player, @Nonnull final PlotId pos1, public boolean canClaim(@Nullable final PlotPlayer player, @Nonnull final PlotId pos1,
@Nonnull final PlotId pos2) { @Nonnull final PlotId pos2) {
if (pos1.x == pos2.x && pos1.y == pos2.y) { if (pos1.getX() == pos2.getX() && pos1.getY() == pos2.getY()) {
if (getOwnedPlot(pos1) != null) { if (getOwnedPlot(pos1) != null) {
return false; return false;
} }
@ -894,9 +894,9 @@ public abstract class PlotArea {
} }
return plot.canClaim(player); return plot.canClaim(player);
} }
for (int x = pos1.x; x <= pos2.x; x++) { for (int x = pos1.getX(); x <= pos2.getX(); x++) {
for (int y = pos1.y; y <= pos2.y; y++) { for (int y = pos1.getY(); y <= pos2.getY(); y++) {
final PlotId id = new PlotId(x, y); final PlotId id = PlotId.of(x, y);
final Plot plot = getPlotAbs(id); final Plot plot = getPlotAbs(id);
if (plot == null) { if (plot == null) {
return false; return false;
@ -926,9 +926,9 @@ public abstract class PlotArea {
final Set<UUID> trusted = new HashSet<>(); final Set<UUID> trusted = new HashSet<>();
final Set<UUID> members = new HashSet<>(); final Set<UUID> members = new HashSet<>();
final Set<UUID> denied = new HashSet<>(); final Set<UUID> denied = new HashSet<>();
for (int x = pos1.x; x <= pos2.x; x++) { for (int x = pos1.getX(); x <= pos2.getX(); x++) {
for (int y = pos1.y; y <= pos2.y; y++) { for (int y = pos1.getY(); y <= pos2.getY(); y++) {
PlotId id = new PlotId(x, y); PlotId id = PlotId.of(x, y);
Plot plot = getPlotAbs(id); Plot plot = getPlotAbs(id);
trusted.addAll(plot.getTrusted()); trusted.addAll(plot.getTrusted());
members.addAll(plot.getMembers()); members.addAll(plot.getMembers());
@ -941,11 +941,11 @@ public abstract class PlotArea {
members.removeAll(trusted); members.removeAll(trusted);
denied.removeAll(trusted); denied.removeAll(trusted);
denied.removeAll(members); denied.removeAll(members);
for (int x = pos1.x; x <= pos2.x; x++) { for (int x = pos1.getX(); x <= pos2.getX(); x++) {
for (int y = pos1.y; y <= pos2.y; y++) { for (int y = pos1.getY(); y <= pos2.getY(); y++) {
final boolean lx = x < pos2.x; final boolean lx = x < pos2.getX();
final boolean ly = y < pos2.y; final boolean ly = y < pos2.getY();
final PlotId id = new PlotId(x, y); final PlotId id = PlotId.of(x, y);
final Plot plot = getPlotAbs(id); final Plot plot = getPlotAbs(id);
plot.setTrusted(trusted); plot.setTrusted(trusted);
@ -987,22 +987,23 @@ public abstract class PlotArea {
* @return the plots in the selection which are owned * @return the plots in the selection which are owned
*/ */
public Set<Plot> getPlotSelectionOwned(@Nonnull final PlotId pos1, @Nonnull final PlotId pos2) { public Set<Plot> getPlotSelectionOwned(@Nonnull final PlotId pos1, @Nonnull final PlotId pos2) {
final int size = (1 + pos2.x - pos1.x) * (1 + pos2.y - pos1.y); final int size = (1 + pos2.getX() - pos1.getX()) * (1 + pos2.getY() - pos1.getY());
final Set<Plot> result = new HashSet<>(); final Set<Plot> result = new HashSet<>();
if (size < 16 || size < getPlotCount()) { if (size < 16 || size < getPlotCount()) {
for (final PlotId pid : MainUtil.getPlotSelectionIds(pos1, pos2)) { for (final PlotId pid : Lists.newArrayList((Iterable<? extends PlotId>)
PlotId.PlotRangeIterator.range(pos1, pos2))) {
final Plot plot = getPlotAbs(pid); final Plot plot = getPlotAbs(pid);
if (plot.hasOwner()) { if (plot.hasOwner()) {
if (plot.getId().x > pos1.x || plot.getId().y > pos1.y if (plot.getId().getX() > pos1.getX() || plot.getId().getY() > pos1.getY()
|| plot.getId().x < pos2.x || plot.getId().y < pos2.y) { || plot.getId().getX() < pos2.getX() || plot.getId().getY() < pos2.getY()) {
result.add(plot); result.add(plot);
} }
} }
} }
} else { } else {
for (final Plot plot : getPlots()) { for (final Plot plot : getPlots()) {
if (plot.getId().x > pos1.x || plot.getId().y > pos1.y || plot.getId().x < pos2.x if (plot.getId().getX() > pos1.getX() || plot.getId().getY() > pos1.getY() || plot.getId().getX() < pos2.getX()
|| plot.getId().y < pos2.y) { || plot.getId().getY() < pos2.getY()) {
result.add(plot); result.add(plot);
} }
} }
@ -1022,8 +1023,8 @@ public abstract class PlotArea {
if (this.clusters == null) { if (this.clusters == null) {
this.clusters = new QuadMap<PlotCluster>(Integer.MAX_VALUE, 0, 0, 62) { this.clusters = new QuadMap<PlotCluster>(Integer.MAX_VALUE, 0, 0, 62) {
@Override public CuboidRegion getRegion(PlotCluster value) { @Override public CuboidRegion getRegion(PlotCluster value) {
BlockVector2 pos1 = BlockVector2.at(value.getP1().x, value.getP1().y); BlockVector2 pos1 = BlockVector2.at(value.getP1().getX(), value.getP1().getY());
BlockVector2 pos2 = BlockVector2.at(value.getP2().x, value.getP2().y); BlockVector2 pos2 = BlockVector2.at(value.getP2().getX(), value.getP2().getY());
return new CuboidRegion(pos1.toBlockVector3(), return new CuboidRegion(pos1.toBlockVector3(),
pos2.toBlockVector3(Plot.MAX_HEIGHT - 1)); pos2.toBlockVector3(Plot.MAX_HEIGHT - 1));
} }

View File

@ -25,14 +25,15 @@
*/ */
package com.plotsquared.core.plot; package com.plotsquared.core.plot;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.database.DBFunc; import com.plotsquared.core.database.DBFunc;
import com.plotsquared.core.location.BlockLoc; import com.plotsquared.core.location.BlockLoc;
import com.plotsquared.core.location.Location; import com.plotsquared.core.location.Location;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.RegionUtil; import com.plotsquared.core.util.RegionUtil;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.HashSet; import java.util.HashSet;
import java.util.UUID; import java.util.UUID;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -87,7 +88,8 @@ public class PlotCluster {
} }
private void setRegion() { private void setRegion() {
this.region = RegionUtil.createRegion(this.pos1.x, this.pos2.x, this.pos1.y, this.pos2.y); this.region = RegionUtil.createRegion(this.pos1.getX(), this.pos2.getX(),
this.pos1.getY(), this.pos2.getY());
} }
public CuboidRegion getRegion() { public CuboidRegion getRegion() {
@ -117,7 +119,7 @@ public class PlotCluster {
* Get the area (in plots). * Get the area (in plots).
*/ */
public int getArea() { public int getArea() {
return (1 + this.pos2.x - this.pos1.x) * (1 + this.pos2.y - this.pos1.y); return (1 + this.pos2.getX() - this.pos1.getX()) * (1 + this.pos2.getY() - this.pos1.getY());
} }
public void setArea(PlotArea plotArea) { public void setArea(PlotArea plotArea) {
@ -148,20 +150,22 @@ public class PlotCluster {
} }
@Override public String toString() { @Override public String toString() {
return this.area + ";" + this.pos1.x + ";" + this.pos1.y + ";" + this.pos2.x + ";" return this.area + ";" + this.pos1.toString() + ";" + this.pos2.toString();
+ this.pos2.y;
} }
public void getHome(@Nonnull final Consumer<Location> result) { public void getHome(@Nonnull final Consumer<Location> result) {
final BlockLoc home = this.settings.getPosition(); final BlockLoc home = this.settings.getPosition();
Consumer<Location> locationConsumer = toReturn -> Consumer<Location> locationConsumer = toReturn ->
MainUtil.getHighestBlock(this.area.getWorldName(), toReturn.getX(), toReturn.getZ(), PlotSquared.platform().getWorldUtil().getHighestBlock(this.area.getWorldName(), toReturn.getX(), toReturn.getZ(),
max -> { highest -> {
if (max > toReturn.getY()) { if (highest == 0) {
result.accept(toReturn.withY(1 + max)); highest = 63;
} else { }
result.accept(toReturn); if (highest > toReturn.getY()) {
} result.accept(toReturn.withY(1 + highest));
} else {
result.accept(toReturn);
}
}); });
if (home.getY() == 0) { if (home.getY() == 0) {
// default pos // default pos
@ -180,13 +184,13 @@ public class PlotCluster {
} }
} }
public PlotId getCenterPlotId() { @Nonnull public PlotId getCenterPlotId() {
PlotId bot = getP1(); final PlotId bot = getP1();
PlotId top = getP2(); final PlotId top = getP2();
return new PlotId((bot.x + top.x) / 2, (bot.y + top.y) / 2); return PlotId.of((bot.getX() + top.getX()) / 2, (bot.getY() + top.getY()) / 2);
} }
public Plot getCenterPlot() { @Nullable public Plot getCenterPlot() {
return this.area.getPlotAbs(getCenterPlotId()); return this.area.getPlotAbs(getCenterPlotId());
} }
@ -201,12 +205,12 @@ public class PlotCluster {
} }
public boolean intersects(PlotId pos1, PlotId pos2) { public boolean intersects(PlotId pos1, PlotId pos2) {
return pos1.x <= this.pos2.x && pos2.x >= this.pos1.x && pos1.y <= this.pos2.y return pos1.getX() <= this.pos2.getX() && pos2.getX() >= this.pos1.getX() &&
&& pos2.y >= this.pos1.y; pos1.getY() <= this.pos2.getY() && pos2.getY() >= this.pos1.getY();
} }
public boolean contains(PlotId id) { public boolean contains(PlotId id) {
return this.pos1.x <= id.x && this.pos1.y <= id.y && this.pos2.x >= id.x return this.pos1.getX() <= id.getX() && this.pos1.getY() <= id.getY() &&
&& this.pos2.y >= id.y; this.pos2.getX() >= id.getX() && this.pos2.getY() >= id.getY();
} }
} }

View File

@ -29,12 +29,17 @@ import com.plotsquared.core.location.Direction;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.Iterator;
/**
* Plot (X,Y) tuples for plot locations
* within a plot area
*/
public class PlotId { public class PlotId {
@Deprecated public int x; private final int x;
@Deprecated public int y; private final int y;
private int hash; private final int hash;
/** /**
* PlotId class (PlotId x,y values do not correspond to Block locations) * PlotId class (PlotId x,y values do not correspond to Block locations)
@ -42,9 +47,20 @@ public class PlotId {
* @param x The plot x coordinate * @param x The plot x coordinate
* @param y The plot y coordinate * @param y The plot y coordinate
*/ */
public PlotId(int x, int y) { private PlotId(int x, int y) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.hash = (this.getX() << 16) | (this.getY() & 0xFFFF);
}
/**
* Create a new plot ID instance
*
* @param x The plot x coordinate
* @param y The plot y coordinate
*/
@Nonnull public static PlotId of(final int x, final int y) {
return PlotId.of(x, y);
} }
/** /**
@ -61,6 +77,12 @@ public class PlotId {
return plot; return plot;
} }
/**
* Attempt to parse a plot ID from a string
*
* @param string ID string
* @return Plot ID, or {@code null} if none could be parsed
*/
@Nullable public static PlotId fromStringOrNull(@Nonnull String string) { @Nullable public static PlotId fromStringOrNull(@Nonnull String string) {
String[] parts = string.split("[;,.]"); String[] parts = string.split("[;,.]");
if (parts.length < 2) { if (parts.length < 2) {
@ -74,101 +96,102 @@ public class PlotId {
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {
return null; return null;
} }
return new PlotId(x, y); return of(x, y);
}
public static PlotId of(@Nullable Plot plot) {
return plot != null ? plot.getId() : null;
} }
/** /**
* Gets the PlotId from the HashCode<br> * Gets the PlotId from the HashCode<br>
* Note: Only accurate for small x,z values (short) * Note: Only accurate for small x,z values (short)
* *
* @param hash * @param hash ID hash
* @return * @return Plot ID
*/ */
public static PlotId unpair(int hash) { @Nonnull public static PlotId unpair(final int hash) {
return new PlotId(hash >> 16, hash & 0xFFFF); return PlotId.of(hash >> 16, hash & 0xFFFF);
} }
/**
* Get a copy of the plot ID
*
* @return Plot ID copy
*/
@NotNull public PlotId copy() {
return of(this.getX(), this.getY());
}
/**
* Get the ID X component
*
* @return X component
*/
public int getX() { public int getX() {
return x; return this.getX();
} }
/**
* Get the ID Y component
*
* @return Y component
*/
public int getY() { public int getY() {
return y; return this.getY();
} }
public PlotId getNextId(int step) { /**
* Get the next plot ID for claiming purposes
*
* @return Next plot ID
*/
@Nonnull public PlotId getNextId() {
int absX = Math.abs(x); int absX = Math.abs(x);
int absY = Math.abs(y); int absY = Math.abs(y);
if (absX > absY) { if (absX > absY) {
if (x > 0) { if (x > 0) {
return new PlotId(x, y + 1); return PlotId.of(x, y + 1);
} else { } else {
return new PlotId(x, y - 1); return PlotId.of(x, y - 1);
} }
} else if (absY > absX) { } else if (absY > absX) {
if (y > 0) { if (y > 0) {
return new PlotId(x - 1, y); return PlotId.of(x - 1, y);
} else { } else {
return new PlotId(x + 1, y); return PlotId.of(x + 1, y);
} }
} else { } else {
if (x == y && x > 0) { if (x == y && x > 0) {
return new PlotId(x, y + step); return PlotId.of(x, y + 1);
} }
if (x == absX) { if (x == absX) {
return new PlotId(x, y + 1); return PlotId.of(x, y + 1);
} }
if (y == absY) { if (y == absY) {
return new PlotId(x, y - 1); return PlotId.of(x, y - 1);
} }
return new PlotId(x + 1, y); return PlotId.of(x + 1, y);
} }
} }
public PlotId getRelative(Direction direction) {
return getRelative(direction.getIndex());
}
/** /**
* Get the PlotId in a relative direction * Get the PlotId in a relative direction
* 0 = north<br>
* 1 = east<br>
* 2 = south<br>
* 3 = west<br>
* *
* @param direction * @param direction Direction
* @return PlotId * @return Relative plot ID
*/ */
public PlotId getRelative(int direction) { @Nonnull public PlotId getRelative(@Nonnull final Direction direction) {
switch (direction) { switch (direction) {
case 0: case NORTH:
return new PlotId(this.x, this.y - 1); return PlotId.of(this.getX(), this.getY() - 1);
case 1: case EAST:
return new PlotId(this.x + 1, this.y); return PlotId.of(this.getX() + 1, this.getY());
case 2: case SOUTH:
return new PlotId(this.x, this.y + 1); return PlotId.of(this.getX(), this.getY() + 1);
case 3: case WEST:
return new PlotId(this.x - 1, this.y); return PlotId.of(this.getX() - 1, this.getY());
} }
return this; return this;
} }
/** @Override public boolean equals(final Object obj) {
* Get the PlotId in a relative location
*
* @param x
* @param y
* @return PlotId
*/
public PlotId getRelative(int x, int y) {
return new PlotId(this.x + x, this.y + y);
}
@Override public boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
@ -181,42 +204,91 @@ public class PlotId {
if (getClass() != obj.getClass()) { if (getClass() != obj.getClass()) {
return false; return false;
} }
PlotId other = (PlotId) obj; final PlotId other = (PlotId) obj;
return this.x == other.x && this.y == other.y; return this.getX() == other.getX() && this.getY() == other.getY();
} }
/** /**
* e.g. * Get a String representation of the plot ID where the
* 5;-6 * components are separated by ";"
* *
* @return * @return {@code x + ";" + y}
*/ */
@Override public String toString() { @Override @Nonnull public String toString() {
return this.x + ";" + this.y; return this.getX() + ";" + this.getY();
}
public String toCommaSeparatedString() {
return this.x + "," + this.y;
}
public String toDashSeparatedString() {
return this.x + "-" + this.y;
} }
/** /**
* The PlotId object caches the hashcode for faster mapping/fetching/sorting<br> * Get a String representation of the plot ID where the
* - Recalculation is required if the x/y values change * components are separated by ","
* TODO maybe make x/y values private and add this to the mutators *
* @return {@code x + "," + y}
*/ */
public void recalculateHash() { @Nonnull public String toCommaSeparatedString() {
this.hash = 0; return this.getX() + "," + this.getY();
hashCode(); }
/**
* Get a String representation of the plot ID where the
* components are separated by "-"
*
* @return {@code x + "-" + y}
*/
@Nonnull public String toDashSeparatedString() {
return this.getX() + "-" + this.getY();
} }
@Override public int hashCode() { @Override public int hashCode() {
if (this.hash == 0) {
this.hash = (this.x << 16) | (this.y & 0xFFFF);
}
return this.hash; return this.hash;
} }
public static final class PlotRangeIterator implements Iterator<PlotId>, Iterable<PlotId> {
private final PlotId start;
private final PlotId end;
private int x;
private int y;
private PlotRangeIterator(@Nonnull final PlotId start, @Nonnull final PlotId end) {
this.start = start;
this.end = end;
this.x = this.start.getX();
this.y = this.start.getY();
}
public static PlotRangeIterator range(@Nonnull final PlotId start, @Nonnull final PlotId end) {
return new PlotRangeIterator(start, end);
}
@Override public boolean hasNext() {
if (this.x < this.end.getX()) {
return true;
} else if (this.x == this.end.getX()) {
return this.y < this.end.getY();
} else {
return false;
}
}
@Override public PlotId next() {
if (!hasNext()) {
throw new IndexOutOfBoundsException("The iterator has no more entries");
}
if (this.y == this.end.getY()) {
this.x++;
this.y = 0;
} else {
this.y++;
}
return PlotId.of(this.start.getX() + this.x, this.start.getY() + this.y);
}
@Nonnull @Override public Iterator<PlotId> iterator() {
return this;
}
}
} }

View File

@ -42,6 +42,8 @@ import com.plotsquared.core.plot.flag.GlobalFlagContainer;
import com.plotsquared.core.plot.flag.PlotFlag; import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.plot.flag.implementations.AnalysisFlag; import com.plotsquared.core.plot.flag.implementations.AnalysisFlag;
import com.plotsquared.core.plot.flag.implementations.KeepFlag; import com.plotsquared.core.plot.flag.implementations.KeepFlag;
import com.plotsquared.core.plot.flag.implementations.ServerPlotFlag;
import com.plotsquared.core.plot.message.PlotMessage;
import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.query.PlotQuery; import com.plotsquared.core.util.query.PlotQuery;
@ -216,7 +218,7 @@ public class ExpireManager {
return new ArrayList<>(); return new ArrayList<>();
} }
if (MainUtil.isServerOwned(plot)) { if (plot.getFlag(ServerPlotFlag.class)) {
return new ArrayList<>(); return new ArrayList<>();
} }

View File

@ -28,8 +28,8 @@ package com.plotsquared.core.plot.flag.implementations;
import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.plot.flag.FlagParseException; import com.plotsquared.core.plot.flag.FlagParseException;
import com.plotsquared.core.plot.flag.PlotFlag; import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.TimeUtil;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
@ -61,7 +61,7 @@ public class KeepFlag extends PlotFlag<Object, KeepFlag> {
case "false": case "false":
return flagOf(false); return flagOf(false);
default: default:
return flagOf(MainUtil.timeToSec(input) * 1000 + System.currentTimeMillis()); return flagOf(TimeUtil.timeToSec(input) * 1000 + System.currentTimeMillis());
} }
} }

View File

@ -31,7 +31,7 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.PlotManager; import com.plotsquared.core.plot.PlotManager;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
@ -46,11 +46,11 @@ public class SinglePlotManager extends PlotManager {
} }
@Override public PlotId getPlotIdAbs(int x, int y, int z) { @Override public PlotId getPlotIdAbs(int x, int y, int z) {
return new PlotId(0, 0); return PlotId.of(0, 0);
} }
@Override public PlotId getPlotId(int x, int y, int z) { @Override public PlotId getPlotId(int x, int y, int z) {
return new PlotId(0, 0); return PlotId.of(0, 0);
} }
@Override public Location getPlotBottomLocAbs(@Nonnull final PlotId plotId) { @Override public Location getPlotBottomLocAbs(@Nonnull final PlotId plotId) {
@ -65,7 +65,7 @@ public class SinglePlotManager extends PlotManager {
PlotSquared.platform().getSetupUtils().unload(plot.getWorldName(), false); PlotSquared.platform().getSetupUtils().unload(plot.getWorldName(), false);
final File worldFolder = new File(PlotSquared.platform().getWorldContainer(), plot.getWorldName()); final File worldFolder = new File(PlotSquared.platform().getWorldContainer(), plot.getWorldName());
TaskManager.getPlatformImplementation().taskAsync(() -> { TaskManager.getPlatformImplementation().taskAsync(() -> {
MainUtil.deleteDirectory(worldFolder); FileUtils.deleteDirectory(worldFolder);
if (whenDone != null) { if (whenDone != null) {
whenDone.run(); whenDone.run();
} }

View File

@ -250,7 +250,7 @@ public class EventDispatcher {
})); }));
MainUtil.sendMessage(player, MainUtil.sendMessage(player,
CaptionUtility.format(player, Captions.TELEPORTED_TO_ROAD.getTranslated()) CaptionUtility.format(player, Captions.TELEPORTED_TO_ROAD.getTranslated())
+ " (on-login) " + "(" + plot.getId().x + ";" + plot.getId().y + ")"); + " (on-login) " + "(" + plot.getId().getX() + ";" + plot.getId().getY() + ")");
} }
} }

View File

@ -0,0 +1,67 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.util;
import javax.annotation.Nonnull;
import java.io.File;
import java.nio.file.Paths;
public final class FileUtils {
private FileUtils() {
}
/**
* Attempt to (recursively) delete a directory
*
* @param directory Directory to delete
* @throws RuntimeException If the deletion fails
*/
public static void deleteDirectory(@Nonnull final File directory) {
if (directory.exists()) {
final File[] files = directory.listFiles();
if (null != files) {
for (final File file : files) {
if (file.isDirectory()) {
deleteDirectory(file);
}
}
}
}
if (!directory.delete()) {
throw new RuntimeException(
String.format("Failed to delete directory %s", directory.getName()));
}
}
@Nonnull public static File getFile(@Nonnull final File base, @Nonnull final String path) {
if (Paths.get(path).isAbsolute()) {
return new File(path);
}
return new File(base, path);
}
}

View File

@ -23,25 +23,35 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.plotsquared.core.plot.schematic; package com.plotsquared.core.util;
import com.sk89q.worldedit.world.item.ItemType; import javax.annotation.Nonnull;
public class PlotItem { public final class HashUtil {
public final int x; private HashUtil() {
public final int y;
public final int z;
// public final short[] id;
// public final byte[] data;
public final ItemType[] types;
public final byte[] amount;
public PlotItem(short x, short y, short z, ItemType[] types, byte[] amount) {
this.x = x;
this.y = y;
this.z = z;
this.types = types;
this.amount = amount;
} }
/**
* Hashcode of a boolean array.<br>
* - Used for traversing mega plots quickly.
*
* @param array Booleans to hash
* @return hashcode
*/
public static int hash(@Nonnull final boolean[] array) {
if (array.length == 4) {
if (!array[0] && !array[1] && !array[2] && !array[3]) {
return 0;
}
return ((array[0] ? 1 : 0) << 3) + ((array[1] ? 1 : 0) << 2) + ((array[2] ? 1 : 0) << 1)
+ (array[3] ? 1 : 0);
}
int n = 0;
for (boolean anArray : array) {
n = (n << 1) + (anArray ? 1 : 0);
}
return n;
}
} }

View File

@ -27,6 +27,7 @@ package com.plotsquared.core.util;
import com.plotsquared.core.PlotSquared; import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.command.Like; import com.plotsquared.core.command.Like;
import com.plotsquared.core.configuration.Caption;
import com.plotsquared.core.configuration.CaptionUtility; import com.plotsquared.core.configuration.CaptionUtility;
import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.ConfigurationSection; import com.plotsquared.core.configuration.ConfigurationSection;
@ -36,76 +37,20 @@ import com.plotsquared.core.database.DBFunc;
import com.plotsquared.core.location.Location; import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.ConsolePlayer; import com.plotsquared.core.player.ConsolePlayer;
import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotAreaTerrainType;
import com.plotsquared.core.plot.PlotAreaType;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.expiration.ExpireManager;
import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.plot.flag.implementations.DescriptionFlag;
import com.plotsquared.core.plot.flag.implementations.ServerPlotFlag;
import com.plotsquared.core.plot.flag.types.DoubleFlag;
import com.plotsquared.core.util.net.AbstractDelegateOutputStream;
import com.plotsquared.core.util.query.PlotQuery;
import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import com.plotsquared.core.uuid.UUIDMapping;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.biome.BiomeType;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Scanner;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.IntFunction;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/** /**
* plot functions * plot functions
* @deprecated Do not use
*/ */
public class MainUtil { @Deprecated public class MainUtil {
private static final Logger logger = LoggerFactory.getLogger("P2/" + MainUtil.class.getSimpleName()); private static final Logger logger =
private static final DecimalFormat FLAG_DECIMAL_FORMAT = new DecimalFormat("0"); LoggerFactory.getLogger("P2/" + MainUtil.class.getSimpleName());
static {
FLAG_DECIMAL_FORMAT.setMaximumFractionDigits(340);
}
/** /**
* Cache of mapping x,y,z coordinates to the chunk array<br> * Cache of mapping x,y,z coordinates to the chunk array<br>
@ -154,795 +99,4 @@ public class MainUtil {
} }
} }
public static void upload(@Nullable UUID uuid, @Nullable final String file,
@Nonnull final String extension, @Nullable final RunnableVal<OutputStream> writeTask,
@Nonnull final RunnableVal<URL> whenDone) {
if (writeTask == null) {
TaskManager.runTask(whenDone);
return;
}
final String filename;
final String website;
if (uuid == null) {
uuid = UUID.randomUUID();
website = Settings.Web.URL + "upload.php?" + uuid;
filename = "plot." + extension;
} else {
website = Settings.Web.URL + "save.php?" + uuid;
filename = file + '.' + extension;
}
final URL url;
try {
url = new URL(Settings.Web.URL + "?key=" + uuid + "&type=" + extension);
} catch (MalformedURLException e) {
e.printStackTrace();
whenDone.run();
return;
}
TaskManager.runTaskAsync(() -> {
try {
String boundary = Long.toHexString(System.currentTimeMillis());
URLConnection con = new URL(website).openConnection();
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (OutputStream output = con.getOutputStream();
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) {
String CRLF = "\r\n";
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append(
"Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName())
.append(CRLF);
String param = "value";
writer.append(CRLF).append(param).append(CRLF).flush();
writer.append("--" + boundary).append(CRLF);
writer.append(
"Content-Disposition: form-data; name=\"schematicFile\"; filename=\""
+ filename + '"').append(CRLF);
writer
.append("Content-Type: " + URLConnection.guessContentTypeFromName(filename))
.append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
writeTask.value = new AbstractDelegateOutputStream(output) {
@Override public void close() {
} // Don't close
};
writeTask.run();
output.flush();
writer.append(CRLF).flush();
writer.append("--" + boundary + "--").append(CRLF).flush();
}
String content;
try (Scanner scanner = new Scanner(con.getInputStream()).useDelimiter("\\A")) {
content = scanner.next().trim();
}
if (!content.startsWith("<")) {
}
int responseCode = ((HttpURLConnection) con).getResponseCode();
if (responseCode == 200) {
whenDone.value = url;
}
TaskManager.runTask(whenDone);
} catch (IOException e) {
e.printStackTrace();
TaskManager.runTask(whenDone);
}
});
}
/**
* Resets the biome if it was modified
*
* @param area
* @param pos1
* @param pos2
* @return true if any changes were made
*/
public static boolean resetBiome(PlotArea area, Location pos1, Location pos2) {
BiomeType biome = area.getPlotBiome();
if (!Objects.equals(PlotSquared.platform().getWorldUtil().getBiomeSynchronous(area.getWorldName(), (pos1.getX() + pos2.getX()) / 2,
(pos1.getZ() + pos2.getZ()) / 2), biome)) {
MainUtil
.setBiome(area.getWorldName(), pos1.getX(), pos1.getZ(), pos2.getX(), pos2.getZ(),
biome);
return true;
}
return false;
}
public static String secToTime(long time) {
StringBuilder toreturn = new StringBuilder();
if (time >= 33868800) {
int years = (int) (time / 33868800);
time -= years * 33868800;
toreturn.append(years + "y ");
}
if (time >= 604800) {
int weeks = (int) (time / 604800);
time -= weeks * 604800;
toreturn.append(weeks + "w ");
}
if (time >= 86400) {
int days = (int) (time / 86400);
time -= days * 86400;
toreturn.append(days + "d ");
}
if (time >= 3600) {
int hours = (int) (time / 3600);
time -= hours * 3600;
toreturn.append(hours + "h ");
}
if (time >= 60) {
int minutes = (int) (time / 60);
time -= minutes * 60;
toreturn.append(minutes + "m ");
}
if (toreturn.equals("") || time > 0) {
toreturn.append((time) + "s ");
}
return toreturn.toString().trim();
}
public static long timeToSec(String string) {
if (MathMan.isInteger(string)) {
return Long.parseLong(string);
}
string = string.toLowerCase().trim().toLowerCase();
if (string.equalsIgnoreCase("false")) {
return 0;
}
String[] split = string.split(" ");
long time = 0;
for (String value : split) {
int nums = Integer.parseInt(value.replaceAll("[^\\d]", ""));
String letters = value.replaceAll("[^a-z]", "");
switch (letters) {
case "week":
case "weeks":
case "wks":
case "w":
time += 604800 * nums;
case "days":
case "day":
case "d":
time += 86400 * nums;
case "hour":
case "hr":
case "hrs":
case "hours":
case "h":
time += 3600 * nums;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
time += 60 * nums;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
time += nums;
}
}
return time;
}
/**
* Hashcode of a boolean array.<br>
* - Used for traversing mega plots quickly.
*
* @param array
* @return hashcode
*/
public static int hash(boolean[] array) {
if (array.length == 4) {
if (!array[0] && !array[1] && !array[2] && !array[3]) {
return 0;
}
return ((array[0] ? 1 : 0) << 3) + ((array[1] ? 1 : 0) << 2) + ((array[2] ? 1 : 0) << 1)
+ (array[3] ? 1 : 0);
}
int n = 0;
for (boolean anArray : array) {
n = (n << 1) + (anArray ? 1 : 0);
}
return n;
}
/**
* Get a list of plot ids within a selection.
*
* @param pos1
* @param pos2
* @return
*/
public static ArrayList<PlotId> getPlotSelectionIds(PlotId pos1, PlotId pos2) {
ArrayList<PlotId> myPlots = new ArrayList<>();
for (int x = pos1.x; x <= pos2.x; x++) {
for (int y = pos1.y; y <= pos2.y; y++) {
myPlots.add(new PlotId(x, y));
}
}
return myPlots;
}
/**
* Get the name from a UUID.
*
* @param owner Owner UUID
* @return The player's name, None, Everyone or Unknown
*/
@Nonnull public static String getName(@Nullable UUID owner) {
return getName(owner, true);
}
/**
* Get the name from a UUID.
*
* @param owner Owner UUID
* @param blocking Whether or not the operation can be blocking
* @return The player's name, None, Everyone or Unknown
*/
@Nonnull public static String getName(@Nullable final UUID owner, final boolean blocking) {
if (owner == null) {
return Captions.NONE.getTranslated();
}
if (owner.equals(DBFunc.EVERYONE)) {
return Captions.EVERYONE.getTranslated();
}
if (owner.equals(DBFunc.SERVER)) {
return Captions.SERVER.getTranslated();
}
final String name;
if (blocking) {
name = PlotSquared.get().getImpromptuUUIDPipeline().getSingle(owner, Settings.UUID.BLOCKING_TIMEOUT);
} else {
final UUIDMapping uuidMapping = PlotSquared.get().getImpromptuUUIDPipeline().getImmediately(owner);
if (uuidMapping != null) {
name = uuidMapping.getUsername();
} else {
name = null;
}
}
if (name == null) {
return Captions.UNKNOWN.getTranslated();
}
return name;
}
public static boolean isServerOwned(Plot plot) {
return plot.getFlag(ServerPlotFlag.class);
}
@Nonnull public static Location[] getCorners(@Nonnull final String world, @Nonnull final CuboidRegion region) {
final BlockVector3 min = region.getMinimumPoint();
final BlockVector3 max = region.getMaximumPoint();
return new Location[] {Location.at(world, min), Location.at(world, max)};
}
/**
* Get the corner locations for a list of regions.
*
* @param world
* @param regions
* @return
* @see Plot#getCorners()
*/
@Nonnull public static Location[] getCorners(String world, Collection<CuboidRegion> regions) {
Location min = null;
Location max = null;
for (CuboidRegion region : regions) {
Location[] corners = getCorners(world, region);
if (min == null) {
min = corners[0];
max = corners[1];
continue;
}
Location pos1 = corners[0];
Location pos2 = corners[1];
if (pos2.getX() > max.getX()) {
max = max.withX(pos2.getX());
}
if (pos1.getX() < min.getX()) {
min = min.withX(pos1.getX());
}
if (pos2.getZ() > max.getZ()) {
max = max.withZ(pos2.getZ());
}
if (pos1.getZ() < min.getZ()) {
min = min.withZ(pos1.getZ());
}
}
return new Location[] {min, max};
}
/**
* Fuzzy plot search with spaces separating terms.
* - Terms: type, alias, world, owner, trusted, member
*
* @param search
* @return
*/
public static List<Plot> getPlotsBySearch(String search) {
String[] split = search.split(" ");
int size = split.length * 2;
List<UUID> uuids = new ArrayList<>();
PlotId id = null;
for (String term : split) {
try {
UUID uuid = PlotSquared.get().getImpromptuUUIDPipeline().getSingle(term, Settings.UUID.BLOCKING_TIMEOUT);
if (uuid == null) {
uuid = UUID.fromString(term);
}
uuids.add(uuid);
} catch (Exception ignored) {
id = PlotId.fromString(term);
}
}
ArrayList<ArrayList<Plot>> plotList =
IntStream.range(0, size).mapToObj(i -> new ArrayList<Plot>())
.collect(Collectors.toCollection(() -> new ArrayList<>(size)));
PlotArea area = null;
String alias = null;
for (Plot plot : PlotQuery.newQuery().allPlots().asList()) {
int count = 0;
if (!uuids.isEmpty()) {
for (UUID uuid : uuids) {
if (plot.isOwner(uuid)) {
count += 2;
} else if (plot.isAdded(uuid)) {
count++;
}
}
}
if (id != null) {
if (plot.getId().equals(id)) {
count++;
}
}
if (area != null && plot.getArea().equals(area)) {
count++;
}
if (alias != null && alias.equals(plot.getAlias())) {
count += 2;
}
if (count != 0) {
plotList.get(count - 1).add(plot);
}
}
List<Plot> plots = new ArrayList<>();
for (int i = plotList.size() - 1; i >= 0; i--) {
if (!plotList.get(i).isEmpty()) {
plots.addAll(plotList.get(i));
}
}
return plots;
}
/**
* Get the plot from a string.
*
* @param player Provides a context for what world to search in. Prefixing the term with 'world_name;' will override this context.
* @param arg The search term
* @param message If a message should be sent to the player if a plot cannot be found
* @return The plot if only 1 result is found, or null
*/
@Nullable public static Plot getPlotFromString(PlotPlayer<?> player, String arg, boolean message) {
if (arg == null) {
if (player == null) {
if (message) {
logger.info("[P2] No plot area string was supplied");
}
return null;
}
return player.getCurrentPlot();
}
PlotArea area;
if (player != null) {
area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(arg);
if (area == null) {
area = player.getApplicablePlotArea();
}
} else {
area = ConsolePlayer.getConsole().getApplicablePlotArea();
}
String[] split = arg.split(";|,");
PlotId id;
if (split.length == 4) {
area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(split[0] + ';' + split[1]);
id = PlotId.fromString(split[2] + ';' + split[3]);
} else if (split.length == 3) {
area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(split[0]);
id = PlotId.fromString(split[1] + ';' + split[2]);
} else if (split.length == 2) {
id = PlotId.fromString(arg);
} else {
Collection<Plot> plots;
if (area == null) {
plots = PlotQuery.newQuery().allPlots().asList();
} else {
plots = area.getPlots();
}
for (Plot p : plots) {
String name = p.getAlias();
if (!name.isEmpty() && name.equalsIgnoreCase(arg)) {
return p;
}
}
if (message && player != null) {
player.sendMessage(TranslatableCaption.of("invalid.not_valid_plot_id"));
}
return null;
}
if (area == null) {
if (message && player != null) {
player.sendMessage(TranslatableCaption.of("errors.not_valid_plot_world"));
}
return null;
}
return area.getPlotAbs(id);
}
public static File getFile(File base, String path) {
if (Paths.get(path).isAbsolute()) {
return new File(path);
}
return new File(base, path);
}
/**
* Synchronously set the biome in a selection.
*
* @param world
* @param p1x
* @param p1z
* @param p2x
* @param p2z
* @param biome
*/
public static void setBiome(String world, int p1x, int p1z, int p2x, int p2z, BiomeType biome) {
BlockVector3 pos1 = BlockVector2.at(p1x, p1z).toBlockVector3();
BlockVector3 pos2 = BlockVector2.at(p2x, p2z).toBlockVector3(Plot.MAX_HEIGHT - 1);
CuboidRegion region = new CuboidRegion(pos1, pos2);
PlotSquared.platform().getWorldUtil().setBiomes(world, region, biome);
}
/**
* Get the highest block at a location.
*/
public static void getHighestBlock(String world, int x, int z, IntConsumer result) {
PlotSquared.platform().getWorldUtil().getHighestBlock(world, x, z, highest -> {
if (highest == 0) {
result.accept(63);
} else {
result.accept(highest);
}
});
}
/**
* If rating categories are enabled, get the average rating by category.<br>
* - The index corresponds to the index of the category in the config
*
* @param plot
* @return
*/
public static double[] getAverageRatings(Plot plot) {
Map<UUID, Integer> rating;
if (plot.getSettings().getRatings() != null) {
rating = plot.getSettings().getRatings();
} else if (Settings.Enabled_Components.RATING_CACHE) {
rating = new HashMap<>();
} else {
rating = DBFunc.getRatings(plot);
}
int size = 1;
if (!Settings.Ratings.CATEGORIES.isEmpty()) {
size = Math.max(1, Settings.Ratings.CATEGORIES.size());
}
double[] ratings = new double[size];
if (rating == null || rating.isEmpty()) {
return ratings;
}
for (Entry<UUID, Integer> entry : rating.entrySet()) {
int current = entry.getValue();
if (Settings.Ratings.CATEGORIES.isEmpty()) {
ratings[0] += current;
} else {
for (int i = 0; i < Settings.Ratings.CATEGORIES.size(); i++) {
ratings[i] += current % 10 - 1;
current /= 10;
}
}
}
for (int i = 0; i < size; i++) {
ratings[i] /= rating.size();
}
return ratings;
}
public static void getUUIDsFromString(final String list, final BiConsumer<Collection<UUID>, Throwable> consumer) {
String[] split = list.split(",");
final Set<UUID> result = new HashSet<>();
final List<String> request = new LinkedList<>();
for (final String name : split) {
if (name.isEmpty()) {
consumer.accept(Collections.emptySet(), null);
return;
} else if ("*".equals(name)) {
result.add(DBFunc.EVERYONE);
} else if (name.length() > 16) {
try {
result.add(UUID.fromString(name));
} catch (IllegalArgumentException ignored) {
consumer.accept(Collections.emptySet(), null);
return;
}
} else {
request.add(name);
}
}
if (request.isEmpty()) {
consumer.accept(result, null);
} else {
PlotSquared.get().getImpromptuUUIDPipeline().getUUIDs(request, Settings.UUID.NON_BLOCKING_TIMEOUT)
.whenComplete((uuids, throwable) -> {
if (throwable != null) {
consumer.accept(null, throwable);
} else {
for (final UUIDMapping uuid : uuids) {
result.add(uuid.getUuid());
}
consumer.accept(result, null);
}
});
}
}
/**
* Format a string with plot information.
*
* @param iInfo
* @param plot
* @param player
* @param full
* @param whenDone
*/
public static void format(final String iInfo, final Plot plot, PlotPlayer player,
final boolean full, final RunnableVal<String> whenDone) {
int num = plot.getConnectedPlots().size();
String alias = !plot.getAlias().isEmpty() ? plot.getAlias() : Captions.NONE.getTranslated();
Location bot = plot.getCorners()[0];
PlotSquared.platform().getWorldUtil().getBiome(plot.getWorldName(), bot.getX(), bot.getZ(), biome -> {
String info = iInfo;
String trusted = getPlayerList(plot.getTrusted());
String members = getPlayerList(plot.getMembers());
String denied = getPlayerList(plot.getDenied());
String seen;
if (Settings.Enabled_Components.PLOT_EXPIRY && ExpireManager.IMP != null) {
if (plot.isOnline()) {
seen = Captions.NOW.getTranslated();
} else {
int time = (int) (ExpireManager.IMP.getAge(plot) / 1000);
if (time != 0) {
seen = MainUtil.secToTime(time);
} else {
seen = Captions.UNKNOWN.getTranslated();
}
}
} else {
seen = Captions.NEVER.getTranslated();
}
String description = plot.getFlag(DescriptionFlag.class);
if (description.isEmpty()) {
description = Captions.PLOT_NO_DESCRIPTION.getTranslated();
}
StringBuilder flags = new StringBuilder();
Collection<PlotFlag<?, ?>> flagCollection = plot.getApplicableFlags(true);
if (flagCollection.isEmpty()) {
flags.append(Captions.NONE.getTranslated());
} else {
String prefix = " ";
for (final PlotFlag<?, ?> flag : flagCollection) {
Object value;
if (flag instanceof DoubleFlag && !Settings.General.SCIENTIFIC) {
value = FLAG_DECIMAL_FORMAT.format(flag.getValue());
} else {
value = flag.toString();
}
flags.append(prefix).append(CaptionUtility
.format(player, Captions.PLOT_FLAG_LIST.getTranslated(), flag.getName(),
CaptionUtility.formatRaw(player, value.toString(), "")));
prefix = ", ";
}
}
boolean build = plot.isAdded(player.getUUID());
String owner = plot.getOwners().isEmpty() ? "unowned" : getPlayerList(plot.getOwners());
if (plot.getArea() != null) {
info = info.replace("%area%",
plot.getArea().getWorldName() + (plot.getArea().getId() == null ?
"" :
"(" + plot.getArea().getId() + ")"));
} else {
info = info.replace("%area%", Captions.NONE.getTranslated());
}
info = info.replace("%id%", plot.getId().toString());
info = info.replace("%alias%", alias);
info = info.replace("%num%", String.valueOf(num));
info = info.replace("%desc%", description);
info = info.replace("%biome%", biome.toString().toLowerCase());
info = info.replace("%owner%", owner);
info = info.replace("%members%", members);
info = info.replace("%player%", player.getName());
info = info.replace("%trusted%", trusted);
info = info.replace("%helpers%", members);
info = info.replace("%denied%", denied);
info = info.replace("%seen%", seen);
info = info.replace("%flags%", flags);
info = info.replace("%build%", String.valueOf(build));
if (info.contains("%rating%")) {
final String newInfo = info;
TaskManager.runTaskAsync(() -> {
String info1;
if (Settings.Ratings.USE_LIKES) {
info1 = newInfo.replaceAll("%rating%",
String.format("%.0f%%", Like.getLikesPercentage(plot) * 100D));
} else {
int max = 10;
if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES
.isEmpty()) {
max = 8;
}
if (full && Settings.Ratings.CATEGORIES != null
&& Settings.Ratings.CATEGORIES.size() > 1) {
double[] ratings = MainUtil.getAverageRatings(plot);
String rating = "";
String prefix = "";
for (int i = 0; i < ratings.length; i++) {
rating += prefix + Settings.Ratings.CATEGORIES.get(i) + '=' + String
.format("%.1f", ratings[i]);
prefix = ",";
}
info1 = newInfo.replaceAll("%rating%", rating);
} else {
info1 = newInfo.replaceAll("%rating%",
String.format("%.1f", plot.getAverageRating()) + '/' + max);
}
}
whenDone.run(info1);
});
return;
}
whenDone.run(info);
});
}
public static boolean deleteDirectory(File directory) {
if (directory.exists()) {
File[] files = directory.listFiles();
if (null != files) {
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(file);
}
}
}
}
return (directory.delete());
}
/*
@Nonnull public static String getName(UUID owner) {
if (owner == null) {
return Captions.NONE.getTranslated();
}
if (owner.equals(DBFunc.EVERYONE)) {
return Captions.EVERYONE.getTranslated();
}
if (owner.equals(DBFunc.SERVER)) {
return Captions.SERVER.getTranslated();
}
String name = PlotSquared.get().getImpromptuUUIDPipeline().getSingle(owner, Settings.UUID.BLOCKING_TIMEOUT);
if (name == null) {
return Captions.UNKNOWN.getTranslated();
}
return name;
}
*/
/**
* Get a list of names given a list of UUIDs.
* - Uses the format {@link Captions#PLOT_USER_LIST} for the returned string
*/
public static String getPlayerList(final Collection<UUID> uuids) {
if (uuids.size() < 1) {
return Captions.NONE.getTranslated();
}
final List<UUID> players = new LinkedList<>();
final List<String> users = new LinkedList<>();
for (final UUID uuid : uuids) {
if (uuid == null) {
users.add(Captions.NONE.getTranslated());
} else if (DBFunc.EVERYONE.equals(uuid)) {
users.add(Captions.EVERYONE.getTranslated());
} else if (DBFunc.SERVER.equals(uuid)) {
users.add(Captions.SERVER.getTranslated());
} else {
players.add(uuid);
}
}
try {
for (final UUIDMapping mapping : PlotSquared.get().getImpromptuUUIDPipeline().getNames(players).get(Settings.UUID.BLOCKING_TIMEOUT,
TimeUnit.MILLISECONDS)) {
users.add(mapping.getUsername());
}
} catch (final Exception e) {
e.printStackTrace();
}
String c = Captions.PLOT_USER_LIST.getTranslated();
StringBuilder list = new StringBuilder();
for (int x = 0; x < users.size(); x++) {
if (x + 1 == uuids.size()) {
list.append(c.replace("%user%", users.get(x)).replace(",", ""));
} else {
list.append(c.replace("%user%", users.get(x)));
}
}
return list.toString();
}
public static void getPersistentMeta(UUID uuid, final String key,
final RunnableVal<byte[]> result) {
PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid);
if (player != null) {
result.run(player.getPersistentMeta(key));
} else {
DBFunc.getPersistentMeta(uuid, new RunnableVal<Map<String, byte[]>>() {
@Override public void run(Map<String, byte[]> value) {
result.run(value.get(key));
}
});
}
}
private static <T> T getValueFromConfig(ConfigurationSection config, String path,
IntFunction<Optional<T>> intParser, Function<String, Optional<T>> textualParser,
Supplier<T> defaultValue) {
String value = config.getString(path);
if (value == null) {
return defaultValue.get();
}
if (MathMan.isInteger(value)) {
return intParser.apply(Integer.parseInt(value)).orElseGet(defaultValue);
}
return textualParser.apply(value).orElseGet(defaultValue);
}
public static PlotAreaType getType(ConfigurationSection config) {
return getValueFromConfig(config, "generator.type", PlotAreaType::fromLegacyInt,
PlotAreaType::fromString, () -> PlotAreaType.NORMAL);
}
public static PlotAreaTerrainType getTerrain(ConfigurationSection config) {
return getValueFromConfig(config, "generator.terrain", PlotAreaTerrainType::fromLegacyInt,
PlotAreaTerrainType::fromString, () -> PlotAreaTerrainType.NONE);
}
} }

View File

@ -25,8 +25,13 @@
*/ */
package com.plotsquared.core.util; package com.plotsquared.core.util;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.database.DBFunc;
import com.plotsquared.core.player.OfflinePlotPlayer; import com.plotsquared.core.player.OfflinePlotPlayer;
import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.uuid.UUIDMapping;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -34,8 +39,14 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
/** /**
* Manages player instances * Manages player instances
@ -45,6 +56,142 @@ public abstract class PlayerManager<P extends PlotPlayer<? extends T>, T> {
private final Map<UUID, P> playerMap = new HashMap<>(); private final Map<UUID, P> playerMap = new HashMap<>();
private final Object playerLock = new Object(); private final Object playerLock = new Object();
public static void getUUIDsFromString(@Nonnull final String list,
@Nonnull final BiConsumer<Collection<UUID>, Throwable> consumer) {
String[] split = list.split(",");
final Set<UUID> result = new HashSet<>();
final List<String> request = new LinkedList<>();
for (final String name : split) {
if (name.isEmpty()) {
consumer.accept(Collections.emptySet(), null);
return;
} else if ("*".equals(name)) {
result.add(DBFunc.EVERYONE);
} else if (name.length() > 16) {
try {
result.add(UUID.fromString(name));
} catch (IllegalArgumentException ignored) {
consumer.accept(Collections.emptySet(), null);
return;
}
} else {
request.add(name);
}
}
if (request.isEmpty()) {
consumer.accept(result, null);
} else {
PlotSquared.get().getImpromptuUUIDPipeline()
.getUUIDs(request, Settings.UUID.NON_BLOCKING_TIMEOUT)
.whenComplete((uuids, throwable) -> {
if (throwable != null) {
consumer.accept(null, throwable);
} else {
for (final UUIDMapping uuid : uuids) {
result.add(uuid.getUuid());
}
consumer.accept(result, null);
}
});
}
}
/**
* Get a list of names given a list of UUIDs.
* - Uses the format {@link Captions#PLOT_USER_LIST} for the returned string
*
* @param uuids UUIDs
* @return Name list
*/
@Nonnull public static String getPlayerList(@Nonnull final Collection<UUID> uuids) {
if (uuids.size() < 1) {
return Captions.NONE.getTranslated();
}
final List<UUID> players = new LinkedList<>();
final List<String> users = new LinkedList<>();
for (final UUID uuid : uuids) {
if (uuid == null) {
users.add(Captions.NONE.getTranslated());
} else if (DBFunc.EVERYONE.equals(uuid)) {
users.add(Captions.EVERYONE.getTranslated());
} else if (DBFunc.SERVER.equals(uuid)) {
users.add(Captions.SERVER.getTranslated());
} else {
players.add(uuid);
}
}
try {
for (final UUIDMapping mapping : PlotSquared.get().getImpromptuUUIDPipeline()
.getNames(players).get(Settings.UUID.BLOCKING_TIMEOUT, TimeUnit.MILLISECONDS)) {
users.add(mapping.getUsername());
}
} catch (final Exception e) {
e.printStackTrace();
}
String c = Captions.PLOT_USER_LIST.getTranslated();
StringBuilder list = new StringBuilder();
for (int x = 0; x < users.size(); x++) {
if (x + 1 == uuids.size()) {
list.append(c.replace("%user%", users.get(x)).replace(",", ""));
} else {
list.append(c.replace("%user%", users.get(x)));
}
}
return list.toString();
}
/**
* Get the name from a UUID.
*
* @param owner Owner UUID
* @return The player's name, None, Everyone or Unknown
*/
@Nonnull public static String getName(@Nullable final UUID owner) {
return getName(owner, true);
}
/**
* Get the name from a UUID.
*
* @param owner Owner UUID
* @param blocking Whether or not the operation can be blocking
* @return The player's name, None, Everyone or Unknown
*/
@Nonnull public static String getName(@Nullable final UUID owner, final boolean blocking) {
if (owner == null) {
return Captions.NONE.getTranslated();
}
if (owner.equals(DBFunc.EVERYONE)) {
return Captions.EVERYONE.getTranslated();
}
if (owner.equals(DBFunc.SERVER)) {
return Captions.SERVER.getTranslated();
}
final String name;
if (blocking) {
name = PlotSquared.get().getImpromptuUUIDPipeline()
.getSingle(owner, Settings.UUID.BLOCKING_TIMEOUT);
} else {
final UUIDMapping uuidMapping =
PlotSquared.get().getImpromptuUUIDPipeline().getImmediately(owner);
if (uuidMapping != null) {
name = uuidMapping.getUsername();
} else {
name = null;
}
}
if (name == null) {
return Captions.UNKNOWN.getTranslated();
}
return name;
}
/** /**
* Remove a player from the player map * Remove a player from the player map
* *

View File

@ -25,6 +25,7 @@
*/ */
package com.plotsquared.core.util; package com.plotsquared.core.util;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.Plot;
import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
@ -32,8 +33,45 @@ import com.sk89q.worldedit.regions.CuboidRegion;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import java.util.Collection;
public class RegionUtil { public class RegionUtil {
@Nonnull public static Location[] getCorners(@Nonnull final String world,
@Nonnull final CuboidRegion region) {
final BlockVector3 min = region.getMinimumPoint();
final BlockVector3 max = region.getMaximumPoint();
return new Location[] {Location.at(world, min), Location.at(world, max)};
}
@Nonnull public static Location[] getCorners(String world, Collection<CuboidRegion> regions) {
Location min = null;
Location max = null;
for (CuboidRegion region : regions) {
Location[] corners = getCorners(world, region);
if (min == null) {
min = corners[0];
max = corners[1];
continue;
}
Location pos1 = corners[0];
Location pos2 = corners[1];
if (pos2.getX() > max.getX()) {
max = max.withX(pos2.getX());
}
if (pos1.getX() < min.getX()) {
min = min.withX(pos1.getX());
}
if (pos2.getZ() > max.getZ()) {
max = max.withZ(pos2.getZ());
}
if (pos1.getZ() < min.getZ()) {
min = min.withZ(pos1.getZ());
}
}
return new Location[] {min, max};
}
public static CuboidRegion createRegion(int pos1x, int pos2x, int pos1z, int pos2z) { public static CuboidRegion createRegion(int pos1x, int pos2x, int pos1z, int pos2z) {
return createRegion(pos1x, pos2x, 0, Plot.MAX_HEIGHT - 1, pos1z, pos2z); return createRegion(pos1x, pos2x, 0, Plot.MAX_HEIGHT - 1, pos1z, pos2z);
} }

View File

@ -33,6 +33,7 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.schematic.Schematic; import com.plotsquared.core.plot.schematic.Schematic;
import com.plotsquared.core.queue.LocalBlockQueue; import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.util.net.AbstractDelegateOutputStream;
import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import com.plotsquared.core.util.task.TaskTime; import com.plotsquared.core.util.task.TaskTime;
@ -65,6 +66,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
@ -75,10 +77,15 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.nio.channels.Channels; import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel; import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -88,6 +95,7 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Scanner;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -108,6 +116,84 @@ public abstract class SchematicHandler {
this.worldUtil = worldUtil; this.worldUtil = worldUtil;
} }
public static void upload(@Nullable UUID uuid, @Nullable final String file,
@Nonnull final String extension, @Nullable final RunnableVal<OutputStream> writeTask,
@Nonnull final RunnableVal<URL> whenDone) {
if (writeTask == null) {
TaskManager.runTask(whenDone);
return;
}
final String filename;
final String website;
if (uuid == null) {
uuid = UUID.randomUUID();
website = Settings.Web.URL + "upload.php?" + uuid;
filename = "plot." + extension;
} else {
website = Settings.Web.URL + "save.php?" + uuid;
filename = file + '.' + extension;
}
final URL url;
try {
url = new URL(Settings.Web.URL + "?key=" + uuid + "&type=" + extension);
} catch (MalformedURLException e) {
e.printStackTrace();
whenDone.run();
return;
}
TaskManager.runTaskAsync(() -> {
try {
String boundary = Long.toHexString(System.currentTimeMillis());
URLConnection con = new URL(website).openConnection();
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (OutputStream output = con.getOutputStream();
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) {
String CRLF = "\r\n";
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append(
"Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName())
.append(CRLF);
String param = "value";
writer.append(CRLF).append(param).append(CRLF).flush();
writer.append("--" + boundary).append(CRLF);
writer.append(
"Content-Disposition: form-data; name=\"schematicFile\"; filename=\""
+ filename + '"').append(CRLF);
writer
.append("Content-Type: " + URLConnection.guessContentTypeFromName(filename))
.append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
writeTask.value = new AbstractDelegateOutputStream(output) {
@Override public void close() {
} // Don't close
};
writeTask.run();
output.flush();
writer.append(CRLF).flush();
writer.append("--" + boundary + "--").append(CRLF).flush();
}
String content;
try (Scanner scanner = new Scanner(con.getInputStream()).useDelimiter("\\A")) {
content = scanner.next().trim();
}
if (!content.startsWith("<")) {
}
int responseCode = ((HttpURLConnection) con).getResponseCode();
if (responseCode == 200) {
whenDone.value = url;
}
TaskManager.runTask(whenDone);
} catch (IOException e) {
e.printStackTrace();
TaskManager.runTask(whenDone);
}
});
}
public boolean exportAll(Collection<Plot> collection, final File outputDir, public boolean exportAll(Collection<Plot> collection, final File outputDir,
final String namingScheme, final Runnable ifSuccess) { final String namingScheme, final Runnable ifSuccess) {
if (this.exportAll) { if (this.exportAll) {
@ -139,11 +225,11 @@ public abstract class SchematicHandler {
final String name; final String name;
if (namingScheme == null) { if (namingScheme == null) {
name = name =
plot.getId().x + ";" + plot.getId().y + ',' + plot.getArea() + ',' + owner; plot.getId().getX() + ";" + plot.getId().getY() + ',' + plot.getArea() + ',' + owner;
} else { } else {
name = namingScheme.replaceAll("%id%", plot.getId().toString()) name = namingScheme.replaceAll("%id%", plot.getId().toString())
.replaceAll("%idx%", plot.getId().x + "") .replaceAll("%idx%", plot.getId().getX() + "")
.replaceAll("%idy%", plot.getId().y + "") .replaceAll("%idy%", plot.getId().getY() + "")
.replaceAll("%world%", plot.getArea().toString()); .replaceAll("%world%", plot.getArea().toString());
} }
@ -312,7 +398,7 @@ public abstract class SchematicHandler {
*/ */
public Schematic getSchematic(String name) throws UnsupportedFormatException { public Schematic getSchematic(String name) throws UnsupportedFormatException {
File parent = File parent =
MainUtil.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS); FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS);
if (!parent.exists()) { if (!parent.exists()) {
if (!parent.mkdir()) { if (!parent.mkdir()) {
throw new RuntimeException("Could not create schematic parent directory"); throw new RuntimeException("Could not create schematic parent directory");
@ -321,10 +407,10 @@ public abstract class SchematicHandler {
if (!name.endsWith(".schem") && !name.endsWith(".schematic")) { if (!name.endsWith(".schem") && !name.endsWith(".schematic")) {
name = name + ".schem"; name = name + ".schem";
} }
File file = MainUtil.getFile(PlotSquared.platform().getDirectory(), File file = FileUtils.getFile(PlotSquared.platform().getDirectory(),
Settings.Paths.SCHEMATICS + File.separator + name); Settings.Paths.SCHEMATICS + File.separator + name);
if (!file.exists()) { if (!file.exists()) {
file = MainUtil.getFile(PlotSquared.platform().getDirectory(), file = FileUtils.getFile(PlotSquared.platform().getDirectory(),
Settings.Paths.SCHEMATICS + File.separator + name); Settings.Paths.SCHEMATICS + File.separator + name);
} }
return getSchematic(file); return getSchematic(file);
@ -337,7 +423,7 @@ public abstract class SchematicHandler {
*/ */
public Collection<String> getSchematicNames() { public Collection<String> getSchematicNames() {
final File parent = final File parent =
MainUtil.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS); FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS);
final List<String> names = new ArrayList<>(); final List<String> names = new ArrayList<>();
if (parent.exists()) { if (parent.exists()) {
final String[] rawNames = final String[] rawNames =
@ -436,7 +522,7 @@ public abstract class SchematicHandler {
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
return; return;
} }
MainUtil.upload(uuid, file, "schem", new RunnableVal<OutputStream>() { upload(uuid, file, "schem", new RunnableVal<OutputStream>() {
@Override public void run(OutputStream output) { @Override public void run(OutputStream output) {
try (NBTOutputStream nos = new NBTOutputStream( try (NBTOutputStream nos = new NBTOutputStream(
new GZIPOutputStream(output, true))) { new GZIPOutputStream(output, true))) {
@ -460,7 +546,7 @@ public abstract class SchematicHandler {
return false; return false;
} }
try { try {
File tmp = MainUtil.getFile(PlotSquared.platform().getDirectory(), path); File tmp = FileUtils.getFile(PlotSquared.platform().getDirectory(), path);
tmp.getParentFile().mkdirs(); tmp.getParentFile().mkdirs();
try (NBTOutputStream nbtStream = new NBTOutputStream( try (NBTOutputStream nbtStream = new NBTOutputStream(
new GZIPOutputStream(new FileOutputStream(tmp)))) { new GZIPOutputStream(new FileOutputStream(tmp)))) {
@ -480,7 +566,7 @@ public abstract class SchematicHandler {
// async // async
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(() -> {
// Main positions // Main positions
Location[] corners = MainUtil.getCorners(world, regions); Location[] corners = RegionUtil.getCorners(world, regions);
final Location bot = corners[0]; final Location bot = corners[0];
final Location top = corners[1]; final Location top = corners[1];

View File

@ -0,0 +1,129 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.util;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
public final class TimeUtil {
private TimeUtil() {
}
/**
* Format seconds into a string with the format
* #y #w #d #h #s
*
* @param time Time to format
* @return Formatted string
*/
@Nonnull public static String secToTime(@Nonnegative long time) {
StringBuilder toReturn = new StringBuilder();
if (time >= 33868800) {
int years = (int) (time / 33868800);
time -= years * 33868800;
toReturn.append(years).append("y ");
}
if (time >= 604800) {
int weeks = (int) (time / 604800);
time -= weeks * 604800;
toReturn.append(weeks).append("w ");
}
if (time >= 86400) {
int days = (int) (time / 86400);
time -= days * 86400;
toReturn.append(days).append("d ");
}
if (time >= 3600) {
int hours = (int) (time / 3600);
time -= hours * 3600;
toReturn.append(hours).append("h ");
}
if (time >= 60) {
int minutes = (int) (time / 60);
time -= minutes * 60;
toReturn.append(minutes).append("m ");
}
if (toReturn.length() == 0 || time > 0) {
toReturn.append(time).append("s ");
}
return toReturn.toString().trim();
}
/**
* Parse a time string back into time
*
* @param string String to parse
* @return Parsed time
*/
@Nonnegative public static long timeToSec(@Nonnull String string) {
if (MathMan.isInteger(string)) {
return Long.parseLong(string);
}
string = string.toLowerCase().trim().toLowerCase();
if (string.equalsIgnoreCase("false")) {
return 0;
}
final String[] split = string.split(" ");
long time = 0;
for (final String value : split) {
final int numbers = Integer.parseInt(value.replaceAll("[^\\d]", ""));
String letters = value.replaceAll("[^a-z]", "");
switch (letters) {
case "week":
case "weeks":
case "wks":
case "w":
time += 604800 * numbers;
case "days":
case "day":
case "d":
time += 86400 * numbers;
case "hour":
case "hr":
case "hrs":
case "hours":
case "h":
time += 3600 * numbers;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
time += 60 * numbers;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
time += numbers;
}
}
return time;
}
}

View File

@ -37,6 +37,7 @@ import com.sk89q.jnbt.NBTInputStream;
import com.sk89q.jnbt.NBTOutputStream; import com.sk89q.jnbt.NBTOutputStream;
import com.sk89q.jnbt.Tag; import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
@ -73,6 +74,23 @@ public abstract class WorldUtil {
this.regionManager = regionManager; this.regionManager = regionManager;
} }
/**
* Set the biome in a region
*
* @param world World name
* @param p1x Min X
* @param p1z Min Z
* @param p2x Max X
* @param p2z Max Z
* @param biome Biome
*/
public static void setBiome(String world, int p1x, int p1z, int p2x, int p2z, BiomeType biome) {
BlockVector3 pos1 = BlockVector2.at(p1x, p1z).toBlockVector3();
BlockVector3 pos2 = BlockVector2.at(p2x, p2z).toBlockVector3(Plot.MAX_HEIGHT - 1);
CuboidRegion region = new CuboidRegion(pos1, pos2);
PlotSquared.platform().getWorldUtil().setBiomes(world, region, biome);
}
/** /**
* Check if a given world name corresponds to a real world * Check if a given world name corresponds to a real world
* *
@ -214,7 +232,7 @@ public abstract class WorldUtil {
public void upload(@Nonnull final Plot plot, @Nullable final UUID uuid, public void upload(@Nonnull final Plot plot, @Nullable final UUID uuid,
@Nullable final String file, @Nonnull final RunnableVal<URL> whenDone) { @Nullable final String file, @Nonnull final RunnableVal<URL> whenDone) {
plot.getHome(home -> MainUtil.upload(uuid, file, "zip", new RunnableVal<OutputStream>() { plot.getHome(home -> SchematicHandler.upload(uuid, file, "zip", new RunnableVal<OutputStream>() {
@Override public void run(OutputStream output) { @Override public void run(OutputStream output) {
try (final ZipOutputStream zos = new ZipOutputStream(output)) { try (final ZipOutputStream zos = new ZipOutputStream(output)) {
File dat = getDat(plot.getWorldName()); File dat = getDat(plot.getWorldName());

View File

@ -41,12 +41,12 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -57,7 +57,7 @@ import java.util.stream.Stream;
* The queries can be reused as no results are stored * The queries can be reused as no results are stored
* in the query itself * in the query itself
*/ */
public final class PlotQuery { public final class PlotQuery implements Iterable<Plot> {
private final Collection<PlotFilter> filters = new LinkedList<>(); private final Collection<PlotFilter> filters = new LinkedList<>();
private final PlotAreaManager plotAreaManager; private final PlotAreaManager plotAreaManager;
@ -381,16 +381,6 @@ public final class PlotQuery {
return this.asList(); return this.asList();
} }
/**
* Perform an action on each plot returned by the query
*
* @param consumer Plot consumer
*/
public void forEach(@Nonnull final Consumer<Plot> consumer) {
Preconditions.checkNotNull(consumer, "Consumer may not be null");
this.asCollection().forEach(consumer);
}
/** /**
* Get the amount of plots contained in the query result * Get the amount of plots contained in the query result
* *
@ -429,5 +419,8 @@ public final class PlotQuery {
return this; return this;
} }
@NotNull @Override public Iterator<Plot> iterator() {
return this.asCollection().iterator();
}
} }

View File

@ -25,11 +25,19 @@
*/ */
package com.plotsquared.core.util.query; package com.plotsquared.core.util.query;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class SearchPlotProvider implements PlotProvider { class SearchPlotProvider implements PlotProvider {
@ -40,7 +48,76 @@ class SearchPlotProvider implements PlotProvider {
} }
@Override public Collection<Plot> getPlots() { @Override public Collection<Plot> getPlots() {
return MainUtil.getPlotsBySearch(this.searchTerm); return getPlotsBySearch(this.searchTerm);
}
/**
* Fuzzy plot search with spaces separating terms.
* - Terms: type, alias, world, owner, trusted, member
*
* @param search Search string
* @return Search results
*/
@Nonnull private static List<Plot> getPlotsBySearch(@Nonnull final String search) {
String[] split = search.split(" ");
int size = split.length * 2;
List<UUID> uuids = new ArrayList<>();
PlotId id = null;
for (String term : split) {
try {
UUID uuid = PlotSquared.get().getImpromptuUUIDPipeline()
.getSingle(term, Settings.UUID.BLOCKING_TIMEOUT);
if (uuid == null) {
uuid = UUID.fromString(term);
}
uuids.add(uuid);
} catch (Exception ignored) {
id = PlotId.fromString(term);
}
}
ArrayList<ArrayList<Plot>> plotList =
IntStream.range(0, size).mapToObj(i -> new ArrayList<Plot>())
.collect(Collectors.toCollection(() -> new ArrayList<>(size)));
PlotArea area = null;
String alias = null;
for (Plot plot : PlotQuery.newQuery().allPlots()) {
int count = 0;
if (!uuids.isEmpty()) {
for (UUID uuid : uuids) {
if (plot.isOwner(uuid)) {
count += 2;
} else if (plot.isAdded(uuid)) {
count++;
}
}
}
if (id != null) {
if (plot.getId().equals(id)) {
count++;
}
}
if (area != null && plot.getArea().equals(area)) {
count++;
}
if (alias != null && alias.equals(plot.getAlias())) {
count += 2;
}
if (count != 0) {
plotList.get(count - 1).add(plot);
}
}
List<Plot> plots = new ArrayList<>();
for (int i = plotList.size() - 1; i >= 0; i--) {
if (!plotList.get(i).isEmpty()) {
plots.addAll(plotList.get(i));
}
}
return plots;
} }
} }

View File

@ -34,20 +34,20 @@ if (PS.hasPlotArea("%s0")) {
var maxplot; var maxplot;
for (var i in plots) { for (var i in plots) {
var plot = plots[i]; var plot = plots[i];
if (plot.x > max) { if (plot.getX() > max) {
max = plot.x; max = plot.getX();
maxplot = plot; maxplot = plot;
} }
if (plot.y > max) { if (plot.getY() > max) {
max = plot.y; max = plot.getY();
maxplot = plot; maxplot = plot;
} }
if (-plot.x > max) { if (-plot.getX() > max) {
max = -plot.x; max = -plot.getX();
maxplot = plot; maxplot = plot;
} }
if (-plot.y > max) { if (-plot.getY() > max) {
max = -plot.y; max = -plot.getY();
maxplot = plot; maxplot = plot;
} }
} }

View File

@ -40,7 +40,7 @@ public class FlagTest {
} }
// @Test public void flagTest() throws Exception { // @Test public void flagTest() throws Exception {
// Plot plot = new Plot(null, new PlotId(0, 0)); // Plot plot = new Plot(null, PlotId.of(0, 0));
// plot.owner = UUID.fromString("84499644-ad72-454b-a19d-f28c28df382b"); // plot.owner = UUID.fromString("84499644-ad72-454b-a19d-f28c28df382b");
// //plot.setFlag(use, use.parseValue("33,33:1,6:4")); //TODO fix this so FlagTest will run during compile // //plot.setFlag(use, use.parseValue("33,33:1,6:4")); //TODO fix this so FlagTest will run during compile
// Optional<? extends Collection> flag = plot.getFlag(use); // Optional<? extends Collection> flag = plot.getFlag(use);