diff --git a/pom.xml b/pom.xml index 656689c..47e602e 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.plytki VirtualRealty - 1.4.1 + 1.5.0 jar VirtualRealty @@ -20,7 +20,6 @@ - org.apache.maven.plugins maven-compiler-plugin 3.8.1 @@ -108,6 +107,10 @@ okaeri-repo https://storehouse.okaeri.eu/repository/maven-public/ + + dynmap-repo + http://repo.mikeprimm.com/ + @@ -168,6 +171,12 @@ 3.12.0 compile + + org.dynmap + dynmap-api + 2.0 + provided + diff --git a/src/main/java/me/plytki/virtualrealty/VirtualRealty.java b/src/main/java/me/plytki/virtualrealty/VirtualRealty.java index 9683095..c61925e 100644 --- a/src/main/java/me/plytki/virtualrealty/VirtualRealty.java +++ b/src/main/java/me/plytki/virtualrealty/VirtualRealty.java @@ -14,6 +14,7 @@ import me.plytki.virtualrealty.sql.SQL; import me.plytki.virtualrealty.tasks.PlotExpireTask; import me.plytki.virtualrealty.utils.ConfigurationFactory; +import me.plytki.virtualrealty.utils.SchematicUtil; import me.plytki.virtualrealty.utils.UpdateChecker; import me.plytki.virtualrealty.utils.multiversion.VMaterial; import org.apache.commons.io.FileUtils; @@ -23,8 +24,13 @@ import org.bstats.charts.SimplePie; import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; +import org.dynmap.DynmapAPI; +import org.dynmap.markers.MarkerIcon; +import org.dynmap.markers.MarkerSet; import java.io.*; import java.util.*; @@ -32,26 +38,28 @@ public final class VirtualRealty extends JavaPlugin { + //CORE private static VirtualRealty instance; public static final String PREFIX = "§a§lVR §8§l» §7"; public static ArrayList tasks = new ArrayList<>(); + private static final ArrayList postVersions = new ArrayList<>(); + public static boolean isLegacy = false; + //FILES public static File plotsFolder; public static File plotsSchemaFolder; + public PluginConfiguration pluginConfiguration; + public SizesConfiguration sizesConfiguration; + private final File pluginConfigurationFile = new File(this.getDataFolder(), "config.yml"); + private final File sizesConfigurationFile = new File(this.getDataFolder(), "sizes.yml"); - public static PluginConfiguration pluginConfiguration; - public static SizesConfiguration sizesConfiguration; - private final File pluginConfigurationFile = new File(this.getDataFolder(), "config.yml"); - private final File sizesConfigurationFile = new File(this.getDataFolder(), "sizes.yml"); - - private static final ArrayList postVersions = new ArrayList<>(); - private boolean configError = false; - - public static boolean isLegacy = false; + //DYNMAP API + public static DynmapAPI dapi = null; + public static MarkerSet markerset = null; + public static MarkerIcon markerIcon = null; @Override public void onEnable() { - // Plugin startup logic instance = this; if (!checkLegacyVersions()) { isLegacy = true; @@ -59,8 +67,8 @@ public void onEnable() { String[] updateCheck = UpdateChecker.getUpdate(); if (updateCheck != null) { if (!updateCheck[0].equals(this.getDescription().getVersion())) { - this.getLogger().info("A new version is available!"); - this.getLogger().info("Current version you're using: " + this.getDescription().getVersion()); + this.getLogger().info("A newer version is available!"); + this.getLogger().info("The current version you use: " + this.getDescription().getVersion()); this.getLogger().info("Latest version available: " + updateCheck[0]); this.getLogger().info("Download link: https://www.spigotmc.org/resources/virtual-realty.95599/"); } else { @@ -73,7 +81,6 @@ public void onEnable() { } catch (IOException e) { e.printStackTrace(); } - registerMetrics(); plotsFolder = new File(getInstance().getDataFolder().getAbsolutePath(), "plots"); plotsFolder.mkdirs(); plotsSchemaFolder = new File(plotsFolder.getAbsolutePath(), "primary-terrain"); @@ -82,31 +89,89 @@ public void onEnable() { ConfigurationFactory configFactory = new ConfigurationFactory(); pluginConfiguration = configFactory.createPluginConfiguration(pluginConfigurationFile); sizesConfiguration = configFactory.createSizesConfiguration(sizesConfigurationFile); - } - catch (Exception exception) { + } catch (Exception exception) { exception.printStackTrace(); - //shutdown("Critical error has been encountered!"); return; } - - //createSizesConfig(); + registerMetrics(); loadSizesConfiguration(); connectToDatabase(); + PlotManager.loadPlots(); + if (pluginConfiguration.dynmapMarkers) { + registerDynmap(); + } registerCommands(); registerListeners(); registerTasks(); + checkForOldSchemas(); + debug("Server Version: " + this.getServer().getBukkitVersion() + " | " + this.getServer().getVersion()); } @Override public void onDisable() { - // Plugin shutdown logic - if (configError) { - return; - } + PlotManager.plots.forEach(Plot::update); tasks.forEach(BukkitTask::cancel); SQL.closeConnection(); } + public static void debug(String debugMessage) { + if (VirtualRealty.getPluginConfiguration().debugMode) + VirtualRealty.getInstance().getLogger().warning("DEBUG-MODE > " + debugMessage); + } + + public static void checkForOldSchemas() { + for (Plot plot : PlotManager.plots) { + File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plot.getID() + ".schem"); + if (f.exists()) { + List data = SchematicUtil.oldLoad(plot.getID()); + FileUtils.deleteQuietly(f); + SchematicUtil.save(plot.getID(), data.toArray(new String[0])); + debug("Converted Plot #" + plot.getID() + " | File: " + f.getName()); + } + } + } + + public void registerDynmap() { + new BukkitRunnable() { + @Override + public void run() { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); + if (plugin != null && plugin.isEnabled()) { + dapi = (DynmapAPI) plugin; + if (dapi.markerAPIInitialized()) { + markerset = dapi.getMarkerAPI().getMarkerSet("virtualrealty.plots"); + if (markerset == null) + markerset = dapi.getMarkerAPI().createMarkerSet("virutalrealty.plots", "Plots", dapi.getMarkerAPI().getMarkerIcons(), false); + for (MarkerSet markerSet : dapi.getMarkerAPI().getMarkerSets()) { + if (markerSet.getMarkerSetLabel().equalsIgnoreCase("Plots")) { + markerset = markerSet; + } + } + try { + if (dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon") == null) { + InputStream in = this.getClass().getResourceAsStream("/ploticon.png"); + if (in.available() > 0) { + markerIcon = dapi.getMarkerAPI().createMarkerIcon("virtualrealty_main_icon", "Plots", in); + } + } + else { + markerIcon = dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon"); + } + } + catch (IOException ex) {} + VirtualRealty.debug("Registering plots markers.."); + for (Plot plot : PlotManager.plots) { + PlotManager.resetPlotMarker(plot); + } + VirtualRealty.debug("Registered plots markers"); + this.cancel(); + } + } + } + }.runTaskTimer(this, 20, 20*5); + } + + private void registerCommands() { this.getCommand("plot").setExecutor(new PlotCommand()); this.getCommand("virtualrealty").setExecutor(new VirtualRealtyCommand()); @@ -116,10 +181,12 @@ private void registerListeners() { getServer().getPluginManager().registerEvents(new PlotListener(), this); getServer().getPluginManager().registerEvents(new PlotProtectionListener(), this); getServer().getPluginManager().registerEvents(new WorldListener(), this); + debug("Registered listeners"); } private void registerTasks() { tasks.add(new PlotExpireTask().runTaskTimer(this, 20 * 30, 20 * 30)); + debug("Registered tasks"); } private void registerMetrics() { @@ -162,15 +229,16 @@ public Map call() throws Exception { return valueMap; } })); + debug("Registered metrics"); } private void connectToDatabase() { SQL.connect(); SQL.createTables(); - PlotManager.loadPlots(); + debug("Connected to database"); } - public static void loadSizesConfiguration() { + public void loadSizesConfiguration() { for (PlotSize plotSize : PlotSize.values()) { if (plotSize == PlotSize.CUSTOM) return; SizesConfiguration.PlotSizes.Size classSize = null; @@ -212,6 +280,7 @@ public static void loadSizesConfiguration() { plotSize.setWidth(classSize.width); plotSize.setHeight(classSize.height); } + debug("Loaded sizes config"); } public static VirtualRealty getInstance() { @@ -219,7 +288,19 @@ public static VirtualRealty getInstance() { } public static PluginConfiguration getPluginConfiguration() { - return pluginConfiguration; + return VirtualRealty.getInstance().pluginConfiguration; + } + + public static File getPluginConfigurationFile() { + return VirtualRealty.getInstance().pluginConfigurationFile; + } + + public static SizesConfiguration getSizesConfiguration() { + return VirtualRealty.getInstance().sizesConfiguration; + } + + public static File getSizesConfigurationFile() { + return VirtualRealty.getInstance().sizesConfigurationFile; } public boolean checkLegacyVersions() { @@ -241,12 +322,13 @@ public void setPostVersions() { } public void checkConfig() throws IOException { - File oldConfigFile = new File(this.getDataFolder().getAbsolutePath(), "config.yml"); + File oldConfigFile = new File(this.getDataFolder(), "config.yml"); if (!oldConfigFile.exists()) return; String version = null; boolean isOldVersion = true; boolean updateConfigVersion = false; - BufferedReader reader = new BufferedReader(new FileReader(this.pluginConfigurationFile)); + FileReader fileReader = new FileReader(this.pluginConfigurationFile); + BufferedReader reader = new BufferedReader(fileReader); String latestLine; while((latestLine = reader.readLine()) != null) { if (latestLine.contains("config-version")) { @@ -254,6 +336,8 @@ public void checkConfig() throws IOException { isOldVersion = false; } } + fileReader.close(); + reader.close(); if (version == null) { System.err.println(" "); this.getLogger().warning("Config has been reset due to major config changes!"); @@ -275,7 +359,7 @@ public void checkConfig() throws IOException { oldConfigFile.delete(); } - // update config version +// update config version if (updateConfigVersion) { List lines = new ArrayList<>(); LineIterator iterator = FileUtils.lineIterator(oldConfigFile); @@ -297,12 +381,12 @@ public void checkConfig() throws IOException { } public void checkSizesConfig() throws IOException { - File oldConfigFile = new File(this.getDataFolder().getAbsolutePath(), "sizes.yml"); + File oldConfigFile = new File(this.getDataFolder(), "sizes.yml"); if (!oldConfigFile.exists()) return; String version = null; boolean isOldVersion = true; boolean updateConfigVersion = false; - BufferedReader reader = new BufferedReader(new FileReader(this.pluginConfigurationFile)); + BufferedReader reader = new BufferedReader(new FileReader(this.sizesConfigurationFile)); String latestLine; while((latestLine = reader.readLine()) != null) { if (latestLine.contains("config-version")) { @@ -310,6 +394,7 @@ public void checkSizesConfig() throws IOException { isOldVersion = false; } } + reader.close(); if (version == null) { System.err.println(" "); this.getLogger().warning("Config has been reset due to major config changes!"); diff --git a/src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java b/src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java index ca5e7f1..ffb175b 100644 --- a/src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java +++ b/src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java @@ -3,9 +3,9 @@ import me.plytki.virtualrealty.VirtualRealty; import me.plytki.virtualrealty.enums.Direction; import me.plytki.virtualrealty.enums.PlotSize; -import me.plytki.virtualrealty.exceptions.MaterialMatchException; import me.plytki.virtualrealty.managers.PlotManager; import me.plytki.virtualrealty.objects.Plot; +import me.plytki.virtualrealty.utils.ConfigurationFactory; import me.plytki.virtualrealty.utils.Permissions; import me.plytki.virtualrealty.utils.PlotUtil; import me.plytki.virtualrealty.utils.multiversion.Chat; @@ -28,6 +28,7 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +import java.util.Arrays; import java.util.UUID; public class VirtualRealtyCommand implements CommandExecutor { @@ -56,8 +57,8 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command if (sender instanceof Player) { sender.sendMessage(" "); sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot create §8<§7small/medium/large§8> §8<§7floorMaterial (optional)§8>"); - sender.sendMessage(" §a/vrplot create §8<§7length§8> §8<§7width§8> §8<§7height§8> §8<§7floorMaterial (optional)§8>"); + sender.sendMessage(" §a/vrplot create §8<§7small/medium/large§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); + sender.sendMessage(" §a/vrplot create §8<§7length§8> §8<§7width§8> §8<§7height§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); } break; } @@ -130,7 +131,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); sender.sendMessage(" "); sender.sendMessage("§7§m "); - sender.sendMessage(" §7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); + sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); for (Plot plot : PlotManager.plots) { LocalDateTime localDateTime = plot.getOwnedUntilDate(); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); @@ -144,10 +145,10 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command for (int i = size.length(); i < 6; i++) { size.append(" "); } - BaseComponent textComponent = new TextComponent(" §f" + plot.getID() + "§8 §f" + ownedBy.substring(0, 14) + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); + BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + ownedBy.substring(0, 14) + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent("§a§oClick to show detailed information about the plot! §8(§7ID: §f" + plot.getID() + "§8)")})); textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - new Chat(textComponent).sendTo(p); + new Chat(textComponent).sendTo(sender); } sender.sendMessage("§7§m "); break; @@ -159,6 +160,33 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command sender.sendMessage(" §a/vrplot tp §8<§7plotID§8>"); break; } + case "RELOAD": { + if (!Permissions.hasPermission(sender, tempPermission, "reload")) return false; + try { + ConfigurationFactory configFactory = new ConfigurationFactory(); + VirtualRealty.getInstance().pluginConfiguration = configFactory.createPluginConfiguration(VirtualRealty.getPluginConfigurationFile()); + VirtualRealty.getInstance().sizesConfiguration = configFactory.createSizesConfiguration(VirtualRealty.getSizesConfigurationFile()); + if (VirtualRealty.getPluginConfiguration().dynmapMarkers) { + if (VirtualRealty.markerset != null) { + VirtualRealty.markerset.deleteMarkerSet(); + } + VirtualRealty.getInstance().registerDynmap(); + for (Plot plot : PlotManager.plots) { + PlotManager.resetPlotMarker(plot); + } + } else { + if (VirtualRealty.markerset != null) { + VirtualRealty.markerset.deleteMarkerSet(); + } + } + PlotManager.loadPlots(); + VirtualRealty.getInstance().loadSizesConfiguration(); + } catch (Exception exception) { + exception.printStackTrace(); + } + sender.sendMessage(VirtualRealty.PREFIX + "§aReload completed!"); + break; + } default: { printHelp(sender); break; @@ -170,38 +198,69 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command case "CREATE": { if (!Permissions.hasPermission(sender, commandPermission, "create")) return false; if (sender instanceof Player) { - if ((args.length == 2 || args.length == 3) && !args[1].equalsIgnoreCase("custom")) { + if (Arrays.stream(PlotSize.values()).anyMatch(plotSize -> plotSize.name().equalsIgnoreCase(args[1])) && !args[1].equalsIgnoreCase(PlotSize.CUSTOM.name())) { PlotSize plotSize = null; try { plotSize = PlotSize.valueOf(args[1].toUpperCase()); } catch (IllegalArgumentException ignored) { } if (plotSize != null) { - //TODO create a plot if (PlotManager.isColliding(PlotUtil.getPlotRegion(location, Direction.byYaw(location.getYaw()), plotSize.getLength(), plotSize.getWidth(), plotSize.getHeight()))) { sender.sendMessage(VirtualRealty.PREFIX + "§cYou cant create new plot on the existing plot!"); return false; } else { - Material material = plotSize.getFloorMaterial(); - if (args.length == 3) { + Material floorMaterial = null; + byte floorData = 0; + if (args.length >= 3) { try { - //String[] materialText = Arrays.copyOfRange(args, 3, args.length); - material = Material.getMaterial(args[2].toUpperCase().replaceAll(" ", "_")); + floorMaterial = VMaterial.getMaterial(args[2].split(":")[0].toUpperCase()); + if (floorMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + "§cCouldn't get floor material with specified name!"); + return false; + } } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + "§cMaterial not found"); + sender.sendMessage(VirtualRealty.PREFIX + "§cCouldn't get floor material with specified name!"); return false; } + if (args[2].split(":").length == 2) { + floorData = Byte.parseByte(args[2].split(":")[1]); + } + } + Material borderMaterial = null; + byte borderData = 0; + if (args.length >= 4) { + try { + borderMaterial = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); + if (borderMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + "§cCouldn't get border material with specified name!"); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + "§cCouldn't get border material with specified name!"); + return false; + } + if (args[3].split(":").length == 2) { + borderData = Byte.parseByte(args[3].split(":")[1]); + } } sender.sendMessage(VirtualRealty.PREFIX + "§aNot colliding. Creating plot.."); long timeStart = System.currentTimeMillis(); - Plot plot = PlotManager.createPlot(location, plotSize, material); + Plot plot = PlotManager.createPlot(location, plotSize); + if (floorMaterial != null) { + plot.setFloor(floorMaterial, floorData); + } + if (borderMaterial != null) { + plot.setBorder(borderMaterial, borderData); + } long timeEnd = System.currentTimeMillis(); BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + "§aPlot "); BaseComponent textComponent2 = new TextComponent("§8#§7" + plot.getID()); BaseComponent textComponent3 = new TextComponent(" §acreated! §8(§7" + (timeEnd - timeStart) + " ms§8)"); textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent("§a§oClick to show detailed information about the plot! §8(§7ID: §f" + plot.getID() + "§8)")})); textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - new Chat(textComponent, textComponent2, textComponent3).sendTo(p); + textComponent.addExtra(textComponent2); + textComponent.addExtra(textComponent3); + new Chat(textComponent).sendTo(p); } } else { sender.sendMessage(VirtualRealty.PREFIX + "§cSize not recognized!"); @@ -227,26 +286,58 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command sender.sendMessage(VirtualRealty.PREFIX + "§cYou cant create new plot on the existing plot!"); return false; } else { - Material material = Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"); + Material floorMaterial = null; + byte floorData = 0; if (args.length >= 5) { try { - //String[] materialText = Arrays.copyOfRange(args, 5, args.length); - material = Material.getMaterial(args[4].toUpperCase().replaceAll(" ", "_")); + floorMaterial = VMaterial.getMaterial(args[4].split(":")[0].toUpperCase()); + if (floorMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + "§cCouldn't get floor material with specified name!"); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + "§cCouldn't get floor material with specified name!"); + return false; + } + if (args[4].split(":").length == 2) { + floorData = Byte.parseByte(args[4].split(":")[1]); + } + } + Material borderMaterial = null; + byte borderData = 0; + if (args.length >= 6) { + try { + borderMaterial = VMaterial.getMaterial(args[5].split(":")[0].toUpperCase()); + if (borderMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + "§cCouldn't get border material with specified name!"); + return false; + } } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + "§cMaterial not found"); + sender.sendMessage(VirtualRealty.PREFIX + "§cCouldn't get border material with specified name!"); return false; } + if (args[5].split(":").length == 2) { + borderData = Byte.parseByte(args[5].split(":")[1]); + } } sender.sendMessage(VirtualRealty.PREFIX + "§aNot colliding. Creating plot.."); long timeStart = System.currentTimeMillis(); - Plot plot = PlotManager.createPlot(location, length, width, height, material); + Plot plot = PlotManager.createPlot(location, length, width, height); + if (floorMaterial != null) { + plot.setFloor(floorMaterial, floorData); + } + if (borderMaterial != null) { + plot.setBorder(borderMaterial, borderData); + } long timeEnd = System.currentTimeMillis(); BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + "§aPlot "); BaseComponent textComponent2 = new TextComponent("§8#§7" + plot.getID()); BaseComponent textComponent3 = new TextComponent(" §acreated! §8(§7" + (timeEnd - timeStart) + " ms§8)"); textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent("§a§oClick to show detailed information about the plot! §8(§7ID: §f" + plot.getID() + "§8)")})); textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - new Chat(textComponent, textComponent2, textComponent3).sendTo(p); + textComponent.addExtra(textComponent2); + textComponent.addExtra(textComponent3); + new Chat(textComponent).sendTo(p); } } } @@ -337,13 +428,13 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command if (args[3].split(":").length == 2) { data = Byte.parseByte(args[3].split(":")[1]); } - plot.setFloorMaterial(material, data); - if (args.length == 5 && (args[4].toLowerCase().startsWith("t"))) { - plot.initializeFloor(); - sender.sendMessage(VirtualRealty.PREFIX + "§aNew floor material has been set and initialized!"); - plot.update(); - return false; - } + plot.setFloor(material, data); +// if (args.length == 5 && (args[4].toLowerCase().startsWith("t"))) { +// plot.initializeFloor(); +// sender.sendMessage(VirtualRealty.PREFIX + "§aNew floor material has been set and initialized!"); +// plot.update(); +// return false; +// } sender.sendMessage(VirtualRealty.PREFIX + "§aNew floor material has been set!"); plot.update(); break; @@ -594,6 +685,7 @@ private static void printInfo(CommandSender sender, String assignedBy, String da sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); + sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); @@ -610,15 +702,16 @@ private static void printHelp(CommandSender sender) { sender.sendMessage(" §a/vrplot info §8- §7Prints info about plot"); sender.sendMessage(" §a/vrplot list §8- §7Prints all plots"); sender.sendMessage(" §a/vrplot tp §8- §7Teleports to the plot"); + sender.sendMessage(" §a/vrplot reload §8- §7Reloads plugin"); } private static void printSetHelp(CommandSender sender) { sender.sendMessage(" "); sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownedBy §8<§7username§8>"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7floorMaterial §8<§7material§8> §8<§7initialize{true/false} (optional)§8>"); + sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7floorMaterial §8<§7material§8>"); sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7borderMaterial §8<§7material§8>"); sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownershipExpires §8<§7dd/mm/YYYY§8> §8<§7HH:mm (optional)§8>"); } -} +} \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java b/src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java index 9f5a0c7..9de9039 100644 --- a/src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java +++ b/src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java @@ -3,8 +3,16 @@ import eu.okaeri.configs.OkaeriConfig; import eu.okaeri.configs.annotation.*; import me.plytki.virtualrealty.VirtualRealty; +import me.plytki.virtualrealty.enums.HighlightType; import org.bukkit.GameMode; +import java.awt.*; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + @Header("################################################################") @Header("# #") @@ -21,6 +29,10 @@ public class PluginConfiguration extends OkaeriConfig { public String configVersion = VirtualRealty.getInstance().getDescription().getVersion(); @Comment("-------------------------") + @Comment("Debug mode (Dev only)") + @CustomKey("debug-mode") + public boolean debugMode = false; + @Comment("Set player gamemode to change when they enter their plot") @CustomKey("enable-plot-gamemode") public boolean enablePlotGameMode = false; @@ -46,6 +58,71 @@ public GameMode getGameMode() { @CustomKey("allow-outplot-build") public boolean allowOutPlotBuild = true; + @Comment("Enables dynmap plots highlighting") + @CustomKey("enable-dynmap-markers") + public boolean dynmapMarkers = false; + + @Comment("Choose which type of plots should be highlighted on Dynmap page | Choose from: { ALL, AVAILABLE, OWNED }") + @CustomKey("dynmap-type") + public HighlightType dynmapType = HighlightType.ALL; + + @CustomKey("dynmap-markers") + public MarkerColor dynmapMarkersColor = new MarkerColor(new MarkerColor.Available("#80eb34", .3), new MarkerColor.Owned("#ffbf00", .45)); + + @Names(strategy = NameStrategy.IDENTITY) + public static class MarkerColor extends OkaeriConfig { + + public Available available; + + public Owned owned; + + public MarkerColor(Available available, Owned owned) { + this.available = available; + this.owned = owned; + } + + @Names(strategy = NameStrategy.IDENTITY) + public static class Available extends OkaeriConfig { + + public String color; + + public double opacity; + + public Available(String color, double opacity) { + this.color = color; + this.opacity = opacity; + } + + public int getHexColor() { + return Integer.decode("0x" + color.replaceAll("#", "")); + } + + } + + @Names(strategy = NameStrategy.IDENTITY) + public static class Owned extends OkaeriConfig { + + public String color; + + public double opacity; + + public Owned(String color, double opacity) { + this.color = color; + this.opacity = opacity; + } + + public int getHexColor() { + return Integer.decode("0x" + color.replaceAll("#", "")); + } + + } + + } + + @Comment("Enables plots enter/leave sounds") + @CustomKey("plot-sounds") + public boolean plotSound = true; + @Comment("Type of data recording") @Comment("H2 - Local database (Automatically started with our plugin)") @Comment("MYSQL - External database") @@ -62,7 +139,6 @@ public GameMode getGameMode() { @CustomKey("mysql") public MySQL mysql = new MySQL("localhost", 3306, "db", "root", "passwd", true, "vr_plots"); - public enum DataModel { H2, MYSQL @@ -86,9 +162,6 @@ public static class MySQL extends OkaeriConfig { @Variable("VR_MYSQL_USERS_TABLE_NAME") public String plotsTableName; - public MySQL() { - } - public MySQL(String hostname, int port, String database, String user, String password, boolean useSSL, String plotsTableName) { this.hostname = hostname; this.port = port; diff --git a/src/main/java/me/plytki/virtualrealty/enums/HighlightType.java b/src/main/java/me/plytki/virtualrealty/enums/HighlightType.java new file mode 100644 index 0000000..dc8f244 --- /dev/null +++ b/src/main/java/me/plytki/virtualrealty/enums/HighlightType.java @@ -0,0 +1,9 @@ +package me.plytki.virtualrealty.enums; + +public enum HighlightType { + + ALL, + AVAILABLE, + OWNED + +} diff --git a/src/main/java/me/plytki/virtualrealty/listeners/PlotListener.java b/src/main/java/me/plytki/virtualrealty/listeners/PlotListener.java index 532ef12..4c1d703 100644 --- a/src/main/java/me/plytki/virtualrealty/listeners/PlotListener.java +++ b/src/main/java/me/plytki/virtualrealty/listeners/PlotListener.java @@ -3,6 +3,8 @@ import me.plytki.virtualrealty.VirtualRealty; import me.plytki.virtualrealty.managers.PlotManager; import me.plytki.virtualrealty.objects.Plot; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -23,10 +25,10 @@ public void onPlotMove(PlayerMoveEvent e) { Plot plot = PlotManager.getPlot(to); if (plot != null) { OfflinePlayer offlinePlayer; - String enterPlotString = "§aYou have entered available plot!"; + String enterPlotString = "§2You have entered available plot!"; if (plot.getOwnedBy() != null) { offlinePlayer = Bukkit.getOfflinePlayer(plot.getOwnedBy()); - enterPlotString = "§eYou have entered §f" + offlinePlayer.getName() + "'s §eplot!"; + enterPlotString = "§7You have entered §2" + offlinePlayer.getName() + "'s §7plot!"; } if (!enteredPlot.containsKey(player)) { enteredPlot.put(player, new AbstractMap.SimpleEntry<>(plot, true)); @@ -39,6 +41,14 @@ public void onPlotMove(PlayerMoveEvent e) { } } } + if (!VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8")) { + if (VirtualRealty.getPluginConfiguration().plotSound) { + player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_OPEN, 0.4f, 0.8f); + } + } + if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(enterPlotString)); + } } else { if (!enteredPlot.get(player).getValue()) { enteredPlot.replace(player, new AbstractMap.SimpleEntry<>(plot, true)); @@ -58,13 +68,21 @@ public void onPlotMove(PlayerMoveEvent e) { String leavePlotString = "§cYou have left available plot!"; if (enteredPlot.get(player).getKey().getOwnedBy() != null) { offlinePlayer = Bukkit.getOfflinePlayer(enteredPlot.get(player).getKey().getOwnedBy()); - leavePlotString = "§cYou have left §f" + offlinePlayer.getName() + "'s §cplot!"; + leavePlotString = "§7You have left §2" + offlinePlayer.getName() + "'s §7plot!"; if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { if (enteredPlot.get(player).getKey().getOwnedBy() != null && enteredPlot.get(player).getKey().getOwnedBy().equals(player.getUniqueId())) { player.setGameMode(Bukkit.getServer().getDefaultGameMode()); } } } + if (!VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8")) { + if (VirtualRealty.getPluginConfiguration().plotSound) { + player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_CLOSE, 0.3f, 1f); + } + if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(leavePlotString)); + } + } enteredPlot.remove(player); return; } diff --git a/src/main/java/me/plytki/virtualrealty/managers/PlotManager.java b/src/main/java/me/plytki/virtualrealty/managers/PlotManager.java index 4312196..83e932c 100644 --- a/src/main/java/me/plytki/virtualrealty/managers/PlotManager.java +++ b/src/main/java/me/plytki/virtualrealty/managers/PlotManager.java @@ -1,26 +1,36 @@ package me.plytki.virtualrealty.managers; import me.plytki.virtualrealty.VirtualRealty; +import me.plytki.virtualrealty.enums.HighlightType; import me.plytki.virtualrealty.enums.PlotSize; import me.plytki.virtualrealty.objects.Cuboid; import me.plytki.virtualrealty.objects.Plot; import me.plytki.virtualrealty.objects.math.BlockVector2; import me.plytki.virtualrealty.objects.math.BlockVector3; import me.plytki.virtualrealty.sql.SQL; +import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; +import org.dynmap.markers.AreaMarker; import java.sql.ResultSet; import java.sql.SQLException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class PlotManager { + private static final String markerString = "

Plot #%s

Owned By: Available"; + private static final String markerOwnedString = "

Plot #%s

Owned By: %s
Owned Until: %s"; + + public static ArrayList areaMarkers = new ArrayList<>(); public static ArrayList plots = new ArrayList<>(); public static void loadPlots() { + plots.clear(); try { ResultSet rs = SQL.getStatement().executeQuery("SELECT * FROM `vr_plots`"); while (rs.next()) { @@ -32,28 +42,14 @@ public static void loadPlots() { } public static Plot createPlot(Location creationLocation, PlotSize plotSize) { - Plot plot = new Plot(creationLocation, plotSize.getFloorMaterial(), plotSize); - plots.add(plot); - plot.insert(); - return plot; - } - - public static Plot createPlot(Location creationLocation, PlotSize plotSize, Material material) { - Plot plot = new Plot(creationLocation, material, plotSize); + Plot plot = new Plot(creationLocation, plotSize.getFloorMaterial(), plotSize.getBorderMaterial(), plotSize); plots.add(plot); plot.insert(); return plot; } public static Plot createPlot(Location creationLocation, int length, int width, int height) { - Plot plot = new Plot(creationLocation, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), length, width, height); - plots.add(plot); - plot.insert(); - return plot; - } - - public static Plot createPlot(Location creationLocation, int length, int width, int height, Material material) { - Plot plot = new Plot(creationLocation, material, length, width, height); + Plot plot = new Plot(creationLocation, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), length, width, height); plots.add(plot); plot.insert(); return plot; @@ -83,7 +79,6 @@ public static List getPlayerPlots(UUID owner) { public static Plot getPlot(Location location) { BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); for (Plot plot : plots) { - //CuboidRegion region = new CuboidRegion(plot.getBottomLeftCorner(), plot.getTopRightCorner()); Cuboid region = new Cuboid(plot.getBottomLeftCorner(), plot.getTopRightCorner(), location.getWorld()); if(region.contains(newVector)) { return plot; @@ -116,7 +111,6 @@ public static boolean isLocationInBorderedPlot(Location location, Plot plot) { } public static boolean isColliding(Cuboid newPlot) { - //long time = System.currentTimeMillis(); for (Plot plot : plots) { Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), plot.getCreatedLocation().getWorld()); for (BlockVector2 vector2 : region.getWalls()) { @@ -125,8 +119,60 @@ public static boolean isColliding(Cuboid newPlot) { } } } - //System.out.println("isColliding() time " + (System.currentTimeMillis() - time)); return false; } + public static AreaMarker getAreaMarker(String areaMarkerName) { + for (AreaMarker areaMarker : VirtualRealty.markerset.getAreaMarkers()) { + if (areaMarker.getMarkerID().equalsIgnoreCase(areaMarkerName)) { + return areaMarker; + } + } + return null; + } + + public static void resetPlotMarker(Plot plot) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + String ownedBy; + double opacity; + int color; + if (plot.getOwnedBy() == null) { + ownedBy = "Available"; + color = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.available.getHexColor(); + opacity = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.available.opacity; + } else { + ownedBy = plot.getPlotOwner().getName(); + color = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.owned.getHexColor(); + opacity = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.owned.opacity; + } + if (VirtualRealty.getPluginConfiguration().dynmapType == HighlightType.OWNED && plot.getOwnedBy() == null) return; + if (VirtualRealty.getPluginConfiguration().dynmapType == HighlightType.AVAILABLE && plot.getOwnedBy() != null) return; + AreaMarker marker = getAreaMarker("virtualrealty.plots." + plot.getID()); + if (marker == null) { + marker = VirtualRealty.markerset.createAreaMarker("virtualrealty.plots." + plot.getID(), + + plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true, + + plot.getCreatedWorld(), new double[]{plot.getXMin(), plot.getXMax()}, new double[]{plot.getZMin(), plot.getZMax()}, true); + + areaMarkers.add(marker); + } else { + marker.setLabel( + + plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true); + + } + marker.setFillStyle(opacity, color); + marker.setLineStyle(2, 0.8, 0x474747); + marker.setMarkerSet(VirtualRealty.markerset); + } + + public static void removeDynMapMarker(Plot plot) { + if (VirtualRealty.dapi == null || VirtualRealty.markerset == null) return; + AreaMarker marker = VirtualRealty.markerset.findAreaMarker("virtualrealty.plots." + plot.getID()); + areaMarkers.remove(marker); + marker.deleteMarker(); + } + } \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/objects/Plot.java b/src/main/java/me/plytki/virtualrealty/objects/Plot.java index 66aa55c..f274a03 100644 --- a/src/main/java/me/plytki/virtualrealty/objects/Plot.java +++ b/src/main/java/me/plytki/virtualrealty/objects/Plot.java @@ -7,11 +7,8 @@ import me.plytki.virtualrealty.objects.math.BlockVector3; import me.plytki.virtualrealty.sql.SQL; import me.plytki.virtualrealty.utils.SchematicUtil; -import me.plytki.virtualrealty.utils.multiversion.VMaterial; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; +import org.apache.commons.io.FileUtils; +import org.bukkit.*; import org.bukkit.block.Block; import java.io.File; @@ -20,7 +17,6 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; -import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; @@ -36,6 +32,8 @@ public class Plot { private int height; private Material floorMaterial; private byte floorData; + private Material borderMaterial; + private byte borderData; private Location createdLocation; private Direction createdDirection; private BlockVector3 bottomLeftCorner; @@ -43,19 +41,22 @@ public class Plot { private BlockVector3 borderBottomLeftCorner; private BlockVector3 borderTopRightCorner; private GameMode selectedGameMode; + private String createdWorld; @Override public String toString() { return "{ ID: " + ID + ", ownedBy: " + ownedBy + "}"; } - public Plot(Location location, Material floorMaterial, PlotSize plotSize) { + public Plot(Location location, Material floorMaterial, Material borderMaterial, PlotSize plotSize) { this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.plots.get(PlotManager.plots.size() - 1).getID() + 1; this.ownedBy = null; this.assignedBy = null; - this.ownedUntilDate = LocalDateTime.of(2999, 1, 1, 0, 0); + this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); this.floorMaterial = floorMaterial; this.floorData = 0; + this.borderMaterial = borderMaterial; + this.borderData = 0; this.plotSize = plotSize; this.length = plotSize.getLength(); this.width = plotSize.getWidth(); @@ -63,17 +64,23 @@ public Plot(Location location, Material floorMaterial, PlotSize plotSize) { this.createdLocation = location; this.createdDirection = Direction.byYaw(location.getYaw()); this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); + this.createdWorld = location.getWorld().getName(); initialize(); initializeCorners(); + if (VirtualRealty.markerset != null) { + PlotManager.resetPlotMarker(this); + } } - public Plot(Location location, Material floorMaterial, int length, int width, int height) { + public Plot(Location location, Material floorMaterial, Material borderMaterial, int length, int width, int height) { this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.plots.get(PlotManager.plots.size() - 1).getID() + 1; this.ownedBy = null; this.assignedBy = null; this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); this.floorMaterial = floorMaterial; this.floorData = 0; + this.borderMaterial = borderMaterial; + this.borderData = 0; this.plotSize = PlotSize.CUSTOM; this.length = length; this.width = width; @@ -81,8 +88,12 @@ public Plot(Location location, Material floorMaterial, int length, int width, in this.createdLocation = location; this.createdDirection = Direction.byYaw(location.getYaw()); this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); + this.createdWorld = location.getWorld().getName(); initialize(); initializeCorners(); + if (VirtualRealty.markerset != null) { + PlotManager.resetPlotMarker(this); + } } @@ -94,20 +105,50 @@ public Plot(ResultSet rs) { this.ownedUntilDate = rs.getTimestamp("ownedUntilDate").toLocalDateTime(); this.floorMaterial = Material.getMaterial(rs.getString("floorMaterial").split(":")[0]); this.floorData = rs.getString("floorMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("floorMaterial").split(":")[1]); + if (rs.getString("borderMaterial") != null) { + this.borderMaterial = Material.getMaterial(rs.getString("borderMaterial").split(":")[0]); + this.borderData = rs.getString("borderMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("borderMaterial").split(":")[1]); + } this.plotSize = PlotSize.valueOf(rs.getString("plotSize")); this.length = rs.getInt("length"); this.width = rs.getInt("width"); this.height = rs.getInt("height"); ArrayList location = new ArrayList<>(Arrays.asList(rs.getString("createdLocation").subSequence(0, rs.getString("createdLocation").length() - 1).toString().split(";"))); - this.createdLocation = rs.getString("createdLocation").isEmpty() ? null : new Location(Bukkit.getWorld(location.get(0)), Double.parseDouble(location.get(1)), Double.parseDouble(location.get(2)), Double.parseDouble(location.get(3)), Float.parseFloat(location.get(4)), Float.parseFloat(location.get(5))); + Location createLocation = new Location(Bukkit.getWorld(location.get(0)), Double.parseDouble(location.get(1)), Double.parseDouble(location.get(2)), Double.parseDouble(location.get(3)), Float.parseFloat(location.get(4)), Float.parseFloat(location.get(5))); + this.createdLocation = rs.getString("createdLocation").isEmpty() ? null : createLocation; this.createdDirection = Direction.byYaw(createdLocation.getYaw()); this.selectedGameMode = GameMode.CREATIVE; + this.createdWorld = location.get(0); + if (floorMaterial == null) { + floorMaterial = plotSize.getFloorMaterial(); + floorData = plotSize.getFloorData(); + } + if (borderMaterial == null) { + borderMaterial = plotSize.getBorderMaterial(); + borderData = plotSize.getBorderData(); + } initializeCorners(); } catch (SQLException e) { e.printStackTrace(); } } + public int getXMin() { + return Math.min(this.getBorderBottomLeftCorner().getBlockX(), this.borderTopRightCorner.getBlockX()); + } + + public int getXMax() { + return Math.max(this.getBorderBottomLeftCorner().getBlockX(), this.borderTopRightCorner.getBlockX()); + } + + public int getZMin() { + return Math.min(this.getBorderBottomLeftCorner().getBlockZ(), this.borderTopRightCorner.getBlockZ()); + } + + public int getZMax() { + return Math.max(this.getBorderBottomLeftCorner().getBlockZ(), this.borderTopRightCorner.getBlockZ()); + } + public int getID() { return ID; } @@ -122,6 +163,7 @@ public UUID getOwnedBy() { public void setOwnedBy(UUID ownedBy) { this.ownedBy = ownedBy; + updateMarker(); } public String getAssignedBy() { @@ -138,6 +180,7 @@ public LocalDateTime getOwnedUntilDate() { public void setOwnedUntilDate(LocalDateTime ownedUntilDate) { this.ownedUntilDate = ownedUntilDate; + updateMarker(); } public PlotSize getPlotSize() { @@ -176,15 +219,25 @@ public Material getFloorMaterial() { return floorMaterial; } - public void setFloorMaterial(Material floorMaterial, byte data) { + public void setFloor(Material floorMaterial, byte data) { this.floorMaterial = floorMaterial; this.floorData = data; + initializeFloor(); } public Location getCreatedLocation() { return createdLocation; } + public void setBorderMaterial(Material borderMaterial, byte data) { + this.borderMaterial = borderMaterial; + this.borderData = data; + } + + public Material getBorderMaterial() { + return borderMaterial; + } + public void setCreatedLocation(Location createdLocation) { this.createdLocation = createdLocation; } @@ -233,11 +286,19 @@ public GameMode getSelectedGameMode() { return selectedGameMode; } + public String getCreatedWorld() { + return createdWorld; + } + + public OfflinePlayer getPlotOwner() { + return ownedBy == null ? null : Bukkit.getOfflinePlayer(ownedBy); + } + public void setSelectedGameMode(GameMode selectedGameMode) { this.selectedGameMode = selectedGameMode; } - public void initializeFloor() { + private void initializeFloor() { Location location = createdLocation; Direction direction = Direction.byYaw(location.getYaw()); switch(direction) { @@ -380,12 +441,12 @@ public void initializeCorners() { } public void initialize() { - //System.out.println( - prepareBlocks(createdLocation); - //+ " blocks"); + prepareBlocks(createdLocation); } public void setBorder(Material material, byte data) { + borderMaterial = material; + borderData = data; Location location = this.getCreatedLocation(); Direction direction = Direction.byYaw(location.getYaw()); switch(direction) { @@ -498,23 +559,21 @@ public void setBorder(Material material, byte data) { } } - public List prepareBlocks(Location location) { - List blocks = new ArrayList<>(); + public void prepareBlocks(Location location) { Direction direction = Direction.byYaw(location.getYaw()); Location location1; Location location2; - long time = System.currentTimeMillis(); - long time2; - switch(direction) { + switch (direction) { case SOUTH: { location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); location2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); - SchematicUtil schematicUtil = new SchematicUtil(VirtualRealty.getInstance()); - schematicUtil.save(ID, schematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - time2 = System.currentTimeMillis(); - // SchematicUtil.saveSchematic(ID, location1, location2); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); for (int x = location.getBlockX() - width + 1; x < location.getBlockX() + 1; x++) { for (int z = location.getBlockZ(); z < location.getBlockZ() + length; z++) { + for (int y = location.getBlockY() + height; y > location.getBlockY() - 1; y--) { + Block airBlock = location.getWorld().getBlockAt(x, y, z); + airBlock.setType(Material.AIR); + } Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); floorBlock.setType(floorMaterial); if (VirtualRealty.isLegacy) { @@ -526,14 +585,6 @@ public List prepareBlocks(Location location) { e.printStackTrace(); } } - for (int y = location.getBlockY(); y < location.getBlockY() + height; y++) { - Block block = location.getWorld().getBlockAt(x, y, z); - Block airBlock = location.getWorld().getBlockAt(x, y + 1, z); - if (airBlock == null || airBlock != null) { - airBlock.setType(Material.AIR); - } - blocks.add(block); - } } } int maxX = location.getBlockX() + 1 + 1; @@ -564,12 +615,13 @@ public List prepareBlocks(Location location) { case WEST: { location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); location2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); - SchematicUtil schematicUtil = new SchematicUtil(VirtualRealty.getInstance()); - schematicUtil.save(ID, schematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - time2 = System.currentTimeMillis(); - //SchematicUtil.saveSchematic(ID, location1, location2); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); for (int x = location.getBlockX() - length + 1; x < location.getBlockX() + 1; x++) { for (int z = location.getBlockZ() - width + 1; z < location.getBlockZ() + 1; z++) { + for (int y = location.getBlockY() + height; y > location.getBlockY() - 1; y--) { + Block airBlock = location.getWorld().getBlockAt(x, y, z); + airBlock.setType(Material.AIR); + } Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); floorBlock.setType(floorMaterial); if (VirtualRealty.isLegacy) { @@ -581,16 +633,6 @@ public List prepareBlocks(Location location) { e.printStackTrace(); } } - for (int y = location.getBlockY(); y < location.getBlockY() + height; y++) { - Block block = location.getWorld().getBlockAt(x, y, z); - Block airBlock = location. - getWorld(). - getBlockAt(x, y + 1, z); - if (airBlock == null || airBlock != null) { - airBlock.setType(Material.AIR); - } - blocks.add(block); - } } } int maxX = location.getBlockX() + 1 + 1; @@ -621,12 +663,13 @@ public List prepareBlocks(Location location) { case NORTH: { location1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); location2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); - SchematicUtil schematicUtil = new SchematicUtil(VirtualRealty.getInstance()); - schematicUtil.save(ID, schematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - time2 = System.currentTimeMillis(); - //SchematicUtil.saveSchematic(ID, location1, location2); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); for (int x = location.getBlockX(); x < location.getBlockX() + width; x++) { for (int z = location.getBlockZ() - length + 1; z < location.getBlockZ() + 1; z++) { + for (int y = location.getBlockY() + height; y > location.getBlockY() - 1; y--) { + Block airBlock = location.getWorld().getBlockAt(x, y, z); + airBlock.setType(Material.AIR); + } Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); floorBlock.setType(floorMaterial); if (VirtualRealty.isLegacy) { @@ -638,14 +681,6 @@ public List prepareBlocks(Location location) { e.printStackTrace(); } } - for (int y = location.getBlockY(); y < location.getBlockY() + height; y++) { - Block block = location.getWorld().getBlockAt(x, y, z); - Block airBlock = location.getWorld().getBlockAt(x, y + 1, z); - if (airBlock == null || airBlock != null) { - airBlock.setType(Material.AIR); - } - blocks.add(block); - } } } int maxX = location.getBlockX() + width + 1; @@ -676,12 +711,13 @@ public List prepareBlocks(Location location) { case EAST: { location1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); location2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); - SchematicUtil schematicUtil = new SchematicUtil(VirtualRealty.getInstance()); - schematicUtil.save(ID, schematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - time2 = System.currentTimeMillis(); - //SchematicUtil.saveSchematic(ID, location1, location2); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); for (int x = location.getBlockX(); x < location.getBlockX() + length; x++) { for (int z = location.getBlockZ(); z < location.getBlockZ() + width; z++) { + for (int y = location.getBlockY() + height; y > location.getBlockY() - 1; y--) { + Block airBlock = location.getWorld().getBlockAt(x, y, z); + airBlock.setType(Material.AIR); + } Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); floorBlock.setType(floorMaterial); if (VirtualRealty.isLegacy) { @@ -693,14 +729,6 @@ public List prepareBlocks(Location location) { e.printStackTrace(); } } - for (int y = location.getBlockY(); y < location.getBlockY() + height; y++) { - Block block = location.getWorld().getBlockAt(x, y, z); - Block airBlock = location.getWorld().getBlockAt(x, y + 1, z); - if (airBlock == null || airBlock != null) { - airBlock.setType(Material.AIR); - } - blocks.add(block); - } } } int maxX = location.getBlockX() + length + 1; @@ -731,42 +759,28 @@ public List prepareBlocks(Location location) { default: throw new IllegalStateException("Unexpected value: " + direction); } - //System.out.println(time2 - time + " ms (saved)"); - return blocks; } public void unloadPlot() { switch (createdDirection) { case SOUTH: { -// SchematicUtil3.loadSchematic(ID, createdLocation.getWorld(), -// createdLocation.getBlockX() - width, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1); - SchematicUtil schematicUtil = new SchematicUtil(VirtualRealty.getInstance()); - schematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - width, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - width, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); break; } case WEST: { -// SchematicUtil3.loadSchematic(ID, createdLocation.getWorld(), -// createdLocation.getBlockX() - length, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - width); - SchematicUtil schematicUtil = new SchematicUtil(VirtualRealty.getInstance()); - schematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - length, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - width)); + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - length, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - width)); break; } case NORTH: { -// SchematicUtil3.loadSchematic(ID, createdLocation.getWorld(), -// createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - length); - SchematicUtil schematicUtil = new SchematicUtil(VirtualRealty.getInstance()); - schematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - length)); + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - length)); break; } case EAST: { -// SchematicUtil3.loadSchematic(ID, createdLocation.getWorld(), -// createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1); - SchematicUtil schematicUtil = new SchematicUtil(VirtualRealty.getInstance()); - schematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); break; } } @@ -782,10 +796,10 @@ public void insert() { builder.append(this.createdLocation.getPitch() + ";"); try { SQL.getStatement().execute("INSERT INTO `vr_plots` (`ID`, `ownedBy`, `assignedBy`, `ownedUntilDate`," + - " `floorMaterial`, `plotSize`, `length`, `width`, `height`, `createdLocation`) " + + " `floorMaterial`, `borderMaterial`, `plotSize`, `length`, `width`, `height`, `createdLocation`) " + "VALUES ('" + this.ID + "', '" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "', '" + this.assignedBy + "', " + - "'" + Timestamp.valueOf(this.ownedUntilDate) + "', '" + this.floorMaterial + ":" + this.floorData + "'," + - " '" + this.plotSize + "', '" + this.length + "', '" + this.width + "', '" + this.height + "', '" + builder.toString() + "')"); + "'" + Timestamp.valueOf(this.ownedUntilDate) + "', '" + this.floorMaterial + ":" + this.floorData + "', '" + this.borderMaterial + ":" + this.borderData + "'," + + " '" + this.plotSize + "', '" + this.length + "', '" + this.width + "', '" + this.height + "', '" + builder + "')"); } catch (SQLException e) { e.printStackTrace(); } @@ -794,7 +808,7 @@ public void insert() { public void update() { try { SQL.getStatement().execute("UPDATE `vr_plots` SET `ownedBy`='" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "', `assignedBy`='" + this.assignedBy + "'," + - " `ownedUntilDate`='" + Timestamp.valueOf(this.ownedUntilDate) + "', `floorMaterial`='" + this.floorMaterial + ":" + this.floorData + "'," + + " `ownedUntilDate`='" + Timestamp.valueOf(this.ownedUntilDate) + "', `floorMaterial`='" + this.floorMaterial + ":" + this.floorData + "', `borderMaterial`='" + this.borderMaterial + ":" + this.borderData + "'," + " `plotSize`='" + this.plotSize + "', `length`='" + this.length + "', `width`='" + this.width + "', `height`='" + this.height + "'" + " WHERE `ID`='" + this.ID + "'"); } catch (SQLException e) { @@ -804,14 +818,16 @@ public void update() { public void remove() { this.unloadPlot(); + PlotManager.removeDynMapMarker(this); try { SQL.getStatement().execute("DELETE FROM `vr_plots` WHERE `ID` = '" + ID + "';"); } catch (SQLException e) { e.printStackTrace(); } int id = ID; - File file = new File(VirtualRealty.plotsSchemaFolder, "plot" + id + ".schem"); - file.delete(); + File file = new File(VirtualRealty.plotsSchemaFolder, "plot" + id + ".region"); + if (file.exists()) + FileUtils.deleteQuietly(file); PlotManager.plots.remove(this); } @@ -822,4 +838,9 @@ public Direction getCreatedDirection() { public void setCreatedDirection(Direction createdDirection) { this.createdDirection = createdDirection; } + + public void updateMarker() { + PlotManager.resetPlotMarker(this); + } + } \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/sql/SQL.java b/src/main/java/me/plytki/virtualrealty/sql/SQL.java index c0dab7b..42411be 100644 --- a/src/main/java/me/plytki/virtualrealty/sql/SQL.java +++ b/src/main/java/me/plytki/virtualrealty/sql/SQL.java @@ -46,11 +46,15 @@ public static void createStatement() { public static void closeConnection() { try { - if (VirtualRealty.getPluginConfiguration().dataModel.equals(PluginConfiguration.DataModel.H2)) { - statement.execute("SHUTDOWN"); + if (statement != null) { + if (VirtualRealty.getPluginConfiguration().dataModel.equals(PluginConfiguration.DataModel.H2)) { + statement.execute("SHUTDOWN"); + } + statement.close(); } - statement.close(); - connection.close(); + if (connection != null) + connection.close(); + VirtualRealty.debug("Database connection closed"); } catch (SQLException ex) { ex.printStackTrace(); } @@ -58,13 +62,21 @@ public static void closeConnection() { public static void createTables() { try { - SQL.getStatement().execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, PRIMARY KEY(`ID`))"); - } - catch (SQLException ex) { + SQL.getStatement().execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, PRIMARY KEY(`ID`))"); + updateTables(); + } catch (SQLException ex) { ex.printStackTrace(); } } + private static void updateTables() { + try { + SQL.getStatement().execute("ALTER TABLE `vr_plots` ADD `borderMaterial` VARCHAR(32) AFTER `floorMaterial`;"); + } catch (SQLException e) { + //e.printStackTrace(); + } + } + public static Statement getStatement() { try { if (System.currentTimeMillis() - lastQuery > MYSQL_TIMEOUT_MS) { diff --git a/src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java b/src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java index bb51a6b..4e521fb 100644 --- a/src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java +++ b/src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java @@ -3,74 +3,77 @@ import me.plytki.virtualrealty.VirtualRealty; import me.plytki.virtualrealty.managers.PlotManager; import me.plytki.virtualrealty.objects.Plot; +import me.plytki.virtualrealty.utils.data.Data; import me.plytki.virtualrealty.utils.multiversion.VMaterial; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; +import org.bukkit.block.BlockState; import org.bukkit.block.data.BlockData; -import org.bukkit.plugin.Plugin; import java.io.*; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; import java.util.*; +import java.util.zip.Deflater; +import java.util.zip.DeflaterOutputStream; +import java.util.zip.InflaterInputStream; public class SchematicUtil { - - Plugin plugin; - - public SchematicUtil(Plugin plugin) { - this.plugin = plugin; - } - public static List getStructure(Block block, Block block2) { - int minX = (block.getX() < block2.getX()) ? block.getX() : block2.getX(); - int minZ = (block.getZ() < block2.getZ()) ? block.getZ() : block2.getZ(); - int minY = (block.getY() < block2.getY()) ? block.getY() : block2.getY(); - int maxX = (block.getX() > block2.getX()) ? block.getX() : block2.getX(); - int maxZ = (block.getZ() > block2.getZ()) ? block.getZ() : block2.getZ(); - int maxY = (block.getY() > block2.getY()) ? block.getY() : block2.getY(); + public static String[] getStructure(Block block, Block block2) { + long time = System.currentTimeMillis(); + int minX = Math.min(block.getX(), block2.getX()); + int minZ = Math.min(block.getZ(), block2.getZ()); + int minY = Math.min(block.getY(), block2.getY()); + int maxX = Math.max(block.getX(), block2.getX()); + int maxZ = Math.max(block.getZ(), block2.getZ()); + int maxY = Math.max(block.getY(), block2.getY()); List blocks = new ArrayList<>(); for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { for (int z = minZ; z <= maxZ; ++z) { Block b = block.getWorld().getBlockAt(x, y, z); - if (b.getType() != Material.AIR) + if (b.getType() != Material.AIR) { if (VirtualRealty.isLegacy) { blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getType().getId() + ";" + b.getData()); } else { blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getBlockData().getAsString().substring(10)); } + } } } } - return blocks; + VirtualRealty.debug("Getted and serialized blocks in: " + (System.currentTimeMillis() - time) + " ms"); + return blocks.toArray(new String[0]); } - public void paste(int plotID, Location l) { - List blocks = this.load(plotID); + public static void paste(int plotID, Location l) { + long time = System.currentTimeMillis(); + String[] blocks = load(plotID); + if (blocks == null) return; Plot plot = PlotManager.getPlot(plotID); Location location = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderBottomLeftCorner().getBlockX(), plot.getBorderBottomLeftCorner().getBlockY(), plot.getBorderBottomLeftCorner().getBlockZ()); Location location2 = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderTopRightCorner().getBlockX(), plot.getBorderTopRightCorner().getBlockY(), plot.getBorderTopRightCorner().getBlockZ()); - Block block = location.getBlock(); - Block block2 = location2.getBlock(); - int minX = (block.getX() < block2.getX()) ? block.getX() : block2.getX(); - int minZ = (block.getZ() < block2.getZ()) ? block.getZ() : block2.getZ(); - int minY = (block.getY() < block2.getY()) ? block.getY() : block2.getY(); - int maxX = (block.getX() > block2.getX()) ? block.getX() : block2.getX(); - int maxZ = (block.getZ() > block2.getZ()) ? block.getZ() : block2.getZ(); - int maxY = (block.getY() > block2.getY()) ? block.getY() : block2.getY(); + Block pos1Block = location.getBlock(); + Block pos2Block = location2.getBlock(); + int minX = Math.min(pos1Block.getX(), pos2Block.getX()); + int minZ = Math.min(pos1Block.getZ(), pos2Block.getZ()); + int minY = Math.min(pos1Block.getY(), pos2Block.getY()); + int maxX = Math.max(pos1Block.getX(), pos2Block.getX()); + int maxZ = Math.max(pos1Block.getZ(), pos2Block.getZ()); + int maxY = Math.max(pos1Block.getY(), pos2Block.getY()); for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { for (int z = minZ; z <= maxZ; ++z) { - Block b = block.getWorld().getBlockAt(x, y, z); + Block b = location.getWorld().getBlockAt(x, y, z); b.setType(Material.AIR); } } } - for (String block1 : blocks) { - String[] cords = block1.split(";"); + for (String block : blocks) { + String[] cords = block.split(";"); int x = Integer.parseInt(cords[0]); int y = Integer.parseInt(cords[1]); int z = Integer.parseInt(cords[2]); @@ -94,56 +97,51 @@ public void paste(int plotID, Location l) { } b.getState().update(true); } + VirtualRealty.debug("Pasted in: " + (System.currentTimeMillis() - time) + " ms"); } - public void save(int plotID, List b) { - ObjectOutputStream oos = null; - FileOutputStream fout = null; - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".schem"); - try { - f.createNewFile(); - } - catch (IOException e1) { - e1.printStackTrace(); + public static void save(int plotID, String[] blocks) { + long time = System.currentTimeMillis(); + File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); + + StringBuilder stringBuilder = new StringBuilder(); + for (String s : blocks) { + stringBuilder.append(s).append("|"); } + String plotString = stringBuilder.toString(); try { - fout = new FileOutputStream(f); - oos = new ObjectOutputStream(fout); - oos.writeObject(b); - } - catch (Exception e2) { - e2.printStackTrace(); - if (oos != null) { - try { - oos.close(); - } - catch (IOException e3) { - e3.printStackTrace(); - } - } + new Data().compressData(plotString.substring(0, plotString.length() - 1).getBytes(StandardCharsets.UTF_8), f); + } catch (IOException e) { + e.printStackTrace(); } - finally { - if (oos != null) { - try { - oos.close(); - } - catch (IOException e4) { - e4.printStackTrace(); - } + VirtualRealty.debug("Saved in: " + (System.currentTimeMillis() - time) + " ms"); + } + + public static String[] load(int plotID) { + long time = System.currentTimeMillis(); + File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); + if (f.exists()) { + String loaded = null; + try { + loaded = new String(new Data().decompressData(f)); + } catch (IOException e) { + e.printStackTrace(); } + VirtualRealty.debug("Loaded in: " + (System.currentTimeMillis() - time) + " ms"); + return loaded.split("\\|"); } + return null; } - public List load(int plotID) { + public static List oldLoad(int plotID) { File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".schem"); - List loaded = new ArrayList(); + List loaded = new ArrayList<>(); try { FileInputStream streamIn = new FileInputStream(f); ObjectInputStream objectinputstream = new ObjectInputStream(streamIn); loaded = (List)objectinputstream.readObject(); objectinputstream.close(); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } return loaded; diff --git a/src/main/java/me/plytki/virtualrealty/utils/data/Data.java b/src/main/java/me/plytki/virtualrealty/utils/data/Data.java new file mode 100644 index 0000000..0ff5e38 --- /dev/null +++ b/src/main/java/me/plytki/virtualrealty/utils/data/Data.java @@ -0,0 +1,31 @@ +package me.plytki.virtualrealty.utils.data; + +import java.io.*; +import java.util.zip.*; + +public class Data { + + public void compressData(byte[] data, File file) throws IOException { + try (OutputStream outputStream = new FileOutputStream(file)) { + Deflater d = new Deflater(); + DeflaterOutputStream dout = new DeflaterOutputStream(outputStream, d); + dout.write(data); + dout.close(); + } + } + + public byte[] decompressData(File file) throws IOException { + try (InputStream inputStream = new FileInputStream(file)) { + InflaterInputStream newInput = new InflaterInputStream(inputStream); + ByteArrayOutputStream bout = new ByteArrayOutputStream(512); + int b; + while ((b = newInput.read()) != -1) { + bout.write(b); + } + newInput.close(); + bout.close(); + return bout.toByteArray(); + } + } + +} diff --git a/src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java b/src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java index c8ecdc2..c3c88bb 100644 --- a/src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java +++ b/src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java @@ -3,6 +3,7 @@ import me.plytki.virtualrealty.VirtualRealty; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.lang.reflect.InvocationTargetException; @@ -10,34 +11,32 @@ public class Chat { - private BaseComponent text; + private final BaseComponent text; public Chat(BaseComponent text) { this.text = text; } - public Chat(BaseComponent... text) { - this.text = new TextComponent(); - for (BaseComponent baseComponent : text) { - this.text.addExtra(baseComponent); - } - } - public Chat(String text) { this.text = new TextComponent(text); } - public void sendTo(Player player) { - if (VirtualRealty.isLegacy) { - try { - Method m = Player.class.getDeclaredMethod("sendMessage", BaseComponent.class); - m.setAccessible(true); - m.invoke(player, text); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); + public void sendTo(CommandSender sender) { + if (sender instanceof Player) { + Player player = (Player) sender; + if (VirtualRealty.isLegacy) { + try { + Method m = Player.class.getDeclaredMethod("sendMessage", BaseComponent.class); + m.setAccessible(true); + m.invoke(player, text); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } else { + player.spigot().sendMessage(text); } } else { - player.spigot().sendMessage(text); + sender.sendMessage(text.toLegacyText()); } } diff --git a/src/main/resources/ploticon.png b/src/main/resources/ploticon.png new file mode 100644 index 0000000..cabbecc Binary files /dev/null and b/src/main/resources/ploticon.png differ diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 58286cd..6cdb9b0 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -5,6 +5,7 @@ prefix: Virtual Realty authors: [ plytki ] api-version: 1.13 description: Virtual Realty Plugin +softdepend: [dynmap] commands: virtualrealty: aliases: [vrplot, virtualr]