diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md deleted file mode 100644 index 9e26f91a6..000000000 --- a/.github/CONTRIBUTING.md +++ /dev/null @@ -1,2 +0,0 @@ -### Bugs -Please provide a `/plot debugpaste` if you are reporting a bug. diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 91ba21cb9..8192d7fa6 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -3,15 +3,13 @@ __*NOTICE: Bukkit/Spigot versions 1.7.10 to 1.12.2 are considered legacy and wil -**[REQUIRED] PlotSquared Version Number:** +**Debug paste link:** + **[REQUIRED] Spigot/Paper Version Number:** **[REQUIRED] Minecraft Version Number:** -**Links to worlds.yml file and settings.yml file:** - - **[REQUIRED] Description of the problem:** **Any relevant console output or screenshots:** diff --git a/.github/ISSUE_TEMPLATE/bug-issue-report-for-plotsquared.md b/.github/ISSUE_TEMPLATE/bug-issue-report-for-plotsquared.md new file mode 100644 index 000000000..12b98374a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-issue-report-for-plotsquared.md @@ -0,0 +1,98 @@ +--- +name: Bug/Issue report for PlotSquared +about: Bug / Issue report about this plugin +title: '' +labels: "[?] Testing Required" +assignees: '' + +--- + + + + + + + +# Bug Report Template: + +## Required Information section: +> ALL FIELDS IN THIS SECTION ARE REQUIRED, and must contain appropriate information +### Server config info (/plot debugpaste / file paste links): + + + + +### Server type: +**Select one** + +- [] Spigot / Paper *(CraftBukkit should not be used, re-test with Spigot first!)* +- [] Sponge *- NOTE: NOT ACTIVELY MAINTAINED* +- [] NukkitX *- NOTE: NOT ACTIVELY MAINTAINED* + +### Minecraft Version: +**Select one** + +- [] Minecraft 1.15 +- [] Minecraft 1.14.4 +- [] Minecraft 1.13.2 +- [] Minecraft Java Edition *other versions, please specify*: +- [] Minecraft Bedrock Edition *specify version*: + +### Server build info: + +``` +Paste the output here, between the tick marks, replacing this text +``` + +### WorldEdit/FAWE versions: + +- [] FAWE *version*: +- [] WorldEdit *version*: + +### Description of the problem: + + + +### How to replicate: + + +## Additional Information: +> The information here is optional for you to provide, however it may help us to more readily diagnose any compatibility and bug issues. + +### Other plugins being used on the server: + + +### Relevant console output, log lines, and/or screenshots: + + +### Additional relevant comments/remarks: + + +# AFFIRMATION OF COMPLETION: + +- [] I included all information required in the sections above +- [] I made sure there are no duplicates of this report [(Use Search)](https://github.com/IntellectualSites/PlotSquared/issues?utf8=%E2%9C%93&q=is%3Aissue) +- [] I made sure I am using an up-to-date version of PlotSquared +- [] I made sure the bug/error is not caused by any other plugin +- [x] I didn't read but checked everything above. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..83661f8c6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: PlotSquared Suggestions + url: https://github.com/IntellectualSites/PlotSquaredSuggestions + about: If you want to submit feature or suggestion ideas, do that here \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..1ccb63862 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,17 @@ +## Overview + + +**Fixes #{issue number}** + +## Description + +## Checklist + +- [] I included all information required in the sections above +- [] I tested my changes and approved their functionality +- [] I ensured my changes do not break other parts of the code +- [] I read and followed the [contribution guidelines](https://github.com/IntellectualSites/PlotSquared/blob/breaking/CONTRIBUTING.md) \ No newline at end of file diff --git a/.github/auto-comment.yml b/.github/auto-comment.yml index f7584d42e..38721ffb9 100644 --- a/.github/auto-comment.yml +++ b/.github/auto-comment.yml @@ -6,10 +6,3 @@ issueOpened: > Failure to do so will prevent us from resolving the issue in a timely manner. Please note that suggestions are now to be submitted to https://git.io/fN5B4 rather than this issue tracker! - -pullRequestOpened: > - Thank your for raising your pull request. - - Please make sure you have followed our contributing guidelines and to take an extra look at the code to make sure that it is functional! - - We will review it as soon as possible! diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml new file mode 100644 index 000000000..22c3d6c65 --- /dev/null +++ b/.github/workflows/gradle.yml @@ -0,0 +1,24 @@ +name: Java CI + +on: + push: + branches: + - breaking + - master + pull_request: + branches: + - breaking + - master + +jobs: + test: + runs-on: ubuntu-18.04 + + steps: + - uses: actions/checkout@v1 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Test with Gradle + run: ./gradlew clean build diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index 2a6b17d65..ba6fa5c55 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -1,22 +1,31 @@ +plugins { + id "com.github.johnrengelman.shadow" +} repositories { - maven { url "https://hub.spigotmc.org/nexus/content/repositories/snapshots/" } - maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } - maven { url "http://nexus.hc.to/content/repositories/pub_releases" } - maven { url "https://repo.codemc.org/repository/maven-public" } - maven { url 'http://repo.onarandombox.com/content/groups/public'} - maven { url 'https://papermc.io/repo/repository/maven-public/' } + maven { url = "https://hub.spigotmc.org/nexus/content/repositories/snapshots/" } + maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" } + maven { url = "http://nexus.hc.to/content/repositories/pub_releases" } + maven { url = "https://repo.codemc.org/repository/maven-public" } + maven { + name = "papermc" + url = "https://papermc.io/repo/repository/maven-public/" + } mavenLocal() } + dependencies { - implementation project(':Core') - compile project(':Core') - compile 'com.destroystokyo.paper:paper-api:1.14-R0.1-SNAPSHOT' - implementation 'com.onarandombox.multiversecore:Multiverse-Core:3.0.0-SNAPSHOT' - implementation 'org.spigotmc:spigot-api:1.14-R0.1-SNAPSHOT' - compile(group: 'com.sk89q.worldedit', name: 'worldedit-bukkit', version: '7.0.0-SNAPSHOT') + implementation(project(":Core")) + compile(project(":Core")) + compile("com.destroystokyo.paper:paper-api:1.14.4-R0.1-SNAPSHOT") + //implementation 'com.onarandombox.multiversecore:Multiverse-Core:3.0.0-SNAPSHOT' + implementation("org.spigotmc:spigot-api:1.15.1-R0.1-SNAPSHOT") + compile(group: "com.sk89q.worldedit", name: "worldedit-bukkit", version: "7.0.1") + compile("io.papermc:paperlib:1.0.2") + compile(group: "com.squareup.retrofit2", name: "retrofit", version: "2.4.0") + implementation("net.kyori:text-adapter-bukkit:3.0.3") compile("net.milkbowl.vault:VaultAPI:1.7") { - exclude module: 'bukkit' + exclude(module: "bukkit") } } @@ -24,29 +33,65 @@ sourceCompatibility = 1.8 targetCompatibility = 1.8 processResources { - from('src/main/resources') { - include 'plugin.yml' + from("src/main/resources") { + include("plugin.yml") expand( name: project.parent.name, version: project.parent.version ) } } -// We only want the shadow jar produced -jar.enabled = false + +//noinspection GroovyAssignabilityCheck +jar.archiveFileName = "PlotSquared-BukkitAPI-${project.parent.version}.jar" +jar.destinationDirectory = file("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-BukkitAPI/" + project.parent.version) +task createPom { + doLast { + pom { + project { + groupId = "com.github.intellectualsites.plotsquared" + artifactId = "PlotSquared-BukkitAPI" + version = project.parent.version + } + }.writeTo("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-BukkitAPI/${project.parent.version}/PlotSquared-BukkitAPI-${project.parent.version}.pom") + pom { + project { + groupId = "com.github.intellectualsites.plotsquared" + artifactId = "PlotSquared-BukkitAPI" + version = "latest" + } + }.writeTo("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-BukkitAPI/latest/PlotSquared-BukkitAPI-latest.pom") + } +} + +task copyFiles { + doLast { + copy { + from("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-BukkitAPI/${project.parent.version}/") + into("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-BukkitAPI/latest/") + include("PlotSquared-BukkitAPI*.jar") + rename("PlotSquared-BukkitAPI-${project.parent.version}.jar", "PlotSquared-BukkitAPI-latest.jar") + } + } +} + shadowJar { dependencies { - include(dependency(':Core')) + include(dependency(":Core")) // update notification stuff - include(dependency('com.github.Sauilitired:Jenkins4J:2.0-SNAPSHOT')) - include(dependency('com.squareup.retrofit2:retrofit:2.4.0')) - include(dependency('com.squareup.okhttp3:okhttp:3.14.0')) - include(dependency('com.squareup.okio:okio:2.2.2')) - include(dependency('org.jetbrains.kotlin:kotlin-stdlib:1.3.30')) + include(dependency("com.github.Sauilitired:Jenkins4J:2.0-SNAPSHOT")) + include(dependency("com.squareup.retrofit2:retrofit:2.4.0")) + include(dependency("com.squareup.okhttp3:okhttp:4.2.2")) + include(dependency("com.squareup.okio:okio:2.4.1")) + include(dependency("org.jetbrains.kotlin:kotlin-stdlib:1.3.61")) + include(dependency("io.papermc:paperlib:1.0.2")) + include(dependency("net.kyori:text-adapter-bukkit:3.0.3")) } - archiveName = "${parent.name}-${project.name}-${parent.version}.jar" - destinationDir = file '../target' + relocate('net.kyori.text', 'com.github.intellectualsites.plotsquared.formatting.text') + relocate("io.papermc.lib", "com.github.intellectualsites.plotsquared.bukkit.paperlib") + archiveFileName = "${parent.name}-${project.name}-${parent.version}.jar" + destinationDirectory = file "../target" } shadowJar.doLast { @@ -55,3 +100,5 @@ shadowJar.doLast { } build.dependsOn(shadowJar) +build.finalizedBy(copyFiles) +copyFiles.dependsOn(createPom) diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java index 94f6adcb7..4ac6a77f2 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java @@ -7,8 +7,19 @@ import com.github.intellectualsites.plotsquared.bukkit.listeners.PlayerEvents; import com.github.intellectualsites.plotsquared.bukkit.listeners.PlotPlusListener; import com.github.intellectualsites.plotsquared.bukkit.listeners.SingleWorldListener; import com.github.intellectualsites.plotsquared.bukkit.listeners.WorldEvents; -import com.github.intellectualsites.plotsquared.bukkit.titles.DefaultTitle; -import com.github.intellectualsites.plotsquared.bukkit.util.*; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitChatManager; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitChunkManager; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitCommand; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitEconHandler; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitEventUtil; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitHybridUtils; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitInventoryUtil; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitSchematicHandler; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitSetupUtils; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitTaskManager; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; +import com.github.intellectualsites.plotsquared.bukkit.util.Metrics; +import com.github.intellectualsites.plotsquared.bukkit.util.SetGenCB; import com.github.intellectualsites.plotsquared.bukkit.util.block.BukkitLocalQueue; import com.github.intellectualsites.plotsquared.bukkit.uuid.DefaultUUIDWrapper; import com.github.intellectualsites.plotsquared.bukkit.uuid.FileUUIDHandler; @@ -25,7 +36,6 @@ import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; import com.github.intellectualsites.plotsquared.plot.generator.HybridGen; import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; -import com.github.intellectualsites.plotsquared.plot.object.BlockRegistry; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; import com.github.intellectualsites.plotsquared.plot.object.PlotId; @@ -36,15 +46,37 @@ import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManag import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; import com.github.intellectualsites.plotsquared.plot.object.worlds.SingleWorldGenerator; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.ChatManager; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.ConsoleColors; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.InventoryUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandlerImplementation; +import com.github.intellectualsites.plotsquared.plot.util.UpdateUtility; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.github.intellectualsites.plotsquared.plot.util.block.QueueProvider; import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.WorldEditPlugin; -import com.sk89q.worldedit.extension.platform.Capability; +import com.sk89q.worldedit.extension.platform.Actor; +import io.papermc.lib.PaperLib; import lombok.Getter; import lombok.NonNull; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; +import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -54,16 +86,18 @@ import org.bukkit.generator.ChunkGenerator; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.io.File; import java.lang.reflect.Method; +import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.UUID; import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass; @@ -79,9 +113,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - private final LegacyMappings legacyMappings = new BukkitLegacyMappings(); - private final BlockRegistry blockRegistry = - new BukkitBlockRegistry(Material.values()); private int[] version; @Getter private String pluginName; @Getter private SingleWorldListener singleWorldListener; @@ -114,42 +145,10 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return Bukkit.getVersion(); } - private void init() { - try { - PluginManager manager = Bukkit.getPluginManager(); - System.out.println("[P2] Force loading WorldEdit"); - Plugin plugin = manager.getPlugin("WorldEdit"); - if (!manager.isPluginEnabled("WorldEdit")) { - manager.enablePlugin(WorldEditPlugin.getPlugin(WorldEditPlugin.class)); - } - System.out.println("[P2] Testing platform capabilities"); - WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS); - } catch (final Throwable throwable) { - throw new IllegalStateException( - "Failed to force load WorldEdit. Road schematics will fail to generate", throwable); - } - } - @Override public void onEnable() { this.pluginName = getDescription().getName(); PlotPlayer.registerConverter(Player.class, BukkitUtil::getPlayer); - - if (Bukkit.getVersion().contains("git-Spigot")) { - // Uses System.out.println because the logger isn't initialized yet - System.out - .println("[P2] ========================== USE PAPER =========================="); - System.out.println("[P2] Paper offers a more complete API for us to work with"); - System.out.println("[P2] and we may come to rely on it in the future."); - System.out.println("[P2] It is also recommended out of a performance standpoint as"); - System.out - .println("[P2] it contains many improvements missing from Spigot and Bukkit."); - System.out.println("[P2] DOWNLOAD: https://papermc.io/downloads"); - System.out.println("[P2] GUIDE: https://www.spigotmc.org/threads/21726/"); - System.out.println("[P2] NOTE: This is only a recommendation"); - System.out.println("[P2] both Spigot and CraftBukkit are still supported."); - System.out - .println("[P2] ==============================================================="); - } + PaperLib.suggestPaper(this); new PlotSquared(this, "Bukkit"); @@ -158,6 +157,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain "You can't use this version of PlotSquared on a server less than Minecraft 1.13.2."); System.out .println("Please check the download page for the link to the legacy versions."); + System.out.println("The server will now be shutdown to prevent any corruption."); Bukkit.shutdown(); return; } @@ -165,13 +165,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain // Check for updates if (PlotSquared.get().getUpdateUtility() != null) { final UpdateUtility updateUtility = PlotSquared.get().getUpdateUtility(); - updateUtility - .checkForUpdate(this.getPluginVersionString(), ((updateDescription, throwable) -> { + updateUtility.checkForUpdate(PlotSquared.get().getVersion().versionString(), + ((updateDescription, throwable) -> { Bukkit.getScheduler().runTask(BukkitMain.this, () -> { getLogger().info("-------- PlotSquared Update Check --------"); if (throwable != null) { getLogger().severe(String - .format("Could not check for update. Reason: %s", + .format("Could not check for updates. Reason: %s", throwable.getMessage())); } else { if (updateDescription == null) { @@ -180,8 +180,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } else { getLogger() .info("There appears to be a PlotSquared update available!"); - getLogger().info(String.format("You are running version %s," - + " the newest available version is %s", + getLogger().info(String.format( + "You are running version %s, the newest available version is %s", getPluginVersionString(), updateDescription.getVersion())); getLogger().info( String.format("Update URL: %s", updateDescription.getUrl())); @@ -322,9 +322,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain @Override public void registerCommands() { final BukkitCommand bukkitCommand = new BukkitCommand(); final PluginCommand plotCommand = getCommand("plots"); - plotCommand.setExecutor(bukkitCommand); - plotCommand.setAliases(Arrays.asList("p", "ps", "plotme", "plot")); - plotCommand.setTabCompleter(bukkitCommand); + if (plotCommand != null) { + plotCommand.setExecutor(bukkitCommand); + plotCommand.setAliases(Arrays.asList("p", "ps", "plotme", "plot")); + plotCommand.setTabCompleter(bukkitCommand); + } } @Override public File getDirectory() { @@ -538,6 +540,14 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain case PUFFERFISH: case PHANTOM: case ILLUSIONER: + case CAT: + case PANDA: + case FOX: + case PILLAGER: + case TRADER_LLAMA: + case WANDERING_TRADER: + case RAVAGER: + //case BEE: default: { if (Settings.Enabled_Components.KILL_ROAD_MOBS) { Location location = entity.getLocation(); @@ -582,7 +592,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } @Override @Nullable - public final ChunkGenerator getDefaultWorldGenerator(final String worldName, final String id) { + public final ChunkGenerator getDefaultWorldGenerator(@NotNull final String worldName, + final String id) { final IndependentPlotGenerator result; if (id != null && id.equalsIgnoreCase("single")) { result = new SingleWorldGenerator(); @@ -630,14 +641,15 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } @Override public QueueProvider initBlockQueue() { - try { - new SendChunk(); - MainUtil.canSendChunk = true; - } catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) { - PlotSquared.debug( - SendChunk.class + " does not support " + StringMan.getString(getServerVersion())); - MainUtil.canSendChunk = false; - } + //TODO Figure out why this code is still here yet isn't being called anywhere. + // try { + // new SendChunk(); + // MainUtil.canSendChunk = true; + // } catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) { + // PlotSquared.debug( + // SendChunk.class + " does not support " + StringMan.getString(getServerVersion())); + // MainUtil.canSendChunk = false; + // } return QueueProvider.of(BukkitLocalQueue.class, BukkitLocalQueue.class); } @@ -699,7 +711,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain getServer().getPluginManager().registerEvents(new WorldEvents(), this); } - @Override public IndependentPlotGenerator getDefaultGenerator() { + @NotNull @Override public IndependentPlotGenerator getDefaultGenerator() { return new HybridGen(); } @@ -727,11 +739,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } if (Settings.UUID.OFFLINE) { - PlotSquared.log(Captions.PREFIX + " &6" + getPluginName() + PlotSquared.log(Captions.PREFIX + "&6" + getPluginName() + " is using Offline Mode UUIDs either because of user preference, or because you are using an old version of " + "Bukkit"); } else { - PlotSquared.log(Captions.PREFIX + " &6" + getPluginName() + " is using online UUIDs"); + PlotSquared.log(Captions.PREFIX + "&6" + getPluginName() + " is using online UUIDs"); } if (Settings.UUID.USE_SQLUUIDHANDLER) { return new SQLUUIDHandler(wrapper); @@ -782,10 +794,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return new BukkitSchematicHandler(); } - @Override public AbstractTitle initTitleManager() { - return new DefaultTitle(); - } - @Override @Nullable public PlotPlayer wrapPlayer(final Object player) { if (player instanceof Player) { return BukkitUtil.getPlayer((Player) player); @@ -820,20 +828,18 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return new BukkitPlotGenerator(generator); } - @Override public List getPluginIds() { - final List names = new ArrayList<>(); + @Override public List, Boolean>> getPluginIds() { + List, Boolean>> names = new ArrayList<>(); for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - names.add(plugin.getName() + ';' + plugin.getDescription().getVersion() + ':' + plugin - .isEnabled()); + Map.Entry id = new AbstractMap.SimpleEntry<>(plugin.getName(), plugin.getDescription().getVersion()); + names.add(new AbstractMap.SimpleEntry<>(id, plugin.isEnabled())); } return names; } - @Override public BlockRegistry getBlockRegistry() { - return this.blockRegistry; - } - - @Override public LegacyMappings getLegacyMappings() { - return this.legacyMappings; + @Override public Actor getConsole() { + @NotNull ConsoleCommandSender console = Bukkit.getServer().getConsoleSender(); + WorldEditPlugin wePlugin = ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit")); + return wePlugin.wrapCommandSender(console); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java index 56635abb0..348f50f9a 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java @@ -19,8 +19,18 @@ import org.bukkit.inventory.ItemStack; import java.io.IOException; import java.io.StringWriter; -import java.lang.reflect.*; -import java.util.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.logging.Level; /** diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java index 43cf15e08..64bdda48d 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java @@ -123,8 +123,7 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa if (insertionData != null) { json.name("insertion").value(insertionData); } - if (translationReplacements.size() > 0 && text != null && TextualComponent - .isTranslatableText(text)) { + if (translationReplacements.size() > 0 && TextualComponent.isTranslatableText(text)) { json.name("with").beginArray(); for (JsonRepresentedObject obj : translationReplacements) { obj.writeJson(json); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java index a92515221..f3f004284 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java @@ -43,10 +43,6 @@ public final class Reflection { */ public synchronized static String getVersion() { if (_versionString == null) { - if (Bukkit.getServer() == null) { - // The server hasn't started, static initializer call? - return null; - } String name = Bukkit.getServer().getClass().getPackage().getName(); _versionString = name.substring(name.lastIndexOf('.') + 1) + "."; } @@ -180,15 +176,11 @@ public final class Reflection { * @return A method object with the specified name declared by the specified class. */ public synchronized static Method getMethod(Class clazz, String name, Class... args) { - if (!_loadedMethods.containsKey(clazz)) { - _loadedMethods.put(clazz, new HashMap<>()); - } + _loadedMethods.computeIfAbsent(clazz, k -> new HashMap<>()); Map>, Method>> loadedMethodNames = _loadedMethods.get(clazz); - if (!loadedMethodNames.containsKey(name)) { - loadedMethodNames.put(name, new HashMap<>()); - } + loadedMethodNames.computeIfAbsent(name, k -> new HashMap<>()); Map>, Method> loadedSignatures = loadedMethodNames.get(name); ArrayWrapper> wrappedArg = new ArrayWrapper<>(args); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java index fdee5edf6..49d399da1 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java @@ -16,7 +16,11 @@ import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.StringWrapper; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.google.common.collect.Sets; @@ -24,8 +28,12 @@ import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; import java.util.Map.Entry; +import java.util.UUID; @CommandDeclaration(command = "uuidconvert", permission = "plots.admin", description = "Debug UUID conversion", usage = "/plot uuidconvert ", @@ -63,7 +71,7 @@ import java.util.Map.Entry; if (args.length != 2 || !"-o".equals(args[1])) { MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, - "/plot uuidconvert " + args[0] + " - o"); + "/plot uuidconvert " + args[0] + " -o"); MainUtil.sendMessage(player, "&cBe aware of the following!"); MainUtil.sendMessage(player, "&8 - &cUse the database command or another method to backup your plots beforehand"); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java index 6d9805660..f2f9efe71 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java @@ -6,9 +6,6 @@ import org.bukkit.event.HandlerList; import java.util.UUID; -/** - * - */ public class PlayerPlotTrustedEvent extends PlotEvent { private static final HandlerList handlers = new HandlerList(); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotAutoMergeEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotAutoMergeEvent.java index 88c9773c9..059b296cf 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotAutoMergeEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotAutoMergeEvent.java @@ -7,8 +7,8 @@ import lombok.Setter; import org.bukkit.World; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; @@ -30,8 +30,8 @@ public final class PlotAutoMergeEvent extends PlotEvent implements Cancellable { * @param plot Plot that was merged * @param plots A list of plots involved in the event */ - public PlotAutoMergeEvent(@Nonnull final World world, @Nonnull final Plot plot, - @Nonnull final List plots) { + public PlotAutoMergeEvent(@NotNull final World world, @NotNull final Plot plot, + @NotNull final List plots) { super(plot); this.world = world; this.plots = plots; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotMergeEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotMergeEvent.java index 493145f2a..55488011e 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotMergeEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotMergeEvent.java @@ -6,8 +6,7 @@ import lombok.Setter; import org.bukkit.World; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; /** * Event called when several plots are merged @@ -29,8 +28,8 @@ public final class PlotMergeEvent extends PlotEvent implements Cancellable { * @param dir The direction of the merge * @param max Max merge size */ - public PlotMergeEvent(@Nonnull final World world, @Nonnull final Plot plot, - @Nonnull final int dir, @Nonnull final int max) { + public PlotMergeEvent(@NotNull final World world, @NotNull final Plot plot, + @NotNull final int dir, @NotNull final int max) { super(plot); this.world = world; this.dir = dir; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotUnlinkEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotUnlinkEvent.java index 675f10d8f..5db7d04d4 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotUnlinkEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotUnlinkEvent.java @@ -8,8 +8,8 @@ import org.bukkit.World; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; @@ -31,8 +31,8 @@ public final class PlotUnlinkEvent extends Event implements Cancellable { * @param world World in which the event occurred * @param plots Plots that are involved in the event */ - public PlotUnlinkEvent(@Nonnull final World world, @Nonnull final PlotArea area, - @Nonnull final List plots) { + public PlotUnlinkEvent(@NotNull final World world, @NotNull final PlotArea area, + @NotNull final List plots) { this.plots = plots; this.world = world; this.area = area; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java index 6942bf6ab..03b0c8123 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java @@ -4,6 +4,7 @@ import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.generator.BlockPopulator; +import org.jetbrains.annotations.NotNull; import java.util.Random; @@ -24,7 +25,8 @@ public class BukkitAugmentedGenerator extends BlockPopulator { return generator; } - @Override public void populate(World world, Random random, Chunk source) { + @Override + public void populate(@NotNull World world, @NotNull Random random, @NotNull Chunk source) { AugmentedUtils.generate(world.getName(), source.getX(), source.getZ(), null); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java index b6a246f0d..1536afa3d 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java @@ -5,13 +5,13 @@ import com.github.intellectualsites.plotsquared.bukkit.util.block.GenChunk; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; -import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; import com.github.intellectualsites.plotsquared.plot.object.worlds.SingleWorldGenerator; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; +import com.sk89q.worldedit.math.BlockVector2; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.BlockPopulator; @@ -41,7 +41,7 @@ public class BukkitPlotGenerator extends ChunkGenerator this.plotGenerator = generator; this.platformGenerator = this; this.populators = new ArrayList<>(); - this.populators.add(new PlotBlockPopulator(this.plotGenerator)); + this.populators.add(new BlockStatePopulator(this.plotGenerator)); this.full = true; MainUtil.initCache(); } @@ -73,7 +73,9 @@ public class BukkitPlotGenerator extends ChunkGenerator return this.platformGenerator; } - @Override @NotNull public List getDefaultPopulators(@NotNull World world) { + @Override + @NotNull + public List getDefaultPopulators(@NotNull World world) { try { if (!this.loaded) { String name = world.getName(); @@ -117,25 +119,26 @@ public class BukkitPlotGenerator extends ChunkGenerator return toAdd; } - @Override @NotNull + @Override + @NotNull public ChunkData generateChunkData(@NotNull World world, @NotNull Random random, int x, int z, @NotNull BiomeGrid biome) { GenChunk result = new GenChunk(); if (this.getPlotGenerator() instanceof SingleWorldGenerator) { - if (result.getCd() != null) { - for (int cx = 0; cx < 16; cx++) { - for (int cz = 0; cz < 16; cz++) { - biome.setBiome(cx, cz, Biome.PLAINS); + if (result.getChunkData() != null) { + for (int chunkX = 0; chunkX < 16; chunkX++) { + for (int chunkZ = 0; chunkZ < 16; chunkZ++) { + biome.setBiome(chunkX, chunkZ, Biome.PLAINS); } } - return result.getCd(); + return result.getChunkData(); } } // Set the chunk location result.setChunk(new ChunkWrapper(world.getName(), x, z)); // Set the result data - result.setCd(createChunkData(world)); + result.setChunkData(createChunkData(world)); result.biomeGrid = biome; result.result = null; @@ -145,16 +148,16 @@ public class BukkitPlotGenerator extends ChunkGenerator if (this.platformGenerator != this) { return this.platformGenerator.generateChunkData(world, random, x, z, biome); } else { - generate(new ChunkLoc(x, z), world, result); + generate(BlockVector2.at(x, z), world, result); } } catch (Throwable e) { e.printStackTrace(); } // Return the result data - return result.getCd(); + return result.getChunkData(); } - private void generate(ChunkLoc loc, World world, ScopedLocalBlockQueue result) { + private void generate(BlockVector2 loc, World world, ScopedLocalBlockQueue result) { // Load if improperly loaded if (!this.loaded) { String name = world.getName(); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/DelegatePlotGenerator.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/DelegatePlotGenerator.java index 820a9fa42..ed4df3714 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/DelegatePlotGenerator.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/DelegatePlotGenerator.java @@ -2,17 +2,20 @@ package com.github.intellectualsites.plotsquared.bukkit.generator; import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; +import com.sk89q.worldedit.bukkit.BukkitAdapter; import lombok.RequiredArgsConstructor; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Range; import java.util.Random; @@ -24,10 +27,6 @@ import java.util.Random; @Override public void initialize(PlotArea area) { } - @Override public PlotManager getNewPlotManager() { - return PlotSquared.get().IMP.getDefaultGenerator().getNewPlotManager(); - } - @Override public String getName() { return this.chunkGenerator.getClass().getName(); } @@ -36,52 +35,29 @@ import java.util.Random; return PlotSquared.get().IMP.getDefaultGenerator().getNewPlotArea(world, id, min, max); } - @Override public BlockBucket[][] generateBlockBucketChunk(PlotArea settings) { - BlockBucket[][] blockBuckets = new BlockBucket[16][]; - HybridPlotWorld hpw = (HybridPlotWorld) settings; - // Bedrock - if (hpw.PLOT_BEDROCK) { - for (short x = 0; x < 16; x++) { - for (short z = 0; z < 16; z++) { - blockBuckets[0][(z << 4) | x] = - BlockBucket.withSingle(PlotBlock.get("bedrock")); - } - } - } - for (short x = 0; x < 16; x++) { - for (short z = 0; z < 16; z++) { - for (int y = 1; y < hpw.PLOT_HEIGHT; y++) { - blockBuckets[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = hpw.MAIN_BLOCK; - } - blockBuckets[hpw.PLOT_HEIGHT >> 4][((hpw.PLOT_HEIGHT & 0xF) << 8) | (z << 4) | x] = - hpw.MAIN_BLOCK; - } - } - return blockBuckets; - } - @Override public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings) { - World w = BukkitUtil.getWorld(world); + World world = BukkitUtil.getWorld(this.world); Location min = result.getMin(); - int cx = min.getX() >> 4; - int cz = min.getZ() >> 4; - Random r = new Random(MathMan.pair((short) cx, (short) cz)); - ChunkGenerator.BiomeGrid grid = new ChunkGenerator.BiomeGrid() { - @Override public void setBiome(int x, int z, Biome biome) { - result.setBiome(x, z, biome.name()); - } - - @Override @NotNull public Biome getBiome(int x, int z) { - return Biome.FOREST; - } - }; + int chunkX = min.getX() >> 4; + int chunkZ = min.getZ() >> 4; + Random random = new Random(MathMan.pair((short) chunkX, (short) chunkZ)); try { - chunkGenerator.generateChunkData(w, r, cx, cz, grid); + ChunkGenerator.BiomeGrid grid = new ChunkGenerator.BiomeGrid() { + @Override public void setBiome(@Range(from = 0, to = 15) int x, + @Range(from = 0, to = 15) int z, Biome biome) { + result.setBiome(x, z, BukkitAdapter.adapt(biome)); + } + + @Override @NotNull public Biome getBiome(int x, int z) { + return Biome.FOREST; + } + }; + chunkGenerator.generateChunkData(world, random, chunkX, chunkZ, grid); return; } catch (Throwable ignored) { } - for (BlockPopulator populator : chunkGenerator.getDefaultPopulators(w)) { - populator.populate(w, r, w.getChunkAt(cx, cz)); + for (BlockPopulator populator : chunkGenerator.getDefaultPopulators(world)) { + populator.populate(world, random, world.getChunkAt(chunkX, chunkZ)); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/PlotBlockPopulator.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/PlotBlockPopulator.java index 4e2fee0b5..de06df5a3 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/PlotBlockPopulator.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/PlotBlockPopulator.java @@ -11,15 +11,17 @@ import lombok.RequiredArgsConstructor; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.generator.BlockPopulator; +import org.jetbrains.annotations.NotNull; import java.util.Random; -@RequiredArgsConstructor final class PlotBlockPopulator extends BlockPopulator { +@RequiredArgsConstructor final class BlockStatePopulator extends BlockPopulator { private final IndependentPlotGenerator plotGenerator; private LocalBlockQueue queue; - @Override public void populate(final World world, final Random random, final Chunk source) { + @Override public void populate(@NotNull final World world, @NotNull final Random random, + @NotNull final Chunk source) { if (this.queue == null) { this.queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java index c55e4f440..046c0de8f 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java @@ -1,7 +1,6 @@ package com.github.intellectualsites.plotsquared.bukkit.listeners; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -9,6 +8,7 @@ import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefCla import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefField; import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefMethod; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import io.papermc.lib.PaperLib; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Material; @@ -168,23 +168,24 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils @EventHandler(priority = EventPriority.LOWEST) public void onItemSpawn(ItemSpawnEvent event) { Item entity = event.getEntity(); - Chunk chunk = entity.getLocation().getChunk(); - if (chunk == this.lastChunk) { - event.getEntity().remove(); - event.setCancelled(true); - return; - } - if (!PlotSquared.get().hasPlotArea(chunk.getWorld().getName())) { - return; - } - Entity[] entities = chunk.getEntities(); - if (entities.length > Settings.Chunk_Processor.MAX_ENTITIES) { - event.getEntity().remove(); - event.setCancelled(true); - this.lastChunk = chunk; - } else { - this.lastChunk = null; - } + PaperLib.getChunkAtAsync(event.getLocation()).thenAccept(chunk -> { + if (chunk == this.lastChunk) { + event.getEntity().remove(); + event.setCancelled(true); + return; + } + if (!PlotSquared.get().hasPlotArea(chunk.getWorld().getName())) { + return; + } + Entity[] entities = chunk.getEntities(); + if (entities.length > Settings.Chunk_Processor.MAX_ENTITIES) { + event.getEntity().remove(); + event.setCancelled(true); + this.lastChunk = chunk; + } else { + this.lastChunk = null; + } + }); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @@ -197,23 +198,24 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils @EventHandler(priority = EventPriority.LOWEST) public void onEntitySpawn(CreatureSpawnEvent event) { LivingEntity entity = event.getEntity(); - Chunk chunk = entity.getLocation().getChunk(); - if (chunk == this.lastChunk) { - event.getEntity().remove(); - event.setCancelled(true); - return; - } - if (!PlotSquared.get().hasPlotArea(chunk.getWorld().getName())) { - return; - } - Entity[] entities = chunk.getEntities(); - if (entities.length > Settings.Chunk_Processor.MAX_ENTITIES) { - event.getEntity().remove(); - event.setCancelled(true); - this.lastChunk = chunk; - } else { - this.lastChunk = null; - } + PaperLib.getChunkAtAsync(event.getLocation()).thenAccept(chunk -> { + if (chunk == this.lastChunk) { + event.getEntity().remove(); + event.setCancelled(true); + return; + } + if (!PlotSquared.get().hasPlotArea(chunk.getWorld().getName())) { + return; + } + Entity[] entities = chunk.getEntities(); + if (entities.length > Settings.Chunk_Processor.MAX_ENTITIES) { + event.getEntity().remove(); + event.setCancelled(true); + this.lastChunk = chunk; + } else { + this.lastChunk = null; + } + }); } private void cleanChunk(final Chunk chunk) { @@ -223,8 +225,7 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils if (!chunk.isLoaded()) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); - PlotSquared - .debug(Captions.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); + PlotSquared.debug("Successfully processed and unloaded chunk!"); chunk.unload(true); return; } @@ -232,8 +233,7 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils if (tiles.length == 0) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); - PlotSquared - .debug(Captions.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); + PlotSquared.debug("Successfully processed and unloaded chunk!"); chunk.unload(true); return; } @@ -243,8 +243,7 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils if (i >= tiles.length) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); - PlotSquared.debug( - Captions.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); + PlotSquared.debug("Successfully processed and unloaded chunk!"); chunk.unload(true); return; } @@ -267,15 +266,11 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils ent.remove(); } } - PlotSquared.debug( - Captions.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX() - << 4) + "," + (chunk.getX() << 4)); + PlotSquared.debug("PlotSquared detected unsafe chunk and processed: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4)); } if (tiles.length > Settings.Chunk_Processor.MAX_TILES) { if (unload) { - PlotSquared.debug( - Captions.PREFIX.s() + "&c detected unsafe chunk: " + (chunk.getX() << 4) + "," - + (chunk.getX() << 4)); + PlotSquared.debug("PlotSquared detected unsafe chunk: " + (chunk.getX()<< 4) + "," + (chunk.getX() << 4)); cleanChunk(chunk); return true; } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/EntitySpawnListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/EntitySpawnListener.java index 27a24ba9d..a982f39fd 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/EntitySpawnListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/EntitySpawnListener.java @@ -7,6 +7,7 @@ import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import io.papermc.lib.PaperLib; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.entity.ArmorStand; @@ -75,7 +76,7 @@ public class EntitySpawnListener implements Listener { if (!world.getName().equalsIgnoreCase(originWorld + "_the_end")) { try { ignoreTP = true; - entity.teleport(origin); + PaperLib.teleportAsync(entity,origin); } finally { ignoreTP = false; } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java index 7a22be0fb..69752719f 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java @@ -1,7 +1,8 @@ package com.github.intellectualsites.plotsquared.bukkit.listeners; +import com.destroystokyo.paper.MaterialTags; import com.github.intellectualsites.plotsquared.bukkit.BukkitMain; -import com.github.intellectualsites.plotsquared.bukkit.object.BukkitLazyBlock; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitBlockUtil; import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; import com.github.intellectualsites.plotsquared.plot.PlotSquared; @@ -10,30 +11,113 @@ import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.listener.PlayerBlockEventType; import com.github.intellectualsites.plotsquared.plot.listener.PlotListener; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotHandler; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotInventory; +import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.StringWrapper; +import com.github.intellectualsites.plotsquared.plot.util.EntityUtil; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.RegExUtil; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.UpdateUtility; +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.item.ItemType; +import io.papermc.lib.PaperLib; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.FluidCollisionMode; import org.bukkit.Material; +import org.bukkit.Tag; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; import org.bukkit.block.data.BlockData; import org.bukkit.command.PluginCommand; -import org.bukkit.entity.*; +import org.bukkit.entity.Ageable; +import org.bukkit.entity.Animals; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Creature; +import org.bukkit.entity.EnderDragon; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.FallingBlock; +import org.bukkit.entity.Fireball; +import org.bukkit.entity.Hanging; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.ItemFrame; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Monster; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.entity.Tameable; +import org.bukkit.entity.ThrownPotion; +import org.bukkit.entity.Vehicle; +import org.bukkit.entity.Villager; +import org.bukkit.entity.WaterMob; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.block.*; -import org.bukkit.event.entity.*; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockBurnEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockDispenseEvent; +import org.bukkit.event.block.BlockExplodeEvent; +import org.bukkit.event.block.BlockFadeEvent; +import org.bukkit.event.block.BlockFormEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockGrowEvent; +import org.bukkit.event.block.BlockIgniteEvent; +import org.bukkit.event.block.BlockPhysicsEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.block.BlockRedstoneEvent; +import org.bukkit.event.block.BlockSpreadEvent; +import org.bukkit.event.block.EntityBlockFormEvent; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityCombustByEntityEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.entity.ExplosionPrimeEvent; +import org.bukkit.event.entity.LingeringPotionSplashEvent; +import org.bukkit.event.entity.PotionSplashEvent; +import org.bukkit.event.entity.ProjectileHitEvent; +import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.hanging.HangingPlaceEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.player.*; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.event.player.PlayerBucketFillEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerEggThrowEvent; +import org.bukkit.event.player.PlayerEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.vehicle.VehicleCreateEvent; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.vehicle.VehicleEntityCollisionEvent; @@ -52,8 +136,16 @@ import org.bukkit.projectiles.ProjectileSource; import org.bukkit.util.Vector; import java.lang.reflect.Field; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; import java.util.Map.Entry; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Supplier; import java.util.regex.Pattern; /** @@ -85,10 +177,10 @@ import java.util.regex.Pattern; int distance = Bukkit.getViewDistance() * 16; for (Entry entry : UUIDHandler.getPlayers().entrySet()) { PlotPlayer player = entry.getValue(); - Location loc = player.getLocation(); - if (loc.getWorld().equals(world)) { - if (16 * Math.abs(loc.getX() - x) / 16 > distance - || 16 * Math.abs(loc.getZ() - z) / 16 > distance) { + Location location = player.getLocation(); + if (location.getWorld().equals(world)) { + if (16 * Math.abs(location.getX() - x) / 16 > distance + || 16 * Math.abs(location.getZ() - z) / 16 > distance) { continue; } ((BukkitPlayer) player).player.sendBlockChange(bloc, data); @@ -314,12 +406,12 @@ import java.util.regex.Pattern; case POWERED_RAIL: return; default:*/ - Location loc = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = loc.getPlotArea(); + Location location = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location.getPlotArea(); if (area == null) { return; } - Plot plot = loc.getOwnedPlot(); + Plot plot = location.getOwnedPlot(); if (plot == null) { return; } @@ -369,12 +461,11 @@ import java.util.regex.Pattern; switch (event.getChangedType()) { case COMPARATOR: { Block block = event.getBlock(); - Location loc = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { + Location location = BukkitUtil.getLocation(block.getLocation()); + if (location.isPlotArea()) { return; } - Plot plot = area.getOwnedPlotAbs(loc); + Plot plot = location.getOwnedPlotAbs(); if (plot == null) { return; } @@ -391,12 +482,12 @@ import java.util.regex.Pattern; case TURTLE_HELMET: case TURTLE_SPAWN_EGG: { Block block = event.getBlock(); - Location loc = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = loc.getPlotArea(); + Location location = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location.getPlotArea(); if (area == null) { return; } - Plot plot = area.getOwnedPlotAbs(loc); + Plot plot = area.getOwnedPlotAbs(location); if (plot == null) { return; } @@ -413,30 +504,30 @@ import java.util.regex.Pattern; case STICKY_PISTON: org.bukkit.block.data.Directional piston = (org.bukkit.block.data.Directional) block.getBlockData(); - Location loc = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = loc.getPlotArea(); + Location location = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location.getPlotArea(); if (area == null) { return; } - Plot plot = area.getOwnedPlotAbs(loc); + Plot plot = area.getOwnedPlotAbs(location); if (plot == null) { return; } switch (piston.getFacing()) { case EAST: - loc.setX(loc.getX() + 1); + location.setX(location.getX() + 1); break; case SOUTH: - loc.setX(loc.getX() - 1); + location.setX(location.getX() - 1); break; case WEST: - loc.setZ(loc.getZ() + 1); + location.setZ(location.getZ() + 1); break; case NORTH: - loc.setZ(loc.getZ() - 1); + location.setZ(location.getZ() - 1); break; } - Plot newPlot = area.getOwnedPlotAbs(loc); + Plot newPlot = area.getOwnedPlotAbs(location); if (!plot.equals(newPlot)) { event.setCancelled(true); return; @@ -470,15 +561,15 @@ import java.util.regex.Pattern; @EventHandler public boolean onProjectileHit(ProjectileHitEvent event) { Projectile entity = event.getEntity(); - Location loc = BukkitUtil.getLocation(entity); - if (!PlotSquared.get().hasPlotArea(loc.getWorld())) { + Location location = BukkitUtil.getLocation(entity); + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { return true; } - PlotArea area = loc.getPlotArea(); + PlotArea area = location.getPlotArea(); if (area == null) { return true; } - Plot plot = area.getPlot(loc); + Plot plot = area.getPlot(location); ProjectileSource shooter = entity.getShooter(); if (shooter instanceof Player) { PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); @@ -523,22 +614,22 @@ import java.util.regex.Pattern; return; } Player player = event.getPlayer(); - PlotPlayer pp = BukkitUtil.getPlayer(player); - Location loc = pp.getLocation(); - PlotArea area = loc.getPlotArea(); + PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); + Location location = plotPlayer.getLocation(); + PlotArea area = location.getPlotArea(); if (area == null) { return; } String[] parts = msg.split(" "); - Plot plot = pp.getCurrentPlot(); + Plot plot = plotPlayer.getCurrentPlot(); // Check WorldEdit switch (parts[0].toLowerCase()) { case "up": case "/up": case "worldedit:up": case "worldedit:/up": - if (plot == null || (!plot.isAdded(pp.getUUID()) && !Permissions - .hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER, true))) { + if (plot == null || (!plot.isAdded(plotPlayer.getUUID()) && !Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER, true))) { event.setCancelled(true); return; } @@ -548,8 +639,8 @@ import java.util.regex.Pattern; } Optional> flag = plot.getFlag(Flags.BLOCKED_CMDS); if (flag.isPresent() && !Permissions - .hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { - List blocked_cmds = flag.get(); + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { + List blockedCommands = flag.get(); String part = parts[0]; if (parts[0].contains(":")) { part = parts[0].split(":")[1]; @@ -583,7 +674,7 @@ import java.util.regex.Pattern; if (!s1.equals(part)) { msg = msg.replace(s1, part); } - for (String s : blocked_cmds) { + for (String s : blockedCommands) { Pattern pattern; if (!RegExUtil.compiledPatterns.containsKey(s)) { RegExUtil.compiledPatterns.put(s, pattern = Pattern.compile(s)); @@ -592,13 +683,13 @@ import java.util.regex.Pattern; } if (pattern.matcher(msg).matches()) { String perm; - if (plot.isAdded(pp.getUUID())) { + if (plot.isAdded(plotPlayer.getUUID())) { perm = "plots.admin.command.blocked-cmds.shared"; } else { perm = "plots.admin.command.blocked-cmds.other"; } - if (!Permissions.hasPermission(pp, perm)) { - MainUtil.sendMessage(pp, Captions.COMMAND_BLOCKED); + if (!Permissions.hasPermission(plotPlayer, perm)) { + MainUtil.sendMessage(plotPlayer, Captions.COMMAND_BLOCKED); event.setCancelled(true); } return; @@ -619,10 +710,10 @@ import java.util.regex.Pattern; UUID uuid = pp.getUUID(); UUIDHandler.add(sw, uuid); - Location loc = pp.getLocation(); - PlotArea area = loc.getPlotArea(); + Location location = pp.getLocation(); + PlotArea area = location.getPlotArea(); if (area != null) { - Plot plot = area.getPlot(loc); + Plot plot = area.getPlot(location); if (plot != null) { plotEntry(pp, plot); } @@ -637,11 +728,11 @@ import java.util.regex.Pattern; EventUtil.manager.doJoinTask(pp); }, 20); - if (pp.hasPermission(Captions.PERMISSION_ADMIN_UPDATE_NOTIFICATION.s()) + if (pp.hasPermission(Captions.PERMISSION_ADMIN_UPDATE_NOTIFICATION.getTranslated()) && PlotSquared.get().getUpdateUtility() != null) { final UpdateUtility updateUtility = PlotSquared.get().getUpdateUtility(); final BukkitMain bukkitMain = BukkitMain.getPlugin(BukkitMain.class); - updateUtility.checkForUpdate(bukkitMain.getPluginVersionString(), + updateUtility.checkForUpdate(PlotSquared.get().getVersion().versionString(), ((updateDescription, throwable) -> { if (throwable != null) { bukkitMain.getLogger().severe(String @@ -654,8 +745,8 @@ import java.util.regex.Pattern; .text(" --------").color("$2").send(pp); new PlotMessage("There appears to be a PlotSquared update available!") .color("$1").send(pp); - new PlotMessage(String.format("You are running version %s," - + " the newest available version is %s", + new PlotMessage(String.format( + "You are running version %s, the newest available version is %s", bukkitMain.getPluginVersionString(), updateDescription.getVersion())).color("$1").send(pp); new PlotMessage("Update URL").color("$1").text(": ").color("$2") @@ -679,37 +770,33 @@ import java.util.regex.Pattern; @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onTeleport(PlayerTeleportEvent event) { - if (event.getTo() == null || event.getFrom() == null || !event.getFrom().getWorld() - .equals(event.getTo().getWorld())) { - final Object lastLoc = - BukkitUtil.getPlayer(event.getPlayer()).deleteMeta(PlotPlayer.META_LOCATION); - final Object lastPlot = - BukkitUtil.getPlayer(event.getPlayer()).deleteMeta(PlotPlayer.META_LAST_PLOT); - org.bukkit.Location to = event.getTo(); - if (to != null) { - Player player = event.getPlayer(); - PlotPlayer pp = PlotPlayer.wrap(player); - Location loc = BukkitUtil.getLocation(to); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); + Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); + org.bukkit.Location to = event.getTo(); + //noinspection ConstantConditions + if (to != null) { + Location location = BukkitUtil.getLocation(to); + PlotArea area = location.getPlotArea(); + if (area == null) { + if (lastPlot != null) { + plotExit(pp, lastPlot); + pp.deleteMeta(PlotPlayer.META_LAST_PLOT); } - Plot plot = area.getPlot(loc); - if (plot != null) { - final boolean result = Flags.DENY_TELEPORT.allowsTeleport(pp, plot); - if (!result) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_ENTRY_DENIED); - event.setCancelled(true); - if (lastLoc != null) { - pp.setMeta(PlotPlayer.META_LOCATION, lastLoc); - } - if (lastPlot != null) { - pp.setMeta(PlotPlayer.META_LAST_PLOT, lastPlot); - } - } else { - plotEntry(pp, plot); - } + pp.deleteMeta(PlotPlayer.META_LOCATION); + return; + } + Plot plot = area.getPlot(location); + if (plot != null) { + final boolean result = Flags.DENY_TELEPORT.allowsTeleport(pp, plot); + // there is one possibility to still allow teleportation: + // to is identical to the plot's home location, and untrusted-visit is true + // i.e. untrusted-visit can override deny-teleport + // this is acceptable, because otherwise it wouldn't make sense to have both flags set + if (!result && !(Flags.UNTRUSTED_VISIT.isTrue(plot) && plot.getHome().equals(BukkitUtil.getLocationFull(to)))) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_ENTRY_DENIED); + event.setCancelled(true); } } } @@ -754,17 +841,10 @@ import java.util.regex.Pattern; dest = null; } if (dest != null) { - if (passengers != null) { - vehicle.eject(); - vehicle.setVelocity(new Vector(0d, 0d, 0d)); - vehicle.teleport(dest); - passengers.forEach(vehicle::addPassenger); - } else { - vehicle.eject(); - vehicle.setVelocity(new Vector(0d, 0d, 0d)); - vehicle.teleport(dest); - vehicle.addPassenger(player); - } + vehicle.eject(); + vehicle.setVelocity(new Vector(0d, 0d, 0d)); + PaperLib.teleportAsync(vehicle, dest); + passengers.forEach(vehicle::addPassenger); return; } } @@ -809,14 +889,14 @@ import java.util.regex.Pattern; // Cancel teleport TaskManager.TELEPORT_QUEUE.remove(pp.getName()); // Set last location - Location loc = BukkitUtil.getLocation(to); - pp.setMeta(PlotPlayer.META_LOCATION, loc); - PlotArea area = loc.getPlotArea(); + Location location = BukkitUtil.getLocation(to); + pp.setMeta(PlotPlayer.META_LOCATION, location); + PlotArea area = location.getPlotArea(); if (area == null) { pp.deleteMeta(PlotPlayer.META_LAST_PLOT); return; } - Plot now = area.getPlot(loc); + Plot now = area.getPlot(location); Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); if (now == null) { if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp @@ -869,14 +949,14 @@ import java.util.regex.Pattern; // Cancel teleport TaskManager.TELEPORT_QUEUE.remove(pp.getName()); // Set last location - Location loc = BukkitUtil.getLocation(to); - pp.setMeta(PlotPlayer.META_LOCATION, loc); - PlotArea area = loc.getPlotArea(); + Location location = BukkitUtil.getLocation(to); + pp.setMeta(PlotPlayer.META_LOCATION, location); + PlotArea area = location.getPlotArea(); if (area == null) { pp.deleteMeta(PlotPlayer.META_LAST_PLOT); return; } - Plot now = area.getPlot(loc); + Plot now = area.getPlot(location); Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); if (now == null) { if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp @@ -939,9 +1019,12 @@ import java.util.regex.Pattern; if (plot == null) { return; } + if (plot.isDenied(plotPlayer.getUUID())) { + return; + } event.setCancelled(true); String message = event.getMessage(); - String format = Captions.PLOT_CHAT_FORMAT.s(); + String format = Captions.PLOT_CHAT_FORMAT.getTranslated(); String sender = event.getPlayer().getDisplayName(); PlotId id = plot.getId(); Set recipients = event.getRecipients(); @@ -968,8 +1051,8 @@ import java.util.regex.Pattern; receiver.sendMessage(full); } if (!spies.isEmpty()) { - String spyMessage = - Captions.PLOT_CHAT_SPY_FORMAT.s().replace("%plot_id%", id.x + ";" + id.y) + String spyMessage = Captions.PLOT_CHAT_SPY_FORMAT.getTranslated() + .replace("%plot_id%", id.x + ";" + id.y) .replace("%sender%", sender).replace("%msg%", message); for (Player player : spies) { player.sendMessage(spyMessage); @@ -999,26 +1082,23 @@ import java.util.regex.Pattern; } else if ( (location.getY() > area.MAX_BUILD_HEIGHT || location.getY() < area.MIN_BUILD_HEIGHT) && !Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_HEIGHT_LIMIT)) { event.setCancelled(true); - MainUtil.sendMessage(plotPlayer, Captions.HEIGHT_LIMIT.s() + MainUtil.sendMessage(plotPlayer, Captions.HEIGHT_LIMIT.getTranslated() .replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); } if (!plot.hasOwner()) { - if (Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - return; + if (!Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED, true)) { + event.setCancelled(true); } - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_UNOWNED); - event.setCancelled(true); return; } if (!plot.isAdded(plotPlayer.getUUID())) { - Optional> destroy = plot.getFlag(Flags.BREAK); + Optional> destroy = plot.getFlag(Flags.BREAK); Block block = event.getBlock(); if (destroy.isPresent() && destroy.get() - .contains(PlotBlock.get(block.getType().name()))) { + .contains(BukkitAdapter.asBlockType(block.getType()))) { return; } if (Permissions @@ -1108,8 +1188,8 @@ import java.util.regex.Pattern; Player player = event.getPlayer(); PlotPlayer pp = BukkitUtil.getPlayer(player); // Delete last location - pp.deleteMeta(PlotPlayer.META_LOCATION); Plot plot = (Plot) pp.deleteMeta(PlotPlayer.META_LAST_PLOT); + pp.deleteMeta(PlotPlayer.META_LOCATION); if (plot != null) { plotExit(pp, plot); } @@ -1123,10 +1203,10 @@ import java.util.regex.Pattern; if (Settings.Enabled_Components.PERMISSION_CACHE) { pp.deleteMeta("perm"); } - Location loc = pp.getLocation(); - PlotArea area = loc.getPlotArea(); - if (loc.isPlotArea()) { - plot = loc.getPlot(); + Location location = pp.getLocation(); + PlotArea area = location.getPlotArea(); + if (location.isPlotArea()) { + plot = location.getPlot(); if (plot != null) { plotEntry(pp, plot); } @@ -1223,6 +1303,11 @@ import java.util.regex.Pattern; event.setCancelled(true); } break; + case KELP: + if (Flags.KELP_GROW.isFalse(plot)) { + event.setCancelled(true); + } + break; } } @@ -1255,12 +1340,6 @@ import java.util.regex.Pattern; if (Flags.ICE_FORM.isFalse(plot)) { event.setCancelled(true); } - return; - case STONE: - case OBSIDIAN: - case COBBLESTONE: - // TODO event ? - return; } } @@ -1268,12 +1347,6 @@ import java.util.regex.Pattern; public void onBlockDamage(BlockDamageEvent event) { Player player = event.getPlayer(); Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); - if (player == null) { - if (location.isPlotRoad()) { - event.setCancelled(true); - return; - } - } PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -1295,10 +1368,10 @@ import java.util.regex.Pattern; } PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); if (!plot.isAdded(plotPlayer.getUUID())) { - Optional> destroy = plot.getFlag(Flags.BREAK); + Optional> destroy = plot.getFlag(Flags.BREAK); Block block = event.getBlock(); if (destroy.isPresent() && destroy.get() - .contains(PlotBlock.get(block.getType().name())) || Permissions + .contains(BukkitAdapter.asBlockType(block.getType())) || Permissions .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { return; } @@ -1412,8 +1485,7 @@ import java.util.regex.Pattern; event.setCancelled(true); return; } - List blocks = event.getBlocks(); - for (Block block1 : blocks) { + for (Block block1 : event.getBlocks()) { Location bloc = BukkitUtil.getLocation(block1.getLocation()); if (!area.contains(bloc.getX(), bloc.getZ()) || !area .contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { @@ -1530,7 +1602,7 @@ import java.util.regex.Pattern; if (!PlotSquared.get().hasPlotArea(event.getWorld().getName())) { return; } - List blocks = event.getBlocks(); + List blocks = event.getBlocks(); if (blocks.isEmpty()) { return; } @@ -1571,11 +1643,11 @@ import java.util.regex.Pattern; location = BukkitUtil.getLocation(blocks.get(i).getLocation()); Plot plot = area.getOwnedPlot(location); /* - * plot -> the base plot of the merged area - * origin -> the plot where the event gets called + * plot → the base plot of the merged area + * origin → the plot where the event gets called */ - // Are plot and origin not the same AND are both plots merged + // Are plot and origin different AND are both plots merged if (!Objects.equals(plot, origin) && (!plot.isMerged() && !origin.isMerged())) { event.getBlocks().remove(i); } @@ -1644,10 +1716,7 @@ import java.util.regex.Pattern; } } Block block = player.getTargetBlock(null, 7); - BlockState state = block.getState(); - if (state == null) { - return; - } + org.bukkit.block.BlockState state = block.getState(); Material stateType = state.getType(); Material itemType = newItem.getType(); if (stateType != itemType) { @@ -1806,7 +1875,7 @@ import java.util.regex.Pattern; return; } if (event.getAction() == Action.RIGHT_CLICK_AIR) { - Material item = event.getItem().getType(); + Material item = event.getMaterial(); if (item.toString().toLowerCase().endsWith("egg")) { event.setCancelled(true); event.setUseItemInHand(Event.Result.DENY); @@ -1814,8 +1883,8 @@ import java.util.regex.Pattern; } ItemStack hand = player.getInventory().getItemInMainHand(); ItemStack offHand = player.getInventory().getItemInOffHand(); - Material type = (hand == null) ? Material.AIR : hand.getType(); - Material offType = (offHand == null) ? Material.AIR : offHand.getType(); + Material type = hand.getType(); + Material offType = offHand.getType(); if (type == Material.AIR) { type = offType; } @@ -1824,8 +1893,7 @@ import java.util.regex.Pattern; if (block != null && block.getType() != Material.AIR) { Location location = BukkitUtil.getLocation(block.getLocation()); if (!EventUtil.manager - .checkPlayerBlockEvent(pp, PlayerBlockEventType.SPAWN_MOB, location, - new BukkitLazyBlock(PlotBlock.get(type.toString())), true)) { + .checkPlayerBlockEvent(pp, PlayerBlockEventType.SPAWN_MOB, location, null, true)) { event.setCancelled(true); event.setUseItemInHand(Event.Result.DENY); } @@ -1834,7 +1902,7 @@ import java.util.regex.Pattern; } } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = false) + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); PlotPlayer pp = BukkitUtil.getPlayer(player); @@ -1843,296 +1911,124 @@ import java.util.regex.Pattern; return; } PlayerBlockEventType eventType = null; - BukkitLazyBlock lb; - Location location; + BlockType blocktype1; + Block block = event.getClickedBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); Action action = event.getAction(); - switch (action) { + outer: switch (action) { case PHYSICAL: { eventType = PlayerBlockEventType.TRIGGER_PHYSICAL; - Block block = event.getClickedBlock(); - lb = new BukkitLazyBlock(block); - location = BukkitUtil.getLocation(block.getLocation()); + blocktype1 = BukkitAdapter.asBlockType(block.getType()); break; } + //todo rearrange the right click code. it is all over the place. case RIGHT_CLICK_BLOCK: { - Block block = event.getClickedBlock(); - location = BukkitUtil.getLocation(block.getLocation()); Material blockType = block.getType(); - switch (blockType) { - case ACACIA_DOOR: - case BIRCH_DOOR: - case DARK_OAK_DOOR: - case IRON_DOOR: - case JUNGLE_DOOR: - case OAK_DOOR: - case SPRUCE_DOOR: + eventType = PlayerBlockEventType.INTERACT_BLOCK; + blocktype1 = BukkitAdapter.asBlockType(block.getType()); - case ACACIA_TRAPDOOR: - case BIRCH_TRAPDOOR: - case DARK_OAK_TRAPDOOR: - case IRON_TRAPDOOR: - case JUNGLE_TRAPDOOR: - case OAK_TRAPDOOR: - case SPRUCE_TRAPDOOR: - - case CHEST: - case ENDER_CHEST: - case TRAPPED_CHEST: - - case ACACIA_FENCE_GATE: - case BIRCH_FENCE_GATE: - case DARK_OAK_FENCE_GATE: - case OAK_FENCE_GATE: - case JUNGLE_FENCE_GATE: - case SPRUCE_FENCE_GATE: - - case ACACIA_BUTTON: - case BIRCH_BUTTON: - case DARK_OAK_BUTTON: - case JUNGLE_BUTTON: - case OAK_BUTTON: - case SPRUCE_BUTTON: - case STONE_BUTTON: - - case BLACK_BED: - case BLUE_BED: - case BROWN_BED: - case CYAN_BED: - case GRAY_BED: - case GREEN_BED: - case LIGHT_BLUE_BED: - case LIGHT_GRAY_BED: - case LIME_BED: - case MAGENTA_BED: - case ORANGE_BED: - case PINK_BED: - case PURPLE_BED: - case RED_BED: - case WHITE_BED: - case YELLOW_BED: - - case BLACK_BANNER: - case BLACK_WALL_BANNER: - case BLUE_BANNER: - case BLUE_WALL_BANNER: - case BROWN_BANNER: - case BROWN_WALL_BANNER: - case CYAN_BANNER: - case CYAN_WALL_BANNER: - case GRAY_BANNER: - case GRAY_WALL_BANNER: - case GREEN_BANNER: - case GREEN_WALL_BANNER: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_BANNER: - case MAGENTA_WALL_BANNER: - case ORANGE_BANNER: - case ORANGE_WALL_BANNER: - case PINK_BANNER: - case PINK_WALL_BANNER: - case PURPLE_BANNER: - case PURPLE_WALL_BANNER: - case RED_BANNER: - case RED_WALL_BANNER: - case WHITE_BANNER: - case WHITE_WALL_BANNER: - case YELLOW_BANNER: - case YELLOW_WALL_BANNER: - - case BLACK_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case LIME_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case PINK_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case RED_SHULKER_BOX: - case WHITE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - - case CHAIN_COMMAND_BLOCK: - case REPEATING_COMMAND_BLOCK: - - case LEGACY_SIGN: - case LEGACY_WALL_SIGN: - case OAK_SIGN: - case ACACIA_SIGN: - case ACACIA_WALL_SIGN: - case BIRCH_SIGN: - case BIRCH_WALL_SIGN: - case DARK_OAK_SIGN: - case DARK_OAK_WALL_SIGN: - case JUNGLE_SIGN: - case JUNGLE_WALL_SIGN: - case OAK_WALL_SIGN: - case SPRUCE_SIGN: - case SPRUCE_WALL_SIGN: - - case REDSTONE_TORCH: - case REDSTONE_WALL_TORCH: - - case TURTLE_EGG: - case TURTLE_HELMET: - case TURTLE_SPAWN_EGG: - - case ANVIL: - case BEACON: - case BREWING_STAND: - case CAKE: - case COMMAND_BLOCK: - case COMPARATOR: - case CRAFTING_TABLE: - //todo re-evaluate adding lectern here - case LECTERN: - case GRINDSTONE: - case LOOM: - case SMOKER: - case STONECUTTER: - case DISPENSER: - case DROPPER: - case ENCHANTING_TABLE: - case FURNACE: - case BLAST_FURNACE: - case HOPPER: - case JUKEBOX: - case LEVER: - case NOTE_BLOCK: - case REDSTONE_ORE: - eventType = PlayerBlockEventType.INTERACT_BLOCK; + if (blockType.isInteractable()) { + if (!player.isSneaking()) { break; - case DRAGON_EGG: - eventType = PlayerBlockEventType.TELEPORT_OBJECT; + } + ItemStack hand = player.getInventory().getItemInMainHand(); + ItemStack offHand = player.getInventory().getItemInOffHand(); + + // sneaking players interact with blocks if both hands are empty + if (hand.getType() == Material.AIR && offHand.getType() == Material.AIR) { break; - default: - if (blockType.isInteractable()) { - eventType = PlayerBlockEventType.INTERACT_BLOCK; - } - } - lb = new BukkitLazyBlock(PlotBlock.get(block.getType().toString())); - if (eventType != null && (eventType != PlayerBlockEventType.INTERACT_BLOCK - || !player.isSneaking())) { - break; - } - ItemStack hand = player.getInventory().getItemInMainHand(); - ItemStack offHand = player.getInventory().getItemInOffHand(); - Material type = (hand == null) ? Material.AIR : hand.getType(); - Material offType = (offHand == null) ? Material.AIR : offHand.getType(); - if ((type == Material.AIR && offType != Material.AIR && !player.isSneaking() - && blockType.isInteractable()) || (type == Material.AIR - && offType == Material.AIR)) { - eventType = PlayerBlockEventType.INTERACT_BLOCK; - break; - } - if (type == Material.AIR) { - type = offType; - } - if (type.isBlock()) { - location = BukkitUtil - .getLocation(block.getRelative(event.getBlockFace()).getLocation()); - eventType = PlayerBlockEventType.PLACE_BLOCK; - break; - } - lb = new BukkitLazyBlock(PlotBlock.get(type.toString())); - if (type.toString().toLowerCase().endsWith("egg")) { - eventType = PlayerBlockEventType.SPAWN_MOB; - } else { - switch (type) { - case FIREWORK_ROCKET: - case FIREWORK_STAR: - eventType = PlayerBlockEventType.SPAWN_MOB; - break; - case ARMOR_STAND: - location = BukkitUtil - .getLocation(block.getRelative(event.getBlockFace()).getLocation()); - eventType = PlayerBlockEventType.PLACE_MISC; - break; - case BOOK: - case ENCHANTED_BOOK: - case KNOWLEDGE_BOOK: - case WRITABLE_BOOK: - case WRITTEN_BOOK: - eventType = PlayerBlockEventType.READ; - break; - case APPLE: - case BAKED_POTATO: - case BEEF: - case BREAD: - case CARROT: - case CHICKEN: - case COD: - case COOKED_BEEF: - case COOKED_CHICKEN: - case COOKED_COD: - case COOKED_MUTTON: - case COOKED_PORKCHOP: - case COOKED_RABBIT: - case COOKED_SALMON: - case COOKIE: - case GOLDEN_CARROT: - case MUSHROOM_STEW: - case MUTTON: - case POISONOUS_POTATO: - case PORKCHOP: - case POTATO: - case POTION: - case PUFFERFISH: - case PUMPKIN_PIE: - case RABBIT: - case RABBIT_FOOT: - case RABBIT_STEW: - case SALMON: - case TROPICAL_FISH: - eventType = PlayerBlockEventType.EAT; - break; - case ACACIA_BOAT: - case BIRCH_BOAT: - case CHEST_MINECART: - case COMMAND_BLOCK_MINECART: - case DARK_OAK_BOAT: - case FURNACE_MINECART: - case HOPPER_MINECART: - case JUNGLE_BOAT: - case MINECART: - case OAK_BOAT: - case SPRUCE_BOAT: - case TNT_MINECART: - eventType = PlayerBlockEventType.PLACE_VEHICLE; - break; - default: - eventType = PlayerBlockEventType.INTERACT_BLOCK; - break; } } + + Material type = event.getMaterial(); + + // in the following, lb needs to have the material of the item in hand i.e. type + switch (type) { + case REDSTONE: + case STRING: + case PUMPKIN_SEEDS: + case MELON_SEEDS: + case COCOA_BEANS: + case WHEAT_SEEDS: + case BEETROOT_SEEDS: + case SWEET_BERRIES: + return; + default: + //eventType = PlayerBlockEventType.PLACE_BLOCK; + if (type.isBlock()) { + return; + } + } + if (PaperLib.isPaper()) { + if (MaterialTags.SPAWN_EGGS.isTagged(type) || Material.EGG.equals(type)) { + eventType = PlayerBlockEventType.SPAWN_MOB; + break outer; + } + } else { + if (type.toString().toLowerCase().endsWith("egg")) { + eventType = PlayerBlockEventType.SPAWN_MOB; + break outer; + } + } + if (type.isEdible()) { + //Allow all players to eat while also allowing the block place event ot be fired + return; + } + switch (type) { + case ACACIA_BOAT: + case BIRCH_BOAT: + case CHEST_MINECART: + case COMMAND_BLOCK_MINECART: + case DARK_OAK_BOAT: + case FURNACE_MINECART: + case HOPPER_MINECART: + case JUNGLE_BOAT: + case MINECART: + case OAK_BOAT: + case SPRUCE_BOAT: + case TNT_MINECART: + eventType = PlayerBlockEventType.PLACE_VEHICLE; + break outer; + case FIREWORK_ROCKET: + case FIREWORK_STAR: + eventType = PlayerBlockEventType.SPAWN_MOB; + break outer; + case BOOK: + case KNOWLEDGE_BOOK: + case WRITABLE_BOOK: + case WRITTEN_BOOK: + eventType = PlayerBlockEventType.READ; + break outer; + case ARMOR_STAND: + location = BukkitUtil + .getLocation(block.getRelative(event.getBlockFace()).getLocation()); + eventType = PlayerBlockEventType.PLACE_MISC; + break outer; + } break; } - case LEFT_CLICK_BLOCK: - Block block = event.getClickedBlock(); + case LEFT_CLICK_BLOCK: { location = BukkitUtil.getLocation(block.getLocation()); - eventType = PlayerBlockEventType.BREAK_BLOCK; - lb = new BukkitLazyBlock(block); - break; + //eventType = PlayerBlockEventType.BREAK_BLOCK; + blocktype1 = BukkitAdapter.asBlockType(block.getType()); + if (block.getType() == Material.DRAGON_EGG) { + eventType = PlayerBlockEventType.TELEPORT_OBJECT; + break; + } + + return; + } default: return; } if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) { - if (player.getInventory().getItemInMainHand().getType() == Material - .getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) { + if (event.getMaterial() == Material.getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) { return; } } - if (!EventUtil.manager.checkPlayerBlockEvent(pp, eventType, location, lb, true)) { + if (!EventUtil.manager.checkPlayerBlockEvent(pp, eventType, location, blocktype1, true)) { event.setCancelled(true); + event.setUseInteractedBlock(Event.Result.DENY); } } @@ -2253,7 +2149,6 @@ import java.util.regex.Pattern; Plot plot = location.getOwnedPlot(); if (plot == null || !plot.getFlag(Flags.BLOCK_BURN, false)) { event.setCancelled(true); - return; } } @@ -2264,17 +2159,8 @@ import java.util.regex.Pattern; Entity ignitingEntity = event.getIgnitingEntity(); Block block = event.getBlock(); BlockIgniteEvent.IgniteCause igniteCause = event.getCause(); - Location loc; - if (block != null) { - loc = BukkitUtil.getLocation(block.getLocation()); - } else if (ignitingEntity != null) { - loc = BukkitUtil.getLocation(ignitingEntity); - } else if (player != null) { - loc = BukkitUtil.getLocation(player); - } else { - return; - } - PlotArea area = loc.getPlotArea(); + Location location1 = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location1.getPlotArea(); if (area == null) { return; } @@ -2283,7 +2169,7 @@ import java.util.regex.Pattern; return; } - Plot plot = area.getOwnedPlotAbs(loc); + Plot plot = area.getOwnedPlotAbs(location1); if (player != null) { PlotPlayer pp = BukkitUtil.getPlayer(player); if (plot == null) { @@ -2379,7 +2265,7 @@ import java.util.regex.Pattern; Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } else if (!plot.isAdded(pp.getUUID())) { - if (Flags.USE.contains(plot, PlotBlock.get(event.getBucket().getId(), 0))) { + if (Flags.USE.contains(plot, BukkitAdapter.asItemType(block.getType()))) { return; } if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { @@ -2439,9 +2325,9 @@ import java.util.regex.Pattern; Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } else if (!plot.isAdded(plotPlayer.getUUID())) { - Optional> use = plot.getFlag(Flags.USE); + Optional> use = plot.getFlag(Flags.USE); Block block = event.getBlockClicked(); - if (use.isPresent() && use.get().contains(PlotBlock.get(block.getType().name()))) { + if (use.isPresent() && use.get().contains(BukkitAdapter.asBlockType(block.getType()))) { return; } if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { @@ -2487,6 +2373,11 @@ import java.util.regex.Pattern; return; } Player p = event.getPlayer(); + if (p == null) { + PlotSquared.debug("PlotSquared does not support HangingPlaceEvent for non-players."); + event.setCancelled(true); + return; + } PlotPlayer pp = BukkitUtil.getPlayer(p); Plot plot = area.getPlot(location); if (plot == null) { @@ -2706,11 +2597,11 @@ import java.util.regex.Pattern; } } - @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST) + @EventHandler(priority = EventPriority.HIGHEST) public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { EntityDamageByEntityEvent eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), - EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration()); + EntityDamageEvent.DamageCause.FIRE_TICK, event.getDuration()); onEntityDamageByEntityEvent(eventChange); if (eventChange.isCancelled()) { event.setCancelled(true); @@ -2984,9 +2875,9 @@ import java.util.regex.Pattern; Plot plot = area.getPlot(location); if (plot != null) { if ((location.getY() > area.MAX_BUILD_HEIGHT || location.getY() < area.MIN_BUILD_HEIGHT) - && !Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { + && !Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_HEIGHT_LIMIT)) { event.setCancelled(true); - MainUtil.sendMessage(pp, Captions.HEIGHT_LIMIT.s() + MainUtil.sendMessage(pp, Captions.HEIGHT_LIMIT.getTranslated() .replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); } if (!plot.hasOwner()) { @@ -2997,11 +2888,11 @@ import java.util.regex.Pattern; return; } } else if (!plot.isAdded(pp.getUUID())) { - Set place = plot.getFlag(Flags.PLACE, null); + Set place = plot.getFlag(Flags.PLACE, null); if (place != null) { - Block block = event.getBlock(); - if (place.contains(PlotBlock.get(block.getType().name()))) { - return; + Block block = event.getBlock(); + if (place.contains(BukkitAdapter.asBlockType(block.getType()))) { + return; } } if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { @@ -3027,7 +2918,7 @@ import java.util.regex.Pattern; } else if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_ROAD); - event.setCancelled(true); - } + event.setCancelled(true); } } +} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java index fc13147dd..a53527fc9 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java @@ -30,8 +30,8 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle").getRealMethod(); try { this.mustSave = classChunk.getField("mustSave").getRealField(); - } catch (Throwable ignore) { - ignore.printStackTrace(); + } catch (NoSuchFieldException e) { + e.printStackTrace(); } Bukkit.getPluginManager().registerEvents(this, plugin); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitBlockUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitBlockUtil.java new file mode 100644 index 000000000..f35d4ea88 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitBlockUtil.java @@ -0,0 +1,31 @@ +package com.github.intellectualsites.plotsquared.bukkit.object; + +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.item.ItemType; +import org.bukkit.Material; +import org.bukkit.block.Block; + +import java.util.function.Supplier; + +public class BukkitBlockUtil { + public static Supplier supplyItem(Block block) { + return new Supplier() { + @Override public ItemType get() { + return BukkitAdapter.asItemType(block.getType()); + } + }; + } + + public static Supplier supplyItem(Material type) { + return () -> BukkitAdapter.asItemType(type); + } + + public static BlockState get(Block block) { + return get(block.getType()); + } + + public static BlockState get(Material material) { + return BukkitAdapter.asBlockType(material).getDefaultState(); + } +} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitLazyBlock.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitLazyBlock.java deleted file mode 100644 index 0903e78d9..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitLazyBlock.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.github.intellectualsites.plotsquared.bukkit.object; - -import com.github.intellectualsites.plotsquared.plot.object.LazyBlock; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; -import com.github.intellectualsites.plotsquared.plot.object.StringPlotBlock; -import org.bukkit.block.Block; - -public class BukkitLazyBlock extends LazyBlock { - - private StringPlotBlock pb; - - public BukkitLazyBlock(Block block) { - this.pb = (StringPlotBlock) PlotBlock.get(block.getType().toString()); - } - - public BukkitLazyBlock(StringPlotBlock pb) { - this.pb = pb; - } - - public StringPlotBlock getPlotBlock() { - return this.pb; - } - - -} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitOfflinePlayer.java index 390e9d9be..7c52a25de 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitOfflinePlayer.java @@ -2,6 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.object; import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; import org.bukkit.OfflinePlayer; +import org.jetbrains.annotations.NotNull; import java.util.UUID; @@ -19,7 +20,7 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { this.player = player; } - @Override public UUID getUUID() { + @NotNull @Override public UUID getUUID() { return this.player.getUniqueId(); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java index 1afe93656..e1a0db358 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java @@ -4,27 +4,38 @@ import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.Location; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.PlotWeather; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.world.item.ItemType; +import com.sk89q.worldedit.world.item.ItemTypes; +import io.papermc.lib.PaperLib; import org.bukkit.GameMode; -import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.WeatherType; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventException; import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.RegisteredListener; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Arrays; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; +import static com.sk89q.worldedit.world.gamemode.GameModes.ADVENTURE; +import static com.sk89q.worldedit.world.gamemode.GameModes.CREATIVE; +import static com.sk89q.worldedit.world.gamemode.GameModes.SPECTATOR; +import static com.sk89q.worldedit.world.gamemode.GameModes.SURVIVAL; + public class BukkitPlayer extends PlotPlayer { private static boolean CHECK_EFFECTIVE = true; @@ -37,25 +48,29 @@ public class BukkitPlayer extends PlotPlayer { *

Please do not use this method. Instead use * BukkitUtil.getPlayer(Player), as it caches player objects.

* - * @param player + * @param player Bukkit player instance */ - public BukkitPlayer(Player player) { + public BukkitPlayer(@NotNull final Player player) { this.player = player; super.populatePersistentMetaMap(); } - public BukkitPlayer(Player player, boolean offline) { + public BukkitPlayer(@NotNull final Player player, final boolean offline) { this.player = player; this.offline = offline; super.populatePersistentMetaMap(); } - @Override public Location getLocation() { - Location location = super.getLocation(); + @Override public Actor toActor() { + return BukkitAdapter.adapt(player); + } + + @NotNull @Override public Location getLocation() { + final Location location = super.getLocation(); return location == null ? BukkitUtil.getLocation(this.player) : location; } - @Nonnull @Override public UUID getUUID() { + @NotNull @Override public UUID getUUID() { if (this.uuid == null) { this.uuid = UUIDHandler.getUUID(this); } @@ -66,9 +81,9 @@ public class BukkitPlayer extends PlotPlayer { return this.player.getLastPlayed(); } - @Override public boolean canTeleport(Location loc) { - org.bukkit.Location to = BukkitUtil.getLocation(loc); - org.bukkit.Location from = player.getLocation(); + @Override public boolean canTeleport(@NotNull final Location location) { + final org.bukkit.Location to = BukkitUtil.getLocation(location); + final org.bukkit.Location from = player.getLocation(); PlayerTeleportEvent event = new PlayerTeleportEvent(player, from, to); callEvent(event); if (event.isCancelled() || !event.getTo().equals(to)) { @@ -79,37 +94,42 @@ public class BukkitPlayer extends PlotPlayer { return true; } - private void callEvent(final Event event) { - RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners(); - for (RegisteredListener listener : listeners) { + @Override + public void sendTitle(String title, String subtitle, int fadeIn, int stay, int fadeOut) { + player.sendTitle(title, subtitle, fadeIn, stay, fadeOut); + } + + private void callEvent(@NotNull final Event event) { + final RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners(); + for (final RegisteredListener listener : listeners) { if (listener.getPlugin().getName().equals(PlotSquared.imp().getPluginName())) { continue; } try { listener.callEvent(event); - } catch (EventException e) { + } catch (final EventException e) { e.printStackTrace(); } } } - @Override public boolean hasPermission(String permission) { + @Override public boolean hasPermission(final String permission) { if (this.offline && EconHandler.manager != null) { return EconHandler.manager.hasPermission(getName(), permission); } return this.player.hasPermission(permission); } - @Override public int hasPermissionRange(String stub, int range) { - if (hasPermission(Captions.PERMISSION_ADMIN.s())) { + @Override public int hasPermissionRange(final String stub, final int range) { + if (hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { return Integer.MAX_VALUE; } - String[] nodes = stub.split("\\."); - StringBuilder n = new StringBuilder(); + final String[] nodes = stub.split("\\."); + final StringBuilder n = new StringBuilder(); for (int i = 0; i < (nodes.length - 1); i++) { n.append(nodes[i]).append("."); - if (!stub.equals(n + Captions.PERMISSION_STAR.s())) { - if (hasPermission(n + Captions.PERMISSION_STAR.s())) { + if (!stub.equals(n + Captions.PERMISSION_STAR.getTranslated())) { + if (hasPermission(n + Captions.PERMISSION_STAR.getTranslated())) { return Integer.MAX_VALUE; } } @@ -121,7 +141,7 @@ public class BukkitPlayer extends PlotPlayer { if (CHECK_EFFECTIVE) { boolean hasAny = false; String stubPlus = stub + "."; - Set effective = player.getEffectivePermissions(); + final Set effective = player.getEffectivePermissions(); if (!effective.isEmpty()) { for (PermissionAttachmentInfo attach : effective) { String permStr = attach.getPermission(); @@ -160,11 +180,11 @@ public class BukkitPlayer extends PlotPlayer { return max; } - @Override public boolean isPermissionSet(String permission) { + @Override public boolean isPermissionSet(final String permission) { return this.player.isPermissionSet(permission); } - @Override public void sendMessage(String message) { + @Override public void sendMessage(final String message) { if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || ( System.currentTimeMillis() - this.getMeta("lastMessageTime") > 5000)) { setMeta("lastMessage", message); @@ -173,14 +193,13 @@ public class BukkitPlayer extends PlotPlayer { } } - @Override public void teleport(Location location) { + @Override public void teleport(@NotNull final Location location) { if (Math.abs(location.getX()) >= 30000000 || Math.abs(location.getZ()) >= 30000000) { return; } - this.player.teleport( - new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5, - location.getY(), location.getZ() + 0.5, location.getYaw(), location.getPitch()), - TeleportCause.COMMAND); + final org.bukkit.Location bukkitLocation = new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5, + location.getY(), location.getZ() + 0.5, location.getYaw(), location.getPitch()); + PaperLib.teleportAsync(player, bukkitLocation, PlayerTeleportEvent.TeleportCause.PLUGIN); } @Override public String getName() { @@ -198,14 +217,13 @@ public class BukkitPlayer extends PlotPlayer { this.player.setCompassTarget( new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ())); - } @Override public Location getLocationFull() { return BukkitUtil.getLocationFull(this.player); } - @Override public void setWeather(PlotWeather weather) { + @Override public void setWeather(@NotNull final PlotWeather weather) { switch (weather) { case CLEAR: this.player.setPlayerWeather(WeatherType.CLEAR); @@ -214,50 +232,39 @@ public class BukkitPlayer extends PlotPlayer { this.player.setPlayerWeather(WeatherType.DOWNFALL); break; case RESET: - this.player.resetPlayerWeather(); - break; default: this.player.resetPlayerWeather(); break; } } - @Override public PlotGameMode getGameMode() { + @NotNull @Override public com.sk89q.worldedit.world.gamemode.GameMode getGameMode() { switch (this.player.getGameMode()) { case ADVENTURE: - return PlotGameMode.ADVENTURE; + return ADVENTURE; case CREATIVE: - return PlotGameMode.CREATIVE; + return CREATIVE; case SPECTATOR: - return PlotGameMode.SPECTATOR; + return SPECTATOR; case SURVIVAL: - return PlotGameMode.SURVIVAL; default: - return PlotGameMode.NOT_SET; + return SURVIVAL; } } - @Override public void setGameMode(PlotGameMode gameMode) { - switch (gameMode) { - case ADVENTURE: - this.player.setGameMode(GameMode.ADVENTURE); - break; - case CREATIVE: - this.player.setGameMode(GameMode.CREATIVE); - break; - case SPECTATOR: - this.player.setGameMode(GameMode.SPECTATOR); - break; - case SURVIVAL: - this.player.setGameMode(GameMode.SURVIVAL); - break; - default: - this.player.setGameMode(GameMode.SURVIVAL); - break; + @Override public void setGameMode(@NotNull final com.sk89q.worldedit.world.gamemode.GameMode gameMode) { + if (ADVENTURE.equals(gameMode)) { + this.player.setGameMode(GameMode.ADVENTURE); + } else if (CREATIVE.equals(gameMode)) { + this.player.setGameMode(GameMode.CREATIVE); + } else if (SPECTATOR.equals(gameMode)) { + this.player.setGameMode(GameMode.SPECTATOR); + } else { + this.player.setGameMode(GameMode.SURVIVAL); } } - @Override public void setTime(long time) { + @Override public void setTime(final long time) { if (time != Long.MAX_VALUE) { this.player.setPlayerTime(time, false); } else { @@ -273,8 +280,8 @@ public class BukkitPlayer extends PlotPlayer { this.player.setAllowFlight(fly); } - @Override public void playMusic(Location location, PlotBlock id) { - if (PlotBlock.isEverything(id) || id.isAir()) { + @Override public void playMusic(@NotNull final Location location, @NotNull final ItemType id) { + if (id == ItemTypes.AIR) { // Let's just stop all the discs because why not? for (final Sound sound : Arrays.stream(Sound.values()) .filter(sound -> sound.name().contains("DISC")).collect(Collectors.toList())) { @@ -284,16 +291,16 @@ public class BukkitPlayer extends PlotPlayer { } else { // this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id.to(Material.class)); this.player.playSound(BukkitUtil.getLocation(location), - Sound.valueOf(id.to(Material.class).name()), Float.MAX_VALUE, 1f); + Sound.valueOf(BukkitAdapter.adapt(id).name()), Float.MAX_VALUE, 1f); } } - @Override public void kick(String message) { + @Override public void kick(final String message) { this.player.kickPlayer(message); } @Override public void stopSpectating() { - if (getGameMode() == PlotGameMode.SPECTATOR) { + if (getGameMode() == SPECTATOR) { this.player.setSpectatorTarget(null); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/EntityBaseStats.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/EntityBaseStats.java index d33b4d913..c36236a5d 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/EntityBaseStats.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/EntityBaseStats.java @@ -1,6 +1,5 @@ package com.github.intellectualsites.plotsquared.bukkit.object.entity; - class EntityBaseStats { EntityWrapper passenger; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java index c7e0e04f6..a237bf96a 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java @@ -1,9 +1,30 @@ package com.github.intellectualsites.plotsquared.bukkit.object.entity; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import org.bukkit.*; +import org.bukkit.Art; +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.Rotation; +import org.bukkit.TreeSpecies; +import org.bukkit.World; import org.bukkit.block.BlockFace; -import org.bukkit.entity.*; +import org.bukkit.entity.AbstractHorse; +import org.bukkit.entity.Ageable; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Bat; +import org.bukkit.entity.Boat; +import org.bukkit.entity.ChestedHorse; +import org.bukkit.entity.EnderDragon; +import org.bukkit.entity.Entity; +import org.bukkit.entity.IronGolem; +import org.bukkit.entity.Item; +import org.bukkit.entity.ItemFrame; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Painting; +import org.bukkit.entity.Rabbit; +import org.bukkit.entity.Sheep; +import org.bukkit.entity.Slime; +import org.bukkit.entity.Tameable; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; @@ -576,14 +597,6 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { restoreAgeable((Ageable) entity); restoreLiving((LivingEntity) entity); return entity; - case GUARDIAN: - case ELDER_GUARDIAN: - restoreLiving((LivingEntity) entity); - return entity; - case SKELETON: - case WITHER_SKELETON: - restoreLiving((LivingEntity) entity); - return entity; case ARMOR_STAND: // CHECK positions ArmorStand stand = (ArmorStand) entity; @@ -679,6 +692,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { case BLAZE: case SNOWMAN: case SHULKER: + case GUARDIAN: + case ELDER_GUARDIAN: + case SKELETON: + case WITHER_SKELETON: restoreLiving((LivingEntity) entity); return entity; case IRON_GOLEM: diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java index aaf5f4aa5..1d2d80198 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java @@ -3,11 +3,15 @@ package com.github.intellectualsites.plotsquared.bukkit.object.schematic; import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; -import com.sk89q.jnbt.*; +import com.sk89q.jnbt.ByteTag; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.ListTag; +import com.sk89q.jnbt.ShortTag; +import com.sk89q.jnbt.StringTag; +import com.sk89q.jnbt.Tag; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; -import org.bukkit.block.BlockState; import org.bukkit.block.Container; import org.bukkit.block.Sign; import org.bukkit.enchantments.Enchantment; @@ -23,10 +27,10 @@ import java.util.Map.Entry; public class StateWrapper { - public BlockState state = null; + public org.bukkit.block.BlockState state = null; public CompoundTag tag = null; - public StateWrapper(BlockState state) { + public StateWrapper(org.bukkit.block.BlockState state) { this.state = state; } @@ -151,7 +155,7 @@ public class StateWrapper { if (block == null) { return false; } - BlockState state = block.getState(); + org.bukkit.block.BlockState state = block.getState(); switch (tileid) { case "chest": case "beacon": diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitle.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitle.java deleted file mode 100644 index e91f8bcae..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitle.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.github.intellectualsites.plotsquared.bukkit.titles; - -import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; -import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import com.github.intellectualsites.plotsquared.plot.util.AbstractTitle; -import org.bukkit.entity.Player; - -public class DefaultTitle extends AbstractTitle { - - @Override - public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) { - final Player playerObj = ((BukkitPlayer) player).player; - playerObj.sendTitle(head, sub, in, delay, out); - } -} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitBlockRegistry.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitBlockRegistry.java deleted file mode 100644 index b5ac5f1fb..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitBlockRegistry.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.github.intellectualsites.plotsquared.bukkit.util; - -import com.github.intellectualsites.plotsquared.plot.object.BlockRegistry; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; -import lombok.NonNull; -import org.bukkit.Material; - -public class BukkitBlockRegistry extends BlockRegistry { - - public BukkitBlockRegistry(final Material... preInitializedItems) { - super(Material.class, preInitializedItems); - } - - @Override public PlotBlock getPlotBlock(@NonNull final Material item) { - return PlotBlock.get(item.name()); - } - -} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java index 744f4b6e9..4fb6f5db4 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java @@ -5,15 +5,24 @@ import com.github.intellectualsites.plotsquared.bukkit.object.entity.Replicating import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils; import com.github.intellectualsites.plotsquared.plot.listener.WEExtent; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotLoc; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.world.RegionUtil; import com.sk89q.worldedit.bukkit.BukkitWorld; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockTypes; +import io.papermc.lib.PaperLib; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.World; @@ -24,29 +33,30 @@ import org.bukkit.entity.Creature; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CompletableFuture; + +import static com.google.common.base.Preconditions.checkNotNull; public class BukkitChunkManager extends ChunkManager { - public static boolean isIn(RegionWrapper region, int x, int z) { - return x >= region.minX && x <= region.maxX && z >= region.minZ && z <= region.maxZ; - } - - private static byte getOrdinal(Object[] list, Object value) { - for (byte i = 0; i < list.length; i++) { - if (list[i].equals(value)) { - return i; - } - } - return 0; + public static boolean isIn(CuboidRegion region, int x, int z) { + return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX() && z >= region.getMinimumPoint().getZ() && z <= region.getMaximumPoint().getZ(); } public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2, - RegionWrapper r1, RegionWrapper r2) { + CuboidRegion r1, CuboidRegion r2) { ContentMap map = new ContentMap(); - int relX = r2.minX - r1.minX; - int relZ = r2.minZ - r1.minZ; + int relX = r2.getMinimumPoint().getX() - r1.getMinimumPoint().getX(); + int relZ = r2.getMinimumPoint().getZ() - r1.getMinimumPoint().getZ(); map.saveEntitiesIn(pos1, r1, relX, relZ, true); map.saveEntitiesIn(pos2, r2, -relX, -relZ, true); @@ -63,8 +73,8 @@ public class BukkitChunkManager extends ChunkManager { LocalBlockQueue queue1 = GlobalBlockQueue.IMP.getNewQueue(worldName1, false); LocalBlockQueue queue2 = GlobalBlockQueue.IMP.getNewQueue(worldName2, false); - for (int x = Math.max(r1.minX, sx); x <= Math.min(r1.maxX, sx + 15); x++) { - for (int z = Math.max(r1.minZ, sz); z <= Math.min(r1.maxZ, sz + 15); z++) { + for (int x = Math.max(r1.getMinimumPoint().getX(), sx); x <= Math.min(r1.getMaximumPoint().getX(), sx + 15); x++) { + for (int z = Math.max(r1.getMinimumPoint().getZ(), sz); z <= Math.min(r1.getMaximumPoint().getZ(), sz + 15); z++) { for (int y = 0; y < 256; y++) { Block block1 = world1.getBlockAt(x, y, z); BaseBlock baseBlock1 = bukkitWorld1.getFullBlock(BlockVector3.at(x, y, z)); @@ -102,10 +112,10 @@ public class BukkitChunkManager extends ChunkManager { return map; } - @Override public Set getChunkChunks(String world) { - Set chunks = super.getChunkChunks(world); - for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) { - ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5); + @Override public Set getChunkChunks(String world) { + Set chunks = super.getChunkChunks(world); + for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)).getLoadedChunks()) { + BlockVector2 loc = BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5); chunks.add(loc); } return chunks; @@ -152,19 +162,20 @@ public class BukkitChunkManager extends ChunkManager { if (doWhole) { for (Entity entity : entities) { org.bukkit.Location location = entity.getLocation(); - Chunk chunk = location.getChunk(); - if (chunks.contains(chunk)) { - int X = chunk.getX(); - int Z = chunk.getZ(); - if (X > bx && X < tx && Z > bz && Z < tz) { - count(count, entity); - } else { - Plot other = area.getPlot(BukkitUtil.getLocation(location)); - if (plot.equals(other)) { + PaperLib.getChunkAtAsync(location).thenAccept( chunk -> { + if (chunks.contains(chunk)) { + int X = chunk.getX(); + int Z = chunk.getZ(); + if (X > bx && X < tx && Z > bz && Z < tz) { count(count, entity); + } else { + Plot other = area.getPlot(BukkitUtil.getLocation(location)); + if (plot.equals(other)) { + count(count, entity); + } } } - } + }); } } else { for (Chunk chunk : chunks) { @@ -191,11 +202,13 @@ public class BukkitChunkManager extends ChunkManager { final int relX = newPos.getX() - pos1.getX(); final int relZ = newPos.getZ() - pos1.getZ(); - final RegionWrapper region = - new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); + final CuboidRegion region = + RegionUtil.createRegion(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); final World oldWorld = Bukkit.getWorld(pos1.getWorld()); final BukkitWorld oldBukkitWorld = new BukkitWorld(oldWorld); final World newWorld = Bukkit.getWorld(newPos.getWorld()); + assert newWorld != null; + assert oldWorld != null; final String newWorldName = newWorld.getName(); final ContentMap map = new ContentMap(); final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(newWorldName, false); @@ -205,16 +218,17 @@ public class BukkitChunkManager extends ChunkManager { int bz = value[3]; int tx = value[4]; int tz = value[5]; - ChunkLoc loc = new ChunkLoc(value[0], value[1]); - int cxx = loc.x << 4; - int czz = loc.z << 4; - Chunk chunk = oldWorld.getChunkAt(loc.x, loc.z); - map.saveEntitiesIn(chunk, region); - for (int x = bx & 15; x <= (tx & 15); x++) { - for (int z = bz & 15; z <= (tz & 15); z++) { - map.saveBlocks(oldBukkitWorld, 256, cxx + x, czz + z, relX, relZ); + BlockVector2 loc = BlockVector2.at(value[0], value[1]); + int cxx = loc.getX() << 4; + int czz = loc.getZ() << 4; + PaperLib.getChunkAtAsync(oldWorld, loc.getX(), loc.getZ()) + .thenAccept(chunk1 -> map.saveEntitiesIn(chunk1, region)).thenRun(() -> { + for (int x = bx & 15; x <= (tx & 15); x++) { + for (int z = bz & 15; z <= (tz & 15); z++) { + map.saveBlocks(oldBukkitWorld, 256, cxx + x, czz + z, relX, relZ); + } } - } + }); } }, () -> { for (Entry entry : map.allBlocks.entrySet()) { @@ -228,7 +242,7 @@ public class BukkitChunkManager extends ChunkManager { } } queue.enqueue(); - GlobalBlockQueue.IMP.addTask(() -> { + GlobalBlockQueue.IMP.addEmptyTask(() -> { //map.restoreBlocks(newWorld, 0, 0); map.restoreEntities(newWorld, relX, relZ); TaskManager.runTask(whenDone); @@ -250,22 +264,23 @@ public class BukkitChunkManager extends ChunkManager { final int tcx = p2x >> 4; final int tcz = p2z >> 4; - final List chunks = new ArrayList<>(); + final List chunks = new ArrayList<>(); for (int x = bcx; x <= tcx; x++) { for (int z = bcz; z <= tcz; z++) { - chunks.add(new ChunkLoc(x, z)); + chunks.add(BlockVector2.at(x, z)); } } final World worldObj = Bukkit.getWorld(world); + checkNotNull(worldObj, "Critical error during regeneration."); final BukkitWorld bukkitWorldObj = new BukkitWorld(worldObj); TaskManager.runTask(new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) { - final ChunkLoc chunk = chunks.remove(0); - int x = chunk.x; - int z = chunk.z; + final BlockVector2 chunk = chunks.remove(0); + int x = chunk.getX(); + int z = chunk.getZ(); int xxb = x << 4; int zzb = z << 4; int xxt = xxb + 15; @@ -278,7 +293,7 @@ public class BukkitChunkManager extends ChunkManager { if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z && PlotSquared.imp().getServerVersion()[1] == 13) { AugmentedUtils - .bypass(ignoreAugment, () -> queue.regenChunkSafe(chunk.x, chunk.z)); + .bypass(ignoreAugment, () -> queue.regenChunkSafe(chunk.getX(), chunk.getZ())); continue; } boolean checkX1 = false; @@ -340,8 +355,8 @@ public class BukkitChunkManager extends ChunkManager { if (checkX2 && checkZ2) { map.saveRegion(bukkitWorldObj, xxt2, xxt, zzt2, zzt); // } - RegionWrapper currentPlotClear = - new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); + CuboidRegion currentPlotClear = + RegionUtil.createRegion(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); map.saveEntitiesOut(chunkObj, currentPlotClear); AugmentedUtils.bypass(ignoreAugment, () -> setChunkInPlotArea(null, new RunnableVal() { @@ -351,15 +366,15 @@ public class BukkitChunkManager extends ChunkManager { int bz = min.getZ(); for (int x1 = 0; x1 < 16; x1++) { for (int z1 = 0; z1 < 16; z1++) { - PlotLoc loc = new PlotLoc(bx + x1, bz + z1); - BaseBlock[] ids = map.allBlocks.get(loc); + PlotLoc plotLoc = new PlotLoc(bx + x1, bz + z1); + BaseBlock[] ids = map.allBlocks.get(plotLoc); if (ids != null) { for (int y = 0; y < Math.min(128, ids.length); y++) { BaseBlock id = ids[y]; if (id != null) { value.setBlock(x1, y, z1, id); } else { - value.setBlock(x1, y, z1, PlotBlock.get("air")); + value.setBlock(x1, y, z1, BlockTypes.AIR.getDefaultState()); } } for (int y = Math.min(128, ids.length); @@ -387,17 +402,17 @@ public class BukkitChunkManager extends ChunkManager { return true; } - @Override public boolean loadChunk(String world, ChunkLoc loc, boolean force) { - return BukkitUtil.getWorld(world).getChunkAt(loc.x, loc.z).load(force); + @Override public CompletableFuture loadChunk(String world, BlockVector2 chunkLoc, boolean force) { + return PaperLib.getChunkAtAsync(BukkitUtil.getWorld(world),chunkLoc.getX(), chunkLoc.getZ(), force); } - @SuppressWarnings("deprecation") @Override - public void unloadChunk(final String world, final ChunkLoc loc, final boolean save, - final boolean safe) { + @Override + public void unloadChunk(final String world, final BlockVector2 chunkLoc, final boolean save) { if (!PlotSquared.get().isMainThread(Thread.currentThread())) { - TaskManager.runTask(() -> BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save)); + TaskManager.runTask( + () -> BukkitUtil.getWorld(world).unloadChunk(chunkLoc.getX(), chunkLoc.getZ(), save)); } else { - BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save); + BukkitUtil.getWorld(world).unloadChunk(chunkLoc.getX(), chunkLoc.getZ(), save); } } @@ -424,13 +439,14 @@ public class BukkitChunkManager extends ChunkManager { @Override public void swap(Location bot1, Location top1, Location bot2, Location top2, final Runnable whenDone) { - RegionWrapper region1 = - new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); - RegionWrapper region2 = - new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ()); + CuboidRegion region1 = + RegionUtil.createRegion(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); + CuboidRegion region2 = + RegionUtil.createRegion(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ()); final World world1 = Bukkit.getWorld(bot1.getWorld()); - World world2 = Bukkit.getWorld(bot2.getWorld()); - + final World world2 = Bukkit.getWorld(bot2.getWorld()); + checkNotNull(world1,"Critical error during swap."); + checkNotNull(world2,"Critical error during swap."); int relX = bot2.getX() - bot1.getX(); int relZ = bot2.getZ() - bot1.getZ(); @@ -443,7 +459,7 @@ public class BukkitChunkManager extends ChunkManager { maps.add(swapChunk(world1, world2, chunk1, chunk2, region1, region2)); } } - GlobalBlockQueue.IMP.addTask(() -> { + GlobalBlockQueue.IMP.addEmptyTask(() -> { for (ContentMap map : maps) { map.restoreEntities(world1, 0, 0); TaskManager.runTaskLater(whenDone, 1); @@ -612,11 +628,11 @@ public class BukkitChunkManager extends ChunkManager { } } - void saveEntitiesOut(Chunk chunk, RegionWrapper region) { + void saveEntitiesOut(Chunk chunk, CuboidRegion region) { for (Entity entity : chunk.getEntities()) { - Location loc = BukkitUtil.getLocation(entity); - int x = loc.getX(); - int z = loc.getZ(); + Location location = BukkitUtil.getLocation(entity); + int x = location.getX(); + int z = location.getZ(); if (isIn(region, x, z)) { continue; } @@ -629,16 +645,16 @@ public class BukkitChunkManager extends ChunkManager { } } - void saveEntitiesIn(Chunk chunk, RegionWrapper region) { + void saveEntitiesIn(Chunk chunk, CuboidRegion region) { saveEntitiesIn(chunk, region, 0, 0, false); } - void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ, + void saveEntitiesIn(Chunk chunk, CuboidRegion region, int offsetX, int offsetZ, boolean delete) { for (Entity entity : chunk.getEntities()) { - Location loc = BukkitUtil.getLocation(entity); - int x = loc.getX(); - int z = loc.getZ(); + Location location = BukkitUtil.getLocation(entity); + int x = location.getX(); + int z = location.getZ(); if (!isIn(region, x, z)) { continue; } @@ -673,8 +689,7 @@ public class BukkitChunkManager extends ChunkManager { //todo optimize maxY void saveBlocks(BukkitWorld world, int maxY, int x, int z, int offsetX, int offsetZ) { maxY = Math.min(255, maxY); - BaseBlock[] ids; - ids = new BaseBlock[maxY + 1]; + BaseBlock[] ids = new BaseBlock[maxY + 1]; for (short y = 0; y <= maxY; y++) { BaseBlock block = world.getFullBlock(BlockVector3.at(x, y, z)); ids[y] = block; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitCommand.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitCommand.java index 27edabf78..cb927f190 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitCommand.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitCommand.java @@ -4,7 +4,13 @@ import com.github.intellectualsites.plotsquared.bukkit.commands.DebugUUID; import com.github.intellectualsites.plotsquared.plot.commands.MainCommand; import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import org.bukkit.command.*; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.command.ProxiedCommandSender; +import org.bukkit.command.RemoteConsoleCommandSender; +import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import java.util.ArrayList; @@ -42,12 +48,12 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { if (args.length == 0) { return Collections.singletonList("plots"); } - Collection objects = MainCommand.getInstance().tab(player, args, s.endsWith(" ")); + Collection objects = MainCommand.getInstance().tab(player, args, s.endsWith(" ")); if (objects == null) { return null; } List result = new ArrayList<>(); - for (Object o : objects) { + for (com.github.intellectualsites.plotsquared.commands.Command o : objects) { result.add(o.toString()); } return result.isEmpty() ? null : result; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java index 744d9084f..25ca0e16e 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java @@ -30,9 +30,9 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.List; import java.util.UUID; @@ -41,91 +41,93 @@ import java.util.UUID; */ public final class BukkitEventUtil extends EventUtil { - @Nullable public Player getPlayer(final PlotPlayer player) { - if (player instanceof BukkitPlayer) { - return ((BukkitPlayer) player).player; + @Nullable public Player getPlayer(final PlotPlayer player) { + if (player instanceof BukkitPlayer) { + return ((BukkitPlayer) player).player; + } + return null; } - return null; - } - private boolean callEvent(@Nonnull final Event event) { - Bukkit.getServer().getPluginManager().callEvent(event); - return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled(); - } - - @Override public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) { - return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto)); - } - - @Override public boolean callTeleport(PlotPlayer player, Location from, Plot plot) { - return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot)); - } - - @Override public boolean callComponentSet(Plot plot, String component) { - return callEvent(new PlotComponentSetEvent(plot, component)); - } - - @Override public boolean callClear(Plot plot) { - return callEvent(new PlotClearEvent(plot)); - } - - @Override public boolean callDelete(Plot plot) { - return callEvent(new PlotDeleteEvent(plot)); - } - - @Override public boolean callFlagAdd(Flag flag, Plot plot) { - return callEvent(new PlotFlagAddEvent(flag, plot)); - } - - @Override public boolean callFlagRemove(Flag flag, Plot plot, Object value) { - return callEvent(new PlotFlagRemoveEvent(flag, plot)); - } - - @Override public boolean callMerge(Plot plot, int dir, int max) { - return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, dir, max)); - } - - @Override public boolean callAutoMerge(Plot plot, List plots) { - return callEvent(new PlotAutoMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, plots)); - } - - @Override public boolean callUnlink(PlotArea area, List plots) { - return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots)); - } - - @Override public void callEntry(PlotPlayer player, Plot plot) { - callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot)); - } - - @Override public void callLeave(PlotPlayer player, Plot plot) { - callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot)); - } - - @Override public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) { - callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added)); - } - - @Override public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) { - callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added)); - } - - @Override public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) { - callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added)); - } - - @Override - public boolean callOwnerChange(PlotPlayer initiator, Plot plot, UUID oldOwner, UUID newOwner, - boolean hasOldOwner) { - return callEvent( - new PlotChangeOwnerEvent(getPlayer(initiator), plot, oldOwner, newOwner, hasOldOwner)); - } - - @Override @Nullable public Rating callRating(PlotPlayer player, Plot plot, Rating rating) { - PlotRateEvent event = new PlotRateEvent(player, rating, plot); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return null; + private boolean callEvent(@NotNull final Event event) { + Bukkit.getServer().getPluginManager().callEvent(event); + return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled(); + } + + @Override public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) { + return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto)); + } + + @Override public boolean callTeleport(PlotPlayer player, Location from, Plot plot) { + return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot)); + } + + @Override public boolean callComponentSet(Plot plot, String component) { + return callEvent(new PlotComponentSetEvent(plot, component)); + } + + @Override public boolean callClear(Plot plot) { + return callEvent(new PlotClearEvent(plot)); + } + + @Override public boolean callDelete(Plot plot) { + return callEvent(new PlotDeleteEvent(plot)); + } + + @Override public boolean callFlagAdd(Flag flag, Plot plot) { + return callEvent(new PlotFlagAddEvent(flag, plot)); + } + + @Override public boolean callFlagRemove(Flag flag, Plot plot, Object value) { + return callEvent(new PlotFlagRemoveEvent(flag, plot)); + } + + @Override public boolean callMerge(Plot plot, int dir, int max) { + return callEvent( + new PlotMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, dir, max)); + } + + @Override public boolean callAutoMerge(Plot plot, List plots) { + return callEvent( + new PlotAutoMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, plots)); + } + + @Override public boolean callUnlink(PlotArea area, List plots) { + return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots)); + } + + @Override public void callEntry(PlotPlayer player, Plot plot) { + callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot)); + } + + @Override public void callLeave(PlotPlayer player, Plot plot) { + callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot)); + } + + @Override public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) { + callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added)); + } + + @Override public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) { + callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added)); + } + + @Override public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) { + callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added)); + } + + @Override + public boolean callOwnerChange(PlotPlayer initiator, Plot plot, UUID oldOwner, UUID newOwner, + boolean hasOldOwner) { + return callEvent( + new PlotChangeOwnerEvent(getPlayer(initiator), plot, oldOwner, newOwner, hasOldOwner)); + } + + @Override @Nullable public Rating callRating(PlotPlayer player, Plot plot, Rating rating) { + PlotRateEvent event = new PlotRateEvent(player, rating, plot); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return null; + } + return event.getRating(); } - return event.getRating(); - } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java index fb0d20fbc..c13a656f8 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java @@ -1,312 +1,8 @@ package com.github.intellectualsites.plotsquared.bukkit.util; -import com.github.intellectualsites.plotsquared.bukkit.generator.BukkitPlotGenerator; -import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; -import com.github.intellectualsites.plotsquared.plot.util.MainUtil; -import com.github.intellectualsites.plotsquared.plot.util.MathMan; -import com.github.intellectualsites.plotsquared.plot.util.TaskManager; -import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; -import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; -import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis; -import com.sk89q.worldedit.world.block.BaseBlock; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Directional; -import org.bukkit.generator.ChunkGenerator; - -import java.util.HashSet; public class BukkitHybridUtils extends HybridUtils { - @Override public void analyzeRegion(final String world, final RegionWrapper region, - final RunnableVal whenDone) { - // int diff, int variety, int vertices, int rotation, int height_sd - /* - * diff: compare to base by looping through all blocks - * variety: add to HashSet for each PlotBlock - * height_sd: loop over all blocks and get top block - * - * vertices: store air map and compare with neighbours - * for each block check the adjacent - * - Store all blocks then go through in second loop - * - recheck each block - * - */ - TaskManager.runTaskAsync(() -> { - final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false); - final World worldObj = Bukkit.getWorld(world); - final ChunkGenerator chunkGenerator = worldObj.getGenerator(); - if (!(chunkGenerator instanceof BukkitPlotGenerator)) { - return; - } - final Location bot = new Location(world, region.minX, region.minY, region.minZ); - final Location top = new Location(world, region.maxX, region.maxY, region.maxZ); - - final int bx = bot.getX(); - final int bz = bot.getZ(); - final int tx = top.getX(); - final int tz = top.getZ(); - final int cbx = bx >> 4; - final int cbz = bz >> 4; - final int ctx = tx >> 4; - final int ctz = tz >> 4; - MainUtil.initCache(); - final int width = tx - bx + 1; - final int length = tz - bz + 1; - - System.gc(); - System.gc(); - final BlockBucket[][][] oldBlocks = new BlockBucket[256][width][length]; - final PlotBlock[][][] newBlocks = new PlotBlock[256][width][length]; - final BlockBucket airBucket = BlockBucket.withSingle(StringPlotBlock.EVERYTHING); - - PlotArea area = PlotSquared.get().getPlotArea(world, null); - - if (!(area instanceof HybridPlotWorld)) { - return; - } - - HybridPlotWorld hpw = (HybridPlotWorld) area; - final BlockBucket[][] result = hpw.getBlockBucketChunk(); - - if (result == null) { - return; - } - - if (hpw.PLOT_SCHEMATIC) { - short[] rx = new short[16]; - short[] rz = new short[16]; - short rbx; - short rbz; - if (bx < 0) { - rbx = (short) (hpw.SIZE + (bx % hpw.SIZE)); - } else { - rbx = (short) (bx % hpw.SIZE); - } - if (bz < 0) { - rbz = (short) (hpw.SIZE + (bz % hpw.SIZE)); - } else { - rbz = (short) (bz % hpw.SIZE); - } - for (short i = 0; i < 16; i++) { - short v = (short) (rbx + i); - if (v >= hpw.SIZE) { - v -= hpw.SIZE; - } - rx[i] = v; - } - for (short i = 0; i < 16; i++) { - short v = (short) (rbz + i); - if (v >= hpw.SIZE) { - v -= hpw.SIZE; - } - rz[i] = v; - } - int minY; - if (Settings.Schematics.PASTE_ON_TOP) { - minY = hpw.SCHEM_Y; - } else { - minY = 1; - } - for (short x = 0; x < 16; x++) { - for (short z = 0; z < 16; z++) { - BaseBlock[] blocks = hpw.G_SCH.get(MathMan.pair(rx[x], rz[z])); - for (int y = 0; y < blocks.length; y++) { - if (blocks[y] != null) { - result[(minY + y) >> 4][(((minY + y) & 0xF) << 8) | (z << 4) | x] = - BlockBucket.withSingle(PlotBlock.get(blocks[y])); - } - } - } - } - } - - final Runnable run = () -> ChunkManager.chunkTask(bot, top, new RunnableVal() { - @Override public void run(int[] value) { - // [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge] - int X = value[0]; - int Z = value[1]; - int xb = (X << 4) - bx; - int zb = (Z << 4) - bz; - for (int i = 0; i < result.length; i++) { - if (result[i] == null) { - for (int j = 0; j < 4096; j++) { - int x = MainUtil.x_loc[i][j] + xb; - if (x < 0 || x >= width) { - continue; - } - int z = MainUtil.z_loc[i][j] + zb; - if (z < 0 || z >= length) { - continue; - } - int y = MainUtil.y_loc[i][j]; - oldBlocks[y][x][z] = airBucket; - } - continue; - } - for (int j = 0; j < result[i].length; j++) { - int x = MainUtil.x_loc[i][j] + xb; - if (x < 0 || x >= width) { - continue; - } - int z = MainUtil.z_loc[i][j] + zb; - if (z < 0 || z >= length) { - continue; - } - int y = MainUtil.y_loc[i][j]; - oldBlocks[y][x][z] = result[i][j] != null ? result[i][j] : airBucket; - } - } - - } - }, () -> TaskManager.runTaskAsync(() -> { - int size = width * length; - int[] changes = new int[size]; - int[] faces = new int[size]; - int[] data = new int[size]; - int[] air = new int[size]; - int[] variety = new int[size]; - int i = 0; - for (int x = 0; x < width; x++) { - for (int z = 0; z < length; z++) { - HashSet types = new HashSet<>(); - for (int y = 0; y < 256; y++) { - BlockBucket old = oldBlocks[y][x][z]; - try { - if (old == null) { - old = airBucket; - } - PlotBlock now = newBlocks[y][x][z]; - if (!old.getBlocks().contains(now)) { - changes[i]++; - } - if (now.isAir()) { - air[i]++; - } else { - // check vertices - // modifications_adjacent - if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 - && y < 255) { - if (newBlocks[y - 1][x][z].isAir()) { - faces[i]++; - } - if (newBlocks[y][x - 1][z].isAir()) { - faces[i]++; - } - if (newBlocks[y][x][z - 1].isAir()) { - faces[i]++; - } - if (newBlocks[y + 1][x][z].isAir()) { - faces[i]++; - } - if (newBlocks[y][x + 1][z].isAir()) { - faces[i]++; - } - if (newBlocks[y][x][z + 1].isAir()) { - faces[i]++; - } - } - - Material material = now.to(Material.class); - if (material != null) { - BlockData blockData = material.createBlockData(); - if (blockData instanceof Directional) { - data[i] += 8; - } else if (!blockData.getClass().equals(BlockData.class)) { - data[i]++; - } - } - types.add(now); - } - } catch (NullPointerException e) { - e.printStackTrace(); - } - } - variety[i] = types.size(); - i++; - } - } - // analyze plot - // put in analysis obj - - // run whenDone - PlotAnalysis analysis = new PlotAnalysis(); - analysis.changes = (int) (MathMan.getMean(changes) * 100); - analysis.faces = (int) (MathMan.getMean(faces) * 100); - analysis.data = (int) (MathMan.getMean(data) * 100); - analysis.air = (int) (MathMan.getMean(air) * 100); - analysis.variety = (int) (MathMan.getMean(variety) * 100); - - analysis.changes_sd = (int) (MathMan.getSD(changes, analysis.changes) * 100); - analysis.faces_sd = (int) (MathMan.getSD(faces, analysis.faces) * 100); - analysis.data_sd = (int) (MathMan.getSD(data, analysis.data) * 100); - analysis.air_sd = (int) (MathMan.getSD(air, analysis.air) * 100); - analysis.variety_sd = (int) (MathMan.getSD(variety, analysis.variety) * 100); - System.gc(); - System.gc(); - whenDone.value = analysis; - whenDone.run(); - }), 5); - System.gc(); - MainUtil.initCache(); - ChunkManager.chunkTask(bot, top, new RunnableVal() { - @Override public void run(int[] value) { - int X = value[0]; - int Z = value[1]; - worldObj.loadChunk(X, Z); - int minX; - if (X == cbx) { - minX = bx & 15; - } else { - minX = 0; - } - int minZ; - if (Z == cbz) { - minZ = bz & 15; - } else { - minZ = 0; - } - int maxX; - if (X == ctx) { - maxX = tx & 15; - } else { - maxX = 16; - } - int maxZ; - if (Z == ctz) { - maxZ = tz & 15; - } else { - maxZ = 16; - } - - int cbx = X << 4; - int cbz = Z << 4; - - int xb = cbx - bx; - int zb = cbz - bz; - for (int x = minX; x <= maxX; x++) { - int xx = cbx + x; - for (int z = minZ; z <= maxZ; z++) { - int zz = cbz + z; - for (int y = 0; y < 256; y++) { - PlotBlock block = queue.getBlock(xx, y, zz); - int xr = xb + x; - int zr = zb + z; - newBlocks[y][xr][zr] = block; - } - } - } - worldObj.unloadChunkRequest(X, Z); - } - }, () -> TaskManager.runTaskAsync(run), 5); - }); - } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java index 2c66f8d3f..7f0a3119f 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java @@ -5,6 +5,7 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotInventory; import com.github.intellectualsites.plotsquared.plot.object.PlotItemStack; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.util.InventoryUtil; +import com.sk89q.worldedit.bukkit.BukkitAdapter; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; @@ -21,104 +22,105 @@ import java.util.stream.IntStream; public class BukkitInventoryUtil extends InventoryUtil { - @Override public void open(PlotInventory inv) { - BukkitPlayer bp = (BukkitPlayer) inv.player; - Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle()); - PlotItemStack[] items = inv.getItems(); - for (int i = 0; i < inv.size * 9; i++) { - PlotItemStack item = items[i]; - if (item != null) { - inventory.setItem(i, getItem(item)); - } + @Override public void open(PlotInventory inv) { + BukkitPlayer bp = (BukkitPlayer) inv.player; + Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle()); + PlotItemStack[] items = inv.getItems(); + for (int i = 0; i < inv.size * 9; i++) { + PlotItemStack item = items[i]; + if (item != null) { + inventory.setItem(i, getItem(item)); + } + } + bp.player.openInventory(inventory); } - bp.player.openInventory(inventory); - } - @Override public void close(PlotInventory inv) { - if (!inv.isOpen()) { - return; + @Override public void close(PlotInventory inv) { + if (!inv.isOpen()) { + return; + } + BukkitPlayer bp = (BukkitPlayer) inv.player; + bp.player.closeInventory(); } - BukkitPlayer bp = (BukkitPlayer) inv.player; - bp.player.closeInventory(); - } - @Override public void setItem(PlotInventory inv, int index, PlotItemStack item) { - BukkitPlayer bp = (BukkitPlayer) inv.player; - InventoryView opened = bp.player.getOpenInventory(); - if (!inv.isOpen()) { - return; + @Override public void setItem(PlotInventory inv, int index, PlotItemStack item) { + BukkitPlayer bp = (BukkitPlayer) inv.player; + InventoryView opened = bp.player.getOpenInventory(); + if (!inv.isOpen()) { + return; + } + opened.setItem(index, getItem(item)); + bp.player.updateInventory(); } - opened.setItem(index, getItem(item)); - bp.player.updateInventory(); - } - private static ItemStack getItem(PlotItemStack item) { - if (item == null) { - return null; + private static ItemStack getItem(PlotItemStack item) { + if (item == null) { + return null; + } + ItemStack stack = new ItemStack(BukkitAdapter.adapt(item.getType()), item.amount); + ItemMeta meta = null; + if (item.name != null) { + meta = stack.getItemMeta(); + meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', item.name)); + } + if (item.lore != null) { + if (meta == null) { + meta = stack.getItemMeta(); + } + List lore = new ArrayList<>(); + for (String entry : item.lore) { + lore.add(ChatColor.translateAlternateColorCodes('&', entry)); + } + meta.setLore(lore); + } + if (meta != null) { + stack.setItemMeta(meta); + } + return stack; } - ItemStack stack = new ItemStack(BukkitUtil.getMaterial(item.getPlotBlock()), item.amount); - ItemMeta meta = null; - if (item.name != null) { - meta = stack.getItemMeta(); - meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', item.name)); - } - if (item.lore != null) { - if (meta == null) { - meta = stack.getItemMeta(); - } - List lore = new ArrayList<>(); - for (String entry : item.lore) { - lore.add(ChatColor.translateAlternateColorCodes('&', entry)); - } - meta.setLore(lore); - } - if (meta != null) { - stack.setItemMeta(meta); - } - return stack; - } - public PlotItemStack getItem(ItemStack item) { - if (item == null) { - return null; + public PlotItemStack getItem(ItemStack item) { + if (item == null) { + return null; + } + // int id = item.getTypeId(); + Material id = item.getType(); + ItemMeta meta = item.getItemMeta(); + int amount = item.getAmount(); + String name = null; + String[] lore = null; + if (item.hasItemMeta()) { + assert meta != null; + if (meta.hasDisplayName()) { + name = meta.getDisplayName(); + } + if (meta.hasLore()) { + List itemLore = meta.getLore(); + assert itemLore != null; + lore = itemLore.toArray(new String[0]); + } + } + return new PlotItemStack(id.name(), amount, name, lore); } - // int id = item.getTypeId(); - Material id = item.getType(); - ItemMeta meta = item.getItemMeta(); - int amount = item.getAmount(); - String name = null; - String[] lore = null; - if (item.hasItemMeta()) { - assert meta != null; - if (meta.hasDisplayName()) { - name = meta.getDisplayName(); - } - if (meta.hasLore()) { - List itemLore = meta.getLore(); - lore = itemLore.toArray(new String[0]); - } - } - return new PlotItemStack(id.name(), amount, name, lore); - } - @Override public PlotItemStack[] getItems(PlotPlayer player) { - BukkitPlayer bp = (BukkitPlayer) player; - PlayerInventory inv = bp.player.getInventory(); - return IntStream.range(0, 36).mapToObj(i -> getItem(inv.getItem(i))) - .toArray(PlotItemStack[]::new); - } + @Override public PlotItemStack[] getItems(PlotPlayer player) { + BukkitPlayer bp = (BukkitPlayer) player; + PlayerInventory inv = bp.player.getInventory(); + return IntStream.range(0, 36).mapToObj(i -> getItem(inv.getItem(i))) + .toArray(PlotItemStack[]::new); + } - @Override public boolean isOpen(PlotInventory plotInventory) { - if (!plotInventory.isOpen()) { - return false; + @Override public boolean isOpen(PlotInventory plotInventory) { + if (!plotInventory.isOpen()) { + return false; + } + BukkitPlayer bp = (BukkitPlayer) plotInventory.player; + InventoryView opened = bp.player.getOpenInventory(); + if (plotInventory.isOpen()) { + if (opened.getType() == InventoryType.CRAFTING) { + opened.getTitle(); + } + } + return false; } - BukkitPlayer bp = (BukkitPlayer) plotInventory.player; - InventoryView opened = bp.player.getOpenInventory(); - if (plotInventory.isOpen()) { - if (opened.getType() == InventoryType.CRAFTING) { - opened.getTitle(); - } - } - return false; - } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitLegacyMappings.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitLegacyMappings.java deleted file mode 100644 index 061712d02..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitLegacyMappings.java +++ /dev/null @@ -1,856 +0,0 @@ -package com.github.intellectualsites.plotsquared.bukkit.util; - -import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.LegacyPlotBlock; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; -import com.github.intellectualsites.plotsquared.plot.object.StringPlotBlock; -import com.github.intellectualsites.plotsquared.plot.util.LegacyMappings; -import com.github.intellectualsites.plotsquared.plot.util.StringComparison; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.stream.Collectors; -import lombok.AccessLevel; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; -import lombok.ToString; -import org.bukkit.Bukkit; -import org.bukkit.Material; - -/** - * Borrowed from https://github.com/Phoenix616/IDConverter/blob/master/mappings/src/main/java/de/themoep/idconverter/IdMappings.java - * Original License: - *

- * Minecraft ID mappings Copyright (C) 2017 Max Lee (https://github.com/Phoenix616) - *

- * 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 . - */ -public final class BukkitLegacyMappings extends LegacyMappings { - - private static final LegacyBlock[] BLOCKS = - new LegacyBlock[] {new LegacyBlock(0, "air"), new LegacyBlock(1, "stone"), - new LegacyBlock(1, 1, "stone", "granite"), - new LegacyBlock(1, 2, "stone", "polished_granite"), - new LegacyBlock(1, 3, "stone", "diorite"), - new LegacyBlock(1, 4, "stone", "polished_diorite"), - new LegacyBlock(1, 5, "stone", "andesite"), - new LegacyBlock(1, 6, "stone", "polished_andesite"), - new LegacyBlock(2, "grass", "grass_block"), new LegacyBlock(3, "dirt"), - new LegacyBlock(3, 1, "dirt", "coarse_dirt"), new LegacyBlock(3, 2, "dirt", "podzol"), - new LegacyBlock(4, "cobblestone"), new LegacyBlock(5, "wood", "oak_planks"), - new LegacyBlock(5, 1, "wood", "spruce_planks"), - new LegacyBlock(5, 2, "wood", "birch_planks"), - new LegacyBlock(5, 3, "wood", "jungle_planks"), - new LegacyBlock(5, 4, "wood", "acacia_planks"), - new LegacyBlock(5, 5, "wood", "dark_oak_planks"), - new LegacyBlock(6, "sapling", "oak_sapling"), - new LegacyBlock(6, 1, "sapling", "spruce_sapling"), - new LegacyBlock(6, 2, "sapling", "birch_sapling"), - new LegacyBlock(6, 3, "sapling", "jungle_sapling"), - new LegacyBlock(6, 4, "sapling", "acacia_sapling"), - new LegacyBlock(6, 5, "sapling", "dark_oak_sapling"), new LegacyBlock(7, "bedrock"), - new LegacyBlock(8, "water", "flowing_water"), - new LegacyBlock(9, "stationary_water", "water"), - new LegacyBlock(10, "lava", "flowing_lava"), - new LegacyBlock(11, "stationary_lava", "lava"), new LegacyBlock(12, "sand"), - new LegacyBlock(12, 1, "sand", "red_sand"), new LegacyBlock(13, "gravel"), - new LegacyBlock(14, "gold_ore"), new LegacyBlock(15, "iron_ore"), - new LegacyBlock(16, "coal_ore"), new LegacyBlock(17, "log", "oak_log"), - new LegacyBlock(17, 1, "log", "oak_log"), new LegacyBlock(17, 2, "log", "spruce_log"), - new LegacyBlock(17, 3, "log", "birch_log"), new LegacyBlock(17, 4, "log", "jungle_log"), - new LegacyBlock(17, 5, "log", "oak_bark"), new LegacyBlock(17, 6, "log", "spruce_bark"), - new LegacyBlock(17, 7, "log", "birch_bark"), - new LegacyBlock(17, 8, "log", "jungle_bark"), - new LegacyBlock(18, "leaves", "oak_leaves"), - new LegacyBlock(18, 1, "leaves", "spruce_leaves"), - new LegacyBlock(18, 2, "leaves", "birch_leaves"), - new LegacyBlock(18, 3, "leaves", "jungle_leaves"), new LegacyBlock(19, "sponge"), - new LegacyBlock(19, 1, "sponge", "wet_sponge"), new LegacyBlock(20, "glass"), - new LegacyBlock(21, "lapis_ore"), new LegacyBlock(22, "lapis_block"), - new LegacyBlock(23, "dispenser"), new LegacyBlock(24, "sandstone"), - new LegacyBlock(24, 1, "sandstone", "chiseled_sandstone"), - new LegacyBlock(24, 2, "sandstone", "cut_sandstone"), new LegacyBlock(25, "note_block"), - new LegacyBlock(26, "bed_block"), new LegacyBlock(27, "powered_rail"), - new LegacyBlock(28, "detector_rail"), - new LegacyBlock(29, "piston_sticky_base", "sticky_piston"), - new LegacyBlock(30, "web", "cobweb"), new LegacyBlock(31, "long_grass", "dead_bush"), - new LegacyBlock(31, 1, "long_grass", "grass"), - new LegacyBlock(31, 2, "long_grass", "fern"), new LegacyBlock(32, "dead_bush"), - new LegacyBlock(33, "piston_base", "piston"), - new LegacyBlock(34, "piston_extension", "piston_head"), - new LegacyBlock(35, "wool", "white_wool"), - new LegacyBlock(35, 1, "wool", "orange_wool"), - new LegacyBlock(35, 2, "wool", "magenta_wool"), - new LegacyBlock(35, 3, "wool", "light_blue_wool"), - new LegacyBlock(35, 4, "wool", "yellow_wool"), - new LegacyBlock(35, 5, "wool", "lime_wool"), - new LegacyBlock(35, 6, "wool", "pink_wool"), - new LegacyBlock(35, 7, "wool", "gray_wool"), - new LegacyBlock(35, 8, "wool", "light_gray_wool"), - new LegacyBlock(35, 9, "wool", "cyan_wool"), - new LegacyBlock(35, 10, "wool", "purple_wool"), - new LegacyBlock(35, 11, "wool", "blue_wool"), - new LegacyBlock(35, 12, "wool", "brown_wool"), - new LegacyBlock(35, 13, "wool", "green_wool"), - new LegacyBlock(35, 14, "wool", "red_wool"), - new LegacyBlock(35, 15, "wool", "black_wool"), - new LegacyBlock(36, "piston_moving_piece", "moving_piston"), - new LegacyBlock(37, "yellow_flower", "dandelion"), - new LegacyBlock(38, "red_rose", "poppy"), - new LegacyBlock(38, 1, "red_rose", "blue_orchid"), - new LegacyBlock(38, 2, "red_rose", "allium"), - new LegacyBlock(38, 3, "red_rose", "azure_bluet"), - new LegacyBlock(38, 4, "red_rose", "red_tulip"), - new LegacyBlock(38, 5, "red_rose", "orange_tulip"), - new LegacyBlock(38, 6, "red_rose", "white_tulip"), - new LegacyBlock(38, 7, "red_rose", "pink_tulip"), - new LegacyBlock(38, 8, "red_rose", "oxeye_daisy"), - new LegacyBlock(39, "brown_mushroom"), new LegacyBlock(40, "red_mushroom"), - new LegacyBlock(41, "gold_block"), new LegacyBlock(42, "iron_block"), - new LegacyBlock(43, "double_step"), - new LegacyBlock(43, 6, "double_step", "smooth_quartz"), - new LegacyBlock(43, 8, "double_step", "smooth_stone"), - new LegacyBlock(43, 9, "double_step", "smooth_sandstone"), - new LegacyBlock(44, "step", "stone_slab"), - new LegacyBlock(44, 1, "step", "sandstone_slab"), - new LegacyBlock(44, 2, "step", "petrified_oak_slab"), - new LegacyBlock(44, 3, "step", "cobblestone_slab"), - new LegacyBlock(44, 4, "step", "brick_slab"), - new LegacyBlock(44, 5, "step", "stone_brick_slab"), - new LegacyBlock(44, 6, "step", "nether_brick_slab"), - new LegacyBlock(44, 7, "step", "quartz_slab"), new LegacyBlock(45, "brick", "bricks"), - new LegacyBlock(46, "tnt"), new LegacyBlock(47, "bookshelf"), - new LegacyBlock(48, "mossy_cobblestone"), new LegacyBlock(49, "obsidian"), - new LegacyBlock(50, "torch"), new LegacyBlock(50, 1, "torch", "wall_torch"), - new LegacyBlock(50, 2, "torch", "wall_torch"), - new LegacyBlock(50, 3, "torch", "wall_torch"), - new LegacyBlock(50, 4, "torch", "wall_torch"), new LegacyBlock(50, 5, "torch"), - new LegacyBlock(51, "fire"), new LegacyBlock(52, "mob_spawner"), - new LegacyBlock(53, "wood_stairs", "oak_stairs"), new LegacyBlock(54, "chest", "chest"), - new LegacyBlock(55, "redstone_wire"), new LegacyBlock(56, "diamond_ore"), - new LegacyBlock(57, "diamond_block"), - new LegacyBlock(58, "workbench", "crafting_table"), - new LegacyBlock(59, "crops", "wheat"), new LegacyBlock(60, "soil", "farmland"), - new LegacyBlock(61, "furnace"), new LegacyBlock(62, "burning_furnace"), - new LegacyBlock(63, "sign_post", "sign"), - new LegacyBlock(64, "wooden_door", "oak_door"), new LegacyBlock(65, "ladder"), - new LegacyBlock(66, "rails", "rail"), new LegacyBlock(67, "cobblestone_stairs"), - new LegacyBlock(68, "wall_sign"), new LegacyBlock(69, "lever"), - new LegacyBlock(70, "stone_plate", "stone_pressure_plate"), - new LegacyBlock(71, "iron_door_block", "iron_door"), - new LegacyBlock(72, "wood_plate", "oak_pressure_plate"), - new LegacyBlock(73, "redstone_ore"), new LegacyBlock(74, "glowing_redstone_ore"), - new LegacyBlock(75, "redstone_torch_off"), - new LegacyBlock(76, "redstone_torch_on", "redstone_torch"), - new LegacyBlock(76, 1, "redstone_torch_on", "redstone_wall_torch"), - new LegacyBlock(76, 2, "redstone_torch_on", "redstone_wall_torch"), - new LegacyBlock(76, 3, "redstone_torch_on", "redstone_wall_torch"), - new LegacyBlock(76, 4, "redstone_torch_on", "redstone_wall_torch"), - new LegacyBlock(76, 5, "redstone_torch_on", "redstone_torch"), - new LegacyBlock(77, "stone_button"), new LegacyBlock(78, "snow"), - new LegacyBlock(79, "ice"), new LegacyBlock(80, "snow_block"), - new LegacyBlock(81, "cactus"), new LegacyBlock(82, "clay"), - new LegacyBlock(83, "sugar_cane_block", "sugar_cane"), new LegacyBlock(84, "jukebox"), - new LegacyBlock(85, "fence", "oak_fence"), - new LegacyBlock(86, "pumpkin", "carved_pumpkin"), new LegacyBlock(87, "netherrack"), - new LegacyBlock(88, "soul_sand"), new LegacyBlock(89, "glowstone"), - new LegacyBlock(90, "portal"), new LegacyBlock(91, "jack_o_lantern"), - new LegacyBlock(92, "cake_block", "cake"), new LegacyBlock(93, "diode_block_off"), - new LegacyBlock(94, "diode_block_on", "repeater"), - new LegacyBlock(95, "stained_glass", "white_stained_glass"), - new LegacyBlock(95, 1, "stained_glass", "orange_stained_glass"), - new LegacyBlock(95, 2, "stained_glass", "magenta_stained_glass"), - new LegacyBlock(95, 3, "stained_glass", "light_blue_stained_glass"), - new LegacyBlock(95, 4, "stained_glass", "yellow_stained_glass"), - new LegacyBlock(95, 5, "stained_glass", "lime_stained_glass"), - new LegacyBlock(95, 6, "stained_glass", "pink_stained_glass"), - new LegacyBlock(95, 7, "stained_glass", "gray_stained_glass"), - new LegacyBlock(95, 8, "stained_glass", "light_gray_stained_glass"), - new LegacyBlock(95, 9, "stained_glass", "cyan_stained_glass"), - new LegacyBlock(95, 10, "stained_glass", "purple_stained_glass"), - new LegacyBlock(95, 11, "stained_glass", "blue_stained_glass"), - new LegacyBlock(95, 12, "stained_glass", "brown_stained_glass"), - new LegacyBlock(95, 13, "stained_glass", "green_stained_glass"), - new LegacyBlock(95, 14, "stained_glass", "red_stained_glass"), - new LegacyBlock(95, 15, "stained_glass", "black_stained_glass"), - new LegacyBlock(96, "trap_door", "oak_trapdoor"), - new LegacyBlock(97, "monster_eggs", "infested_stone"), - new LegacyBlock(97, 1, "monster_eggs", "infested_cobblestone"), - new LegacyBlock(97, 2, "monster_eggs", "infested_stone_bricks"), - new LegacyBlock(97, 3, "monster_eggs", "infested_mossy_stone_bricks"), - new LegacyBlock(97, 4, "monster_eggs", "infested_cracked_stone_bricks"), - new LegacyBlock(97, 5, "monster_eggs", "infested_chiseled_stone_bricks"), - new LegacyBlock(98, "smooth_brick", "stone_bricks"), - new LegacyBlock(98, 1, "smooth_brick", "mossy_stone_bricks"), - new LegacyBlock(98, 2, "smooth_brick", "cracked_stone_bricks"), - new LegacyBlock(98, 3, "smooth_brick", "chiseled_bricks"), - new LegacyBlock(99, "huge_mushroom_1", "brown_mushroom_block"), - new LegacyBlock(99, 1, "huge_mushroom_1"), new LegacyBlock(99, 2, "huge_mushroom_1"), - new LegacyBlock(99, 3, "huge_mushroom_1"), new LegacyBlock(99, 4, "huge_mushroom_1"), - new LegacyBlock(99, 5, "huge_mushroom_1"), new LegacyBlock(99, 6, "huge_mushroom_1"), - new LegacyBlock(99, 7, "huge_mushroom_1"), new LegacyBlock(99, 8, "huge_mushroom_1"), - new LegacyBlock(99, 9, "huge_mushroom_1"), - new LegacyBlock(99, 10, "huge_mushroom_1", "mushroom_stem"), - new LegacyBlock(99, 14, "huge_mushroom_1"), new LegacyBlock(99, 15, "huge_mushroom_1"), - new LegacyBlock(100, "huge_mushroom_2", "red_mushroom_block"), - new LegacyBlock(100, 1, "huge_mushroom_2"), new LegacyBlock(100, 2, "huge_mushroom_2"), - new LegacyBlock(100, 3, "huge_mushroom_2"), new LegacyBlock(100, 4, "huge_mushroom_2"), - new LegacyBlock(100, 5, "huge_mushroom_2"), new LegacyBlock(100, 6, "huge_mushroom_2"), - new LegacyBlock(100, 7, "huge_mushroom_2"), new LegacyBlock(100, 8, "huge_mushroom_2"), - new LegacyBlock(100, 9, "huge_mushroom_2"), - new LegacyBlock(100, 10, "huge_mushroom_2", "mushroom_stem"), - new LegacyBlock(100, 14, "huge_mushroom_2"), - new LegacyBlock(100, 15, "huge_mushroom_2"), - new LegacyBlock(101, "iron_fence", "iron_bars"), - new LegacyBlock(102, "thin_glass", "glass_pane"), new LegacyBlock(103, "melon_block"), - new LegacyBlock(104, "pumpkin_stem"), new LegacyBlock(105, "melon_stem"), - new LegacyBlock(106, "vine"), new LegacyBlock(107, "fence_gate", "oak_fence_gate"), - new LegacyBlock(108, "brick_stairs"), - new LegacyBlock(109, "smooth_stairs", "stone_brick_stairs"), - new LegacyBlock(110, "mycel", "mycelium"), - new LegacyBlock(111, "water_lily", "lily_pad"), - new LegacyBlock(112, "nether_brick", "nether_bricks"), - new LegacyBlock(113, "nether_fence", "nether_brick_fence"), - new LegacyBlock(114, "nether_brick_stairs"), - new LegacyBlock(115, "nether_warts", "nether_wart"), - new LegacyBlock(116, "enchantment_table", "enchanting_table"), - new LegacyBlock(117, "brewing_stand"), new LegacyBlock(118, "cauldron"), - new LegacyBlock(119, "ender_portal", "end_portal"), - new LegacyBlock(120, "ender_portal_frame", "end_portal_frame"), - new LegacyBlock(121, "ender_stone", "end_stone"), new LegacyBlock(122, "dragon_egg"), - new LegacyBlock(123, "redstone_lamp_off"), - new LegacyBlock(124, "redstone_lamp_on", "redstone_lamp"), - new LegacyBlock(125, "wood_double_step"), new LegacyBlock(125, 1, "wood_double_step"), - new LegacyBlock(125, 2, "wood_double_step"), - new LegacyBlock(125, 3, "wood_double_step"), - new LegacyBlock(125, 4, "wood_double_step"), - new LegacyBlock(125, 5, "wood_double_step"), - new LegacyBlock(126, "wood_step", "oak_slab"), - new LegacyBlock(126, 1, "wood_step", "spruce_slab"), - new LegacyBlock(126, 2, "wood_step", "birch_slab"), - new LegacyBlock(126, 3, "wood_step", "jungle_slab"), - new LegacyBlock(126, 4, "wood_step", "acacia_slab"), - new LegacyBlock(126, 5, "wood_step", "dark_oak_slab"), new LegacyBlock(127, "cocoa"), - new LegacyBlock(128, "sandstone_stairs"), new LegacyBlock(129, "emerald_ore"), - new LegacyBlock(130, "ender_chest"), new LegacyBlock(131, "tripwire_hook"), - new LegacyBlock(132, "tripwire"), new LegacyBlock(133, "emerald_block"), - new LegacyBlock(134, "spruce_wood_stairs", "spruce_stairs"), - new LegacyBlock(135, "birch_wood_stairs", "birch_stairs"), - new LegacyBlock(136, "jungle_wood_stairs", "jungle_stairs"), - new LegacyBlock(137, "command", "command_block"), new LegacyBlock(138, "beacon"), - new LegacyBlock(139, "cobble_wall", "cobblestone_wall"), - new LegacyBlock(139, 1, "cobble_wall", "mossy_cobblestone_wall"), - new LegacyBlock(140, "flower_pot"), new LegacyBlock(141, "carrot", "carrots"), - new LegacyBlock(142, "potato", "potatoes"), - new LegacyBlock(143, "wood_button", "oak_button"), - new LegacyBlock(144, "skull", "skeleton_skull"), - new LegacyBlock(144, 1, "skull", "skeleton_wall_skull"), - new LegacyBlock(144, 2, "skull", "skeleton_wall_skull"), - new LegacyBlock(144, 3, "skull", "skeleton_wall_skull"), - new LegacyBlock(144, 4, "skull", "skeleton_wall_skull"), - new LegacyBlock(144, 5, "skull", "skeleton_wall_skull"), new LegacyBlock(145, "anvil"), - new LegacyBlock(145, 1, "anvil", "chipped_anvil"), - new LegacyBlock(145, 2, "anvil", "damaged_anvil"), - new LegacyBlock(146, "trapped_chest"), - new LegacyBlock(147, "gold_plate", "light_weighted_pressure_plate"), - new LegacyBlock(148, "iron_plate", "heavy_weighted_pressure_plate"), - new LegacyBlock(149, "redstone_comparator_off"), - new LegacyBlock(150, "redstone_comparator_on", "comparator"), - new LegacyBlock(151, "daylight_detector"), new LegacyBlock(152, "redstone_block"), - new LegacyBlock(153, "quartz_ore", "nether_quartz_ore"), new LegacyBlock(154, "hopper"), - new LegacyBlock(155, "quartz_block"), new LegacyBlock(156, "quartz_stairs"), - new LegacyBlock(157, "activator_rail"), new LegacyBlock(158, "dropper"), - new LegacyBlock(159, "stained_clay", "white_terracotta"), - new LegacyBlock(159, 1, "stained_clay", "orange_terracotta"), - new LegacyBlock(159, 2, "stained_clay", "magenta_terracotta"), - new LegacyBlock(159, 3, "stained_clay", "light_blue_terracotta"), - new LegacyBlock(159, 4, "stained_clay", "yellow_terracotta"), - new LegacyBlock(159, 5, "stained_clay", "lime_terracotta"), - new LegacyBlock(159, 6, "stained_clay", "pink_terracotta"), - new LegacyBlock(159, 7, "stained_clay", "gray_terracotta"), - new LegacyBlock(159, 8, "stained_clay", "light_gray_terracotta"), - new LegacyBlock(159, 9, "stained_clay", "cyan_terracotta"), - new LegacyBlock(159, 10, "stained_clay", "purple_terracotta"), - new LegacyBlock(159, 11, "stained_clay", "blue_terracotta"), - new LegacyBlock(159, 12, "stained_clay", "brown_terracotta"), - new LegacyBlock(159, 13, "stained_clay", "green_terracotta"), - new LegacyBlock(159, 14, "stained_clay", "red_terracotta"), - new LegacyBlock(159, 15, "stained_clay", "black_terracotta"), - new LegacyBlock(160, "stained_glass_pane", "white_stained_glass_pane"), - new LegacyBlock(160, 1, "stained_glass_pane", "orange_stained_glass_pane"), - new LegacyBlock(160, 2, "stained_glass_pane", "magenta_stained_glass_pane"), - new LegacyBlock(160, 3, "stained_glass_pane", "light_blue_stained_glass_pane"), - new LegacyBlock(160, 4, "stained_glass_pane", "yellow_stained_glass_pane"), - new LegacyBlock(160, 5, "stained_glass_pane", "lime_stained_glass_pane"), - new LegacyBlock(160, 6, "stained_glass_pane", "pink_stained_glass_pane"), - new LegacyBlock(160, 7, "stained_glass_pane", "gray_stained_glass_pane"), - new LegacyBlock(160, 8, "stained_glass_pane", "light_gray_stained_glass_pane"), - new LegacyBlock(160, 9, "stained_glass_pane", "cyan_stained_glass_pane"), - new LegacyBlock(160, 10, "stained_glass_pane", "purple_stained_glass_pane"), - new LegacyBlock(160, 11, "stained_glass_pane", "blue_stained_glass_pane"), - new LegacyBlock(160, 12, "stained_glass_pane", "brown_stained_glass_pane"), - new LegacyBlock(160, 13, "stained_glass_pane", "green_stained_glass_pane"), - new LegacyBlock(160, 14, "stained_glass_pane", "red_stained_glass_pane"), - new LegacyBlock(160, 15, "stained_glass_pane", "black_stained_glass_pane"), - new LegacyBlock(161, "leaves_2", "acacia_leaves"), - new LegacyBlock(161, 1, "leaves_2", "dark_oak_leaves"), - new LegacyBlock(162, "log_2", "acacia_log"), - new LegacyBlock(162, 1, "log_2", "spruce_log"), - new LegacyBlock(162, 2, "log_2", "birch_log"), - new LegacyBlock(162, 3, "log_2", "jungle_log"), - new LegacyBlock(163, "acacia_stairs", "acacia_stairs"), - new LegacyBlock(164, "dark_oak_stairs", "dark_oak_stairs"), - new LegacyBlock(165, "slime_block", "slime_block"), - new LegacyBlock(166, "barrier", "barrier"), - new LegacyBlock(167, "iron_trapdoor", "iron_trapdoor"), - new LegacyBlock(168, "prismarine"), - new LegacyBlock(168, 1, "prismarine", "prismarine_bricks"), - new LegacyBlock(168, 2, "prismarine", "dark_prismarine"), - new LegacyBlock(169, "sea_lantern"), new LegacyBlock(170, "hay_block"), - new LegacyBlock(171, "carpet", "white_carpet"), - new LegacyBlock(171, 1, "carpet", "orange_carpet"), - new LegacyBlock(171, 2, "carpet", "magenta_carpet"), - new LegacyBlock(171, 3, "carpet", "light_blue_carpet"), - new LegacyBlock(171, 4, "carpet", "yellow_carpet"), - new LegacyBlock(171, 5, "carpet", "lime_carpet"), - new LegacyBlock(171, 6, "carpet", "pink_carpet"), - new LegacyBlock(171, 7, "carpet", "gray_carpet"), - new LegacyBlock(171, 8, "carpet", "light_gray_carpet"), - new LegacyBlock(171, 9, "carpet", "cyan_carpet"), - new LegacyBlock(171, 10, "carpet", "purple_carpet"), - new LegacyBlock(171, 11, "carpet", "blue_carpet"), - new LegacyBlock(171, 12, "carpet", "brown_carpet"), - new LegacyBlock(171, 13, "carpet", "green_carpet"), - new LegacyBlock(171, 14, "carpet", "red_carpet"), - new LegacyBlock(171, 15, "carpet", "black_carpet"), - new LegacyBlock(172, "hard_clay", "terracotta"), new LegacyBlock(173, "coal_block"), - new LegacyBlock(174, "packed_ice"), new LegacyBlock(175, "double_plant", "sunflower"), - new LegacyBlock(175, 1, "double_plant", "lilac"), - new LegacyBlock(175, 2, "double_plant", "tall_grass"), - new LegacyBlock(175, 3, "double_plant", "large_fern"), - new LegacyBlock(175, 4, "double_plant", "rose_bush"), - new LegacyBlock(175, 5, "double_plant", "peony"), - new LegacyBlock(176, "standing_banner"), new LegacyBlock(177, "wall_banner"), - new LegacyBlock(178, "daylight_detector_inverted"), - new LegacyBlock(179, "red_sandstone", "red_sandstone"), - new LegacyBlock(179, 1, "red_sandstone", "chiseled_red_sandstone"), - new LegacyBlock(179, 2, "red_sandstone", "cut_red_sandstone"), - new LegacyBlock(180, "red_sandstone_stairs"), - new LegacyBlock(181, "double_stone_slab2"), - new LegacyBlock(181, 8, "double_stone_slab2", "smooth_red_sandstone"), - new LegacyBlock(182, "stone_slab2", "red_sandstone_slab"), - new LegacyBlock(183, "spruce_fence_gate"), new LegacyBlock(184, "birch_fence_gate"), - new LegacyBlock(185, "jungle_fence_gate"), new LegacyBlock(186, "dark_oak_fence_gate"), - new LegacyBlock(187, "acacia_fence_gate"), new LegacyBlock(188, "spruce_fence"), - new LegacyBlock(189, "birch_fence"), new LegacyBlock(190, "jungle_fence"), - new LegacyBlock(191, "dark_oak_fence"), new LegacyBlock(192, "acacia_fence"), - new LegacyBlock(193, "spruce_door"), new LegacyBlock(194, "birch_door"), - new LegacyBlock(195, "jungle_door"), new LegacyBlock(196, "acacia_door"), - new LegacyBlock(197, "dark_oak_door"), new LegacyBlock(198, "end_rod"), - new LegacyBlock(199, "chorus_plant"), new LegacyBlock(200, "chorus_flower"), - new LegacyBlock(201, "purpur_block"), new LegacyBlock(202, "purpur_pillar"), - new LegacyBlock(203, "purpur_stairs"), new LegacyBlock(204, "purpur_double_slab"), - new LegacyBlock(205, "purpur_slab"), - new LegacyBlock(206, "end_bricks", "end_stone_bricks"), - new LegacyBlock(207, "beetroot_block", "beetroots"), new LegacyBlock(208, "grass_path"), - new LegacyBlock(209, "end_gateway"), - new LegacyBlock(210, "command_repeating", "repeating_command_block"), - new LegacyBlock(211, "command_chain", "chain_command_block"), - new LegacyBlock(212, "frosted_ice"), new LegacyBlock(213, "magma", "magma_block"), - new LegacyBlock(214, "nether_wart_block"), - new LegacyBlock(215, "red_nether_brick", "red_nether_bricks"), - new LegacyBlock(216, "bone_block"), new LegacyBlock(217, "structure_void"), - new LegacyBlock(218, "observer"), new LegacyBlock(219, "white_shulker_box"), - new LegacyBlock(220, "orange_shulker_box"), new LegacyBlock(221, "magenta_shulker_box"), - new LegacyBlock(222, "light_blue_shulker_box"), - new LegacyBlock(223, "yellow_shulker_box"), new LegacyBlock(224, "lime_shulker_box"), - new LegacyBlock(225, "pink_shulker_box"), new LegacyBlock(226, "gray_shulker_box"), - new LegacyBlock(227, "silver_shulker_box", "light_gray_shulker_box"), - new LegacyBlock(228, "cyan_shulker_box"), new LegacyBlock(229, "purple_shulker_box"), - new LegacyBlock(230, "blue_shulker_box"), new LegacyBlock(231, "brown_shulker_box"), - new LegacyBlock(232, "green_shulker_box"), new LegacyBlock(233, "red_shulker_box"), - new LegacyBlock(234, "black_shulker_box"), - new LegacyBlock(235, "white_glazed_terracotta"), - new LegacyBlock(236, "orange_glazed_terracotta"), - new LegacyBlock(237, "magenta_glazed_terracotta"), - new LegacyBlock(238, "light_blue_glazed_terracotta"), - new LegacyBlock(239, "yellow_glazed_terracotta"), - new LegacyBlock(240, "lime_glazed_terracotta"), - new LegacyBlock(241, "pink_glazed_terracotta"), - new LegacyBlock(242, "gray_glazed_terracotta"), - new LegacyBlock(243, "silver_glazed_terracotta", "light_gray_glazed_terracotta"), - new LegacyBlock(244, "cyan_glazed_terracotta"), - new LegacyBlock(245, "purple_glazed_terracotta"), - new LegacyBlock(246, "blue_glazed_terracotta"), - new LegacyBlock(247, "brown_glazed_terracotta"), - new LegacyBlock(248, "green_glazed_terracotta"), - new LegacyBlock(249, "red_glazed_terracotta"), - new LegacyBlock(250, "black_glazed_terracotta"), - new LegacyBlock(251, "concrete", "white_concrete"), - new LegacyBlock(251, 1, "concrete", "orange_concrete"), - new LegacyBlock(251, 2, "concrete", "magenta_concrete"), - new LegacyBlock(251, 3, "concrete", "light_blue_concrete"), - new LegacyBlock(251, 4, "concrete", "yellow_concrete"), - new LegacyBlock(251, 5, "concrete", "lime_concrete"), - new LegacyBlock(251, 6, "concrete", "pink_concrete"), - new LegacyBlock(251, 7, "concrete", "gray_concrete"), - new LegacyBlock(251, 8, "concrete", "light_gray_concrete"), - new LegacyBlock(251, 9, "concrete", "cyan_concrete"), - new LegacyBlock(251, 10, "concrete", "purple_concrete"), - new LegacyBlock(251, 11, "concrete", "blue_concrete"), - new LegacyBlock(251, 12, "concrete", "brown_concrete"), - new LegacyBlock(251, 13, "concrete", "green_concrete"), - new LegacyBlock(251, 14, "concrete", "red_concrete"), - new LegacyBlock(251, 15, "concrete", "black_concrete"), - new LegacyBlock(252, "concrete_powder", "white_concrete_powder"), - new LegacyBlock(252, 1, "concrete_powder", "orange_concrete_powder"), - new LegacyBlock(252, 2, "concrete_powder", "magenta_concrete_powder"), - new LegacyBlock(252, 3, "concrete_powder", "light_blue_concrete_powder"), - new LegacyBlock(252, 4, "concrete_powder", "yellow_concrete_powder"), - new LegacyBlock(252, 5, "concrete_powder", "lime_concrete_powder"), - new LegacyBlock(252, 6, "concrete_powder", "pink_concrete_powder"), - new LegacyBlock(252, 7, "concrete_powder", "gray_concrete_powder"), - new LegacyBlock(252, 8, "concrete_powder", "light_gray_concrete_powder"), - new LegacyBlock(252, 9, "concrete_powder", "cyan_concrete_powder"), - new LegacyBlock(252, 10, "concrete_powder", "purple_concrete_powder"), - new LegacyBlock(252, 11, "concrete_powder", "blue_concrete_powder"), - new LegacyBlock(252, 12, "concrete_powder", "brown_concrete_powder"), - new LegacyBlock(252, 13, "concrete_powder", "green_concrete_powder"), - new LegacyBlock(252, 14, "concrete_powder", "red_concrete_powder"), - new LegacyBlock(252, 15, "concrete_powder", "black_concrete_powder"), - new LegacyBlock(255, "structure_block"), - new LegacyBlock(256, "iron_spade", "iron_shovel"), new LegacyBlock(257, "iron_pickaxe"), - new LegacyBlock(258, "iron_axe"), new LegacyBlock(259, "flint_and_steel"), - new LegacyBlock(260, "apple"), new LegacyBlock(261, "bow"), - new LegacyBlock(262, "arrow"), new LegacyBlock(263, "coal"), - new LegacyBlock(263, 1, "coal", "charcoal"), new LegacyBlock(264, "diamond"), - new LegacyBlock(265, "iron_ingot"), new LegacyBlock(266, "gold_ingot"), - new LegacyBlock(267, "iron_sword"), new LegacyBlock(268, "wood_sword", "wooden_sword"), - new LegacyBlock(269, "wood_spade", "wooden_shovel"), - new LegacyBlock(270, "wood_pickaxe", "wooden_pickaxe"), - new LegacyBlock(271, "wood_axe", "wooden_axe"), new LegacyBlock(272, "stone_sword"), - new LegacyBlock(273, "stone_spade", "stone_shovel"), - new LegacyBlock(274, "stone_pickaxe"), new LegacyBlock(275, "stone_axe"), - new LegacyBlock(276, "diamond_sword"), - new LegacyBlock(277, "diamond_spade", "diamond_shovel"), - new LegacyBlock(278, "diamond_pickaxe"), new LegacyBlock(279, "diamond_axe"), - new LegacyBlock(280, "stick"), new LegacyBlock(281, "bowl"), - new LegacyBlock(282, "mushroom_soup", "mushroom_stew"), - new LegacyBlock(283, "gold_sword", "golden_sword"), - new LegacyBlock(284, "gold_spade", "golden_shovel"), - new LegacyBlock(285, "gold_pickaxe", "golden_pickaxe"), - new LegacyBlock(286, "gold_axe", "golden_axe"), new LegacyBlock(287, "string"), - new LegacyBlock(288, "feather"), new LegacyBlock(289, "sulphur", "gunpowder"), - new LegacyBlock(290, "wood_hoe", "wooden_hoe"), new LegacyBlock(291, "stone_hoe"), - new LegacyBlock(292, "iron_hoe"), new LegacyBlock(293, "diamond_hoe"), - new LegacyBlock(294, "gold_hoe", "golden_hoe"), - new LegacyBlock(295, "seeds", "wheat_seeds"), new LegacyBlock(296, "wheat"), - new LegacyBlock(297, "bread"), new LegacyBlock(298, "leather_helmet"), - new LegacyBlock(299, "leather_chestplate"), new LegacyBlock(300, "leather_leggings"), - new LegacyBlock(301, "leather_boots"), new LegacyBlock(302, "chainmail_helmet"), - new LegacyBlock(303, "chainmail_chestplate"), - new LegacyBlock(304, "chainmail_leggings"), new LegacyBlock(305, "chainmail_boots"), - new LegacyBlock(306, "iron_helmet"), new LegacyBlock(307, "iron_chestplate"), - new LegacyBlock(308, "iron_leggings"), new LegacyBlock(309, "iron_boots"), - new LegacyBlock(310, "diamond_helmet"), new LegacyBlock(311, "diamond_chestplate"), - new LegacyBlock(312, "diamond_leggings"), new LegacyBlock(313, "diamond_boots"), - new LegacyBlock(314, "gold_helmet", "golden_helmet"), - new LegacyBlock(315, "gold_chestplate", "golden_chestplate"), - new LegacyBlock(316, "gold_leggings", "golden_leggings"), - new LegacyBlock(317, "gold_boots", "golden_boots"), new LegacyBlock(318, "flint"), - new LegacyBlock(319, "pork", "porkchop"), - new LegacyBlock(320, "grilled_pork", "cooked_porkchop"), - new LegacyBlock(321, "painting"), new LegacyBlock(322, "golden_apple", "golden_apple"), - new LegacyBlock(322, 1, "golden_apple", "enchanted_golden_apple"), - new LegacyBlock(323, "sign"), new LegacyBlock(324, "wood_door", "oak_door"), - new LegacyBlock(325, "bucket"), new LegacyBlock(326, "water_bucket"), - new LegacyBlock(327, "lava_bucket"), new LegacyBlock(328, "minecart"), - new LegacyBlock(329, "saddle"), new LegacyBlock(330, "iron_door"), - new LegacyBlock(331, "redstone"), new LegacyBlock(332, "snow_ball", "snowball"), - new LegacyBlock(333, "boat", "oak_boat"), new LegacyBlock(334, "leather"), - new LegacyBlock(335, "milk_bucket"), new LegacyBlock(336, "clay_brick", "brick"), - new LegacyBlock(337, "clay_ball"), new LegacyBlock(338, "sugar_cane"), - new LegacyBlock(339, "paper"), new LegacyBlock(340, "book"), - new LegacyBlock(341, "slime_ball"), - new LegacyBlock(342, "storage_minecart", "chest_minecart"), - new LegacyBlock(343, "powered_minecart", "furnace_minecart"), - new LegacyBlock(344, "egg"), new LegacyBlock(345, "compass"), - new LegacyBlock(346, "fishing_rod"), new LegacyBlock(347, "watch", "clock"), - new LegacyBlock(348, "glowstone_dust"), new LegacyBlock(349, "raw_fish", "cod"), - new LegacyBlock(349, 1, "raw_fish", "salmon"), - new LegacyBlock(349, 2, "raw_fish", "tropical_fish"), - new LegacyBlock(349, 3, "raw_fish", "pufferfish"), - new LegacyBlock(350, "cooked_fish", "cooked_cod"), - new LegacyBlock(350, 1, "cooked_fish", "cooked_salmon"), - new LegacyBlock(351, "ink_sack", "ink_sac"), - new LegacyBlock(351, 1, "ink_sack", "rose_red"), - new LegacyBlock(351, 2, "ink_sack", "cactus_green"), - new LegacyBlock(351, 3, "ink_sack", "cocoa_beans"), - new LegacyBlock(351, 4, "ink_sack", "lapis_lazuli"), - new LegacyBlock(351, 5, "ink_sack", "purple_dye"), - new LegacyBlock(351, 6, "ink_sack", "cyan_dye"), - new LegacyBlock(351, 7, "ink_sack", "light_gray_dye"), - new LegacyBlock(351, 8, "ink_sack", "gray_dye"), - new LegacyBlock(351, 9, "ink_sack", "pink_dye"), - new LegacyBlock(351, 10, "ink_sack", "lime_dye"), - new LegacyBlock(351, 11, "ink_sack", "dandelion_yellow"), - new LegacyBlock(351, 12, "ink_sack", "light_blue_dye"), - new LegacyBlock(351, 13, "ink_sack", "magenta_dye"), - new LegacyBlock(351, 14, "ink_sack", "orange_dye"), - new LegacyBlock(351, 15, "ink_sack", "bone_meal"), new LegacyBlock(352, "bone"), - new LegacyBlock(353, "sugar", "sugar"), new LegacyBlock(354, "cake", "cake"), - new LegacyBlock(355, "bed", "white_bed"), new LegacyBlock(355, 1, "bed", "orange_bed"), - new LegacyBlock(355, 2, "bed", "magenta_bed"), - new LegacyBlock(355, 3, "bed", "light_blue_bed"), - new LegacyBlock(355, 4, "bed", "yellow_bed"), - new LegacyBlock(355, 5, "bed", "lime_bed"), new LegacyBlock(355, 6, "bed", "pink_bed"), - new LegacyBlock(355, 7, "bed", "gray_bed"), - new LegacyBlock(355, 8, "bed", "light_gray_bed"), - new LegacyBlock(355, 9, "bed", "cyan_bed"), - new LegacyBlock(355, 10, "bed", "purple_bed"), - new LegacyBlock(355, 11, "bed", "blue_bed"), - new LegacyBlock(355, 12, "bed", "brown_bed"), - new LegacyBlock(355, 13, "bed", "green_bed"), - new LegacyBlock(355, 14, "bed", "red_bed"), - new LegacyBlock(355, 15, "bed", "black_bed"), new LegacyBlock(356, "diode", "repeater"), - new LegacyBlock(357, "cookie", "cookie"), new LegacyBlock(358, "map"), - new LegacyBlock(359, "shears"), new LegacyBlock(360, "melon", "melon"), - new LegacyBlock(361, "pumpkin_seeds", "pumpkin_seeds"), - new LegacyBlock(362, "melon_seeds", "melon_seeds"), - new LegacyBlock(363, "raw_beef", "beef"), new LegacyBlock(364, "cooked_beef"), - new LegacyBlock(365, "raw_chicken", "chicken"), new LegacyBlock(366, "cooked_chicken"), - new LegacyBlock(367, "rotten_flesh"), new LegacyBlock(368, "ender_pearl"), - new LegacyBlock(369, "blaze_rod"), new LegacyBlock(370, "ghast_tear"), - new LegacyBlock(371, "gold_nugget"), - new LegacyBlock(372, "nether_stalk", "nether_wart"), - new LegacyBlock(373, "potion", "potion"), new LegacyBlock(374, "glass_bottle"), - new LegacyBlock(375, "spider_eye"), new LegacyBlock(376, "fermented_spider_eye"), - new LegacyBlock(377, "blaze_powder"), new LegacyBlock(378, "magma_cream"), - new LegacyBlock(379, "brewing_stand_item", "brewing_stand"), - new LegacyBlock(380, "cauldron_item", "cauldron"), - new LegacyBlock(381, "eye_of_ender", "ender_eye"), - new LegacyBlock(382, "speckled_melon"), new LegacyBlock(383, "monster_egg"), - new LegacyBlock(383, 4, "monster_egg", "elder_guardian_spawn_egg"), - new LegacyBlock(383, 5, "monster_egg", "wither_skeleton_spawn_egg"), - new LegacyBlock(383, 6, "monster_egg", "stray_spawn_egg"), - new LegacyBlock(383, 23, "monster_egg", "husk_spawn_egg"), - new LegacyBlock(383, 27, "monster_egg", "zombie_villager_spawn_egg"), - new LegacyBlock(383, 28, "monster_egg", "skeleton_horse_spawn_egg"), - new LegacyBlock(383, 29, "monster_egg", "zombie_horse_spawn_egg"), - new LegacyBlock(383, 31, "monster_egg", "donkey_spawn_egg"), - new LegacyBlock(383, 32, "monster_egg", "mule_spawn_egg"), - new LegacyBlock(383, 34, "monster_egg", "evocation_illager_spawn_egg"), - new LegacyBlock(383, 35, "monster_egg", "vex_spawn_egg"), - new LegacyBlock(383, 36, "monster_egg", "vindication_illager_spawn_egg"), - new LegacyBlock(383, 50, "monster_egg", "creeper_spawn_egg"), - new LegacyBlock(383, 51, "monster_egg", "skeleton_spawn_egg"), - new LegacyBlock(383, 52, "monster_egg", "spider_spawn_egg"), - new LegacyBlock(383, 54, "monster_egg", "zombie_spawn_egg"), - new LegacyBlock(383, 55, "monster_egg", "slime_spawn_egg"), - new LegacyBlock(383, 56, "monster_egg", "ghast_spawn_egg"), - new LegacyBlock(383, 57, "monster_egg", "zombie_pigman_spawn_egg"), - new LegacyBlock(383, 58, "monster_egg", "enderman_spawn_egg"), - new LegacyBlock(383, 59, "monster_egg", "cave_spider_spawn_egg"), - new LegacyBlock(383, 60, "monster_egg", "silverfish_spawn_egg"), - new LegacyBlock(383, 61, "monster_egg", "blaze_spawn_egg"), - new LegacyBlock(383, 62, "monster_egg", "magma_cube_spawn_egg"), - new LegacyBlock(383, 65, "monster_egg", "bat_spawn_egg"), - new LegacyBlock(383, 66, "monster_egg", "witch_spawn_egg"), - new LegacyBlock(383, 67, "monster_egg", "endermite_spawn_egg"), - new LegacyBlock(383, 68, "monster_egg", "guardian_spawn_egg"), - new LegacyBlock(383, 69, "monster_egg", "shulker_spawn_egg"), - new LegacyBlock(383, 90, "monster_egg", "pig_spawn_egg"), - new LegacyBlock(383, 91, "monster_egg", "sheep_spawn_egg"), - new LegacyBlock(383, 92, "monster_egg", "cow_spawn_egg"), - new LegacyBlock(383, 93, "monster_egg", "chicken_spawn_egg"), - new LegacyBlock(383, 94, "monster_egg", "squid_spawn_egg"), - new LegacyBlock(383, 95, "monster_egg", "wolf_spawn_egg"), - new LegacyBlock(383, 96, "monster_egg", "mooshroom_spawn_egg"), - new LegacyBlock(383, 98, "monster_egg", "ocelot_spawn_egg"), - new LegacyBlock(383, 100, "monster_egg", "horse_spawn_egg"), - new LegacyBlock(383, 101, "monster_egg", "rabbit_spawn_egg"), - new LegacyBlock(383, 102, "monster_egg", "polar_bear_spawn_egg"), - new LegacyBlock(383, 103, "monster_egg", "llama_spawn_egg"), - new LegacyBlock(383, 120, "monster_egg", "villager_spawn_egg"), - new LegacyBlock(384, "exp_bottle", "experience_bottle"), - new LegacyBlock(385, "fireball", "fire_charge"), - new LegacyBlock(386, "book_and_quill", "writable_book"), - new LegacyBlock(387, "written_book"), new LegacyBlock(388, "emerald"), - new LegacyBlock(389, "item_frame"), - new LegacyBlock(390, "flower_pot_item", "flower_pot"), - new LegacyBlock(391, "carrot_item", "carrot"), - new LegacyBlock(392, "potato_item", "potato"), new LegacyBlock(393, "baked_potato"), - new LegacyBlock(394, "poisonous_potato"), new LegacyBlock(395, "empty_map", "map"), - new LegacyBlock(396, "golden_carrot"), - new LegacyBlock(397, "skull_item", "skeleton_skull"), - new LegacyBlock(397, 1, "skull_item", "wither_skeleton_skull"), - new LegacyBlock(397, 2, "skull_item", "zombie_head"), - new LegacyBlock(397, 3, "skull_item", "player_head"), - new LegacyBlock(397, 4, "skull_item", "creeper_head"), - new LegacyBlock(397, 5, "skull_item", "dragon_head"), - new LegacyBlock(398, "carrot_stick"), new LegacyBlock(399, "nether_star"), - new LegacyBlock(400, "pumpkin_pie"), - new LegacyBlock(401, "firework", "firework_rocket"), - new LegacyBlock(402, "firework_charge", "firework_star"), - new LegacyBlock(403, "enchanted_book"), - new LegacyBlock(404, "redstone_comparator", "comparator"), - new LegacyBlock(405, "nether_brick_item", "nether_brick"), - new LegacyBlock(406, "quartz"), - new LegacyBlock(407, "explosive_minecart", "tnt_minecart"), - new LegacyBlock(408, "hopper_minecart"), new LegacyBlock(409, "prismarine_shard"), - new LegacyBlock(410, "prismarine_crystals"), new LegacyBlock(411, "rabbit"), - new LegacyBlock(412, "cooked_rabbit"), new LegacyBlock(413, "rabbit_stew"), - new LegacyBlock(414, "rabbit_foot"), new LegacyBlock(415, "rabbit_hide"), - new LegacyBlock(416, "armor_stand"), - new LegacyBlock(417, "iron_barding", "iron_horse_armor"), - new LegacyBlock(418, "gold_barding", "gold_horse_armor"), - new LegacyBlock(419, "diamond_barding", "diamond_horse_armor"), - new LegacyBlock(420, "leash", "lead"), new LegacyBlock(421, "name_tag"), - new LegacyBlock(422, "command_minecart", "command_block_minecart"), - new LegacyBlock(423, "mutton"), new LegacyBlock(424, "cooked_mutton"), - new LegacyBlock(425, "banner", "white_banner"), - new LegacyBlock(425, 1, "banner", "orange_banner"), - new LegacyBlock(425, 2, "banner", "magenta_banner"), - new LegacyBlock(425, 3, "banner", "light_blue_banner"), - new LegacyBlock(425, 4, "banner", "yellow_banner"), - new LegacyBlock(425, 5, "banner", "lime_banner"), - new LegacyBlock(425, 6, "banner", "pink_banner"), - new LegacyBlock(425, 7, "banner", "gray_banner"), - new LegacyBlock(425, 8, "banner", "light_gray_banner"), - new LegacyBlock(425, 9, "banner", "cyan_banner"), - new LegacyBlock(425, 10, "banner", "purple_banner"), - new LegacyBlock(425, 11, "banner", "blue_banner"), - new LegacyBlock(425, 12, "banner", "brown_banner"), - new LegacyBlock(425, 13, "banner", "green_banner"), - new LegacyBlock(425, 14, "banner", "red_banner"), - new LegacyBlock(425, 15, "banner", "black_banner"), new LegacyBlock(426, "end_crystal"), - new LegacyBlock(427, "spruce_door_item", "spruce_door"), - new LegacyBlock(428, "birch_door_item", "birch_door"), - new LegacyBlock(429, "jungle_door_item", "jungle_door"), - new LegacyBlock(430, "acacia_door_item", "acacia_door"), - new LegacyBlock(431, "dark_oak_door_item", "dark_oak_door"), - new LegacyBlock(432, "chorus_fruit"), new LegacyBlock(433, "chorus_fruit_popped"), - new LegacyBlock(434, "beetroot"), new LegacyBlock(435, "beetroot_seeds"), - new LegacyBlock(436, "beetroot_soup"), - new LegacyBlock(437, "dragons_breath", "dragon_breath"), - new LegacyBlock(438, "splash_potion"), new LegacyBlock(439, "spectral_arrow"), - new LegacyBlock(440, "tipped_arrow"), new LegacyBlock(441, "lingering_potion"), - new LegacyBlock(442, "shield"), new LegacyBlock(443, "elytra"), - new LegacyBlock(444, "boat_spruce", "spruce_boat"), - new LegacyBlock(445, "boat_birch", "birch_boat"), - new LegacyBlock(446, "boat_jungle", "jungle_boat"), - new LegacyBlock(447, "boat_acacia", "acacia_boat"), - new LegacyBlock(448, "boat_dark_oak", "dark_oak_boat"), - new LegacyBlock(449, "totem", "totem_of_undying"), - new LegacyBlock(450, "shulker_shell"), new LegacyBlock(452, "iron_nugget"), - new LegacyBlock(453, "knowledge_book"), - new LegacyBlock(2256, "gold_record", "music_disc_13"), - new LegacyBlock(2257, "green_record", "music_disc_cat"), - new LegacyBlock(2258, "record_3", "music_disc_blocks"), - new LegacyBlock(2259, "record_4", "music_disc_chirp"), - new LegacyBlock(2260, "record_5", "music_disc_far"), - new LegacyBlock(2261, "record_6", "music_disc_mall"), - new LegacyBlock(2262, "record_7", "music_disc_mellohi"), - new LegacyBlock(2263, "record_8", "music_disc_stal"), - new LegacyBlock(2264, "record_9", "music_disc_strad"), - new LegacyBlock(2265, "record_10", "music_disc_ward"), - new LegacyBlock(2266, "record_11", "music_disc_11"), - new LegacyBlock(2267, "record_12", "music_disc_wait")}; - - private static final Map LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK = - new HashMap<>(); - private static final Map NEW_STRING_TO_LEGACY_PLOT_BLOCK = new HashMap<>(); - private static final Map OLD_STRING_TO_STRING_PLOT_BLOCK = new HashMap<>(); - - @SuppressWarnings("deprecation") public BukkitLegacyMappings() { - this.addAll(Arrays.asList(BLOCKS)); - // Make sure to add new blocks as well - final List missing = new ArrayList<>(); - for (final Material material : Material.values()) { - final String materialName = material.name().toLowerCase(Locale.ENGLISH); - if (NEW_STRING_TO_LEGACY_PLOT_BLOCK.get(materialName) == null) { - try { - final LegacyBlock missingBlock = - new LegacyBlock(material.getId(), materialName, materialName); - missing.add(missingBlock); - } catch (Exception e) { - Bukkit.getLogger().severe( - "Error creating legacy block: " + materialName + ". Possibly a new block."); - } - } - } - addAll(missing); - } - - private void addAll(@NonNull final Collection blocks) { - for (final LegacyBlock legacyBlock : blocks) { - LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK - .put(new IdDataPair(legacyBlock.getNumericalId(), legacyBlock.getDataValue()), - legacyBlock.toStringPlotBlock()); - NEW_STRING_TO_LEGACY_PLOT_BLOCK - .put(legacyBlock.getNewName(), legacyBlock.toLegacyPlotBlock()); - OLD_STRING_TO_STRING_PLOT_BLOCK - .put(legacyBlock.getLegacyName(), legacyBlock.toStringPlotBlock()); - Material material; - try { - material = Material.valueOf(legacyBlock.getNewName()); - } catch (final Exception e) { - try { - material = Material.getMaterial(legacyBlock.getLegacyName(), true); - } catch (NoSuchMethodError error) { - PlotSquared.log( - "You can't use this version of PlotSquared on a server " - + "less than Minecraft 1.13.2"); - Bukkit.shutdown(); - break; - } - } - legacyBlock.material = material; - } - } - - public Collection getPlotBlocks() { - return Arrays.stream(BLOCKS).map(block -> PlotBlock.get(block.getNewName())) - .collect(Collectors.toList()); - } - - public StringComparison.ComparisonResult getClosestsMatch( - @NonNull final String string) { - final StringComparison comparison = - new StringComparison<>(string, getPlotBlocks()); - return comparison.getBestMatchAdvanced(); - } - - /** - * Try to find a legacy plot block by any means possible. Strategy: - Check if the name contains - * a namespace, if so, strip it - Check if there's a (new) material matching the name - Check if - * there's a legacy material matching the name - Check if there's a numerical ID matching the - * name - Return null if everything else fails - * - * @param string String ID - * @return LegacyBlock if found, else null - */ - public PlotBlock fromAny(@NonNull final String string) { - if (string.isEmpty()) { - return StringPlotBlock.EVERYTHING; - } - String workingString = string; - String[] parts = null; - IdDataPair idDataPair = null; - if (string.contains(":")) { - parts = string.split(":"); - if (parts.length > 1) { - if (parts[0].equalsIgnoreCase("minecraft")) { - workingString = parts[1]; - } else { - if (parts[0].matches("^\\d+$")) { - idDataPair = - new IdDataPair(Integer.parseInt(parts[0]), Integer.parseInt(parts[0])); - } else { - workingString = parts[0]; - } - } - } - } else if (string.matches("^\\d+$")) { - idDataPair = new IdDataPair(Integer.parseInt(string), 0); - } - PlotBlock plotBlock; - if (NEW_STRING_TO_LEGACY_PLOT_BLOCK.keySet().contains(workingString.toLowerCase())) { - return PlotBlock.get(workingString); - } else if ((plotBlock = fromLegacyToString(idDataPair)) != null) { - return plotBlock; - } else if ((plotBlock = fromLegacyToString(workingString)) != null) { - return plotBlock; - } else { - try { - if (parts != null && parts.length > 1) { - final int id = Integer.parseInt(parts[0]); - final int data = Integer.parseInt(parts[1]); - return fromLegacyToString(id, data); - } else { - return fromLegacyToString(Integer.parseInt(workingString), 0); - } - } catch (final Throwable exception) { - return null; - } - } - } - - public PlotBlock fromLegacyToString(final int id, final int data) { - return LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK.get(new IdDataPair(id, data)); - } - - public PlotBlock fromLegacyToString(IdDataPair idDataPair) { - if (idDataPair == null) { - return null; - } - return LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK.get(idDataPair); - } - - public PlotBlock fromLegacyToString(final String id) { - return OLD_STRING_TO_STRING_PLOT_BLOCK.get(id); - } - - public PlotBlock fromStringToLegacy(final String id) { - return NEW_STRING_TO_LEGACY_PLOT_BLOCK.get(id.toLowerCase(Locale.ENGLISH)); - } - - @Getter @EqualsAndHashCode @ToString @RequiredArgsConstructor - private static final class IdDataPair { - private final int id; - private final int data; - } - - - @Getter @RequiredArgsConstructor(access = AccessLevel.PRIVATE) - public static final class LegacyBlock { - - private final int numericalId; - private final int dataValue; - private final String legacyName; - private final String newName; - - private Material material; - - LegacyBlock(final int numericalId, final int dataValue, @NonNull final String legacyName) { - this(numericalId, dataValue, legacyName, legacyName); - } - - LegacyBlock(final int numericalId, @NonNull final String legacyName, - @NonNull final String newName) { - this(numericalId, 0, legacyName, newName); - } - - LegacyBlock(final int numericalId, @NonNull final String legacyName) { - this(numericalId, legacyName, legacyName); - } - - PlotBlock toStringPlotBlock() { - return StringPlotBlock.get(newName); - } - - PlotBlock toLegacyPlotBlock() { - return LegacyPlotBlock.get(numericalId, dataValue); - } - - @Override public String toString() { - return this.newName; - } - } - -} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSchematicHandler.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSchematicHandler.java index 76462a11e..4139d2191 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSchematicHandler.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSchematicHandler.java @@ -2,19 +2,31 @@ package com.github.intellectualsites.plotsquared.bukkit.util; import com.github.intellectualsites.plotsquared.bukkit.object.schematic.StateWrapper; import com.github.intellectualsites.plotsquared.plot.object.Location; -import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; -import com.sk89q.jnbt.*; +import com.sk89q.jnbt.ByteArrayTag; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.IntArrayTag; +import com.sk89q.jnbt.IntTag; +import com.sk89q.jnbt.ListTag; +import com.sk89q.jnbt.ShortTag; +import com.sk89q.jnbt.StringTag; +import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.block.BaseBlock; import java.io.ByteArrayOutputStream; -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.stream.IntStream; /** @@ -22,7 +34,7 @@ import java.util.stream.IntStream; */ public class BukkitSchematicHandler extends SchematicHandler { - @Override public void getCompoundTag(final String world, final Set regions, + @Override public void getCompoundTag(final String world, final Set regions, final RunnableVal whenDone) { // async TaskManager.runTaskAsync(new Runnable() { @@ -61,7 +73,7 @@ public class BukkitSchematicHandler extends SchematicHandler { List tileEntities = new ArrayList<>(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(width * height * length); // Queue - final ArrayDeque queue = new ArrayDeque<>(regions); + final ArrayDeque queue = new ArrayDeque<>(regions); TaskManager.runTask(new Runnable() { @Override public void run() { if (queue.isEmpty()) { @@ -82,9 +94,9 @@ public class BukkitSchematicHandler extends SchematicHandler { return; } final Runnable regionTask = this; - RegionWrapper region = queue.poll(); - Location pos1 = new Location(world, region.minX, region.minY, region.minZ); - Location pos2 = new Location(world, region.maxX, region.maxY, region.maxZ); + CuboidRegion region = queue.poll(); + Location pos1 = new Location(world, region.getMinimumPoint().getX(), region.getMinimumPoint().getY(), region.getMinimumPoint().getZ()); + Location pos2 = new Location(world, region.getMaximumPoint().getX(), region.getMaximumPoint().getY(), region.getMaximumPoint().getZ()); final int p1x = pos1.getX(); final int sy = pos1.getY(); final int p1z = pos1.getZ(); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java index 6237f0ba3..59be5f5e7 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java @@ -9,10 +9,13 @@ import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; import com.github.intellectualsites.plotsquared.plot.object.SetupObject; import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; -import com.onarandombox.MultiverseCore.MultiverseCore; -import com.onarandombox.MultiverseCore.api.MultiverseCoreConfig; -import org.bukkit.*; +import io.papermc.lib.PaperLib; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.World; import org.bukkit.World.Environment; +import org.bukkit.WorldCreator; +import org.bukkit.WorldType; import org.bukkit.entity.Player; import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.Plugin; @@ -59,7 +62,7 @@ public class BukkitSetupUtils extends SetupUtils { } World dw = Bukkit.getWorlds().get(0); for (Player player : world.getPlayers()) { - player.teleport(dw.getSpawnLocation()); + PaperLib.teleportAsync(player,dw.getSpawnLocation()); } if (save) { for (Chunk chunk : world.getLoadedChunks()) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitTaskManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitTaskManager.java index 56448ff34..0989ccf1a 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitTaskManager.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitTaskManager.java @@ -24,8 +24,12 @@ public class BukkitTaskManager extends TaskManager { } @Override public void taskAsync(Runnable runnable) { - this.bukkitMain.getServer().getScheduler().runTaskAsynchronously(this.bukkitMain, runnable) - .getTaskId(); + if (this.bukkitMain.isEnabled()) { + this.bukkitMain.getServer().getScheduler() + .runTaskAsynchronously(this.bukkitMain, runnable); + } else { + runnable.run(); + } } @Override public void task(Runnable runnable) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java index 66b509615..23ed71550 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java @@ -3,25 +3,46 @@ package com.github.intellectualsites.plotsquared.bukkit.util; import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.schematic.PlotItem; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.StringComparison; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import com.github.intellectualsites.plotsquared.plot.util.world.BlockUtil; +import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.BukkitWorld; +import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.block.BlockState; import lombok.NonNull; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.World; -import org.bukkit.block.*; +import org.bukkit.block.Biome; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Sign; import org.bukkit.block.data.Directional; +import org.bukkit.block.data.type.WallSign; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; @SuppressWarnings({"unused", "WeakerAccess"}) public class BukkitUtil extends WorldUtil { @@ -200,6 +221,12 @@ import java.util.*; MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ())); } + public static Location getLocationFull(@NonNull final org.bukkit.Location location) { + return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), + MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), + location.getYaw(), location.getPitch()); + } + public static org.bukkit.Location getLocation(@NonNull final Location location) { return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ()); @@ -215,7 +242,11 @@ import java.util.*; public static List getEntities(@NonNull final String worldName) { World world = getWorld(worldName); - return world != null ? world.getEntities() : new ArrayList(); + if (world != null) { + return world.getEntities(); + } else { + return new ArrayList<>(); + } } public static Location getLocation(@NonNull final Entity entity) { @@ -225,30 +256,18 @@ import java.util.*; location.getBlockZ()); } - public static Location getLocationFull(@NonNull final Entity entity) { + @NotNull public static Location getLocationFull(@NonNull final Entity entity) { final org.bukkit.Location location = entity.getLocation(); return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), location.getYaw(), location.getPitch()); } - public static BukkitLegacyMappings getBukkitLegacyMappings() { - return (BukkitLegacyMappings) PlotSquared.imp().getLegacyMappings(); + public static Material getMaterial(@NonNull final BlockState plotBlock) { + return BukkitAdapter.adapt(plotBlock.getBlockType()); } - public static Material getMaterial(@NonNull final PlotBlock plotBlock) { - if (plotBlock instanceof StringPlotBlock) { - return Material - .getMaterial(((StringPlotBlock) plotBlock).getItemId().toUpperCase(Locale.ENGLISH)); - } else { - final LegacyPlotBlock legacyPlotBlock = (LegacyPlotBlock) plotBlock; - return getBukkitLegacyMappings() - .fromLegacyToString(legacyPlotBlock.getId(), legacyPlotBlock.getData()) - .to(Material.class); - } - } - - @Override public boolean isBlockSame(PlotBlock block1, PlotBlock block2) { + @Override public boolean isBlockSame(BlockState block1, BlockState block2) { if (block1.equals(block2)) { return true; } @@ -260,8 +279,8 @@ import java.util.*; return getWorld(worldName) != null; } - @Override public String getBiome(String world, int x, int z) { - return getWorld(world).getBiome(x, z).name(); + @Override public BiomeType getBiome(String world, int x, int z) { + return BukkitAdapter.adapt(getWorld(world).getBiome(x, z)); } @Override public int getHighestBlock(@NonNull final String world, final int x, final int z) { @@ -270,38 +289,32 @@ import java.util.*; int air = 1; for (int y = bukkitWorld.getMaxHeight() - 1; y >= 0; y--) { Block block = bukkitWorld.getBlockAt(x, y, z); - if (block != null) { - Material type = block.getType(); - if (type.isSolid()) { - if (air > 1) { - return y; - } - air = 0; - } else { - if (block.isLiquid()) { - return y; - } - air++; + Material type = block.getType(); + if (type.isSolid()) { + if (air > 1) { + return y; } + air = 0; + } else { + if (block.isLiquid()) { + return y; + } + air++; } } return bukkitWorld.getMaxHeight() - 1; } @Override @Nullable public String[] getSign(@NonNull final Location location) { - Block block = getWorld(location.getWorld()) - .getBlockAt(location.getX(), location.getY(), location.getZ()); - if (block != null) { - if (block.getState() instanceof Sign) { - Sign sign = (Sign) block.getState(); - return sign.getLines(); + Block block = getWorld(location.getWorld()).getBlockAt(location.getX(), location.getY(), location.getZ()); + return TaskManager.IMP.sync(new RunnableVal() { + @Override public void run(String[] value) { + if (block.getState() instanceof Sign) { + Sign sign = (Sign) block.getState(); + this.value = sign.getLines(); + } } - } - return null; - } - - @Override public Location getSpawn(@NonNull final PlotPlayer player) { - return getLocation(((BukkitPlayer) player).player.getBedSpawnLocation()); + }); } @Override public Location getSpawn(@NonNull final String world) { @@ -345,11 +358,15 @@ import java.util.*; } else { block.setType(Material.valueOf("OAK_WALL_SIGN"), false); } + if (!(block.getBlockData() instanceof WallSign)) { + PlotSquared.debug(block.getBlockData().getAsString()); + throw new RuntimeException("Something went wrong generating a sign"); + } final Directional sign = (Directional) block.getBlockData(); sign.setFacing(facing); block.setBlockData(sign, false); } - final BlockState blockstate = block.getState(); + final org.bukkit.block.BlockState blockstate = block.getState(); if (blockstate instanceof Sign) { final Sign sign = (Sign) blockstate; for (int i = 0; i < lines.length; i++) { @@ -359,34 +376,17 @@ import java.util.*; } } - @Override public int getBiomeFromString(@NonNull final String biomeString) { - try { - final Biome biome = Biome.valueOf(biomeString.toUpperCase()); - return Arrays.asList(Biome.values()).indexOf(biome); - } catch (IllegalArgumentException ignored) { - return -1; - } - } - - @Override public String[] getBiomeList() { - final Biome[] biomes = Biome.values(); - return Arrays.stream(biomes).map(Enum::name).toArray(String[]::new); - } - @Override public boolean addItems(@NonNull final String worldName, @NonNull final PlotItem items) { final World world = getWorld(worldName); final Block block = world.getBlockAt(items.x, items.y, items.z); - if (block == null) { - return false; - } - final BlockState state = block.getState(); + final org.bukkit.block.BlockState state = block.getState(); if (state instanceof InventoryHolder) { InventoryHolder holder = (InventoryHolder) state; Inventory inv = holder.getInventory(); for (int i = 0; i < items.types.length; i++) { // ItemStack item = new ItemStack(LegacyMappings.fromLegacyId(items.id[i]).getMaterial(), items.amount[i], items.data[i]); - ItemStack item = new ItemStack(items.types[i].to(Material.class), items.amount[i]); + ItemStack item = new ItemStack(BukkitAdapter.adapt(items.types[i]), items.amount[i]); inv.addItem(item); } state.update(true); @@ -395,33 +395,11 @@ import java.util.*; return false; } - @Override public boolean isBlockSolid(@NonNull final PlotBlock block) { - try { - Material material = getMaterial(block); - if (material.isLegacy()) { - material = getBukkitLegacyMappings().fromLegacyToString(material.name()) - .to(Material.class); - } - if (material.isBlock() && material.isSolid() && !material.hasGravity()) { - String name = material.name().toLowerCase(Locale.ENGLISH); - if (material.isOccluding() || name.contains("stairs") || name.contains("slab") - || name.contains("wool")) { - switch (material) { - case NOTE_BLOCK: - case SPAWNER: - return false; - default: - return true; - } - } - } - return false; - } catch (Exception ignored) { - return false; - } + @Override public boolean isBlockSolid(@NonNull final BlockState block) { + return block.getBlockType().getMaterial().isSolid(); } - @Override public String getClosestMatchingName(@NonNull final PlotBlock block) { + @Override public String getClosestMatchingName(@NonNull final BlockState block) { try { return getMaterial(block).name(); } catch (Exception ignored) { @@ -430,21 +408,18 @@ import java.util.*; } @Override @Nullable - public StringComparison.ComparisonResult getClosestBlock(String name) { - final PlotBlock plotBlock = BukkitUtil.getBukkitLegacyMappings().fromAny(name); - if (plotBlock != null) { - return new StringComparison().new ComparisonResult(1, plotBlock); - } - return BukkitUtil.getBukkitLegacyMappings().getClosestsMatch(name); + public StringComparison.ComparisonResult getClosestBlock(String name) { + BlockState state = BlockUtil.get(name); + return new StringComparison().new ComparisonResult(1, state); } @Override - public void setBiomes(@NonNull final String worldName, @NonNull final RegionWrapper region, - @NonNull final String biomeString) { + public void setBiomes(@NonNull final String worldName, @NonNull final CuboidRegion region, + @NonNull final BiomeType biomeType) { final World world = getWorld(worldName); - final Biome biome = Biome.valueOf(biomeString.toUpperCase()); - for (int x = region.minX; x <= region.maxX; x++) { - for (int z = region.minZ; z <= region.maxZ; z++) { + final Biome biome = BukkitAdapter.adapt(biomeType); + for (int x = region.getMinimumPoint().getX(); x <= region.getMaximumPoint().getX(); x++) { + for (int z = region.getMinimumPoint().getZ(); z <= region.getMaximumPoint().getZ(); z++) { world.setBiome(x, z, biome); } } @@ -454,13 +429,10 @@ import java.util.*; return new BukkitWorld(Bukkit.getWorld(world)); } - @Override public PlotBlock getBlock(@NonNull final Location location) { + @Override public BlockState getBlock(@NonNull final Location location) { final World world = getWorld(location.getWorld()); final Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ()); - if (block == null) { - return StringPlotBlock.EVERYTHING; - } - return PlotBlock.get(block.getType().name()); + return BukkitAdapter.asBlockType(block.getType()).getDefaultState(); } @Override public String getMainWorld() { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitVersion.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitVersion.java index 8bfa3da59..124108193 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitVersion.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitVersion.java @@ -2,6 +2,4 @@ package com.github.intellectualsites.plotsquared.bukkit.util; public class BukkitVersion { public static int[] v1_13_2 = {1, 13, 2}; - public static int[] v1_13_1 = {1, 13, 1}; - public static int[] v1_13_0 = {1, 13, 0}; } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java index ff6e1b310..edc2f9669 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java @@ -10,12 +10,24 @@ import org.json.simple.JSONArray; import org.json.simple.JSONObject; import javax.net.ssl.HttpsURLConnection; -import java.io.*; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.zip.GZIPOutputStream; @@ -36,6 +48,7 @@ public class Metrics { new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java deleted file mode 100644 index acf0f82fa..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java +++ /dev/null @@ -1,1022 +0,0 @@ -package com.github.intellectualsites.plotsquared.bukkit.util; - -import com.google.common.base.Splitter; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.Lists; -import com.google.common.collect.MapMaker; -import com.google.common.io.ByteSink; -import com.google.common.io.Closeables; -import com.google.common.primitives.Primitives; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.inventory.ItemStack; - -import java.io.*; -import java.lang.reflect.*; -import java.util.*; -import java.util.concurrent.ConcurrentMap; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -public class NbtFactory { - - // Convert between NBT type and the equivalent class in java - private static final BiMap> NBT_CLASS = HashBiMap.create(); - private static final BiMap NBT_ENUM = HashBiMap.create(); - // Shared instance - private static NbtFactory INSTANCE; - private final Field[] DATA_FIELD = new Field[12]; - // The NBT base class - private Class BASE_CLASS; - private Class COMPOUND_CLASS; - private Class STREAM_TOOLS; - private Class READ_LIMITER_CLASS; - private Method NBT_CREATE_TAG; - private Method NBT_GET_TYPE; - private Field NBT_LIST_TYPE; - // CraftItemStack - private Class CRAFT_STACK; - private Field CRAFT_HANDLE; - private Field STACK_TAG; - // Loading/saving compounds - private LoadCompoundMethod LOAD_COMPOUND; - private Method SAVE_COMPOUND; - - /** - * Construct an instance of the NBT factory by deducing the class of NBTBase. - */ - private NbtFactory() { - if (this.BASE_CLASS == null) { - try { - // Keep in mind that I do use hard-coded field names - but it's okay as long as we're dealing - // with CraftBukkit or its derivatives. This does not work in MCPC+ however. - ClassLoader loader = NbtFactory.class.getClassLoader(); - - String packageName = getPackageName(); - String craftpackageName = getCraftPackageName(); - Class offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer"); - - // Prepare NBT - this.COMPOUND_CLASS = - getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType(); - this.BASE_CLASS = loader.loadClass(craftpackageName + ".NBTBase"); - this.NBT_GET_TYPE = getMethod(0, Modifier.STATIC, this.BASE_CLASS, "getTypeId"); - this.NBT_CREATE_TAG = - getMethod(Modifier.STATIC, 0, this.BASE_CLASS, "createTag", byte.class); - - // Prepare CraftItemStack - this.CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack"); - this.CRAFT_HANDLE = getField(null, this.CRAFT_STACK, "handle"); - this.STACK_TAG = getField(null, this.CRAFT_HANDLE.getType(), "tag"); - - // Loading/saving - String nmsPackage = this.BASE_CLASS.getPackage().getName(); - initializeNMS(loader, nmsPackage); - - if (this.READ_LIMITER_CLASS != null) { - this.LOAD_COMPOUND = - new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS); - } else { - this.LOAD_COMPOUND = new LoadMethodWorldUpdate(this.STREAM_TOOLS); - } - this.SAVE_COMPOUND = - getMethod(Modifier.STATIC, 0, this.STREAM_TOOLS, null, this.BASE_CLASS, - DataOutput.class); - - } catch (ClassNotFoundException e) { - throw new IllegalStateException("Unable to find offline player.", e); - } - } - } - - /** - * Retrieve or construct a shared NBT factory. - * - * @return The factory. - */ - private static NbtFactory get() { - if (INSTANCE == null) { - INSTANCE = new NbtFactory(); - } - return INSTANCE; - } - - /** - * Construct a new NBT list of an unspecified type. - * - * @return The NBT list. - */ - public static NbtList createList(Object... content) { - return createList(Arrays.asList(content)); - } - - /** - * Construct a new NBT list of an unspecified type. - * - * @return The NBT list. - */ - public static NbtList createList(Iterable iterable) { - NbtList list = get().new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null)); - - // Add the content as well - for (Object obj : iterable) { - list.add(obj); - } - return list; - } - - /** - * Construct a new NBT compound. - * - * @return The NBT compound. - */ - public static NbtCompound createCompound() { - return get().new NbtCompound(INSTANCE.createNbtTag(NbtType.TAG_COMPOUND, null)); - } - - /** - * Construct a new NBT wrapper from a list. - * - * @param nmsList - the NBT list. - * @return The wrapper. - */ - public static NbtList fromList(Object nmsList) { - return get().new NbtList(nmsList); - } - - /** - * Load the content of a file from a stream. - * - * @param input - the stream. - * @param option - whether or not to decompress the input stream. - * @return The decoded NBT compound. - * @throws IOException If anything went wrong. - */ - @SuppressWarnings({"IOResourceOpenedButNotSafelyClosed", "resource"}) - public static NbtCompound fromStream(InputStream input, StreamOptions option) - throws IOException { - DataInputStream data = null; - boolean suppress = true; - - try { - if (option == StreamOptions.GZIP_COMPRESSION) { - data = new DataInputStream(new BufferedInputStream(new GZIPInputStream(input))); - } else { - data = new DataInputStream(new BufferedInputStream(input)); - } - - NbtCompound result = fromCompound(get().LOAD_COMPOUND.loadNbt(data)); - suppress = false; - return result; - - } finally { - if (data != null) { - Closeables.close(data, suppress); - } else if (input != null) { - Closeables.close(input, suppress); - } - } - } - - /** - * Save the content of a NBT compound to a stream. - * - * @param source - the NBT compound to save. - * @param stream - the stream. - * @param option - whether or not to compress the output. - * @throws IOException If anything went wrong. - */ - public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option) - throws IOException { - - try (OutputStream output = stream.openStream(); - DataOutputStream data = new DataOutputStream( - option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output)) { - invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data); - } - } - - /** - * Construct a new NBT wrapper from a compound. - * - * @param nmsCompound - the NBT compound. - * @return The wrapper. - */ - public static NbtCompound fromCompound(Object nmsCompound) { - return get().new NbtCompound(nmsCompound); - } - - /** - * Set the NBT compound tag of a given item stack. - *

- * - * @param stack - the item stack, cannot be air. - * @param compound - the new NBT compound, or NULL to remove it. - * @throws IllegalArgumentException If the stack is not a CraftItemStack, or it represents air. - */ - public static void setItemTag(ItemStack stack, NbtCompound compound) { - checkItemStack(stack); - Object nms = getFieldValue(get().CRAFT_HANDLE, stack); - - // Now update the tag compound - setFieldValue(get().STACK_TAG, nms, compound.getHandle()); - } - - /** - * Construct a wrapper for an NBT tag stored (in memory) in an item stack. This is where - * auxiliary data such as enchanting, name and lore is stored. It does not include items - * material, damage value or count. - *

- * The item stack must be a wrapper for a CraftItemStack. - * - * @param stack - the item stack. - * @return A wrapper for its NBT tag. - */ - public static NbtCompound fromItemTag(ItemStack stack) { - checkItemStack(stack); - Object nms = getFieldValue(get().CRAFT_HANDLE, stack); - Object tag = getFieldValue(get().STACK_TAG, nms); - - // Create the tag if it doesn't exist - if (tag == null) { - NbtCompound compound = createCompound(); - setItemTag(stack, compound); - return compound; - } - return fromCompound(tag); - } - - /** - * Retrieve a CraftItemStack version of the stack. - * - * @param stack - the stack to convert. - * @return The CraftItemStack version. - */ - public static ItemStack getCraftItemStack(ItemStack stack) { - // Any need to convert? - if ((stack == null) || get().CRAFT_STACK.isAssignableFrom(stack.getClass())) { - return stack; - } - try { - // Call the private constructor - Constructor caller = INSTANCE.CRAFT_STACK.getDeclaredConstructor(ItemStack.class); - caller.setAccessible(true); - return (ItemStack) caller.newInstance(stack); - } catch (Exception ignored) { - throw new IllegalStateException( - "Unable to convert " + stack + " + to a CraftItemStack."); - } - } - - /** - * Ensure that the given stack can store arbitrary NBT information. - * - * @param stack - the stack to check. - */ - private static void checkItemStack(ItemStack stack) { - if (stack == null) { - throw new IllegalArgumentException("Stack cannot be NULL."); - } - if (!get().CRAFT_STACK.isAssignableFrom(stack.getClass())) { - throw new IllegalArgumentException("Stack must be a CraftItemStack."); - } - if (stack.getType() == Material.AIR) { - throw new IllegalArgumentException( - "ItemStacks representing air cannot store NMS information."); - } - } - - /** - * Invoke a method on the given target instance using the provided parameters. - * - * @param method - the method to invoke. - * @param target - the target. - * @param params - the parameters to supply. - * @return The result of the method. - */ - private static Object invokeMethod(Method method, Object target, Object... params) { - try { - return method.invoke(target, params); - } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) { - throw new RuntimeException("Unable to invoke method " + method + " for " + target, e); - } - } - - private static void setFieldValue(Field field, Object target, Object value) { - try { - field.set(target, value); - } catch (IllegalAccessException | IllegalArgumentException e) { - throw new RuntimeException("Unable to set " + field + " for " + target, e); - } - } - - private static Object getFieldValue(Field field, Object target) { - try { - return field.get(target); - } catch (IllegalAccessException | IllegalArgumentException e) { - throw new RuntimeException("Unable to retrieve " + field + " for " + target, e); - } - } - - /** - * Search for the first publicly and privately defined method of the given name and parameter count. - * - * @param requireMod - modifiers that are required. - * @param bannedMod - modifiers that are banned. - * @param clazz - a class to start with. - * @param methodName - the method name, or NULL to skip. - * @param params - the expected parameters. - * @return The first method by this name. - * @throws IllegalStateException If we cannot find this method. - */ - private static Method getMethod(int requireMod, int bannedMod, Class clazz, - String methodName, Class... params) { - for (Method method : clazz.getDeclaredMethods()) { - // Limitation: Doesn't handle overloads - if (((method.getModifiers() & requireMod) == requireMod) && ( - (method.getModifiers() & bannedMod) == 0) && ((methodName == null) || method - .getName().equals(methodName)) && Arrays - .equals(method.getParameterTypes(), params)) { - - method.setAccessible(true); - return method; - } - } - // Search in every superclass - if (clazz.getSuperclass() != null) { - return getMethod(requireMod, bannedMod, clazz.getSuperclass(), methodName, params); - } - throw new IllegalStateException( - String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params))); - } - - /** - * Search for the first publicly and privately defined field of the given name. - * - * @param instance - an instance of the class with the field. - * @param clazz - an optional class to start with, or NULL to deduce it from instance. - * @param fieldName - the field name. - * @return The first field by this name. - * @throws IllegalStateException If we cannot find this field. - */ - private static Field getField(Object instance, Class clazz, String fieldName) { - if (clazz == null) { - clazz = instance.getClass(); - } - // Ignore access rules - for (Field field : clazz.getDeclaredFields()) { - if (field.getName().equals(fieldName)) { - field.setAccessible(true); - return field; - } - } - // Recursively fild the correct field - if (clazz.getSuperclass() != null) { - return getField(instance, clazz.getSuperclass(), fieldName); - } - throw new IllegalStateException("Unable to find field " + fieldName + " in " + instance); - } - - private void initializeNMS(ClassLoader loader, String nmsPackage) { - try { - this.STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools"); - this.READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter"); - } catch (ClassNotFoundException ignored) { - } - } - - private String getPackageName() { - Server server = Bukkit.getServer(); - String name = server != null ? server.getClass().getPackage().getName() : null; - - if ((name != null) && name.contains("craftbukkit")) { - return name; - } else { - // Fallback - return "org.bukkit.craftbukkit.v1_13_R1"; - } - } - - private String getCraftPackageName() { - String version = - Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - return "net.minecraft.server." + version; - } - - @SuppressWarnings("unchecked") private Map getDataMap(Object handle) { - return (Map) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), - handle); - } - - @SuppressWarnings("unchecked") private List getDataList(Object handle) { - return (List) getFieldValue(getDataField(NbtType.TAG_LIST, handle), handle); - } - - /** - * Convert wrapped List and Map objects into their respective NBT counterparts. - * - * @param value - the value of the element to create. Can be a List or a Map. - * @return The NBT element. - */ - private Object unwrapValue(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Wrapper) { - return ((Wrapper) value).getHandle(); - } else if (value instanceof List) { - throw new IllegalArgumentException("Can only insert a WrappedList."); - } else if (value instanceof Map) { - throw new IllegalArgumentException("Can only insert a WrappedCompound."); - } else { - return createNbtTag(getPrimitiveType(value), value); - } - } - - /** - * Convert a given NBT element to a primitive wrapper or List/Map equivalent. - *

All changes to any mutable objects will be reflected in the underlying NBT element(s). - * - * @param nms - the NBT element. - * @return The wrapper equivalent. - */ - private Object wrapNative(Object nms) { - if (nms == null) { - return null; - } - - if (this.BASE_CLASS.isAssignableFrom(nms.getClass())) { - NbtType type = getNbtType(nms); - - // Handle the different types - switch (type) { - case TAG_COMPOUND: - return new NbtCompound(nms); - case TAG_LIST: - return new NbtList(nms); - default: - return getFieldValue(getDataField(type, nms), nms); - } - } - throw new IllegalArgumentException("Unexpected type: " + nms); - } - - /** - * Construct a new NMS NBT tag initialized with the given value. - * - * @param type - the NBT type. - * @param value - the value, or NULL to keep the original value. - * @return The created tag. - */ - private Object createNbtTag(NbtType type, Object value) { - Object tag = invokeMethod(this.NBT_CREATE_TAG, null, (byte) type.id); - - if (value != null) { - setFieldValue(getDataField(type, tag), tag, value); - } - return tag; - } - - /** - * Retrieve the field where the NBT class stores its value. - * - * @param type - the NBT type. - * @param nms - the NBT class instance. - * @return The corresponding field. - */ - private Field getDataField(NbtType type, Object nms) { - if (this.DATA_FIELD[type.id] == null) { - this.DATA_FIELD[type.id] = getField(nms, null, type.getFieldName()); - } - return this.DATA_FIELD[type.id]; - } - - /** - * Retrieve the NBT type from a given NMS NBT tag. - * - * @param nms - the native NBT tag. - * @return The corresponding type. - */ - private NbtType getNbtType(Object nms) { - int type = (Byte) invokeMethod(this.NBT_GET_TYPE, nms); - return NBT_ENUM.get(type); - } - - /** - * Retrieve the nearest NBT type for a given primitive type. - * - * @param primitive - the primitive type. - * @return The corresponding type. - */ - private NbtType getPrimitiveType(Object primitive) { - NbtType type = - NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass()))); - - // Display the illegal value at least - if (type == null) { - throw new IllegalArgumentException( - String.format("Illegal type: %s (%s)", primitive.getClass(), primitive)); - } - return type; - } - - /** - * Whether or not to enable stream compression. - * - * @author Kristian - */ - public enum StreamOptions { - NO_COMPRESSION, GZIP_COMPRESSION, - } - - - private enum NbtType { - TAG_END(0, Void.class), TAG_BYTE(1, byte.class), TAG_SHORT(2, short.class), TAG_INT(3, - int.class), TAG_LONG(4, long.class), TAG_FLOAT(5, float.class), TAG_DOUBLE(6, - double.class), TAG_BYTE_ARRAY(7, byte[].class), TAG_INT_ARRAY(11, - int[].class), TAG_STRING(8, String.class), TAG_LIST(9, List.class), TAG_COMPOUND(10, - Map.class); - - // Unique NBT type - public final int id; - - NbtType(int id, Class type) { - this.id = id; - NBT_CLASS.put(id, type); - NBT_ENUM.put(id, this); - } - - private String getFieldName() { - if (this == TAG_COMPOUND) { - return "map"; - } else if (this == TAG_LIST) { - return "list"; - } else { - return "data"; - } - } - } - - - /** - * Represents an object that provides a view of a native NMS class. - * - * @author Kristian - */ - public interface Wrapper { - - /** - * Retrieve the underlying native NBT tag. - * - * @return The underlying NBT. - */ - Object getHandle(); - } - - - /** - * Represents a method for loading an NBT compound. - * - * @author Kristian - */ - private static abstract class LoadCompoundMethod { - - protected Method staticMethod; - - protected void setMethod(Method method) { - this.staticMethod = method; - this.staticMethod.setAccessible(true); - } - - /** - * Load an NBT compound from a given stream. - * - * @param input - the input stream. - * @return The loaded NBT compound. - */ - public abstract Object loadNbt(DataInput input); - } - - - /** - * Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.2 - 1.7.5 - */ - private static class LoadMethodWorldUpdate extends LoadCompoundMethod { - - LoadMethodWorldUpdate(Class streamClass) { - setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class)); - } - - @Override public Object loadNbt(DataInput input) { - return invokeMethod(this.staticMethod, null, input); - } - } - - - /** - * Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.8 - */ - private static class LoadMethodSkinUpdate extends LoadCompoundMethod { - - private Object readLimiter; - - LoadMethodSkinUpdate(Class streamClass, Class readLimiterClass) { - setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, - readLimiterClass)); - - // Find the unlimited read limiter - for (Field field : readLimiterClass.getDeclaredFields()) { - if (readLimiterClass.isAssignableFrom(field.getType())) { - try { - this.readLimiter = field.get(null); - } catch (Exception e) { - throw new RuntimeException("Cannot retrieve read limiter.", e); - } - } - } - } - - @Override public Object loadNbt(DataInput input) { - return invokeMethod(this.staticMethod, null, input, this.readLimiter); - } - } - - - /** - * Represents a root NBT compound. - *

All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following: - *

    - *
  • Primitive types
  • - *
  • {@link String String}
  • - *
  • {@link NbtList}
  • - *
  • {@link NbtCompound}
  • - *
- *

- * See also: - *

    - *
  • {@link NbtFactory#createCompound()}
  • - *
  • {@link NbtFactory#fromCompound(Object)}
  • - *
- * - * @author Kristian - */ - public final class NbtCompound extends ConvertedMap { - - private NbtCompound(Object handle) { - super(handle, getDataMap(handle)); - } - - // Simplifying access to each value - public Byte getByte(String key, Byte defaultValue) { - return containsKey(key) ? (Byte) get(key) : defaultValue; - } - - public Short getShort(String key, Short defaultValue) { - return containsKey(key) ? (Short) get(key) : defaultValue; - } - - public Integer getInteger(String key, Integer defaultValue) { - return containsKey(key) ? (Integer) get(key) : defaultValue; - } - - public Long getLong(String key, Long defaultValue) { - return containsKey(key) ? (Long) get(key) : defaultValue; - } - - public Float getFloat(String key, Float defaultValue) { - return containsKey(key) ? (Float) get(key) : defaultValue; - } - - public Double getDouble(String key, Double defaultValue) { - return containsKey(key) ? (Double) get(key) : defaultValue; - } - - public String getString(String key, String defaultValue) { - return containsKey(key) ? (String) get(key) : defaultValue; - } - - public byte[] getByteArray(String key, byte[] defaultValue) { - return containsKey(key) ? (byte[]) get(key) : defaultValue; - } - - public int[] getIntegerArray(String key, int[] defaultValue) { - return containsKey(key) ? (int[]) get(key) : defaultValue; - } - - /** - * Retrieve the list by the given name. - * - * @param key - the name of the list. - * @param createNew - whether or not to create a new list if its missing. - * @return An existing list, a new list or NULL. - */ - public NbtList getList(String key, boolean createNew) { - NbtList list = (NbtList) get(key); - - if ((list == null) && createNew) { - put(key, list = createList()); - } - return list; - } - - /** - * Retrieve the map by the given name. - * - * @param key - the name of the map. - * @param createNew - whether or not to create a new map if its missing. - * @return An existing map, a new map or NULL. - */ - public NbtCompound getMap(String key, boolean createNew) { - return getMap(Collections.singletonList(key), createNew); - } - - // Done - - /** - * Set the value of an entry at a given location. - *

- * Every element of the path (except the end) are assumed to be compounds, and will - * be created if they are missing. - * - * @param path - the path to the entry. - * @param value - the new value of this entry. - * @return This compound, for chaining. - */ - public NbtCompound putPath(String path, Object value) { - List entries = getPathElements(path); - Map map = getMap(entries.subList(0, entries.size() - 1), true); - - map.put(entries.get(entries.size() - 1), value); - return this; - } - - /** - * Retrieve the value of a given entry in the tree. - *

- * Every element of the path (except the end) are assumed to be compounds. The - * retrieval operation will be cancelled if any of them are missing. - * - * @param path - path to the entry. - * @return The value, or NULL if not found. - */ - @SuppressWarnings("unchecked") public T getPath(String path) { - List entries = getPathElements(path); - NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false); - - if (map != null) { - return (T) map.get(entries.get(entries.size() - 1)); - } - return null; - } - - /** - * Save the content of a NBT compound to a stream. - * - * @param stream - the output stream. - * @param option - whether or not to compress the output. - * @throws IOException If anything went wrong. - */ - public void saveTo(ByteSink stream, StreamOptions option) throws IOException { - saveStream(this, stream, option); - } - - /** - * Retrieve a map from a given path. - * - * @param path - path of compounds to look up. - * @param createNew - whether or not to create new compounds on the way. - * @return The map at this location. - */ - private NbtCompound getMap(Iterable path, boolean createNew) { - NbtCompound current = this; - - for (String entry : path) { - NbtCompound child = (NbtCompound) current.get(entry); - - if (child == null) { - if (!createNew) { - return null; - } - current.put(entry, child = createCompound()); - } - current = child; - } - return current; - } - - /** - * Split the path into separate elements. - * - * @param path - the path to split. - * @return The elements. - */ - private List getPathElements(String path) { - return Lists.newArrayList(Splitter.on(".").omitEmptyStrings().split(path)); - } - } - - - /** - * Represents a root NBT list. - * See also: - *

    - *
  • {@link NbtFactory#createList(Iterable)}}
  • - *
  • {@link NbtFactory#fromList(Object)}
  • - *
- * - * @author Kristian - */ - public final class NbtList extends ConvertedList { - - private NbtList(Object handle) { - super(handle, getDataList(handle)); - } - } - - - /** - * Represents a class for caching wrappers. - * - * @author Kristian - */ - private final class CachedNativeWrapper { - - // Don't recreate wrapper objects - private final ConcurrentMap cache = new MapMaker().weakKeys().makeMap(); - - public Object wrap(Object value) { - Object current = this.cache.get(value); - - if (current == null) { - current = wrapNative(value); - - // Only cache composite objects - if ((current instanceof ConvertedMap) || (current instanceof ConvertedList)) { - this.cache.put(value, current); - } - } - return current; - } - } - - - /** - * Represents a map that wraps another map and automatically - * converts entries of its type and another exposed type. - * - * @author Kristian - */ - private class ConvertedMap extends AbstractMap implements Wrapper { - - private final Object handle; - private final Map original; - - private final CachedNativeWrapper cache = new CachedNativeWrapper(); - - public ConvertedMap(Object handle, Map original) { - this.handle = handle; - this.original = original; - } - - // For converting back and forth - protected Object wrapOutgoing(Object value) { - return this.cache.wrap(value); - } - - protected Object unwrapIncoming(Object wrapped) { - return unwrapValue(wrapped); - } - - // Modification - @Override public Object put(String key, Object value) { - return wrapOutgoing(this.original.put(key, unwrapIncoming(value))); - } - - // Performance - @Override public Object get(Object key) { - return wrapOutgoing(this.original.get(key)); - } - - @Override public Object remove(Object key) { - return wrapOutgoing(this.original.remove(key)); - } - - @Override public boolean containsKey(Object key) { - return this.original.containsKey(key); - } - - @Override public Set> entrySet() { - return new AbstractSet>() { - @Override public boolean add(Entry e) { - String key = e.getKey(); - Object value = e.getValue(); - - ConvertedMap.this.original.put(key, unwrapIncoming(value)); - return true; - } - - @Override public int size() { - return ConvertedMap.this.original.size(); - } - - @Override public Iterator> iterator() { - return ConvertedMap.this.iterator(); - } - }; - } - - private Iterator> iterator() { - final Iterator> proxy = this.original.entrySet().iterator(); - - return new Iterator>() { - @Override public boolean hasNext() { - return proxy.hasNext(); - } - - @Override public Entry next() { - Entry entry = proxy.next(); - - return new SimpleEntry(entry.getKey(), - wrapOutgoing(entry.getValue())); - } - - @Override public void remove() { - proxy.remove(); - } - }; - } - - @Override public Object getHandle() { - return this.handle; - } - } - - - /** - * Represents a list that wraps another list and converts elements - * of its type and another exposed type. - * - * @author Kristian - */ - private class ConvertedList extends AbstractList implements Wrapper { - - private final Object handle; - - private final List original; - private final CachedNativeWrapper cache = new CachedNativeWrapper(); - - public ConvertedList(Object handle, List original) { - if (NbtFactory.this.NBT_LIST_TYPE == null) { - NbtFactory.this.NBT_LIST_TYPE = getField(handle, null, "type"); - } - this.handle = handle; - this.original = original; - } - - protected Object wrapOutgoing(Object value) { - return this.cache.wrap(value); - } - - protected Object unwrapIncoming(Object wrapped) { - return unwrapValue(wrapped); - } - - @Override public Object get(int index) { - return wrapOutgoing(this.original.get(index)); - } - - @Override public int size() { - return this.original.size(); - } - - @Override public Object set(int index, Object element) { - return wrapOutgoing(this.original.set(index, unwrapIncoming(element))); - } - - @Override public void add(int index, Object element) { - Object nbt = unwrapIncoming(element); - - // Set the list type if its the first element - if (size() == 0) { - setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle, - (byte) getNbtType(nbt).id); - } - this.original.add(index, nbt); - } - - @Override public Object remove(int index) { - return wrapOutgoing(this.original.remove(index)); - } - - @Override public boolean remove(Object o) { - return this.original.remove(unwrapIncoming(o)); - } - - @Override public Object getHandle() { - return this.handle; - } - } -} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/OfflinePlayerUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/OfflinePlayerUtil.java index f1bc97bb1..a4ee94f80 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/OfflinePlayerUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/OfflinePlayerUtil.java @@ -9,18 +9,16 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.UUID; -import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.*; +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.callConstructor; +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.callMethod; +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getCbClass; +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getNmsClass; +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getUtilClass; +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.makeConstructor; +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.makeMethod; public class OfflinePlayerUtil { - public static Player loadPlayer(String name) { - return loadPlayer(Bukkit.getOfflinePlayer(name)); - } - - public static Player loadPlayer(UUID id) { - return loadPlayer(Bukkit.getOfflinePlayer(id)); - } - public static Player loadPlayer(OfflinePlayer player) { if (player == null) { return null; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java index 62d82cedb..8b5e89b27 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java @@ -2,7 +2,6 @@ package com.github.intellectualsites.plotsquared.bukkit.util; import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -12,6 +11,8 @@ import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefFie import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefMethod; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.sk89q.worldedit.math.BlockVector2; +import io.papermc.lib.PaperLib; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.World; @@ -42,7 +43,6 @@ public class SendChunk { * Constructor. */ public SendChunk() throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException { - RefConstructor tempMapChunk; RefClass classCraftPlayer = getRefClass("{cb}.entity.CraftPlayer"); this.methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle"); RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); @@ -50,8 +50,7 @@ public class SendChunk { RefClass classChunk = getRefClass("{nms}.Chunk"); this.methodInitLighting = classChunk.getMethod("initLighting"); RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); - tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), int.class); - this.mapChunk = tempMapChunk; + this.mapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), int.class); RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer"); this.connection = classEntityPlayer.getField("playerConnection"); RefClass classPacket = getRefClass("{nms}.Packet"); @@ -88,14 +87,14 @@ public class SendChunk { if (location == null) { location = pp.getLocation(); } - int cx = location.getX() >> 4; - int cz = location.getZ() >> 4; + int chunkX = location.getX() >> 4; + int chunkZ = location.getZ() >> 4; Player player = ((BukkitPlayer) pp).player; Object entity = this.methodGetHandlePlayer.of(player).call(); for (Chunk chunk : list) { - int dx = Math.abs(cx - chunk.getX()); - int dz = Math.abs(cz - chunk.getZ()); + int dx = Math.abs(chunkX - chunk.getX()); + int dz = Math.abs(chunkZ - chunk.getZ()); if ((dx > view) || (dz > view)) { continue; } @@ -130,12 +129,12 @@ public class SendChunk { } } - public void sendChunk(String worldName, Collection chunkLocations) { + public void sendChunk(String worldName, Collection chunkLocations) { World myWorld = Bukkit.getWorld(worldName); ArrayList chunks = new ArrayList<>(); - for (ChunkLoc loc : chunkLocations) { - if (myWorld.isChunkLoaded(loc.x, loc.z)) { - chunks.add(myWorld.getChunkAt(loc.x, loc.z)); + for (BlockVector2 loc : chunkLocations) { + if (myWorld.isChunkLoaded(loc.getX(), loc.getZ())) { + PaperLib.getChunkAtAsync(myWorld, loc.getX(), loc.getZ()).thenAccept(chunks::add); } } sendChunk(chunks); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java index 483fb51c0..82f5c4282 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java @@ -1,40 +1,35 @@ package com.github.intellectualsites.plotsquared.bukkit.util.block; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitBlockUtil; import com.github.intellectualsites.plotsquared.bukkit.object.schematic.StateWrapper; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.LegacyPlotBlock; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; -import com.github.intellectualsites.plotsquared.plot.object.StringPlotBlock; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; -import com.github.intellectualsites.plotsquared.plot.util.StringMan; import com.github.intellectualsites.plotsquared.plot.util.block.BasicLocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.world.BlockUtil; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; +import io.papermc.lib.PaperLib; import lombok.NonNull; import org.bukkit.Bukkit; -import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Locale; +import java.util.concurrent.ExecutionException; -public class BukkitLocalQueue extends BasicLocalBlockQueue { - - private Field fieldNeighbors; - private Method chunkGetHandle; +public class BukkitLocalQueue extends BasicLocalBlockQueue { public BukkitLocalQueue(String world) { super(world); } - @Override public LocalChunk getLocalChunk(int x, int z) { - return (LocalChunk) new BasicLocalChunk(this, x, z) { + @Override public LocalChunk getLocalChunk(int x, int z) { + return new BasicLocalChunk(this, x, z) { // Custom stuff? }; } @@ -43,19 +38,23 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { } - @Override public PlotBlock getBlock(int x, int y, int z) { + @Override public BlockState getBlock(int x, int y, int z) { World worldObj = Bukkit.getWorld(getWorld()); if (worldObj != null) { Block block = worldObj.getBlockAt(x, y, z); - return PlotBlock.get(block.getType().toString()); + return BukkitBlockUtil.get(block); } else { - return PlotBlock.get(0, 0); + return BlockUtil.get(0, 0); } } @Override public void refreshChunk(int x, int z) { World worldObj = Bukkit.getWorld(getWorld()); - worldObj.refreshChunk(x, z); + if (worldObj != null) { + worldObj.refreshChunk(x, z); + } else { + PlotSquared.debug("Error Refreshing Chunk"); + } } @Override public void fixChunkLighting(int x, int z) { @@ -64,133 +63,79 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { @Override public final void regenChunk(int x, int z) { World worldObj = Bukkit.getWorld(getWorld()); - worldObj.regenerateChunk(x, z); - } - - @Override public final void setComponents(LocalChunk lc) { - if (isBaseBlocks()) { - setBaseBlocks(lc); + if (worldObj != null) { + worldObj.regenerateChunk(x, z); } else { - setBlocks(lc); + PlotSquared.debug("Error Regenerating Chunk"); } } - public World getBukkitWorld() { - return Bukkit.getWorld(getWorld()); + @Override public final void setComponents(LocalChunk lc) + throws ExecutionException, InterruptedException { + setBaseBlocks(lc); } - public Chunk getChunk(int x, int z) { - return getBukkitWorld().getChunkAt(x, z); - } - - public void setBlocks(LocalChunk lc) { + public void setBaseBlocks(LocalChunk localChunk) { World worldObj = Bukkit.getWorld(getWorld()); - Chunk chunk = worldObj.getChunkAt(lc.getX(), lc.getZ()); - chunk.load(true); - for (int layer = 0; layer < lc.blocks.length; layer++) { - PlotBlock[] blocksLayer = (PlotBlock[]) lc.blocks[layer]; - if (blocksLayer != null) { - for (int j = 0; j < blocksLayer.length; j++) { - if (blocksLayer[j] != null) { - PlotBlock block = blocksLayer[j]; - int x = MainUtil.x_loc[layer][j]; - int y = MainUtil.y_loc[layer][j]; - int z = MainUtil.z_loc[layer][j]; - Block existing = chunk.getBlock(x, y, z); - if (equals(block, existing)) { - continue; - } - setMaterial(block, existing); - } - } - } + if (worldObj == null) { + throw new NullPointerException("World cannot be null."); } - } + PaperLib.getChunkAtAsync(worldObj, localChunk.getX(), localChunk.getZ(), true) + .thenAccept(chunk -> { + for (int layer = 0; layer < localChunk.baseblocks.length; layer++) { + BaseBlock[] blocksLayer = localChunk.baseblocks[layer]; + if (blocksLayer != null) { + for (int j = 0; j < blocksLayer.length; j++) { + if (blocksLayer[j] != null) { + BaseBlock block = blocksLayer[j]; + int x = MainUtil.x_loc[layer][j]; + int y = MainUtil.y_loc[layer][j]; + int z = MainUtil.z_loc[layer][j]; - public void setBaseBlocks(LocalChunk lc) { - World worldObj = Bukkit.getWorld(getWorld()); - Chunk chunk = worldObj.getChunkAt(lc.getX(), lc.getZ()); - chunk.load(true); - for (int layer = 0; layer < lc.baseblocks.length; layer++) { - BaseBlock[] blocksLayer = lc.baseblocks[layer]; - if (blocksLayer != null) { - for (int j = 0; j < blocksLayer.length; j++) { - if (blocksLayer[j] != null) { - BaseBlock block = blocksLayer[j]; - int x = MainUtil.x_loc[layer][j]; - int y = MainUtil.y_loc[layer][j]; - int z = MainUtil.z_loc[layer][j]; + BlockData blockData = BukkitAdapter.adapt(block); - BlockData blockData = BukkitAdapter.adapt(block); + Block existing = chunk.getBlock(x, y, z); + if (BukkitBlockUtil.get(existing).equals(block) && existing + .getBlockData().matches(blockData)) { + continue; + } - Block existing = chunk.getBlock(x, y, z); - if (equals(PlotBlock.get(block), existing) && existing.getBlockData() - .matches(blockData)) { - continue; - } + existing.setType(BukkitAdapter.adapt(block.getBlockType()), false); + existing.setBlockData(blockData, false); + if (block.hasNbtData()) { + CompoundTag tag = block.getNbtData(); + StateWrapper sw = new StateWrapper(tag); - existing.setType(BukkitAdapter.adapt(block.getBlockType()), false); - existing.setBlockData(blockData, false); - if (block.hasNbtData()) { - CompoundTag tag = block.getNbtData(); - StateWrapper sw = new StateWrapper(tag); - - sw.restoreTag(worldObj.getName(), existing.getX(), existing.getY(), - existing.getZ()); + sw.restoreTag(worldObj.getName(), existing.getX(), + existing.getY(), existing.getZ()); + } + } } } } - } - } + }); } - private void setMaterial(@NonNull final PlotBlock plotBlock, @NonNull final Block block) { - final Material material; - if (plotBlock instanceof StringPlotBlock) { - material = Material - .getMaterial(((StringPlotBlock) plotBlock).getItemId().toUpperCase(Locale.ENGLISH)); - if (material == null) { - throw new IllegalStateException(String - .format("Could not find material that matches %s", - ((StringPlotBlock) plotBlock).getItemId())); - } - } else { - final LegacyPlotBlock legacyPlotBlock = (LegacyPlotBlock) plotBlock; - material = PlotSquared.get().IMP.getLegacyMappings() - .fromLegacyToString(legacyPlotBlock.getId(), legacyPlotBlock.getData()) - .to(Material.class); - if (material == null) { - throw new IllegalStateException(String - .format("Could not find material that matches %s", legacyPlotBlock.toString())); - } - } + private void setMaterial(@NonNull final BlockState plotBlock, @NonNull final Block block) { + Material material = BukkitAdapter.adapt(plotBlock.getBlockType()); block.setType(material, false); } - private boolean equals(@NonNull final PlotBlock plotBlock, @NonNull final Block block) { - if (plotBlock instanceof StringPlotBlock) { - return ((StringPlotBlock) plotBlock).idEquals(block.getType().name()); - } - final LegacyPlotBlock legacyPlotBlock = (LegacyPlotBlock) plotBlock; - return Material.getMaterial(PlotSquared.get().IMP.getLegacyMappings() - .fromLegacyToString(((LegacyPlotBlock) plotBlock).id, - ((LegacyPlotBlock) plotBlock).data).toString()) == block.getType() && ( - legacyPlotBlock.id == 0 || legacyPlotBlock.data == block.getData()); + private boolean equals(@NonNull final BlockState plotBlock, @NonNull final Block block) { + return plotBlock.equals(BukkitBlockUtil.get(block)); } - public void setBiomes(LocalChunk lc) { + public void setBiomes(LocalChunk lc) { if (lc.biomes != null) { World worldObj = Bukkit.getWorld(getWorld()); int bx = lc.getX() << 4; int bz = lc.getX() << 4; - String last = null; - Biome biome = null; for (int x = 0; x < lc.biomes.length; x++) { - String[] biomes2 = lc.biomes[x]; + BiomeType[] biomes2 = lc.biomes[x]; if (biomes2 != null) { - for (String biomeStr : biomes2) { + for (BiomeType biomeStr : biomes2) { if (biomeStr != null) { - biome = Biome.valueOf(biomeStr.toUpperCase()); + Biome biome = BukkitAdapter.adapt(biomeStr); worldObj.setBiome(bx, bz, biome); } } @@ -199,59 +144,4 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { } } - /** - * Exploiting a bug in the vanilla lighting algorithm for faster block placement - * - Could have been achieved without reflection by force unloading specific chunks - * - Much faster just setting the variable manually though - * - * @param chunk - * @return - */ - protected Object[] disableLighting(Chunk chunk) { - try { - if (chunkGetHandle == null) { - chunkGetHandle = chunk.getClass().getDeclaredMethod("getHandle"); - chunkGetHandle.setAccessible(true); - } - Object nmsChunk = chunkGetHandle.invoke(chunk); - if (fieldNeighbors == null) { - fieldNeighbors = nmsChunk.getClass().getDeclaredField("neighbors"); - fieldNeighbors.setAccessible(true); - } - Object value = fieldNeighbors.get(nmsChunk); - fieldNeighbors.set(nmsChunk, 0); - return new Object[] {nmsChunk, value}; - } catch (Throwable ignore) { - } - return null; - } - - protected void disableLighting(Object[] disableResult) { - if (disableResult != null) { - try { - fieldNeighbors.set(disableResult[0], 0); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - } - - protected void resetLighting(Object[] disableResult) { - if (disableResult != null) { - try { - fieldNeighbors.set(disableResult[0], disableResult[1]); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - protected void enableLighting(Object[] disableResult) { - if (disableResult != null) { - try { - fieldNeighbors.set(disableResult[0], 0x739C0); - } catch (Throwable ignore) { - } - } - } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/GenChunk.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/GenChunk.java index eebac8ef0..72c570df5 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/GenChunk.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/GenChunk.java @@ -1,17 +1,21 @@ package com.github.intellectualsites.plotsquared.bukkit.util.block; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitBlockUtil; import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper; import com.github.intellectualsites.plotsquared.plot.object.Location; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.world.PatternUtil; import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockTypes; import lombok.Getter; import lombok.Setter; import org.bukkit.Chunk; -import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.ChunkGenerator.BiomeGrid; @@ -22,13 +26,13 @@ import java.util.Arrays; public class GenChunk extends ScopedLocalBlockQueue { public final Biome[] biomes; - public PlotBlock[][] result; + public BlockState[][] result; public BiomeGrid biomeGrid; public Chunk chunk; public String world; - public int cx; - public int cz; - @Getter @Setter private ChunkData cd = null; + public int chunkX; + public int chunkZ; + @Getter @Setter private ChunkData chunkData = null; public GenChunk() { super(null, new Location(null, 0, 0, 0), new Location(null, 15, 255, 15)); @@ -39,7 +43,7 @@ public class GenChunk extends ScopedLocalBlockQueue { if (chunk == null) { World worldObj = BukkitUtil.getWorld(world); if (worldObj != null) { - this.chunk = worldObj.getChunkAt(cx, cz); + this.chunk = worldObj.getChunkAt(chunkX, chunkZ); } } return chunk; @@ -52,15 +56,15 @@ public class GenChunk extends ScopedLocalBlockQueue { public void setChunk(ChunkWrapper wrap) { chunk = null; world = wrap.world; - cx = wrap.x; - cz = wrap.z; + chunkX = wrap.x; + chunkZ = wrap.z; } - @Override public void fillBiome(String biomeName) { + @Override public void fillBiome(BiomeType biomeType) { if (biomeGrid == null) { return; } - Biome biome = Biome.valueOf(biomeName.toUpperCase()); + Biome biome = BukkitAdapter.adapt(biomeType); for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { this.biomeGrid.setBiome(x, z, biome); @@ -68,31 +72,31 @@ public class GenChunk extends ScopedLocalBlockQueue { } } - @Override public void setCuboid(Location pos1, Location pos2, PlotBlock block) { + @Override public void setCuboid(Location pos1, Location pos2, BlockState block) { if (result != null && pos1.getX() == 0 && pos1.getZ() == 0 && pos2.getX() == 15 && pos2.getZ() == 15) { for (int y = pos1.getY(); y <= pos2.getY(); y++) { int layer = y >> 4; - PlotBlock[] data = result[layer]; + BlockState[] data = result[layer]; if (data == null) { - result[layer] = data = new PlotBlock[4096]; + result[layer] = data = new BlockState[4096]; } int start = y << 8; int end = start + 256; Arrays.fill(data, start, end, block); } } - int minx = Math.min(pos1.getX(), pos2.getX()); - int miny = Math.min(pos1.getY(), pos2.getY()); - int minz = Math.min(pos1.getZ(), pos2.getZ()); - int maxx = Math.max(pos1.getX(), pos2.getX()); - int maxy = Math.max(pos1.getY(), pos2.getY()); - int maxz = Math.max(pos1.getZ(), pos2.getZ()); - cd.setRegion(minx, miny, minz, maxx + 1, maxy + 1, maxz + 1, block.to(Material.class)); + int minX = Math.min(pos1.getX(), pos2.getX()); + int minY = Math.min(pos1.getY(), pos2.getY()); + int minZ = Math.min(pos1.getZ(), pos2.getZ()); + int maxX = Math.max(pos1.getX(), pos2.getX()); + int maxY = Math.max(pos1.getY(), pos2.getY()); + int maxZ = Math.max(pos1.getZ(), pos2.getZ()); + chunkData.setRegion(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1, BukkitAdapter.adapt(block)); } - @Override public boolean setBiome(int x, int z, String biome) { - return setBiome(x, z, Biome.valueOf(biome.toUpperCase())); + @Override public boolean setBiome(int x, int z, BiomeType biomeType) { + return setBiome(x, z, BukkitAdapter.adapt(biomeType)); } public boolean setBiome(int x, int z, Biome biome) { @@ -103,21 +107,25 @@ public class GenChunk extends ScopedLocalBlockQueue { return false; } - @Override public boolean setBlock(int x, int y, int z, PlotBlock id) { + @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { + return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z)); + } + + @Override public boolean setBlock(int x, int y, int z, BlockState id) { if (this.result == null) { - this.cd.setBlock(x, y, z, id.to(Material.class)); + this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); return true; } - this.cd.setBlock(x, y, z, id.to(Material.class)); + this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); this.storeCache(x, y, z, id); return true; } - private void storeCache(final int x, final int y, final int z, final PlotBlock id) { + private void storeCache(final int x, final int y, final int z, final BlockState id) { int i = MainUtil.CACHE_I[y][x][z]; - PlotBlock[] v = this.result[i]; + BlockState[] v = this.result[i]; if (v == null) { - this.result[i] = v = new PlotBlock[4096]; + this.result[i] = v = new BlockState[4096]; } int j = MainUtil.CACHE_J[y][x][z]; v[j] = id; @@ -125,33 +133,33 @@ public class GenChunk extends ScopedLocalBlockQueue { @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { if (this.result == null) { - this.cd.setBlock(x, y, z, BukkitAdapter.adapt(id)); + this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); return true; } - this.cd.setBlock(x, y, z, BukkitAdapter.adapt(id)); - this.storeCache(x, y, z, PlotBlock.get(id.getBlockType().getId())); + this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); + this.storeCache(x, y, z, id.toImmutableState()); return true; } - @Override public PlotBlock getBlock(int x, int y, int z) { + @Override public BlockState getBlock(int x, int y, int z) { int i = MainUtil.CACHE_I[y][x][z]; if (result == null) { - return PlotBlock.get(cd.getType(x, y, z)); + return BukkitBlockUtil.get(chunkData.getType(x, y, z)); } - PlotBlock[] array = result[i]; + BlockState[] array = result[i]; if (array == null) { - return PlotBlock.get(""); + return BlockTypes.AIR.getDefaultState(); } int j = MainUtil.CACHE_J[y][x][z]; return array[j]; } public int getX() { - return chunk == null ? cx : chunk.getX(); + return chunk == null ? chunkX : chunk.getX(); } public int getZ() { - return chunk == null ? cz : chunk.getZ(); + return chunk == null ? chunkZ : chunk.getZ(); } @Override public String getWorld() { @@ -170,14 +178,14 @@ public class GenChunk extends ScopedLocalBlockQueue { GenChunk toReturn = new GenChunk(); if (this.result != null) { for (int i = 0; i < this.result.length; i++) { - PlotBlock[] matrix = this.result[i]; + BlockState[] matrix = this.result[i]; if (matrix != null) { - toReturn.result[i] = new PlotBlock[matrix.length]; + toReturn.result[i] = new BlockState[matrix.length]; System.arraycopy(matrix, 0, toReturn.result[i], 0, matrix.length); } } } - toReturn.cd = this.cd; + toReturn.chunkData = this.chunkData; return toReturn; } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java index ce058b691..40d902f8e 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java @@ -7,13 +7,14 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; +import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.UUID; public class DefaultUUIDWrapper extends UUIDWrapper { - @Override public UUID getUUID(PlotPlayer player) { + @NotNull @Override public UUID getUUID(PlotPlayer player) { return ((BukkitPlayer) player).player.getUniqueId(); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java index 8d2726bfd..df19ed711 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java @@ -1,6 +1,5 @@ package com.github.intellectualsites.plotsquared.bukkit.uuid; -import com.github.intellectualsites.plotsquared.bukkit.util.NbtFactory; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; @@ -15,6 +14,13 @@ import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.google.common.collect.HashBiMap; import com.google.common.collect.Sets; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.NBTInputStream; +import com.sk89q.jnbt.Tag; +import java.io.BufferedInputStream; +import java.io.FileNotFoundException; +import java.util.Map; +import java.util.zip.GZIPInputStream; import org.bukkit.Bukkit; import org.bukkit.World; @@ -38,6 +44,16 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { return super.startCaching(whenDone) && cache(whenDone); } + private Tag readTag(File file) throws IOException { + // Don't chain the creation of the GZIP stream and the NBT stream, because their + // constructors may throw an IOException. + try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); + GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream); + NBTInputStream nbtInputStream = new NBTInputStream(gzipInputStream)) { + return nbtInputStream.readNamedTag().getTag(); + } + } + public boolean cache(final Runnable whenDone) { final File container = Bukkit.getWorldContainer(); List worlds = Bukkit.getWorlds(); @@ -48,7 +64,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { world = worlds.get(0).getName(); } TaskManager.runTaskAsync(() -> { - PlotSquared.debug(Captions.PREFIX + "&6Starting player data caching for: " + world); + PlotSquared.debug(Captions.PREFIX + "Starting player data caching for: " + world); File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt"); if (uuidFile.exists()) { try { @@ -83,7 +99,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { HashBiMap toAdd = HashBiMap.create(new HashMap<>()); if (Settings.UUID.NATIVE_UUID_PROVIDER) { HashSet all = UUIDHandler.getAllUUIDS(); - PlotSquared.debug("&aFast mode UUID caching enabled!"); + PlotSquared.debug("Fast mode UUID caching enabled!"); File playerDataFolder = new File(container, world + File.separator + "playerdata"); String[] dat = playerDataFolder.list(new DatFileFilter()); boolean check = all.isEmpty(); @@ -94,18 +110,18 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { UUID uuid = UUID.fromString(s); if (check || all.remove(uuid)) { File file = new File(playerDataFolder, current); - NbtFactory.NbtCompound compound = NbtFactory - .fromStream(new FileInputStream(file), - NbtFactory.StreamOptions.GZIP_COMPRESSION); + CompoundTag compound = (CompoundTag) readTag(file); if (!compound.containsKey("bukkit")) { PlotSquared.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\""); } else { - NbtFactory.NbtCompound bukkit = - (NbtFactory.NbtCompound) compound.get("bukkit"); - String name = (String) bukkit.get("lastKnownName"); - long last = (long) bukkit.get("lastPlayed"); - long first = (long) bukkit.get("firstPlayed"); + Map compoundMap = compound.getValue(); + CompoundTag bukkit = (CompoundTag) compoundMap.get("bukkit"); + Map bukkitMap = bukkit.getValue(); + String name = + (String) bukkitMap.get("lastKnownName").getValue(); + long last = (long) bukkitMap.get("lastPlayed").getValue(); + long first = (long) bukkitMap.get("firstPlayed").getValue(); if (ExpireManager.IMP != null) { ExpireManager.IMP.storeDate(uuid, last); ExpireManager.IMP.storeAccountAge(uuid, last - first); @@ -167,27 +183,26 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { if (!file.exists()) { continue; } - NbtFactory.NbtCompound compound = NbtFactory - .fromStream(new FileInputStream(file), - NbtFactory.StreamOptions.GZIP_COMPRESSION); + CompoundTag compound = (CompoundTag) readTag(file); if (!compound.containsKey("bukkit")) { PlotSquared.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\""); } else { - NbtFactory.NbtCompound bukkit = - (NbtFactory.NbtCompound) compound.get("bukkit"); - String name = (String) bukkit.get("lastKnownName"); + Map compoundMap = compound.getValue(); + CompoundTag bukkit = (CompoundTag) compoundMap.get("bukkit"); + Map bukkitMap = bukkit.getValue(); + String name = (String) bukkitMap.get("lastKnownName").getValue(); StringWrapper wrap = new StringWrapper(name); if (!toAdd.containsKey(wrap)) { - long last = (long) bukkit.get("lastPlayed"); - long first = (long) bukkit.get("firstPlayed"); + long last = (long) bukkitMap.get("lastPlayed").getValue(); + long first = (long) bukkitMap.get("firstPlayed").getValue(); if (Settings.UUID.OFFLINE) { if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase() .equals(name)) { uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); } else { - long most = (long) compound.get("UUIDMost"); - long least = (long) compound.get("UUIDLeast"); + long most = (long) compoundMap.get("UUIDMost").getValue(); + long least = (long) compoundMap.get("UUIDLeast").getValue(); uuid = new UUID(most, least); } } @@ -210,14 +225,22 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } if (getUUIDMap().isEmpty()) { - for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper.getOfflinePlayers()) { - long last = op.getLastPlayed(); + for (OfflinePlotPlayer offlinePlotPlayer : FileUUIDHandler.this.uuidWrapper + .getOfflinePlayers()) { + long last = offlinePlotPlayer.getLastPlayed(); if (last != 0) { - String name = op.getName(); + String name = offlinePlotPlayer.getName(); StringWrapper wrap = new StringWrapper(name); if (!toAdd.containsKey(wrap)) { - UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op); - toAdd.put(wrap, uuid); + UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(offlinePlotPlayer); + if (toAdd.containsValue(uuid)) { + StringWrapper duplicate = toAdd.inverse().get(uuid); + PlotSquared.debug( + "The UUID: " + uuid.toString() + " is already mapped to " + + duplicate + + "\n It cannot be added to the Map with a key of " + wrap); + } + toAdd.putIfAbsent(wrap, uuid); if (ExpireManager.IMP != null) { ExpireManager.IMP.storeDate(uuid, last); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java index 55e2039a0..a152445a8 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java @@ -4,14 +4,15 @@ import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.google.common.base.Charsets; import org.bukkit.OfflinePlayer; +import org.jetbrains.annotations.NotNull; +import java.util.Objects; import java.util.UUID; public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper { - @Override public UUID getUUID(PlotPlayer player) { - return UUID.nameUUIDFromBytes( - ("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); + @NotNull @Override public UUID getUUID(PlotPlayer player) { + return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); } @Override public UUID getUUID(OfflinePlotPlayer player) { @@ -21,7 +22,7 @@ public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper { @Override public UUID getUUID(OfflinePlayer player) { return UUID.nameUUIDFromBytes( - ("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); + ("OfflinePlayer:" + Objects.requireNonNull(player.getName()).toLowerCase()).getBytes(Charsets.UTF_8)); } @Override public UUID getUUID(String name) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java index 6686c09f1..306f67e4e 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java @@ -13,6 +13,7 @@ import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.Server; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -33,9 +34,8 @@ public class OfflineUUIDWrapper extends UUIDWrapper { } } - @Override public UUID getUUID(PlotPlayer player) { - return UUID - .nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); + @NotNull @Override public UUID getUUID(PlotPlayer player) { + return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); } @Override public UUID getUUID(OfflinePlotPlayer player) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java index 86cd9ae0d..ca682366e 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java @@ -31,13 +31,13 @@ import java.util.ArrayDeque; import java.util.Collections; import java.util.HashMap; import java.util.UUID; +import java.util.concurrent.TimeUnit; public class SQLUUIDHandler extends UUIDHandlerImplementation { final int MAX_REQUESTS = 500; private final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; - private final int INTERVAL = 12000; private final JSONParser jsonParser = new JSONParser(); private final SQLite sqlite; @@ -52,8 +52,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } try (PreparedStatement stmt = getConnection().prepareStatement( - "CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username)" - + ')')) { + "CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username))")) { stmt.execute(); } catch (SQLException e) { e.printStackTrace(); @@ -133,7 +132,10 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { "Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)"); } try { - Thread.sleep(INTERVAL * 50); + //Mojang allows requests every 10 minutes according to https://wiki.vg/Mojang_API + //15 Minutes is chosen here since system timers are not always precise + //and it should provide enough time where Mojang won't block requests. + TimeUnit.MINUTES.sleep(15); } catch (InterruptedException e) { e.printStackTrace(); break; @@ -142,7 +144,6 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { if (whenDone != null) { whenDone.run(); } - return; }); }); } catch (SQLException e) { @@ -235,7 +236,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { return false; } - private class SQLUUIDHandlerException extends RuntimeException { + private static class SQLUUIDHandlerException extends RuntimeException { SQLUUIDHandlerException(String s, Throwable c) { super("SQLUUIDHandler caused an exception: " + s, c); diff --git a/Bukkit/src/main/resources/plugin.yml b/Bukkit/src/main/resources/plugin.yml index d9cd4e9d4..797d21ba3 100644 --- a/Bukkit/src/main/resources/plugin.yml +++ b/Bukkit/src/main/resources/plugin.yml @@ -1,11 +1,11 @@ name: ${name} main: com.github.intellectualsites.plotsquared.bukkit.BukkitMain -api-version: 1.13 -version: ${version} +api-version: "1.13" +version: "${version}" load: STARTUP -description: > - Easy, yet powerful Plot World generation and management. +description: "Easy, yet powerful Plot World generation and management." authors: [Citymonstret, Empire92, MattBDev, dordsor21] +website: https://github.com/IntellectualSites/ softdepend: [BarAPI, CameraAPI, Vault] loadbefore: [MultiWorld, Multiverse-Core] depend: [WorldEdit] @@ -126,6 +126,7 @@ permissions: plots.toggle: true plots.toggle.titles: true plots.toggle.chat: true + plots.toggle.time: true plots.set.biome: true plots.set.home: true plots.set.alias: true @@ -251,9 +252,6 @@ permissions: plotme.limit.10: children: plots.plot.10: true - plotme.admin.home.other: - children: - plots.plot.: true plotme.admin.clear: children: plots.admin.command.clear: true diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..5a97f91a9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,9 @@ +# Contributing +If you feel like you can improve the plugin any way, then you are more than welcome to contribute to PlotSquared. It would be highly appreciated if you made sure to test your code before committing it, as it will save us a lot of time and effort. + +### Code Style +If you are planning to commit any changes to the project, it would be highly appreciated if you were to follow the project code style conventions. To make this easier we have provided settings that can be imported into your IDE. + +Eclipse: `Window > Preferences > Java > Code Style > Formatter` Press `Import` and select `...path/to/project/code_style.xml` + +IntelliJ: `File > Settings > Editor > Code Style`. Next to "Scheme" there is a cog wheel, press that and then `Import Scheme > IntelliJ IDEA Code Style XML` and then select `..path/to/project/code_style.xml` diff --git a/Core/build.gradle b/Core/build.gradle index 82f6abd3a..4d57e4c86 100644 --- a/Core/build.gradle +++ b/Core/build.gradle @@ -1,29 +1,31 @@ repositories { - maven { url 'https://jitpack.io' } + maven { url = "https://jitpack.io" } } +def textVersion = "3.0.2" dependencies { - implementation 'org.yaml:snakeyaml:1.23' - //keep inline with Minecraft which uses gson 2.8.0 - implementation 'com.google.code.gson:gson:2.8.0' - implementation("org.projectlombok:lombok:1.18.6") - compileOnly("org.projectlombok:lombok:1.18.6") - testCompileOnly("org.projectlombok:lombok:1.18.6") - annotationProcessor("org.projectlombok:lombok:1.18.6") - testAnnotationProcessor("org.projectlombok:lombok:1.18.6") - - implementation 'com.github.Sauilitired:Jenkins4J:2.0-SNAPSHOT' - implementation 'com.squareup.okhttp3:okhttp:3.14.0' - implementation 'com.squareup.okio:okio:2.2.2' - implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.30' + implementation("org.yaml:snakeyaml:1.25") + implementation("com.google.code.gson:gson:2.8.6") { + because("Minecraft uses GSON 2.8.0") + force = true + } + implementation("org.projectlombok:lombok:1.18.10") + compileOnly("org.projectlombok:lombok:1.18.8") + testCompileOnly("org.projectlombok:lombok:1.18.8") + annotationProcessor("org.projectlombok:lombok:1.18.8") + testAnnotationProcessor("org.projectlombok:lombok:1.18.8") + implementation("com.github.Sauilitired:Jenkins4J:2.0-SNAPSHOT") + implementation("com.squareup.okhttp3:okhttp:4.2.2") + implementation("com.squareup.okio:okio:2.4.1") + implementation("org.jetbrains.kotlin:kotlin-stdlib:1.3.61") } sourceCompatibility = 1.8 targetCompatibility = 1.8 processResources { - from('src/main/resources') { - include 'plugin.properties' + from("src/main/resources") { + include "plugin.properties" expand( version: "${project.parent.version}", name: project.parent.name, @@ -33,22 +35,23 @@ processResources { } } -jar.setArchiveName("PlotSquared-API-${project.parent.version}.jar") -jar.destinationDir = file '../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/' + project.parent.version +//noinspection GroovyAssignabilityCheck +jar.archiveFileName = "PlotSquared-API-${project.parent.version}.jar" +jar.destinationDirectory = file("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/" + project.parent.version) task createPom { doLast { pom { project { - groupId 'com.github.intellectualsites.plotsquared' - artifactId 'PlotSquared-API' - version project.parent.version + groupId = "com.github.intellectualsites.plotsquared" + artifactId = "PlotSquared-API" + version = project.parent.version } }.writeTo("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/${project.parent.version}/PlotSquared-API-${project.parent.version}.pom") pom { project { - groupId 'com.github.intellectualsites.plotsquared' - artifactId 'PlotSquared-API' - version 'latest' + groupId = "com.github.intellectualsites.plotsquared" + artifactId = "PlotSquared-API" + version = "latest" } }.writeTo("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/latest/PlotSquared-API-latest.pom") } @@ -57,13 +60,30 @@ task createPom { task copyFiles { doLast { copy { - from "../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/${project.parent.version}/" - into '../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/latest/' - include('*.jar') - rename("PlotSquared-API-${project.parent.version}.jar", 'PlotSquared-API-latest.jar') + from("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/${project.parent.version}/") + into("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/latest/") + include("*.jar") + rename("PlotSquared-API-${project.parent.version}.jar", "PlotSquared-API-latest.jar") } } } +shadowJar { + dependencies { + include(dependency("net.kyori:text-api:3.0.2")) + include(dependency("net.kyori:text-serializer-gson:3.0.2")) + include(dependency("net.kyori:text-serializer-legacy:3.0.2")) + include(dependency("net.kyori:text-serializer-plain:3.0.2")) + } + relocate('net.kyori.text', 'com.github.intellectualsites.plotsquared.formatting.text') +} + +shadowJar.doLast { + task -> + ant.checksum file: task.archivePath +} + +build.dependsOn(shadowJar) + build.finalizedBy(copyFiles) copyFiles.dependsOn(createPom) diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/api/PlotAPI.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/api/PlotAPI.java index d2b4e7343..610362953 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/api/PlotAPI.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/api/PlotAPI.java @@ -165,7 +165,7 @@ import java.util.UUID; * @see Captions */ public void sendConsoleMessage(Captions caption) { - sendConsoleMessage(caption.s()); + sendConsoleMessage(caption.getTranslated()); } /** diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Argument.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Argument.java index dd5221a3a..7ae1985ce 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Argument.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Argument.java @@ -33,7 +33,7 @@ public abstract class Argument { } }; public static final Argument PlayerName = - new Argument("PlayerName", "Dinnerbone") { + new Argument("PlayerName", "") { @Override public String parse(String in) { return in.length() <= 16 ? in : null; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java index bf803d712..691daa93e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java @@ -10,12 +10,25 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.StringComparison; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; public abstract class Command { @@ -33,19 +46,19 @@ public abstract class Command { private RequiredType required; private String usage; private String description; - private String perm; + private String permission; private boolean confirmation; private CommandCategory category; private Argument[] arguments; - public Command(Command parent, boolean isStatic, String id, String perm, RequiredType required, - CommandCategory cat) { + public Command(Command parent, boolean isStatic, String id, String permission, + RequiredType required, CommandCategory category) { this.parent = parent; this.isStatic = isStatic; this.id = id; - this.perm = perm; + this.permission = permission; this.required = required; - this.category = cat; + this.category = category; this.aliases = Arrays.asList(id); if (this.parent != null) { this.parent.register(this); @@ -68,14 +81,16 @@ public abstract class Command { && types[2] == String[].class && types[3] == RunnableVal3.class && types[4] == RunnableVal2.class) { Command tmp = new Command(this, true) { - @Override public void execute(PlotPlayer player, String[] args, + @Override public CompletableFuture execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { try { method.invoke(Command.this, this, player, args, confirm, whenDone); + return CompletableFuture.completedFuture(true); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } + return CompletableFuture.completedFuture(false); } }; tmp.init(method.getAnnotation(CommandDeclaration.class)); @@ -147,13 +162,13 @@ public abstract class Command { public void init(CommandDeclaration declaration) { this.id = declaration.command(); - this.perm = declaration.permission(); + this.permission = declaration.permission(); this.required = declaration.requiredType(); this.category = declaration.category(); - HashMap options = new HashMap<>(); List aliasOptions = new ArrayList<>(); aliasOptions.add(this.id); aliasOptions.addAll(Arrays.asList(declaration.aliases())); + HashMap options = new HashMap<>(); options.put("aliases", aliasOptions); options.put("description", declaration.description()); options.put("usage", declaration.usage()); @@ -197,8 +212,8 @@ public abstract class Command { } public String getPermission() { - if (this.perm != null && !this.perm.isEmpty()) { - return this.perm; + if (this.permission != null && !this.permission.isEmpty()) { + return this.permission; } if (this.parent == null) { return "plots.use"; @@ -237,29 +252,31 @@ public abstract class Command { if (page < totalPages && page > 0) { // Back | Next new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ") .color("$3").text("->").color("$1").command(baseCommand + " " + (page + 2)) - .text(Captions.CLICKABLE.s()).color("$2").send(player); + .text(Captions.CLICKABLE.getTranslated()).color("$2").send(player); return; } if (page == 0 && totalPages != 0) { // Next new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1") - .command(baseCommand + " " + (0 + 2)).text(Captions.CLICKABLE.s()).color("$2") + .command(baseCommand + " " + 2).text(Captions.CLICKABLE.getTranslated()).color("$2") .send(player); return; } - if (page == totalPages && totalPages != 0) { // Back + if (totalPages != 0) { // Back new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ") - .color("$3").text("->").color("$3").text(Captions.CLICKABLE.s()).color("$2") + .color("$3").text("->").color("$3").text(Captions.CLICKABLE.getTranslated()) + .color("$2") .send(player); } } /** * @param player Caller - * @param args Arguments + * @param args Arguments * @param confirm Instance, Success, Failure - * @return + * @return CompletableFuture true if the command executed fully, false in + * any other case */ - public void execute(PlotPlayer player, String[] args, + public CompletableFuture execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { if (args.length == 0 || args[0] == null) { @@ -268,18 +285,18 @@ public abstract class Command { } else { Captions.COMMAND_SYNTAX.send(player, getUsage()); } - return; + return CompletableFuture.completedFuture(false); } if (this.allCommands.isEmpty()) { player.sendMessage( "Not Implemented: https://github.com/IntellectualSites/PlotSquared/issues/new"); - return; + return CompletableFuture.completedFuture(false); } Command cmd = getCommand(args[0]); if (cmd == null) { if (this.parent != null) { Captions.COMMAND_SYNTAX.send(player, getUsage()); - return; + return CompletableFuture.completedFuture(false); } // Help command try { @@ -289,7 +306,7 @@ public abstract class Command { // This will default certain syntax to the help command // e.g. /plot, /plot 1, /plot claiming MainCommand.getInstance().help.execute(player, args, null, null); - return; + return CompletableFuture.completedFuture(false); } catch (IllegalArgumentException ignored) { } // Command recommendation @@ -298,13 +315,16 @@ public abstract class Command { if (commands.isEmpty()) { MainUtil.sendMessage(player, Captions.DID_YOU_MEAN, MainCommand.getInstance().help.getUsage()); - return; + return CompletableFuture.completedFuture(false); } - String[] allargs = - Arrays.stream(args).map(String::toLowerCase).distinct().toArray(String[]::new); + HashSet setArgs = new HashSet<>(args.length); + for (String arg : args) { + setArgs.add(arg.toLowerCase()); + } + String[] allArgs = setArgs.toArray(new String[0]); int best = 0; for (Command current : commands) { - int match = getMatch(allargs, current); + int match = getMatch(allArgs, current); if (match > best) { cmd = current; } @@ -313,17 +333,18 @@ public abstract class Command { cmd = new StringComparison<>(args[0], this.allCommands).getMatchObject(); } MainUtil.sendMessage(player, Captions.DID_YOU_MEAN, cmd.getUsage()); - return; + return CompletableFuture.completedFuture(false); } String[] newArgs = Arrays.copyOfRange(args, 1, args.length); if (!cmd.checkArgs(player, newArgs) || !cmd.canExecute(player, true)) { - return; + return CompletableFuture.completedFuture(false); } try { cmd.execute(player, newArgs, confirm, whenDone); } catch (CommandException e) { e.perform(player); } + return CompletableFuture.completedFuture(true); } public boolean checkArgs(CommandCaller player, String[] args) { @@ -375,7 +396,7 @@ public abstract class Command { String[] split = usage[i].split("\\|| |\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/"); for (String aSplit : split) { for (String arg : args) { - if (StringMan.isEqualIgnoreCase(arg, aSplit)) { + if (arg.equalsIgnoreCase(aSplit)) { count += 5 - i + require; } } @@ -477,7 +498,7 @@ public abstract class Command { return null; } List result = new ArrayList<>(); - int index = input.length - (space ? 0 : 1); + int index = input.length; for (String arg : args) { arg = arg.replace(getCommandString() + " ", ""); String[] split = arg.split(" "); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationOptions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationOptions.java index 5d13920e4..81c96196d 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationOptions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationOptions.java @@ -6,7 +6,6 @@ package com.github.intellectualsites.plotsquared.configuration; */ class ConfigurationOptions { private final Configuration configuration; - private char pathSeparator = '.'; private boolean copyDefaults = false; protected ConfigurationOptions(Configuration configuration) { @@ -26,28 +25,12 @@ class ConfigurationOptions { * Gets the char that will be used to separate {@link * ConfigurationSection}s. * - *

This value does not affect how the {@link Configuration} is stored, - * only in how you access the data. The default value is '.'. + *

This value is always '.'. * * @return Path separator */ - public char pathSeparator() { - return pathSeparator; - } - - /** - * Sets the char that will be used to separate {@link - * ConfigurationSection}s. - * - *

This value does not affect how the {@link Configuration} is stored, - * only in how you access the data. The default value is '.'. - * - * @param value Path separator - * @return This object, for chaining - */ - public ConfigurationOptions pathSeparator(char value) { - pathSeparator = value; - return this; + char pathSeparator() { + return '.'; } /** diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfigurationOptions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfigurationOptions.java index 971ea1e70..22f9d751b 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfigurationOptions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfigurationOptions.java @@ -18,8 +18,4 @@ public class MemoryConfigurationOptions extends ConfigurationOptions { return this; } - @Override public MemoryConfigurationOptions pathSeparator(char value) { - super.pathSeparator(value); - return this; - } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemorySection.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemorySection.java index 0f87931f4..14233b758 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemorySection.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemorySection.java @@ -1,6 +1,11 @@ package com.github.intellectualsites.plotsquared.configuration; -import java.util.*; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; /** * A type of {@link ConfigurationSection} that is stored in memory. diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java index a56c65901..e8123cfc9 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java @@ -4,7 +4,16 @@ import com.github.intellectualsites.plotsquared.configuration.Configuration; import com.github.intellectualsites.plotsquared.configuration.InvalidConfigurationException; import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguration; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.stream.Collectors; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfigurationOptions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfigurationOptions.java index a216d0566..6eb99bb6e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfigurationOptions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfigurationOptions.java @@ -25,11 +25,6 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { return this; } - @Override public FileConfigurationOptions pathSeparator(char value) { - super.pathSeparator(value); - return this; - } - /** * Gets the header that will be applied to the top of the saved output. * diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfigurationOptions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfigurationOptions.java index a17bc3538..a7e71cdaf 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfigurationOptions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfigurationOptions.java @@ -5,7 +5,6 @@ package com.github.intellectualsites.plotsquared.configuration.file; * YamlConfiguration}. */ public class YamlConfigurationOptions extends FileConfigurationOptions { - private int indent = 2; YamlConfigurationOptions(YamlConfiguration configuration) { super(configuration); @@ -20,11 +19,6 @@ public class YamlConfigurationOptions extends FileConfigurationOptions { return this; } - @Override public YamlConfigurationOptions pathSeparator(char value) { - super.pathSeparator(value); - return this; - } - @Override public YamlConfigurationOptions header(String value) { super.header(value); return this; @@ -42,27 +36,8 @@ public class YamlConfigurationOptions extends FileConfigurationOptions { * * @return How much to indent by */ - public int indent() { - return indent; + int indent() { + return 2; } - /** - * Sets how much spaces should be used to indent each line. - * - *

The minimum value this may be is 2, and the maximum is 9. - * - * @param value New indent - * @return This object, for chaining - */ - public YamlConfigurationOptions indent(int value) { - if (value < 2) { - throw new IllegalArgumentException("Indent must be at least 2 characters"); - } - if (value > 9) { - throw new IllegalArgumentException("Indent cannot be greater than 9 characters"); - } - - indent = value; - return this; - } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerialization.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerialization.java index 0783b4af5..cb1abd54a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerialization.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerialization.java @@ -212,10 +212,15 @@ public class ConfigurationSerialization { return result; } } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ex) { - Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, - "Could not call method '" + method.toString() + "' of " + this.clazz - + " for deserialization", - ex instanceof InvocationTargetException ? ex.getCause() : ex); + if (ex instanceof InvocationTargetException) { + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call method '" + method.toString() + "' of " + this.clazz + + " for deserialization", ex.getCause()); + } else { + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call method '" + method.toString() + "' of " + this.clazz + + " for deserialization", ex); + } } return null; @@ -226,10 +231,15 @@ public class ConfigurationSerialization { try { return ctor.newInstance(args); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) { - Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, - "Could not call constructor '" + ctor.toString() + "' of " + this.clazz - + " for deserialization", - ex instanceof InvocationTargetException ? ex.getCause() : ex); + if (ex instanceof InvocationTargetException) { + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call constructor '" + ctor.toString() + "' of " + this.clazz + + " for deserialization", ex.getCause()); + } else { + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call constructor '" + ctor.toString() + "' of " + this.clazz + + " for deserialization", ex); + } } return null; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONObject.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONObject.java index cd67bb158..965e95644 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONObject.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONObject.java @@ -7,8 +7,15 @@ import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.*; +import java.util.Collection; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; import java.util.Map.Entry; +import java.util.ResourceBundle; +import java.util.Set; import java.util.stream.IntStream; /** @@ -554,7 +561,9 @@ public class JSONObject { return new JSONObject((Map) object); } Package objectPackage = object.getClass().getPackage(); + String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; + if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || ( object.getClass().getClassLoader() == null)) { return object.toString(); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONTokener.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONTokener.java index 290b9ea0b..195ceeb5d 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONTokener.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONTokener.java @@ -1,6 +1,11 @@ package com.github.intellectualsites.plotsquared.json; -import java.io.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; /** * A JSONTokener takes a source string and extracts characters and tokens from it. It is used by the JSONObject and diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java index 6ca241dcd..48f87a96e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java @@ -4,13 +4,24 @@ import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; import com.github.intellectualsites.plotsquared.plot.logger.ILogger; -import com.github.intellectualsites.plotsquared.plot.object.BlockRegistry; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.ChatManager; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.InventoryUtil; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandlerImplementation; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.github.intellectualsites.plotsquared.plot.util.block.QueueProvider; +import com.sk89q.worldedit.extension.platform.Actor; +import org.jetbrains.annotations.NotNull; import java.io.File; import java.util.List; +import java.util.Map; public interface IPlotMain extends ILogger { @@ -62,12 +73,12 @@ public interface IPlotMain extends ILogger { */ String getPluginVersionString(); - String getPluginName(); + default String getPluginName() { + return "PlotSquared"; + } /** * Gets the version of Minecraft that is running. - * - * @return */ int[] getServerVersion(); @@ -100,7 +111,7 @@ public interface IPlotMain extends ILogger { /** * The task manager will run and manage Minecraft tasks. * - * @return + * @return the PlotSquared task manager */ TaskManager getTaskManager(); @@ -137,49 +148,39 @@ public interface IPlotMain extends ILogger { /** * Gets the economy provider. * - * @return + * @return the PlotSquared economy manager */ EconHandler getEconomyHandler(); /** * Gets the {@link QueueProvider} class. - * - * @return */ QueueProvider initBlockQueue(); /** * Gets the {@link WorldUtil} class. - * - * @return */ WorldUtil initWorldUtil(); /** * Gets the EventUtil class. - * - * @return */ EventUtil initEventUtil(); /** * Gets the chunk manager. * - * @return + * @return the PlotSquared chunk manager */ ChunkManager initChunkManager(); /** * Gets the {@link SetupUtils} class. - * - * @return */ SetupUtils initSetupUtils(); /** * Gets {@link HybridUtils} class. - * - * @return */ HybridUtils initHybridUtils(); @@ -198,32 +199,28 @@ public interface IPlotMain extends ILogger { /** * Gets the {@link UUIDHandlerImplementation} which will cache and * provide UUIDs. - * - * @return */ UUIDHandlerImplementation initUUIDHandler(); /** * Gets the {@link InventoryUtil} class (used for implementation specific * inventory guis). - * - * @return */ InventoryUtil initInventoryUtil(); /** * Unregisters a {@link PlotPlayer} from cache e.g. if they have logged off. * - * @param player + * @param player the player to remove */ void unregister(PlotPlayer player); /** * Gets the generator wrapper for a world (world) and generator (name). * - * @param world - * @param name - * @return + * @param world the world to get the generator from + * @param name the name of the generator + * @return the generator being used for the provided world */ GeneratorWrapper getGenerator(String world, String name); @@ -231,7 +228,7 @@ public interface IPlotMain extends ILogger { /** * Register the chunk processor which will clean out chunks that have too - * many blockstates or entities. + * many block states or entities. */ void registerChunkProcessor(); @@ -246,19 +243,9 @@ public interface IPlotMain extends ILogger { * * @return Default implementation generator */ - IndependentPlotGenerator getDefaultGenerator(); + @NotNull IndependentPlotGenerator getDefaultGenerator(); - /** - * Gets the class that will manage player titles. - * - * @return - */ - AbstractTitle initTitleManager(); - - List getPluginIds(); - - BlockRegistry getBlockRegistry(); - - LegacyMappings getLegacyMappings(); + List, Boolean>> getPluginIds(); + Actor getConsole(); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java index 9dfbf2ffb..1736edf6f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java @@ -1,6 +1,6 @@ package com.github.intellectualsites.plotsquared.plot; public enum Platform { - Bukkit, Sponge, Spigot + Bukkit, Sponge, Spigot, Paper } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java index 7c94060fd..880f2aaab 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java @@ -20,30 +20,78 @@ import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; import com.github.intellectualsites.plotsquared.plot.listener.WESubscriber; import com.github.intellectualsites.plotsquared.plot.logger.ILogger; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.BlockBucket; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotCluster; +import com.github.intellectualsites.plotsquared.plot.object.PlotFilter; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.StringWrapper; import com.github.intellectualsites.plotsquared.plot.object.worlds.DefaultPlotAreaManager; import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager; import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.ChatManager; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.CommentManager; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.InventoryUtil; +import com.github.intellectualsites.plotsquared.plot.util.LegacyConverter; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.UpdateUtility; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpiryTask; import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.regions.CuboidRegion; import lombok.Getter; import lombok.NonNull; import lombok.Setter; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.sql.SQLException; -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; import java.util.function.Consumer; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -54,8 +102,7 @@ import java.util.zip.ZipInputStream; * An implementation of the core, with a static getter for easy access. */ @SuppressWarnings({"unused", "WeakerAccess"}) public class PlotSquared { - private static final Set EMPTY_SET = Collections. - unmodifiableSet(Collections.emptySet()); + private static final Set EMPTY_SET = Collections.unmodifiableSet(Collections.emptySet()); private static PlotSquared instance; // Implementation public final IPlotMain IMP; @@ -106,7 +153,7 @@ import java.util.zip.ZipInputStream; // // Register configuration serializable classes // - ConfigurationSerialization.registerClass(PlotBlock.class, "PlotBlock"); +// ConfigurationSerialization.registerClass(BlockState.class, "BlockState"); ConfigurationSerialization.registerClass(BlockBucket.class, "BlockBucket"); try { @@ -188,8 +235,6 @@ import java.util.zip.ZipInputStream; ChunkManager.manager = this.IMP.initChunkManager(); // Schematic handler SchematicHandler.manager = this.IMP.initSchematicHandler(); - // Titles - AbstractTitle.TITLE_CLASS = this.IMP.initTitleManager(); // Chat ChatManager.manager = this.IMP.initChatManager(); // Commands @@ -200,7 +245,7 @@ import java.util.zip.ZipInputStream; if (Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) { try { if (this.IMP.initWorldEdit()) { - PlotSquared.debug(IMP.getPluginName() + " hooked into WorldEdit."); + PlotSquared.log(Captions.PREFIX + "&6" + IMP.getPluginName() + " hooked into WorldEdit."); this.worldedit = WorldEdit.getInstance(); WorldEdit.getInstance().getEventBus().register(new WESubscriber()); if (Settings.Enabled_Components.COMMANDS) { @@ -219,21 +264,6 @@ import java.util.zip.ZipInputStream; .runTask(() -> EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler()); } -/* // Check for updates - if (Settings.Enabled_Components.UPDATER) { - updater = new Updater(); - TaskManager.IMP.taskAsync(new Runnable() { - @Override public void run() { - updater.update(getPlatform(), getVersion()); - } - }); - TaskManager.IMP.taskRepeatAsync(new Runnable() { - @Override public void run() { - updater.update(getPlatform(), getVersion()); - } - }, 36000); - }*/ - // World generators: final ConfigurationSection section = this.worlds.getConfigurationSection("worlds"); if (section != null) { @@ -251,13 +281,14 @@ import java.util.zip.ZipInputStream; continue; } if (!WorldUtil.IMP.isWorld(world) && !world.equals("*")) { - debug( - "&c`" + world + "` was not properly loaded - " + IMP.getPluginName() + debug("`" + world + "` was not properly loaded - " + IMP.getPluginName() + " will now try to load it properly: "); debug( - "&8 - &7Are you trying to delete this world? Remember to remove it from the settings.yml, bukkit.yml and multiverse worlds.yml"); + " - Are you trying to delete this world? Remember to remove it from the worlds.yml, bukkit.yml and multiverse worlds.yml"); debug( - "&8 - &7Your world management plugin may be faulty (or non existent)"); + " - Your world management plugin may be faulty (or non existent)"); + debug( + " This message may also be a false positive and could be ignored."); PlotSquared.this.IMP.setGenerator(world); } } @@ -268,12 +299,12 @@ import java.util.zip.ZipInputStream; copyFile("addplots.js", Settings.Paths.SCRIPTS); copyFile("addsigns.js", Settings.Paths.SCRIPTS); copyFile("automerge.js", Settings.Paths.SCRIPTS); + copyFile("fixborders.js", Settings.Paths.SCRIPTS); copyFile("furthest.js", Settings.Paths.SCRIPTS); copyFile("mycommand.js", Settings.Paths.SCRIPTS); copyFile("setbiomes.js", Settings.Paths.SCRIPTS); copyFile("start.js", Settings.Paths.SCRIPTS); copyFile("town.template", Settings.Paths.TEMPLATES); - copyFile("skyblock.template", Settings.Paths.TEMPLATES); copyFile("bridge.template", Settings.Paths.TEMPLATES); copyFile("de-DE.yml", Settings.Paths.TRANSLATIONS); copyFile("es-ES.yml", Settings.Paths.TRANSLATIONS); @@ -286,7 +317,8 @@ import java.util.zip.ZipInputStream; e.printStackTrace(); } - PlotSquared.log(Captions.ENABLED.f(IMP.getPluginName())); + PlotSquared.log(Captions.PREFIX + Captions + .format(Captions.ENABLED.getTranslated(), IMP.getPluginName())); } /** @@ -616,9 +648,7 @@ import java.util.zip.ZipInputStream; */ private void sortPlotsByHash(Plot[] input) { List[] bucket = new ArrayList[32]; - for (int i = 0; i < bucket.length; i++) { - bucket[i] = new ArrayList<>(); - } + Arrays.fill(bucket, new ArrayList<>()); boolean maxLength = false; int placement = 1; while (!maxLength) { @@ -1088,7 +1118,7 @@ import java.util.zip.ZipInputStream; } // Conventional plot generator PlotArea plotArea = plotGenerator.getNewPlotArea(world, null, null, null); - PlotManager plotManager = plotGenerator.getNewPlotManager(); + PlotManager plotManager = plotArea.getPlotManager(); PlotSquared.log(Captions.PREFIX + "&aDetected world load for '" + world + "'"); PlotSquared .log(Captions.PREFIX + "&3 - generator: &7" + baseGenerator + ">" + plotGenerator); @@ -1193,7 +1223,7 @@ import java.util.zip.ZipInputStream; "Invalid type for multi-area world. Expected `2`, got `" + 1 + "`"); } for (String areaId : areasSection.getKeys(false)) { - PlotSquared.log(Captions.PREFIX + "&3 - " + areaId); + PlotSquared.log(Captions.PREFIX + " - " + areaId); String[] split = areaId.split("(?<=[^;-])-"); if (split.length != 3) { throw new IllegalArgumentException("Invalid Area identifier: " + areaId @@ -1291,7 +1321,7 @@ import java.util.zip.ZipInputStream; .filter(validArgument -> args.toLowerCase(Locale.ENGLISH).contains(validArgument)) .count(); - String[] split = args.toLowerCase(Locale.ENGLISH).split(","); + String[] split = args.toLowerCase(Locale.ENGLISH).split(",(?![^\\(\\[]*[\\]\\)])"); if (split.length > expected) { // This means we have multi-block block buckets @@ -1333,8 +1363,8 @@ import java.util.zip.ZipInputStream; } String key = pair[0].toLowerCase(); String value = pair[1]; - String base = "worlds." + world + "."; try { + String base = "worlds." + world + "."; switch (key) { case "s": case "size": @@ -1620,7 +1650,7 @@ import java.util.zip.ZipInputStream; this.version = PlotVersion.tryParse(versionString, commitString, dateString); Settings.DATE = new Date(100 + version.year, version.month, version.day).toGMTString(); - Settings.BUILD = "https://ci.athion.net/job/PlotSquared/" + version.build; + Settings.BUILD = "https://ci.athion.net/job/PlotSquared-Releases/" + version.build; Settings.COMMIT = "https://github.com/IntellectualSites/PlotSquared/commit/" + Integer .toHexString(version.hash); @@ -1642,7 +1672,7 @@ import java.util.zip.ZipInputStream; final Properties properties = new Properties(); properties.load(bufferedReader); final boolean enabled = - Boolean.valueOf(properties.getOrDefault("enabled", true).toString()); + Boolean.parseBoolean(properties.getOrDefault("enabled", true).toString()); if (enabled) { this.updateUtility = new UpdateUtility(properties.getProperty("path"), properties.getProperty("job"), properties.getProperty("artifact")); @@ -1680,11 +1710,11 @@ import java.util.zip.ZipInputStream; .getString("configuration_version") .equalsIgnoreCase(LegacyConverter.CONFIGURATION_VERSION)) { // Conversion needed - log(Captions.LEGACY_CONFIG_FOUND.s()); + log(Captions.LEGACY_CONFIG_FOUND.getTranslated()); try { com.google.common.io.Files .copy(this.worldsFile, new File(folder, "worlds.yml.old")); - log(Captions.LEGACY_CONFIG_BACKUP.s()); + log(Captions.LEGACY_CONFIG_BACKUP.getTranslated()); final ConfigurationSection worlds = this.worlds.getConfigurationSection("worlds"); final LegacyConverter converter = new LegacyConverter(worlds); @@ -1693,9 +1723,9 @@ import java.util.zip.ZipInputStream; .set("configuration_version", LegacyConverter.CONFIGURATION_VERSION); this.worlds.set("worlds", worlds); // Redundant, but hey... ¯\_(ツ)_/¯ this.worlds.save(this.worldsFile); - log(Captions.LEGACY_CONFIG_DONE.s()); + log(Captions.LEGACY_CONFIG_DONE.getTranslated()); } catch (final Exception e) { - log(Captions.LEGACY_CONFIG_CONVERSION_FAILED.s()); + log(Captions.LEGACY_CONFIG_CONVERSION_FAILED.getTranslated()); e.printStackTrace(); } // Disable plugin @@ -1796,15 +1826,28 @@ import java.util.zip.ZipInputStream; */ private void setupStyle() { if (this.version != null) { - this.style.set("version", this.version.toString()); + this.style.set("Version", this.version.toString()); } - Map o = new HashMap<>(4); - o.put("color.1", "6"); - o.put("color.2", "7"); - o.put("color.3", "8"); - o.put("color.4", "3"); + this.style.set("Information", "Left Row: PlotSquared color codes ($), right row: Minecraft color codes (&)"); + Map object = new HashMap<>(16); + object.put("color.1", "6"); + object.put("color.2", "7"); + object.put("color.3", "8"); + object.put("color.4", "3"); + object.put("color.5", "1"); + object.put("color.6", "2"); + object.put("color.7", "4"); + object.put("color.8", "5"); + object.put("color.9", "9"); + object.put("color.10", "0"); + object.put("color.11", "a"); + object.put("color.12", "b"); + object.put("color.13", "c"); + object.put("color.14", "d"); + object.put("color.15", "e"); + object.put("color.16", "f"); if (!this.style.contains("color")) { - for (Entry node : o.entrySet()) { + for (Entry node : object.entrySet()) { this.style.set(node.getKey(), node.getValue()); } } @@ -1979,7 +2022,7 @@ import java.util.zip.ZipInputStream; return Collections.unmodifiableSet(result); } - public Set getPlotAreas(final String world, final RegionWrapper region) { + public Set getPlotAreas(final String world, final CuboidRegion region) { final PlotArea[] areas = plotAreaManager.getPlotAreas(world, region); final Set set = new HashSet<>(); Collections.addAll(set, areas); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java index 1d65c36e0..4646a787a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java @@ -24,12 +24,19 @@ public class PlotVersion { public static PlotVersion tryParse(String version, String commit, String date) { try { return new PlotVersion(version, commit, date); - } catch (Exception ignore) { - ignore.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); return new PlotVersion(0, 0, 0, 0, 0); } } + public String versionString() { + if (hash == 0 && build == 0) { + return "NoVer-SNAPSHOT"; + } else { + return "4." + build; + } + } @Override public String toString() { if (hash == 0 && build == 0) { return "PlotSquared-NoVer-SNAPSHOT"; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java index 5741fb7ba..d92dd4ea3 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java @@ -15,6 +15,7 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; import java.util.Iterator; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CompletableFuture; @CommandDeclaration(command = "add", description = "Allow a user to build in a plot while you are online", @@ -25,7 +26,7 @@ import java.util.UUID; super(MainCommand.getInstance(), true); } - @Override public void execute(final PlotPlayer player, String[] args, + @Override public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT); @@ -36,25 +37,25 @@ import java.util.UUID; checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage()); final Set uuids = MainUtil.getUUIDsFromString(args[0]); checkTrue(!uuids.isEmpty(), Captions.INVALID_PLAYER, args[0]); - Iterator iter = uuids.iterator(); + Iterator iterator = uuids.iterator(); int size = plot.getTrusted().size() + plot.getMembers().size(); - while (iter.hasNext()) { - UUID uuid = iter.next(); + while (iterator.hasNext()) { + UUID uuid = iterator.next(); if (uuid == DBFunc.EVERYONE && !( Permissions.hasPermission(player, Captions.PERMISSION_TRUST_EVERYONE) || Permissions .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST))) { MainUtil.sendMessage(player, Captions.INVALID_PLAYER, MainUtil.getName(uuid)); - iter.remove(); + iterator.remove(); continue; } if (plot.isOwner(uuid)) { - MainUtil.sendMessage(player, Captions.ALREADY_OWNER, MainUtil.getName(uuid)); - iter.remove(); + MainUtil.sendMessage(player, Captions.ALREADY_ADDED, MainUtil.getName(uuid)); + iterator.remove(); continue; } if (plot.getMembers().contains(uuid)) { MainUtil.sendMessage(player, Captions.ALREADY_ADDED, MainUtil.getName(uuid)); - iter.remove(); + iterator.remove(); continue; } size += plot.getTrusted().contains(uuid) ? 0 : 1; @@ -78,5 +79,7 @@ import java.util.UUID; MainUtil.sendMessage(player, Captions.MEMBER_ADDED); } }, null); + + return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Alias.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Alias.java index 8e0847f57..401446243 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Alias.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Alias.java @@ -21,12 +21,12 @@ import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; @Override public boolean onCommand(PlotPlayer player, String[] args) { if (args.length == 0) { - Captions.COMMAND_SYNTAX.send(player, "/plot alias "); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return false; } - Location loc = player.getLocation(); - Plot plot = loc.getPlotAbs(); + Location location = player.getLocation(); + Plot plot = location.getPlotAbs(); if (plot == null) { return !sendMessage(player, Captions.NOT_IN_PLOT); } @@ -64,7 +64,7 @@ import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; } break; default: - Captions.COMMAND_SYNTAX.send(player, "/plot alias "); + Captions.COMMAND_SYNTAX.send(player, getUsage()); result = false; } @@ -101,13 +101,14 @@ import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; return false; } plot.setAlias(alias); - MainUtil.sendMessage(player, Captions.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); + MainUtil.sendMessage(player, + Captions.ALIAS_SET_TO.getTranslated().replaceAll("%alias%", alias)); return true; } private boolean removeAlias(PlotPlayer player, Plot plot) { plot.setAlias(null); - MainUtil.sendMessage(player, Captions.ALIAS_REMOVED.s()); + MainUtil.sendMessage(player, Captions.ALIAS_REMOVED.getTranslated()); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java index bfd42f36e..e21c82f7f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java @@ -7,8 +7,25 @@ import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Configuration; import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils; import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.object.SetupObject; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.CmdConfirm; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import com.github.intellectualsites.plotsquared.plot.util.world.RegionUtil; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.regions.CuboidRegion; import java.io.IOException; import java.util.ArrayList; @@ -83,7 +100,7 @@ import java.util.Set; area.ROAD_WIDTH / 2; final int offsetX = bx - (area.ROAD_WIDTH == 0 ? 0 : lower); final int offsetZ = bz - (area.ROAD_WIDTH == 0 ? 0 : lower); - final RegionWrapper region = new RegionWrapper(bx, tx, bz, tz); + final CuboidRegion region = RegionUtil.createRegion(bx, tx, bz, tz); Set areas = PlotSquared.get().getPlotAreas(area.worldname, region); if (!areas.isEmpty()) { @@ -120,10 +137,10 @@ import java.util.Set; player.teleport(WorldUtil.IMP.getSpawn(world)); if (area.TERRAIN != 3) { ChunkManager.largeRegionTask(world, region, - new RunnableVal() { - @Override public void run(ChunkLoc value) { + new RunnableVal() { + @Override public void run(BlockVector2 value) { AugmentedUtils - .generate(world, value.x, value.z, + .generate(world, value.getX(), value.getZ(), null); } }, null); @@ -143,7 +160,6 @@ import java.util.Set; return true; } default: // Start creation - final SetupObject object = new SetupObject(); String[] split = args[1].split(":"); String id; if (split.length == 2) { @@ -151,6 +167,7 @@ import java.util.Set; } else { id = null; } + final SetupObject object = new SetupObject(); object.world = split[0]; final HybridPlotWorld pa = new HybridPlotWorld(object.world, id, PlotSquared.get().IMP.getDefaultGenerator(), null, null); @@ -331,8 +348,8 @@ import java.util.Set; + "\n$1Claimed: $2" + claimed + "\n$1Clusters: $2" + clusters + "\n$1Region: $2" + region + "\n$1Generator: $2" + generator; MainUtil.sendMessage(player, - Captions.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + Captions.PLOT_INFO_FOOTER - .s(), false); + Captions.PLOT_INFO_HEADER.getTranslated() + '\n' + value + '\n' + + Captions.PLOT_INFO_FOOTER.getTranslated(), false); return true; } case "l": @@ -394,7 +411,7 @@ import java.util.Set; .color("$1").text(" - ").color("$2") .text(area.TYPE + ":" + area.TERRAIN).color("$3"); } - }, "/plot area list", Captions.AREA_LIST_HEADER_PAGED.s()); + }, "/plot area list", Captions.AREA_LIST_HEADER_PAGED.getTranslated()); return true; case "regen": case "clear": @@ -415,9 +432,9 @@ import java.util.Set; return false; } ChunkManager - .largeRegionTask(area.worldname, area.getRegion(), new RunnableVal() { - @Override public void run(ChunkLoc value) { - AugmentedUtils.generate(area.worldname, value.x, value.z, null); + .largeRegionTask(area.worldname, area.getRegion(), new RunnableVal() { + @Override public void run(BlockVector2 value) { + AugmentedUtils.generate(area.worldname, value.getX(), value.getZ(), null); } }, () -> player.sendMessage("Regen complete")); return true; @@ -444,10 +461,10 @@ import java.util.Set; if (area.TYPE != 2) { center = WorldUtil.IMP.getSpawn(area.worldname); } else { - RegionWrapper region = area.getRegion(); + CuboidRegion region = area.getRegion(); center = - new Location(area.worldname, region.minX + (region.maxX - region.minX) / 2, - 0, region.minZ + (region.maxZ - region.minZ) / 2); + new Location(area.worldname, region.getMinimumPoint().getX() + (region.getMaximumPoint().getX() - region.getMinimumPoint().getX()) / 2, + 0, region.getMinimumPoint().getZ() + (region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ()) / 2); center.setY(1 + WorldUtil.IMP .getHighestBlock(area.worldname, center.getX(), center.getZ())); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java index fb6d571be..d3148370c 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java @@ -5,10 +5,20 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.Direction; +import com.github.intellectualsites.plotsquared.plot.object.Expression; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.google.common.primitives.Ints; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.util.Set; @CommandDeclaration(command = "auto", permission = "plots.auto", @@ -37,8 +47,7 @@ public class Auto extends SubCommand { MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS_NUM, -diff + ""); return false; } else if (player.hasPersistentMeta("grantedPlots")) { - int grantedPlots = - ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots")); + int grantedPlots = Ints.fromByteArray(player.getPersistentMeta("grantedPlots")); if (grantedPlots - diff < sizeX * sizeZ) { player.removePersistentMeta("grantedPlots"); MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); @@ -48,8 +57,7 @@ public class Auto extends SubCommand { if (left == 0) { player.removePersistentMeta("grantedPlots"); } else { - player.setPersistentMeta("grantedPlots", - ByteArrayUtilities.integerToBytes(left)); + player.setPersistentMeta("grantedPlots", Ints.toByteArray(left)); } MainUtil.sendMessage(player, Captions.REMOVED_GRANTED_PLOT, "" + left, "" + (grantedPlots - left)); @@ -68,15 +76,15 @@ public class Auto extends SubCommand { * @param player * @param area * @param start - * @param schem + * @param schematic */ public static void homeOrAuto(final PlotPlayer player, final PlotArea area, PlotId start, - final String schem) { + final String schematic) { Set plots = player.getPlots(); if (!plots.isEmpty()) { plots.iterator().next().teleportPlayer(player); } else { - autoClaimSafe(player, area, start, schem); + autoClaimSafe(player, area, start, schematic); } } @@ -86,11 +94,11 @@ public class Auto extends SubCommand { * @param player * @param area * @param start - * @param schem + * @param schematic */ public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, - final String schem) { - autoClaimSafe(player, area, start, schem, null); + final String schematic) { + autoClaimSafe(player, area, start, schematic, null); } /** @@ -99,10 +107,10 @@ public class Auto extends SubCommand { * @param player * @param area * @param start - * @param schem + * @param schematic */ public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, - final String schem, @Nullable final Integer allowedPlots) { + final String schematic, @Nullable final Integer allowedPlots) { player.setMeta(Auto.class.getName(), true); autoClaimFromDatabase(player, area, start, new RunnableVal() { @Override public void run(final Plot plot) { @@ -112,9 +120,10 @@ public class Auto extends SubCommand { if (plot == null) { MainUtil.sendMessage(player, Captions.NO_FREE_PLOTS); } else if (checkAllowedPlots(player, area, allowedPlots, 1, 1)) { - plot.claim(player, true, schem, false); + plot.claim(player, true, schematic, false); if (area.AUTO_MERGE) { - plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); + plot.autoMerge(Direction.ALL, Integer.MAX_VALUE, player.getUUID(), + true); } } else { DBFunc.delete(plot); @@ -165,10 +174,16 @@ public class Auto extends SubCommand { if (Permissions.hasPermission(player, Captions.PERMISSION_AUTO_MEGA)) { try { String[] split = args[0].split(",|;"); - size_x = Integer.parseInt(split[0]); - size_z = Integer.parseInt(split[1]); + if (split[1] == null) { + MainUtil.sendMessage(player,"Correct use /plot auto [length,width]"); + size_x = 1; + size_z = 1; + } else { + size_x = Integer.parseInt(split[0]); + size_z = Integer.parseInt(split[1]); + } if (size_x < 1 || size_z < 1) { - MainUtil.sendMessage(player, "&cError: size<=0"); + MainUtil.sendMessage(player, "Error: size<=0"); } if (args.length > 1) { schematic = args[1]; @@ -203,11 +218,12 @@ public class Auto extends SubCommand { sendMessage(player, Captions.SCHEMATIC_INVALID, "non-existent: " + schematic); return true; } - if (!Permissions.hasPermission(player, Captions.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) + if (!Permissions.hasPermission(player, + Captions.format(Captions.PERMISSION_CLAIM_SCHEMATIC.getTranslated(), schematic)) && !Permissions .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_CLAIM_SCHEMATIC.f(schematic)); + Captions.format(Captions.PERMISSION_CLAIM_SCHEMATIC.getTranslated(), schematic)); return true; } } @@ -244,6 +260,9 @@ public class Auto extends SubCommand { for (int j = start.y; j <= end.y; j++) { Plot plot = plotarea.getPlotAbs(new PlotId(i, j)); boolean teleport = i == end.x && j == end.y; + if (plot == null) { + return false; + } plot.claim(player, teleport, null); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Biome.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Biome.java index b40167b4c..df48c1aed 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Biome.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Biome.java @@ -6,7 +6,8 @@ import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.StringMan; -import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.biome.BiomeTypes; @CommandDeclaration(command = "setbiome", permission = "plots.set.biome", description = "Set the plot biome", usage = "/plot biome [biome]", @@ -14,12 +15,16 @@ import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; requiredType = RequiredType.NONE) public class Biome extends SetCommand { @Override public boolean set(final PlotPlayer player, final Plot plot, final String value) { - int biome = WorldUtil.IMP.getBiomeFromString(value); - if (biome == -1) { - String biomes = - StringMan.join(WorldUtil.IMP.getBiomeList(), Captions.BLOCK_LIST_SEPARATER.s()); + BiomeType biome = null; + try { + biome = BiomeTypes.get(value.toLowerCase()); + } catch (final Exception ignore) {} + if (biome == null) { + String biomes = StringMan + .join(BiomeType.REGISTRY.values(), Captions.BLOCK_LIST_SEPARATOR.getTranslated()); Captions.NEED_BIOME.send(player); - MainUtil.sendMessage(player, Captions.SUBCOMMAND_SET_OPTIONS_HEADER.s() + biomes); + MainUtil.sendMessage(player, + Captions.SUBCOMMAND_SET_OPTIONS_HEADER.getTranslated() + biomes); return false; } if (plot.getRunning() > 0) { @@ -27,9 +32,10 @@ import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; return false; } plot.addRunning(); - plot.setBiome(value.toUpperCase(), () -> { + plot.setBiome(biome, () -> { plot.removeRunning(); - MainUtil.sendMessage(player, Captions.BIOME_SET_TO.s() + value.toLowerCase()); + MainUtil + .sendMessage(player, Captions.BIOME_SET_TO.getTranslated() + value.toLowerCase()); }); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java index 6398b30be..dbfd37768 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java @@ -14,6 +14,7 @@ import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CompletableFuture; @CommandDeclaration(command = "buy", description = "Buy the plot you are standing on", usage = "/plot buy", permission = "plots.buy", category = CommandCategory.CLAIMING, @@ -23,7 +24,7 @@ import java.util.Set; super(MainCommand.getInstance(), true); } - @Override public void execute(final PlotPlayer player, String[] args, + @Override public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, final RunnableVal2 whenDone) { @@ -65,5 +66,6 @@ import java.util.Set; player.deposit(price); whenDone.run(Buy.this, CommandResult.FAILURE); }); + return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java index b06e0b57b..a10e83aca 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java @@ -4,11 +4,17 @@ import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.ByteArrayUtilities; +import com.github.intellectualsites.plotsquared.plot.object.Direction; +import com.github.intellectualsites.plotsquared.plot.object.Expression; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.util.EconHandler; import com.github.intellectualsites.plotsquared.plot.util.Permissions; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.google.common.primitives.Ints; @CommandDeclaration(command = "claim", aliases = "c", description = "Claim the current plot you're standing on", category = CommandCategory.CLAIMING, @@ -20,18 +26,19 @@ public class Claim extends SubCommand { if (args.length >= 1) { schematic = args[0]; } - Location loc = player.getLocation(); - final Plot plot = loc.getPlotAbs(); + Location location = player.getLocation(); + final Plot plot = location.getPlotAbs(); if (plot == null) { return sendMessage(player, Captions.NOT_IN_PLOT); } - int currentPlots = - Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); + int currentPlots = Settings.Limit.GLOBAL ? + player.getPlotCount() : + player.getPlotCount(location.getWorld()); int grants = 0; if (currentPlots >= player.getAllowedPlots()) { if (player.hasPersistentMeta("grantedPlots")) { grants = - ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots")); + Ints.fromByteArray(player.getPersistentMeta("grantedPlots")); if (grants <= 0) { player.removePersistentMeta("grantedPlots"); return sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); @@ -51,7 +58,8 @@ public class Claim extends SubCommand { "non-existent: " + schematic); } if (!Permissions - .hasPermission(player, Captions.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) + .hasPermission(player, Captions + .format(Captions.PERMISSION_CLAIM_SCHEMATIC.getTranslated(), schematic)) && !Permissions .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { return sendMessage(player, Captions.NO_SCHEMATIC_PERMISSION, schematic); @@ -78,7 +86,7 @@ public class Claim extends SubCommand { player.removePersistentMeta("grantedPlots"); } else { player.setPersistentMeta("grantedPlots", - ByteArrayUtilities.integerToBytes(grants - 1)); + Ints.toByteArray(grants - 1)); } sendMessage(player, Captions.REMOVED_GRANTED_PLOT, "1", "" + (grants - 1)); } @@ -89,7 +97,7 @@ public class Claim extends SubCommand { @Override public void run(Object value) { plot.claim(player, true, finalSchematic, false); if (area.AUTO_MERGE) { - plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); + plot.autoMerge(Direction.ALL, Integer.MAX_VALUE, player.getUUID(), true); } } }), () -> sendMessage(player, Captions.PLOT_NOT_CLAIMED)); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java index c16b603ac..9dcd475a1 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java @@ -14,6 +14,8 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.Permissions; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; +import java.util.concurrent.CompletableFuture; + @CommandDeclaration(command = "clear", description = "Clear the plot you stand on", permission = "plots.clear", category = CommandCategory.APPEARANCE, usage = "/plot clear", aliases = "reset", confirmation = true) public class Clear extends Command { @@ -25,7 +27,7 @@ import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue super(MainCommand.getInstance(), true); } - @Override public void execute(final PlotPlayer player, String[] args, + @Override public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { checkTrue(args.length == 0, Captions.COMMAND_SYNTAX, getUsage()); @@ -36,34 +38,29 @@ import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue checkTrue(plot.getRunning() == 0, Captions.WAIT_FOR_TIMER); checkTrue(!Settings.Done.RESTRICT_BUILDING || !Flags.DONE.isSet(plot) || Permissions .hasPermission(player, Captions.PERMISSION_CONTINUE), Captions.DONE_ALREADY_DONE); - confirm.run(this, new Runnable() { - @Override public void run() { - final long start = System.currentTimeMillis(); - boolean result = plot.clear(true, false, new Runnable() { - @Override public void run() { - plot.unlink(); - GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override public void run() { - plot.removeRunning(); - // If the state changes, then mark it as no longer done - if (plot.getFlag(Flags.DONE).isPresent()) { - FlagManager.removePlotFlag(plot, Flags.DONE); - } - if (plot.getFlag(Flags.ANALYSIS).isPresent()) { - FlagManager.removePlotFlag(plot, Flags.ANALYSIS); - } - MainUtil.sendMessage(player, Captions.CLEARING_DONE, - "" + (System.currentTimeMillis() - start)); - } - }); + confirm.run(this, () -> { + final long start = System.currentTimeMillis(); + boolean result = plot.clear(true, false, () -> { + plot.unlink(); + GlobalBlockQueue.IMP.addEmptyTask(() -> { + plot.removeRunning(); + // If the state changes, then mark it as no longer done + if (plot.getFlag(Flags.DONE).isPresent()) { + FlagManager.removePlotFlag(plot, Flags.DONE); } + if (plot.getFlag(Flags.ANALYSIS).isPresent()) { + FlagManager.removePlotFlag(plot, Flags.ANALYSIS); + } + MainUtil.sendMessage(player, Captions.CLEARING_DONE, + "" + (System.currentTimeMillis() - start)); }); - if (!result) { - MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER); - } else { - plot.addRunning(); - } + }); + if (!result) { + MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER); + } else { + plot.addRunning(); } }, null); + return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java index a59c65550..088273c9c 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java @@ -5,7 +5,13 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.BlockLoc; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotCluster; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.Permissions; import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; @@ -297,7 +303,8 @@ import java.util.UUID; Settings.Limit.MAX_PLOTS); if (current + cluster.getArea() > allowed) { MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_CLUSTER.s() + "." + (current + cluster.getArea())); + Captions.PERMISSION_CLUSTER.getTranslated() + "." + (current + cluster + .getArea())); return false; } // resize cluster @@ -466,7 +473,6 @@ import java.util.UUID; PlotSquared.get().getPlots(player.getLocation().getWorld(), uuid))) { PlotCluster current = plot.getCluster(); if (current != null && current.equals(cluster)) { - player.getLocation().getWorld(); plot.unclaim(); } } @@ -589,7 +595,7 @@ import java.util.UUID; String size = (cluster.getP2().x - cluster.getP1().x + 1) + "x" + ( cluster.getP2().y - cluster.getP1().y + 1); String rights = cluster.isAdded(player.getUUID()) + ""; - String message = Captions.CLUSTER_INFO.s(); + String message = Captions.CLUSTER_INFO.getTranslated(); message = message.replaceAll("%id%", id); message = message.replaceAll("%owner%", owner); message = message.replaceAll("%name%", name); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CommandCategory.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CommandCategory.java index bebf77907..3958f2d39 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CommandCategory.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CommandCategory.java @@ -16,7 +16,7 @@ import lombok.RequiredArgsConstructor; * Teleportation CommandConfig. * Such as: /plot visit */ - TELEPORT(Captions.COMMAND_CATEGORY_TELEPPORT), + TELEPORT(Captions.COMMAND_CATEGORY_TELEPORT), /** * Protection. */ @@ -53,6 +53,6 @@ import lombok.RequiredArgsConstructor; private final Captions caption; @Override public String toString() { - return this.caption.s(); + return this.caption.getTranslated(); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Comment.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Comment.java index 048047bb6..171a5bfe5 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Comment.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Comment.java @@ -32,7 +32,7 @@ public class Comment extends SubCommand { StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } - Location loc = player.getLocation(); + Location location = player.getLocation(); PlotId id; try { id = PlotId.fromString(args[1]); @@ -44,7 +44,7 @@ public class Comment extends SubCommand { int index; if (plot == null) { index = 1; - plot = loc.getPlotAbs(); + plot = location.getPlotAbs(); } else { if (args.length < 4) { sendMessage(player, Captions.COMMENT_SYNTAX, @@ -59,7 +59,7 @@ public class Comment extends SubCommand { } String message = StringMan.join(Arrays.copyOfRange(args, index, args.length), " "); PlotComment comment = - new PlotComment(loc.getWorld(), id, message, player.getName(), inbox.toString(), + new PlotComment(location.getWorld(), id, message, player.getName(), inbox.toString(), System.currentTimeMillis()); boolean result = inbox.addComment(plot, comment); if (!result) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java index 478a0cab9..a9341f373 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java @@ -11,11 +11,16 @@ import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; import java.util.Set; -import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; @CommandDeclaration(command = "condense", permission = "plots.admin", + usage = "/plot condense [radius]", description = "Condense a plotworld", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE) public class Condense extends SubCommand { @@ -23,7 +28,7 @@ import java.util.concurrent.atomic.AtomicBoolean; @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length != 2 && args.length != 3) { - MainUtil.sendMessage(player, "/plot condense [radius]"); + MainUtil.sendMessage(player, getUsage()); return false; } PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]); @@ -104,6 +109,7 @@ import java.util.concurrent.atomic.AtomicBoolean; return false; } MainUtil.sendMessage(player, "TASK STARTED..."); + Condense.TASK = true; Runnable run = new Runnable() { @Override public void run() { if (!Condense.TASK) { @@ -147,7 +153,6 @@ import java.util.concurrent.atomic.AtomicBoolean; } } }; - Condense.TASK = true; TaskManager.runTaskAsync(run); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Continue.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Continue.java index 4aec2d6d0..961742c1b 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Continue.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Continue.java @@ -12,7 +12,7 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; @CommandDeclaration(command = "continue", description = "Continue a plot that was previously marked as done", permission = "plots.continue", category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE) public class Continue extends SubCommand { + requiredType = RequiredType.PLAYER) public class Continue extends SubCommand { @Override public boolean onCommand(PlotPlayer player, String[] args) { Plot plot = player.getCurrentPlot(); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java index dd95a8c2f..de77513bc 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java @@ -13,13 +13,13 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; requiredType = RequiredType.NONE) public class Copy extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { - Location loc = player.getLocation(); - Plot plot1 = loc.getPlotAbs(); + Location location = player.getLocation(); + Plot plot1 = location.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot1.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN.s())) { + .hasPermission(player, Captions.PERMISSION_ADMIN.getTranslated())) { MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CreateRoadSchematic.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CreateRoadSchematic.java index 26962781c..14fa6347e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CreateRoadSchematic.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CreateRoadSchematic.java @@ -16,17 +16,16 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; usage = "/plot createroadschematic") public class CreateRoadSchematic extends SubCommand { @Override public boolean onCommand(PlotPlayer player, String[] args) { - Location loc = player.getLocation(); - Plot plot = loc.getPlotAbs(); + Location location = player.getLocation(); + Plot plot = location.getPlotAbs(); if (plot == null) { return sendMessage(player, Captions.NOT_IN_PLOT); } - if (!(loc.getPlotArea() instanceof HybridPlotWorld)) { + if (!(location.getPlotArea() instanceof HybridPlotWorld)) { return sendMessage(player, Captions.NOT_IN_PLOT_WORLD); } HybridUtils.manager.setupRoadSchematic(plot); - MainUtil.sendMessage(player, - "$1Saved new road schematic. To test the road, fly to a few other plots and use /plot debugroadregen"); + MainUtil.sendMessage(player, Captions.SCHEMATIC_ROAD_CREATED); return true; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java index e94850121..abbddc9ca 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java @@ -48,7 +48,7 @@ import java.util.Map.Entry; @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length < 1) { - MainUtil.sendMessage(player, "/plot database [area] "); + MainUtil.sendMessage(player, getUsage()); return false; } List plots; @@ -60,7 +60,7 @@ import java.util.Map.Entry; plots = PlotSquared.get().sortPlotsByTemp(PlotSquared.get().getPlots()); } if (args.length < 1) { - MainUtil.sendMessage(player, "/plot database [world] "); + MainUtil.sendMessage(player, getUsage()); MainUtil.sendMessage(player, "[arg] indicates an optional argument"); return false; } @@ -87,8 +87,8 @@ import java.util.Map.Entry; HashMap> map = manager.getPlots(); plots = new ArrayList<>(); for (Entry> entry : map.entrySet()) { - String areaname = entry.getKey(); - PlotArea pa = PlotSquared.get().getPlotAreaByString(areaname); + String areaName = entry.getKey(); + PlotArea pa = PlotSquared.get().getPlotAreaByString(areaName); if (pa != null) { for (Entry entry2 : entry.getValue().entrySet()) { Plot plot = entry2.getValue(); @@ -123,9 +123,9 @@ import java.util.Map.Entry; plots.add(plot); } } else { - HashMap plotmap = PlotSquared.get().plots_tmp - .computeIfAbsent(areaname, k -> new HashMap<>()); - plotmap.putAll(entry.getValue()); + HashMap plotMap = PlotSquared.get().plots_tmp + .computeIfAbsent(areaName, k -> new HashMap<>()); + plotMap.putAll(entry.getValue()); } } DBFunc.createPlotsAndData(plots, diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Debug.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Debug.java index 527b67819..c1970f969 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Debug.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Debug.java @@ -7,23 +7,32 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import java.util.Map; + @CommandDeclaration(command = "debug", category = CommandCategory.DEBUG, description = "Show debug information", usage = "/plot debug [msg]", permission = "plots.admin") public class Debug extends SubCommand { @Override public boolean onCommand(PlotPlayer player, String[] args) { + if ((args.length > 0) && "player".equalsIgnoreCase(args[1])) { + for (Map.Entry meta : player.getMeta().entrySet()) { + MainUtil.sendMessage(player, + "Key: " + meta.getKey() + " Value: " + meta.getValue().toString() + " , "); + } + ; + } if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) { StringBuilder msg = new StringBuilder(); for (Captions caption : Captions.values()) { - msg.append(caption.s()).append("\n"); + msg.append(caption.getTranslated()).append("\n"); } MainUtil.sendMessage(player, msg.toString()); return true; } StringBuilder information = new StringBuilder(); - String header = Captions.DEBUG_HEADER.s(); - String line = Captions.DEBUG_LINE.s(); - String section = Captions.DEBUG_SECTION.s(); + String header = Captions.DEBUG_HEADER.getTranslated(); + String line = Captions.DEBUG_LINE.getTranslated(); + String section = Captions.DEBUG_SECTION.getTranslated(); information.append(header); information.append(getSection(section, "PlotArea")); information.append( diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java index 9d5dc9d3d..411a3290b 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java @@ -4,12 +4,19 @@ import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.StringWrapper; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.google.common.collect.BiMap; +import com.sk89q.worldedit.math.BlockVector2; import java.util.ArrayList; import java.util.Map; @@ -17,8 +24,7 @@ import java.util.UUID; @CommandDeclaration(command = "debugclaimtest", description = "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot signs. " - + "Execution time may vary", category = CommandCategory.DEBUG, - requiredType = RequiredType.CONSOLE, permission = "plots.debugclaimtest") + + "Execution time may vary", category = CommandCategory.DEBUG, requiredType = RequiredType.CONSOLE, permission = "plots.debugclaimtest") public class DebugClaimTest extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { @@ -55,58 +61,55 @@ public class DebugClaimTest extends SubCommand { MainUtil.sendMessage(player, " - &cDB Already contains: " + plot.getId()); continue; } - Location loc = manager.getSignLoc(area, plot); - ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); - boolean result = ChunkManager.manager.loadChunk(area.worldname, chunk, false); - if (!result) { - continue; - } - String[] lines = WorldUtil.IMP.getSign(loc); - if (lines != null) { - String line = lines[2]; - if (line != null && line.length() > 2) { - line = line.substring(2); - BiMap map = UUIDHandler.getUuidMap(); - UUID uuid = map.get(new StringWrapper(line)); - if (uuid == null) { - for (Map.Entry stringWrapperUUIDEntry : map - .entrySet()) { - if (stringWrapperUUIDEntry.getKey().value.toLowerCase() - .startsWith(line.toLowerCase())) { - uuid = stringWrapperUUIDEntry.getValue(); - break; + Location location = manager.getSignLoc(plot); + BlockVector2 chunk = BlockVector2.at(location.getX() >> 4, location.getZ() >> 4); + ChunkManager.manager.loadChunk(area.worldname, chunk, false).thenRun(() -> { + String[] lines = WorldUtil.IMP.getSign(location); + if (lines != null) { + String line = lines[2]; + if (line != null && line.length() > 2) { + line = line.substring(2); + BiMap map = UUIDHandler.getUuidMap(); + UUID uuid = map.get(new StringWrapper(line)); + if (uuid == null) { + for (Map.Entry stringWrapperUUIDEntry : map + .entrySet()) { + if (stringWrapperUUIDEntry.getKey().value.toLowerCase() + .startsWith(line.toLowerCase())) { + uuid = stringWrapperUUIDEntry.getValue(); + break; + } } } - } - if (uuid == null) { - uuid = UUIDHandler.getUUID(line, null); - } - if (uuid != null) { - MainUtil - .sendMessage(player, " - &aFound plot: " + plot.getId() + " : " + line); - plot.setOwner(uuid); - plots.add(plot); - } else { - MainUtil.sendMessage(player, - " - &cInvalid PlayerName: " + plot.getId() + " : " + line); + if (uuid == null) { + uuid = UUIDHandler.getUUID(line, null); + } + if (uuid != null) { + MainUtil.sendMessage(player, + " - &aFound plot: " + plot.getId() + " : " + line); + plot.setOwner(uuid); + plots.add(plot); + } else { + MainUtil.sendMessage(player, + " - &cInvalid PlayerName: " + plot.getId() + " : " + line); + } } } - } - } - if (!plots.isEmpty()) { - MainUtil.sendMessage(player, - "&3Sign Block&8->&3Plot&8: &7Updating '" + plots.size() + "' plots!"); - DBFunc.createPlotsAndData(plots, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "&6Database update finished!"); + }).thenRun(() -> { + if (!plots.isEmpty()) { + MainUtil.sendMessage(player, + "&3Sign Block&8->&3Plot&8: &7Updating '" + plots.size() + "' plots!"); + DBFunc.createPlotsAndData(plots, + () -> MainUtil.sendMessage(player, "&6Database update finished!")); + for (Plot plot1 : plots) { + plot.create(); + } + MainUtil.sendMessage(player, "&3Sign Block&8->&3Plot&8: &7Complete!"); + } else { + MainUtil.sendMessage(player, "No plots were found for the given search."); } }); - for (Plot plot : plots) { - plot.create(); - } - MainUtil.sendMessage(player, "&3Sign Block&8->&3Plot&8: &7Complete!"); - } else { - MainUtil.sendMessage(player, "No plots were found for the given search."); + return true; } return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java index 4e533fe61..8bafa55b7 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java @@ -10,19 +10,50 @@ import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; import com.github.intellectualsites.plotsquared.plot.listener.WEManager; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis; import com.google.common.io.Files; +import com.sk89q.worldedit.world.block.BlockState; -import javax.script.*; +import javax.script.Bindings; +import javax.script.ScriptContext; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import javax.script.SimpleScriptContext; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; -import java.util.*; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; @CommandDeclaration(command = "debugexec", permission = "plots.admin", description = "Mutli-purpose debug command", aliases = {"exec", "$"}, @@ -93,7 +124,7 @@ import java.util.*; // Classes this.scope.put("Location", Location.class); - this.scope.put("PlotBlock", PlotBlock.class); + this.scope.put("BlockState", BlockState.class); this.scope.put("Plot", Plot.class); this.scope.put("PlotId", PlotId.class); this.scope.put("Runnable", Runnable.class); @@ -107,7 +138,6 @@ import java.util.*; this.scope.put("WEManager", new WEManager()); } this.scope.put("TaskManager", TaskManager.IMP); - this.scope.put("TitleManager", AbstractTitle.TITLE_CLASS); this.scope.put("ConsolePlayer", ConsolePlayer.getConsole()); this.scope.put("SchematicHandler", SchematicHandler.manager); this.scope.put("ChunkManager", ChunkManager.manager); @@ -276,7 +306,7 @@ import java.util.*; System.getProperty("line.separator")); new Command(MainCommand.getInstance(), true, args[1].split("\\.")[0], null, RequiredType.NONE, CommandCategory.DEBUG) { - @Override public void execute(PlotPlayer player, String[] args, + @Override public CompletableFuture execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { try { @@ -287,6 +317,7 @@ import java.util.*; e.printStackTrace(); MainUtil.sendMessage(player, Captions.COMMAND_WENT_WRONG); } + return CompletableFuture.completedFuture(true); } }; return true; @@ -359,17 +390,17 @@ import java.util.*; Command cmd = MainCommand.getInstance().getCommand(args[3]); String[] params = Arrays.copyOfRange(args, 4, args.length); if ("true".equals(args[1])) { - Location loc = player.getMeta(PlotPlayer.META_LOCATION); + Location location = player.getMeta(PlotPlayer.META_LOCATION); Plot plot = player.getMeta(PlotPlayer.META_LAST_PLOT); for (Plot current : PlotSquared.get().getBasePlots()) { player.setMeta(PlotPlayer.META_LOCATION, current.getBottomAbs()); player.setMeta(PlotPlayer.META_LAST_PLOT, current); cmd.execute(player, params, null, null); } - if (loc == null) { + if (location == null) { player.deleteMeta(PlotPlayer.META_LOCATION); } else { - player.setMeta(PlotPlayer.META_LOCATION, loc); + player.setMeta(PlotPlayer.META_LOCATION, location); } if (plot == null) { player.deleteMeta(PlotPlayer.META_LAST_PLOT); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugImportWorlds.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugImportWorlds.java index ddac91e4d..978c95e34 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugImportWorlds.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugImportWorlds.java @@ -16,6 +16,7 @@ import com.google.common.base.Charsets; import java.io.File; import java.util.UUID; +import java.util.concurrent.CompletableFuture; @CommandDeclaration(command = "debugimportworlds", permission = "plots.admin", description = "Import worlds by player name", requiredType = RequiredType.CONSOLE, @@ -24,14 +25,14 @@ import java.util.UUID; super(MainCommand.getInstance(), true); } - @Override public void execute(PlotPlayer player, String[] args, + @Override public CompletableFuture execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { // UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)) PlotAreaManager pam = PlotSquared.get().getPlotAreaManager(); if (!(pam instanceof SinglePlotAreaManager)) { player.sendMessage("Must be a single plot area!"); - return; + return CompletableFuture.completedFuture(false); } SinglePlotArea area = ((SinglePlotAreaManager) pam).getArea(); PlotId id = new PlotId(0, 0); @@ -39,7 +40,7 @@ import java.util.UUID; if (container.equals(new File("."))) { player.sendMessage( "World container must be configured to be a separate directory to your base files!"); - return; + return CompletableFuture.completedFuture(false); } for (File folder : container.listFiles()) { String name = folder.getName(); @@ -64,5 +65,6 @@ import java.util.UUID; } } player.sendMessage("Done!"); + return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugPaste.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugPaste.java index f28b33a0a..426b46eaa 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugPaste.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugPaste.java @@ -17,21 +17,25 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; import java.nio.file.Files; import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @CommandDeclaration(command = "debugpaste", aliases = "dp", usage = "/plot debugpaste", - description = "Upload settings.yml, worlds.yml, PlotSquared.use_THIS.yml and your latest.log to https://athion.net/ISPaster/paste", - permission = "plots.debugpaste", category = CommandCategory.DEBUG) public class DebugPaste - extends SubCommand { + description = "Upload settings.yml, worlds.yml, PlotSquared.use_THIS.yml your latest.log and Multiverse's worlds.yml (if being used) to https://athion.net/ISPaster/paste", + permission = "plots.debugpaste", category = CommandCategory.DEBUG, confirmation = true, requiredType = RequiredType.NONE) +public class DebugPaste extends SubCommand { private static String readFile(@NonNull final File file) throws IOException { - final StringBuilder content = new StringBuilder(); final List lines; try (final BufferedReader reader = new BufferedReader(new FileReader(file))) { lines = reader.lines().collect(Collectors.toList()); } + final StringBuilder content = new StringBuilder(); for (int i = Math.max(0, lines.size() - 1000); i < lines.size(); i++) { content.append(lines.get(i)).append("\n"); } @@ -41,44 +45,44 @@ import java.util.stream.Collectors; @Override public boolean onCommand(final PlotPlayer player, String[] args) { TaskManager.runTaskAsync(() -> { try { - final IncendoPaster incendoPaster = new IncendoPaster("plotsquared"); StringBuilder b = new StringBuilder(); b.append( "# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your " + "problem\n\n"); b.append("# Server Information\n"); - b.append("server.version: ").append(PlotSquared.get().IMP.getServerImplementation()) + b.append("Server Version: ").append(PlotSquared.get().IMP.getServerImplementation()) .append("\n"); b.append("online_mode: ").append(UUIDHandler.getUUIDWrapper()).append(';') .append(!Settings.UUID.OFFLINE).append('\n'); - b.append("plugins:"); - for (String id : PlotSquared.get().IMP.getPluginIds()) { - String[] split = id.split(":"); - String[] split2 = split[0].split(";"); - String enabled = split.length == 2 ? split[1] : "unknown"; - String name = split2[0]; - String version = split2.length == 2 ? split2[1] : "unknown"; + b.append("Plugins:"); + for (Map.Entry, Boolean> pluginInfo : PlotSquared.get().IMP.getPluginIds()) { + Map.Entry nameVersion = pluginInfo.getKey(); + String name = nameVersion.getKey(); + String version = nameVersion.getValue(); + boolean enabled = pluginInfo.getValue(); b.append("\n ").append(name).append(":\n ").append("version: '") .append(version).append('\'').append("\n enabled: ").append(enabled); } b.append("\n\n# YAY! Now, let's see what we can find in your JVM\n"); Runtime runtime = Runtime.getRuntime(); - b.append("memory.free: ").append(runtime.freeMemory()).append('\n'); - b.append("memory.max: ").append(runtime.maxMemory()).append('\n'); - b.append("java.specification.version: '") - .append(System.getProperty("java.specification.version")).append("'\n"); - b.append("java.vendor: '").append(System.getProperty("java.vendor")).append("'\n"); - b.append("java.version: '").append(System.getProperty("java.version")) - .append("'\n"); - b.append("os.arch: '").append(System.getProperty("os.arch")).append("'\n"); - b.append("os.name: '").append(System.getProperty("os.name")).append("'\n"); - b.append("os.version: '").append(System.getProperty("os.version")).append("'\n\n"); + RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean(); + b.append("Uptime: ").append(TimeUnit.MINUTES.convert(rb.getUptime(), TimeUnit.MILLISECONDS) + " minutes").append('\n'); + b.append("JVM Flags: ").append(rb.getInputArguments()).append('\n'); + b.append("Free Memory: ").append(runtime.freeMemory() / 1024 / 1024 + " MB").append('\n'); + b.append("Max Memory: ").append(runtime.maxMemory() / 1024 / 1024 + " MB").append('\n'); + b.append("Java Name: ").append(rb.getVmName()).append('\n'); + b.append("Java Version: '").append(System.getProperty("java.version")).append("'\n"); + b.append("Java Vendor: '").append(System.getProperty("java.vendor")).append("'\n"); + b.append("Operating System: '").append(System.getProperty("os.name")).append("'\n"); + b.append("OS Version: ").append(System.getProperty("os.version")).append('\n'); + b.append("OS Arch: ").append(System.getProperty("os.arch")).append('\n'); b.append("# Okay :D Great. You are now ready to create your bug report!"); b.append( "\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues"); b.append("\n# or via our Discord at https://discord.gg/ngZCzbU"); + final IncendoPaster incendoPaster = new IncendoPaster("plotsquared"); incendoPaster.addFile(new IncendoPaster.PasteFile("information", b.toString())); try { @@ -114,6 +118,15 @@ import java.util.stream.Collectors; "&cSkipping PlotSquared.use_THIS.yml because it's empty"); } + try { + final File MultiverseWorlds = + new File(PlotSquared.get().IMP.getDirectory(), "../Multiverse-Core/worlds.yml"); + incendoPaster + .addFile(new IncendoPaster.PasteFile("MultiverseCore/worlds.yml", readFile(MultiverseWorlds))); + } catch (final IOException ignored) { + MainUtil.sendMessage(player, "&cSkipping Multiverse worlds.yml because the plugin is not in use"); + } + try { final String rawResponse = incendoPaster.upload(); final JsonObject jsonObject = @@ -123,8 +136,8 @@ import java.util.stream.Collectors; final String pasteId = jsonObject.get("paste_id").getAsString(); final String link = String.format("https://athion.net/ISPaster/paste/view/%s", pasteId); - player - .sendMessage(Captions.DEBUG_REPORT_CREATED.s().replace("%url%", link)); + player.sendMessage( + Captions.DEBUG_REPORT_CREATED.getTranslated().replace("%url%", link)); } else { final String responseMessage = jsonObject.get("response").getAsString(); MainUtil.sendMessage(player, String diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugRoadRegen.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugRoadRegen.java index fd0b29657..a268f8903 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugRoadRegen.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugRoadRegen.java @@ -3,23 +3,44 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotManager; -import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; +import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; -@CommandDeclaration(command = "debugroadregen", usage = "/plot debugroadregen", +import java.util.Arrays; + +@CommandDeclaration(command = "debugroadregen", usage = DebugRoadRegen.USAGE, requiredType = RequiredType.NONE, - description = "Regenerate all roads based on the road schematic", + description = "Regenerate roads in the plot or region the user is, based on the road schematic", category = CommandCategory.DEBUG, permission = "plots.debugroadregen") public class DebugRoadRegen extends SubCommand { + public static final String USAGE = "/plot debugroadregen "; @Override public boolean onCommand(PlotPlayer player, String[] args) { - Location loc = player.getLocation(); - PlotArea plotArea = loc.getPlotArea(); - if (!(plotArea instanceof HybridPlotWorld)) { + if (args.length < 1) { + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, DebugRoadRegen.USAGE); + return false; + } + String kind = args[0].toLowerCase(); + switch (kind) { + case "plot": + return regenPlot(player); + case "region": + return regenRegion(player, Arrays.copyOfRange(args, 1, args.length)); + default: + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, DebugRoadRegen.USAGE); + return false; + } + } + + public boolean regenPlot(PlotPlayer player) { + Location location = player.getLocation(); + PlotArea area = location.getPlotArea(); + if (area == null) { return sendMessage(player, Captions.NOT_IN_PLOT_WORLD); } Plot plot = player.getCurrentPlot(); @@ -28,14 +49,56 @@ public class DebugRoadRegen extends SubCommand { } else if (plot.isMerged()) { Captions.REQUIRES_UNMERGED.send(player); } else { - HybridPlotManager manager = (HybridPlotManager) plotArea.getPlotManager(); - manager.createRoadEast(plotArea, plot); - manager.createRoadSouth(plotArea, plot); - manager.createRoadSouthEast(plotArea, plot); + PlotManager manager = area.getPlotManager(); + manager.createRoadEast(plot); + manager.createRoadSouth(plot); + manager.createRoadSouthEast(plot); MainUtil.sendMessage(player, "&6Regenerating plot south/east roads: " + plot.getId() + "\n&6 - Result: &aSuccess"); MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads"); } return true; } + + public boolean regenRegion(PlotPlayer player, String[] args) { + int height = 0; + if (args.length == 1) { + try { + height = Integer.parseInt(args[0]); + } catch (NumberFormatException ignored) { + MainUtil.sendMessage(player, Captions.NOT_VALID_NUMBER, "(0, 256)"); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + DebugRoadRegen.USAGE); + return false; + } + } else if (args.length != 0) { + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + DebugRoadRegen.USAGE); + return false; + } + + Location location = player.getLocation(); + PlotArea area = location.getPlotArea(); + if (area == null) { + return sendMessage(player, Captions.NOT_IN_PLOT_WORLD); + } + Plot plot = player.getCurrentPlot(); + PlotManager manager = area.getPlotManager(); + if (!(manager instanceof HybridPlotManager)) { + MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD); + return true; + } + MainUtil + .sendMessage(player, "&cIf no schematic is set, the following will not do anything"); + MainUtil.sendMessage(player, + "&7 - To set a schematic, stand in a plot and use &c/plot createroadschematic"); + MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads"); + boolean result = HybridUtils.manager.scheduleSingleRegionRoadUpdate(plot, height); + if (!result) { + MainUtil.sendMessage(player, + "&cCannot schedule mass schematic update! (Is one already in progress?)"); + return false; + } + return true; + } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java index 16f10b7b0..72c6da126 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java @@ -3,21 +3,29 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.Expression; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.CmdConfirm; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; @CommandDeclaration(command = "delete", permission = "plots.delete", description = "Delete the plot you stand on", usage = "/plot delete", - aliases = {"dispose", "del"}, category = CommandCategory.CLAIMING, + aliases = {"dispose", "del", "unclaim"}, category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE, confirmation = true) public class Delete extends SubCommand { // Note: To delete a specific plot use /plot delete // The syntax also works with any command: /plot @Override public boolean onCommand(final PlotPlayer player, String[] args) { - Location loc = player.getLocation(); - final Plot plot = loc.getPlotAbs(); + Location location = player.getLocation(); + final Plot plot = location.getPlotAbs(); if (plot == null) { return !sendMessage(player, Captions.NOT_IN_PLOT); } @@ -30,8 +38,9 @@ import com.github.intellectualsites.plotsquared.plot.util.*; } final PlotArea plotArea = plot.getArea(); final java.util.Set plots = plot.getConnectedPlots(); - final int currentPlots = - Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); + final int currentPlots = Settings.Limit.GLOBAL ? + player.getPlotCount() : + player.getPlotCount(location.getWorld()); Runnable run = new Runnable() { @Override public void run() { if (plot.getRunning() > 0) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java index 34a2936f8..220341f5f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java @@ -8,9 +8,13 @@ import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import com.sk89q.worldedit.world.gamemode.GameModes; -import java.util.Iterator; import java.util.Set; import java.util.UUID; @@ -44,9 +48,7 @@ import java.util.UUID; MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[0]); return false; } - Iterator iter = uuids.iterator(); - while (iter.hasNext()) { - UUID uuid = iter.next(); + for (UUID uuid : uuids) { if (uuid == DBFunc.EVERYONE && !( Permissions.hasPermission(player, Captions.PERMISSION_DENY_EVERYONE) || Permissions .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DENY))) { @@ -54,7 +56,7 @@ import java.util.UUID; continue; } if (plot.isOwner(uuid)) { - MainUtil.sendMessage(player, Captions.ALREADY_OWNER, MainUtil.getName(uuid)); + MainUtil.sendMessage(player, Captions.CANT_REMOVE_OWNER, MainUtil.getName(uuid)); return false; } @@ -92,18 +94,18 @@ import java.util.UUID; if (player.hasPermission("plots.admin.entry.denied")) { return; } - if (player.getGameMode() == PlotGameMode.SPECTATOR) { + if (player.getGameMode() == GameModes.SPECTATOR) { player.stopSpectating(); } - Location loc = player.getLocation(); - Location spawn = WorldUtil.IMP.getSpawn(loc.getWorld()); + Location location = player.getLocation(); + Location spawn = WorldUtil.IMP.getSpawn(location.getWorld()); MainUtil.sendMessage(player, Captions.YOU_GOT_DENIED); if (plot.equals(spawn.getPlot())) { Location newSpawn = WorldUtil.IMP.getSpawn(PlotSquared.get().getPlotAreaManager().getAllWorlds()[0]); if (plot.equals(newSpawn.getPlot())) { // Kick from server if you can't be teleported to spawn - player.kick(Captions.YOU_GOT_DENIED.s()); + player.kick(Captions.YOU_GOT_DENIED.getTranslated()); } else { player.teleport(newSpawn); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Done.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Done.java index 8ef920565..055cfabd9 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Done.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Done.java @@ -19,8 +19,8 @@ import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis; requiredType = RequiredType.NONE) public class Done extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { - Location loc = player.getLocation(); - final Plot plot = loc.getPlotAbs(); + Location location = player.getLocation(); + final Plot plot = location.getPlotAbs(); if ((plot == null) || !plot.hasOwner()) { return !sendMessage(player, Captions.NOT_IN_PLOT); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Download.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Download.java index 43560b81f..776cff0f8 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Download.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Download.java @@ -8,7 +8,11 @@ import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.sk89q.jnbt.CompoundTag; import java.net.URL; @@ -37,7 +41,7 @@ import java.net.URL; return false; } if ((!plot.isOwner(player.getUUID())) && !Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN.s())) { + .hasPermission(player, Captions.PERMISSION_ADMIN.getTranslated())) { MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } @@ -72,7 +76,7 @@ import java.net.URL; Captions.NO_PERMISSION.send(player, Captions.PERMISSION_DOWNLOAD_WORLD); return false; } - MainUtil.sendMessage(player, "&cNote: The `.mca` files are 512x512"); + MainUtil.sendMessage(player, Captions.MCA_FILE_SIZE); plot.addRunning(); WorldUtil.IMP.saveWorld(world); WorldUtil.IMP.upload(plot, null, null, new RunnableVal() { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java index a732df9a7..bfe3cc4c9 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java @@ -5,25 +5,44 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; -import com.github.intellectualsites.plotsquared.plot.flag.*; +import com.github.intellectualsites.plotsquared.plot.flag.BlockStateListFlag; +import com.github.intellectualsites.plotsquared.plot.flag.Flag; +import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.flag.IntegerFlag; +import com.github.intellectualsites.plotsquared.plot.flag.ListFlag; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.PlotWeather; +import com.github.intellectualsites.plotsquared.plot.util.StringComparison; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.sk89q.worldedit.world.block.BlockType; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; -@CommandDeclaration(command = "setflag", aliases = {"f", "flag", "setf", "setflag"}, - usage = "/plot flag ", description = "Set plot flags", - category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE, - permission = "plots.flag") public class FlagCmd extends SubCommand { +@CommandDeclaration(command = "setflag", aliases = {"f", "flag", + "setflag"}, usage = "/plot flag ", description = "Set plot flags", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE, permission = "plots.flag") +public class FlagCmd extends SubCommand { private boolean checkPermValue(PlotPlayer player, Flag flag, String key, String value) { key = key.toLowerCase(); value = value.toLowerCase(); - String perm = - Captions.PERMISSION_SET_FLAG_KEY_VALUE.f(key.toLowerCase(), value.toLowerCase()); + String perm = Captions + .format(Captions.PERMISSION_SET_FLAG_KEY_VALUE.getTranslated(), key.toLowerCase(), + value.toLowerCase()); if (flag instanceof IntegerFlag && MathMan.isInteger(value)) { try { int numeric = Integer.parseInt(value); @@ -34,26 +53,27 @@ import java.util.*; Settings.Limit.MAX_PLOTS; final boolean result = player.hasPermissionRange(perm, checkRange) >= numeric; if (!result) { - MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_SET_FLAG_KEY_VALUE - .f(key.toLowerCase(), value.toLowerCase())); + MainUtil.sendMessage(player, Captions.NO_PERMISSION, Captions + .format(Captions.PERMISSION_SET_FLAG_KEY_VALUE.getTranslated(), + key.toLowerCase(), value.toLowerCase())); } return result; } } catch (NumberFormatException ignore) { } - } else if (flag instanceof PlotBlockListFlag) { - final PlotBlockListFlag blockListFlag = (PlotBlockListFlag) flag; - final HashSet parsedBlocks = blockListFlag.parseValue(value); - for (final PlotBlock block : parsedBlocks) { - final String permission = Captions.PERMISSION_SET_FLAG_KEY_VALUE - .f(key.toLowerCase(), block.getRawId().toString().toLowerCase()); + } else if (flag instanceof BlockStateListFlag) { + final BlockStateListFlag blockListFlag = (BlockStateListFlag) flag; + Set parsedBlocks = blockListFlag.parseValue(value); + for (final BlockType block : parsedBlocks) { + final String permission = Captions + .format(Captions.PERMISSION_SET_FLAG_KEY_VALUE.getTranslated(), + key.toLowerCase(), block.toString().toLowerCase()); final boolean result = Permissions.hasPermission(player, permission); if (!result) { - MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_SET_FLAG_KEY_VALUE - .f(key.toLowerCase(), value.toLowerCase())); + MainUtil.sendMessage(player, Captions.NO_PERMISSION, Captions + .format(Captions.PERMISSION_SET_FLAG_KEY_VALUE.getTranslated(), + key.toLowerCase(), value.toLowerCase())); return false; } } @@ -61,8 +81,9 @@ import java.util.*; } final boolean result = Permissions.hasPermission(player, perm); if (!result) { - MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_SET_FLAG_KEY_VALUE.f(key.toLowerCase(), value.toLowerCase())); + MainUtil.sendMessage(player, Captions.NO_PERMISSION, Captions + .format(Captions.PERMISSION_SET_FLAG_KEY_VALUE.getTranslated(), key.toLowerCase(), + value.toLowerCase())); } return result; } @@ -77,12 +98,11 @@ import java.util.*; * plot flag list */ if (args.length == 0) { - MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, - "/plot flag "); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, getUsage()); return false; } - Location loc = player.getLocation(); - Plot plot = loc.getPlotAbs(); + Location location = player.getLocation(); + Plot plot = location.getPlotAbs(); if (plot == null) { MainUtil.sendMessage(player, Captions.NOT_IN_PLOT); return false; @@ -155,6 +175,11 @@ import java.util.*; MainUtil.sendMessage(player, "&c" + flag.getValueDescription()); return false; } + if (flag instanceof ListFlag) { + if (!(parsed instanceof Collection) || ((Collection) parsed).isEmpty()) { + return !MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED); + } + } boolean result = plot.setFlag(flag, parsed); if (!result) { MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED); @@ -174,11 +199,13 @@ import java.util.*; "/plot flag remove [values]"); return false; } - if (!Permissions.hasPermission(player, - Captions.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase()))) { + if (!Permissions.hasPermission(player, Captions + .format(Captions.PERMISSION_SET_FLAG_KEY.getTranslated(), + args[1].toLowerCase()))) { if (args.length != 3) { - MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase())); + MainUtil.sendMessage(player, Captions.NO_PERMISSION, Captions + .format(Captions.PERMISSION_SET_FLAG_KEY.getTranslated(), + args[1].toLowerCase())); return false; } for (String entry : args[2].split(",")) { @@ -189,25 +216,26 @@ import java.util.*; } if (args.length == 3 && flag instanceof ListFlag) { String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); - Optional flag1 = - plot.getFlag((Flag>) flag); - if (flag1.isPresent()) { - boolean o = flag1.get().removeAll((Collection) flag.parseValue(value)); - if (o) { - if (flag1.get().isEmpty()) { - final boolean result = plot.removeFlag(flag); - if (result) { - MainUtil.sendMessage(player, Captions.FLAG_REMOVED); + final ListFlag listFlag = (ListFlag) flag; + final Optional collectionOptional = plot.getFlag(listFlag); + if (collectionOptional.isPresent()) { + final Collection parsedCollection = (Collection) flag.parseValue(value); + if (parsedCollection.isEmpty()) { + return !MainUtil.sendMessage(player, Captions.FLAG_NOT_REMOVED); + } + final Collection flagCollection = collectionOptional.get(); + if (flagCollection.removeAll(parsedCollection)) { + if (flagCollection.isEmpty()) { + if (plot.removeFlag(flag)) { + return MainUtil.sendMessage(player, Captions.FLAG_REMOVED); } else { - MainUtil.sendMessage(player, Captions.FLAG_NOT_REMOVED); + return !MainUtil.sendMessage(player, Captions.FLAG_NOT_REMOVED); } - return true; } else { MainUtil.sendMessage(player, Captions.FLAG_REMOVED); } } else { - MainUtil.sendMessage(player, Captions.FLAG_NOT_REMOVED); - return false; + return !MainUtil.sendMessage(player, Captions.FLAG_NOT_REMOVED); } } DBFunc.setFlags(plot, plot.getFlags()); @@ -251,16 +279,19 @@ import java.util.*; } Object val = parsed; if (flag instanceof ListFlag) { - Optional flag1 = - plot.getFlag((Flag>) flag); - if (flag1.isPresent()) { - boolean o = flag1.get().addAll((Collection) parsed); - if (o) { + final Collection parsedCollection = (Collection) parsed; + if (parsedCollection.isEmpty()) { + return !MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED); + } + final ListFlag listFlag = (ListFlag) flag; + final Optional collectionOptional = plot.getFlag(listFlag); + if (collectionOptional.isPresent()) { + final Collection flagCollection = collectionOptional.get(); + if (flagCollection.addAll(parsedCollection)) { MainUtil.sendMessage(player, Captions.FLAG_ADDED); - val = flag1.get(); + val = flagCollection; } else { - MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED); - return false; + return !MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED); } } } @@ -281,29 +312,32 @@ import java.util.*; MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot flag list"); return false; } - HashMap> flags = new HashMap<>(); + final Map> flags = new HashMap<>(); for (Flag flag1 : Flags.getFlags()) { - String type = flag1.getClass().getSimpleName(); - if (!flags.containsKey(type)) { - flags.put(type, new ArrayList<>()); - } - flags.get(type).add(flag1.getName()); + final String category = flag1.getCategoryCaption(); + final Collection flagList = + flags.computeIfAbsent(category, k -> new ArrayList<>()); + flagList.add(flag1.getName()); } - StringBuilder message = new StringBuilder(); - String prefix = ""; - for (Map.Entry> entry : flags.entrySet()) { - String category = entry.getKey(); - List flagNames = entry.getValue(); + + final StringBuilder message = new StringBuilder(); + final Iterator>> iterator = + flags.entrySet().iterator(); + while (iterator.hasNext()) { + final Map.Entry> flagsEntry = iterator.next(); + final List flagNames = flagsEntry.getValue(); Collections.sort(flagNames); - message.append(prefix).append("&6").append(category).append(": &7") - .append(StringMan.join(flagNames, ", ")); - prefix = "\n"; + message.append(String.format(Captions.FLAG_LIST_ENTRY.formatted(), + flagsEntry.getKey(), StringMan.join(flagNames, ", "))); + if (iterator.hasNext()) { + message.append("\n"); + } } MainUtil.sendMessage(player, message.toString()); return true; } MainUtil - .sendMessage(player, Captions.COMMAND_SYNTAX, "/plot flag "); + .sendMessage(player, Captions.COMMAND_SYNTAX, getUsage()); return false; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java index 83161d73a..7a1d2cddc 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java @@ -142,7 +142,7 @@ public class GenerateDocs { Matcher m2 = p2.matcher(line); while (m2.find()) { - perms.add(Captions.valueOf("PERMISSION_" + m2.group(1)).s()); + perms.add(Captions.valueOf("PERMISSION_" + m2.group(1)).getTranslated()); } if (line.contains("Permissions.hasPermission(")) { String[] split = line.split("Permissions.hasPermission"); @@ -151,7 +151,7 @@ public class GenerateDocs { String perm = method.split("[,|)]")[1].trim(); if (!perm.equalsIgnoreCase(perm)) { if (perm.startsWith("C.")) { - perm = Captions.valueOf(perm.split("\\.")[1]).s(); + perm = Captions.valueOf(perm.split("\\.")[1]).getTranslated(); } else { continue; } @@ -181,7 +181,7 @@ public class GenerateDocs { String perm = method.split("[,|)]")[1].trim(); if (!perm.equalsIgnoreCase(perm)) { if (perm.startsWith("C.")) { - perm = Captions.valueOf(perm.split("\\.")[1]).s(); + perm = Captions.valueOf(perm.split("\\.")[1]).getTranslated(); } else { continue; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Grant.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Grant.java index a3e46dd08..a3d8855ec 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Grant.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Grant.java @@ -8,12 +8,13 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; -import com.github.intellectualsites.plotsquared.plot.util.ByteArrayUtilities; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.Permissions; import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.google.common.primitives.Ints; import java.util.UUID; +import java.util.concurrent.CompletableFuture; @CommandDeclaration(command = "grant", category = CommandCategory.CLAIMING, usage = "/plot grant [player]", permission = "plots.grant", @@ -23,7 +24,7 @@ import java.util.UUID; super(MainCommand.getInstance(), true); } - @Override public void execute(final PlotPlayer player, String[] args, + @Override public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { checkTrue(args.length >= 1 && args.length <= 2, Captions.COMMAND_SYNTAX, getUsage()); @@ -31,9 +32,11 @@ import java.util.UUID; switch (arg0) { case "add": case "check": - if (!Permissions.hasPermission(player, Captions.PERMISSION_GRANT.f(arg0))) { - Captions.NO_PERMISSION.send(player, Captions.PERMISSION_GRANT.f(arg0)); - return; + if (!Permissions.hasPermission(player, + Captions.format(Captions.PERMISSION_GRANT.getTranslated(), arg0))) { + Captions.NO_PERMISSION.send(player, + Captions.format(Captions.PERMISSION_GRANT.getTranslated(), arg0)); + return CompletableFuture.completedFuture(false); } if (args.length > 2) { break; @@ -46,7 +49,7 @@ import java.util.UUID; } if (uuid == null) { Captions.INVALID_PLAYER.send(player, args[1]); - return; + return CompletableFuture.completedFuture(false); } MainUtil.getPersistentMeta(uuid, "grantedPlots", new RunnableVal() { @Override public void run(byte[] array) { @@ -55,7 +58,7 @@ import java.util.UUID; if (array == null) { granted = 0; } else { - granted = ByteArrayUtilities.bytesToInteger(array); + granted = Ints.fromByteArray(array); } Captions.GRANTED_PLOTS.send(player, granted); } else { // add @@ -63,11 +66,11 @@ import java.util.UUID; if (array == null) { amount = 1; } else { - amount = 1 + ByteArrayUtilities.bytesToInteger(array); + amount = 1 + Ints.fromByteArray(array); } boolean replace = array != null; String key = "grantedPlots"; - byte[] rawData = ByteArrayUtilities.integerToBytes(amount); + byte[] rawData = Ints.toByteArray(amount); PlotPlayer online = UUIDHandler.getPlayer(uuid); if (online != null) { online.setPersistentMeta(key, rawData); @@ -77,7 +80,9 @@ import java.util.UUID; } } }); + return CompletableFuture.completedFuture(true); } Captions.COMMAND_SYNTAX.send(player, getUsage()); + return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java index 97c793221..7949df513 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java @@ -12,7 +12,9 @@ import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.StringMan; import com.github.intellectualsites.plotsquared.plot.util.helpmenu.HelpMenu; -@CommandDeclaration(command = "help", description = "Get this help menu", aliases = {"he", "?"}, +import java.util.concurrent.CompletableFuture; + +@CommandDeclaration(command = "help", description = "Get this help menu", aliases = "?", category = CommandCategory.INFO, usage = "help [category|#]", permission = "plots.use") public class Help extends Command { public Help(Command parent) { @@ -23,72 +25,75 @@ public class Help extends Command { return true; } - @Override public void execute(PlotPlayer player, String[] args, + @Override public CompletableFuture execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { switch (args.length) { case 0: - displayHelp(player, null, 0); - return; + return displayHelp(player, null, 0); case 1: if (MathMan.isInteger(args[0])) { try { - displayHelp(player, null, Integer.parseInt(args[0])); + return displayHelp(player, null, Integer.parseInt(args[0])); } catch (NumberFormatException ignored) { - displayHelp(player, null, 1); + return displayHelp(player, null, 1); } } else { - displayHelp(player, args[0], 1); + return displayHelp(player, args[0], 1); } - return; case 2: if (MathMan.isInteger(args[1])) { try { - displayHelp(player, args[0], Integer.parseInt(args[1])); + return displayHelp(player, args[0], Integer.parseInt(args[1])); } catch (NumberFormatException ignored) { - displayHelp(player, args[0], 1); + return displayHelp(player, args[0], 1); } } - return; + return CompletableFuture.completedFuture(false); default: Captions.COMMAND_SYNTAX.send(player, getUsage()); } + return CompletableFuture.completedFuture(true); } - public void displayHelp(CommandCaller player, String cat, int page) { - CommandCategory catEnum = null; - if (cat != null) { - if (StringMan.isEqualIgnoreCase(cat, "all")) { - catEnum = null; - } else { - for (CommandCategory c : CommandCategory.values()) { - if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) { - catEnum = c; - cat = c.name(); - break; + public CompletableFuture displayHelp(final CommandCaller player, final String catRaw, final int page) { + return CompletableFuture.supplyAsync(() -> { + String cat = catRaw; + + CommandCategory catEnum = null; + if (cat != null) { + if (!"all".equalsIgnoreCase(cat)) { + for (CommandCategory c : CommandCategory.values()) { + if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) { + catEnum = c; + cat = c.name(); + break; + } + } + if (catEnum == null) { + cat = null; } } - if (catEnum == null) { - cat = null; + } + if (cat == null && page == 0) { + StringBuilder builder = new StringBuilder(); + builder.append(Captions.HELP_HEADER.getTranslated()); + for (CommandCategory c : CommandCategory.values()) { + builder.append("\n").append(StringMan + .replaceAll(Captions.HELP_INFO_ITEM.getTranslated(), "%category%", + c.toString().toLowerCase(), + "%category_desc%", c.toString())); } + builder.append("\n") + .append(Captions.HELP_INFO_ITEM.getTranslated().replaceAll("%category%", "all") + .replaceAll("%category_desc%", "Display all commands")); + builder.append("\n").append(Captions.HELP_FOOTER.getTranslated()); + MainUtil.sendMessage(player, builder.toString(), false); + return true; } - } - if (cat == null && page == 0) { - StringBuilder builder = new StringBuilder(); - builder.append(Captions.HELP_HEADER.s()); - for (CommandCategory c : CommandCategory.values()) { - builder.append("\n" + StringMan - .replaceAll(Captions.HELP_INFO_ITEM.s(), "%category%", - c.toString().toLowerCase(), "%category_desc%", c.toString())); - } - builder.append("\n").append(Captions.HELP_INFO_ITEM.s().replaceAll("%category%", "all") - .replaceAll("%category_desc%", Captions.HELP_DISPLAY_ALL_COMMANDS.s())); - builder.append("\n" + Captions.HELP_FOOTER.s()); - MainUtil.sendMessage(player, builder.toString(), false); - return; - } - page--; - new HelpMenu(player).setCategory(catEnum).getCommands().generateMaxPages() - .generatePage(page, getParent().toString()).render(); + new HelpMenu(player).setCategory(catEnum).getCommands().generateMaxPages() + .generatePage(page - 1, getParent().toString()).render(); + return true; + }); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java index 4a59850a9..030ef0f44 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java @@ -14,9 +14,8 @@ import com.github.intellectualsites.plotsquared.plot.util.StringMan; import java.util.List; @CommandDeclaration(command = "inbox", description = "Review the comments for a plot", - usage = "/plot inbox [inbox] [delete |clear|page]", permission = "plots.inbox", - category = CommandCategory.CHAT, requiredType = RequiredType.PLAYER) public class Inbox - extends SubCommand { + usage = "/plot inbox [inbox] [delete |clear|page]", permission = "plots.inbox", category = CommandCategory.CHAT, requiredType = RequiredType.PLAYER) +public class Inbox extends SubCommand { public void displayComments(PlotPlayer player, List oldComments, int page) { if (oldComments == null || oldComments.isEmpty()) { @@ -40,7 +39,8 @@ import java.util.List; } StringBuilder string = new StringBuilder(); string.append(StringMan - .replaceAll(Captions.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur", + .replaceAll(Captions.COMMENT_LIST_HEADER_PAGED.getTranslated(), "%amount%", + comments.length, "%cur", page + 1, "%max", totalPages + 1, "%word", "all") + '\n'); // This might work xD @@ -70,8 +70,7 @@ import java.util.List; return false; } if (args.length == 0) { - sendMessage(player, Captions.COMMAND_SYNTAX, - "/plot inbox [inbox] [delete |clear|page]"); + sendMessage(player, Captions.COMMAND_SYNTAX, getUsage()); for (final CommentInbox inbox : CommentManager.inboxes.values()) { if (inbox.canRead(plot, player)) { if (!inbox.getComments(plot, new RunnableVal>() { @@ -148,8 +147,15 @@ import java.util.List; } PlotComment comment = value.get(index - 1); inbox.removeComment(plot, comment); - plot.removeComment(comment); - MainUtil.sendMessage(player, Captions.COMMENT_REMOVED, comment.comment); + boolean success = plot.removeComment(comment); + if (success) { + MainUtil.sendMessage(player, Captions.COMMENT_REMOVED_SUCCESS, + comment.comment); + } else { + MainUtil.sendMessage(player, Captions.COMMENT_REMOVED_FAILURE, + comment.comment); + + } } })) { sendMessage(player, Captions.NOT_IN_PLOT); @@ -165,14 +171,13 @@ import java.util.List; if (!comments.isEmpty()) { plot.removeComments(comments); } - MainUtil.sendMessage(player, Captions.COMMENT_REMOVED, "*"); + MainUtil.sendMessage(player, Captions.COMMENT_REMOVED_SUCCESS, "*"); return true; default: try { page = Integer.parseInt(args[1]); } catch (NumberFormatException ignored) { - sendMessage(player, Captions.COMMAND_SYNTAX, - "/plot inbox [inbox] [delete |clear|page]"); + sendMessage(player, Captions.COMMAND_SYNTAX, getUsage()); return false; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java index 51e5cd6c0..3db27bdd6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java @@ -5,7 +5,11 @@ import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.flag.Flags; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotInventory; +import com.github.intellectualsites.plotsquared.plot.object.PlotItemStack; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; @@ -53,7 +57,7 @@ public class Info extends SubCommand { plot = player.getCurrentPlot(); } if (plot == null) { - MainUtil.sendMessage(player, Captions.NOT_IN_PLOT.s()); + MainUtil.sendMessage(player, Captions.NOT_IN_PLOT.getTranslated()); return false; } @@ -70,7 +74,8 @@ public class Info extends SubCommand { boolean allowed = false; for (final String argument : args) { if (argument.equalsIgnoreCase("-f")) { - if (!player.hasPermission(Captions.PERMISSION_AREA_INFO_FORCE.s())) { + if (!player + .hasPermission(Captions.PERMISSION_AREA_INFO_FORCE.getTranslated())) { Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_INFO_FORCE); return true; } @@ -95,9 +100,9 @@ public class Info extends SubCommand { UUID uuid = player.getUUID(); String name = MainUtil.getName(plot.getOwner()); inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", - "&cID: &6" + plot.getId().toString(), "&cOwner: &6" + name, + "&cID: &6" + plot.getId().toString(), "&cOwner:&6" + name, "&cAlias: &6" + plot.getAlias(), - "&cBiome: &6" + plot.getBiome().replaceAll("_", "").toLowerCase(), + "&cBiome: &6" + plot.getBiome().toString().replaceAll("_", "").toLowerCase(), "&cCan Build: &6" + plot.isAdded(uuid), "&cSeen: &6" + MainUtil.secToTime((int) (ExpireManager.IMP.getAge(plot) / 1000)), "&cIs Denied: &6" + plot.isDenied(uuid))); @@ -125,7 +130,7 @@ public class Info extends SubCommand { plot.getId().x + ";" + plot.getId().y); return true; } - String info = Captions.PLOT_INFO.s(); + String info = Captions.PLOT_INFO.getTranslated(); boolean full; if (arg != null) { info = getCaption(arg); @@ -148,8 +153,8 @@ public class Info extends SubCommand { MainUtil.format(info, plot, player, full, new RunnableVal() { @Override public void run(String value) { MainUtil.sendMessage(player, - Captions.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + Captions.PLOT_INFO_FOOTER - .s(), false); + Captions.PLOT_INFO_HEADER.getTranslated() + '\n' + value + '\n' + + Captions.PLOT_INFO_FOOTER.getTranslated(), false); } }); return true; @@ -158,29 +163,29 @@ public class Info extends SubCommand { private String getCaption(String string) { switch (string) { case "trusted": - return Captions.PLOT_INFO_TRUSTED.s(); + return Captions.PLOT_INFO_TRUSTED.getTranslated(); case "alias": - return Captions.PLOT_INFO_ALIAS.s(); + return Captions.PLOT_INFO_ALIAS.getTranslated(); case "biome": - return Captions.PLOT_INFO_BIOME.s(); + return Captions.PLOT_INFO_BIOME.getTranslated(); case "denied": - return Captions.PLOT_INFO_DENIED.s(); + return Captions.PLOT_INFO_DENIED.getTranslated(); case "flags": - return Captions.PLOT_INFO_FLAGS.s(); + return Captions.PLOT_INFO_FLAGS.getTranslated(); case "id": - return Captions.PLOT_INFO_ID.s(); + return Captions.PLOT_INFO_ID.getTranslated(); case "size": - return Captions.PLOT_INFO_SIZE.s(); + return Captions.PLOT_INFO_SIZE.getTranslated(); case "members": - return Captions.PLOT_INFO_MEMBERS.s(); + return Captions.PLOT_INFO_MEMBERS.getTranslated(); case "owner": - return Captions.PLOT_INFO_OWNER.s(); + return Captions.PLOT_INFO_OWNER.getTranslated(); case "rating": - return Captions.PLOT_INFO_RATING.s(); + return Captions.PLOT_INFO_RATING.getTranslated(); case "likes": - return Captions.PLOT_INFO_LIKES.s(); + return Captions.PLOT_INFO_LIKES.getTranslated(); case "seen": - return Captions.PLOT_INFO_SEEN.s(); + return Captions.PLOT_INFO_SEEN.getTranslated(); default: return null; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Kick.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Kick.java index b749eaba4..eb36f8e67 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Kick.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Kick.java @@ -17,7 +17,7 @@ import java.util.HashSet; import java.util.Set; import java.util.UUID; -@CommandDeclaration(command = "kick", aliases = {"k"}, description = "Kick a player from your plot", +@CommandDeclaration(command = "kick", aliases = "k", description = "Kick a player from your plot", permission = "plots.kick", usage = "/plot kick ", category = CommandCategory.TELEPORT, requiredType = RequiredType.PLAYER) public class Kick extends SubCommand { @@ -79,7 +79,7 @@ import java.util.UUID; .getSpawn(PlotSquared.get().getPlotAreaManager().getAllWorlds()[0]); if (plot.equals(newSpawn.getPlot())) { // Kick from server if you can't be teleported to spawn - player2.kick(Captions.YOU_GOT_KICKED.s()); + player2.kick(Captions.YOU_GOT_KICKED.getTranslated()); } else { player2.plotkick(newSpawn); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Leave.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Leave.java index be29265bf..187977b2b 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Leave.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Leave.java @@ -11,21 +11,22 @@ import com.github.intellectualsites.plotsquared.plot.util.EventUtil; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import java.util.UUID; +import java.util.concurrent.CompletableFuture; @CommandDeclaration(command = "leave", description = "Removes self from being trusted or a member of the plot", - permission = "plots.leave", category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE) public class Leave extends Command { + permission = "plots.leave", usage = "/plot leave", category = CommandCategory.CLAIMING, + requiredType = RequiredType.PLAYER) public class Leave extends Command { public Leave() { super(MainCommand.getInstance(), true); } - @Override public void execute(PlotPlayer player, String[] args, + @Override public CompletableFuture execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT); checkTrue(plot.hasOwner(), Captions.PLOT_UNOWNED); - checkTrue(plot.isAdded(player.getUUID()), Captions.NO_PLOT_PERMS); + checkTrue(plot.isAdded(player.getUUID()), Captions.NOT_ADDED_TRUSTED); checkTrue(args.length == 0, Captions.COMMAND_SYNTAX, getUsage()); if (plot.isOwner(player.getUUID())) { checkTrue(plot.hasOwner(), Captions.ALREADY_OWNER); @@ -39,10 +40,11 @@ import java.util.UUID; if (plot.removeMember(uuid)) { EventUtil.manager.callMember(player, plot, uuid, false); } - MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[0]); + MainUtil.sendMessage(player, Captions.PLOT_LEFT, player.getName()); } else { - MainUtil.sendMessage(player, Captions.REMOVED_PLAYERS, 1); + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, 1); } } + return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Like.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Like.java index f839a9b1a..378da26c2 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Like.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Like.java @@ -14,7 +14,11 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.Permissions; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; @CommandDeclaration(command = "like", permission = "plots.like", description = "Like the plot", usage = "/plot like [next|purge]", category = CommandCategory.INFO, diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java index e2951db6a..8230922c6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java @@ -5,12 +5,27 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.PlotSquared.SortType; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.flag.Flags; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Rating; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.StringComparison; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.Map.Entry; +import java.util.Optional; +import java.util.UUID; @CommandDeclaration(command = "list", aliases = {"l", "find", "search"}, description = "List plots", permission = "plots.list", category = CommandCategory.INFO, @@ -20,7 +35,7 @@ public class ListCmd extends SubCommand { private String[] getArgumentList(PlotPlayer player) { List args = new ArrayList<>(); if (EconHandler.manager != null && Permissions - .hasPermission(player, Captions.PERMISSION_LIST_FORSALE)) { + .hasPermission(player, Captions.PERMISSION_LIST_FOR_SALE)) { args.add("forsale"); } if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_MINE)) { @@ -63,8 +78,8 @@ public class ListCmd extends SubCommand { } public void noArgs(PlotPlayer player) { - MainUtil.sendMessage(player, - Captions.SUBCOMMAND_SET_OPTIONS_HEADER.s() + Arrays.toString(getArgumentList(player))); + MainUtil.sendMessage(player, Captions.SUBCOMMAND_SET_OPTIONS_HEADER.getTranslated() + Arrays + .toString(getArgumentList(player))); } @Override public boolean onCommand(PlotPlayer player, String[] args) { @@ -122,9 +137,10 @@ public class ListCmd extends SubCommand { return false; } if (!Permissions - .hasPermission(player, Captions.PERMISSION_LIST_WORLD_NAME.f(world))) { + .hasPermission(player, + Captions.format(Captions.PERMISSION_LIST_WORLD_NAME.getTranslated(), world))) { MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_LIST_WORLD_NAME.f(world)); + Captions.format(Captions.PERMISSION_LIST_WORLD_NAME.getTranslated(), world)); return false; } plots = new ArrayList<>(PlotSquared.get().getPlots(world)); @@ -146,9 +162,10 @@ public class ListCmd extends SubCommand { return false; } if (!Permissions - .hasPermission(player, Captions.PERMISSION_LIST_WORLD_NAME.f(world))) { + .hasPermission(player, + Captions.format(Captions.PERMISSION_LIST_WORLD_NAME.getTranslated(), world))) { MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_LIST_WORLD_NAME.f(world)); + Captions.format(Captions.PERMISSION_LIST_WORLD_NAME.getTranslated(), world)); return false; } plots = area == null ? new ArrayList() : new ArrayList<>(area.getPlots()); @@ -199,8 +216,7 @@ public class ListCmd extends SubCommand { int p1s = p1.getSettings().getRatings().size(); int p2s = p2.getRatings().size(); if (!p1.getSettings().getRatings().isEmpty()) { - v1 = p1.getRatings().entrySet().stream() - .mapToDouble(entry -> entry.getValue().getAverageRating()) + v1 = p1.getRatings().values().stream().mapToDouble(Rating::getAverageRating) .map(av -> av * av).sum(); v1 /= p1s; v1 += p1s; @@ -222,9 +238,9 @@ public class ListCmd extends SubCommand { sort = false; break; case "forsale": - if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_FORSALE)) { + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_FOR_SALE)) { MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_LIST_FORSALE); + Captions.PERMISSION_LIST_FOR_SALE); return false; } if (EconHandler.manager == null) { @@ -294,9 +310,10 @@ public class ListCmd extends SubCommand { return false; } if (!Permissions - .hasPermission(player, Captions.PERMISSION_LIST_WORLD_NAME.f(args[0]))) { - MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_LIST_WORLD_NAME.f(args[0])); + .hasPermission(player, Captions + .format(Captions.PERMISSION_LIST_WORLD_NAME.getTranslated(), args[0]))) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, Captions + .format(Captions.PERMISSION_LIST_WORLD_NAME.getTranslated(), args[0])); return false; } plots = new ArrayList<>(PlotSquared.get().getPlots(args[0])); @@ -339,12 +356,7 @@ public class ListCmd extends SubCommand { public void displayPlots(final PlotPlayer player, List plots, int pageSize, int page, PlotArea area, String[] args, boolean sort) { // Header - Iterator iterator = plots.iterator(); - while (iterator.hasNext()) { - if (!iterator.next().isBasePlot()) { - iterator.remove(); - } - } + plots.removeIf(plot -> !plot.isBasePlot()); if (sort) { plots = PlotSquared.get().sortPlots(plots, SortType.CREATION_DATE, area); } @@ -364,19 +376,19 @@ public class ListCmd extends SubCommand { color = "$1"; } PlotMessage trusted = new PlotMessage().text(Captions.color( - Captions.PLOT_INFO_TRUSTED.s() + Captions.PLOT_INFO_TRUSTED.getTranslated() .replaceAll("%trusted%", MainUtil.getPlayerList(plot.getTrusted())))) .color("$1"); PlotMessage members = new PlotMessage().text(Captions.color( - Captions.PLOT_INFO_MEMBERS.s() + Captions.PLOT_INFO_MEMBERS.getTranslated() .replaceAll("%members%", MainUtil.getPlayerList(plot.getMembers())))) .color("$1"); String strFlags = StringMan.join(plot.getFlags().values(), ","); if (strFlags.isEmpty()) { - strFlags = Captions.NONE.s(); + strFlags = Captions.NONE.getTranslated(); } - PlotMessage flags = new PlotMessage().text(Captions - .color(Captions.PLOT_INFO_FLAGS.s().replaceAll("%flags%", strFlags))) + PlotMessage flags = new PlotMessage().text(Captions.color( + Captions.PLOT_INFO_FLAGS.getTranslated().replaceAll("%flags%", strFlags))) .color("$1"); message.text("[").color("$3").text(i + "") .command("/plot visit " + plot.getArea() + ";" + plot.getId()) @@ -404,7 +416,7 @@ public class ListCmd extends SubCommand { prefix = ", "; } } - }, "/plot list " + args[0], Captions.PLOT_LIST_HEADER_PAGED.s()); + }, "/plot list " + args[0], Captions.PLOT_LIST_HEADER_PAGED.getTranslated()); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java index 234568fda..4b0305969 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java @@ -4,7 +4,11 @@ import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.schematic.Schematic; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.Permissions; @@ -15,7 +19,7 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.List; -@CommandDeclaration(command = "load", aliases = {"restore"}, category = CommandCategory.SCHEMATIC, +@CommandDeclaration(command = "load", aliases = "restore", category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE, description = "Load your plot", permission = "plots.load", usage = "/plot load") public class Load extends SubCommand { @@ -50,9 +54,9 @@ import java.util.List; MainUtil.sendMessage(player, Captions.LOAD_NULL); return false; } - String schem; + String schematic; try { - schem = schematics.get(Integer.parseInt(args[0]) - 1); + schematic = schematics.get(Integer.parseInt(args[0]) - 1); } catch (Exception ignored) { // use /plot load MainUtil.sendMessage(player, Captions.NOT_VALID_NUMBER, @@ -61,7 +65,7 @@ import java.util.List; } final URL url; try { - url = new URL(Settings.Web.URL + "saves/" + player.getUUID() + '/' + schem); + url = new URL(Settings.Web.URL + "saves/" + player.getUUID() + '/' + schematic); } catch (MalformedURLException e) { e.printStackTrace(); MainUtil.sendMessage(player, Captions.LOAD_FAILED); @@ -70,8 +74,8 @@ import java.util.List; plot.addRunning(); MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); TaskManager.runTaskAsync(() -> { - Schematic schematic = SchematicHandler.manager.getSchematic(url); - if (schematic == null) { + Schematic taskSchematic = SchematicHandler.manager.getSchematic(url); + if (taskSchematic == null) { plot.removeRunning(); sendMessage(player, Captions.SCHEMATIC_INVALID, "non-existent or not in gzip format"); @@ -79,7 +83,7 @@ import java.util.List; } PlotArea area = plot.getArea(); SchematicHandler.manager - .paste(schematic, plot, 0, area.MIN_BUILD_HEIGHT, 0, false, + .paste(taskSchematic, plot, 0, area.MIN_BUILD_HEIGHT, 0, false, new RunnableVal() { @Override public void run(Boolean value) { plot.removeRunning(); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java index d1daa73cd..dd060c88e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java @@ -5,12 +5,20 @@ import com.github.intellectualsites.plotsquared.commands.CommandCaller; import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer; +import com.github.intellectualsites.plotsquared.plot.object.Expression; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; import com.github.intellectualsites.plotsquared.plot.util.CmdConfirm; import com.github.intellectualsites.plotsquared.plot.util.EconHandler; import com.github.intellectualsites.plotsquared.plot.util.Permissions; import java.util.Arrays; +import java.util.concurrent.CompletableFuture; /** * PlotSquared command class. @@ -176,6 +184,8 @@ public class MainCommand extends Command { @Override public void run(Command cmd, CommandResult result) { // Post command stuff!? } + }).thenAccept(result -> { + // TODO: Something with the command result }); } catch (CommandException e) { e.perform(player); @@ -184,25 +194,25 @@ public class MainCommand extends Command { return true; } - @Override public void execute(final PlotPlayer player, String[] args, + @Override public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { // Clear perm caching // player.deleteMeta("perm"); // Optional command scope // - Location loc = null; + Location location = null; Plot plot = null; boolean tp = false; if (args.length >= 2) { PlotArea area = player.getApplicablePlotArea(); Plot newPlot = Plot.fromString(area, args[0]); if (newPlot != null && (player instanceof ConsolePlayer || newPlot.getArea() - .equals(area) || Permissions.hasPermission(player, Captions.PERMISSION_ADMIN)) + .equals(area) || Permissions.hasPermission(player, Captions.PERMISSION_ADMIN) || Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_SUDO_AREA)) && !newPlot.isDenied(player.getUUID())) { Location newLoc = newPlot.getCenter(); if (player.canTeleport(newLoc)) { // Save meta - loc = player.getMeta(PlotPlayer.META_LOCATION); + location = player.getMeta(PlotPlayer.META_LOCATION); plot = player.getMeta(PlotPlayer.META_LAST_PLOT); tp = true; // Set loc @@ -215,37 +225,32 @@ public class MainCommand extends Command { args = Arrays.copyOfRange(args, 1, args.length); } if (args.length >= 2 && !args[0].isEmpty() && args[0].charAt(0) == '-') { - switch (args[0].substring(1)) { - case "f": - confirm = new RunnableVal3() { - @Override - public void run(Command cmd, Runnable success, Runnable failure) { - if (EconHandler.manager != null) { - PlotArea area = player.getApplicablePlotArea(); - if (area != null) { - Expression priceEval = - area.PRICES.get(cmd.getFullId()); - Double price = - priceEval != null ? priceEval.evaluate(0d) : 0d; - if (price != 0d - && EconHandler.manager.getMoney(player) < price) { - if (failure != null) { - failure.run(); - } - return; + if ("f".equals(args[0].substring(1))) { + confirm = new RunnableVal3() { + @Override public void run(Command cmd, Runnable success, Runnable failure) { + if (EconHandler.manager != null) { + PlotArea area = player.getApplicablePlotArea(); + if (area != null) { + Expression priceEval = area.PRICES.get(cmd.getFullId()); + Double price = priceEval != null ? priceEval.evaluate(0d) : 0d; + if (price != 0d + && EconHandler.manager.getMoney(player) < price) { + if (failure != null) { + failure.run(); } + return; } } - if (success != null) { - success.run(); - } } - }; - args = Arrays.copyOfRange(args, 1, args.length); - break; - default: - Captions.INVALID_COMMAND_FLAG.send(player); - return; + if (success != null) { + success.run(); + } + } + }; + args = Arrays.copyOfRange(args, 1, args.length); + } else { + Captions.INVALID_COMMAND_FLAG.send(player); + return CompletableFuture.completedFuture(false); } } } @@ -264,10 +269,10 @@ public class MainCommand extends Command { } // Reset command scope // if (tp && !(player instanceof ConsolePlayer)) { - if (loc == null) { + if (location == null) { player.deleteMeta(PlotPlayer.META_LOCATION); } else { - player.setMeta(PlotPlayer.META_LOCATION, loc); + player.setMeta(PlotPlayer.META_LOCATION, location); } if (plot == null) { player.deleteMeta(PlotPlayer.META_LAST_PLOT); @@ -275,6 +280,7 @@ public class MainCommand extends Command { player.setMeta(PlotPlayer.META_LAST_PLOT, plot); } } + return CompletableFuture.completedFuture(true); } @Override public boolean canExecute(CommandCaller player, boolean message) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java index 970a0d35c..43204b266 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java @@ -3,13 +3,25 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.Direction; +import com.github.intellectualsites.plotsquared.plot.object.Expression; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.CmdConfirm; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import java.util.UUID; +import static com.github.intellectualsites.plotsquared.plot.object.Direction.getFromIndex; + @CommandDeclaration(command = "merge", aliases = "m", - description = "Merge the plot you are standing on, with another plot", + description = "Merge the plot you are standing on with another plot", permission = "plots.merge", usage = "/plot merge [removeroads]", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE, confirmation = true) public class Merge extends SubCommand { @@ -40,8 +52,8 @@ public class Merge extends SubCommand { } @Override public boolean onCommand(final PlotPlayer player, String[] args) { - Location loc = player.getLocationFull(); - final Plot plot = loc.getPlotAbs(); + Location location = player.getLocationFull(); + final Plot plot = location.getPlotAbs(); if (plot == null) { return !sendMessage(player, Captions.NOT_IN_PLOT); } @@ -59,8 +71,7 @@ public class Merge extends SubCommand { } } final PlotArea plotArea = plot.getArea(); - Expression priceExr = - plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null; + Expression priceExr = plotArea.PRICES.getOrDefault("merge", null); final int size = plot.getConnectedPlots().size(); final double price = priceExr == null ? 0d : priceExr.evaluate((double) size); if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d @@ -74,20 +85,20 @@ public class Merge extends SubCommand { MainUtil.sendMessage(player, Captions.NO_PERMISSION, "plots.merge." + (size + 1)); return false; } - int direction = -1; + Direction direction = Direction.ALL; if (args.length == 0) { switch (direction(player.getLocationFull().getYaw())) { case "NORTH": - direction = 0; + direction = Direction.NORTH; break; case "EAST": - direction = 1; + direction = Direction.EAST; break; case "SOUTH": - direction = 2; + direction = Direction.SOUTH; break; case "WEST": - direction = 3; + direction = Direction.WEST; break; } } else { @@ -97,12 +108,12 @@ public class Merge extends SubCommand { terrain = "true".equalsIgnoreCase(args[1]); } if (!terrain && !Permissions - .hasPermission(player, Captions.PERMISSION_MERGE_KEEPROAD)) { + .hasPermission(player, Captions.PERMISSION_MERGE_KEEP_ROAD)) { MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_MERGE_KEEPROAD.s()); + Captions.PERMISSION_MERGE_KEEP_ROAD.getTranslated()); return true; } - if (plot.autoMerge(-1, maxSize, uuid, terrain)) { + if (plot.autoMerge(Direction.ALL, maxSize, uuid, terrain)) { if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d) { EconHandler.manager.withdrawMoney(player, price); sendMessage(player, Captions.REMOVED_BALANCE, String.valueOf(price)); @@ -116,16 +127,16 @@ public class Merge extends SubCommand { } for (int i = 0; i < values.length; i++) { if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) { - direction = i; + direction = getFromIndex(i); break; } } } - if (direction == -1) { + if (direction == Direction.ALL) { MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot merge <" + StringMan.join(values, "|") + "> [removeroads]"); - MainUtil.sendMessage(player, - Captions.DIRECTION.s().replaceAll("%dir%", direction(loc.getYaw()))); + MainUtil.sendMessage(player, Captions.DIRECTION.getTranslated() + .replaceAll("%dir%", direction(location.getYaw()))); return false; } final boolean terrain; @@ -134,9 +145,9 @@ public class Merge extends SubCommand { } else { terrain = true; } - if (!terrain && !Permissions.hasPermission(player, Captions.PERMISSION_MERGE_KEEPROAD)) { + if (!terrain && !Permissions.hasPermission(player, Captions.PERMISSION_MERGE_KEEP_ROAD)) { MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_MERGE_KEEPROAD.s()); + Captions.PERMISSION_MERGE_KEEP_ROAD.getTranslated()); return true; } if (plot.autoMerge(direction, maxSize - size, uuid, terrain)) { @@ -148,7 +159,8 @@ public class Merge extends SubCommand { return true; } Plot adjacent = plot.getRelative(direction); - if (adjacent == null || !adjacent.hasOwner() || adjacent.getMerged((direction + 2) % 4) + if (adjacent == null || !adjacent.hasOwner() || adjacent + .getMerged((direction.getIndex() + 2) % 4) || adjacent.isOwner(uuid)) { MainUtil.sendMessage(player, Captions.NO_AVAILABLE_AUTOMERGE); return false; @@ -165,7 +177,7 @@ public class Merge extends SubCommand { continue; } isOnline = true; - final int dir = direction; + final Direction dir = direction; Runnable run = () -> { MainUtil.sendMessage(accepter, Captions.MERGE_ACCEPTED); plot.autoMerge(dir, maxSize - size, owner, terrain); @@ -185,8 +197,8 @@ public class Merge extends SubCommand { MainUtil.sendMessage(player, Captions.SUCCESS_MERGE); }; if (hasConfirmation(player)) { - CmdConfirm.addPending(accepter, - Captions.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", player.getName()), run); + CmdConfirm.addPending(accepter, Captions.MERGE_REQUEST_CONFIRM.getTranslated() + .replaceAll("%s", player.getName()), run); } else { run.run(); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Middle.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Middle.java index 8fbec1ecb..f3acaf5a0 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Middle.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Middle.java @@ -11,7 +11,7 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; */ @CommandDeclaration(command = "middle", aliases = {"center", "centre"}, description = "Teleports you to the center of the plot", usage = "/plot middle", - category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE) public class Middle + category = CommandCategory.TELEPORT, requiredType = RequiredType.PLAYER) public class Middle extends SubCommand { @Override public boolean onCommand(PlotPlayer player, String[] arguments) { @@ -20,9 +20,6 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; if (plot == null) { return sendMessage(player, Captions.NOT_IN_PLOT); } - if (!plot.hasOwner()) { - return sendMessage(player, Captions.PLOT_UNOWNED); - } player.teleport(plot.getCenter()); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java index e52ec1fcf..02c7494cb 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java @@ -11,17 +11,17 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.Permissions; @CommandDeclaration(usage = "/plot move ", command = "move", description = "Move a plot", - aliases = {"debugmove"}, permission = "plots.move", category = CommandCategory.CLAIMING, + permission = "plots.move", category = CommandCategory.CLAIMING, requiredType = RequiredType.PLAYER) public class Move extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { - Location loc = player.getLocation(); - Plot plot1 = loc.getPlotAbs(); + Location location = player.getLocation(); + Plot plot1 = location.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot1.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN.s())) { + .hasPermission(player, Captions.PERMISSION_ADMIN.getTranslated())) { MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } @@ -50,7 +50,7 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; return false; } if (!plot1.getArea().isCompatible(plot2.getArea()) && (!override || !Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN.s()))) { + .hasPermission(player, Captions.PERMISSION_ADMIN.getTranslated()))) { Captions.PLOTWORLD_INCOMPATIBLE.send(player); return false; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Music.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Music.java index e773879ae..482a1f050 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Music.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Music.java @@ -3,7 +3,12 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.flag.Flags; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotInventory; +import com.github.intellectualsites.plotsquared.plot.object.PlotItemStack; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.sk89q.worldedit.world.item.ItemTypes; import java.util.Arrays; import java.util.Collection; @@ -20,8 +25,8 @@ import java.util.Locale; "music_disc_strad", "music_disc_ward", "music_disc_11", "music_disc_wait"); @Override public boolean onCommand(PlotPlayer player, String[] args) { - Location loc = player.getLocation(); - final Plot plot = loc.getPlotAbs(); + Location location = player.getLocation(); + final Plot plot = location.getPlotAbs(); if (plot == null) { return !sendMessage(player, Captions.NOT_IN_PLOT); } @@ -35,11 +40,11 @@ import java.util.Locale; if (item == null) { return true; } - if (item.getPlotBlock().equalsAny(7, "bedrock")) { + if (item.getType() == ItemTypes.BEDROCK) { plot.removeFlag(Flags.MUSIC); Captions.FLAG_REMOVED.send(player); } else if (item.name.toLowerCase(Locale.ENGLISH).contains("disc")) { - plot.setFlag(Flags.MUSIC, item.getPlotBlock().getRawId()); + plot.setFlag(Flags.MUSIC, item.getType().getId()); Captions.FLAG_ADDED.send(player); } else { Captions.FLAG_NOT_ADDED.send(player); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Near.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Near.java index 3d73c7bbe..d897fb3cf 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Near.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Near.java @@ -9,6 +9,8 @@ import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import java.util.concurrent.CompletableFuture; + @CommandDeclaration(command = "near", aliases = "n", description = "Display nearby players", usage = "/plot near", category = CommandCategory.INFO, requiredType = RequiredType.PLAYER) public class Near extends Command { @@ -16,10 +18,11 @@ public class Near extends Command { super(MainCommand.getInstance(), true); } - @Override public void execute(PlotPlayer player, String[] args, + @Override public CompletableFuture execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT); Captions.PLOT_NEAR.send(player, StringMan.join(plot.getPlayersInPlot(), ", ")); + return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java index 89416512f..82ec9f652 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java @@ -5,7 +5,11 @@ import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.CmdConfirm; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import java.util.Set; import java.util.UUID; @@ -16,6 +20,10 @@ import java.util.UUID; requiredType = RequiredType.NONE, confirmation = true) public class Owner extends SetCommand { @Override public boolean set(final PlotPlayer player, final Plot plot, String value) { + if (value == null || value.isEmpty()) { + Captions.SET_OWNER_MISSING_PLAYER.send(player); + return false; + } Set plots = plot.getConnectedPlots(); UUID uuid = null; String name = null; @@ -33,8 +41,8 @@ import java.util.UUID; if (uuid == null || value.equalsIgnoreCase("-")) { if (value.equalsIgnoreCase("none") || value.equalsIgnoreCase("null") || value .equalsIgnoreCase("-")) { - if (!Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SETOWNER.s(), true)) { + if (!Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_COMMAND_SET_OWNER.getTranslated(), true)) { return false; } Set connected = plot.getConnectedPlots(); @@ -54,7 +62,7 @@ import java.util.UUID; Captions.ALREADY_OWNER.send(player, MainUtil.getName(uuid)); return false; } - if (!Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SETOWNER)) { + if (!Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SET_OWNER)) { if (other == null) { Captions.INVALID_PLAYER_OFFLINE.send(player, value); return false; @@ -71,20 +79,18 @@ import java.util.UUID; final String finalName = name; final UUID finalUUID = uuid; final boolean removeDenied = plot.isDenied(finalUUID); - Runnable run = new Runnable() { - @Override public void run() { - if (plot.setOwner(finalUUID, player)) { - if (removeDenied) - plot.removeDenied(finalUUID); - plot.setSign(finalName); - MainUtil.sendMessage(player, Captions.SET_OWNER); - if (other != null) { - MainUtil.sendMessage(other, Captions.NOW_OWNER, - plot.getArea() + ";" + plot.getId()); - } - } else { - MainUtil.sendMessage(player, Captions.SET_OWNER_CANCELLED); + Runnable run = () -> { + if (plot.setOwner(finalUUID, player)) { + if (removeDenied) + plot.removeDenied(finalUUID); + plot.setSign(finalName); + MainUtil.sendMessage(player, Captions.SET_OWNER); + if (other != null) { + MainUtil.sendMessage(other, Captions.NOW_OWNER, + plot.getArea() + ";" + plot.getId()); } + } else { + MainUtil.sendMessage(player, Captions.SET_OWNER_CANCELLED); } }; if (hasConfirmation(player)) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/PluginCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/PluginCmd.java index 81047ec9b..8e31051fb 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/PluginCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/PluginCmd.java @@ -21,9 +21,9 @@ import com.github.intellectualsites.plotsquared.plot.util.TaskManager; MainUtil.sendMessage(player, "$2>> $1&lAuthors$2: $1Citymonstret $2& $1Empire92 $2& $1MattBDev $2& $1dordsor21"); MainUtil.sendMessage(player, - "$2>> $1&lWiki$2: $1https://github.com/IntellectualCrafters/PlotSquared/wiki"); - MainUtil.sendMessage(player, - "$2>> $1&lNewest Version$2: $1" + getNewestVersionString()); + "$2>> $1&lWiki$2: $1https://github.com/IntellectualSites/PlotSquared/wiki"); + // MainUtil.sendMessage(player, + // "$2>> $1&lNewest Version$2: $1" + getNewestVersionString()); } }); return true; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java index 9c93925b6..f81f02719 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java @@ -7,8 +7,16 @@ import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.flag.Flags; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotInventory; +import com.github.intellectualsites.plotsquared.plot.object.PlotItemStack; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Rating; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import java.util.ArrayList; import java.util.HashMap; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RegenAllRoads.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RegenAllRoads.java index 9fcdc811d..e47cb610f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RegenAllRoads.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RegenAllRoads.java @@ -43,7 +43,7 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD); return false; } - //Set chunks = ChunkManager.manager.getChunkChunks(name); + //Set chunks = ChunkManager.manager.getChunkChunks(name); MainUtil .sendMessage(player, "&cIf no schematic is set, the following will not do anything"); MainUtil.sendMessage(player, diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java index 65656117a..cc5c8c21a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java @@ -3,37 +3,40 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.Command; import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.config.Captions; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; -import java.util.HashSet; +import java.util.concurrent.CompletableFuture; @CommandDeclaration(command = "relight", description = "Relight your plot", usage = "/plot relight", - category = CommandCategory.DEBUG) public class Relight extends Command { + category = CommandCategory.DEBUG, requiredType = RequiredType.PLAYER) public class Relight extends Command { public Relight() { super(MainCommand.getInstance(), true); } - @Override public void execute(final PlotPlayer player, String[] args, + @Override public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { final Plot plot = player.getCurrentPlot(); if (plot == null) { Captions.NOT_IN_PLOT.send(player); - return; + return CompletableFuture.completedFuture(false); } - HashSet regions = plot.getRegions(); final LocalBlockQueue queue = plot.getArea().getQueue(false); ChunkManager.chunkTask(plot, new RunnableVal() { @Override public void run(int[] value) { queue.fixChunkLighting(value[0], value[1]); } - }, new Runnable() { - @Override public void run() { - plot.refreshChunks(); - Captions.SET_BLOCK_ACTION_FINISHED.send(player); - } + }, () -> { + plot.refreshChunks(); + Captions.SET_BLOCK_ACTION_FINISHED.send(player); }, 5); + + return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Remove.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Remove.java index 30c364671..038355d83 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Remove.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Remove.java @@ -44,11 +44,11 @@ import java.util.UUID; int count = 0; switch (args[0]) { case "unknown": { - ArrayList toRemove = new ArrayList<>(); HashSet all = new HashSet<>(); all.addAll(plot.getMembers()); all.addAll(plot.getTrusted()); all.addAll(plot.getDenied()); + ArrayList toRemove = new ArrayList<>(); for (UUID uuid : all) { if (UUIDHandler.getName(uuid) == null) { toRemove.add(uuid); @@ -66,18 +66,7 @@ import java.util.UUID; Set uuids = MainUtil.getUUIDsFromString(args[0]); if (!uuids.isEmpty()) { for (UUID uuid : uuids) { - if (uuid == DBFunc.EVERYONE) { - if (plot.removeTrusted(uuid)) { - EventUtil.manager.callTrusted(player, plot, uuid, false); - count++; - } else if (plot.removeMember(uuid)) { - EventUtil.manager.callMember(player, plot, uuid, false); - count++; - } else if (plot.removeDenied(uuid)) { - EventUtil.manager.callDenied(player, plot, uuid, false); - count++; - } - } else if (plot.getTrusted().contains(uuid)) { + if (plot.getTrusted().contains(uuid)) { if (plot.removeTrusted(uuid)) { EventUtil.manager.callTrusted(player, plot, uuid, false); count++; @@ -92,6 +81,17 @@ import java.util.UUID; EventUtil.manager.callDenied(player, plot, uuid, false); count++; } + } else if (uuid == DBFunc.EVERYONE) { + if (plot.removeTrusted(uuid)) { + EventUtil.manager.callTrusted(player, plot, uuid, false); + count++; + } else if (plot.removeMember(uuid)) { + EventUtil.manager.callMember(player, plot, uuid, false); + count++; + } else if (plot.removeDenied(uuid)) { + EventUtil.manager.callDenied(player, plot, uuid, false); + count++; + } } } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Save.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Save.java index 481acba53..d000f55e2 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Save.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Save.java @@ -3,7 +3,11 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.Permissions; import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java index 48f0a8a1c..130f2ad1d 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java @@ -4,9 +4,19 @@ import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.schematic.Schematic; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.google.common.collect.Lists; import java.net.URL; import java.util.ArrayList; @@ -15,7 +25,7 @@ import java.util.UUID; @CommandDeclaration(command = "schematic", permission = "plots.schematic", description = "Schematic command", aliases = {"sch", "schem"}, - category = CommandCategory.SCHEMATIC, usage = "/plot schematic ") + category = CommandCategory.SCHEMATIC, usage = "/plot schematic ") public class SchematicCmd extends SubCommand { private boolean running = false; @@ -52,7 +62,7 @@ public class SchematicCmd extends SubCommand { return false; } if (this.running) { - MainUtil.sendMessage(player, "&cTask is already running."); + MainUtil.sendMessage(player, Captions.TASK_IN_PROCESS); return false; } final String location = args[1]; @@ -99,38 +109,6 @@ public class SchematicCmd extends SubCommand { }); break; } - // TODO test - // case "test": { - // if (!Permissions.hasPermission(plr, "plots.schematic.test")) { - // MainUtil.sendMessage(plr, Captions.NO_PERMISSION, "plots.schematic.test"); - // return false; - // } - // if (args.length < 2) { - // sendMessage(plr, Captions.SCHEMATIC_MISSING_ARG); - // return false; - // } - // final Location loc = plr.getLocation(); - // final Plot plot = MainUtil.getPlot(loc); - // if (plot == null) { - // sendMessage(plr, Captions.NOT_IN_PLOT); - // return false; - // } - // file = args[1]; - // schematic = SchematicHandler.manager.getSchematic(file); - // if (schematic == null) { - // sendMessage(plr, Captions.SCHEMATIC_INVALID, "non-existent"); - // return false; - // } - // final int l1 = schematic.getSchematicDimension().getX(); - // final int l2 = schematic.getSchematicDimension().getZ(); - // final int length = MainUtil.getPlotWidth(loc.getWorld(), plot.id); - // if ((l1 < length) || (l2 < length)) { - // sendMessage(plr, Captions.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); - // break; - // } - // sendMessage(plr, Captions.SCHEMATIC_VALID); - // break; - // } case "saveall": case "exportall": { if (!(player instanceof ConsolePlayer)) { @@ -138,8 +116,7 @@ public class SchematicCmd extends SubCommand { return false; } if (args.length != 2) { - MainUtil.sendMessage(player, - "&cNeed world argument. Use &7/plot sch exportall "); + MainUtil.sendMessage(player, Captions.SCHEMATIC_EXPORTALL_WORLD_ARGS); return false; } PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]); @@ -149,20 +126,17 @@ public class SchematicCmd extends SubCommand { } Collection plots = area.getPlots(); if (plots.isEmpty()) { - MainUtil - .sendMessage(player, "&cInvalid world. Use &7/plot sch exportall "); + MainUtil.sendMessage(player, Captions.SCHEMATIC_EXPORTALL_WORLD); return false; } boolean result = SchematicHandler.manager.exportAll(plots, null, null, - () -> MainUtil.sendMessage(player, "&aFinished mass export")); + () -> MainUtil.sendMessage(player, Captions.SCHEMATIC_EXPORTALL_FINISHED)); if (!result) { - MainUtil.sendMessage(player, "&cTask is already running."); + MainUtil.sendMessage(player, Captions.TASK_IN_PROCESS); return false; } else { - MainUtil.sendMessage(player, - "&3Plot&8->&3Schematic&8: &7Mass export has started. This may take a while."); - MainUtil.sendMessage(player, - "&3Plot&8->&3Schematic&8: &7Found &c" + plots.size() + "&7 plots..."); + MainUtil.sendMessage(player, Captions.SCHEMATIC_EXPORTALL_STARTED); + MainUtil.sendMessage(player, "&3Plot&8->&3Schematic&8: &7Found &c" + plots.size() + "&7 plots..."); } break; } @@ -174,7 +148,7 @@ public class SchematicCmd extends SubCommand { return false; } if (this.running) { - MainUtil.sendMessage(player, "&cTask is already running."); + MainUtil.sendMessage(player, Captions.TASK_IN_PROCESS); return false; } Location location = player.getLocation(); @@ -191,18 +165,16 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } - location.getWorld(); - Collection plots = new ArrayList<>(); - plots.add(plot); + ArrayList plots = Lists.newArrayList(plot); boolean result = SchematicHandler.manager.exportAll(plots, null, null, () -> { - MainUtil.sendMessage(player, "&aFinished export"); + MainUtil.sendMessage(player, Captions.SCHEMATIC_EXPORTALL_SINGLE_FINISHED); SchematicCmd.this.running = false; }); if (!result) { - MainUtil.sendMessage(player, "&cTask is already running."); + MainUtil.sendMessage(player, Captions.TASK_IN_PROCESS); return false; } else { - MainUtil.sendMessage(player, "&7Starting export..."); + MainUtil.sendMessage(player, Captions.SCHEMATIC_EXPORTALL_STARTED); } break; case "list": { @@ -212,7 +184,7 @@ public class SchematicCmd extends SubCommand { return false; } final String string = - StringMan.join(SchematicHandler.manager.getShematicNames(), "$2, $1"); + StringMan.join(SchematicHandler.manager.getSchematicNames(), "$2, $1"); Captions.SCHEMATIC_LIST.send(player, string); } break; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Set.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Set.java index 6f9277166..438086b43 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Set.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Set.java @@ -3,14 +3,18 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.Command; import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.config.Captions; -import com.github.intellectualsites.plotsquared.plot.config.Configuration; -import com.github.intellectualsites.plotsquared.plot.config.Configuration.UnknownBlockException; import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; import com.github.intellectualsites.plotsquared.plot.flag.Flags; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.world.PatternUtil; +import com.sk89q.worldedit.function.pattern.Pattern; import java.util.ArrayList; import java.util.Arrays; @@ -36,9 +40,8 @@ import java.util.stream.IntStream; } @Override public boolean set(PlotPlayer player, final Plot plot, String value) { - PlotArea plotArea = player.getLocation().getPlotArea(); PlotManager manager = player.getLocation().getPlotManager(); - String[] components = manager.getPlotComponents(plotArea, plot.getId()); + String[] components = manager.getPlotComponents(plot.getId()); boolean allowUnsafe = DebugAllowUnsafe.unsafeAllowed.contains(player.getUUID()); String[] args = value.split(" "); @@ -47,62 +50,29 @@ import java.util.stream.IntStream; for (String component : components) { if (component.equalsIgnoreCase(args[0])) { - if (!Permissions.hasPermission(player, - Captions.PERMISSION_SET_COMPONENT.f(component))) { - MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_SET_COMPONENT.f(component)); + if (!Permissions.hasPermission(player, Captions + .format(Captions.PERMISSION_SET_COMPONENT.getTranslated(), component))) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, Captions + .format(Captions.PERMISSION_SET_COMPONENT.getTranslated(), + component)); return false; } - // PlotBlock[] blocks; - BlockBucket bucket; - try { - if (args.length < 2) { - MainUtil.sendMessage(player, Captions.NEED_BLOCK); - return true; - } - String[] split = material.split(","); - // blocks = Configuration.BLOCKLIST.parseString(material); - - try { - bucket = Configuration.BLOCK_BUCKET.parseString(material); - } catch (final UnknownBlockException unknownBlockException) { - final String unknownBlock = unknownBlockException.getUnknownValue(); - Captions.NOT_VALID_BLOCK.send(player, unknownBlock); - StringComparison.ComparisonResult match = - WorldUtil.IMP.getClosestBlock(unknownBlock); - if (match != null) { - final String found = - WorldUtil.IMP.getClosestMatchingName(match.best); - if (found != null) { - MainUtil.sendMessage(player, Captions.DID_YOU_MEAN, - found.toLowerCase()); - } - } - return false; - } - - if (!allowUnsafe) { - for (final PlotBlock block : bucket.getBlocks()) { - if (!block.isAir() && !WorldUtil.IMP.isBlockSolid(block)) { - Captions.NOT_ALLOWED_BLOCK.send(player, block.toString()); - return false; - } - } - } - } catch (Exception ignored) { - MainUtil.sendMessage(player, Captions.NOT_VALID_BLOCK, material); - return false; + if (args.length < 2) { + MainUtil.sendMessage(player, Captions.NEED_BLOCK); + return true; } + + Pattern pattern = PatternUtil.parse(player, material); if (plot.getRunning() > 0) { MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER); return false; } plot.addRunning(); for (Plot current : plot.getConnectedPlots()) { - current.setComponent(component, bucket); + current.setComponent(component, pattern); } MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); - GlobalBlockQueue.IMP.addTask(plot::removeRunning); + GlobalBlockQueue.IMP.addEmptyTask(plot::removeRunning); return true; } } @@ -117,10 +87,11 @@ import java.util.stream.IntStream; Plot plot = player.getCurrentPlot(); if (plot != null) { newValues.addAll( - Arrays.asList(plot.getManager().getPlotComponents(plot.getArea(), plot.getId()))); + Arrays.asList(plot.getManager().getPlotComponents(plot.getId()))); } - MainUtil.sendMessage(player, Captions.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringMan - .join(newValues, Captions.BLOCK_LIST_SEPARATER.formatted())); + MainUtil + .sendMessage(player, Captions.SUBCOMMAND_SET_OPTIONS_HEADER.getTranslated() + StringMan + .join(newValues, Captions.BLOCK_LIST_SEPARATOR.formatted())); return false; } @@ -144,7 +115,7 @@ import java.util.stream.IntStream; } // components HashSet components = new HashSet<>( - Arrays.asList(plot.getManager().getPlotComponents(plot.getArea(), plot.getId()))); + Arrays.asList(plot.getManager().getPlotComponents(plot.getId()))); if (components.contains(args[0].toLowerCase())) { return this.component.onCommand(player, Arrays.copyOfRange(args, 0, args.length)); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetCommand.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetCommand.java index bc64f0244..8ec4bee2c 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetCommand.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetCommand.java @@ -11,25 +11,27 @@ import com.github.intellectualsites.plotsquared.plot.util.StringMan; public abstract class SetCommand extends SubCommand { @Override public boolean onCommand(PlotPlayer player, String[] args) { - Location loc = player.getLocation(); - Plot plot = loc.getPlotAbs(); + Location location = player.getLocation(); + Plot plot = location.getPlotAbs(); if (plot == null) { return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { if (!Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND.f(getFullId()))) { + .hasPermission(player, + Captions.format(Captions.PERMISSION_ADMIN_COMMAND.getTranslated(), getFullId()))) { MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_ADMIN_COMMAND.f(getFullId())); + Captions.format(Captions.PERMISSION_ADMIN_COMMAND.getTranslated(), getFullId())); MainUtil.sendMessage(player, Captions.PLOT_NOT_CLAIMED); return false; } } if (!plot.isOwner(player.getUUID())) { if (!Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND.f(getFullId()))) { + .hasPermission(player, + Captions.format(Captions.PERMISSION_ADMIN_COMMAND.getTranslated(), getFullId()))) { MainUtil.sendMessage(player, Captions.NO_PERMISSION, - Captions.PERMISSION_ADMIN_COMMAND.f(getFullId())); + Captions.format(Captions.PERMISSION_ADMIN_COMMAND.getTranslated(), getFullId())); MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetHome.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetHome.java index af0968a92..4b742ad94 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetHome.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetHome.java @@ -10,7 +10,7 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; @CommandDeclaration(command = "sethome", permission = "plots.set.home", description = "Set the plot home to your current position", usage = "/plot sethome [none]", - aliases = {"sh", "seth"}, category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) + aliases = {"sh", "seth"}, category = CommandCategory.SETTINGS, requiredType = RequiredType.PLAYER) public class SetHome extends SetCommand { @Override public boolean set(PlotPlayer player, Plot plot, String value) { @@ -25,11 +25,10 @@ public class SetHome extends SetCommand { } case "": Plot base = plot.getBasePlot(false); - Location bot = base.getBottomAbs(); - Location loc = player.getLocationFull(); - BlockLoc rel = - new BlockLoc(loc.getX() - bot.getX(), loc.getY(), loc.getZ() - bot.getZ(), - loc.getYaw(), loc.getPitch()); + Location bottom = base.getBottomAbs(); + Location location = player.getLocationFull(); + BlockLoc rel = new BlockLoc(location.getX() - bottom.getX(), location.getY(), + location.getZ() - bottom.getZ(), location.getYaw(), location.getPitch()); base.setHome(rel); return MainUtil.sendMessage(player, Captions.POSITION_SET); default: diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java index 66fbd041a..eb7826ee5 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java @@ -6,16 +6,32 @@ import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Configuration; import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.SetupObject; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; import com.github.intellectualsites.plotsquared.plot.util.StringMan; import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; -import lombok.*; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.ToString; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.UUID; @CommandDeclaration(command = "setup", permission = "plots.admin.command.setup", description = "Setup wizard for plot worlds", usage = "/plot setup", aliases = {"create"}, @@ -260,8 +276,9 @@ import java.util.Map.Entry; Captions.NOT_ALLOWED_BLOCK.send(player, e.getUnsafeBlock().toString()); } if (valid) { - sendMessage(player, Captions.SETUP_VALID_ARG, step.getConstant(), args[0]); step.setValue(args[0]); + Object value = step.getValue(); + sendMessage(player, Captions.SETUP_VALID_ARG, step.getConstant(), value); object.setup_index++; if (object.setup_index == object.step.length) { onCommand(player, args); @@ -284,6 +301,11 @@ import java.util.Map.Entry; MainUtil.sendMessage(player, "&cYou need to choose a world name!"); return false; } + if (!d(args[0])) { + MainUtil.sendMessage(player, + "Non [a-z0-9_.-] character in the world name: " + args[0]); + return false; + } if (WorldUtil.IMP.isWorld(args[0])) { if (PlotSquared.get().hasPlotArea(args[0])) { MainUtil.sendMessage(player, "&cThat world name is already taken!"); @@ -313,6 +335,11 @@ import java.util.Map.Entry; return false; } + private static boolean d(String s) { + return s.chars().allMatch((i) -> { + return i == 95 || i == 45 || i >= 97 && i <= 122 || i >= 48 && i <= 57 || i == 46; + }); + } private static final class StepPickGenerator extends SetupStep { @Getter private String generator; @@ -345,7 +372,7 @@ import java.util.Map.Entry; return messages; } - @Override public boolean parseInut(String input) { + @Override public boolean parseInput(String input) { this.generator = input.toLowerCase(); return true; } @@ -385,7 +412,7 @@ import java.util.Map.Entry; return messages; } - @Override public boolean parseInut(String input) { + @Override public boolean parseInput(String input) { if (!WORLD_TYPES.keySet().contains(input.toLowerCase())) { return false; } @@ -416,7 +443,7 @@ import java.util.Map.Entry; public abstract Collection showDescriptionMessage(); - public abstract boolean parseInut(String input); + public abstract boolean parseInput(String input); public final PlotMessage getUsage() { return new PlotMessage("Usage: ").color("$1") diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SubCommand.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SubCommand.java index 91dd83069..458442ff2 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SubCommand.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SubCommand.java @@ -7,6 +7,8 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import java.util.concurrent.CompletableFuture; + /** * SubCommand class * @@ -28,10 +30,10 @@ public abstract class SubCommand extends Command { return true; } - @Override public void execute(PlotPlayer player, String[] args, + @Override public CompletableFuture execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { - onCommand(player, args); + return CompletableFuture.completedFuture(onCommand(player, args)); } public abstract boolean onCommand(PlotPlayer player, String[] args); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java index da709d2a3..b3ec2ff05 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java @@ -13,13 +13,13 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; public class Swap extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { - Location loc = player.getLocation(); - Plot plot1 = loc.getPlotAbs(); + Location location = player.getLocation(); + Plot plot1 = location.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot1.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN.s())) { + .hasPermission(player, Captions.PERMISSION_ADMIN.getTranslated())) { MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java index 472542523..85a0fe633 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java @@ -8,14 +8,21 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.FileBytes; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.SetupObject; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -113,8 +120,7 @@ import java.util.zip.ZipOutputStream; return true; } } - MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, - "/plot template [template]"); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, getUsage()); return true; } final String world = args[1]; @@ -159,7 +165,7 @@ import java.util.zip.ZipOutputStream; setup.step = new ConfigurationNode[0]; setup.world = world; SetupUtils.manager.setupWorld(setup); - GlobalBlockQueue.IMP.addTask(() -> { + GlobalBlockQueue.IMP.addEmptyTask(() -> { MainUtil.sendMessage(player, "Done!"); player.teleport(WorldUtil.IMP.getSpawn(world)); }); @@ -179,7 +185,7 @@ import java.util.zip.ZipOutputStream; final PlotManager manager = area.getPlotManager(); TaskManager.runTaskAsync(() -> { try { - manager.exportTemplate(area); + manager.exportTemplate(); } catch (Exception e) { // Must recover from any exception thrown a third party template manager e.printStackTrace(); MainUtil.sendMessage(player, "Failed: " + e.getMessage()); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Toggle.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Toggle.java index d9bd9bd99..87411f1c6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Toggle.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Toggle.java @@ -3,13 +3,13 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.Command; import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.config.Captions; -import com.github.intellectualsites.plotsquared.plot.object.PlotArea; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; @CommandDeclaration(command = "toggle", aliases = {"attribute"}, permission = "plots.use", + usage = "/plot toggle ", description = "Toggle per user settings", requiredType = RequiredType.NONE, category = CommandCategory.SETTINGS) public class Toggle extends Command { public Toggle() { @@ -17,7 +17,7 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; } @CommandDeclaration(command = "chatspy", aliases = {"spy"}, - permission = "plots.admin.command.chat", description = "Toggle admin chat spying") + permission = "plots.admin.command.chat", description = "Toggle plot chat spy") public void chatspy(Command command, PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { @@ -69,9 +69,19 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; public void titles(Command command, PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { - PlotArea area = player.getApplicablePlotArea(); - boolean chat = area != null && area.PLOT_CHAT; - if (toggle(player, "disabletitles") != chat) { + if (toggle(player, "disabletitles")) { + MainUtil.sendMessage(player, Captions.TOGGLE_ENABLED, command.toString()); + } else { + MainUtil.sendMessage(player, Captions.TOGGLE_DISABLED, command.toString()); + } + } + + @CommandDeclaration(command = "time", permission = "plots.toggle.time", + description = "Toggle plot time settings") + public void time(Command command, PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { + if (toggle(player, "disabletime")) { MainUtil.sendMessage(player, Captions.TOGGLE_ENABLED, command.toString()); } else { MainUtil.sendMessage(player, Captions.TOGGLE_DISABLED, command.toString()); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trim.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trim.java index 291657454..fcdce4898 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trim.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trim.java @@ -3,7 +3,11 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; @@ -11,6 +15,9 @@ import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; +import com.github.intellectualsites.plotsquared.plot.util.world.RegionUtil; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.regions.CuboidRegion; import java.io.File; import java.io.IOException; @@ -31,7 +38,7 @@ import java.util.Set; public static ArrayList expired = null; private static volatile boolean TASK = false; - public static boolean getBulkRegions(final ArrayList empty, final String world, + public static boolean getBulkRegions(final ArrayList empty, final String world, final Runnable whenDone) { if (Trim.TASK) { return false; @@ -71,7 +78,7 @@ import java.util.Set; String[] split = name.split("\\."); int x = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); - ChunkLoc loc = new ChunkLoc(x, z); + BlockVector2 loc = BlockVector2.at(x, z); empty.add(loc); } catch (NumberFormatException ignored) { PlotSquared.debug("INVALID MCA: " + name); @@ -90,13 +97,12 @@ import java.util.Set; * @return */ public static boolean getTrimRegions(String world, - final RunnableVal2, Set> result) { + final RunnableVal2, Set> result) { if (result == null) { return false; } MainUtil.sendMessage(null, "Collecting region data..."); - ArrayList plots = new ArrayList<>(); - plots.addAll(PlotSquared.get().getPlots(world)); + ArrayList plots = new ArrayList<>(PlotSquared.get().getPlots(world)); if (ExpireManager.IMP != null) { plots.removeAll(ExpireManager.IMP.getPendingExpired()); } @@ -115,7 +121,7 @@ import java.util.Set; int ccz2 = pos2.getZ() >> 9; for (int x = ccx1; x <= ccx2; x++) { for (int z = ccz1; z <= ccz2; z++) { - ChunkLoc loc = new ChunkLoc(x, z); + BlockVector2 loc = BlockVector2.at(x, z); if (result.value1.remove(loc)) { result.value2.add(loc); } @@ -142,8 +148,8 @@ import java.util.Set; } Trim.TASK = true; final boolean regen = args.length == 2 && Boolean.parseBoolean(args[1]); - getTrimRegions(world, new RunnableVal2, Set>() { - @Override public void run(Set viable, final Set nonViable) { + getTrimRegions(world, new RunnableVal2, Set>() { + @Override public void run(Set viable, final Set nonViable) { Runnable regenTask; if (regen) { PlotSquared.log("Starting regen task:"); @@ -156,53 +162,51 @@ import java.util.Set; player.sendMessage("Trim done!"); return; } - Iterator iterator = nonViable.iterator(); - ChunkLoc mcr = iterator.next(); + Iterator iterator = nonViable.iterator(); + BlockVector2 mcr = iterator.next(); iterator.remove(); - int cbx = mcr.x << 5; - int cbz = mcr.z << 5; + int cbx = mcr.getX() << 5; + int cbz = mcr.getZ() << 5; // get all 1024 chunks - HashSet chunks = new HashSet<>(); + HashSet chunks = new HashSet<>(); for (int x = cbx; x < cbx + 32; x++) { for (int z = cbz; z < cbz + 32; z++) { - ChunkLoc loc = new ChunkLoc(x, z); + BlockVector2 loc = BlockVector2.at(x, z); chunks.add(loc); } } int bx = cbx << 4; int bz = cbz << 4; - RegionWrapper region = new RegionWrapper(bx, bx + 511, bz, bz + 511); + CuboidRegion region = RegionUtil.createRegion(bx, bx + 511, bz, bz + 511); for (Plot plot : PlotSquared.get().getPlots(world)) { Location bot = plot.getBottomAbs(); Location top = plot.getExtendedTopAbs(); - RegionWrapper plotReg = - new RegionWrapper(bot.getX(), top.getX(), bot.getZ(), + CuboidRegion plotReg = + RegionUtil.createRegion(bot.getX(), top.getX(), bot.getZ(), top.getZ()); - if (!region.intersects(plotReg)) { + if (!RegionUtil.intersects(region, plotReg)) { continue; } - for (int x = plotReg.minX >> 4; x <= plotReg.maxX >> 4; x++) { - for (int z = plotReg.minZ >> 4; z <= plotReg.maxZ >> 4; z++) { - ChunkLoc loc = new ChunkLoc(x, z); + for (int x = plotReg.getMinimumPoint().getX() >> 4; x <= plotReg.getMaximumPoint().getX() >> 4; x++) { + for (int z = plotReg.getMinimumPoint().getZ() >> 4; z <= plotReg.getMaximumPoint().getZ() >> 4; z++) { + BlockVector2 loc = BlockVector2.at(x, z); chunks.remove(loc); } } } final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false); - TaskManager.objectTask(chunks, new RunnableVal() { - @Override public void run(ChunkLoc value) { - queue.regenChunk(value.x, value.z); + TaskManager.objectTask(chunks, new RunnableVal() { + @Override public void run(BlockVector2 value) { + queue.regenChunk(value.getX(), value.getZ()); } }, this); } }; } else { - regenTask = new Runnable() { - @Override public void run() { - Trim.TASK = false; - player.sendMessage("Trim done!"); - } + regenTask = () -> { + Trim.TASK = false; + player.sendMessage("Trim done!"); }; } ChunkManager.manager.deleteRegionFiles(world, viable, regenTask); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trust.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trust.java index 6724efdda..c0cd3309e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trust.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trust.java @@ -15,17 +15,18 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; import java.util.Iterator; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CompletableFuture; @CommandDeclaration(command = "trust", aliases = {"t"}, requiredType = RequiredType.PLAYER, usage = "/plot trust ", - description = "Allow a user to build in a plot while you are offline", + description = "Allow a user to build in a plot and use WorldEdit while you are offline", category = CommandCategory.SETTINGS) public class Trust extends Command { public Trust() { super(MainCommand.getInstance(), true); } - @Override public void execute(final PlotPlayer player, String[] args, + @Override public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { final Plot currentPlot = player.getCurrentPlot(); @@ -39,25 +40,25 @@ import java.util.UUID; checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage()); final Set uuids = MainUtil.getUUIDsFromString(args[0]); checkTrue(!uuids.isEmpty(), Captions.INVALID_PLAYER, args[0]); - Iterator iter = uuids.iterator(); + Iterator iterator = uuids.iterator(); int size = currentPlot.getTrusted().size() + currentPlot.getMembers().size(); - while (iter.hasNext()) { - UUID uuid = iter.next(); + while (iterator.hasNext()) { + UUID uuid = iterator.next(); if (uuid == DBFunc.EVERYONE && !( Permissions.hasPermission(player, Captions.PERMISSION_TRUST_EVERYONE) || Permissions .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST))) { MainUtil.sendMessage(player, Captions.INVALID_PLAYER, MainUtil.getName(uuid)); - iter.remove(); + iterator.remove(); continue; } if (currentPlot.isOwner(uuid)) { - MainUtil.sendMessage(player, Captions.ALREADY_OWNER, MainUtil.getName(uuid)); - iter.remove(); + MainUtil.sendMessage(player, Captions.ALREADY_ADDED, MainUtil.getName(uuid)); + iterator.remove(); continue; } if (currentPlot.getTrusted().contains(uuid)) { MainUtil.sendMessage(player, Captions.ALREADY_ADDED, MainUtil.getName(uuid)); - iter.remove(); + iterator.remove(); continue; } size += currentPlot.getMembers().contains(uuid) ? 0 : 1; @@ -81,5 +82,7 @@ import java.util.UUID; MainUtil.sendMessage(player, Captions.TRUSTED_ADDED); } }, null); + + return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Unlink.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Unlink.java index 9ce6bd5fb..66682ccda 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Unlink.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Unlink.java @@ -5,7 +5,11 @@ import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.CmdConfirm; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; @CommandDeclaration(command = "unlink", aliases = {"u", "unmerge"}, description = "Unlink a mega-plot", usage = "/plot unlink [createroads]", @@ -13,9 +17,8 @@ import com.github.intellectualsites.plotsquared.plot.util.*; public class Unlink extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { - - Location loc = player.getLocation(); - final Plot plot = loc.getPlotAbs(); + Location location = player.getLocation(); + final Plot plot = location.getPlotAbs(); if (plot == null) { return !sendMessage(player, Captions.NOT_IN_PLOT); } @@ -41,7 +44,7 @@ public class Unlink extends SubCommand { } Runnable runnable = () -> { if (!plot.unlinkPlot(createRoad, createRoad)) { - MainUtil.sendMessage(player, "&cUnlink has been cancelled"); + MainUtil.sendMessage(player, Captions.UNMERGE_CANCELLED); return; } MainUtil.sendMessage(player, Captions.UNLINK_SUCCESS); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Visit.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Visit.java index f5dc5710e..e2b7fa382 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Visit.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Visit.java @@ -5,17 +5,27 @@ import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.Permissions; import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; @CommandDeclaration(command = "visit", permission = "plots.visit", description = "Visit someones plot", usage = "/plot visit [|||] [#]", - aliases = {"v", "tp", "teleport", "goto", "home", "h"}, requiredType = RequiredType.PLAYER, + aliases = {"v", "tp", "teleport", "goto", "home", "h", "warp"}, requiredType = RequiredType.PLAYER, category = CommandCategory.TELEPORT) public class Visit extends Command { public Visit() { @@ -26,7 +36,7 @@ import java.util.*; return tabOf(player, args, space, getUsage()); } - @Override public void execute(final PlotPlayer player, String[] args, + @Override public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, final RunnableVal2 whenDone) throws CommandException { if (args.length == 1 && args[0].contains(":")) { @@ -41,7 +51,7 @@ import java.util.*; if (!MathMan.isInteger(args[1])) { Captions.NOT_VALID_NUMBER.send(player, "(1, ∞)"); Captions.COMMAND_SYNTAX.send(player, getUsage()); - return; + return CompletableFuture.completedFuture(false); } page = Integer.parseInt(args[2]); case 2: @@ -50,12 +60,12 @@ import java.util.*; if (sortByArea == null) { Captions.NOT_VALID_NUMBER.send(player, "(1, ∞)"); Captions.COMMAND_SYNTAX.send(player, getUsage()); - return; + return CompletableFuture.completedFuture(false); } UUID user = UUIDHandler.getUUIDFromString(args[0]); if (user == null) { Captions.COMMAND_SYNTAX.send(player, getUsage()); - return; + return CompletableFuture.completedFuture(false); } unsorted = PlotSquared.get().getBasePlots(user); shouldSortByArea = true; @@ -93,7 +103,7 @@ import java.util.*; } if (unsorted == null || unsorted.isEmpty()) { Captions.FOUND_NO_PLOTS.send(player); - return; + return CompletableFuture.completedFuture(false); } unsorted = new ArrayList<>(unsorted); if (unsorted.size() > 1) { @@ -101,7 +111,7 @@ import java.util.*; } if (page < 1 || page > unsorted.size()) { Captions.NOT_VALID_NUMBER.send(player, "(1, " + unsorted.size() + ")"); - return; + return CompletableFuture.completedFuture(false); } List plots; if (shouldSortByArea) { @@ -114,23 +124,24 @@ import java.util.*; if (!plot.hasOwner()) { if (!Permissions.hasPermission(player, Captions.PERMISSION_VISIT_UNOWNED)) { Captions.NO_PERMISSION.send(player, Captions.PERMISSION_VISIT_UNOWNED); - return; + return CompletableFuture.completedFuture(false); } } else if (plot.isOwner(player.getUUID())) { if (!Permissions.hasPermission(player, Captions.PERMISSION_VISIT_OWNED) && !Permissions .hasPermission(player, Captions.PERMISSION_HOME)) { Captions.NO_PERMISSION.send(player, Captions.PERMISSION_VISIT_OWNED); - return; + return CompletableFuture.completedFuture(false); } } else if (plot.isAdded(player.getUUID())) { if (!Permissions.hasPermission(player, Captions.PERMISSION_SHARED)) { Captions.NO_PERMISSION.send(player, Captions.PERMISSION_SHARED); - return; + return CompletableFuture.completedFuture(false); } } else { - if (!Permissions.hasPermission(player, Captions.PERMISSION_VISIT_OTHER)) { + if (!Permissions.hasPermission(player, Captions.PERMISSION_VISIT_OTHER) && + !Flags.UNTRUSTED_VISIT.isTrue(plot)) { Captions.NO_PERMISSION.send(player, Captions.PERMISSION_VISIT_OTHER); - return; + return CompletableFuture.completedFuture(false); } } confirm.run(this, () -> { @@ -140,6 +151,8 @@ import java.util.*; whenDone.run(Visit.this, CommandResult.FAILURE); } }, () -> whenDone.run(Visit.this, CommandResult.FAILURE)); + + return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/WE_Anywhere.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/WE_Anywhere.java index bd18e3886..36744cc44 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/WE_Anywhere.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/WE_Anywhere.java @@ -4,8 +4,9 @@ import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @CommandDeclaration(command = "weanywhere", permission = "plots.worldedit.bypass", - description = "Force bypass of WorldEdit", aliases = {"wea"}, usage = "/plot weanywhere", - requiredType = RequiredType.NONE, category = CommandCategory.ADMINISTRATION) @Deprecated + description = "Force bypass of WorldEdit restrictions", aliases = {"wea"}, usage = "/plot weanywhere", + requiredType = RequiredType.NONE, category = CommandCategory.ADMINISTRATION) +@Deprecated public class WE_Anywhere extends SubCommand { @Override public boolean onCommand(PlotPlayer player, String[] arguments) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Captions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Captions.java index 2037bcdf1..be175260b 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Captions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Captions.java @@ -21,16 +21,13 @@ import java.util.Set; public enum Captions { //@formatter:off - /* - * Static flags - */ + // FLAG_USE("use", "static.flags"), FLAG_BREAK("break", "static.flags"), FLAG_PLACE("place", "static.flags"), FLAG_PVP("pvp", "static.flags"), FLAG_HANGING_PLACE("hanging-place", "static.flags"), FLAG_HANGING_BREAK("hanging-break", "static.flags"), - FLAG_HANGING_INTERACT("hanging-interact", "static.flags"), FLAG_MISC_INTERACT("misc-interact", "static.flags"), FLAG_MISC_BREAK("misc-break", "static.flags"), FLAG_MISC_PLACE("misc-place", "static.flags"), @@ -44,24 +41,25 @@ public enum Captions { FLAG_TAMED_INTERACT("tamed-interact", "static.flags"), FLAG_DISABLE_PHYSICS("disable-physics", "static.flags"), FLAG_MOB_PLACE("mob-place", "static.flags"), - /* - * Static permission - */ + // + // PERMISSION_STAR("*", "static.permissions"), PERMISSION_ADMIN("plots.admin", "static.permissions"), + PERMISSION_ADMIN_SUDO_AREA("plots.admin.area.sudo", "static.permissions"), PERMISSION_PROJECTILE_UNOWNED("plots.projectile.unowned", "static.permissions"), PERMISSION_PROJECTILE_OTHER("plots.projectile.other", "static.permissions"), PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS("plots.admin.interact.blockedcommands", "static.permissions"), PERMISSION_WORLDEDIT_BYPASS("plots.worldedit.bypass", "static.permissions"), PERMISSION_PLOT_TOGGLE_TITLES("plots.toggle.titles", "static.permissions"), PERMISSION_PLOT_TOGGLE_CHAT("plots.toggle.chat", "static.permissions"), + PERMISSION_PLOT_TOGGLE_TIME("plots.toggle.time", "static.permissions"), PERMISSION_ADMIN_UPDATE_NOTIFICATION("plots.admin.update.notify", "static.permissions"), PERMISSION_ADMIN_EXIT_DENIED("plots.admin.exit.denied", "static.permissions"), PERMISSION_ADMIN_ENTRY_DENIED("plots.admin.entry.denied", "static.permissions"), PERMISSION_ADMIN_ENTRY_FORCEFIELD("plots.admin.entry.forcefield", "static.permissions"), PERMISSION_COMMANDS_CHAT("plots.admin.command.chat", "static.permissions"), PERMISSION_MERGE_OTHER("plots.merge.other", "static.permissions"), - PERMISSION_MERGE_KEEPROAD("plots.merge.keeproad", "static.permissions"), + PERMISSION_MERGE_KEEP_ROAD("plots.merge.keeproad", "static.permissions"), PERMISSION_ADMIN_DESTROY_UNOWNED("plots.admin.destroy.unowned", "static.permissions"), PERMISSION_ADMIN_DESTROY_GROUNDLEVEL("plots.admin.destroy.groundlevel", "static.permissions"), PERMISSION_ADMIN_DESTROY_OTHER("plots.admin.destroy.other", "static.permissions"), @@ -72,7 +70,7 @@ public enum Captions { PERMISSION_ADMIN_INTERACT_ROAD("plots.admin.interact.road", "static.permissions"), PERMISSION_ADMIN_INTERACT_UNOWNED("plots.admin.interact.unowned", "static.permissions"), PERMISSION_ADMIN_INTERACT_OTHER("plots.admin.interact.other", "static.permissions"), - PERMISSION_ADMIN_BUILD_HEIGHTLIMIT("plots.admin.build.heightlimit", "static.permissions"), + PERMISSION_ADMIN_BUILD_HEIGHT_LIMIT("plots.admin.build.heightlimit", "static.permissions"), PERMISSION_ADMIN_UPDATE("plots.admin.command.update", "static.permissions"), PERMISSION_ADMIN_COMMAND_RATE("plots.admin.command.rate", "static.permissions"), PERMISSION_ADMIN_COMMAND_TRUST("plots.admin.command.trust", "static.permissions"), @@ -126,7 +124,7 @@ public enum Captions { PERMISSION_FLAG_LIST("plots.flag.list", "static.permissions"), PERMISSION_ADMIN_COMMAND_KICK("plots.admin.command.kick", "static.permissions"), PERMISSION_GRANT("plots.grant.%s0", "static.permissions"), - PERMISSION_LIST_FORSALE("plots.list.forsale", "static.permissions"), + PERMISSION_LIST_FOR_SALE("plots.list.forsale", "static.permissions"), PERMISSION_LIST_MINE("plots.list.mine", "static.permissions"), PERMISSION_LIST_SHARED("plots.list.shared", "static.permissions"), PERMISSION_LIST_WORLD("plots.list.world", "static.permissions"), @@ -142,7 +140,7 @@ public enum Captions { PERMISSION_LIST_AREA("plots.list.area", "static.permissions"), PERMISSION_ADMIN_COMMAND_LOAD("plots.admin.command.load", "static.permissions"), PERMISSION_ADMIN_COMMAND_MERGE("plots.admin.command.merge", "static.permissions"), - PERMISSION_ADMIN_COMMAND_SETOWNER("plots.admin.command.setowner", "static.permissions"), + PERMISSION_ADMIN_COMMAND_SET_OWNER("plots.admin.command.setowner", "static.permissions"), PERMISSION_COMMENT("plots.comment", "static.permissions"), PERMISSION_ADMIN_COMMAND_REMOVE("plots.admin.command.remove", "static.permissions"), PERMISSION_ADMIN_COMMAND_SAVE("plots.admin.command.save", "static.permissions"), @@ -162,749 +160,463 @@ public enum Captions { PERMISSION_ALIAS_SET_OBSOLETE("plots.set.alias", "static.permissions"), // Note this is for backwards compatibility PERMISSION_ALIAS_SET("plots.alias.set", "static.permissions"), PERMISSION_ALIAS_REMOVE("plots.alias.remove", "static.permissions"), - /* - * Static console - */ + // + // CONSOLE_JAVA_OUTDATED( "&cYour version of java is outdated. It is highly recommended that you update to Java 8 as it increases performance " + "and security. %s0 will require Java 8 in a future update.", - "static.console"), CONSOLE_PLEASE_ENABLE_METRICS( + "static.console"), + CONSOLE_PLEASE_ENABLE_METRICS( "&dPlease enable metrics for %s0. Using metrics improves plugin stability, performance, and features. " + "Bug fixes and new features are influenced on metrics.", "static.console"), - /* - * Confirm - */ + // + // EXPIRED_CONFIRM("$2Confirmation has expired, please run the command again!", "Confirm"), FAILED_CONFIRM("$2You have no pending actions to confirm!", "Confirm"), - REQUIRES_CONFIRM( - "$2Are you sure you wish to execute: $1%s$2?&-$2This cannot be undone! If you are sure: $1/plot confirm", - "Confirm"), - /* - * Move - */ - MOVE_SUCCESS("$4Successfully moved plot.", "Move"), COPY_SUCCESS("$4Successfully copied plot.", - "Move"), + REQUIRES_CONFIRM("$2Are you sure you wish to execute: $1%s$2?&-$2This cannot be undone! If you are sure: $1/plot confirm", "Confirm"), + // + // + MOVE_SUCCESS("$4Successfully moved plot.", "Move"), + COPY_SUCCESS("$4Successfully copied plot.", "Move"), REQUIRES_UNOWNED("$2The location specified is already occupied.", "Move"), - /* - * Area Create - */ + // + // REQUIRES_UNMERGED("$2The plot cannot be merged", "debug"), SET_ATTRIBUTE("$4Successfully set %s0 set to %s1", "Set"), - /* - * Web - */ + // + // GENERATING_LINK("$1Processing plot...", "Web"), - GENERATING_LINK_FAILED( - "$2Failed to generate download link!", "Web"), + GENERATING_LINK_FAILED("$2Failed to generate download link!", "Web"), SAVE_FAILED("$2Failed to save", "Web"), LOAD_NULL("$2Please use $4/plot load $2to get a list of schematics", "Web"), LOAD_FAILED("$2Failed to load schematic", "Web"), LOAD_LIST("$2To load a schematic, use $1/plot load #", "Web"), SAVE_SUCCESS("$1Successfully saved!", "Web"), - /* - * Compass - */ + // + // COMPASS_TARGET("$4Successfully targeted plot with compass", "Compass"), - /* - * Cluster - */ + // + // CLUSTER_AVAILABLE_ARGS( "$1The following sub commands are available: $4list$2, $4create$2, $4delete$2, $4resize$2, $4invite$2, $4kick$2, $4leave$2, " - + "$4members$2, $4info$2, $4tp$2, $4sethome", "Cluster"), CLUSTER_LIST_HEADING( - "$2There are $1%s$2 clusters in this world", "Cluster"), - - CLUSTER_LIST_ELEMENT("$2 - $1%s&-", "Cluster"), CLUSTER_INTERSECTION( - "$2The proposed area overlaps with: %s0", "Cluster"), - - CLUSTER_OUTSIDE("$2The proposed area is outside the plot area: %s0", "Cluster"), CLUSTER_ADDED( - "$4Successfully created the cluster.", "Cluster"), - - CLUSTER_DELETED("$4Successfully deleted the cluster.", "Cluster"), CLUSTER_RESIZED( - "$4Successfully resized the cluster.", "Cluster"), - - CLUSTER_ADDED_USER("$4Successfully added user to the cluster.", "Cluster"), CANNOT_KICK_PLAYER( - "$2You cannot kick that player", "Cluster"), - - CLUSTER_INVITED("$1You have been invited to the following cluster: $2%s", - "Cluster"), CLUSTER_REMOVED("$1You have been removed from cluster: $2%s", "Cluster"), - - CLUSTER_KICKED_USER("$4Successfully kicked the user", "Cluster"), INVALID_CLUSTER( - "$1Invalid cluster name: $2%s", "Cluster"), - - CLUSTER_NOT_ADDED("$2That player was not added to the plot cluster", - "Cluster"), CLUSTER_CANNOT_LEAVE("$1You must delete or transfer ownership before leaving", - "Cluster"), - - CLUSTER_ADDED_HELPER("$4Successfully added a helper to the cluster", - "Cluster"), CLUSTER_REMOVED_HELPER("$4Successfully removed a helper from the cluster", - "Cluster"), - - CLUSTER_REGENERATED("$4Successfully started cluster regeneration", - "Cluster"), CLUSTER_TELEPORTING("$4Teleporting...", "Cluster"), - - CLUSTER_INFO( - "$1Current cluster: $2%id%&-$1Name: $2%name%&-$1Owner: $2%owner%&-$1Size: $2%size%&-$1Rights: $2%rights%", - "Cluster"), - /* - * Border - */ + + "$4members$2, $4info$2, $4tp$2, $4sethome", "Cluster"), + CLUSTER_LIST_HEADING("$2There are $1%s$2 clusters in this world", "Cluster"), + CLUSTER_LIST_ELEMENT("$2 - $1%s&-", "Cluster"), + CLUSTER_INTERSECTION("$2The proposed area overlaps with: %s0", "Cluster"), + CLUSTER_OUTSIDE("$2The proposed area is outside the plot area: %s0", "Cluster"), + CLUSTER_ADDED("$4Successfully created the cluster.", "Cluster"), + CLUSTER_DELETED("$4Successfully deleted the cluster.", "Cluster"), + CLUSTER_RESIZED("$4Successfully resized the cluster.", "Cluster"), + CLUSTER_ADDED_USER("$4Successfully added user to the cluster.", "Cluster"), + CANNOT_KICK_PLAYER("$2You cannot kick that player", "Cluster"), + CLUSTER_INVITED("$1You have been invited to the following cluster: $2%s", "Cluster"), + CLUSTER_REMOVED("$1You have been removed from cluster: $2%s", "Cluster"), + CLUSTER_KICKED_USER("$4Successfully kicked the user", "Cluster"), + INVALID_CLUSTER("$1Invalid cluster name: $2%s", "Cluster"), + CLUSTER_NOT_ADDED("$2That player was not added to the plot cluster", "Cluster"), + CLUSTER_CANNOT_LEAVE("$1You must delete or transfer ownership before leaving", "Cluster"), + CLUSTER_ADDED_HELPER("$4Successfully added a helper to the cluster", "Cluster"), + CLUSTER_REMOVED_HELPER("$4Successfully removed a helper from the cluster", "Cluster"), + CLUSTER_REGENERATED("$4Successfully started cluster regeneration", "Cluster"), + CLUSTER_TELEPORTING("$4Teleporting...", "Cluster"), + CLUSTER_INFO("$1Current cluster: $2%id%&-$1Name: $2%name%&-$1Owner: $2%owner%&-$1Size: $2%size%&-$1Rights: $2%rights%", "Cluster"), + // + // BORDER("$2You are outside the current map border", "Border"), - /* - * Un-claim - */ - UNCLAIM_SUCCESS("$4You successfully unclaimed the plot.", "Unclaim"), UNCLAIM_FAILED( - "$2Could not unclaim the plot", "Unclaim"), - /* - * WorldEdit masks - */ - WORLDEDIT_DELAYED("$2Please wait while we process your WorldEdit action...", - "WorldEdit Masks"), WORLDEDIT_RUN("$2Apologies for the delay. Now executing: %s", - "WorldEdit Masks"), - REQUIRE_SELECTION_IN_MASK( - "$2%s of your selection is not within your plot mask. You can only make edits within your plot.", - "WorldEdit Masks"), WORLDEDIT_VOLUME( - "$2You cannot select a volume of %current%. The maximum volume you can modify is %max%.", - "WorldEdit Masks"), - - WORLDEDIT_ITERATIONS( - "$2You cannot iterate %current% times. The maximum number of iterations allowed is %max%.", - "WorldEdit Masks"), WORLDEDIT_UNSAFE("$2Access to that command has been blocked", - "WorldEdit Masks"), - - WORLDEDIT_BYPASS("$2&oTo bypass your restrictions use $4/plot wea", - "WorldEdit Masks"), WORLDEDIT_BYPASSED("$2Currently bypassing WorldEdit restriction.", - "WorldEdit Masks"), - - WORLDEDIT_UNMASKED("$1Your WorldEdit is now unrestricted.", - "WorldEdit Masks"), WORLDEDIT_RESTRICTED("$1Your WorldEdit is now restricted.", - "WorldEdit Masks"), - - GAMEMODE_WAS_BYPASSED("$1You bypassed the GameMode ($2{gamemode}$1) $1set for $2{plot}", - "GameMode"), HEIGHT_LIMIT("$1This plot area has a height limit of $2{limit}", - "Height Limit"), - /* - * Records - */ - RECORD_PLAY("$2%player $2started playing record $1%name", "Records"), NOTIFY_ENTER( - "$2%player $2entered your plot ($1%plot$2)", "Records"), - + WORLDEDIT_BYPASS("$2&oTo bypass your restrictions use $4/plot wea", "WorldEdit Masks"), + WORLDEDIT_BYPASSED("$2Currently bypassing WorldEdit restriction.", "WorldEdit Masks"), + GAMEMODE_WAS_BYPASSED("$1You bypassed the GameMode ($2{gamemode}$1) $1set for $2{plot}", "GameMode"), + HEIGHT_LIMIT("$1This plot area has a height limit of $2{limit}", "Height Limit"), + // + // + NOTIFY_ENTER("$2%player $2entered your plot ($1%plot$2)", "Records"), NOTIFY_LEAVE("$2%player $2left your plot ($1%plot$2)", "Records"), - /* - * Swap - */ - SWAP_OVERLAP("$2The proposed areas are not allowed to overlap", "Swap"), SWAP_DIMENSIONS( - "$2The proposed areas must have comparable dimensions", "Swap"), - - SWAP_SYNTAX("$2/plot swap ", "Swap"), SWAP_SUCCESS("$4Successfully swapped plots", "Swap"), - - STARTED_SWAP("$2Started plot swap task. You will be notified when it finishes", "Swap"), - /* - * Comment - */ - INBOX_NOTIFICATION("%s unread messages. Use /plot inbox", "Comment"), NOT_VALID_INBOX_INDEX( - "$2No comment at index %s", "Comment"), - - INBOX_ITEM("$2 - $4%s", "Comment"), COMMENT_SYNTAX("$2Use /plot comment [X;Z] <%s> ", - "Comment"), - - INVALID_INBOX("$2That is not a valid inbox.&-$1Accepted values: %s", "Comment"), NO_PERM_INBOX( - "$2You do not have permission for that inbox", "Comment"), - - NO_PERM_INBOX_MODIFY("$2You do not have permission to modify that inbox", - "Comment"), NO_PLOT_INBOX("$2You must stand in or supply a plot argument", "Comment"), - - COMMENT_REMOVED("$4Successfully deleted comment/s:n$2 - '$3%s$2'", "Comment"), COMMENT_ADDED( - "$4A comment has been left", "Comment"), - - COMMENT_HEADER("$2&m---------&r $1Comments $2&m---------&r", "Comment"), INBOX_EMPTY( - "$2No comments", "Comment"), - /* - * Console - */ - NOT_CONSOLE("$2For safety reasons, this command can only be executed by console.", - "Console"), IS_CONSOLE("$2This command can only be executed by a player.", "Console"), - /* - Inventory - */ - INVENTORY_USAGE("&cUsage: &6{usage}", "Inventory"), INVENTORY_DESC("&cDescription: &6{desc}", - "Inventory"), - - INVENTORY_CATEGORY("&cCategory: &6{category}", "Inventory"), - /* - * Clipboard - */ - CLIPBOARD_SET( - "$2The current plot is now copied to your clipboard, use $1/plot paste$2 to paste it", - "Clipboard"), PASTED( - "$4The plot selection was successfully pasted. It has been cleared from your clipboard.", - "Clipboard"), - - PASTE_FAILED("$2Failed to paste the selection. Reason: $2%s", "Clipboard"), NO_CLIPBOARD( - "$2You don't have a selection in your clipboard", "Clipboard"), - - CLIPBOARD_INFO( - "$2Current Selection - Plot ID: $1%id$2, Width: $1%width$2, Total Blocks: $1%total$2", - "Clipboard"), - /* - * Toggle - */ - TOGGLE_ENABLED("$2Enabled setting: %s", "Toggle"), TOGGLE_DISABLED("$2Disabled setting: %s", - "Toggle"), - + // + // + SWAP_OVERLAP("$2The proposed areas are not allowed to overlap", "Swap"), + SWAP_DIMENSIONS("$2The proposed areas must have comparable dimensions", "Swap"), + SWAP_SYNTAX("$2/plot swap ", "Swap"), + SWAP_SUCCESS("$4Successfully swapped plots", "Swap"), + // + // + INBOX_NOTIFICATION("%s unread messages. Use /plot inbox", "Comment"), + NOT_VALID_INBOX_INDEX("$2No comment at index %s", "Comment"), + INBOX_ITEM("$2 - $4%s", "Comment"), + COMMENT_SYNTAX("$2Use /plot comment [X;Z] <%s> ", "Comment"), + INVALID_INBOX("$2That is not a valid inbox.&-$1Accepted values: %s", "Comment"), + NO_PERM_INBOX("$2You do not have permission for that inbox", "Comment"), + NO_PERM_INBOX_MODIFY("$2You do not have permission to modify that inbox", "Comment"), + NO_PLOT_INBOX("$2You must stand in or supply a plot argument", "Comment"), + COMMENT_REMOVED_SUCCESS("$4Successfully deleted comment/s:n$2 - '$3%s$2'", "Comment"), + COMMENT_REMOVED_FAILURE("$4Failed to delete comment!", "Comment"), + COMMENT_ADDED("$4A comment has been left", "Comment"), + COMMENT_HEADER("$2&m---------&r $1Comments $2&m---------&r", "Comment"), + INBOX_EMPTY("$2No comments", "Comment"), + // + // + NOT_CONSOLE("$2For safety reasons, this command can only be executed by console.", "Console"), + IS_CONSOLE("$2This command can only be executed by a player.", "Console"), + // + // + PASTE_FAILED("$2Failed to paste the selection. Reason: $2%s", "Clipboard"), + // + // + TOGGLE_ENABLED("$2Enabled setting: %s", "Toggle"), + TOGGLE_DISABLED("$2Disabled setting: %s", "Toggle"), COMMAND_BLOCKED("$2That command is not allowed in this plot", "Blocked Command"), - /* - * Done - */ - DONE_ALREADY_DONE("$2This plot is already marked as done", "Done"), DONE_NOT_DONE( - "$2This plot is not marked as done.", "Done"), - - DONE_INSUFFICIENT_COMPLEXITY( - "$2This plot is too simple. Please add more detail before using this command.", - "Done"), DONE_SUCCESS("$1Successfully marked this plot as done.", "Done"), - + // + // + DONE_ALREADY_DONE("$2This plot is already marked as done", "Done"), + DONE_NOT_DONE("$2This plot is not marked as done.", "Done"), + DONE_INSUFFICIENT_COMPLEXITY("$2This plot is too simple. Please add more detail before using this command.", "Done"), + DONE_SUCCESS("$1Successfully marked this plot as done.", "Done"), DONE_REMOVED("$1You may now continue building in this plot.", "Done"), - /* - * Ratings - */ - - RATINGS_PURGED("$2Purged ratings for this plot", "Ratings"), RATING_NOT_VALID( - "$2You need to specify a number between 1 and 10", "Ratings"), - - RATING_ALREADY_EXISTS("$2You have already rated plot $2%s", "Ratings"), RATING_APPLIED( - "$4You successfully rated plot $2%s", "Ratings"), - - RATING_DISLIKED("$4You successfully disliked plot $2%s", "Ratings"), RATING_LIKED( - "$4You successfully liked plot $2%s", "Ratings"), - - RATING_NOT_YOUR_OWN("$2You cannot rate your own plot", "Ratings"), RATING_NOT_DONE( - "$2You can only rate finished plots.", "Ratings"), - + // + // + RATINGS_PURGED("$2Purged ratings for this plot", "Ratings"), + RATING_NOT_VALID("$2You need to specify a number between 1 and 10", "Ratings"), + RATING_ALREADY_EXISTS("$2You have already rated plot $2%s", "Ratings"), + RATING_APPLIED("$4You successfully rated plot $2%s", "Ratings"), + RATING_DISLIKED("$4You successfully disliked plot $2%s", "Ratings"), + RATING_LIKED("$4You successfully liked plot $2%s", "Ratings"), + RATING_NOT_YOUR_OWN("$2You cannot rate your own plot", "Ratings"), + RATING_NOT_DONE("$2You can only rate finished plots.", "Ratings"), RATING_NOT_OWNED("$2You cannot rate a plot that is not claimed by anyone", "Ratings"), - /* - * Tutorial - */ - - RATE_THIS("$2Rate this plot!", "Tutorial"), COMMENT_THIS( - "$2Leave some feedback on this plot: %s", "Tutorial"), - /* - * Economy Stuff - */ - - ECON_DISABLED("$2Economy is not enabled", "Economy"), CANNOT_AFFORD_PLOT( - "$2You cannot afford to buy this plot. It costs $1%s", "Economy"), - - NOT_FOR_SALE("$2This plot is not for sale", "Economy"), CANNOT_BUY_OWN( - "$2You cannot buy your own plot", "Economy"), - - PLOT_SOLD("$4Your plot; $1%s0$4, has been sold to $1%s1$4 for $1$%s2", - "Economy"), CANNOT_AFFORD_MERGE("$2You cannot afford to merge the plots. It costs $1%s", - "Economy"), - - ADDED_BALANCE("$1%s $2has been added to your balance", "Economy"), REMOVED_BALANCE( - "$1%s $2has been taken from your balance", "Economy"), - + // + // + RATE_THIS("$2Rate this plot!", "Tutorial"), + COMMENT_THIS("$2Leave some feedback on this plot: %s", "Tutorial"), + // + // + ECON_DISABLED("$2Economy is not enabled", "Economy"), + CANNOT_AFFORD_PLOT("$2You cannot afford to buy this plot. It costs $1%s", "Economy"), + NOT_FOR_SALE("$2This plot is not for sale", "Economy"), + CANNOT_BUY_OWN("$2You cannot buy your own plot", "Economy"), + PLOT_SOLD("$4Your plot; $1%s0$4, has been sold to $1%s1$4 for $1$%s2", "Economy"), + CANNOT_AFFORD_MERGE("$2You cannot afford to merge the plots. It costs $1%s","Economy"), + ADDED_BALANCE("$1%s $2has been added to your balance", "Economy"), + REMOVED_BALANCE("$1%s $2has been taken from your balance", "Economy"), REMOVED_GRANTED_PLOT("$2You used %s plot grant(s), you've got $1%s $2left", "Economy"), - /* - * Setup Stuff - */ - - SETUP_INIT("$1Usage: $2/plot setup ", "Setup"), SETUP_STEP( - "$3[$1Step %s0$3] $1%s1 $2- $1Expecting: $2%s2 $1Default: $2%s3", "Setup"), - - SETUP_INVALID_ARG( - "$2%s0 is not a valid argument for step %s1. To cancel setup use: $1/plot setup cancel", - "Setup"), SETUP_VALID_ARG("$2Value $1%s0 $2set to %s1", "Setup"), - + // + // + SETUP_INIT("$1Usage: $2/plot setup ", "Setup"), + SETUP_STEP("$3[$1Step %s0$3] $1%s1 $2- $1Expecting: $2%s2 $1Default: $2%s3", "Setup"), + SETUP_INVALID_ARG("$2%s0 is not a valid argument for step %s1. To cancel setup use: $1/plot setup cancel", "Setup"), + SETUP_VALID_ARG("$2Value $1%s0 $2set to %s1", "Setup"), SETUP_FINISHED( "$4You should have been teleported to the created world. Otherwise you will need to set the generator manually using the bukkit.yml or " - + "your chosen world management plugin.", "Setup"), SETUP_WORLD_TAKEN( - "$2%s is already a world", "Setup"), - + + "your chosen world management plugin.", "Setup"), + SETUP_WORLD_TAKEN("$2%s is already a world", "Setup"), SETUP_MISSING_WORLD( "$2You need to specify a world name ($1/plot setup &l$1 $2)&-$1Additional commands:&-$2 - $1/plot setup &-$2 -" - + " $1/plot setup back&-$2 - $1/plot setup cancel", "Setup"), SETUP_MISSING_GENERATOR( + + " $1/plot setup back&-$2 - $1/plot setup cancel", "Setup"), + SETUP_MISSING_GENERATOR( "$2You need to specify a generator ($1/plot setup &l&r$2)&-$1Additional commands:&-$2 - $1/plot setup &-$2 - " + "$1/plot setup back&-$2 - $1/plot setup cancel", "Setup"), SETUP_INVALID_GENERATOR("$2Invalid generator. Possible options: %s", "Setup"), - /* - * Schematic Stuff - */ - - SCHEMATIC_TOO_LARGE("$2The plot is too large for this action!", - "Schematics"), SCHEMATIC_MISSING_ARG( - "$2You need to specify an argument. Possible values: $1test $2 , $1save$2 , $1paste $2, $1exportall$2, $1list", - "Schematics"), - - SCHEMATIC_INVALID("$2That is not a valid schematic. Reason: $2%s", - "Schematics"), SCHEMATIC_VALID("$2That is a valid schematic", "Schematics"), - - SCHEMATIC_PASTE_FAILED("$2Failed to paste the schematic", - "Schematics"), SCHEMATIC_PASTE_SUCCESS("$4The schematic pasted successfully", "Schematics"), - + // + // + SCHEMATIC_TOO_LARGE("$2The plot is too large for this action!", "Schematics"), + SCHEMATIC_MISSING_ARG("$2You need to specify an argument. Possible values: $1save$2, $1paste $2, $1exportall$2, $1list", "Schematics"), + SCHEMATIC_INVALID("$2That is not a valid schematic. Reason: $2%s", "Schematics"), + SCHEMATIC_VALID("$2That is a valid schematic", "Schematics"), + SCHEMATIC_PASTE_FAILED("$2Failed to paste the schematic", "Schematics"), + SCHEMATIC_PASTE_SUCCESS("$4The schematic pasted successfully", "Schematics"), SCHEMATIC_LIST("$4Saved Schematics: $1%s", "Schematics"), - - /* - * Title Stuff - */ - TITLE_ENTERED_PLOT("$1Plot: %world%;%x%;%z%", "Titles"), TITLE_ENTERED_PLOT_SUB("$4Owned by %s", - "Titles"), - - PREFIX_GREETING("$1%id%$2> ", "Titles"), PREFIX_FAREWELL("$1%id%$2> ", "Titles"), - /* - * Core Stuff - */ - - TASK_START("Starting task...", "Core"), PREFIX("$3[$1P2$3] $2", "Core"), - + SCHEMATIC_ROAD_CREATED("$1Saved new road schematic. To test the schematic, fly to a few other plots and run /plot debugroadregen", "Schematics"), + MCA_FILE_SIZE("$1Note: The `.mca` files are 512x512", "Schematics"), + SCHEMATIC_EXPORTALL_STARTED("$1Starting export...", "Schematics"), + SCHEMATIC_EXPORTALL_WORLD_ARGS("$1Need world argument. Use $3/plot sch exportall ", "Schematics"), + SCHEMATIC_EXPORTALL_WORLD("$1Invalid world. Use &3/plot sch exportall ", "Schematic"), + SCHEMATIC_EXPORTALL_MASS_STARTED("$1Schematic mass export has been started. This may take a while", "Schematics"), + SCHEMATIC_EXPORTALL_COUNT("$1Found $3%s $1plots...", "Schematics"), + SCHEMATIC_EXPORTALL_FINISHED("$1Finished mass export", "Schematics"), + SCHEMATIC_EXPORTALL_SINGLE_FINISHED("$1Finished export", "Schematics"), + TASK_IN_PROCESS("$1Task is already running.", "Error"), + // + // + TITLE_ENTERED_PLOT("$1Plot: %world%;%x%;%z%", "Titles"), + TITLE_ENTERED_PLOT_SUB("$4Owned by %s", "Titles"), + PREFIX_GREETING("$1%id%$2> ", "Titles"), + PREFIX_FAREWELL("$1%id%$2> ", "Titles"), + // + // + PREFIX("$3[$1P2$3] $2", "Core"), ENABLED("$1%s0 is now enabled", "Core"), - /* - * Reload - */ - - RELOADED_CONFIGS("$1Translations and world settings have been reloaded", - "Reload"), RELOAD_FAILED("$2Failed to reload file configurations", "Reload"), - /* - * BarAPI - */ - - DESC_SET("$2Plot description set", "Desc"), DESC_UNSET("$2Plot description unset", "Desc"), - - MISSING_DESC("$2You need to specify a description", "Desc"), - - /* - * Alias - */ - ALIAS_SET_TO("$2Plot alias set to $1%alias%", "Alias"), ALIAS_REMOVED("$2Plot alias removed", - "Alias"), - - MISSING_ALIAS("$2You need to specify an alias", "Alias"), ALIAS_TOO_LONG( - "$2The alias must be < 50 characters in length", "Alias"), + // + // + RELOADED_CONFIGS("$1Translations and world settings have been reloaded", "Reload"), + RELOAD_FAILED("$2Failed to reload file configurations", "Reload"), + // + // + DESC_SET("$2Plot description set", "Desc"), + DESC_UNSET("$2Plot description unset", "Desc"), + // + // + ALIAS_SET_TO("$2Plot alias set to $1%alias%", "Alias"), + ALIAS_REMOVED("$2Plot alias removed", "Alias"), + ALIAS_TOO_LONG("$2The alias must be < 50 characters in length", "Alias"), ALIAS_IS_TAKEN("$2That alias is already taken", "Alias"), - /* - * Position - */ - - MISSING_POSITION("$2You need to specify a position. Possible values: $1none", - "Position"), POSITION_SET("$1Home position set to your current location", "Position"), - - POSITION_UNSET("$1Home position reset to the default location", "Position"), HOME_ARGUMENT( - "$2Use /plot set home [none]", "Position"), - - INVALID_POSITION("$2That is not a valid position value", "Position"), - /* - * Cap - */ - - ENTITY_CAP("$2You are not allowed to spawn more mobs", "cap"), - /* - * Time - */ - - TIME_FORMAT("$1%hours%, %min%, %sec%", "Time"), - /* - * Permission - */ - - NO_SCHEMATIC_PERMISSION("$2You don't have the permission required to use schematic $1%s", - "Permission"), NO_PERMISSION("$2You are lacking the permission node: $1%s", "Permission"), - - NO_PERMISSION_EVENT("$2You are lacking the permission node: $1%s", "Permission"), NO_PLOT_PERMS( - "$2You must be the plot owner to perform this action", "Permission"), - - CANT_CLAIM_MORE_PLOTS("$2You can't claim more plots.", "Permission"), CANT_CLAIM_MORE_CLUSTERS( - "$2You can't claim more clusters.", "Permission"), - - CANT_TRANSFER_MORE_PLOTS("$2You can't send more plots to that user", - "Permission"), CANT_CLAIM_MORE_PLOTS_NUM("$2You can't claim more than $1%s $2plots at once", - "Permission"), - - YOU_BE_DENIED("$2You are not allowed to enter this plot", "Permission"), - - /* - * Merge - */ - MERGE_NOT_VALID("$2This merge request is no longer valid.", "Merge"), MERGE_ACCEPTED( - "$2The merge request has been accepted", "Merge"), - - SUCCESS_MERGE("$2Plots have been merged!", "Merge"), MERGE_REQUESTED( - "$2Successfully sent a merge request", "Merge"), - - MERGE_REQUEST_CONFIRM("Merge request from %s", "Permission"), NO_PERM_MERGE( - "$2You are not the owner of the plot: $1%plot%", "Merge"), - - NO_AVAILABLE_AUTOMERGE( - "$2You do not own any adjacent plots in the specified direction or are not allowed to merge to the required size.", - "Merge"), UNLINK_REQUIRED("$2An unlink is required to do this.", "Merge"), - - UNLINK_IMPOSSIBLE("$2You can only unlink a mega-plot", "Merge"), UNLINK_SUCCESS( - "$2Successfully unlinked plots.", "Merge"), - /* - * CommandConfig - */ - - NOT_VALID_SUBCOMMAND("$2That is not a valid subcommand", "CommandConfig"), DID_YOU_MEAN( - "$2Did you mean: $1%s", "CommandConfig"), - - NAME_LITTLE("$2%s0 name is too short, $1%s1$2<$1%s3", "CommandConfig"), NO_COMMANDS( - "$2I'm sorry, but you're not permitted to use any subcommands.", "CommandConfig"), - - SUBCOMMAND_SET_OPTIONS_HEADER("$2Possible Values: ", "CommandConfig"), COMMAND_SYNTAX( - "$1Usage: $2%s", "CommandConfig"), - /* - * Player not found - */ - - INVALID_PLAYER_WAIT("$2Player not found: $1%s$2, fetching it. Try again soon.", - "Errors"), INVALID_PLAYER("$2Player not found: $1%s$2.", "Errors"), + // + // + POSITION_SET("$1Home position set to your current location", "Position"), + POSITION_UNSET("$1Home position reset to the default location", "Position"), + HOME_ARGUMENT("$2Use /plot set home [none]", "Position"), + // + // + NO_SCHEMATIC_PERMISSION("$2You don't have the permission required to use schematic $1%s", "Permission"), + NO_PERMISSION("$2You are lacking the permission node: $1%s", "Permission"), + NO_PERMISSION_EVENT("$2You are lacking the permission node: $1%s", "Permission"), + NO_PLOT_PERMS("$2You must be the plot owner to perform this action", "Permission"), + CANT_CLAIM_MORE_PLOTS("$2You can't claim more plots.", "Permission"), + CANT_CLAIM_MORE_CLUSTERS("$2You can't claim more clusters.", "Permission"), + CANT_TRANSFER_MORE_PLOTS("$2You can't send more plots to that user", "Permission"), + CANT_CLAIM_MORE_PLOTS_NUM("$2You can't claim more than $1%s $2plots at once", "Permission"), + // + // + MERGE_NOT_VALID("$2This merge request is no longer valid.", "Merge"), + MERGE_ACCEPTED("$2The merge request has been accepted", "Merge"), + SUCCESS_MERGE("$2Plots have been merged!", "Merge"), + MERGE_REQUESTED("$2Successfully sent a merge request", "Merge"), + MERGE_REQUEST_CONFIRM("Merge request from %s", "Permission"), + NO_PERM_MERGE("$2You are not the owner of the plot: $1%plot%", "Merge"), + NO_AVAILABLE_AUTOMERGE("$2You do not own any adjacent plots in the specified direction or are not allowed to merge to the required size.", "Merge"), + UNLINK_IMPOSSIBLE("$2You can only unlink a mega-plot", "Merge"), + UNMERGE_CANCELLED("$1Unlink has been cancelled", "Merge"), + UNLINK_SUCCESS("$2Successfully unlinked plots.", "Merge"), + // + // + NOT_VALID_SUBCOMMAND("$2That is not a valid subcommand", "CommandConfig"), + DID_YOU_MEAN("$2Did you mean: $1%s", "CommandConfig"), + SUBCOMMAND_SET_OPTIONS_HEADER("$2Possible Values: ", "CommandConfig"), + COMMAND_SYNTAX("$1Usage: $2%s", "CommandConfig"), + // + // + INVALID_PLAYER("$2Player not found: $1%s$2.", "Errors"), INVALID_PLAYER_OFFLINE("$2The player must be online: $1%s.", "Errors"), - /* - * Command flag - */ - - INVALID_COMMAND_FLAG("$2Invalid command flag: %s0", "Errors"), /* - * Unknown Error - */ - - ERROR("$2An error occurred: %s", - "Errors"), // SETTINGS_PASTE_UPLOADED("$2settings.yml was uploaded to: $1%url%", "Paste"), - - // LATEST_LOG_UPLOADED("$2latest.log was uploaded to: $1%url%", "Paste"), - DEBUG_REPORT_CREATED("$1Uploaded a full debug to: $1%url%", "Paste"), - + INVALID_COMMAND_FLAG("$2Invalid command flag: %s0", "Errors"), + ERROR("$2An error occurred: %s", "Errors"), COMMAND_WENT_WRONG("$2Something went wrong when executing that command...", "Errors"), - /* - * purge - */ - - PURGE_SUCCESS("$4Successfully purged %s plots", "Purge"), - /* - * trim - */ - - TRIM_IN_PROGRESS("A world trim task is already in progress!", - "Trim"), NOT_VALID_HYBRID_PLOT_WORLD( - "The hybrid plot manager is required to perform this action", "Trim"), - /* - * No - */ - - NO_FREE_PLOTS("$2There are no free plots available", "Errors"), NOT_IN_PLOT( - "$2You're not in a plot", "Errors"), - - NOT_LOADED("$2The plot could not be loaded", "Errors"), NOT_IN_CLUSTER( - "$2You must be within a plot cluster to perform that action", "Errors"), - - NOT_IN_PLOT_WORLD("$2You're not in a plot area", "Errors"), PLOTWORLD_INCOMPATIBLE( - "$2The two worlds must be compatible", "Errors"), - - NOT_VALID_WORLD("$2That is not a valid world (case sensitive)", "Errors"), NOT_VALID_PLOT_WORLD( - "$2That is not a valid plot area (case sensitive)", "Errors"), - + NO_FREE_PLOTS("$2There are no free plots available", "Errors"), + NOT_IN_PLOT("$2You're not in a plot", "Errors"), + NOT_LOADED("$2The plot could not be loaded", "Errors"), + NOT_IN_CLUSTER("$2You must be within a plot cluster to perform that action", "Errors"), + NOT_IN_PLOT_WORLD("$2You're not in a plot area", "Errors"), + PLOTWORLD_INCOMPATIBLE("$2The two worlds must be compatible", "Errors"), + NOT_VALID_WORLD("$2That is not a valid world (case sensitive)", "Errors"), + NOT_VALID_PLOT_WORLD("$2That is not a valid plot area (case sensitive)", "Errors"), NO_PLOTS("$2You don't have any plots", "Errors"), - /* - * Block List - */ - - BLOCK_LIST_SEPARATER("$1,$2 ", "Block List"), - /* - * Biome - */ - - NEED_BIOME("$2You need to specify a valid biome.", "Biome"), BIOME_SET_TO( - "$2Plot biome set to $2", "Biome"), - /* - * Teleport / Entry - */ - - TELEPORTED_TO_PLOT("$1You have been teleported", "Teleport"), TELEPORTED_TO_ROAD( - "$2You got teleported to the road", "Teleport"), - - TELEPORT_IN_SECONDS("$1Teleporting in %s seconds. Do not move...", "Teleport"), TELEPORT_FAILED( - "$2Teleportation cancelled due to movement or damage", "Teleport"), - /* - * Set Block - */ - + WAIT_FOR_TIMER("$2A set block timer is bound to either the current plot or you. Please wait for it to finish", "Errors"), + // + DEBUG_REPORT_CREATED("$1Uploaded a full debug to: $1%url%", "Paste"), + PURGE_SUCCESS("$4Successfully purged %s plots", "Purge"), + // + TRIM_IN_PROGRESS("A world trim task is already in progress!", "Trim"), + // + // + BLOCK_LIST_SEPARATOR("$1,$2 ", "Block List"), + // + // + NEED_BIOME("$2You need to specify a valid biome.", "Biome"), + BIOME_SET_TO("$2Plot biome set to $2", "Biome"), + // + // + TELEPORTED_TO_PLOT("$1You have been teleported", "Teleport"), + TELEPORTED_TO_ROAD("$2You got teleported to the road", "Teleport"), + TELEPORT_IN_SECONDS("$1Teleporting in %s seconds. Do not move...", "Teleport"), + TELEPORT_FAILED("$2Teleportation cancelled due to movement or damage", "Teleport"), + // + // SET_BLOCK_ACTION_FINISHED("$1The last setblock action is now finished.", "Set Block"), - - /* - AllowUnsafe - */ - DEBUGALLOWUNSAFE_ON("$2Unsafe actions allowed", "unsafe"), DEBUGALLOWUNSAFE_OFF( - "$2Unsafe actions disabled", "unsafe"), - /* - * Debug - */ - - DEBUG_HEADER("$1Debug Information&-", "Debug"), DEBUG_SECTION("$2>> $1&l%val%", "Debug"), - + // + // + DEBUGALLOWUNSAFE_ON("$2Unsafe actions allowed", "unsafe"), + DEBUGALLOWUNSAFE_OFF("$2Unsafe actions disabled", "unsafe"), + // + // + DEBUG_HEADER("$1Debug Information&-", "Debug"), + DEBUG_SECTION("$2>> $1&l%val%", "Debug"), DEBUG_LINE("$2>> $1%var%$2:$1 %val%&-", "Debug"), - - /* - * Invalid - */ - - NOT_VALID_DATA("$2That's not a valid data id.", "Invalid"), NOT_VALID_BLOCK( - "$2That's not a valid block: %s", "Invalid"), - - NOT_ALLOWED_BLOCK("$2That block is not allowed: %s", "Invalid"), NOT_VALID_NUMBER( - "$2That's not a valid number within the range: %s", "Invalid"), - - NOT_VALID_PLOT_ID("$2That's not a valid plot id.", "Invalid"), PLOT_ID_FORM( - "$2The plot id must be in the form: $1X;Y $2e.g. $1-5;7", "Invalid"), - - NOT_YOUR_PLOT("$2That is not your plot.", "Invalid"), NO_SUCH_PLOT("$2There is no such plot", - "Invalid"), - - PLAYER_HAS_NOT_BEEN_ON("$2That player hasn't been in the plotworld", "Invalid"), FOUND_NO_PLOTS( - "$2Found no plots with your search query", "Invalid"), - - FOUND_NO_PLOTS_FOR_PLAYER("$2No plots found for player: %s", "Invalid"), - /* - * Need - */ - NEED_PLOT_NUMBER("$2You've got to specify a plot number or alias", "Need"), NEED_BLOCK( - "$2You've got to specify a block", "Need"), - - NEED_PLOT_ID("$2You've got to specify a plot id.", "Need"), NEED_PLOT_WORLD( - "$2You've got to specify a plot area.", "Need"), - - NEED_USER("$2You need to specify a username", "Need"), - /* - * Near - */ + // + // + NOT_VALID_BLOCK("$2That's not a valid block: %s", "Invalid"), + NOT_ALLOWED_BLOCK("$2That block is not allowed: %s", "Invalid"), + NOT_VALID_NUMBER("$2That's not a valid number within the range: %s", "Invalid"), + NOT_VALID_PLOT_ID("$2That's not a valid plot id.", "Invalid"), + FOUND_NO_PLOTS("$2Found no plots with your search query", "Invalid"), + // + // + NEED_BLOCK("$2You've got to specify a block", "Need"), + // + // PLOT_NEAR("$1Players: %s0", "Near"), - /* - * Info - */ - NONE("None", "Info"), NOW("Now", "Info"), - - NEVER("Never", "Info"), UNKNOWN("Unknown", "Info"), - + // + // + NONE("None", "Info"), + NOW("Now", "Info"), + NEVER("Never", "Info"), + UNKNOWN("Unknown", "Info"), SERVER("Server", "Info"), - - EVERYONE("Everyone", "Info"), PLOT_UNOWNED( - "$2The current plot must have an owner to perform this action", "Info"), - - PLOT_INFO_UNCLAIMED("$2Plot $1%s$2 is not yet claimed", "Info"), PLOT_INFO_HEADER( - "$3&m---------&r $1INFO $3&m---------", false, "Info"), - + EVERYONE("Everyone", "Info"), + PLOT_UNOWNED("$2The current plot must have an owner to perform this action", "Info"), + PLOT_INFO_UNCLAIMED("$2Plot $1%s$2 is not yet claimed", "Info"), + PLOT_INFO_HEADER("$3&m---------&r $1INFO $3&m---------", false, "Info"), PLOT_INFO_HIDDEN("$2You cannot view the information about this plot", "Info"), - - PLOT_INFO("$1ID: $2%id%$1&-" + "$1Alias: $2%alias%$1&-" + "$1Owner: $2%owner%$1&-" + PLOT_INFO("$1ID: $2%id%$1&-" + "$1Alias: $2%alias%$1&-" + "$1Owner:$2%owner%$1&-" + "$1Biome: $2%biome%$1&-" + "$1Can Build: $2%build%$1&-" + "$1Rating: $2%rating%&-" + "$1Seen: $2%seen%&-" + "$1Trusted: $2%trusted%$1&-" + "$1Members: $2%members%$1&-" - + "$1Denied: $2%denied%$1&-" + "$1Flags: $2%flags%", "Info"), PLOT_INFO_FOOTER( - "$3&m---------&r $1INFO $3&m---------", false, "Info"), - - PLOT_INFO_TRUSTED("$1Trusted:$2 %trusted%", "Info"), PLOT_INFO_MEMBERS("$1Members:$2 %members%", - "Info"), - - PLOT_INFO_DENIED("$1Denied:$2 %denied%", "Info"), PLOT_INFO_FLAGS("$1Flags:$2 %flags%", "Info"), - - PLOT_INFO_BIOME("$1Biome:$2 %biome%", "Info"), PLOT_INFO_RATING("$1Rating:$2 %rating%", "Info"), - + + "$1Denied: $2%denied%$1&-" + "$1Flags: $2%flags%", "Info"), + PLOT_INFO_FOOTER("$3&m---------&r $1INFO $3&m---------", false, "Info"), + PLOT_INFO_TRUSTED("$1Trusted:$2 %trusted%", "Info"), + PLOT_INFO_MEMBERS("$1Members:$2 %members%", "Info"), + PLOT_INFO_DENIED("$1Denied:$2 %denied%", "Info"), + PLOT_INFO_FLAGS("$1Flags:$2 %flags%", "Info"), + PLOT_INFO_BIOME("$1Biome:$2 %biome%", "Info"), + PLOT_INFO_RATING("$1Rating:$2 %rating%", "Info"), PLOT_INFO_LIKES("$1Like Ratio:$2 %likes%%", "Info"), - - PLOT_INFO_OWNER("$1Owner:$2 %owner%", "Info"), PLOT_INFO_ID("$1ID:$2 %id%", "Info"), - - PLOT_INFO_ALIAS("$1Alias:$2 %alias%", "Info"), PLOT_INFO_SIZE("$1Size:$2 %size%", "Info"), - - PLOT_INFO_SEEN("$1Seen:$2 %seen%", "Info"), PLOT_USER_LIST(" $1%user%$2,", "Info"), - - PLOT_FLAG_LIST("$1%s0:%s1$2", "Info"), INFO_SYNTAX_CONSOLE("$2/plot info X;Y", "Info"), - /* - * Generating - */ - + PLOT_INFO_OWNER("$1Owner:$2%owner%", "Info"), + PLOT_INFO_ID("$1ID:$2 %id%", "Info"), + PLOT_INFO_ALIAS("$1Alias:$2 %alias%", "Info"), + PLOT_INFO_SIZE("$1Size:$2 %size%", "Info"), + PLOT_INFO_SEEN("$1Seen:$2 %seen%", "Info"), + PLOT_USER_LIST(" $1%user%$2,", "Info"), + PLOT_FLAG_LIST("$1%s0:%s1$2", "Info"), + INFO_SYNTAX_CONSOLE("$2/plot info X;Z", "Info"), + // + // GENERATING_COMPONENT("$1Started generating component from your settings", "Working"), - /* - * Clearing - */ - - CLEARING_PLOT("$2Clearing plot async.", "Working"), CLEARING_DONE( - "$4Clear completed! Took %sms.", "Working"), - + CLEARING_DONE("$4Clear completed! Took %sms.", "Working"), DELETING_DONE("$4Delete completed! Took %sms.", "Working"), - /* - * Claiming - */ - - PLOT_NOT_CLAIMED("$2Plot not claimed", "Working"), PLOT_IS_CLAIMED( - "$2This plot is already claimed", "Working"), - + PLOT_NOT_CLAIMED("$2Plot not claimed", "Working"), + PLOT_IS_CLAIMED("$2This plot is already claimed", "Working"), CLAIMED("$4You successfully claimed the plot", "Working"), - /* - * List - */ - - COMMENT_LIST_HEADER_PAGED("$2(Page $1%cur$2/$1%max$2) $1List of %amount% comments", - "List"), CLICKABLE(" (interactive)", "List"), - - AREA_LIST_HEADER_PAGED("$2(Page $1%cur$2/$1%max$2) $1List of %amount% areas", - "List"), PLOT_LIST_HEADER_PAGED("$2(Page $1%cur$2/$1%max$2) $1List of %amount% plots", - "List"), - - PLOT_LIST_HEADER("$1List of %word% plots", "List"), PLOT_LIST_ITEM( - "$2>> $1%id$2:$1%world $2- $1%owner", "List"), - - PLOT_LIST_ITEM_ORDERED("$2[$1%in$2] >> $1%id$2:$1%world $2- $1%owner", - "List"), PLOT_LIST_FOOTER("$2>> $1%word% a total of $2%num% $1claimed %plot%.", "List"), - /* - * Left - */ - - LEFT_PLOT("$2You left a plot", "Left"), - /* - * Wait - */ - - WAIT_FOR_TIMER( - "$2A setblock timer is bound to either the current plot or you. Please wait for it to finish", - "Errors"), - /* - * Chat - */ - - PLOT_CHAT_SPY_FORMAT("$2[$1Plot Spy$2][$1%plot_id%$2] $1%sender%$2: $1%msg%", - "Chat"), PLOT_CHAT_FORMAT("$2[$1Plot Chat$2][$1%plot_id%$2] $1%sender%$2: $1%msg%", "Chat"), - - PLOT_CHAT_FORCED("$2This world forces everyone to use plot chat.", "Chat"), PLOT_CHAT_ON( - "$4Plot chat enabled.", "Chat"), - + // + // + COMMENT_LIST_HEADER_PAGED("$2(Page $1%cur$2/$1%max$2) $1List of %amount% comments", "List"), + CLICKABLE(" (interactive)", "List"), + AREA_LIST_HEADER_PAGED("$2(Page $1%cur$2/$1%max$2) $1List of %amount% areas", "List"), + PLOT_LIST_HEADER_PAGED("$2(Page $1%cur$2/$1%max$2) $1List of %amount% plots", "List"), + PLOT_LIST_HEADER("$1List of %word% plots", "List"), + PLOT_LIST_ITEM("$2>> $1%id$2:$1%world $2- $1%owner", "List"), + PLOT_LIST_ITEM_ORDERED("$2[$1%in$2] >> $1%id$2:$1%world $2- $1%owner", "List"), + PLOT_LIST_FOOTER("$2>> $1%word% a total of $2%num% $1claimed %plot%.", "List"), + // + // + PLOT_CHAT_SPY_FORMAT("$2[$1Plot Spy$2][$1%plot_id%$2] $1%sender%$2: $1%msg%", "Chat"), + PLOT_CHAT_FORMAT("$2[$1Plot Chat$2][$1%plot_id%$2] $1%sender%$2: $1%msg%", "Chat"), + PLOT_CHAT_FORCED("$2This world forces everyone to use plot chat.", "Chat"), + PLOT_CHAT_ON("$4Plot chat enabled.", "Chat"), PLOT_CHAT_OFF("$4Plot chat disabled.", "Chat"), - /* - * Denied - */ - - DENIED_REMOVED("$4You successfully undenied the player from this plot", "Deny"), DENIED_ADDED( - "$4You successfully denied the player from this plot", "Deny"), - - DENIED_NEED_ARGUMENT( - "$2Arguments are missing. $1/plot denied add $2or $1/plot denied remove ", - "Deny"), WAS_NOT_DENIED("$2That player was not denied on this plot", "Deny"), - - YOU_GOT_DENIED( - "$4You are denied from the plot you were previously on, and got teleported to spawn", - "Deny"), - /* - * Kick - */ - + // + // + DENIED_ADDED("$4You successfully denied the player from this plot", "Deny"), + DENIED_NEED_ARGUMENT("$2Arguments are missing. $1/plot denied add $2or $1/plot denied remove ", "Deny"), + WAS_NOT_DENIED("$2That player was not denied on this plot", "Deny"), + YOU_GOT_DENIED("$4You are denied from the plot you were previously on, and got teleported to spawn", "Deny"), + CANT_REMOVE_OWNER("$2You can't remove the plot owner", "Deny"), + // YOU_GOT_KICKED("$4You got kicked!", "Kick"), - /* - * Rain - */ - - NEED_ON_OFF("$2You need to specify a value. Possible values: $1on$2, $1off", - "Rain"), SETTING_UPDATED("$4You successfully updated the setting", "Rain"), - /* - * Flag - */ - - FLAG_KEY("$2Key: %s", "Flag"), FLAG_TYPE("$2Type: %s", "Flag"), - - FLAG_DESC("$2Desc: %s", "Flag"), NOT_VALID_FLAG("$2That is not a valid flag", "Flag"), - - NOT_VALID_FLAG_SUGGESTED("$2That is not a valid flag. Did you mean: $1%s", - "Flag"), NOT_VALID_VALUE("$2Flag values must be alphanumerical", "Flag"), - - FLAG_NOT_IN_PLOT("$2The plot does not have that flag", "Flag"), FLAG_NOT_REMOVED( - "$2The flag could not be removed", "Flag"), - - FLAG_NOT_ADDED("$2The flag could not be added", "Flag"), FLAG_REMOVED( - "$4Successfully removed flag", "Flag"), - - FLAG_ADDED("$4Successfully added flag", "Flag"), FLAG_TUTORIAL_USAGE( - "$1Have an admin set the flag: $2%s", "CommandConfig"), - /* - * Trusted - */ - - TRUSTED_ADDED("$4You successfully trusted a user to the plot", "Trusted"), TRUSTED_REMOVED( - "$4You successfully removed a trusted user from the plot", "Trusted"), - - WAS_NOT_ADDED("$2That player was not trusted on this plot", "Trusted"), PLOT_REMOVED_USER( - "$1Plot %s of which you were added to has been deleted due to owner inactivity", - "Trusted"), - /* - * Member - */ - - REMOVED_PLAYERS("$2Removed %s players from this plot.", "Member"), ALREADY_OWNER( - "$2That user is already the plot owner: %s0", "Member"), - - ALREADY_ADDED("$2That user is already added to that category: %s0", "Member"), MEMBER_ADDED( - "$4That user can now build while the plot owner is online", "Member"), - - MEMBER_REMOVED("$1You successfully removed a user from the plot", - "Member"), MEMBER_WAS_NOT_ADDED("$2That player was not added as a user on this plot", - "Member"), - + // + FLAG_KEY("$2Key: %s", "Flag"), + FLAG_TYPE("$2Type: %s", "Flag"), + FLAG_DESC("$2Desc: %s", "Flag"), + NOT_VALID_FLAG("$2That is not a valid flag", "Flag"), + NOT_VALID_FLAG_SUGGESTED("$2That is not a valid flag. Did you mean: $1%s", "Flag"), + NOT_VALID_VALUE("$2Flag values must be alphanumerical", "Flag"), + FLAG_NOT_REMOVED("$2The flag could not be removed", "Flag"), + FLAG_NOT_ADDED("$2The flag could not be added", "Flag"), + FLAG_REMOVED("$4Successfully removed flag", "Flag"), + FLAG_ADDED("$4Successfully added flag", "Flag"), + FLAG_TUTORIAL_USAGE("$1Have an admin set the flag: $2%s", "CommandConfig"), + FLAG_LIST_ENTRY("$2%s: $1%s", "Flag"), + // + // + FLAG_CATEGORY_STRING("String Flags", "Flags"), + FLAG_CATEGORY_INTEGERS("Integer Flags", "Flags"), + FLAG_CATEGORY_TELEPORT_DENY("Teleport Deny Flag", "Flags"), + FLAG_CATEGORY_STRING_LIST("String List Flags", "Flags"), + FLAG_CATEGORY_WEATHER("Weather Flags", "Flags"), + FLAG_CATEGORY_BLOCK_LIST("Material Flags", "Flags"), + FLAG_CATEGORY_INTERVALS("Interval Flags", "Flags"), + FLAG_CATEGORY_INTEGER_LIST("Integer List Flags", "Flags"), + FLAG_CATEGORY_GAMEMODE("Game Mode Flags", "Flags"), + FLAG_CATEGORY_ENUM("Generic Enum Flags", "Flags"), + FLAG_CATEGORY_DECIMAL("Decimal Flags", "Flags"), + FLAG_CATEGORY_BOOLEAN("Boolean Flags", "Flags"), + FLAG_CATEGORY_MIXED("Mixed Value Flags", "Flags"), + // + // + FLAG_ERROR_BOOLEAN("Flag value must be a boolean (true|false)", "Flags"), + FLAG_ERROR_ENUM("Must be one of: %s", "Flags"), + FLAG_ERROR_GAMEMODE("Flag value must be a gamemode: 'survival', 'creative', 'adventure' or 'spectator.", "Flags"), + FLAG_ERROR_INTEGER("Flag value must be a whole number", "Flags"), + FLAG_ERROR_INTEGER_LIST("Flag value must be an integer list", "Flags"), + FLAG_ERROR_INTERVAL("Value(s) must be numeric. /plot set flag [amount]", "Flags"), + FLAG_ERROR_KEEP("Flag value must be a timestamp or a boolean", "Flags"), + FLAG_ERROR_LONG("Flag value must be a whole number (large numbers allowed)", "Flags"), + FLAG_ERROR_PLOTBLOCKLIST("Flag value must be a block list", "Flags"), + FLAG_ERROR_PRICE("Flag value must be a positive number.", "Flags"), + FLAG_ERROR_STRING("Flag value must be alphanumeric. Some special characters are allowed.", "Flags"), + FLAG_ERROR_STRINGLIST("Flag value must be a string list", "Flags"), + FLAG_ERROR_WEATHER("Flag must be a weather: 'rain' or 'sun'", "Flags"), + // + // + TRUSTED_ADDED("$4You successfully trusted a user to the plot", "Trusted"), + WAS_NOT_ADDED("$2That player was not trusted on this plot", "Trusted"), + PLOT_REMOVED_USER("$1Plot %s of which you were added to has been deleted due to owner inactivity", "Trusted"), + // + // + REMOVED_PLAYERS("$2Removed %s players from this plot.", "Member"), + PLOT_LEFT("$2%s left the plot.", "Member"), + ALREADY_OWNER("$2That user is already the plot owner: %s0", "Member"), + ALREADY_ADDED("$2That user is already added to that category: %s0", "Member"), + MEMBER_ADDED("$4That user can now build while the plot owner is online", "Member"), PLOT_MAX_MEMBERS("$2You are not allowed to add any more players to this plot", "Member"), - /* - * Set Owner - */ - - SET_OWNER("$4You successfully set the plot owner", "Owner"), SET_OWNER_CANCELLED( - "$2The setowner action was cancelled", "Owner"), - + NOT_ADDED_TRUSTED("$2You must be added or trusted to the plot to run that command", "Member"), + // + // + SET_OWNER("$4You successfully set the plot owner", "Owner"), + SET_OWNER_CANCELLED("$2The set owner action was cancelled", "Owner"), + SET_OWNER_MISSING_PLAYER("$1You need to specify a new owner. Correct usage is: $2/plot setowner ", "Owner"), NOW_OWNER("$4You are now owner of plot %s", "Owner"), - /* - * Signs - */ - - OWNER_SIGN_LINE_1("$1ID: $1%id%", "Signs"), OWNER_SIGN_LINE_2("$1Owner:", "Signs"), - - OWNER_SIGN_LINE_3("$2%plr%", "Signs"), OWNER_SIGN_LINE_4("$3Claimed", "Signs"), - /* - * Help - */ - - HELP_HEADER("$3&m---------&r $1Plot\u00B2 Help $3&m---------", "Help"), HELP_PAGE_HEADER( - "$1Category: $2%category%$2,$1 Page: $2%current%$3/$2%max%$2", "Help"), - - HELP_FOOTER("$3&m---------&r $1Plot\u00B2 Help $3&m---------", "Help"), - - HELP_INFO_ITEM("$1/plot help %category% $3- $2%category_desc%", "Help"), HELP_ITEM( - "$1%usage% [%alias%]&- $3- $2%desc%&-", "Help"), - + // + // + OWNER_SIGN_LINE_1("$1ID: $1%id%", "Signs"), + OWNER_SIGN_LINE_2("$1Owner:", "Signs"), + OWNER_SIGN_LINE_3("$2%plr%", "Signs"), + OWNER_SIGN_LINE_4("$3Claimed", "Signs"), + // + // + HELP_HEADER("$3&m---------&r $1Plot² Help $3&m---------", "Help"), + HELP_PAGE_HEADER("$1Category: $2%category%$2,$1 Page: $2%current%$3/$2%max%$2", "Help"), + HELP_FOOTER("$3&m---------&r $1Plot² Help $3&m---------", "Help"), + HELP_INFO_ITEM("$1/plot help %category% $3- $2%category_desc%", "Help"), + HELP_ITEM("$1%usage% [%alias%]&- $3- $2%desc%&-", "Help"), HELP_DISPLAY_ALL_COMMANDS("Display all commands", "Help"), - - BUCKET_ENTRIES_IGNORED( - "$2Total bucket values add up to 1 or more. Blocks without a spcified chance will be ignored", - "Generator_Bucket"), - - - /** - * Command Categories - */ - COMMAND_CATEGORY_CLAIMING("Claiming", "Category"), COMMAND_CATEGORY_TELEPPORT("Teleport", - "Category"), COMMAND_CATEGORY_SETTINGS("Protection", "Category"), COMMAND_CATEGORY_CHAT( - "Chat", "Category"), COMMAND_CATEGORY_SCHEMATIC("Web", - "Category"), COMMAND_CATEGORY_APPEARANCE("Cosmetic", "Category"), COMMAND_CATEGORY_INFO( - "Info", "Category"), COMMAND_CATEGORY_DEBUG("Debug", - "Category"), COMMAND_CATEGORY_ADMINISTRATION("Admin", "Category"), - - /* - * Direction - */ - DIRECTION("$1Current direction: %dir%", "Help"), - /* - * Grant - */ + // + BUCKET_ENTRIES_IGNORED("$2Total bucket values add up to 1 or more. Blocks without a specified chance will be ignored","Generator_Bucket"), - GRANTED_PLOTS("$1Result: $2%s $1grants left", "Grants"), GRANTED_PLOT( - "$1You granted %s0 plot to $2%s1", "Grants"), + // + COMMAND_CATEGORY_CLAIMING("Claiming", "Category"), + COMMAND_CATEGORY_TELEPORT("Teleport", "Category"), + COMMAND_CATEGORY_SETTINGS("Protection", "Category"), + COMMAND_CATEGORY_CHAT("Chat", "Category"), + COMMAND_CATEGORY_SCHEMATIC("Web", "Category"), + COMMAND_CATEGORY_APPEARANCE("Cosmetic", "Category"), + COMMAND_CATEGORY_INFO("Info", "Category"), + COMMAND_CATEGORY_DEBUG("Debug", "Category"), + COMMAND_CATEGORY_ADMINISTRATION("Admin", "Category"), + // + // + GRANTED_PLOTS("$1Result: $2%s $1grants left", "Grants"), + GRANTED_PLOT("$1You granted %s0 plot to $2%s1", "Grants"), GRANTED_PLOT_FAILED("$1Grant failed: $2%s", "Grants"), - /* - * Custom - */ + // /** * Legacy Configuration Conversion @@ -927,48 +639,25 @@ public enum Captions { public static final HashMap replacements = new HashMap<>(); - /** - * Default. - */ - private final String def; - /** - * What locale category should this translation fall under. - */ + private final String defaultString; private final String category; - /** - * Should the string be prefixed. - */ private final boolean prefix; - /** - * Translated. - */ - private String s; + private String translatedString; - /** - * Constructor. - * - * @param def default - * @param prefix use prefix - */ - Captions(String def, boolean prefix, String category) { - this.def = def; - this.s = def; + Captions(String defaultString, boolean prefix, String category) { + this.defaultString = defaultString; + this.translatedString = defaultString; this.prefix = prefix; this.category = category.toLowerCase(); } - /** - * Constructor. - * - * @param def default - */ - Captions(String def, String category) { - this(def, true, category.toLowerCase()); + Captions(String defaultString, String category) { + this(defaultString, true, category.toLowerCase()); } - public static String format(String m, Object... args) { + public static String format(String message, Object... args) { if (args.length == 0) { - return m; + return message; } Map map = new LinkedHashMap<>(); for (int i = args.length - 1; i >= 0; i--) { @@ -983,15 +672,15 @@ public enum Captions { map.put("%s", arg); } } - m = StringMan.replaceFromMap(m, map); - return m; + message = StringMan.replaceFromMap(message, map); + return message; } public static String format(Captions caption, Object... args) { - if (caption.usePrefix() && caption.s.length() > 0) { - return Captions.PREFIX.s() + format(caption.s, args); + if (caption.usePrefix() && caption.translatedString.length() > 0) { + return Captions.PREFIX.getTranslated() + format(caption.translatedString, args); } else { - return format(caption.s, args); + return format(caption.translatedString, args); } } @@ -1043,7 +732,7 @@ public enum Captions { yml.set(caption.category + '.' + caption.name().toLowerCase(), value); } captions.add(caption); - caption.s = value; + caption.translatedString = value; } else { toRemove.add(key); } @@ -1071,9 +760,11 @@ public enum Captions { continue; } changed = true; - yml.set(caption.category + '.' + caption.name().toLowerCase(), caption.def); + yml.set(caption.category + '.' + caption.name().toLowerCase(), + caption.defaultString); } - caption.s = StringMan.replaceFromMap(caption.s, replacements); + caption.translatedString = + StringMan.replaceFromMap(caption.translatedString, replacements); } if (changed) { yml.save(file); @@ -1083,16 +774,12 @@ public enum Captions { } } - public String f(final Object... args) { - return format(s(), args); - } - @Override public String toString() { - return this.s; + return this.translatedString; } - public String s() { - return this.s; + public String getTranslated() { + return this.translatedString; } public boolean usePrefix() { @@ -1100,7 +787,7 @@ public enum Captions { } public String formatted() { - return StringMan.replaceFromMap(s(), replacements); + return StringMan.replaceFromMap(getTranslated(), replacements); } public String getCategory() { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Config.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Config.java index ace39f846..26c5050ce 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Config.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Config.java @@ -13,8 +13,11 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.invoke.MethodHandles; import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class Config { @@ -361,12 +364,8 @@ public class Config { * @throws NoSuchFieldException * @throws IllegalAccessException */ - private static void setAccessible(Field field) - throws NoSuchFieldException, IllegalAccessException { + private static void setAccessible(Field field) { field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } /** diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Configuration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Configuration.java index 3d636e0dd..1fa167177 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Configuration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Configuration.java @@ -1,9 +1,10 @@ package com.github.intellectualsites.plotsquared.plot.config; import com.github.intellectualsites.plotsquared.plot.object.BlockBucket; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; -import com.github.intellectualsites.plotsquared.plot.util.StringComparison; -import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.biome.BiomeTypes; +import com.sk89q.worldedit.world.block.BlockState; import lombok.Getter; import lombok.NonNull; @@ -37,92 +38,39 @@ public class Configuration { return Boolean.parseBoolean(string); } }; - public static final SettingValue BIOME = new SettingValue("BIOME") { + public static final SettingValue BIOME = new SettingValue("BIOME") { @Override public boolean validateValue(String string) { try { - int biome = WorldUtil.IMP.getBiomeFromString(string.toUpperCase()); - return biome != -1; + return BiomeTypes.get(string) != null; } catch (Exception ignored) { return false; } } - @Override public String parseString(String string) { + @Override public BiomeType parseString(String string) { if (validateValue(string)) { - return string.toUpperCase(); + return BiomeTypes.get(string.toLowerCase()); } - return "FOREST"; + return BiomeTypes.FOREST; } }; public static final SettingValue BLOCK_BUCKET = new SettingValue("BLOCK_BUCKET") { - @Override public BlockBucket parseString(final String string) { - if (string == null || string.isEmpty()) { - return new BlockBucket(); - } - final BlockBucket blockBucket = new BlockBucket(); - final String[] parts = string.split(","); - for (final String part : parts) { - String block; - int chance = -1; - if (part.contains(":")) { - final String[] innerParts = part.split(":"); - if (innerParts.length > 1) { - chance = Integer.parseInt(innerParts[1]); - } - block = innerParts[0]; - } else { - block = part; - } - final StringComparison.ComparisonResult value = - WorldUtil.IMP.getClosestBlock(block); - if (value == null) { - throw new UnknownBlockException(block); - } else if (Settings.Enabled_Components.PREVENT_UNSAFE && !value.best.isAir() - && !WorldUtil.IMP.isBlockSolid(value.best)) { - throw new UnsafeBlockException(value.best); - } - blockBucket.addBlock(value.best, chance); - } - blockBucket.compile(); // Pre-compile :D - return blockBucket; + @Override public BlockBucket parseString(final String string) { + BlockBucket bucket = new BlockBucket(string); + bucket.compile(); + Pattern pattern = bucket.toPattern(); + return pattern != null ? bucket : null; } @Override public boolean validateValue(final String string) { try { - if (string == null || string.isEmpty()) { - return false; - } - final String[] parts = string.split(","); - for (final String part : parts) { - String block; - if (part.contains(":")) { - final String[] innerParts = part.split(":"); - if (innerParts.length > 1) { - final int chance = Integer.parseInt(innerParts[1]); - if (chance < 1 || chance > 100) { - return false; - } - } - block = innerParts[0]; - } else { - block = part; - } - StringComparison.ComparisonResult value = - WorldUtil.IMP.getClosestBlock(block); - if (value == null || value.match > 1) { - return false; - } else if (Settings.Enabled_Components.PREVENT_UNSAFE && !value.best.isAir() - && !WorldUtil.IMP.isBlockSolid(value.best)) { - throw new UnsafeBlockException(value.best); - } - } - } catch (final Throwable exception) { + return parseString(string) != null; + } catch (Exception e) { return false; } - return true; } }; @@ -162,9 +110,9 @@ public class Configuration { public static final class UnsafeBlockException extends IllegalArgumentException { - @Getter private final PlotBlock unsafeBlock; + @Getter private final BlockState unsafeBlock; - UnsafeBlockException(@NonNull final PlotBlock unsafeBlock) { + UnsafeBlockException(@NonNull final BlockState unsafeBlock) { super(String.format("%s is not a valid block", unsafeBlock)); this.unsafeBlock = unsafeBlock; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/ConfigurationNode.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/ConfigurationNode.java index 31539d5c2..2b6167e97 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/ConfigurationNode.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/ConfigurationNode.java @@ -1,8 +1,8 @@ package com.github.intellectualsites.plotsquared.plot.config; import com.github.intellectualsites.plotsquared.plot.object.BlockBucket; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.sk89q.worldedit.world.block.BlockState; import java.util.ArrayList; import java.util.Arrays; @@ -66,7 +66,7 @@ public class ConfigurationNode { if (this.value instanceof BlockBucket) { return this.value.toString(); } - if (this.value instanceof PlotBlock) { + if (this.value instanceof BlockState) { return this.value.toString(); } return this.value; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Settings.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Settings.java index 3c492583c..434783241 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Settings.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/config/Settings.java @@ -16,19 +16,19 @@ public class Settings extends Config { @Comment("These first 7 aren't configurable") // This is a comment @Final // Indicates that this value isn't configurable - public static final String ISSUES = "https://github.com/IntellectualSites/PlotSquared/issues"; - @Final public static final String SUGGESTION = + public static String ISSUES = "https://github.com/IntellectualSites/PlotSquared/issues"; + @Final public static String SUGGESTION = "https://github.com/IntellectualSites/PlotSquaredSuggestions"; - @Final public static final String WIKI = + @Final public static String WIKI = "https://github.com/IntellectualSites/PlotSquared/wiki"; @Final public static String DATE; // These values are set from P2 before loading @Final public static String BUILD; // These values are set from P2 before loading @Final public static String COMMIT; // These values are set from P2 before loading @Final public static String PLATFORM; // These values are set from P2 before loading - @Comment("Show additional information in console") public static boolean DEBUG = true; + @Comment("Show additional information in console") public static boolean DEBUG = false; @Comment({"The big annoying text that appears when you enter a plot", - "For a single plot: `/plot flag set titles false`", "For just you: `/plot toggle titles`"}) + "For a single plot: `/plot flag set titles false`", "For just you: `/plot toggle titles`", "For all plots: Add `titles: false` in the worlds.yml flags block"}) public static boolean TITLES = true; @Create // This value will be generated automatically @@ -256,10 +256,10 @@ public class Settings extends Config { public static final class Done { - @Comment("Require a done plot to download") public static boolean REQUIRED_FOR_DOWNLOAD = + @Comment("Require a plot marked as done to download") public static boolean REQUIRED_FOR_DOWNLOAD = false; - @Comment("Only done plots can be rated") public static boolean REQUIRED_FOR_RATINGS = false; - @Comment("Restrict building when a plot is done") public static boolean RESTRICT_BUILDING = + @Comment("Only plots marked as done can be rated") public static boolean REQUIRED_FOR_RATINGS = false; + @Comment("Restrict building when a plot is marked as done") public static boolean RESTRICT_BUILDING = false; @Comment("The limit being how many plots a player can claim") public static boolean COUNTS_TOWARDS_LIMIT = true; @@ -269,14 +269,15 @@ public class Settings extends Config { public static final class Chat { @Comment("Sometimes console color doesn't work, you can disable it here") public static boolean CONSOLE_COLOR = true; - @Comment("Should chat be interactive") public static boolean INTERACTIVE = true; + @Comment("Should the chat be interactive?") public static boolean INTERACTIVE = true; } @Comment("Relating to how many plots someone can claim ") public static final class Limit { @Comment("Should the limit be global (over multiple worlds)") public static boolean GLOBAL = false; - @Comment("The range of permissions to check e.g. plots.plot.127") public static int + @Comment({"The max. range of permissions to check e.g. plots.plot.127", "The value covers the range to check only, you need to assign the permission to players/groups still", + "Modifying the value does NOT change the amount of plots players can claim"}) public static int MAX_PLOTS = 127; } @@ -291,7 +292,7 @@ public class Settings extends Config { @Comment("Teleport to your plot on death") public static boolean ON_DEATH = false; @Comment("Teleport to your plot on login") public static boolean ON_LOGIN = false; @Comment("Teleport to your plot on claim") public static boolean ON_CLAIM = true; - @Comment("Add a teleportation delay to all commands") public static int DELAY = 0; + @Comment("Add a delay to all teleport commands") public static int DELAY = 0; @Comment("The visit command is ordered by world instead of globally") public static boolean PER_WORLD_VISIT = false; } @@ -322,7 +323,7 @@ public class Settings extends Config { @Comment( - {"Enable or disable part of the plugin", "Note: A cache will use some memory if enabled"}) + {"Enable or disable parts of the plugin", "Note: A cache will use some memory if enabled"}) public static final class Enabled_Components { // Group the following values into a new config section @Comment("The database stores all the plots") public static boolean DATABASE = true; @Comment("Events are needed to track a lot of things") public static boolean EVENTS = true; @@ -330,7 +331,7 @@ public class Settings extends Config { true; @Comment("The UUID cacher is used to resolve player names") public static boolean UUID_CACHE = true; - @Comment("The plugin auto updater") public static boolean UPDATER = true; + @Comment("The plugin auto updater will notify you if updates are available.") public static boolean UPDATER = true; @Comment("Stores user metadata in a database") public static boolean PERSISTENT_META = true; @Comment("Optimizes permission checks") public static boolean PERMISSION_CACHE = true; @Comment("Optimizes block changing code") public static boolean BLOCK_CACHE = true; @@ -339,7 +340,7 @@ public class Settings extends Config { @Comment("Allow WorldEdit to be restricted to plots") public static boolean WORLDEDIT_RESTRICTIONS = true; @Comment("Allow economy to be used") public static boolean ECONOMY = true; - @Comment("Send anonymous usage statistics. Bukkit only setting.") public static boolean + @Comment("Send anonymous usage statistics to bStats. Bukkit only setting.") public static boolean METRICS = true; @Comment("Expiry will clear old or simplistic plots") public static boolean PLOT_EXPIRY = false; @@ -350,12 +351,12 @@ public class Settings extends Config { @Comment("Kill vehicles on roads") public static boolean KILL_ROAD_VEHICLES = false; @Comment("Notify a player of any missed comments upon plot entry") public static boolean COMMENT_NOTIFIER = false; - @Comment("Let player's claim entire worlds with PlotSquared") public static boolean WORLDS = + @Comment("Let players claim entire worlds with PlotSquared") public static boolean WORLDS = false; @Comment("Actively purge invalid database entries") public static boolean DATABASE_PURGER = false; @Comment("Delete plots when a player is banned") public static boolean BAN_DELETER = false; - @Comment("Prevent possibly unsafe blocks from being used in plot components") + @Comment({"Prevent possibly unsafe blocks from being used in plot components", "Can be bypassed with `/plot debugallowunsafe`"}) public static boolean PREVENT_UNSAFE = true; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDB.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDB.java index d812413ea..5beef2aab 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDB.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDB.java @@ -1,11 +1,19 @@ package com.github.intellectualsites.plotsquared.plot.database; import com.github.intellectualsites.plotsquared.plot.flag.Flag; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotCluster; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.comment.PlotComment; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; public interface AbstractDB { @@ -223,7 +231,7 @@ public interface AbstractDB { /** * @param cluster PlotCluster Object - * @param uuid Player that should be removed + * @param uuid Player that should be removed */ void setHelper(PlotCluster cluster, UUID uuid); @@ -275,7 +283,7 @@ public interface AbstractDB { /** * Removes the specified comment from the given plot. * - * @param plot the plot + * @param plot the plot * @param comment the comment to remove */ void removeComment(Plot plot, PlotComment comment); @@ -283,7 +291,7 @@ public interface AbstractDB { /** * Clears the specified inbox on the given plot. * - * @param plot the plot + * @param plot the plot * @param inbox the inbox to clear */ void clearInbox(Plot plot, String inbox); @@ -291,17 +299,17 @@ public interface AbstractDB { /** * Adds the specified comment to the given plot. * - * @param plot the plot + * @param plot the plot * @param comment the comment to add */ void setComment(Plot plot, PlotComment comment); /** - * Gets Plot Comments. + * Gets Plot comments. * * @param plot The Plot to get comments from */ - void getComments(@Nonnull Plot plot, String inbox, RunnableVal> whenDone); + void getComments(@NotNull Plot plot, String inbox, RunnableVal> whenDone); void createPlotAndSettings(Plot plot, Runnable whenDone); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/DBFunc.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/DBFunc.java index abb4dad24..47a03cf60 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/DBFunc.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/DBFunc.java @@ -1,13 +1,21 @@ package com.github.intellectualsites.plotsquared.plot.database; import com.github.intellectualsites.plotsquared.plot.flag.Flag; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotCluster; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.comment.PlotComment; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; /** * Database Functions @@ -74,6 +82,8 @@ public class DBFunc { DBFunc.dbManager.validateAllPlots(plots); } + + //TODO Consider Removal /** * Check if a {@link ResultSet} contains a column. * @@ -81,7 +91,7 @@ public class DBFunc { * @param name * @return */ - public static boolean hasColumn(ResultSet resultSet, String name) { + @Deprecated public static boolean hasColumn(ResultSet resultSet, String name) { try { ResultSetMetaData meta = resultSet.getMetaData(); int count = meta.getColumnCount(); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/MySQL.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/MySQL.java index d5943d1ac..f8b2cedb0 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/MySQL.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/MySQL.java @@ -3,7 +3,11 @@ package com.github.intellectualsites.plotsquared.plot.database; import com.github.intellectualsites.plotsquared.plot.config.Storage; import com.github.intellectualsites.plotsquared.plot.util.StringMan; -import java.sql.*; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; /** * Connects to and uses a MySQL database diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLManager.java index fac357c46..cf229e316 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLManager.java @@ -6,19 +6,40 @@ import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.config.Storage; import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.BlockLoc; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotCluster; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotSettings; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.comment.PlotComment; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.StringMan; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.google.common.base.Charsets; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; -import java.sql.*; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Queue; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; @@ -308,7 +329,6 @@ import java.util.concurrent.atomic.AtomicInteger; PlotSquared.debug("============ DATABASE ERROR ============"); PlotSquared.debug("There was an error updating the database."); PlotSquared.debug(" - It will be corrected on shutdown"); - PlotSquared.debug("========================================"); e.printStackTrace(); PlotSquared.debug("========================================"); } @@ -326,15 +346,15 @@ import java.util.concurrent.atomic.AtomicInteger; PreparedStatement statement = null; UniqueStatement task = null; UniqueStatement lastTask = null; - Iterator>> iter = + Iterator>> iterator = this.plotTasks.entrySet().iterator(); - while (iter.hasNext()) { + while (iterator.hasNext()) { try { - Entry> entry = iter.next(); + Entry> entry = iterator.next(); Plot plot = entry.getKey(); Queue tasks = entry.getValue(); if (tasks.isEmpty()) { - iter.remove(); + iterator.remove(); continue; } task = tasks.remove(); @@ -352,10 +372,10 @@ import java.util.concurrent.atomic.AtomicInteger; task.set(statement); task.addBatch(statement); try { - if (statement != null && statement.isClosed()) { + if (statement.isClosed()) { statement = null; } - } catch (AbstractMethodError ignore) { + } catch (NullPointerException | AbstractMethodError ignore) { } } lastTask = task; @@ -858,10 +878,10 @@ import java.util.concurrent.atomic.AtomicInteger; statement.setInt(i * 10 + 9, hash); BlockLoc loc = pair.settings.getPosition(); String position; - if (loc.y == 0) { + if (loc.getY() == 0) { position = "DEFAULT"; } else { - position = loc.x + "," + loc.y + ',' + loc.z; + position = loc.getX() + "," + loc.getY() + ',' + loc.getZ(); } statement.setString(i * 10 + 10, position); } @@ -899,10 +919,10 @@ import java.util.concurrent.atomic.AtomicInteger; stmt.setInt(i * 10 + 9, n); BlockLoc loc = pair.settings.getPosition(); String position; - if (loc.y == 0) { + if (loc.getY() == 0) { position = "DEFAULT"; } else { - position = loc.x + "," + loc.y + ',' + loc.z; + position = loc.getX() + "," + loc.getY() + ',' + loc.getZ(); } stmt.setString(i * 10 + 10, position); } @@ -1615,17 +1635,17 @@ import java.util.concurrent.atomic.AtomicInteger; PlotId plot_id = new PlotId(resultSet.getInt("plot_id_x"), resultSet.getInt("plot_id_z")); id = resultSet.getInt("id"); - String areaid = resultSet.getString("world"); - if (!areas.contains(areaid)) { + String areaID = resultSet.getString("world"); + if (!areas.contains(areaID)) { if (Settings.Enabled_Components.DATABASE_PURGER) { toDelete.add(id); continue; } else { - AtomicInteger value = noExist.get(areaid); + AtomicInteger value = noExist.get(areaID); if (value != null) { value.incrementAndGet(); } else { - noExist.put(areaid, new AtomicInteger(1)); + noExist.put(areaID, new AtomicInteger(1)); } } } @@ -1657,7 +1677,7 @@ import java.util.concurrent.atomic.AtomicInteger; .getTime(); } catch (ParseException e) { PlotSquared.debug( - "Could not parse date for plot: #" + id + "(" + areaid + ";" + "Could not parse date for plot: #" + id + "(" + areaID + ";" + plot_id + ") (" + parsable + ")"); time = System.currentTimeMillis() + id; } @@ -1665,7 +1685,7 @@ import java.util.concurrent.atomic.AtomicInteger; Plot p = new Plot(plot_id, user, new HashSet<>(), new HashSet<>(), new HashSet<>(), "", null, null, null, new boolean[] {false, false, false, false}, time, id); - HashMap map = newPlots.get(areaid); + HashMap map = newPlots.get(areaID); if (map != null) { Plot last = map.put(p.getId(), p); if (last != null) { @@ -1679,7 +1699,7 @@ import java.util.concurrent.atomic.AtomicInteger; } } else { map = new HashMap<>(); - newPlots.put(areaid, map); + newPlots.put(areaID, map); map.put(p.getId(), p); } plots.put(id, p); @@ -2171,7 +2191,7 @@ import java.util.concurrent.atomic.AtomicInteger; }); } - @Override public void getComments(@Nonnull Plot plot, final String inbox, + @Override public void getComments(@NotNull Plot plot, final String inbox, final RunnableVal> whenDone) { addPlotTask(plot, new UniqueStatement("getComments_" + plot) { @Override public void set(PreparedStatement statement) throws SQLException { @@ -2539,11 +2559,7 @@ import java.util.concurrent.atomic.AtomicInteger; id = resultSet.getInt("id"); String areaid = resultSet.getString("world"); if (!areas.contains(areaid)) { - if (noExist.containsKey(areaid)) { - noExist.put(areaid, noExist.get(areaid) + 1); - } else { - noExist.put(areaid, 1); - } + noExist.merge(areaid, 1, Integer::sum); } owner = resultSet.getString("owner"); user = uuids.get(owner); @@ -2858,6 +2874,16 @@ import java.util.concurrent.atomic.AtomicInteger; if (plot.temp == -1) { continue; } + if (plot.getArea() == null) { + PlotSquared.debug("CRITICAL ERROR IN VALIDATION TASK!"); + PlotSquared.debug("PLOT AREA CANNOT BE NULL! SKIPPING PLOT!"); + continue; + } + if (database == null) { + PlotSquared.debug("CRITICAL ERROR IN VALIDATION TASK!"); + PlotSquared.debug("DATABASE VARIABLE CANNOT BE NULL! NOW ENDING VALIDATION!!"); + break; + } HashMap worldPlots = database.get(plot.getArea().toString()); if (worldPlots == null) { PlotSquared.debug("&8 - &7Creating plot (1): " + plot); @@ -2937,7 +2963,7 @@ import java.util.concurrent.atomic.AtomicInteger; boolean[] pm = plot.getMerged(); boolean[] dm = dataPlot.getMerged(); if (pm[0] != dm[0] || pm[1] != dm[1]) { - PlotSquared.debug("&8 - &7Correcting merge for: " + plot); + PlotSquared.debug(" - Correcting merge for: " + plot); setMerged(dataPlot, plot.getMerged()); } HashMap, Object> pf = plot.getFlags(); @@ -2946,7 +2972,7 @@ import java.util.concurrent.atomic.AtomicInteger; if (pf.size() != df.size() || !StringMan .isEqual(StringMan.joinOrdered(pf.values(), ","), StringMan.joinOrdered(df.values(), ","))) { - PlotSquared.debug("&8 - &7Correcting flags for: " + plot); + PlotSquared.debug(" - Correcting flags for: " + plot); setFlags(plot, pf); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLite.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLite.java index 3675ad0cd..10ceb8784 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLite.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/database/SQLite.java @@ -4,7 +4,11 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import java.io.File; import java.io.IOException; -import java.sql.*; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; /** * Connects to and uses a SQLite database. diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/BlockStateListFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/BlockStateListFlag.java new file mode 100644 index 000000000..117551488 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/BlockStateListFlag.java @@ -0,0 +1,36 @@ +package com.github.intellectualsites.plotsquared.plot.flag; + +import com.github.intellectualsites.plotsquared.plot.config.Captions; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.world.BlockUtil; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockType; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +public class BlockStateListFlag extends ListFlag> { + + public BlockStateListFlag(String name) { + super(Captions.FLAG_CATEGORY_BLOCK_LIST, name); + } + + @Override public String valueToString(Object value) { + return StringMan.join((Set) value, ","); + } + + @Override public Set parseValue(final String value) { + return Arrays.stream(BlockUtil.parse(value)).filter(Objects::nonNull).map(BlockState::getBlockType).collect(Collectors.toSet()); + } + + @Override public String getValueDescription() { + return Captions.FLAG_ERROR_PLOTBLOCKLIST.getTranslated(); + } + + public boolean contains(Plot plot, BlockState value) { + return contains(plot, value.getBlockType()); + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/BooleanFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/BooleanFlag.java index a492c9c0f..692c0b501 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/BooleanFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/BooleanFlag.java @@ -1,11 +1,12 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.Plot; public class BooleanFlag extends Flag { public BooleanFlag(String name) { - super(name); + super(Captions.FLAG_CATEGORY_BOOLEAN, name); } @Override public String valueToString(Object value) { @@ -30,7 +31,7 @@ public class BooleanFlag extends Flag { } @Override public String getValueDescription() { - return "Flag value must be a boolean (true|false)"; + return Captions.FLAG_ERROR_BOOLEAN.getTranslated(); } public boolean isTrue(Plot plot) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/DoubleFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/DoubleFlag.java index 9b46a2cde..ab2c86c45 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/DoubleFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/DoubleFlag.java @@ -1,9 +1,11 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; + public class DoubleFlag extends Flag { public DoubleFlag(String name) { - super(name); + super(Captions.FLAG_CATEGORY_DECIMAL, name); } @Override public String valueToString(Object value) { @@ -20,6 +22,6 @@ public class DoubleFlag extends Flag { } @Override public String getValueDescription() { - return "Flag value must be a number."; + return Captions.FLAG_ERROR_BOOLEAN.getTranslated(); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/EnumFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/EnumFlag.java index 3ba6b2457..06936d4df 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/EnumFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/EnumFlag.java @@ -1,15 +1,17 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.util.StringMan; import java.util.Arrays; import java.util.HashSet; public class EnumFlag extends Flag { + private final HashSet values; public EnumFlag(String name, String... values) { - super(name); + super(Captions.FLAG_CATEGORY_ENUM, name); this.values = new HashSet<>(Arrays.asList(values)); } @@ -26,6 +28,6 @@ public class EnumFlag extends Flag { } @Override public String getValueDescription() { - return "Must be one of: " + StringMan.getString(values); + return Captions.FLAG_ERROR_ENUM.getTranslated() + StringMan.getString(values); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/Flag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/Flag.java index 3b247d87a..21047d9cd 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/Flag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/Flag.java @@ -1,13 +1,21 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.util.StringComparison; +import lombok.Getter; public abstract class Flag implements StringComparison.StringComparable { + @Getter private final Captions typeCaption; private final String name; private boolean reserved = false; + public Flag(Captions typeCaption, String name) { + this.typeCaption = typeCaption; + this.name = name; + } + /** * Flag object used to store basic information for a Plot. Flags are a * key/value pair. For a flag to be usable by a player, you need to @@ -16,7 +24,7 @@ public abstract class Flag implements StringComparison.StringComparable { * @param name the flag name */ public Flag(String name) { - this.name = name; + this(null, name); } public Flag reserve() { @@ -57,4 +65,11 @@ public abstract class Flag implements StringComparison.StringComparable { @Override public String getComparableString() { return getName(); } + + public String getCategoryCaption() { + return this.typeCaption == null ? + getClass().getSimpleName() : + this.typeCaption.getTranslated(); + } + } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/FlagManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/FlagManager.java index 6dc4aa2ff..51391f788 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/FlagManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/FlagManager.java @@ -10,7 +10,12 @@ import com.github.intellectualsites.plotsquared.plot.util.EventUtil; import com.github.intellectualsites.plotsquared.plot.util.Permissions; import com.google.common.collect.ImmutableSet; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; /** diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/Flags.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/Flags.java index 12d9e2b06..6df44dca7 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/Flags.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/Flags.java @@ -1,6 +1,7 @@ package com.github.intellectualsites.plotsquared.plot.flag; import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.StringMan; @@ -39,34 +40,33 @@ public final class Flags { } @Override public String getValueDescription() { - return "Flag value must be a positive number."; + return Captions.FLAG_ERROR_PRICE.getTranslated(); } }; public static final BooleanFlag EXPLOSION = new BooleanFlag("explosion"); public static final BooleanFlag GRASS_GROW = new BooleanFlag("grass-grow"); public static final BooleanFlag VINE_GROW = new BooleanFlag("vine-grow"); public static final BooleanFlag MYCEL_GROW = new BooleanFlag("mycel-grow"); + public static final BooleanFlag KELP_GROW = new BooleanFlag("kelp-grow"); public static final BooleanFlag DISABLE_PHYSICS = new BooleanFlag("disable-physics"); public static final BooleanFlag LIQUID_FLOW = new BooleanFlag("liquid-flow"); public static final BooleanFlag SNOW_MELT = new BooleanFlag("snow-melt"); public static final BooleanFlag SNOW_FORM = new BooleanFlag("snow-form"); public static final BooleanFlag ICE_MELT = new BooleanFlag("ice-melt"); - public static final BooleanFlag FIRE_SPREAD = new BooleanFlag("fire-spread"); public static final BooleanFlag BLOCK_BURN = new BooleanFlag("block-burn"); public static final BooleanFlag ICE_FORM = new BooleanFlag("ice-form"); public static final BooleanFlag BLOCK_IGNITION = new BooleanFlag("block-ignition"); public static final BooleanFlag SOIL_DRY = new BooleanFlag("soil-dry"); public static final StringListFlag BLOCKED_CMDS = new StringListFlag("blocked-cmds"); - public static final PlotBlockListFlag USE = new PlotBlockListFlag("use"); - public static final PlotBlockListFlag BREAK = new PlotBlockListFlag("break"); - public static final PlotBlockListFlag PLACE = new PlotBlockListFlag("place"); + public static final BlockStateListFlag USE = new BlockStateListFlag("use"); + public static final BlockStateListFlag BREAK = new BlockStateListFlag("break"); + public static final BlockStateListFlag PLACE = new BlockStateListFlag("place"); public static final BooleanFlag DEVICE_INTERACT = new BooleanFlag("device-interact"); public static final BooleanFlag VEHICLE_BREAK = new BooleanFlag("vehicle-break"); public static final BooleanFlag VEHICLE_PLACE = new BooleanFlag("vehicle-place"); public static final BooleanFlag VEHICLE_USE = new BooleanFlag("vehicle-use"); public static final BooleanFlag HANGING_BREAK = new BooleanFlag("hanging-break"); public static final BooleanFlag HANGING_PLACE = new BooleanFlag("hanging-place"); - public static final BooleanFlag HANGING_INTERACT = new BooleanFlag("hanging-interact"); public static final BooleanFlag MISC_PLACE = new BooleanFlag("misc-place"); public static final BooleanFlag MISC_BREAK = new BooleanFlag("misc-break"); public static final BooleanFlag MISC_INTERACT = new BooleanFlag("misc-interact"); @@ -94,7 +94,7 @@ public final class Flags { public static final IntegerFlag ANIMAL_CAP = new IntegerFlag("animal-cap"); public static final IntegerFlag HOSTILE_CAP = new IntegerFlag("hostile-cap"); public static final IntegerFlag VEHICLE_CAP = new IntegerFlag("vehicle-cap"); - public static final Flag KEEP = new Flag("keep") { + public static final Flag KEEP = new Flag(Captions.FLAG_CATEGORY_MIXED, "keep") { @Override public String valueToString(Object value) { return value.toString(); } @@ -114,12 +114,12 @@ public final class Flags { } @Override public String getValueDescription() { - return "Flag value must a timestamp or a boolean"; + return Captions.FLAG_ERROR_KEEP.getTranslated(); } }; - public static final BooleanFlag SLEEP = new BooleanFlag("sleep"); public static final TeleportDenyFlag DENY_TELEPORT = new TeleportDenyFlag("deny-teleport"); public static final BooleanFlag DENY_EXIT = new BooleanFlag("deny-exit"); + public static final BooleanFlag UNTRUSTED_VISIT = new BooleanFlag("untrusted-visit"); private static final HashMap> flags; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/GameModeFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/GameModeFlag.java index 3467171f2..0c4ca07a1 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/GameModeFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/GameModeFlag.java @@ -1,40 +1,42 @@ package com.github.intellectualsites.plotsquared.plot.flag; -import com.github.intellectualsites.plotsquared.plot.util.PlotGameMode; +import com.github.intellectualsites.plotsquared.plot.config.Captions; +import com.sk89q.worldedit.world.gamemode.GameMode; +import com.sk89q.worldedit.world.gamemode.GameModes; -public class GameModeFlag extends Flag { +public class GameModeFlag extends Flag { public GameModeFlag(String name) { - super(name); + super(Captions.FLAG_CATEGORY_GAMEMODE, name); } @Override public String valueToString(Object value) { - return ((PlotGameMode) value).getName(); + return ((GameMode) value).getName(); } - @Override public PlotGameMode parseValue(String value) { + @Override public GameMode parseValue(String value) { switch (value.toLowerCase()) { - case "survival": - case "s": - case "0": - return PlotGameMode.SURVIVAL; case "creative": case "c": case "1": - return PlotGameMode.CREATIVE; + return GameModes.CREATIVE; case "adventure": case "a": case "2": - return PlotGameMode.ADVENTURE; + return GameModes.ADVENTURE; case "spectator": + case "sp": case "3": - return PlotGameMode.SPECTATOR; + return GameModes.SPECTATOR; + case "survival": + case "s": + case "0": default: - return PlotGameMode.NOT_SET; + return GameModes.SURVIVAL; } } @Override public String getValueDescription() { - return "Flag value must be a gamemode: 'survival', 'creative', 'adventure' or 'spectator'"; + return Captions.FLAG_ERROR_GAMEMODE.getTranslated(); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntegerFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntegerFlag.java index 2cafed4d1..8b527c46a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntegerFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntegerFlag.java @@ -1,15 +1,16 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.Plot; public class IntegerFlag extends Flag { public IntegerFlag(String name) { - super(name); + super(Captions.FLAG_CATEGORY_INTEGERS, name); } @Override public String getValueDescription() { - return "Flag value must be a whole number"; + return Captions.FLAG_ERROR_INTEGER.getTranslated(); } @Override public String valueToString(Object value) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntegerListFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntegerListFlag.java index e46071b86..e9162000b 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntegerListFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntegerListFlag.java @@ -1,5 +1,6 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.util.StringMan; import java.util.ArrayList; @@ -9,7 +10,7 @@ import java.util.List; public class IntegerListFlag extends ListFlag> { public IntegerListFlag(String name) { - super(name); + super(Captions.FLAG_CATEGORY_INTEGER_LIST, name); } @Override public String valueToString(Object value) { @@ -26,6 +27,6 @@ public class IntegerListFlag extends ListFlag> { } @Override public String getValueDescription() { - return "Flag value must be an integer list"; + return Captions.FLAG_ERROR_INTEGER_LIST.getTranslated(); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntervalFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntervalFlag.java index c8f490591..7b6b64d47 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntervalFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/IntervalFlag.java @@ -1,5 +1,6 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; @@ -7,7 +8,7 @@ import lombok.RequiredArgsConstructor; public class IntervalFlag extends Flag { public IntervalFlag(String name) { - super(name); + super(Captions.FLAG_CATEGORY_INTERVALS, name); } @Override public String valueToString(Object value) { @@ -39,7 +40,7 @@ public class IntervalFlag extends Flag { } @Override public String getValueDescription() { - return "Value(s) must be numeric. /plot set flag [amount]"; + return Captions.FLAG_ERROR_INTERVAL.getTranslated(); } @EqualsAndHashCode @RequiredArgsConstructor @Getter public static final class Interval { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/ItemTypeListFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/ItemTypeListFlag.java new file mode 100644 index 000000000..5812588c2 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/ItemTypeListFlag.java @@ -0,0 +1,31 @@ +package com.github.intellectualsites.plotsquared.plot.flag; + +import com.github.intellectualsites.plotsquared.plot.config.Captions; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.world.ItemUtil; +import com.sk89q.worldedit.world.item.ItemType; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +public class ItemTypeListFlag extends ListFlag> { + + public ItemTypeListFlag(String name) { + super(Captions.FLAG_CATEGORY_BLOCK_LIST, name); + } + + @Override public String valueToString(Object value) { + return StringMan.join((Set) value, ","); + } + + @Override public Set parseValue(final String value) { + return Arrays.stream(ItemUtil.parse(value)).filter(Objects::nonNull) + .collect(Collectors.toSet()); + } + + @Override public String getValueDescription() { + return Captions.FLAG_ERROR_PLOTBLOCKLIST.getTranslated(); + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/ListFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/ListFlag.java index 518c3df11..3085288b1 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/ListFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/ListFlag.java @@ -1,11 +1,16 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.Plot; import java.util.Collection; public abstract class ListFlag> extends Flag { + public ListFlag(Captions typeCaption, String name) { + super(typeCaption, name); + } + public ListFlag(String name) { super(name); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/LongFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/LongFlag.java index 464780af8..1d8846701 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/LongFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/LongFlag.java @@ -1,9 +1,11 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; + public class LongFlag extends Flag { public LongFlag(String name) { - super(name); + super(Captions.FLAG_CATEGORY_INTEGERS, name); } @Override public Long parseValue(String value) { @@ -19,6 +21,6 @@ public class LongFlag extends Flag { } @Override public String getValueDescription() { - return "Flag value must be a whole number (large numbers allowed)"; + return Captions.FLAG_ERROR_LONG.getTranslated(); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/PlotBlockListFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/PlotBlockListFlag.java deleted file mode 100644 index 56cd0e901..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/PlotBlockListFlag.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.flag; - -import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; -import com.github.intellectualsites.plotsquared.plot.util.StringMan; - -import java.util.HashSet; - -public class PlotBlockListFlag extends ListFlag> { - - public PlotBlockListFlag(String name) { - super(name); - } - - @Override public String valueToString(Object value) { - return StringMan.join((HashSet) value, ","); - } - - @Override public HashSet parseValue(final String value) { - final HashSet list = new HashSet<>(); - for (final String item : value.split(",")) { - final PlotBlock block = PlotSquared.get().IMP.getLegacyMappings().fromAny(item); - if (block != null) { - list.add(block); - } - } - return list; - } - - @Override public String getValueDescription() { - return "Flag value must be a block list"; - } -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/PlotWeatherFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/PlotWeatherFlag.java index e6f93ee2d..1893d5370 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/PlotWeatherFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/PlotWeatherFlag.java @@ -1,11 +1,12 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.util.PlotWeather; public class PlotWeatherFlag extends Flag { public PlotWeatherFlag(String name) { - super(name); + super(Captions.FLAG_CATEGORY_WEATHER, name); } @Override public String valueToString(Object value) { @@ -30,6 +31,6 @@ public class PlotWeatherFlag extends Flag { } @Override public String getValueDescription() { - return "Flag must be a weather: 'rain' or 'sun'"; + return Captions.FLAG_ERROR_WEATHER.getTranslated(); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/StringFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/StringFlag.java index 36a68f66b..21f1690a6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/StringFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/StringFlag.java @@ -1,10 +1,11 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; public class StringFlag extends Flag { public StringFlag(String name) { - super(name); + super(Captions.FLAG_CATEGORY_STRING, name); } @Override public String valueToString(Object value) { @@ -16,6 +17,6 @@ public class StringFlag extends Flag { } @Override public String getValueDescription() { - return "Flag value must be alphanumeric. Some special characters are allowed."; + return Captions.FLAG_ERROR_STRING.getTranslated(); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/StringListFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/StringListFlag.java index 8f02a3801..eb76ec8c1 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/StringListFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/StringListFlag.java @@ -1,5 +1,6 @@ package com.github.intellectualsites.plotsquared.plot.flag; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.util.StringMan; import java.util.ArrayList; @@ -9,7 +10,7 @@ import java.util.List; public class StringListFlag extends ListFlag> { public StringListFlag(String name) { - super(name); + super(Captions.FLAG_CATEGORY_STRING_LIST, name); } @Override public String valueToString(Object value) { @@ -21,6 +22,6 @@ public class StringListFlag extends ListFlag> { } @Override public String getValueDescription() { - return "Flag value must be a string list"; + return Captions.FLAG_ERROR_STRINGLIST.getTranslated(); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/TeleportDenyFlag.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/TeleportDenyFlag.java index b24f14faf..6c02516fd 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/TeleportDenyFlag.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/flag/TeleportDenyFlag.java @@ -4,6 +4,7 @@ import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; public class TeleportDenyFlag extends EnumFlag { + public TeleportDenyFlag(String name) { super(name, "trusted", "members", "nonmembers", "nontrusted", "nonowners"); } @@ -22,14 +23,14 @@ public class TeleportDenyFlag extends EnumFlag { result = !plot.getMembers().contains(player.getUUID()); break; case "nonmembers": - result = !plot.isAdded(player.getUUID()); + result = plot.isAdded(player.getUUID()); break; case "nontrusted": - result = !plot.getTrusted().contains(player.getUUID()) && !plot + result = plot.getTrusted().contains(player.getUUID()) || plot .isOwner(player.getUUID()); break; case "nonowners": - result = !plot.isOwner(player.getUUID()); + result = plot.isOwner(player.getUUID()); break; default: return true; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/AugmentedUtils.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/AugmentedUtils.java index 1d18cbdcd..f1bf833b6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/AugmentedUtils.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/AugmentedUtils.java @@ -1,11 +1,19 @@ package com.github.intellectualsites.plotsquared.plot.generator; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; import com.github.intellectualsites.plotsquared.plot.util.block.DelegateLocalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.world.RegionUtil; +import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockTypes; +import org.jetbrains.annotations.NotNull; import java.util.Set; @@ -19,15 +27,15 @@ public class AugmentedUtils { enabled = true; } - public static boolean generate(final String world, final int cx, final int cz, + public static boolean generate(@NotNull final String world, final int chunkX, final int chunkZ, LocalBlockQueue queue) { if (!enabled) { return false; } - final int bx = cx << 4; - final int bz = cz << 4; - RegionWrapper region = new RegionWrapper(bx, bx + 15, bz, bz + 15); + final int blockX = chunkX << 4; + final int blockZ = chunkZ << 4; + CuboidRegion region = RegionUtil.createRegion(blockX, blockX + 15, blockZ, blockZ + 15); Set areas = PlotSquared.get().getPlotAreas(world, region); if (areas.isEmpty()) { return false; @@ -41,34 +49,31 @@ public class AugmentedUtils { continue; } IndependentPlotGenerator generator = area.getGenerator(); - if (generator == null) { - continue; - } // Mask if (queue == null) { queue = GlobalBlockQueue.IMP.getNewQueue(world, false); } LocalBlockQueue primaryMask; - // coords + // coordinates int bxx; int bzz; int txx; int tzz; // gen if (area.TYPE == 2) { - bxx = Math.max(0, area.getRegion().minX - bx); - bzz = Math.max(0, area.getRegion().minZ - bz); - txx = Math.min(15, area.getRegion().maxX - bx); - tzz = Math.min(15, area.getRegion().maxZ - bz); + bxx = Math.max(0, area.getRegion().getMinimumPoint().getX() - blockX); + bzz = Math.max(0, area.getRegion().getMinimumPoint().getZ() - blockZ); + txx = Math.min(15, area.getRegion().getMaximumPoint().getX() - blockX); + tzz = Math.min(15, area.getRegion().getMaximumPoint().getZ() - blockZ); primaryMask = new DelegateLocalBlockQueue(queue) { - @Override public boolean setBlock(int x, int y, int z, PlotBlock id) { + @Override public boolean setBlock(int x, int y, int z, BlockState id) { if (area.contains(x, z)) { return super.setBlock(x, y, z, id); } return false; } - @Override public boolean setBiome(int x, int z, String biome) { + @Override public boolean setBiome(int x, int z, BiomeType biome) { if (area.contains(x, z)) { return super.setBiome(x, z, biome); } @@ -81,16 +86,16 @@ public class AugmentedUtils { primaryMask = queue; } LocalBlockQueue secondaryMask; - PlotBlock air = StringPlotBlock.EVERYTHING; + BlockState air = BlockTypes.AIR.getDefaultState(); if (area.TERRAIN == 2) { PlotManager manager = area.getPlotManager(); final boolean[][] canPlace = new boolean[16][16]; boolean has = false; for (int x = bxx; x <= txx; x++) { for (int z = bzz; z <= tzz; z++) { - int rx = x + bx; - int rz = z + bz; - boolean can = manager.getPlotId(area, rx, 0, rz) == null; + int rx = x + blockX; + int rz = z + blockZ; + boolean can = manager.getPlotId(rx, 0, rz) == null; if (can) { for (int y = 1; y < 128; y++) { queue.setBlock(rx, y, rz, air); @@ -105,14 +110,14 @@ public class AugmentedUtils { } toReturn = true; secondaryMask = new DelegateLocalBlockQueue(primaryMask) { - @Override public boolean setBlock(int x, int y, int z, PlotBlock id) { - if (canPlace[x - bx][z - bz]) { + @Override public boolean setBlock(int x, int y, int z, BlockState id) { + if (canPlace[x - blockX][z - blockZ]) { return super.setBlock(x, y, z, id); } return false; } - @Override public boolean setBiome(int x, int y, String biome) { + @Override public boolean setBiome(int x, int y, BiomeType biome) { return super.setBiome(x, y, biome); } }; @@ -121,15 +126,15 @@ public class AugmentedUtils { for (int x = bxx; x <= txx; x++) { for (int z = bzz; z <= tzz; z++) { for (int y = 1; y < 128; y++) { - queue.setBlock(bx + x, y, bz + z, air); + queue.setBlock(blockX + x, y, blockZ + z, air); } } } toReturn = true; } - ScopedLocalBlockQueue scoped = - new ScopedLocalBlockQueue(secondaryMask, new Location(area.worldname, bx, 0, bz), - new Location(area.worldname, bx + 15, 255, bz + 15)); + ScopedLocalBlockQueue scoped = new ScopedLocalBlockQueue(secondaryMask, + new Location(area.worldname, blockX, 0, blockZ), + new Location(area.worldname, blockX + 15, 255, blockZ + 15)); generator.generateChunk(scoped, area); generator.populateChunk(scoped, area); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotManager.java index bd465a12f..b26e40c46 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotManager.java @@ -1,164 +1,163 @@ package com.github.intellectualsites.plotsquared.plot.generator; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.BlockBucket; +import com.github.intellectualsites.plotsquared.plot.object.Direction; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.world.BlockUtil; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.world.block.BlockTypes; import java.util.List; +import static com.github.intellectualsites.plotsquared.plot.util.world.PatternUtil.isAir; + /** * A plot manager with square plots which tessellate on a square grid with the following sections: ROAD, WALL, BORDER (wall), PLOT, FLOOR (plot). */ public class ClassicPlotManager extends SquarePlotManager { - @Override public boolean setComponent(PlotArea plotArea, PlotId plotId, String component, - BlockBucket blocks) { + private final ClassicPlotWorld classicPlotWorld; + + public ClassicPlotManager(ClassicPlotWorld classicPlotWorld) { + super(classicPlotWorld); + this.classicPlotWorld = classicPlotWorld; + } + + @Override public boolean setComponent(PlotId plotId, String component, + Pattern blocks) { switch (component) { case "floor": - setFloor(plotArea, plotId, blocks); - return true; + return setFloor(plotId, blocks); case "wall": - setWallFilling(plotArea, plotId, blocks); - return true; + return setWallFilling(plotId, blocks); case "all": - setAll(plotArea, plotId, blocks); - return true; + return setAll(plotId, blocks); case "air": - setAir(plotArea, plotId, blocks); - return true; + return setAir(plotId, blocks); case "main": - setMain(plotArea, plotId, blocks); - return true; + return setMain(plotId, blocks); case "middle": - setMiddle(plotArea, plotId, blocks); - return true; + return setMiddle(plotId, blocks); case "outline": - setOutline(plotArea, plotId, blocks); - return true; + return setOutline(plotId, blocks); case "border": - setWall(plotArea, plotId, blocks); - return true; + return setWall(plotId, blocks); } return false; } - @Override public boolean unClaimPlot(PlotArea plotArea, Plot plot, Runnable whenDone) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - setWallFilling(dpw, plot.getId(), dpw.WALL_FILLING); - setWall(dpw, plot.getId(), dpw.WALL_BLOCK); - GlobalBlockQueue.IMP.addTask(whenDone); - return true; + @Override public boolean unClaimPlot(Plot plot, Runnable whenDone) { + setWallFilling(plot.getId(), classicPlotWorld.WALL_FILLING.toPattern()); + if (!classicPlotWorld.WALL_BLOCK.isAir() || !classicPlotWorld.WALL_BLOCK.equals(classicPlotWorld.CLAIMED_WALL_BLOCK)) { + setWall(plot.getId(), classicPlotWorld.WALL_BLOCK.toPattern()); + } + return GlobalBlockQueue.IMP.addEmptyTask(whenDone); } - public boolean setFloor(PlotArea plotArea, PlotId plotId, BlockBucket blocks) { - Plot plot = plotArea.getPlotAbs(plotId); - LocalBlockQueue queue = plotArea.getQueue(false); + public boolean setFloor(PlotId plotId, Pattern blocks) { + Plot plot = classicPlotWorld.getPlotAbs(plotId); + LocalBlockQueue queue = classicPlotWorld.getQueue(false); if (plot.isBasePlot()) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - for (RegionWrapper region : plot.getRegions()) { + for (CuboidRegion region : plot.getRegions()) { Location pos1 = - new Location(plotArea.worldname, region.minX, dpw.PLOT_HEIGHT, region.minZ); + new Location(classicPlotWorld.worldname, region.getMinimumPoint().getX(), classicPlotWorld.PLOT_HEIGHT, region.getMinimumPoint().getZ()); Location pos2 = - new Location(plotArea.worldname, region.maxX, dpw.PLOT_HEIGHT, region.maxZ); + new Location(classicPlotWorld.worldname, region.getMaximumPoint().getX(), classicPlotWorld.PLOT_HEIGHT, region.getMaximumPoint().getZ()); queue.setCuboid(pos1, pos2, blocks); } } - queue.enqueue(); - return true; + return queue.enqueue(); } - public boolean setAll(PlotArea plotArea, PlotId plotId, BlockBucket blocks) { - Plot plot = plotArea.getPlotAbs(plotId); + public boolean setAll(PlotId plotId, Pattern blocks) { + Plot plot = classicPlotWorld.getPlotAbs(plotId); if (!plot.isBasePlot()) { return false; } - LocalBlockQueue queue = plotArea.getQueue(false); - int maxY = plotArea.getPlotManager().getWorldHeight(); - for (RegionWrapper region : plot.getRegions()) { - Location pos1 = new Location(plotArea.worldname, region.minX, 1, region.minZ); - Location pos2 = new Location(plotArea.worldname, region.maxX, maxY, region.maxZ); + LocalBlockQueue queue = classicPlotWorld.getQueue(false); + int maxY = getWorldHeight(); + for (CuboidRegion region : plot.getRegions()) { + Location pos1 = new Location(classicPlotWorld.worldname, region.getMinimumPoint().getX(), 1, region.getMinimumPoint().getZ()); + Location pos2 = new Location(classicPlotWorld.worldname, region.getMaximumPoint().getX(), maxY, region.getMaximumPoint().getZ()); queue.setCuboid(pos1, pos2, blocks); } - queue.enqueue(); - return true; + return queue.enqueue(); } - public boolean setAir(PlotArea plotArea, PlotId plotId, BlockBucket blocks) { - Plot plot = plotArea.getPlotAbs(plotId); + public boolean setAir(PlotId plotId, Pattern blocks) { + Plot plot = classicPlotWorld.getPlotAbs(plotId); if (!plot.isBasePlot()) { return false; } - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - LocalBlockQueue queue = plotArea.getQueue(false); - int maxY = plotArea.getPlotManager().getWorldHeight(); - for (RegionWrapper region : plot.getRegions()) { + LocalBlockQueue queue = classicPlotWorld.getQueue(false); + int maxY = getWorldHeight(); + for (CuboidRegion region : plot.getRegions()) { Location pos1 = - new Location(plotArea.worldname, region.minX, dpw.PLOT_HEIGHT + 1, region.minZ); - Location pos2 = new Location(plotArea.worldname, region.maxX, maxY, region.maxZ); + new Location(classicPlotWorld.worldname, region.getMinimumPoint().getX(), classicPlotWorld.PLOT_HEIGHT + 1, region.getMinimumPoint().getZ()); + Location pos2 = new Location(classicPlotWorld.worldname, region.getMaximumPoint().getX(), maxY, region.getMaximumPoint().getZ()); queue.setCuboid(pos1, pos2, blocks); } - queue.enqueue(); - return true; + return queue.enqueue(); } - public boolean setMain(PlotArea plotArea, PlotId plotId, BlockBucket blocks) { - Plot plot = plotArea.getPlotAbs(plotId); + public boolean setMain(PlotId plotId, Pattern blocks) { + Plot plot = classicPlotWorld.getPlotAbs(plotId); if (!plot.isBasePlot()) { return false; } - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - LocalBlockQueue queue = plotArea.getQueue(false); - for (RegionWrapper region : plot.getRegions()) { - Location pos1 = new Location(plotArea.worldname, region.minX, 1, region.minZ); + LocalBlockQueue queue = classicPlotWorld.getQueue(false); + for (CuboidRegion region : plot.getRegions()) { + Location pos1 = new Location(classicPlotWorld.worldname, region.getMinimumPoint().getX(), 1, region.getMinimumPoint().getZ()); Location pos2 = - new Location(plotArea.worldname, region.maxX, dpw.PLOT_HEIGHT - 1, region.maxZ); + new Location(classicPlotWorld.worldname, region.getMaximumPoint().getX(), classicPlotWorld.PLOT_HEIGHT - 1, region.getMaximumPoint().getZ()); queue.setCuboid(pos1, pos2, blocks); } - queue.enqueue(); - return true; + return queue.enqueue(); } - public boolean setMiddle(PlotArea plotArea, PlotId plotId, BlockBucket blocks) { - Plot plot = plotArea.getPlotAbs(plotId); + public boolean setMiddle(PlotId plotId, Pattern blocks) { + Plot plot = classicPlotWorld.getPlotAbs(plotId); if (!plot.isBasePlot()) { return false; } Location[] corners = plot.getCorners(); - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - LocalBlockQueue queue = plotArea.getQueue(false); + LocalBlockQueue queue = classicPlotWorld.getQueue(false); int x = MathMan.average(corners[0].getX(), corners[1].getX()); int z = MathMan.average(corners[0].getZ(), corners[1].getZ()); - queue.setBlock(x, dpw.PLOT_HEIGHT, z, blocks.getBlock()); - queue.enqueue(); - return true; + queue.setBlock(x, classicPlotWorld.PLOT_HEIGHT, z, blocks); + return queue.enqueue(); } - public boolean setOutline(PlotArea plotArea, PlotId plotId, BlockBucket blocks) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - if (dpw.ROAD_WIDTH == 0) { + public boolean setOutline(PlotId plotId, Pattern blocks) { + if (classicPlotWorld.ROAD_WIDTH == 0) { return false; } - Plot plot = plotArea.getPlotAbs(plotId); + Plot plot = classicPlotWorld.getPlotAbs(plotId); Location bottom = plot.getBottomAbs(); Location top = plot.getExtendedTopAbs(); - LocalBlockQueue queue = plotArea.getQueue(false); - int maxY = plotArea.getPlotManager().getWorldHeight(); + LocalBlockQueue queue = classicPlotWorld.getQueue(false); + int maxY = classicPlotWorld.getPlotManager().getWorldHeight(); if (!plot.getMerged(Direction.NORTH)) { int z = bottom.getZ(); for (int x = bottom.getX(); x <= top.getX(); x++) { - for (int y = dpw.PLOT_HEIGHT; y <= maxY; y++) { - queue.setBlock(x, y, z, blocks.getBlock()); + for (int y = classicPlotWorld.PLOT_HEIGHT; y <= maxY; y++) { + queue.setBlock(x, y, z, blocks); } } } if (!plot.getMerged(Direction.WEST)) { int x = bottom.getX(); for (int z = bottom.getZ(); z <= top.getZ(); z++) { - for (int y = dpw.PLOT_HEIGHT; y <= maxY; y++) { - queue.setBlock(x, y, z, blocks.getBlock()); + for (int y = classicPlotWorld.PLOT_HEIGHT; y <= maxY; y++) { + queue.setBlock(x, y, z, blocks); } } } @@ -166,54 +165,52 @@ public class ClassicPlotManager extends SquarePlotManager { if (!plot.getMerged(Direction.SOUTH)) { int z = top.getZ(); for (int x = bottom.getX(); x <= top.getX(); x++) { - for (int y = dpw.PLOT_HEIGHT; y <= maxY; y++) { - queue.setBlock(x, y, z, blocks.getBlock()); + for (int y = classicPlotWorld.PLOT_HEIGHT; y <= maxY; y++) { + queue.setBlock(x, y, z, blocks); } } } if (!plot.getMerged(Direction.EAST)) { int x = top.getX(); for (int z = bottom.getZ(); z <= top.getZ(); z++) { - for (int y = dpw.PLOT_HEIGHT; y <= maxY; y++) { - queue.setBlock(x, y, z, blocks.getBlock()); + for (int y = classicPlotWorld.PLOT_HEIGHT; y <= maxY; y++) { + queue.setBlock(x, y, z, blocks); } } } if (plot.isBasePlot()) { - for (RegionWrapper region : plot.getRegions()) { - Location pos1 = new Location(plotArea.worldname, region.minX, maxY, region.minZ); - Location pos2 = new Location(plotArea.worldname, region.maxX, maxY, region.maxZ); + for (CuboidRegion region : plot.getRegions()) { + Location pos1 = new Location(classicPlotWorld.worldname, region.getMinimumPoint().getX(), maxY, region.getMinimumPoint().getZ()); + Location pos2 = new Location(classicPlotWorld.worldname, region.getMaximumPoint().getX(), maxY, region.getMaximumPoint().getZ()); queue.setCuboid(pos1, pos2, blocks); } } - queue.enqueue(); - return true; + return queue.enqueue(); } - public boolean setWallFilling(PlotArea plotArea, PlotId plotId, BlockBucket blocks) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - if (dpw.ROAD_WIDTH == 0) { + public boolean setWallFilling(PlotId plotId, Pattern blocks) { + if (classicPlotWorld.ROAD_WIDTH == 0) { return false; } - Plot plot = plotArea.getPlotAbs(plotId); + Plot plot = classicPlotWorld.getPlotAbs(plotId); Location bot = plot.getExtendedBottomAbs() .subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1); - LocalBlockQueue queue = plotArea.getQueue(false); + LocalBlockQueue queue = classicPlotWorld.getQueue(false); if (!plot.getMerged(Direction.NORTH)) { int z = bot.getZ(); for (int x = bot.getX(); x < top.getX(); x++) { - for (int y = 1; y <= dpw.WALL_HEIGHT; y++) { - queue.setBlock(x, y, z, blocks.getBlock()); + for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) { + queue.setBlock(x, y, z, blocks); } } } if (!plot.getMerged(Direction.WEST)) { int x = bot.getX(); for (int z = bot.getZ(); z < top.getZ(); z++) { - for (int y = 1; y <= dpw.WALL_HEIGHT; y++) { - queue.setBlock(x, y, z, blocks.getBlock()); + for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) { + queue.setBlock(x, y, z, blocks); } } } @@ -221,8 +218,8 @@ public class ClassicPlotManager extends SquarePlotManager { int z = top.getZ(); for (int x = bot.getX(); x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) { - for (int y = 1; y <= dpw.WALL_HEIGHT; y++) { - queue.setBlock(x, y, z, blocks.getBlock()); + for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) { + queue.setBlock(x, y, z, blocks); } } } @@ -230,249 +227,247 @@ public class ClassicPlotManager extends SquarePlotManager { int x = top.getX(); for (int z = bot.getZ(); z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) { - for (int y = 1; y <= dpw.WALL_HEIGHT; y++) { - queue.setBlock(x, y, z, blocks.getBlock()); + for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) { + queue.setBlock(x, y, z, blocks); } } } - queue.enqueue(); - return true; + return queue.enqueue(); } - public boolean setWall(PlotArea plotArea, PlotId plotId, BlockBucket blocks) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - if (dpw.ROAD_WIDTH == 0) { + public boolean setWall(PlotId plotId, Pattern blocks) { + if (classicPlotWorld.ROAD_WIDTH == 0) { return false; } - Plot plot = plotArea.getPlotAbs(plotId); + Plot plot = classicPlotWorld.getPlotAbs(plotId); Location bot = plot.getExtendedBottomAbs() .subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1); - PseudoRandom random = new PseudoRandom(); - LocalBlockQueue queue = plotArea.getQueue(false); - int y = dpw.WALL_HEIGHT + 1; + LocalBlockQueue queue = classicPlotWorld.getQueue(false); + int y = classicPlotWorld.WALL_HEIGHT + 1; if (!plot.getMerged(Direction.NORTH)) { int z = bot.getZ(); for (int x = bot.getX(); x < top.getX(); x++) { - queue.setBlock(x, y, z, blocks.getBlock()); + queue.setBlock(x, y, z, blocks); } } if (!plot.getMerged(Direction.WEST)) { int x = bot.getX(); for (int z = bot.getZ(); z < top.getZ(); z++) { - queue.setBlock(x, y, z, blocks.getBlock()); + queue.setBlock(x, y, z, blocks); } } if (!plot.getMerged(Direction.SOUTH)) { int z = top.getZ(); for (int x = bot.getX(); x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) { - queue.setBlock(x, y, z, blocks.getBlock()); + queue.setBlock(x, y, z, blocks); } } if (!plot.getMerged(Direction.EAST)) { int x = top.getX(); for (int z = bot.getZ(); z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) { - queue.setBlock(x, y, z, blocks.getBlock()); + queue.setBlock(x, y, z, blocks); } } - queue.enqueue(); - return true; + return queue.enqueue(); } /** * PLOT MERGING. */ - @Override public boolean createRoadEast(PlotArea plotArea, Plot plot) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - Location pos1 = getPlotBottomLocAbs(plotArea, plot.getId()); - Location pos2 = getPlotTopLocAbs(plotArea, plot.getId()); + @Override public boolean createRoadEast(Plot plot) { + Location pos1 = getPlotBottomLocAbs(plot.getId()); + Location pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; - int ex = sx + dpw.ROAD_WIDTH - 1; + int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = pos1.getZ() - 2; int ez = pos2.getZ() + 2; - LocalBlockQueue queue = plotArea.getQueue(false); - int maxY = plotArea.getPlotManager().getWorldHeight(); + LocalBlockQueue queue = classicPlotWorld.getQueue(false); + int maxY = getWorldHeight(); queue.setCuboid( - new Location(plotArea.worldname, sx, Math.min(dpw.WALL_HEIGHT, dpw.ROAD_HEIGHT) + 1, - sz + 1), new Location(plotArea.worldname, ex, maxY, ez - 1), - PlotBlock.get((short) 0, (byte) 0)); - queue.setCuboid(new Location(plotArea.worldname, sx, 0, sz + 1), - new Location(plotArea.worldname, ex, 0, ez - 1), PlotBlock.get((short) 7, (byte) 0)); - queue.setCuboid(new Location(plotArea.worldname, sx, 1, sz + 1), - new Location(plotArea.worldname, sx, dpw.WALL_HEIGHT, ez - 1), dpw.WALL_FILLING); - queue.setCuboid(new Location(plotArea.worldname, sx, dpw.WALL_HEIGHT + 1, sz + 1), - new Location(plotArea.worldname, sx, dpw.WALL_HEIGHT + 1, ez - 1), dpw.WALL_BLOCK); - queue.setCuboid(new Location(plotArea.worldname, ex, 1, sz + 1), - new Location(plotArea.worldname, ex, dpw.WALL_HEIGHT, ez - 1), dpw.WALL_FILLING); - queue.setCuboid(new Location(plotArea.worldname, ex, dpw.WALL_HEIGHT + 1, sz + 1), - new Location(plotArea.worldname, ex, dpw.WALL_HEIGHT + 1, ez - 1), dpw.WALL_BLOCK); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, 1, sz + 1), - new Location(plotArea.worldname, ex - 1, dpw.ROAD_HEIGHT, ez - 1), dpw.ROAD_BLOCK); - queue.enqueue(); - return true; + new Location(classicPlotWorld.worldname, sx, Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, + sz + 1), new Location(classicPlotWorld.worldname, ex, maxY, ez - 1), + BlockTypes.AIR.getDefaultState()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx, 0, sz + 1), + new Location(classicPlotWorld.worldname, ex, 0, ez - 1), BlockUtil.get((short) 7, (byte) 0)); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx, 1, sz + 1), + new Location(classicPlotWorld.worldname, sx, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx, classicPlotWorld.WALL_HEIGHT + 1, sz + 1), + new Location(classicPlotWorld.worldname, sx, classicPlotWorld.WALL_HEIGHT + 1, ez - 1), classicPlotWorld.WALL_BLOCK.toPattern()); + queue.setCuboid(new Location(classicPlotWorld.worldname, ex, 1, sz + 1), + new Location(classicPlotWorld.worldname, ex, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(new Location(classicPlotWorld.worldname, ex, classicPlotWorld.WALL_HEIGHT + 1, sz + 1), + new Location(classicPlotWorld.worldname, ex, classicPlotWorld.WALL_HEIGHT + 1, ez - 1), classicPlotWorld.WALL_BLOCK.toPattern()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, 1, sz + 1), + new Location(classicPlotWorld.worldname, ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); + return queue.enqueue(); } - @Override public boolean createRoadSouth(PlotArea plotArea, Plot plot) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - Location pos1 = getPlotBottomLocAbs(plotArea, plot.getId()); - Location pos2 = getPlotTopLocAbs(plotArea, plot.getId()); + @Override public boolean createRoadSouth(Plot plot) { + Location pos1 = getPlotBottomLocAbs(plot.getId()); + Location pos2 = getPlotTopLocAbs(plot.getId()); int sz = pos2.getZ() + 1; - int ez = sz + dpw.ROAD_WIDTH - 1; + int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; int sx = pos1.getX() - 2; int ex = pos2.getX() + 2; - LocalBlockQueue queue = plotArea.getQueue(false); + LocalBlockQueue queue = classicPlotWorld.getQueue(false); queue.setCuboid( - new Location(plotArea.worldname, sx + 1, Math.min(dpw.WALL_HEIGHT, dpw.ROAD_HEIGHT) + 1, + new Location(classicPlotWorld.worldname, sx + 1, Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), - new Location(plotArea.worldname, ex - 1, plotArea.getPlotManager().getWorldHeight(), - ez), PlotBlock.get((short) 0, (byte) 0)); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, 0, sz), - new Location(plotArea.worldname, ex - 1, 0, ez), PlotBlock.get((short) 7, (byte) 0)); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, 1, sz), - new Location(plotArea.worldname, ex - 1, dpw.WALL_HEIGHT, sz), dpw.WALL_FILLING); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, dpw.WALL_HEIGHT + 1, sz), - new Location(plotArea.worldname, ex - 1, dpw.WALL_HEIGHT + 1, sz), dpw.WALL_BLOCK); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, 1, ez), - new Location(plotArea.worldname, ex - 1, dpw.WALL_HEIGHT, ez), dpw.WALL_FILLING); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, dpw.WALL_HEIGHT + 1, ez), - new Location(plotArea.worldname, ex - 1, dpw.WALL_HEIGHT + 1, ez), dpw.WALL_BLOCK); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, 1, sz + 1), - new Location(plotArea.worldname, ex - 1, dpw.ROAD_HEIGHT, ez - 1), dpw.ROAD_BLOCK); - queue.enqueue(); - return true; + new Location(classicPlotWorld.worldname, ex - 1, classicPlotWorld.getPlotManager().getWorldHeight(), + ez), BlockTypes.AIR.getDefaultState()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, 0, sz), + new Location(classicPlotWorld.worldname, ex - 1, 0, ez), BlockUtil.get((short) 7, (byte) 0)); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, 1, sz), + new Location(classicPlotWorld.worldname, ex - 1, classicPlotWorld.WALL_HEIGHT, sz), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, classicPlotWorld.WALL_HEIGHT + 1, sz), + new Location(classicPlotWorld.worldname, ex - 1, classicPlotWorld.WALL_HEIGHT + 1, sz), classicPlotWorld.WALL_BLOCK.toPattern()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, 1, ez), + new Location(classicPlotWorld.worldname, ex - 1, classicPlotWorld.WALL_HEIGHT, ez), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, classicPlotWorld.WALL_HEIGHT + 1, ez), + new Location(classicPlotWorld.worldname, ex - 1, classicPlotWorld.WALL_HEIGHT + 1, ez), classicPlotWorld.WALL_BLOCK.toPattern()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, 1, sz + 1), + new Location(classicPlotWorld.worldname, ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); + return queue.enqueue(); } - @Override public boolean createRoadSouthEast(PlotArea plotArea, Plot plot) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - Location pos2 = getPlotTopLocAbs(plotArea, plot.getId()); + @Override public boolean createRoadSouthEast(Plot plot) { + Location pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; - int ex = sx + dpw.ROAD_WIDTH - 1; + int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = pos2.getZ() + 1; - int ez = sz + dpw.ROAD_WIDTH - 1; - LocalBlockQueue queue = plotArea.getQueue(false); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, dpw.ROAD_HEIGHT + 1, sz + 1), - new Location(plotArea.worldname, ex - 1, dpw.getPlotManager().getWorldHeight(), ez - 1), - PlotBlock.get((short) 0, (byte) 0)); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, 0, sz + 1), - new Location(plotArea.worldname, ex - 1, 0, ez - 1), - PlotBlock.get((short) 7, (byte) 0)); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, 1, sz + 1), - new Location(plotArea.worldname, ex - 1, dpw.ROAD_HEIGHT, ez - 1), dpw.ROAD_BLOCK); - queue.enqueue(); - return true; + int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; + LocalBlockQueue queue = classicPlotWorld.getQueue(false); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, classicPlotWorld.ROAD_HEIGHT + 1, sz + 1), + new Location(classicPlotWorld.worldname, ex - 1, classicPlotWorld.getPlotManager().getWorldHeight(), ez - 1), + BlockTypes.AIR.getDefaultState()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, 0, sz + 1), + new Location(classicPlotWorld.worldname, ex - 1, 0, ez - 1), + BlockUtil.get((short) 7, (byte) 0)); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, 1, sz + 1), + new Location(classicPlotWorld.worldname, ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); + return queue.enqueue(); } - @Override public boolean removeRoadEast(PlotArea plotArea, Plot plot) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - Location pos1 = getPlotBottomLocAbs(plotArea, plot.getId()); - Location pos2 = getPlotTopLocAbs(plotArea, plot.getId()); + @Override public boolean removeRoadEast(Plot plot) { + Location pos1 = getPlotBottomLocAbs(plot.getId()); + Location pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; - int ex = sx + dpw.ROAD_WIDTH - 1; + int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = pos1.getZ() - 1; int ez = pos2.getZ() + 1; - LocalBlockQueue queue = plotArea.getQueue(false); + LocalBlockQueue queue = classicPlotWorld.getQueue(false); queue.setCuboid( - new Location(plotArea.worldname, sx, Math.min(dpw.PLOT_HEIGHT, dpw.ROAD_HEIGHT) + 1, + new Location(classicPlotWorld.worldname, sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), - new Location(plotArea.worldname, ex, plotArea.getPlotManager().getWorldHeight(), ez), - PlotBlock.get((short) 0, (byte) 0)); - queue.setCuboid(new Location(plotArea.worldname, sx, 1, sz + 1), - new Location(plotArea.worldname, ex, dpw.PLOT_HEIGHT - 1, ez - 1), dpw.MAIN_BLOCK); - queue.setCuboid(new Location(plotArea.worldname, sx, dpw.PLOT_HEIGHT, sz + 1), - new Location(plotArea.worldname, ex, dpw.PLOT_HEIGHT, ez - 1), dpw.TOP_BLOCK); - queue.enqueue(); - return true; + new Location(classicPlotWorld.worldname, ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez), BlockTypes.AIR.getDefaultState()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx, 1, sz + 1), + new Location(classicPlotWorld.worldname, ex, classicPlotWorld.PLOT_HEIGHT - 1, ez - 1), classicPlotWorld.MAIN_BLOCK.toPattern()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx, classicPlotWorld.PLOT_HEIGHT, sz + 1), + new Location(classicPlotWorld.worldname, ex, classicPlotWorld.PLOT_HEIGHT, ez - 1), classicPlotWorld.TOP_BLOCK.toPattern()); + return queue.enqueue(); } - @Override public boolean removeRoadSouth(PlotArea plotArea, Plot plot) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - Location pos1 = getPlotBottomLocAbs(plotArea, plot.getId()); - Location pos2 = getPlotTopLocAbs(plotArea, plot.getId()); + @Override public boolean removeRoadSouth(Plot plot) { + Location pos1 = getPlotBottomLocAbs(plot.getId()); + Location pos2 = getPlotTopLocAbs(plot.getId()); int sz = pos2.getZ() + 1; - int ez = sz + dpw.ROAD_WIDTH - 1; + int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; int sx = pos1.getX() - 1; int ex = pos2.getX() + 1; - LocalBlockQueue queue = plotArea.getQueue(false); + LocalBlockQueue queue = classicPlotWorld.getQueue(false); queue.setCuboid( - new Location(plotArea.worldname, sx, Math.min(dpw.PLOT_HEIGHT, dpw.ROAD_HEIGHT) + 1, + new Location(classicPlotWorld.worldname, sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), - new Location(plotArea.worldname, ex, plotArea.getPlotManager().getWorldHeight(), ez), - PlotBlock.get((short) 0, (byte) 0)); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, 1, sz), - new Location(plotArea.worldname, ex - 1, dpw.PLOT_HEIGHT - 1, ez), dpw.MAIN_BLOCK); - queue.setCuboid(new Location(plotArea.worldname, sx + 1, dpw.PLOT_HEIGHT, sz), - new Location(plotArea.worldname, ex - 1, dpw.PLOT_HEIGHT, ez), dpw.TOP_BLOCK); - queue.enqueue(); - return true; + new Location(classicPlotWorld.worldname, ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez), + BlockTypes.AIR.getDefaultState()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, 1, sz), + new Location(classicPlotWorld.worldname, ex - 1, classicPlotWorld.PLOT_HEIGHT - 1, ez), classicPlotWorld.MAIN_BLOCK.toPattern()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx + 1, classicPlotWorld.PLOT_HEIGHT, sz), + new Location(classicPlotWorld.worldname, ex - 1, classicPlotWorld.PLOT_HEIGHT, ez), classicPlotWorld.TOP_BLOCK.toPattern()); + return queue.enqueue(); } - @Override public boolean removeRoadSouthEast(PlotArea plotArea, Plot plot) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; - Location location = getPlotTopLocAbs(dpw, plot.getId()); + @Override public boolean removeRoadSouthEast(Plot plot) { + Location location = getPlotTopLocAbs(plot.getId()); int sx = location.getX() + 1; - int ex = sx + dpw.ROAD_WIDTH - 1; + int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = location.getZ() + 1; - int ez = sz + dpw.ROAD_WIDTH - 1; - LocalBlockQueue queue = plotArea.getQueue(false); - queue.setCuboid(new Location(plotArea.worldname, sx, dpw.ROAD_HEIGHT + 1, sz), - new Location(plotArea.worldname, ex, plotArea.getPlotManager().getWorldHeight(), ez), - PlotBlock.get((short) 0, (byte) 0)); - queue.setCuboid(new Location(plotArea.worldname, sx, 1, sz), - new Location(plotArea.worldname, ex, dpw.ROAD_HEIGHT - 1, ez), dpw.MAIN_BLOCK); - queue.setCuboid(new Location(plotArea.worldname, sx, dpw.ROAD_HEIGHT, sz), - new Location(plotArea.worldname, ex, dpw.ROAD_HEIGHT, ez), dpw.TOP_BLOCK); - queue.enqueue(); - return true; + int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; + LocalBlockQueue queue = classicPlotWorld.getQueue(false); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx, classicPlotWorld.ROAD_HEIGHT + 1, sz), + new Location(classicPlotWorld.worldname, ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez), + BlockTypes.AIR.getDefaultState()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx, 1, sz), + new Location(classicPlotWorld.worldname, ex, classicPlotWorld.ROAD_HEIGHT - 1, ez), classicPlotWorld.MAIN_BLOCK.toPattern()); + queue.setCuboid(new Location(classicPlotWorld.worldname, sx, classicPlotWorld.ROAD_HEIGHT, sz), + new Location(classicPlotWorld.worldname, ex, classicPlotWorld.ROAD_HEIGHT, ez), classicPlotWorld.TOP_BLOCK.toPattern()); + return queue.enqueue(); } /** * Finishing off plot merging by adding in the walls surrounding the plot (OPTIONAL)(UNFINISHED). + * + * @return false if part of the merge failed, otherwise true if successful. */ - @Override public boolean finishPlotMerge(PlotArea plotArea, List plotIds) { - final BlockBucket block = ((ClassicPlotWorld) plotArea).CLAIMED_WALL_BLOCK; - plotIds.forEach(id -> setWall(plotArea, id, block)); + @Override public boolean finishPlotMerge(List plotIds) { + final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; + if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { + for (PlotId plotId : plotIds) { + setWall(plotId, claim.toPattern()); + } + } if (Settings.General.MERGE_REPLACE_WALL) { - final BlockBucket wallBlock = ((ClassicPlotWorld) plotArea).WALL_FILLING; - plotIds.forEach(id -> setWallFilling(plotArea, id, wallBlock)); + final BlockBucket wallBlock = classicPlotWorld.WALL_FILLING; + for (PlotId id : plotIds) { + setWallFilling(id, wallBlock.toPattern()); + } } return true; } - @Override public boolean finishPlotUnlink(PlotArea plotArea, List plotIds) { - final BlockBucket block = ((ClassicPlotWorld) plotArea).CLAIMED_WALL_BLOCK; - plotIds.forEach(id -> setWall(plotArea, id, block)); + @Override public boolean finishPlotUnlink(List plotIds) { + final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; + if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { + for (PlotId id : plotIds) { + setWall(id, claim.toPattern()); + } + } + return true; // return false if unlink has been denied + } + + @Override public boolean startPlotMerge(List plotIds) { return true; } - @Override public boolean startPlotMerge(PlotArea plotArea, List plotIds) { + @Override public boolean startPlotUnlink(List plotIds) { return true; } - @Override public boolean startPlotUnlink(PlotArea plotArea, List plotIds) { + @Override public boolean claimPlot(Plot plot) { + final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; + if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { + return setWall(plot.getId(), claim.toPattern()); + } return true; } - @Override public boolean claimPlot(PlotArea plotArea, Plot plot) { - final BlockBucket claim = ((ClassicPlotWorld) plotArea).CLAIMED_WALL_BLOCK; - setWall(plotArea, plot.getId(), claim); - return true; - } - - @Override public String[] getPlotComponents(PlotArea plotArea, PlotId plotId) { + @Override public String[] getPlotComponents(PlotId plotId) { return new String[] {"main", "floor", "air", "all", "border", "wall", "outline", "middle"}; } /** - * Remove sign for a plot. + * Retrieves the location of where a sign should be for a plot. + * @param plot The plot + * @return The location where a sign should be */ - @Override public Location getSignLoc(PlotArea plotArea, Plot plot) { - ClassicPlotWorld dpw = (ClassicPlotWorld) plotArea; + @Override public Location getSignLoc(Plot plot) { plot = plot.getBasePlot(false); Location bot = plot.getBottomAbs(); - return new Location(plotArea.worldname, bot.getX() - 1, dpw.ROAD_HEIGHT + 1, + return new Location(classicPlotWorld.worldname, bot.getX() - 1, classicPlotWorld.ROAD_HEIGHT + 1, bot.getZ() - 2); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotWorld.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotWorld.java index 755f694d6..00ec5dd7f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotWorld.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/ClassicPlotWorld.java @@ -6,10 +6,13 @@ import com.github.intellectualsites.plotsquared.plot.config.Configuration; import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.BlockBucket; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.util.world.BlockUtil; +import com.sk89q.worldedit.function.pattern.BlockPattern; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.world.block.BlockTypes; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.lang.reflect.Field; import java.util.Locale; @@ -18,21 +21,22 @@ import java.util.Locale; public int ROAD_HEIGHT = 62; public int PLOT_HEIGHT = 62; public int WALL_HEIGHT = 62; - public BlockBucket MAIN_BLOCK = BlockBucket.withSingle(PlotBlock.get("stone")); - // new PlotBlock[] {PlotBlock.get("stone")}; - public BlockBucket TOP_BLOCK = BlockBucket.withSingle(PlotBlock.get("grass_block")); - //new PlotBlock[] {PlotBlock.get("grass")}; - public BlockBucket WALL_BLOCK = BlockBucket.withSingle(PlotBlock.get("stone_slab")); - // PlotBlock.get((short) 44, (byte) 0); - public BlockBucket CLAIMED_WALL_BLOCK = BlockBucket.withSingle(PlotBlock.get("sandstone_slab")); - // PlotBlock.get((short) 44, (byte) 1); - public BlockBucket WALL_FILLING = BlockBucket.withSingle(PlotBlock.get("stone")); - //PlotBlock.get((short) 1, (byte) 0); - public BlockBucket ROAD_BLOCK = BlockBucket.withSingle(PlotBlock.get("quartz_block")); - // PlotBlock.get((short) 155, (byte) 0); + public BlockBucket MAIN_BLOCK = new BlockBucket(BlockTypes.STONE); + // new BlockState[] {BlockUtil.get("stone")}; + public BlockBucket TOP_BLOCK = new BlockBucket(BlockTypes.GRASS_BLOCK); + //new BlockState[] {BlockUtil.get("grass")}; + public BlockBucket WALL_BLOCK = new BlockBucket(BlockTypes.STONE_SLAB); + // BlockUtil.get((short) 44, (byte) 0); + public BlockBucket CLAIMED_WALL_BLOCK = new BlockBucket(BlockTypes.SANDSTONE_SLAB); + // BlockUtil.get((short) 44, (byte) 1); + public BlockBucket WALL_FILLING = new BlockBucket(BlockTypes.STONE); + //BlockUtil.get((short) 1, (byte) 0); + public BlockBucket ROAD_BLOCK = new BlockBucket(BlockTypes.QUARTZ_BLOCK); + // BlockUtil.get((short) 155, (byte) 0); public boolean PLOT_BEDROCK = true; - public ClassicPlotWorld(String worldName, String id, IndependentPlotGenerator generator, + public ClassicPlotWorld(String worldName, String id, + @NotNull IndependentPlotGenerator generator, PlotId min, PlotId max) { super(worldName, id, generator, min, max); } @@ -44,7 +48,7 @@ import java.util.Locale; * command - this may be useful if a config value can be changed at a later date, and has no impact on the actual * world generation

*/ - @Nonnull @Override public ConfigurationNode[] getSettingNodes() { + @NotNull @Override public ConfigurationNode[] getSettingNodes() { return new ConfigurationNode[] { new ConfigurationNode("plot.height", this.PLOT_HEIGHT, "Plot height", Configuration.INTEGER), @@ -80,16 +84,16 @@ import java.util.Locale; super.loadConfiguration(config); this.PLOT_BEDROCK = config.getBoolean("plot.bedrock"); this.PLOT_HEIGHT = Math.min(255, config.getInt("plot.height")); - this.MAIN_BLOCK = Configuration.BLOCK_BUCKET.parseString(config.getString("plot.filling")); - this.TOP_BLOCK = Configuration.BLOCK_BUCKET.parseString(config.getString("plot.floor")); - this.WALL_BLOCK = Configuration.BLOCK_BUCKET.parseString(config.getString("wall.block")); + this.MAIN_BLOCK = new BlockBucket(config.getString("plot.filling")); + this.TOP_BLOCK = new BlockBucket(config.getString("plot.floor")); + this.WALL_BLOCK = new BlockBucket(config.getString("wall.block")); this.ROAD_HEIGHT = Math.min(255, config.getInt("road.height")); - this.ROAD_BLOCK = Configuration.BLOCK_BUCKET.parseString(config.getString("road.block")); + this.ROAD_BLOCK = new BlockBucket(config.getString("road.block")); this.WALL_FILLING = - Configuration.BLOCK_BUCKET.parseString(config.getString("wall.filling")); + new BlockBucket(config.getString("wall.filling")); this.WALL_HEIGHT = Math.min(254, config.getInt("wall.height")); this.CLAIMED_WALL_BLOCK = - Configuration.BLOCK_BUCKET.parseString(config.getString("wall.block_claimed")); + new BlockBucket(config.getString("wall.block_claimed")); // Dump world settings if (Settings.DEBUG) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/GridPlotManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/GridPlotManager.java index 4ea841c3c..a0ed41226 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/GridPlotManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/GridPlotManager.java @@ -1,10 +1,13 @@ package com.github.intellectualsites.plotsquared.plot.generator; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; import com.github.intellectualsites.plotsquared.plot.object.PlotManager; /** * A plot manager where plots tessellate in a grid formation symmetrical about x=z. */ public abstract class GridPlotManager extends PlotManager { - + public GridPlotManager(PlotArea plotArea) { + super(plotArea); + } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/GridPlotWorld.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/GridPlotWorld.java index 34dbef203..b0cc10323 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/GridPlotWorld.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/GridPlotWorld.java @@ -2,12 +2,13 @@ package com.github.intellectualsites.plotsquared.plot.generator; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import org.jetbrains.annotations.NotNull; public abstract class GridPlotWorld extends PlotArea { public short SIZE; - public GridPlotWorld(String worldName, String id, IndependentPlotGenerator generator, + public GridPlotWorld(String worldName, String id, @NotNull IndependentPlotGenerator generator, PlotId min, PlotId max) { super(worldName, id, generator, min, max); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridGen.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridGen.java index 66a32db4c..7fbf5c0ae 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridGen.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridGen.java @@ -2,10 +2,13 @@ package com.github.intellectualsites.plotsquared.plot.generator; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockTypes; public class HybridGen extends IndependentPlotGenerator { @@ -31,37 +34,6 @@ public class HybridGen extends IndependentPlotGenerator { } } - @Override public BlockBucket[][] generateBlockBucketChunk(PlotArea settings) { - BlockBucket[][] blockBuckets = new BlockBucket[16][]; - HybridPlotWorld hpw = (HybridPlotWorld) settings; - // Bedrock - if (hpw.PLOT_BEDROCK) { - for (short x = 0; x < 16; x++) { - for (short z = 0; z < 16; z++) { - blockBuckets[0][(z << 4) | x] = - BlockBucket.withSingle(PlotBlock.get("bedrock")); - } - } - } - for (short x = 0; x < 16; x++) { - for (short z = 0; z < 16; z++) { - for (int y = 1; y < hpw.PLOT_HEIGHT; y++) { - int layer = y >> 4; - if (blockBuckets[layer] == null) { - blockBuckets[layer] = new BlockBucket[4096]; - } - blockBuckets[layer][((y & 0xF) << 8) | (z << 4) | x] = hpw.MAIN_BLOCK; - } - int layer = hpw.PLOT_HEIGHT >> 4; - if (blockBuckets[layer] == null) { - blockBuckets[layer] = new BlockBucket[4096]; - } - blockBuckets[layer][((hpw.PLOT_HEIGHT & 0xF) << 8) | (z << 4) | x] = hpw.MAIN_BLOCK; - } - } - return blockBuckets; - } - @Override public void generateChunk(ScopedLocalBlockQueue result, PlotArea settings) { HybridPlotWorld hpw = (HybridPlotWorld) settings; // Biome @@ -70,7 +42,7 @@ public class HybridGen extends IndependentPlotGenerator { if (hpw.PLOT_BEDROCK) { for (short x = 0; x < 16; x++) { for (short z = 0; z < 16; z++) { - result.setBlock(x, 0, z, PlotBlock.get("bedrock")); + result.setBlock(x, 0, z, BlockTypes.BEDROCK.getDefaultState()); } } } @@ -124,7 +96,7 @@ public class HybridGen extends IndependentPlotGenerator { for (short z = 0; z < 16; z++) { // Road for (int y = 1; y <= hpw.ROAD_HEIGHT; y++) { - result.setBlock(x, y, z, hpw.ROAD_BLOCK.getBlock()); + result.setBlock(x, y, z, hpw.ROAD_BLOCK.toPattern()); } if (hpw.ROAD_SCHEMATIC_ENABLED) { placeSchem(hpw, result, rx[x], rz[z], x, z, true); @@ -135,7 +107,7 @@ public class HybridGen extends IndependentPlotGenerator { if (gz[z]) { // road for (int y = 1; y <= hpw.ROAD_HEIGHT; y++) { - result.setBlock(x, y, z, hpw.ROAD_BLOCK.getBlock()); + result.setBlock(x, y, z, hpw.ROAD_BLOCK.toPattern()); } if (hpw.ROAD_SCHEMATIC_ENABLED) { placeSchem(hpw, result, rx[x], rz[z], x, z, true); @@ -143,10 +115,10 @@ public class HybridGen extends IndependentPlotGenerator { } else { // wall for (int y = 1; y <= hpw.WALL_HEIGHT; y++) { - result.setBlock(x, y, z, hpw.WALL_FILLING.getBlock()); + result.setBlock(x, y, z, hpw.WALL_FILLING.toPattern()); } if (!hpw.ROAD_SCHEMATIC_ENABLED) { - result.setBlock(x, hpw.WALL_HEIGHT + 1, z, hpw.WALL_BLOCK.getBlock()); + result.setBlock(x, hpw.WALL_HEIGHT + 1, z, hpw.WALL_BLOCK.toPattern()); } else { placeSchem(hpw, result, rx[x], rz[z], x, z, true); } @@ -157,7 +129,7 @@ public class HybridGen extends IndependentPlotGenerator { if (gz[z]) { // road for (int y = 1; y <= hpw.ROAD_HEIGHT; y++) { - result.setBlock(x, y, z, hpw.ROAD_BLOCK.getBlock()); + result.setBlock(x, y, z, hpw.ROAD_BLOCK.toPattern()); } if (hpw.ROAD_SCHEMATIC_ENABLED) { placeSchem(hpw, result, rx[x], rz[z], x, z, true); @@ -165,19 +137,19 @@ public class HybridGen extends IndependentPlotGenerator { } else if (wz[z]) { // wall for (int y = 1; y <= hpw.WALL_HEIGHT; y++) { - result.setBlock(x, y, z, hpw.WALL_FILLING.getBlock()); + result.setBlock(x, y, z, hpw.WALL_FILLING.toPattern()); } if (!hpw.ROAD_SCHEMATIC_ENABLED) { - result.setBlock(x, hpw.WALL_HEIGHT + 1, z, hpw.WALL_BLOCK.getBlock()); + result.setBlock(x, hpw.WALL_HEIGHT + 1, z, hpw.WALL_BLOCK.toPattern()); } else { placeSchem(hpw, result, rx[x], rz[z], x, z, true); } } else { // plot for (int y = 1; y < hpw.PLOT_HEIGHT; y++) { - result.setBlock(x, y, z, hpw.MAIN_BLOCK.getBlock()); + result.setBlock(x, y, z, hpw.MAIN_BLOCK.toPattern()); } - result.setBlock(x, hpw.PLOT_HEIGHT, z, hpw.TOP_BLOCK.getBlock()); + result.setBlock(x, hpw.PLOT_HEIGHT, z, hpw.TOP_BLOCK.toPattern()); if (hpw.PLOT_SCHEMATIC) { placeSchem(hpw, result, rx[x], rz[z], x, z, false); } @@ -253,10 +225,6 @@ public class HybridGen extends IndependentPlotGenerator { return new HybridPlotWorld(world, id, this, min, max); } - @Override public PlotManager getNewPlotManager() { - return new HybridPlotManager(); - } - @Override public void initialize(PlotArea area) { // All initialization is done in the PlotArea class } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotManager.java index 4796e3644..e6c165029 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotManager.java @@ -3,12 +3,9 @@ package com.github.intellectualsites.plotsquared.plot.generator; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.commands.Template; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.BlockBucket; import com.github.intellectualsites.plotsquared.plot.object.FileBytes; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; -import com.github.intellectualsites.plotsquared.plot.object.PlotArea; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.object.PlotId; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; @@ -16,8 +13,14 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.world.BlockUtil; import com.google.common.collect.Sets; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockTypes; + import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -27,23 +30,29 @@ public class HybridPlotManager extends ClassicPlotManager { public static boolean REGENERATIVE_CLEAR = true; - @Override public void exportTemplate(PlotArea plotArea) throws IOException { + private final HybridPlotWorld hybridPlotWorld; + + public HybridPlotManager(HybridPlotWorld hybridPlotWorld) { + super(hybridPlotWorld); + this.hybridPlotWorld = hybridPlotWorld; + } + + @Override public void exportTemplate() throws IOException { HashSet files = Sets.newHashSet( - new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", Template.getBytes(plotArea))); + new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", Template.getBytes(hybridPlotWorld))); String dir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator - + plotArea.worldname + File.separator; - String newDir = - "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + "__TEMP_DIR__" - + File.separator; + + hybridPlotWorld.worldname + File.separator; try { - File sideroad = + File sideRoad = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), dir + "sideroad.schem"); - if (sideroad.exists()) { + String newDir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + + "__TEMP_DIR__" + File.separator; + if (sideRoad.exists()) { files.add(new FileBytes(newDir + "sideroad.schem", - Files.readAllBytes(sideroad.toPath()))); + Files.readAllBytes(sideRoad.toPath()))); } File intersection = - MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), "intersection.schem"); + MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), dir + "intersection.schem"); if (intersection.exists()) { files.add(new FileBytes(newDir + "intersection.schem", Files.readAllBytes(intersection.toPath()))); @@ -55,54 +64,57 @@ public class HybridPlotManager extends ClassicPlotManager { } catch (IOException e) { e.printStackTrace(); } - Template.zipAll(plotArea.worldname, files); + Template.zipAll(hybridPlotWorld.worldname, files); } - @Override public boolean createRoadEast(PlotArea plotArea, Plot plot) { - super.createRoadEast(plotArea, plot); - HybridPlotWorld hpw = (HybridPlotWorld) plotArea; + @Override public boolean createRoadEast(Plot plot) { + super.createRoadEast(plot); PlotId id = plot.getId(); PlotId id2 = new PlotId(id.x + 1, id.y); - Location bot = getPlotBottomLocAbs(hpw, id2); - Location top = getPlotTopLocAbs(hpw, id); - Location pos1 = new Location(plotArea.worldname, top.getX() + 1, 0, bot.getZ() - 1); + Location bot = getPlotBottomLocAbs(id2); + Location top = getPlotTopLocAbs(id); + Location pos1 = new Location(hybridPlotWorld.worldname, top.getX() + 1, 0, bot.getZ() - 1); Location pos2 = - new Location(plotArea.worldname, bot.getX(), Math.min(getWorldHeight(), 255), + new Location(hybridPlotWorld.worldname, bot.getX(), Math.min(getWorldHeight(), 255), top.getZ() + 1); - MainUtil.resetBiome(plotArea, pos1, pos2); - if (!hpw.ROAD_SCHEMATIC_ENABLED) { + MainUtil.resetBiome(hybridPlotWorld, pos1, pos2); + if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; } - LocalBlockQueue queue = hpw.getQueue(false); - createSchemAbs(hpw, queue, pos1, pos2, true); + LocalBlockQueue queue = hybridPlotWorld.getQueue(false); + createSchemAbs(queue, pos1, pos2); queue.enqueue(); return true; } - private void createSchemAbs(HybridPlotWorld hpw, LocalBlockQueue queue, Location pos1, - Location pos2, boolean clear) { - int size = hpw.SIZE; + private void createSchemAbs(LocalBlockQueue queue, Location pos1, + Location pos2) { + int size = hybridPlotWorld.SIZE; int minY; if (Settings.Schematics.PASTE_ON_TOP) { - minY = hpw.SCHEM_Y; + minY = hybridPlotWorld.SCHEM_Y; } else { minY = 1; } + BaseBlock airBlock = BlockTypes.AIR.getDefaultState().toBaseBlock(); for (int x = pos1.getX(); x <= pos2.getX(); x++) { - short absX = (short) ((x - hpw.ROAD_OFFSET_X) % size); + short absX = (short) ((x - hybridPlotWorld.ROAD_OFFSET_X) % size); if (absX < 0) { absX += size; } for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { - short absZ = (short) ((z - hpw.ROAD_OFFSET_Z) % size); + short absZ = (short) ((z - hybridPlotWorld.ROAD_OFFSET_Z) % size); if (absZ < 0) { absZ += size; } - BaseBlock[] blocks = hpw.G_SCH.get(MathMan.pair(absX, absZ)); + BaseBlock[] blocks = hybridPlotWorld.G_SCH.get(MathMan.pair(absX, absZ)); if (blocks != null) { for (int y = 0; y < blocks.length; y++) { if (blocks[y] != null) { queue.setBlock(x, minY + y, z, blocks[y]); + } else { + // This is necessary, otherwise any blocks not specified in the schematic will remain after a clear + queue.setBlock(x, minY + y, z, airBlock); } } } @@ -110,43 +122,40 @@ public class HybridPlotManager extends ClassicPlotManager { } } - @Override public boolean createRoadSouth(PlotArea plotArea, Plot plot) { - super.createRoadSouth(plotArea, plot); - HybridPlotWorld hpw = (HybridPlotWorld) plotArea; + @Override public boolean createRoadSouth(Plot plot) { + super.createRoadSouth(plot); PlotId id = plot.getId(); PlotId id2 = new PlotId(id.x, id.y + 1); - Location bot = getPlotBottomLocAbs(hpw, id2); - Location top = getPlotTopLocAbs(hpw, id); - Location pos1 = new Location(plotArea.worldname, bot.getX() - 1, 0, top.getZ() + 1); + Location bot = getPlotBottomLocAbs(id2); + Location top = getPlotTopLocAbs(id); + Location pos1 = new Location(hybridPlotWorld.worldname, bot.getX() - 1, 0, top.getZ() + 1); Location pos2 = - new Location(plotArea.worldname, top.getX() + 1, Math.min(getWorldHeight(), 255), + new Location(hybridPlotWorld.worldname, top.getX() + 1, Math.min(getWorldHeight(), 255), bot.getZ()); - MainUtil.resetBiome(plotArea, pos1, pos2); - if (!hpw.ROAD_SCHEMATIC_ENABLED) { + MainUtil.resetBiome(hybridPlotWorld, pos1, pos2); + if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; } - LocalBlockQueue queue = hpw.getQueue(false); - createSchemAbs(hpw, queue, pos1, pos2, true); + LocalBlockQueue queue = hybridPlotWorld.getQueue(false); + createSchemAbs(queue, pos1, pos2); queue.enqueue(); return true; } - @Override public boolean createRoadSouthEast(PlotArea plotArea, Plot plot) { - super.createRoadSouthEast(plotArea, plot); - HybridPlotWorld hpw = (HybridPlotWorld) plotArea; + @Override public boolean createRoadSouthEast(Plot plot) { + super.createRoadSouthEast(plot); PlotId id = plot.getId(); PlotId id2 = new PlotId(id.x + 1, id.y + 1); - Location pos1 = getPlotTopLocAbs(hpw, id).add(1, 0, 1); - Location pos2 = getPlotBottomLocAbs(hpw, id2); + Location pos1 = getPlotTopLocAbs(id).add(1, 0, 1); + Location pos2 = getPlotBottomLocAbs(id2); pos1.setY(0); pos2.setY(Math.min(getWorldHeight(), 255)); - LocalBlockQueue queue = hpw.getQueue(false); - createSchemAbs(hpw, queue, pos1, pos2, true); - if (hpw.ROAD_SCHEMATIC_ENABLED) { - createSchemAbs(hpw, queue, pos1, pos2, true); + LocalBlockQueue queue = hybridPlotWorld.getQueue(false); + createSchemAbs(queue, pos1, pos2); + if (hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { + createSchemAbs(queue, pos1, pos2); } - queue.enqueue(); - return true; + return queue.enqueue(); } /** @@ -156,27 +165,26 @@ public class HybridPlotManager extends ClassicPlotManager { * don't need to do something quite as complex unless you happen to have 512x512 sized plots. *

*/ - @Override public boolean clearPlot(final PlotArea plotArea, Plot plot, - final Runnable whenDone) { - final String world = plotArea.worldname; - final HybridPlotWorld dpw = (HybridPlotWorld) plotArea; + @Override public boolean clearPlot(Plot plot, + final Runnable whenDone) { + final String world = hybridPlotWorld.worldname; Location pos1 = plot.getBottomAbs(); Location pos2 = plot.getExtendedTopAbs(); // If augmented final boolean canRegen = - (plotArea.TYPE == 0) && (plotArea.TERRAIN == 0) && REGENERATIVE_CLEAR; + (hybridPlotWorld.TYPE == 0) && (hybridPlotWorld.TERRAIN == 0) && REGENERATIVE_CLEAR; // The component blocks - final BlockBucket plotfloor = dpw.TOP_BLOCK; - final BlockBucket filling = dpw.MAIN_BLOCK; - final PlotBlock bedrock; - if (dpw.PLOT_BEDROCK) { - bedrock = PlotBlock.get((short) 7, (byte) 0); + final Pattern plotfloor = hybridPlotWorld.TOP_BLOCK.toPattern(); + final Pattern filling = hybridPlotWorld.MAIN_BLOCK.toPattern(); + final BlockState bedrock; + if (hybridPlotWorld.PLOT_BEDROCK) { + bedrock = BlockUtil.get((short) 7, (byte) 0); } else { - bedrock = PlotBlock.get((short) 0, (byte) 0); + bedrock = BlockUtil.get((short) 0, (byte) 0); } - final PlotBlock air = PlotBlock.get((short) 0, (byte) 0); - final String biome = dpw.PLOT_BIOME; - final LocalBlockQueue queue = plotArea.getQueue(false); + final BlockState air = BlockUtil.get((short) 0, (byte) 0); + final BiomeType biome = hybridPlotWorld.PLOT_BIOME; + final LocalBlockQueue queue = hybridPlotWorld.getQueue(false); ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { @Override public void run(int[] value) { // If the chunk isn't near the edge and it isn't an augmented world we can just regen the whole chunk @@ -193,38 +201,39 @@ public class HybridPlotManager extends ClassicPlotManager { queue.setCuboid(bot, top, bedrock); // Each component has a different layer bot.setY(1); - top.setY(dpw.PLOT_HEIGHT); + top.setY(hybridPlotWorld.PLOT_HEIGHT); queue.setCuboid(bot, top, filling); - bot.setY(dpw.PLOT_HEIGHT); - top.setY(dpw.PLOT_HEIGHT + 1); + bot.setY(hybridPlotWorld.PLOT_HEIGHT); + top.setY(hybridPlotWorld.PLOT_HEIGHT + 1); queue.setCuboid(bot, top, plotfloor); - bot.setY(dpw.PLOT_HEIGHT + 1); + bot.setY(hybridPlotWorld.PLOT_HEIGHT + 1); top.setY(getWorldHeight()); queue.setCuboid(bot, top, air); // And finally set the schematic, the y value is unimportant for this function - pastePlotSchematic(dpw, queue, bot, top); + pastePlotSchematic(queue, bot, top); } }, () -> { queue.enqueue(); // And notify whatever called this when plot clearing is done - GlobalBlockQueue.IMP.addTask(whenDone); + GlobalBlockQueue.IMP.addEmptyTask(whenDone); }, 10); return true; } - public void pastePlotSchematic(HybridPlotWorld plotWorld, LocalBlockQueue queue, Location l1, - Location l2) { - if (!plotWorld.PLOT_SCHEMATIC) { + public void pastePlotSchematic(LocalBlockQueue queue, + Location bottom, Location top) { + if (!hybridPlotWorld.PLOT_SCHEMATIC) { return; } - createSchemAbs(plotWorld, queue, l1, l2, false); + createSchemAbs(queue, bottom, top); } /** - * Remove sign for a plot. + * Retrieves the location of where a sign should be for a plot. + * @param plot The plot + * @return The location where a sign should be */ - @Override public Location getSignLoc(PlotArea plotArea, Plot plot) { - HybridPlotWorld dpw = (HybridPlotWorld) plotArea; - return dpw.getSignLocation(plot); + @Override public Location getSignLoc(Plot plot) { + return hybridPlotWorld.getSignLocation(plot); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotWorld.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotWorld.java index 880ddee35..6b44487ce 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotWorld.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridPlotWorld.java @@ -7,13 +7,14 @@ import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; import com.github.intellectualsites.plotsquared.plot.object.schematic.Schematic; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTagBuilder; -import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; +import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.transform.BlockTransformExtent; import com.sk89q.worldedit.internal.helper.MCDirections; import com.sk89q.worldedit.math.BlockVector3; @@ -21,6 +22,7 @@ import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.world.block.BaseBlock; +import org.jetbrains.annotations.NotNull; import java.io.File; import java.util.HashMap; @@ -37,11 +39,16 @@ public class HybridPlotWorld extends ClassicPlotWorld { public int SCHEM_Y; private Location SIGN_LOCATION; - public HybridPlotWorld(String worldName, String id, IndependentPlotGenerator generator, + public HybridPlotWorld(String worldName, String id, @NotNull IndependentPlotGenerator generator, PlotId min, PlotId max) { super(worldName, id, generator, min, max); } + @NotNull @Override + protected PlotManager createManager() { + return new HybridPlotManager(this); + } + public static byte wrap(byte data, int start) { if ((data >= start) && (data < (start + 4))) { data = (byte) ((((data - start) + 2) & 3) + start); @@ -119,8 +126,8 @@ public class HybridPlotWorld extends ClassicPlotWorld { } try { setupSchematics(); - } catch (Exception ignored) { - ignored.printStackTrace(); + } catch (Exception event) { + event.printStackTrace(); PlotSquared.debug("&c - road schematics are disabled for this world."); } } @@ -171,7 +178,7 @@ public class HybridPlotWorld extends ClassicPlotWorld { if (schematic3 != null) { this.PLOT_SCHEMATIC = true; - BlockArrayClipboard blockArrayClipboard3 = schematic3.getClipboard(); + Clipboard blockArrayClipboard3 = schematic3.getClipboard(); BlockVector3 d3 = blockArrayClipboard3.getDimensions(); short w3 = (short) d3.getX(); @@ -245,9 +252,9 @@ public class HybridPlotWorld extends ClassicPlotWorld { } this.ROAD_SCHEMATIC_ENABLED = true; // Do not populate road if using schematic population - // TODO: What? this.ROAD_BLOCK = BlockBucket.empty(); // PlotBlock.getEmptyData(this.ROAD_BLOCK); // PlotBlock.get(this.ROAD_BLOCK.id, (byte) 0); + // TODO: What? this.ROAD_BLOCK = BlockBucket.empty(); // BlockState.getEmptyData(this.ROAD_BLOCK); // BlockUtil.get(this.ROAD_BLOCK.id, (byte) 0); - BlockArrayClipboard blockArrayClipboard1 = schematic1.getClipboard(); + Clipboard blockArrayClipboard1 = schematic1.getClipboard(); BlockVector3 d1 = blockArrayClipboard1.getDimensions(); short w1 = (short) d1.getX(); @@ -270,7 +277,7 @@ public class HybridPlotWorld extends ClassicPlotWorld { } } - BlockArrayClipboard blockArrayClipboard2 = schematic2.getClipboard(); + Clipboard blockArrayClipboard2 = schematic2.getClipboard(); BlockVector3 d2 = blockArrayClipboard2.getDimensions(); short w2 = (short) d2.getX(); short l2 = (short) d2.getZ(); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridUtils.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridUtils.java index de6c3390b..db3df521a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridUtils.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/HybridUtils.java @@ -1,36 +1,243 @@ package com.github.intellectualsites.plotsquared.plot.generator; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.listener.WEExtent; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import com.github.intellectualsites.plotsquared.plot.util.block.ChunkBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis; +import com.github.intellectualsites.plotsquared.plot.util.world.RegionUtil; import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.block.BlockTypes; import java.io.File; -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public abstract class HybridUtils { public static HybridUtils manager; - public static Set regions; - public static Set chunks = new HashSet<>(); + public static Set regions; + public static Set chunks = new HashSet<>(); public static PlotArea area; public static boolean UPDATE = false; - public abstract void analyzeRegion(String world, RegionWrapper region, - RunnableVal whenDone); + public void analyzeRegion(final String world, final CuboidRegion region, final RunnableVal whenDone) { + // int diff, int variety, int vertices, int rotation, int height_sd + /* + * diff: compare to base by looping through all blocks + * variety: add to HashSet for each BlockState + * height_sd: loop over all blocks and get top block + * + * vertices: store air map and compare with neighbours + * for each block check the adjacent + * - Store all blocks then go through in second loop + * - recheck each block + * + */ + TaskManager.runTaskAsync(() -> { + final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false); + + final BlockVector3 bot = region.getMinimumPoint(); + final BlockVector3 top = region.getMaximumPoint(); + + final int bx = bot.getX(); + final int bz = bot.getZ(); + final int tx = top.getX(); + final int tz = top.getZ(); + final int cbx = bx >> 4; + final int cbz = bz >> 4; + final int ctx = tx >> 4; + final int ctz = tz >> 4; + MainUtil.initCache(); + final int width = tx - bx + 1; + final int length = tz - bz + 1; + + PlotArea area = PlotSquared.get().getPlotArea(world, null); + + if (!(area instanceof HybridPlotWorld)) { + return; + } + + HybridPlotWorld hpw = (HybridPlotWorld) area; + ChunkBlockQueue chunk = new ChunkBlockQueue(bot, top, false); + hpw.getGenerator().generateChunk(chunk, hpw); + + final BlockState[][][] oldBlocks = chunk.getBlocks(); + final BlockState[][][] newBlocks = new BlockState[256][width][length]; + final BlockState airBlock = BlockTypes.AIR.getDefaultState(); + + System.gc(); + System.gc(); + + final Runnable run = () -> TaskManager.runTaskAsync(() -> { + int size = width * length; + int[] changes = new int[size]; + int[] faces = new int[size]; + int[] data = new int[size]; + int[] air = new int[size]; + int[] variety = new int[size]; + int i = 0; + for (int x = 0; x < width; x++) { + for (int z = 0; z < length; z++) { + Set types = new HashSet<>(); + for (int y = 0; y < 256; y++) { + BlockState old = oldBlocks[y][x][z]; + try { + if (old == null) { + old = airBlock; + } + BlockState now = newBlocks[y][x][z]; + if (!old.equals(now)) { + changes[i]++; + } + if (now.getBlockType().getMaterial().isAir()) { + air[i]++; + } else { + // check vertices + // modifications_adjacent + if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 + && y < 255) { + if (newBlocks[y - 1][x][z].getBlockType().getMaterial().isAir()) { + faces[i]++; + } + if (newBlocks[y][x - 1][z].getBlockType().getMaterial().isAir()) { + faces[i]++; + } + if (newBlocks[y][x][z - 1].getBlockType().getMaterial().isAir()) { + faces[i]++; + } + if (newBlocks[y + 1][x][z].getBlockType().getMaterial().isAir()) { + faces[i]++; + } + if (newBlocks[y][x + 1][z].getBlockType().getMaterial().isAir()) { + faces[i]++; + } + if (newBlocks[y][x][z + 1].getBlockType().getMaterial().isAir()) { + faces[i]++; + } + } + + if (!now.equals(now.getBlockType().getDefaultState())) { + data[i]++; + } + types.add(now.getBlockType()); + } + } catch (NullPointerException e) { + e.printStackTrace(); + } + } + variety[i] = types.size(); + i++; + } + } + // analyze plot + // put in analysis obj + + // run whenDone + PlotAnalysis analysis = new PlotAnalysis(); + analysis.changes = (int) (MathMan.getMean(changes) * 100); + analysis.faces = (int) (MathMan.getMean(faces) * 100); + analysis.data = (int) (MathMan.getMean(data) * 100); + analysis.air = (int) (MathMan.getMean(air) * 100); + analysis.variety = (int) (MathMan.getMean(variety) * 100); + + analysis.changes_sd = (int) (MathMan.getSD(changes, analysis.changes) * 100); + analysis.faces_sd = (int) (MathMan.getSD(faces, analysis.faces) * 100); + analysis.data_sd = (int) (MathMan.getSD(data, analysis.data) * 100); + analysis.air_sd = (int) (MathMan.getSD(air, analysis.air) * 100); + analysis.variety_sd = (int) (MathMan.getSD(variety, analysis.variety) * 100); + System.gc(); + System.gc(); + whenDone.value = analysis; + whenDone.run(); + }); + System.gc(); + MainUtil.initCache(); + Location botLoc = new Location(world, bot.getX(), bot.getY(), bot.getZ()); + Location topLoc = new Location(world, top.getX(), top.getY(), top.getZ()); + ChunkManager.chunkTask(botLoc, topLoc, new RunnableVal() { + @Override public void run(int[] value) { + int X = value[0]; + int Z = value[1]; + int minX; + if (X == cbx) { + minX = bx & 15; + } else { + minX = 0; + } + int minZ; + if (Z == cbz) { + minZ = bz & 15; + } else { + minZ = 0; + } + int maxX; + if (X == ctx) { + maxX = tx & 15; + } else { + maxX = 16; + } + int maxZ; + if (Z == ctz) { + maxZ = tz & 15; + } else { + maxZ = 16; + } + + int cbx = X << 4; + int cbz = Z << 4; + + int xb = cbx - bx; + int zb = cbz - bz; + for (int x = minX; x <= maxX; x++) { + int xx = cbx + x; + for (int z = minZ; z <= maxZ; z++) { + int zz = cbz + z; + for (int y = 0; y < 256; y++) { + BlockState block = queue.getBlock(xx, y, zz); + int xr = xb + x; + int zr = zb + z; + newBlocks[y][xr][zr] = block; + } + } + } + } + }, () -> TaskManager.runTaskAsync(run), 5); + }); + } public void analyzePlot(final Plot origin, final RunnableVal whenDone) { - final ArrayDeque zones = new ArrayDeque<>(origin.getRegions()); + final ArrayDeque zones = new ArrayDeque<>(origin.getRegions()); final ArrayList analysis = new ArrayList<>(); Runnable run = new Runnable() { @Override public void run() { @@ -78,7 +285,7 @@ public abstract class HybridUtils { TaskManager.runTask(whenDone); return; } - RegionWrapper region = zones.poll(); + CuboidRegion region = zones.poll(); final Runnable task = this; analyzeRegion(origin.getWorldName(), region, new RunnableVal() { @Override public void run(PlotAnalysis value) { @@ -92,12 +299,12 @@ public abstract class HybridUtils { } public int checkModified(LocalBlockQueue queue, int x1, int x2, int y1, int y2, int z1, int z2, - PlotBlock[] blocks) { + BlockState[] blocks) { int count = 0; for (int y = y1; y <= y2; y++) { for (int x = x1; x <= x2; x++) { for (int z = z1; z <= z2; z++) { - PlotBlock block = queue.getBlock(x, y, z); + BlockState block = queue.getBlock(x, y, z); boolean same = Arrays.stream(blocks).anyMatch(p -> WorldUtil.IMP.isBlockSame(block, p)); if (!same) { @@ -109,13 +316,13 @@ public abstract class HybridUtils { return count; } - public final ArrayList getChunks(ChunkLoc region) { - ArrayList chunks = new ArrayList<>(); - int sx = region.x << 5; - int sz = region.z << 5; + public final ArrayList getChunks(BlockVector2 region) { + ArrayList chunks = new ArrayList<>(); + int sx = region.getX() << 5; + int sz = region.getZ() << 5; for (int x = sx; x < sx + 32; x++) { for (int z = sz; z < sz + 32; z++) { - chunks.add(new ChunkLoc(x, z)); + chunks.add(BlockVector2.at(x, z)); } } return chunks; @@ -126,48 +333,66 @@ public abstract class HybridUtils { return false; } HybridUtils.UPDATE = true; - Set regions = ChunkManager.manager.getChunkChunks(area.worldname); + Set regions = ChunkManager.manager.getChunkChunks(area.worldname); return scheduleRoadUpdate(area, regions, extend); } - public boolean scheduleRoadUpdate(final PlotArea area, Set rgs, final int extend) { - HybridUtils.regions = rgs; + public boolean scheduleSingleRegionRoadUpdate(Plot plot, int extend) { + if (HybridUtils.UPDATE) { + return false; + } + HybridUtils.UPDATE = true; + Set regions = new HashSet<>(); + regions.add(ChunkManager.getRegion(plot.getCenter())); + return scheduleRoadUpdate(plot.getArea(), regions, extend); + } + + public boolean scheduleRoadUpdate(final PlotArea area, Set regions, + final int extend) { + HybridUtils.regions = regions; HybridUtils.area = area; chunks = new HashSet<>(); final AtomicInteger count = new AtomicInteger(0); TaskManager.runTask(new Runnable() { @Override public void run() { if (!UPDATE) { - Iterator iter = chunks.iterator(); + Iterator iter = chunks.iterator(); while (iter.hasNext()) { - ChunkLoc chunk = iter.next(); + BlockVector2 chunk = iter.next(); iter.remove(); - regenerateRoad(area, chunk, extend); - ChunkManager.manager.unloadChunk(area.worldname, chunk, true, true); + boolean regenedRoad = regenerateRoad(area, chunk, extend); + if (!regenedRoad) { + PlotSquared.debug("Failed to regenerate roads."); + } + ChunkManager.manager.unloadChunk(area.worldname, chunk, true); } - PlotSquared.debug("&cCancelled road task"); + PlotSquared.debug("Cancelled road task"); return; } count.incrementAndGet(); if (count.intValue() % 20 == 0) { PlotSquared.debug("PROGRESS: " + 100 * (2048 - chunks.size()) / 2048 + "%"); } - if (regions.isEmpty() && chunks.isEmpty()) { + if (HybridUtils.regions.isEmpty() && chunks.isEmpty()) { + PlotSquared.debug("Regenerating plot walls"); + regeneratePlotWalls(area); + HybridUtils.UPDATE = false; - PlotSquared.debug(Captions.PREFIX.s() + "Finished road conversion"); + PlotSquared.debug("Finished road conversion"); // CANCEL TASK } else { final Runnable task = this; TaskManager.runTaskAsync(() -> { try { if (chunks.size() < 1024) { - if (!regions.isEmpty()) { - Iterator iterator = regions.iterator(); - ChunkLoc loc = iterator.next(); + if (!HybridUtils.regions.isEmpty()) { + Iterator iterator = HybridUtils.regions.iterator(); + BlockVector2 loc = iterator.next(); iterator.remove(); - PlotSquared.debug("&3Updating .mcr: " + loc.x + ", " + loc.z - + " (aprrox 1024 chunks)"); - PlotSquared.debug(" - Remaining: " + regions.size()); + PlotSquared.debug("Updating .mcr: " + loc.getX() + ", " + loc.getZ() + + " (approx 1024 chunks)"); + PlotSquared + .debug(" - Remaining: " + HybridUtils.regions.size()); chunks.addAll(getChunks(loc)); System.gc(); } @@ -176,37 +401,40 @@ public abstract class HybridUtils { TaskManager.IMP.sync(new RunnableVal() { @Override public void run(Object value) { long start = System.currentTimeMillis(); - Iterator iterator = chunks.iterator(); + Iterator iterator = chunks.iterator(); while (System.currentTimeMillis() - start < 20 && !chunks .isEmpty()) { - final ChunkLoc chunk = iterator.next(); + final BlockVector2 chunk = iterator.next(); iterator.remove(); - regenerateRoad(area, chunk, extend); + boolean regenedRoads = + regenerateRoad(area, chunk, extend); + if (!regenedRoads) { + PlotSquared.debug("Failed to regenerate road."); + } } } }); } } catch (Exception e) { e.printStackTrace(); - Iterator iterator = regions.iterator(); - ChunkLoc loc = iterator.next(); + Iterator iterator = HybridUtils.regions.iterator(); + BlockVector2 loc = iterator.next(); iterator.remove(); PlotSquared.debug( - "&c[ERROR]&7 Could not update '" + area.worldname + "/region/r." - + loc.x + "." + loc.z + ".mca' (Corrupt chunk?)"); - int sx = loc.x << 5; - int sz = loc.z << 5; + "[ERROR] Could not update '" + area.worldname + "/region/r." + loc.getX() + + "." + loc.getZ() + ".mca' (Corrupt chunk?)"); + int sx = loc.getX() << 5; + int sz = loc.getZ() << 5; for (int x = sx; x < sx + 32; x++) { for (int z = sz; z < sz + 32; z++) { ChunkManager.manager - .unloadChunk(area.worldname, new ChunkLoc(x, z), true, - true); + .unloadChunk(area.worldname, BlockVector2.at(x, z), true); } } - PlotSquared.debug("&d - Potentially skipping 1024 chunks"); - PlotSquared.debug("&d - TODO: recommend chunkster if corrupt"); + PlotSquared.debug(" - Potentially skipping 1024 chunks"); + PlotSquared.debug(" - TODO: recommend chunkster if corrupt"); } - GlobalBlockQueue.IMP.addTask(() -> TaskManager.runTaskLater(task, 20)); + GlobalBlockQueue.IMP.addEmptyTask(() -> TaskManager.runTaskLater(task, 20)); }); } } @@ -231,10 +459,10 @@ public abstract class HybridUtils { int tz = sz - 1; int ty = get_ey(plotManager, queue, sx, ex, bz, tz, sy); - Set sideRoad = - new HashSet<>(Collections.singletonList(new RegionWrapper(sx, ex, sy, ey, sz, ez))); - final Set intersection = - new HashSet<>(Collections.singletonList(new RegionWrapper(sx, ex, sy, ty, bz, tz))); + Set sideRoad = + new HashSet<>(Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ey, sz, ez))); + final Set intersection = + new HashSet<>(Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ty, bz, tz))); final String dir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + plot.getArea() @@ -267,8 +495,8 @@ public abstract class HybridUtils { for (int z = sz; z <= ez; z++) { for (int y = sy; y <= pm.getWorldHeight(); y++) { if (y > ey) { - PlotBlock block = queue.getBlock(x, y, z); - if (!block.isAir()) { + BlockState block = queue.getBlock(x, y, z); + if (!block.getBlockType().getMaterial().isAir()) { ey = y; } } @@ -278,51 +506,52 @@ public abstract class HybridUtils { return ey; } - public boolean regenerateRoad(final PlotArea area, final ChunkLoc chunk, int extend) { - int x = chunk.x << 4; - int z = chunk.z << 4; + public boolean regenerateRoad(final PlotArea area, final BlockVector2 chunk, int extend) { + int x = chunk.getX() << 4; + int z = chunk.getZ() << 4; int ex = x + 15; int ez = z + 15; HybridPlotWorld plotWorld = (HybridPlotWorld) area; if (!plotWorld.ROAD_SCHEMATIC_ENABLED) { return false; } - boolean toCheck = false; + AtomicBoolean toCheck = new AtomicBoolean(false); if (plotWorld.TYPE == 2) { - boolean c1 = area.contains(x, z); - boolean c2 = area.contains(ex, ez); - if (!c1 && !c2) { + boolean chunk1 = area.contains(x, z); + boolean chunk2 = area.contains(ex, ez); + if (!chunk1 && !chunk2) { return false; } else { - toCheck = c1 ^ c2; + toCheck.set(chunk1 ^ chunk2); } } PlotManager manager = area.getPlotManager(); - PlotId id1 = manager.getPlotId(plotWorld, x, 0, z); - PlotId id2 = manager.getPlotId(plotWorld, ex, 0, ez); - x -= plotWorld.ROAD_OFFSET_X; + PlotId id1 = manager.getPlotId(x, 0, z); + PlotId id2 = manager.getPlotId(ex, 0, ez); + x = x - plotWorld.ROAD_OFFSET_X; z -= plotWorld.ROAD_OFFSET_Z; + final int finalX = x; + final int finalZ = z; LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(plotWorld.worldname, false); if (id1 == null || id2 == null || id1 != id2) { - boolean result = ChunkManager.manager.loadChunk(area.worldname, chunk, false); - if (result) { + ChunkManager.manager.loadChunk(area.worldname, chunk, false).thenRun(() -> { if (id1 != null) { Plot p1 = area.getPlotAbs(id1); if (p1 != null && p1.hasOwner() && p1.isMerged()) { - toCheck = true; + toCheck.set(true); } } - if (id2 != null && !toCheck) { + if (id2 != null && !toCheck.get()) { Plot p2 = area.getPlotAbs(id2); if (p2 != null && p2.hasOwner() && p2.isMerged()) { - toCheck = true; + toCheck.set(true); } } int size = plotWorld.SIZE; for (int X = 0; X < 16; X++) { - short absX = (short) ((x + X) % size); + short absX = (short) ((finalX + X) % size); for (int Z = 0; Z < 16; Z++) { - short absZ = (short) ((z + Z) % size); + short absZ = (short) ((finalZ + Z) % size); if (absX < 0) { absX += size; } @@ -330,11 +559,9 @@ public abstract class HybridUtils { absZ += size; } boolean condition; - if (toCheck) { - condition = manager - .getPlotId(plotWorld, x + X + plotWorld.ROAD_OFFSET_X, 1, - z + Z + plotWorld.ROAD_OFFSET_Z) == null; - // condition = MainUtil.isPlotRoad(new Location(plotworld.worldname, x + X, 1, z + Z)); + if (toCheck.get()) { + condition = manager.getPlotId(finalX + X + plotWorld.ROAD_OFFSET_X, 1, + finalZ + Z + plotWorld.ROAD_OFFSET_Z) == null; } else { boolean gx = absX > plotWorld.PATH_WIDTH_LOWER; boolean gz = absZ > plotWorld.PATH_WIDTH_LOWER; @@ -345,26 +572,22 @@ public abstract class HybridUtils { if (condition) { BaseBlock[] blocks = plotWorld.G_SCH.get(MathMan.pair(absX, absZ)); int minY = plotWorld.SCHEM_Y; - if (!Settings.Schematics.PASTE_ON_TOP) + if (!Settings.Schematics.PASTE_ON_TOP) { minY = 1; + } int maxY = Math.max(extend, blocks.length); - if (blocks != null) { - for (int y = 0; y < maxY; y++) { - if (y > blocks.length - 1) { - queue.setBlock(x + X + plotWorld.ROAD_OFFSET_X, minY + y, - z + Z + plotWorld.ROAD_OFFSET_Z, WEExtent.AIRBASE); + for (int y = 0; y < maxY; y++) { + if (y > blocks.length - 1) { + queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, + finalZ + Z + plotWorld.ROAD_OFFSET_Z, WEExtent.AIRBASE); + } else { + BaseBlock block = blocks[y]; + if (block != null) { + queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, + finalZ + Z + plotWorld.ROAD_OFFSET_Z, block); } else { - BaseBlock block = blocks[y]; - if (block != null) { - queue - .setBlock(x + X + plotWorld.ROAD_OFFSET_X, minY + y, - z + Z + plotWorld.ROAD_OFFSET_Z, block); - } else { - queue - .setBlock(x + X + plotWorld.ROAD_OFFSET_X, minY + y, - z + Z + plotWorld.ROAD_OFFSET_Z, - WEExtent.AIRBASE); - } + queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, + finalZ + Z + plotWorld.ROAD_OFFSET_Z, WEExtent.AIRBASE); } } } @@ -372,9 +595,14 @@ public abstract class HybridUtils { } } queue.enqueue(); - return true; - } + }); + return true; } return false; } + + public boolean regeneratePlotWalls(final PlotArea area) { + PlotManager plotManager = area.getPlotManager(); + return plotManager.regenerateAllPlotWalls(); + } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/IndependentPlotGenerator.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/IndependentPlotGenerator.java index e06d7208e..1467dc1dd 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/IndependentPlotGenerator.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/IndependentPlotGenerator.java @@ -1,7 +1,9 @@ package com.github.intellectualsites.plotsquared.plot.generator; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.SetupObject; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; /** @@ -16,14 +18,6 @@ public abstract class IndependentPlotGenerator { */ public abstract String getName(); - /** - * Generates a 16x4096 array of BlockBuckets corresponding to the area settings to allow for plot analysis - * - * @param settings - * @return - */ - public abstract BlockBucket[][] generateBlockBucketChunk(PlotArea settings); - /** * Use the setBlock or setBiome method of the PlotChunk result parameter to make changes. * The PlotArea settings is the same one this was initialized with. @@ -49,13 +43,6 @@ public abstract class IndependentPlotGenerator { */ public abstract PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max); - /** - * Return a new PlotManager object. - * - * @return - */ - public abstract PlotManager getNewPlotManager(); - /** * If any additional setup options need to be changed before world creation. * - e.g. If setup doesn't support some standard options diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/SquarePlotManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/SquarePlotManager.java index 5be65a394..eeda6d06e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/SquarePlotManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/SquarePlotManager.java @@ -1,35 +1,47 @@ package com.github.intellectualsites.plotsquared.plot.generator; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Direction; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.sk89q.worldedit.regions.CuboidRegion; import java.util.Arrays; -import java.util.HashSet; import java.util.Iterator; +import java.util.Set; /** * A plot manager with a square grid layout, with square shaped plots. */ public abstract class SquarePlotManager extends GridPlotManager { + private final SquarePlotWorld squarePlotWorld; + + public SquarePlotManager(SquarePlotWorld squarePlotWorld) { + super(squarePlotWorld); + this.squarePlotWorld = squarePlotWorld; + } + @Override - public boolean clearPlot(PlotArea plotArea, final Plot plot, final Runnable whenDone) { - final HashSet regions = plot.getRegions(); + public boolean clearPlot(final Plot plot, final Runnable whenDone) { + final Set regions = plot.getRegions(); Runnable run = new Runnable() { @Override public void run() { if (regions.isEmpty()) { whenDone.run(); return; } - Iterator iterator = regions.iterator(); - RegionWrapper region = iterator.next(); + Iterator iterator = regions.iterator(); + CuboidRegion region = iterator.next(); iterator.remove(); Location pos1 = - new Location(plot.getWorldName(), region.minX, region.minY, region.minZ); + new Location(plot.getWorldName(), region.getMinimumPoint().getX(), region.getMinimumPoint().getY(), region.getMinimumPoint().getZ()); Location pos2 = - new Location(plot.getWorldName(), region.maxX, region.maxY, region.maxZ); + new Location(plot.getWorldName(), region.getMaximumPoint().getX(), region.getMaximumPoint().getY(), region.getMaximumPoint().getZ()); ChunkManager.manager.regenerateRegion(pos1, pos2, false, this); } }; @@ -37,39 +49,37 @@ public abstract class SquarePlotManager extends GridPlotManager { return true; } - @Override public Location getPlotTopLocAbs(PlotArea plotArea, PlotId plotId) { - SquarePlotWorld dpw = (SquarePlotWorld) plotArea; + @Override public Location getPlotTopLocAbs(PlotId plotId) { int px = plotId.x; int pz = plotId.y; - int x = (dpw.ROAD_OFFSET_X + (px * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH))) - (int) Math - .floor(dpw.ROAD_WIDTH / 2) - 1; - int z = (dpw.ROAD_OFFSET_Z + (pz * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH))) - (int) Math - .floor(dpw.ROAD_WIDTH / 2) - 1; - return new Location(plotArea.worldname, x, Math.min(getWorldHeight(), 255), z); + int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - (int) Math + .floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; + int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - (int) Math + .floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; + return new Location(squarePlotWorld.worldname, x, Math.min(getWorldHeight(), 255), z); } - @Override public PlotId getPlotIdAbs(PlotArea plotArea, int x, int y, int z) { - SquarePlotWorld dpw = (SquarePlotWorld) plotArea; - if (dpw.ROAD_OFFSET_X != 0) { - x -= dpw.ROAD_OFFSET_X; + @Override public PlotId getPlotIdAbs(int x, int y, int z) { + if (squarePlotWorld.ROAD_OFFSET_X != 0) { + x -= squarePlotWorld.ROAD_OFFSET_X; } - if (dpw.ROAD_OFFSET_Z != 0) { - z -= dpw.ROAD_OFFSET_Z; + if (squarePlotWorld.ROAD_OFFSET_Z != 0) { + z -= squarePlotWorld.ROAD_OFFSET_Z; } int pathWidthLower; int end; - if (dpw.ROAD_WIDTH == 0) { + if (squarePlotWorld.ROAD_WIDTH == 0) { pathWidthLower = -1; - end = dpw.PLOT_WIDTH; + end = squarePlotWorld.PLOT_WIDTH; } else { - if ((dpw.ROAD_WIDTH % 2) == 0) { - pathWidthLower = (dpw.ROAD_WIDTH / 2) - 1; + if ((squarePlotWorld.ROAD_WIDTH % 2) == 0) { + pathWidthLower = (squarePlotWorld.ROAD_WIDTH / 2) - 1; } else { - pathWidthLower = dpw.ROAD_WIDTH / 2; + pathWidthLower = squarePlotWorld.ROAD_WIDTH / 2; } - end = pathWidthLower + dpw.PLOT_WIDTH; + end = pathWidthLower + squarePlotWorld.PLOT_WIDTH; } - int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH; + int size = squarePlotWorld.PLOT_WIDTH + squarePlotWorld.ROAD_WIDTH; int idx; if (x < 0) { idx = x / size; @@ -117,27 +127,23 @@ public abstract class SquarePlotManager extends GridPlotManager { return new PlotId(idx, idz); } - @Override public PlotId getPlotId(PlotArea plotArea, int x, int y, int z) { + @Override public PlotId getPlotId(int x, int y, int z) { try { - SquarePlotWorld dpw = (SquarePlotWorld) plotArea; - if (plotArea == null) { - return null; - } - x -= dpw.ROAD_OFFSET_X; - z -= dpw.ROAD_OFFSET_Z; - int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH; + x -= squarePlotWorld.ROAD_OFFSET_X; + z -= squarePlotWorld.ROAD_OFFSET_Z; + int size = squarePlotWorld.PLOT_WIDTH + squarePlotWorld.ROAD_WIDTH; int pathWidthLower; int end; - if (dpw.ROAD_WIDTH == 0) { + if (squarePlotWorld.ROAD_WIDTH == 0) { pathWidthLower = -1; - end = dpw.PLOT_WIDTH; + end = squarePlotWorld.PLOT_WIDTH; } else { - if ((dpw.ROAD_WIDTH % 2) == 0) { - pathWidthLower = (dpw.ROAD_WIDTH / 2) - 1; + if ((squarePlotWorld.ROAD_WIDTH % 2) == 0) { + pathWidthLower = (squarePlotWorld.ROAD_WIDTH / 2) - 1; } else { - pathWidthLower = dpw.ROAD_WIDTH / 2; + pathWidthLower = squarePlotWorld.ROAD_WIDTH / 2; } - end = pathWidthLower + dpw.PLOT_WIDTH; + end = pathWidthLower + squarePlotWorld.PLOT_WIDTH; } int dx; int rx; @@ -165,7 +171,7 @@ public abstract class SquarePlotManager extends GridPlotManager { if (hash == 0) { return id; } - Plot plot = plotArea.getOwnedPlotAbs(id); + Plot plot = squarePlotWorld.getOwnedPlotAbs(id); // Not merged, and standing on road if (plot == null) { return null; @@ -199,7 +205,7 @@ public abstract class SquarePlotManager extends GridPlotManager { PlotSquared.debug("invalid location: " + Arrays.toString(merged)); } catch (Exception ignored) { PlotSquared.debug( - "Invalid plot / road width in settings.yml for world: " + plotArea.worldname); + "Invalid plot / road width in settings.yml for world: " + squarePlotWorld.worldname); } return null; } @@ -207,14 +213,13 @@ public abstract class SquarePlotManager extends GridPlotManager { /** * Get the bottom plot loc (some basic math). */ - @Override public Location getPlotBottomLocAbs(PlotArea plotArea, PlotId plotId) { - SquarePlotWorld dpw = (SquarePlotWorld) plotArea; + @Override public Location getPlotBottomLocAbs(PlotId plotId) { int px = plotId.x; int pz = plotId.y; - int x = (dpw.ROAD_OFFSET_X + (px * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH))) - dpw.PLOT_WIDTH - - (int) Math.floor(dpw.ROAD_WIDTH / 2); - int z = (dpw.ROAD_OFFSET_Z + (pz * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH))) - dpw.PLOT_WIDTH - - (int) Math.floor(dpw.ROAD_WIDTH / 2); - return new Location(plotArea.worldname, x, plotArea.MIN_BUILD_HEIGHT, z); + int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH + - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2); + int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH + - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2); + return new Location(squarePlotWorld.worldname, x, squarePlotWorld.MIN_BUILD_HEIGHT, z); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/SquarePlotWorld.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/SquarePlotWorld.java index 5401d221a..c2d1ddb31 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/SquarePlotWorld.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/generator/SquarePlotWorld.java @@ -3,6 +3,7 @@ package com.github.intellectualsites.plotsquared.plot.generator; import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import org.jetbrains.annotations.NotNull; public abstract class SquarePlotWorld extends GridPlotWorld { @@ -11,7 +12,7 @@ public abstract class SquarePlotWorld extends GridPlotWorld { public int ROAD_OFFSET_X = 0; public int ROAD_OFFSET_Z = 0; - public SquarePlotWorld(String worldName, String id, IndependentPlotGenerator generator, + public SquarePlotWorld(String worldName, String id, @NotNull IndependentPlotGenerator generator, PlotId min, PlotId max) { super(worldName, id, generator, min, max); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlayerBlockEventType.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlayerBlockEventType.java index 815f5ea43..c226d87aa 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlayerBlockEventType.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlayerBlockEventType.java @@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.listener; public enum PlayerBlockEventType { // Non interactive - EAT, READ, + READ, // Right click with monster egg SPAWN_MOB, @@ -11,21 +11,11 @@ public enum PlayerBlockEventType { TELEPORT_OBJECT, // armor stands - PLACE_MISC, // blocks - PLACE_BLOCK, // paintings / item frames - PLACE_HANGING, // vehicles + PLACE_MISC, PLACE_VEHICLE, // armor stands - BREAK_MISC, // blocks - BREAK_BLOCK, // paintings / item frames - BREAK_HANGING, BREAK_VEHICLE, - - // armor stands - INTERACT_MISC, // blocks - INTERACT_BLOCK, // vehicle - INTERACT_VEHICLE, // item frame / painting - INTERACT_HANGING, + INTERACT_BLOCK, // blocks // Pressure plate, tripwire etc TRIGGER_PHYSICAL, diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlotListener.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlotListener.java index c56763a76..fd3572229 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlotListener.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/PlotListener.java @@ -5,9 +5,26 @@ import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; import com.github.intellectualsites.plotsquared.plot.flag.Flags; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.util.ByteArrayUtilities; +import com.github.intellectualsites.plotsquared.plot.util.CommentManager; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.PlotWeather; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; +import com.github.intellectualsites.plotsquared.plot.util.world.ItemUtil; +import com.sk89q.worldedit.world.gamemode.GameMode; +import com.sk89q.worldedit.world.gamemode.GameModes; +import com.sk89q.worldedit.world.item.ItemType; +import com.sk89q.worldedit.world.item.ItemTypes; import java.util.HashMap; import java.util.Map; @@ -52,7 +69,9 @@ public class PlotListener { Optional greetingFlag = plot.getFlag(Flags.GREETING); if (greetingFlag.isPresent()) { greeting = greetingFlag.get(); - MainUtil.format(Captions.PREFIX_GREETING.s() + greeting, plot, player, false, + MainUtil + .format(Captions.PREFIX_GREETING.getTranslated() + greeting, plot, player, + false, new RunnableVal() { @Override public void run(String value) { MainUtil.sendMessage(player, value); @@ -67,8 +86,8 @@ public class PlotListener { for (UUID uuid : plot.getOwners()) { PlotPlayer owner = UUIDHandler.getPlayer(uuid); if (owner != null && !owner.getUUID().equals(player.getUUID())) { - MainUtil.sendMessage(owner, - Captions.NOTIFY_ENTER.s().replace("%player", player.getName()) + MainUtil.sendMessage(owner, Captions.NOTIFY_ENTER.getTranslated() + .replace("%player", player.getName()) .replace("%plot", plot.getId().toString())); } } @@ -77,9 +96,9 @@ public class PlotListener { Optional flyFlag = plot.getFlag(Flags.FLY); if (flyFlag.isPresent()) { boolean flight = player.getFlight(); - PlotGameMode gamemode = player.getGameMode(); - if (flight != (gamemode == PlotGameMode.CREATIVE - || gamemode == PlotGameMode.SPECTATOR)) { + GameMode gamemode = player.getGameMode(); + if (flight != (gamemode == GameModes.CREATIVE + || gamemode == GameModes.SPECTATOR)) { player.setPersistentMeta("flight", ByteArrayUtilities.booleanToBytes(player.getFlight())); } @@ -87,19 +106,20 @@ public class PlotListener { player.setFlight(flyFlag.get()); } } - Optional gamemodeFlag = plot.getFlag(Flags.GAMEMODE); + Optional gamemodeFlag = plot.getFlag(Flags.GAMEMODE); if (gamemodeFlag.isPresent()) { if (player.getGameMode() != gamemodeFlag.get()) { if (!Permissions.hasPermission(player, "plots.gamemode.bypass")) { player.setGameMode(gamemodeFlag.get()); } else { MainUtil.sendMessage(player, StringMan - .replaceAll(Captions.GAMEMODE_WAS_BYPASSED.s(), "{plot}", + .replaceAll(Captions.GAMEMODE_WAS_BYPASSED.getTranslated(), + "{plot}", plot.getId(), "{gamemode}", gamemodeFlag.get())); } } } - Optional guestGamemodeFlag = plot.getFlag(Flags.GUEST_GAMEMODE); + Optional guestGamemodeFlag = plot.getFlag(Flags.GUEST_GAMEMODE); if (guestGamemodeFlag.isPresent()) { if (player.getGameMode() != guestGamemodeFlag.get() && !plot .isAdded(player.getUUID())) { @@ -107,13 +127,14 @@ public class PlotListener { player.setGameMode(guestGamemodeFlag.get()); } else { MainUtil.sendMessage(player, StringMan - .replaceAll(Captions.GAMEMODE_WAS_BYPASSED.s(), "{plot}", + .replaceAll(Captions.GAMEMODE_WAS_BYPASSED.getTranslated(), + "{plot}", plot.getId(), "{gamemode}", guestGamemodeFlag.get())); } } } Optional timeFlag = plot.getFlag(Flags.TIME); - if (timeFlag.isPresent()) { + if (timeFlag.isPresent() && !player.getAttribute("disabletime")) { try { long time = timeFlag.get(); player.setTime(time); @@ -126,21 +147,21 @@ public class PlotListener { Optional musicFlag = plot.getFlag(Flags.MUSIC); if (musicFlag.isPresent()) { final String id = musicFlag.get(); - final PlotBlock block = PlotBlock.get(id); - final String rawId = block.getRawId().toString(); - if (rawId.contains("disc") || PlotBlock.isEverything(block) || block.isAir()) { - Location loc = player.getLocation(); - Location lastLoc = player.getMeta("music"); - if (lastLoc != null) { - player.playMusic(lastLoc, PlotBlock.get("air")); - if (PlotBlock.isEverything(block) || block.isAir()) { + final ItemType item = ItemUtil.get(id); + final String rawId = item.getId(); + if (rawId.contains("disc") || item == ItemTypes.AIR) { + Location location = player.getLocation(); + Location lastLocation = player.getMeta("music"); + if (lastLocation != null) { + player.playMusic(lastLocation, item); + if (item == ItemTypes.AIR) { player.deleteMeta("music"); } } - if (!(PlotBlock.isEverything(block) || block.isAir())) { + if (item != ItemTypes.AIR) { try { - player.setMeta("music", loc); - player.playMusic(loc, block); + player.setMeta("music", location); + player.playMusic(location, item); } catch (Exception ignored) { } } @@ -149,14 +170,14 @@ public class PlotListener { Location lastLoc = player.getMeta("music"); if (lastLoc != null) { player.deleteMeta("music"); - player.playMusic(lastLoc, PlotBlock.get("air")); + player.playMusic(lastLoc, ItemTypes.AIR); } } CommentManager.sendTitle(player, plot); } - if (titles) { - if (!Captions.TITLE_ENTERED_PLOT.s().isEmpty() || !Captions.TITLE_ENTERED_PLOT_SUB - .s().isEmpty()) { + if (titles && !player.getAttribute("disabletitles")) { + if (!Captions.TITLE_ENTERED_PLOT.getTranslated().isEmpty() + || !Captions.TITLE_ENTERED_PLOT_SUB.getTranslated().isEmpty()) { TaskManager.runTaskLaterAsync(() -> { Plot lastPlot = player.getMeta(PlotPlayer.META_LAST_PLOT); if ((lastPlot != null) && plot.getId().equals(lastPlot.getId())) { @@ -168,10 +189,12 @@ public class PlotListener { replacements.put("%alias", plot.toString()); replacements.put("%s", MainUtil.getName(plot.getOwner())); String main = StringMan - .replaceFromMap(Captions.TITLE_ENTERED_PLOT.s(), replacements); + .replaceFromMap(Captions.TITLE_ENTERED_PLOT.getTranslated(), + replacements); String sub = StringMan - .replaceFromMap(Captions.TITLE_ENTERED_PLOT_SUB.s(), replacements); - AbstractTitle.sendTitle(player, main, sub); + .replaceFromMap(Captions.TITLE_ENTERED_PLOT_SUB.getTranslated(), + replacements); + player.sendTitle(main, sub); } }, 20); } @@ -189,7 +212,9 @@ public class PlotListener { if (pw == null) { return true; } - if (Flags.DENY_EXIT.isTrue(plot) && !player.getMeta("kick", false)) { + if (Flags.DENY_EXIT.isTrue(plot) + && !Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_EXIT_DENIED) + && !player.getMeta("kick", false)) { if (previous != null) { player.setMeta(PlotPlayer.META_LAST_PLOT, previous); } @@ -202,14 +227,14 @@ public class PlotListener { player.setGameMode(pw.GAMEMODE); } else { MainUtil.sendMessage(player, StringMan - .replaceAll(Captions.GAMEMODE_WAS_BYPASSED.s(), "{plot}", - plot.toString(), "{gamemode}", pw.GAMEMODE.name().toLowerCase())); + .replaceAll(Captions.GAMEMODE_WAS_BYPASSED.getTranslated(), "{plot}", + plot.toString(), "{gamemode}", pw.GAMEMODE.getName().toLowerCase())); } } } Optional farewell = plot.getFlag(Flags.FAREWELL); farewell.ifPresent(s -> MainUtil - .format(Captions.PREFIX_FAREWELL.s() + s, plot, player, false, + .format(Captions.PREFIX_FAREWELL.getTranslated() + s, plot, player, false, new RunnableVal() { @Override public void run(String value) { MainUtil.sendMessage(player, value); @@ -221,8 +246,8 @@ public class PlotListener { for (UUID uuid : plot.getOwners()) { PlotPlayer owner = UUIDHandler.getPlayer(uuid); if ((owner != null) && !owner.getUUID().equals(player.getUUID())) { - MainUtil.sendMessage(owner, - Captions.NOTIFY_LEAVE.s().replace("%player", player.getName()) + MainUtil.sendMessage(owner, Captions.NOTIFY_LEAVE.getTranslated() + .replace("%player", player.getName()) .replace("%plot", plot.getId().toString())); } } @@ -234,8 +259,8 @@ public class PlotListener { ByteArrayUtilities.bytesToBoolean(player.getPersistentMeta("flight"))); player.removePersistentMeta("flight"); } else { - PlotGameMode gameMode = player.getGameMode(); - if (gameMode == PlotGameMode.SURVIVAL || gameMode == PlotGameMode.ADVENTURE) { + GameMode gameMode = player.getGameMode(); + if (gameMode == GameModes.SURVIVAL || gameMode == GameModes.ADVENTURE) { player.setFlight(false); } else if (!player.getFlight()) { player.setFlight(true); @@ -253,7 +278,7 @@ public class PlotListener { Location lastLoc = player.getMeta("music"); if (lastLoc != null) { player.deleteMeta("music"); - player.playMusic(lastLoc, PlotBlock.get("air")); + player.playMusic(lastLoc, ItemTypes.AIR); } } return true; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/ProcessedWEExtent.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/ProcessedWEExtent.java index 21014db70..fc7f95d11 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/ProcessedWEExtent.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/ProcessedWEExtent.java @@ -3,7 +3,6 @@ package com.github.intellectualsites.plotsquared.plot.listener; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; @@ -12,6 +11,7 @@ import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.NullExtent; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; @@ -19,11 +19,11 @@ import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import java.lang.reflect.Field; -import java.util.HashSet; +import java.util.Set; public class ProcessedWEExtent extends AbstractDelegateExtent { - private final HashSet mask; + private final Set mask; private final String world; private final int max; int BScount = 0; @@ -33,7 +33,7 @@ public class ProcessedWEExtent extends AbstractDelegateExtent { private int count; private Extent parent; - public ProcessedWEExtent(String world, HashSet mask, int max, Extent child, + public ProcessedWEExtent(String world, Set mask, int max, Extent child, Extent parent) { super(child); this.mask = mask; @@ -107,7 +107,7 @@ public class ProcessedWEExtent extends AbstractDelegateExtent { if (this.BScount > Settings.Chunk_Processor.MAX_TILES) { this.BSblocked = true; PlotSquared.debug( - Captions.PREFIX + "&cdetected unsafe WorldEdit: " + location.getX() + "," + Captions.PREFIX + "&cDetected unsafe WorldEdit: " + location.getX() + "," + location.getZ()); } if (WEManager @@ -162,7 +162,7 @@ public class ProcessedWEExtent extends AbstractDelegateExtent { if (this.Ecount > Settings.Chunk_Processor.MAX_ENTITIES) { this.Eblocked = true; PlotSquared.debug( - Captions.PREFIX + "&cdetected unsafe WorldEdit: " + location.getBlockX() + "," + Captions.PREFIX + "&cDetected unsafe WorldEdit: " + location.getBlockX() + "," + location.getBlockZ()); } if (WEManager.maskContains(this.mask, location.getBlockX(), location.getBlockY(), diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WEExtent.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WEExtent.java index 073819fa3..c9a414ed0 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WEExtent.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WEExtent.java @@ -1,6 +1,5 @@ package com.github.intellectualsites.plotsquared.plot.listener; -import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; @@ -8,6 +7,7 @@ import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; @@ -15,15 +15,15 @@ import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; -import java.util.HashSet; +import java.util.Set; public class WEExtent extends AbstractDelegateExtent { public static BlockState AIRSTATE = BlockTypes.AIR.getDefaultState(); public static BaseBlock AIRBASE = BlockTypes.AIR.getDefaultState().toBaseBlock(); - private final HashSet mask; + private final Set mask; - public WEExtent(HashSet mask, Extent extent) { + public WEExtent(Set mask, Extent extent) { super(extent); this.mask = mask; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WEManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WEManager.java index 0d80cab31..8d0081273 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WEManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WEManager.java @@ -3,62 +3,69 @@ package com.github.intellectualsites.plotsquared.plot.listener; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.Flags; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.world.RegionUtil; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; import java.util.HashSet; +import java.util.Set; import java.util.UUID; public class WEManager { - public static boolean maskContains(HashSet mask, int x, int y, int z) { - for (RegionWrapper region : mask) { - if (region.isIn(x, y, z)) { + public static boolean maskContains(Set mask, int x, int y, int z) { + for (CuboidRegion region : mask) { + if (RegionUtil.contains(region, x, y, z)) { return true; } } return false; } - public static boolean maskContains(HashSet mask, int x, int z) { - for (RegionWrapper region : mask) { - if (region.isIn(x, z)) { + public static boolean maskContains(Set mask, int x, int z) { + for (CuboidRegion region : mask) { + if (RegionUtil.contains(region, x, z)) { return true; } } return false; } - public static boolean maskContains(HashSet mask, double dx, double dy, + public static boolean maskContains(Set mask, double dx, double dy, double dz) { int x = Math.toIntExact(Math.round(dx >= 0 ? dx - 0.5 : dx + 0.5)); int y = Math.toIntExact(Math.round(dy - 0.5)); int z = Math.toIntExact(Math.round(dz >= 0 ? dz - 0.5 : dz + 0.5)); - for (RegionWrapper region : mask) { - if (region.isIn(x, y, z)) { + for (CuboidRegion region : mask) { + if (RegionUtil.contains(region, x, y, z)) { return true; } } return false; } - public static boolean maskContains(HashSet mask, double dx, double dz) { + public static boolean maskContains(Set mask, double dx, double dz) { int x = Math.toIntExact(Math.round(dx >= 0 ? dx - 0.5 : dx + 0.5)); int z = Math.toIntExact(Math.round(dz >= 0 ? dz - 0.5 : dz + 0.5)); - for (RegionWrapper region : mask) { - if (region.isIn(x, z)) { + for (CuboidRegion region : mask) { + if (RegionUtil.contains(region, x, z)) { return true; } } return false; } - public static HashSet getMask(PlotPlayer player) { - HashSet regions = new HashSet<>(); + public static HashSet getMask(PlotPlayer player) { + HashSet regions = new HashSet<>(); UUID uuid = player.getUUID(); Location location = player.getLocation(); String world = location.getWorld(); if (!PlotSquared.get().hasPlotArea(world)) { - regions.add(new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, + regions.add(RegionUtil.createRegion(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE)); return regions; } @@ -68,17 +75,16 @@ public class WEManager { } boolean allowMember = player.hasPermission("plots.worldedit.member"); Plot plot = player.getCurrentPlot(); - HashSet allowed = new HashSet<>(); if (plot == null) { plot = player.getMeta("WorldEditRegionPlot"); } if (plot != null && (!Settings.Done.RESTRICT_BUILDING || !Flags.DONE.isSet(plot)) && ( (allowMember && plot.isAdded(uuid)) || (!allowMember && (plot.isOwner(uuid)) || plot .getTrusted().contains(uuid))) && !(Flags.NO_WORLDEDIT.isTrue(plot))) { - for (RegionWrapper region : plot.getRegions()) { - RegionWrapper copy = - new RegionWrapper(region.minX, region.maxX, area.MIN_BUILD_HEIGHT, - area.MAX_BUILD_HEIGHT, region.minZ, region.maxZ); + for (CuboidRegion region : plot.getRegions()) { + BlockVector3 pos1 = region.getMinimumPoint().withY(area.MIN_BUILD_HEIGHT); + BlockVector3 pos2 = region.getMaximumPoint().withY(area.MAX_BUILD_HEIGHT); + CuboidRegion copy = new CuboidRegion(pos1, pos2); regions.add(copy); } player.setMeta("WorldEditRegionPlot", plot); @@ -86,12 +92,12 @@ public class WEManager { return regions; } - public static boolean intersects(RegionWrapper region1, RegionWrapper region2) { - return region1.intersects(region2); + public static boolean intersects(CuboidRegion region1, CuboidRegion region2) { + return RegionUtil.intersects(region1, region2); } - public static boolean regionContains(RegionWrapper selection, HashSet mask) { - for (RegionWrapper region : mask) { + public static boolean regionContains(CuboidRegion selection, HashSet mask) { + for (CuboidRegion region : mask) { if (intersects(region, selection)) { return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WESubscriber.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WESubscriber.java index 8b3c5c624..753ec2a20 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WESubscriber.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/listener/WESubscriber.java @@ -5,7 +5,6 @@ import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.Permissions; import com.sk89q.worldedit.WorldEdit; @@ -13,48 +12,51 @@ import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.extent.EditSessionEvent; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extent.NullExtent; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.eventbus.EventHandler.Priority; import com.sk89q.worldedit.util.eventbus.Subscribe; import com.sk89q.worldedit.world.World; -import java.util.HashSet; +import java.util.Set; public class WESubscriber { @Subscribe(priority = Priority.VERY_EARLY) public void onEditSession(EditSessionEvent event) { - WorldEdit worldedit = PlotSquared.get().worldedit; - if (worldedit == null) { + if (!Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) { WorldEdit.getInstance().getEventBus().unregister(this); return; } World worldObj = event.getWorld(); + if (worldObj == null) { + return; + } String world = worldObj.getName(); Actor actor = event.getActor(); if (actor != null && actor.isPlayer()) { String name = actor.getName(); - PlotPlayer pp = PlotPlayer.wrap(name); - HashSet mask; - if (pp == null) { + PlotPlayer plotPlayer = PlotPlayer.wrap(name); + Set mask; + if (plotPlayer == null) { Player player = (Player) actor; - Location loc = player.getLocation(); + Location location = player.getLocation(); com.github.intellectualsites.plotsquared.plot.object.Location pLoc = new com.github.intellectualsites.plotsquared.plot.object.Location( - player.getWorld().getName(), loc.getBlockX(), loc.getBlockX(), - loc.getBlockZ()); + player.getWorld().getName(), location.getBlockX(), location.getBlockX(), + location.getBlockZ()); Plot plot = pLoc.getPlot(); if (plot == null) { event.setExtent(new NullExtent()); return; } mask = plot.getRegions(); - } else if (pp.getAttribute("worldedit")) { + } else if (plotPlayer.getAttribute("worldedit")) { return; } else { - mask = WEManager.getMask(pp); + mask = WEManager.getMask(plotPlayer); if (mask.isEmpty()) { - if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) { - MainUtil.sendMessage(pp, Captions.WORLDEDIT_BYPASS); + if (Permissions.hasPermission(plotPlayer, "plots.worldedit.bypass")) { + MainUtil.sendMessage(plotPlayer, Captions.WORLDEDIT_BYPASS); } if (PlotSquared.get().hasPlotArea(world)) { event.setExtent(new NullExtent()); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/BlockBucket.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/BlockBucket.java index e357de0b7..447ef0142 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/BlockBucket.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/BlockBucket.java @@ -2,38 +2,59 @@ package com.github.intellectualsites.plotsquared.plot.object; import com.github.intellectualsites.plotsquared.configuration.serialization.ConfigurationSerializable; import com.github.intellectualsites.plotsquared.plot.config.Configuration; -import com.github.intellectualsites.plotsquared.plot.object.collection.RandomCollection; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.world.BlockUtil; +import com.github.intellectualsites.plotsquared.plot.util.world.PatternUtil; import com.google.common.collect.ImmutableMap; +import com.sk89q.worldedit.function.pattern.BlockPattern; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockType; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; -import java.util.*; -import java.util.Map.Entry; +import java.util.Arrays; +import java.util.Map; +import java.util.regex.Matcher; /** * A block bucket is a container of block types, where each block * has a specified chance of being randomly picked */ -@EqualsAndHashCode @SuppressWarnings({"unused", "WeakerAccess"}) public final class BlockBucket - implements Iterable, ConfigurationSerializable { +@EqualsAndHashCode(of = {"input"}) @SuppressWarnings({"unused", "WeakerAccess"}) +public final class BlockBucket implements ConfigurationSerializable { + private boolean compiled; - private final Random random = new Random(); - private final Map blocks; + private StringBuilder input; + private BlockState single; + private Pattern pattern; - private final BucketIterator bucketIterator = new BucketIterator(); - private boolean compiled, singleItem; - private PlotBlock head; - - private RandomCollection randomBlocks; - private PlotBlock single; - - public BlockBucket() { - this.blocks = new HashMap<>(); + public BlockBucket(BlockType type) { + this(type.getId()); + this.single = type.getDefaultState(); + this.pattern = new BlockPattern(this.single); + this.compiled = true; } - public static BlockBucket withSingle(@NonNull final PlotBlock block) { + public BlockBucket(BlockState state) { + this(state.getAsString()); + this.single = state; + this.pattern = new BlockPattern(this.single); + this.compiled = true; + } + + public BlockBucket(String input) { + this.input = new StringBuilder(input); + } + + public BlockBucket() { + this.input = new StringBuilder(); + } + + public static BlockBucket withSingle(@NonNull final BlockState block) { final BlockBucket blockBucket = new BlockBucket(); blockBucket.addBlock(block, 100); return blockBucket; @@ -46,140 +67,93 @@ import java.util.Map.Entry; return Configuration.BLOCK_BUCKET.parseString(map.get("blocks").toString()); } - public void addBlock(@NonNull final PlotBlock block) { + public void addBlock(@NonNull final BlockState block) { this.addBlock(block, -1); } - public void addBlock(@NonNull final PlotBlock block, final int chance) { + public void addBlock(@NonNull final BlockState block, final int chance) { addBlock(block, (double) chance); } - private void addBlock(@NonNull final PlotBlock block, double chance) { - if (chance == -1) - chance = 1; - this.blocks.put(block, chance); + private void addBlock(@NonNull final BlockState block, double chance) { + if (chance == -1) chance = 1; + String prefix = input.length() == 0 ? "" : ","; + input.append(prefix).append(chance).append("%").append(prefix); this.compiled = false; - if (head == null) { - head = block; - } } public boolean isEmpty() { - return blocks.isEmpty(); + return input == null || input.length() == 0; } - /** - * Get all blocks that are configured in the bucket - * - * @return Immutable collection containing all blocks that can - * be found in the bucket - */ - public Collection getBlocks() { - if (!isCompiled()) { - this.compile(); - } - return Collections.unmodifiableCollection(this.blocks.keySet()); - } - - /** - * Get a collection containing a specified amount of randomly selected blocks - * - * @param count Number of blocks - * @return Immutable collection containing randomly selected blocks - */ - public Collection getBlocks(final int count) { - return Arrays.asList(getBlockArray(count)); - } - - /** - * Get an array containing a specified amount of randomly selected blocks - * - * @param count Number of blocks - * @return Immutable collection containing randomly selected blocks - */ - public PlotBlock[] getBlockArray(final int count) { - final PlotBlock[] blocks = new PlotBlock[count]; - if (this.singleItem) { - Arrays.fill(blocks, 0, count, getBlock()); - } else { - for (int i = 0; i < count; i++) { - blocks[i] = getBlock(); - } - } - return blocks; - } - - public boolean hasSingleItem() { - return this.singleItem; - } + private static java.util.regex.Pattern regex = java.util.regex.Pattern.compile("((?[A-Za-z_]+):)?(?([A-Za-z_]+(\\[?[\\S\\s]+\\])?))(:(?[0-9]{1,3}))?"); public void compile() { if (isCompiled()) { return; } - this.compiled = true; - switch (blocks.size()) { - case 0: - single = null; - this.randomBlocks = null; - break; - case 1: - single = blocks.keySet().iterator().next(); - this.randomBlocks = null; - break; - default: - single = null; - this.randomBlocks = RandomCollection.of(blocks, random); - break; + String string = this.input.toString(); + if (string.isEmpty()) { + this.single = null; + this.pattern = null; + return; } - } - - @Override public Iterator iterator() { - return this.bucketIterator; + // Convert legacy format + boolean legacy = false; + String[] blocksStr = string.split(",(?![^\\(\\[]*[\\]\\)])"); + if (blocksStr.length == 1) { + try { + Matcher matcher = regex.matcher(string); + if (matcher.find()) { + String chanceStr = matcher.group("chance"); + String block = matcher.group("block"); + if (chanceStr != null && block != null && !MathMan.isInteger(block) && MathMan.isInteger(chanceStr)) { + String namespace = matcher.group("namespace"); + string = (namespace == null ? "" : namespace + ":") + block; + } + } + this.single = BlockUtil.get(string); + this.pattern = new BlockPattern(single); + return; + } catch (Exception ignore) { } + } + for (int i = 0; i < blocksStr.length; i++) { + String entry = blocksStr[i]; + Matcher matcher = regex.matcher(entry); + if (matcher.find()) { + String chanceStr = matcher.group("chance"); + if (chanceStr != null && MathMan.isInteger(chanceStr)) { + String[] parts = entry.split(":"); + parts = Arrays.copyOf(parts, parts.length - 1); + entry = chanceStr + "%" + StringMan.join(parts, ":"); + blocksStr[i] = entry; + legacy = true; + } + } + } + if (legacy) { + string = StringMan.join(blocksStr, ","); + } + pattern = PatternUtil.parse(null, string); } public boolean isCompiled() { return this.compiled; } - /** - * Get a random block out of the bucket - * - * @return Randomly picked block (cased on specified rates) - */ - public PlotBlock getBlock() { - if (!isCompiled()) { - this.compile(); - } - if (single != null) { - return single; - } - if (randomBlocks != null) { - return randomBlocks.next(); - } - return StringPlotBlock.EVERYTHING; + public Pattern toPattern() { + this.compile(); + return this.pattern; } @Override public String toString() { - if (!isCompiled()) { - compile(); - } - final StringBuilder builder = new StringBuilder(); - Iterator> iter = blocks.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - PlotBlock block = entry.getKey(); - builder.append(block.getRawId()); - Double weight = entry.getValue(); - if (weight != 1) { - builder.append(":").append(weight.intValue()); - } - if (iter.hasNext()) { - builder.append(","); - } - } - return builder.toString(); + return input.toString(); + } + + public boolean isAir() { + compile(); + return isEmpty() || (single != null && single.getBlockType().getMaterial().isAir()); } @Override public Map serialize() { @@ -189,8 +163,7 @@ import java.util.Map.Entry; return ImmutableMap.of("blocks", this.toString()); } - - @Getter @EqualsAndHashCode @RequiredArgsConstructor private final static class Range { + @Getter @EqualsAndHashCode @RequiredArgsConstructor private static final class Range { private final int min; private final int max; @@ -204,16 +177,4 @@ import java.util.Map.Entry; return num <= max && num >= min; } } - - - private final class BucketIterator implements Iterator { - - @Override public boolean hasNext() { - return true; - } - - @Override public PlotBlock next() { - return getBlock(); - } - } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/BlockLoc.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/BlockLoc.java index d170054a8..a4f02a9ef 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/BlockLoc.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/BlockLoc.java @@ -2,12 +2,12 @@ package com.github.intellectualsites.plotsquared.plot.object; public class BlockLoc { - public final int x; - public final int y; - public final int z; + private final int x; + private final int y; + private final int z; - public final float yaw; - public final float pitch; + private final float yaw; + private final float pitch; public BlockLoc(int x, int y, int z, float yaw, float pitch) { this.x = x; @@ -27,10 +27,6 @@ public class BlockLoc { float yaw; float pitch; - if (parts.length == 3) { - yaw = 0f; - pitch = 0f; - } if (parts.length == 5) { yaw = Float.parseFloat(parts[3]); pitch = Float.parseFloat(parts[4]); @@ -47,9 +43,9 @@ public class BlockLoc { @Override public int hashCode() { int prime = 31; int result = 1; - result = prime * result + this.x; - result = prime * result + this.y; - result = prime * result + this.z; + result = prime * result + this.getX(); + result = prime * result + this.getY(); + result = prime * result + this.getZ(); return result; } @@ -58,20 +54,42 @@ public class BlockLoc { return true; } if (obj == null) { - return this.x == 0 && this.y == 0 && this.z == 0; + return this.getX() == 0 && this.getY() == 0 && this.getZ() == 0; } if (getClass() != obj.getClass()) { return false; } BlockLoc other = (BlockLoc) 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(); } @Override public String toString() { - if (this.x == 0 && this.y == 0 && this.z == 0) { + if (this.getX() == 0 && this.getY() == 0 && this.getZ() == 0) { return ""; } - return this.x + "," + this.y + ',' + this.z + ',' + this.yaw + ',' + this.pitch; + return this.getX() + "," + this.getY() + ',' + this.getZ() + ',' + this.getYaw() + + ',' + this.getPitch(); } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + public int getZ() { + return z; + } + + public float getYaw() { + return yaw; + } + + public float getPitch() { + return pitch; + } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/BlockRegistry.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/BlockRegistry.java deleted file mode 100644 index e125ca188..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/BlockRegistry.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.object; - -import lombok.Getter; -import lombok.NonNull; - -import java.util.HashMap; -import java.util.Map; - -public abstract class BlockRegistry { - - @Getter private final Class type; - private final Map map = new HashMap<>(); - - public BlockRegistry(@NonNull final Class type, final T... preInitializedItems) { - this.type = type; - for (final T preInitializedItem : preInitializedItems) { - this.addMapping(getPlotBlock(preInitializedItem), preInitializedItem); - } - } - - public final void addMapping(@NonNull final PlotBlock plotBlock, @NonNull final T t) { - if (map.containsKey(plotBlock)) { - return; - } - this.map.put(plotBlock, t); - } - - public abstract PlotBlock getPlotBlock(final T item); - - public final T getItem(final PlotBlock plotBlock) { - return this.map.get(plotBlock); - } - -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/ChunkLoc.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/ChunkLoc.java deleted file mode 100644 index 2035a8811..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/ChunkLoc.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.object; - -public class ChunkLoc { - - public int x; - public int z; - - public ChunkLoc(int x, int z) { - this.x = x; - this.z = z; - } - - @Override public int hashCode() { - return (x << 16) | (z & 0xFFFF); - } - - @Override public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - ChunkLoc other = (ChunkLoc) obj; - return (this.x == other.x) && (this.z == other.z); - } - - @Override public String toString() { - return this.x + "," + this.z; - } -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/ConsolePlayer.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/ConsolePlayer.java index 6f386b3cb..d22e23a7e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/ConsolePlayer.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/ConsolePlayer.java @@ -3,10 +3,14 @@ package com.github.intellectualsites.plotsquared.plot.object; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.commands.RequiredType; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; -import com.github.intellectualsites.plotsquared.plot.util.PlotGameMode; import com.github.intellectualsites.plotsquared.plot.util.PlotWeather; +import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.world.gamemode.GameMode; +import com.sk89q.worldedit.world.gamemode.GameModes; +import com.sk89q.worldedit.world.item.ItemType; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.UUID; public class ConsolePlayer extends PlotPlayer { @@ -15,15 +19,15 @@ public class ConsolePlayer extends PlotPlayer { private ConsolePlayer() { PlotArea area = PlotSquared.get().getFirstPlotArea(); - Location loc; + Location location; if (area != null) { - RegionWrapper region = area.getRegion(); - loc = new Location(area.worldname, region.minX + region.maxX / 2, 0, - region.minZ + region.maxZ / 2); + CuboidRegion region = area.getRegion(); + location = new Location(area.worldname, region.getMinimumPoint().getX() + region.getMaximumPoint().getX() / 2, 0, + region.getMinimumPoint().getZ() + region.getMaximumPoint().getZ() / 2); } else { - loc = new Location("world", 0, 0, 0); + location = new Location("world", 0, 0, 0); } - setMeta("location", loc); + setMeta("location", location); } public static ConsolePlayer getConsole() { @@ -34,11 +38,19 @@ public class ConsolePlayer extends PlotPlayer { return instance; } - @Override public boolean canTeleport(Location loc) { + @Override public Actor toActor() { + return PlotSquared.get().IMP.getConsole(); + } + + @Override public boolean canTeleport(@NotNull Location location) { return true; } - @Override public Location getLocation() { + @Override + public void sendTitle(String title, String subtitle, int fadeIn, int stay, int fadeOut) { + } + + @NotNull @Override public Location getLocation() { return this.getMeta("location"); } @@ -46,7 +58,7 @@ public class ConsolePlayer extends PlotPlayer { return getLocation(); } - @Nonnull @Override public UUID getUUID() { + @NotNull @Override public UUID getUUID() { return DBFunc.EVERYONE; } @@ -96,14 +108,14 @@ public class ConsolePlayer extends PlotPlayer { return RequiredType.CONSOLE; } - @Override public void setWeather(PlotWeather weather) { + @Override public void setWeather(@NotNull PlotWeather weather) { } - @Override public PlotGameMode getGameMode() { - return PlotGameMode.NOT_SET; + @Override public @NotNull GameMode getGameMode() { + return GameModes.SPECTATOR; } - @Override public void setGameMode(PlotGameMode gameMode) { + @Override public void setGameMode(@NotNull GameMode gameMode) { } @Override public void setTime(long time) { @@ -116,7 +128,7 @@ public class ConsolePlayer extends PlotPlayer { @Override public void setFlight(boolean fly) { } - @Override public void playMusic(Location location, PlotBlock id) { + @Override public void playMusic(@NotNull Location location, @NotNull ItemType id) { } @Override public void kick(String message) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Direction.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Direction.java index 0c7de4905..3c3900dc1 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Direction.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Direction.java @@ -1,9 +1,9 @@ package com.github.intellectualsites.plotsquared.plot.object; public enum Direction { - NORTH(0, "north"), EAST(1, "east"), SOUTH(2, "south"), WEST(3, "west"), NORTHEAST(4, - "northeast"), SOUTHEAST(5, "southeast"), SOUTHWEST(6, "southwest"), NORTHWEST(7, - "northwest"), + ALL(-1, "all"), NORTH(0, "north"), EAST(1, "east"), SOUTH(2, "south"), WEST(3, + "west"), NORTHEAST(4, "northeast"), SOUTHEAST(5, "southeast"), SOUTHWEST(6, + "southwest"), NORTHWEST(7, "northwest"), ; @@ -16,6 +16,15 @@ public enum Direction { this.name = name; } + public static Direction getFromIndex(int index) { + for (Direction value : values()) { + if (value.getIndex() == index) { + return value; + } + } + return NORTH; + } + public int getIndex() { return index; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/LazyBlock.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/LazyBlock.java index 3413bd235..9f3345a83 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/LazyBlock.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/LazyBlock.java @@ -1,10 +1,12 @@ package com.github.intellectualsites.plotsquared.plot.object; +import com.sk89q.worldedit.world.block.BlockState; + public abstract class LazyBlock { - public abstract StringPlotBlock getPlotBlock(); + public abstract BlockState getBlockState(); public String getId() { - return getPlotBlock().getItemId(); + return getBlockState().toString(); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/LegacyPlotBlock.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/LegacyPlotBlock.java deleted file mode 100644 index be551b372..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/LegacyPlotBlock.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.object; - -import lombok.Getter; - -public class LegacyPlotBlock extends PlotBlock { - - public static final PlotBlock EVERYTHING = new LegacyPlotBlock((short) 0, (byte) 0); - public static final PlotBlock[] CACHE = new PlotBlock[65535]; - - static { - for (int i = 0; i < 65535; i++) { - short id = (short) (i >> 4); - byte data = (byte) (i & 15); - CACHE[i] = new LegacyPlotBlock(id, data); - } - } - - @Getter public final short id; - @Getter public final byte data; - - public LegacyPlotBlock(short id, byte data) { - this.id = id; - this.data = data; - } - - @Override public Object getRawId() { - return this.id; - } - - @Override public boolean isAir() { - return this.id == 0; - } - - @Override public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - LegacyPlotBlock other = (LegacyPlotBlock) obj; - return (this.id == other.id) && ((this.data == other.data) || (this.data == -1) || ( - other.data == -1)); - } - - @Override public int hashCode() { - return this.id; - } - - @Override public String toString() { - if (this.data == -1) { - return this.id + ""; - } - return this.id + ":" + this.data; - } - -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Location.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Location.java index 2e28594df..9daad699d 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Location.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Location.java @@ -2,15 +2,16 @@ package com.github.intellectualsites.plotsquared.plot.object; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import lombok.Getter; import lombok.Setter; public class Location implements Cloneable, Comparable { - @Getter private int x; - @Getter private int y; - @Getter private int z; + private int x; + private int y; + private int z; @Getter @Setter private float yaw; @Getter @Setter private float pitch; @Getter @Setter private String world; @@ -26,14 +27,22 @@ public class Location implements Cloneable, Comparable { this.blockVector3 = BlockVector3.at(x, y, z); } - public Location() { - this.world = ""; - } - public Location(String world, int x, int y, int z) { this(world, x, y, z, 0f, 0f); } + public int getX() { + return this.x; + } + + public int getY() { + return this.y; + } + + public int getZ() { + return this.z; + } + public void setX(int x) { this.x = x; this.blockVector3 = BlockVector3.at(x, y, z); @@ -56,7 +65,8 @@ public class Location implements Cloneable, Comparable { this.z = blockVector3.getZ(); } - @Override public Location clone() { + @Override + public Location clone() { try { return (Location) super.clone(); } catch (CloneNotSupportedException e) { @@ -95,6 +105,10 @@ public class Location implements Cloneable, Comparable { return area != null && area.getPlotAbs(this) == null; } + /** + * Checks if anyone owns a plot at the current location. + * @return true if the location is a road, not a plot area, or if the plot is unclaimed. + */ public boolean isUnownedPlotArea() { PlotArea area = getPlotArea(); return area != null && area.getOwnedPlotAbs(this) == null; @@ -127,8 +141,8 @@ public class Location implements Cloneable, Comparable { } } - public ChunkLoc getChunkLoc() { - return new ChunkLoc(this.x >> 4, this.z >> 4); + public BlockVector2 getBlockVector2() { + return BlockVector2.at(this.x >> 4, this.z >> 4); } public Location add(int x, int y, int z) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Plot.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Plot.java index e2f83172e..5308e620a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Plot.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Plot.java @@ -1,5 +1,8 @@ package com.github.intellectualsites.plotsquared.plot.object; +import static java.util.concurrent.TimeUnit.SECONDS; + + import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Configuration; @@ -12,7 +15,16 @@ import com.github.intellectualsites.plotsquared.plot.generator.SquarePlotWorld; import com.github.intellectualsites.plotsquared.plot.listener.PlotListener; import com.github.intellectualsites.plotsquared.plot.object.comment.PlotComment; import com.github.intellectualsites.plotsquared.plot.object.schematic.Schematic; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; @@ -21,17 +33,34 @@ import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.function.pattern.Pattern; +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 com.sk89q.worldedit.world.block.BlockTypes; +import java.util.concurrent.TimeUnit; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.awt.geom.Area; import java.awt.geom.PathIterator; import java.awt.geom.Rectangle2D; import java.io.File; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @@ -45,14 +74,15 @@ import java.util.stream.Collectors; */ public class Plot { - private static final int MAX_HEIGHT = 256; + public static final int MAX_HEIGHT = 256; + /** * @deprecated raw access is deprecated */ - @Deprecated private static HashSet connected_cache; - private static HashSet regions_cache; + @Deprecated private static Set connected_cache; + private static Set regions_cache; - private final PlotId id; + @NotNull private final PlotId id; /** * plot owner @@ -62,10 +92,12 @@ public class Plot { * @deprecated */ @Deprecated public UUID owner; + /** * Has the plot changed since the last save cycle? */ public boolean countsTowardsMax = true; + /** * Represents whatever the database manager needs it to:
* - A value of -1 usually indicates the plot will not be stored in the DB
@@ -74,23 +106,28 @@ public class Plot { * @deprecated magical */ @Deprecated public int temp; + /** * Plot creation timestamp (not accurate if the plot was created before this was implemented)
* - Milliseconds since the epoch
*/ private long timestamp; + /** * List of trusted (with plot permissions). */ private HashSet trusted; + /** * List of members users (with plot permissions). */ private HashSet members; + /** * List of denied players. */ private HashSet denied; + /** * External settings class. * - Please favor the methods over direct access to this class
@@ -99,6 +136,7 @@ public class Plot { private PlotSettings settings; private PlotArea area; + /** * Session only plot metadata (session is until the server stops)
*
@@ -107,6 +145,7 @@ public class Plot { * @see FlagManager */ private ConcurrentHashMap meta; + /** * The cached origin plot. * - The origin plot is used for plot grouping and relational data @@ -117,12 +156,12 @@ public class Plot { * Constructor for a new plot. * (Only changes after plot.create() will be properly set in the database) * - * @param area the PlotArea where the plot is located - * @param id the plot id + * @param area the PlotArea where the plot is located + * @param id the plot id * @param owner the plot owner * @see Plot#getPlot(Location) for existing plots */ - public Plot(PlotArea area, PlotId id, UUID owner) { + public Plot(PlotArea area, @NotNull PlotId id, UUID owner) { this.area = area; this.id = id; this.owner = owner; @@ -133,10 +172,10 @@ public class Plot { * (Only changes after plot.create() will be properly set in the database) * * @param area the PlotArea where the plot is located - * @param id the plot id + * @param id the plot id * @see Plot#getPlot(Location) for existing plots */ - public Plot(PlotArea area, PlotId id) { + public Plot(PlotArea area, @NotNull PlotId id) { this.area = area; this.id = id; } @@ -146,13 +185,13 @@ public class Plot { * The database will ignore any queries regarding temporary plots. * Please note that some bulk plot management functions may still affect temporary plots (TODO: fix this) * - * @param area the PlotArea where the plot is located - * @param id the plot id + * @param area the PlotArea where the plot is located + * @param id the plot id * @param owner the owner of the plot - * @param temp Represents whatever the database manager needs it to + * @param temp Represents whatever the database manager needs it to * @see Plot#getPlot(Location) for existing plots */ - public Plot(PlotArea area, PlotId id, UUID owner, int temp) { + public Plot(PlotArea area, @NotNull PlotId id, UUID owner, int temp) { this.area = area; this.id = id; this.owner = owner; @@ -162,14 +201,14 @@ public class Plot { /** * Constructor for a saved plots (Used by the database manager when plots are fetched) * - * @param id the plot id - * @param owner the plot owner + * @param id the plot id + * @param owner the plot owner * @param trusted the plot trusted players - * @param denied the plot denied players - * @param merged array giving merged plots + * @param denied the plot denied players + * @param merged an array giving merged plots * @see Plot#getPlot(Location) for existing plots */ - public Plot(PlotId id, UUID owner, HashSet trusted, HashSet members, + public Plot(@NotNull PlotId id, UUID owner, HashSet trusted, HashSet members, HashSet denied, String alias, BlockLoc position, Collection flags, PlotArea area, boolean[] merged, long timestamp, int temp) { this.id = id; @@ -194,8 +233,8 @@ public class Plot { /** * Gets a plot from a string e.g. [area];[id] * - * @param defaultArea If no area is specified - * @param string plot id/area + id + * @param defaultArea if no area is specified + * @param string plot id/area + id * @return New or existing plot object */ public static Plot fromString(PlotArea defaultArea, String string) { @@ -326,7 +365,7 @@ public class Plot { * @param uuid the player uuid * @return if the provided uuid is the owner of the plot */ - public boolean isOwner(@Nonnull UUID uuid) { + public boolean isOwner(@NotNull UUID uuid) { if (uuid.equals(this.getOwner())) { return true; } @@ -452,7 +491,7 @@ public class Plot { * * @return the PlotId for this plot */ - public PlotId getId() { + @NotNull public PlotId getId() { return this.id; } @@ -779,7 +818,7 @@ public class Plot { /** * Sets the plot owner (and update the database) * - * @param owner uuid to set as owner + * @param owner uuid to set as owner * @param initiator player initiating set owner * @return boolean */ @@ -834,7 +873,7 @@ public class Plot { return false; } } - final HashSet regions = this.getRegions(); + final Set regions = this.getRegions(); final Set plots = this.getConnectedPlots(); final ArrayDeque queue = new ArrayDeque<>(plots); if (isDelete) { @@ -846,29 +885,36 @@ public class Plot { @Override public void run() { if (queue.isEmpty()) { Runnable run = () -> { - for (RegionWrapper region : regions) { - Location[] corners = region.getCorners(getWorldName()); + for (CuboidRegion region : regions) { + Location[] corners = MainUtil.getCorners(getWorldName(), region); ChunkManager.manager.clearAllEntities(corners[0], corners[1]); } TaskManager.runTask(whenDone); }; for (Plot current : plots) { if (isDelete || current.owner == null) { - manager.unClaimPlot(Plot.this.area, current, null); + manager.unClaimPlot(current, null); } else { - manager.claimPlot(Plot.this.area, current); + manager.claimPlot(current); } } - GlobalBlockQueue.IMP.addTask(run); + GlobalBlockQueue.IMP.addEmptyTask(run); return; } Plot current = queue.poll(); if (Plot.this.area.TERRAIN != 0) { - ChunkManager.manager - .regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, this); + try { + ChunkManager.manager + .regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, + this); + } catch (UnsupportedOperationException exception) { + MainUtil.sendMessage(null, + "Please ask md_5 to fix regenerateChunk() because it breaks plugins. We apologize for the inconvenience"); + return; + } return; } - manager.clearPlot(Plot.this.area, current, this); + manager.clearPlot(current, this); } }; run.run(); @@ -881,8 +927,8 @@ public class Plot { * @param biome The biome e.g. "forest" * @param whenDone The task to run when finished, or null */ - public void setBiome(final String biome, final Runnable whenDone) { - final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); + public void setBiome(final BiomeType biome, final Runnable whenDone) { + final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); final int extendBiome; if (area instanceof SquarePlotWorld) { extendBiome = (((SquarePlotWorld) area).ROAD_WIDTH > 0) ? 1 : 0; @@ -896,18 +942,24 @@ public class Plot { TaskManager.runTask(whenDone); return; } - RegionWrapper region = regions.poll(); - Location pos1 = new Location(getWorldName(), region.minX - extendBiome, region.minY, - region.minZ - extendBiome); - Location pos2 = new Location(getWorldName(), region.maxX + extendBiome, region.maxY, - region.maxZ + extendBiome); + CuboidRegion region = regions.poll(); + Location pos1 = new Location(getWorldName(), region.getMinimumPoint().getX() - extendBiome, region.getMinimumPoint().getY(), + region.getMinimumPoint().getZ() - extendBiome); + Location pos2 = new Location(getWorldName(), region.getMaximumPoint().getX() + extendBiome, region.getMaximumPoint().getY(), + region.getMaximumPoint().getZ() + extendBiome); ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { @Override public void run(int[] value) { - ChunkLoc loc = new ChunkLoc(value[0], value[1]); + BlockVector2 loc = BlockVector2.at(value[0], value[1]); + long start = System.currentTimeMillis(); ChunkManager.manager.loadChunk(getWorldName(), loc, false); + long end = System.currentTimeMillis(); + PlotSquared.debug("[Biome Operation] Loading chunk took: " + TimeUnit.MILLISECONDS.toSeconds(end - start)); MainUtil.setBiome(getWorldName(), value[2], value[3], value[4], value[5], biome); - ChunkManager.manager.unloadChunk(getWorldName(), loc, true, true); + start = System.currentTimeMillis(); + ChunkManager.manager.unloadChunk(getWorldName(), loc, true); + end = System.currentTimeMillis(); + PlotSquared.debug("[Biome Operation] Unloading chunk took: " + TimeUnit.MILLISECONDS.toSeconds(end - start)); } }, this, 5); @@ -919,8 +971,8 @@ public class Plot { /** * Unlink the plot and all connected plots. * - * @param createSign whether to recreate signs * @param createRoad whether to recreate road + * @param createSign whether to recreate signs * @return success/!cancelled */ public boolean unlinkPlot(boolean createRoad, boolean createSign) { @@ -943,20 +995,21 @@ public class Plot { } PlotManager manager = this.area.getPlotManager(); if (createRoad) { - manager.startPlotUnlink(this.area, ids); + manager.startPlotUnlink(ids); } if (this.area.TERRAIN != 3 && createRoad) { for (Plot current : plots) { if (current.getMerged(Direction.EAST)) { - manager.createRoadEast(current.area, current); - if (getMerged(Direction.SOUTH)) { - manager.createRoadSouth(current.area, current); - if (getMerged(Direction.SOUTHEAST)) { - manager.createRoadSouthEast(current.area, current); + manager.createRoadEast(current); + if (current.getMerged(Direction.SOUTH)) { + manager.createRoadSouth(current); + if (current.getMerged(Direction.SOUTHEAST)) { + manager.createRoadSouthEast(current); } } - } else if (getMerged(Direction.SOUTH)) { - manager.createRoadSouth(current.area, current); + } + if (current.getMerged(Direction.SOUTH)) { + manager.createRoadSouth(current); } } } @@ -965,14 +1018,14 @@ public class Plot { current.setMerged(merged); } if (createSign) { - GlobalBlockQueue.IMP.addTask(() -> { + GlobalBlockQueue.IMP.addEmptyTask(() -> { for (Plot current : plots) { current.setSign(MainUtil.getName(current.owner)); } }); } if (createRoad) { - manager.finishPlotUnlink(this.area, ids); + manager.finishPlotUnlink(ids); } return true; } @@ -982,7 +1035,7 @@ public class Plot { * * @param name name */ - public void setSign(@Nonnull String name) { + public void setSign(@NotNull String name) { if (!isLoaded()) { return; } @@ -992,7 +1045,7 @@ public class Plot { } PlotManager manager = this.area.getPlotManager(); if (this.area.ALLOW_SIGNS) { - Location loc = manager.getSignLoc(this.area, this); + Location location = manager.getSignLoc(this); String id = this.id.x + ";" + this.id.y; String[] lines = new String[] {Captions.OWNER_SIGN_LINE_1.formatted().replaceAll("%id%", id), @@ -1002,7 +1055,9 @@ public class Plot { "%plr%", name), Captions.OWNER_SIGN_LINE_4.formatted().replaceAll("%id%", id).replaceAll( "%plr%", name)}; - WorldUtil.IMP.setSign(this.getWorldName(), loc.getX(), loc.getY(), loc.getZ(), lines); + WorldUtil.IMP + .setSign(this.getWorldName(), location.getX(), location.getY(), location.getZ(), + lines); } } @@ -1074,7 +1129,7 @@ public class Plot { * Delete a plot (use null for the runnable if you don't need to be notified on completion) * * @see PlotSquared#removePlot(Plot, boolean) - * @see #clear(Runnable) to simply clear a plot + * @see #clear(boolean, boolean, Runnable) to simply clear a plot */ public boolean deletePlot(final Runnable whenDone) { if (!this.hasOwner()) { @@ -1199,28 +1254,28 @@ public class Plot { Location[] corners = getCorners(); Location top = corners[0]; Location bot = corners[1]; - Location loc = new Location(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), + Location location = + new Location(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ())); if (!isLoaded()) { - return loc; + return location; } - int y = - isLoaded() ? WorldUtil.IMP.getHighestBlock(getWorldName(), loc.getX(), loc.getZ()) : 62; + int y = WorldUtil.IMP.getHighestBlock(getWorldName(), location.getX(), location.getZ()); if (area.ALLOW_SIGNS) { - y = Math.max(y, getManager().getSignLoc(area, this).getY()); + y = Math.max(y, getManager().getSignLoc(this).getY()); } - loc.setY(1 + y); - return loc; + location.setY(1 + y); + return location; } public Location getSide() { - RegionWrapper largest = getLargestRegion(); - int x = (largest.maxX >> 1) - (largest.minX >> 1) + largest.minX; - int z = largest.minZ - 1; + CuboidRegion largest = getLargestRegion(); + int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX(); + int z = largest.getMinimumPoint().getZ() - 1; PlotManager manager = getManager(); int y = isLoaded() ? WorldUtil.IMP.getHighestBlock(getWorldName(), x, z) : 62; if (area.ALLOW_SIGNS && (y <= 0 || y >= 255)) { - y = Math.max(y, manager.getSignLoc(area, this).getY() - 1); + y = Math.max(y, manager.getSignLoc(this).getY() - 1); } return new Location(getWorldName(), x, y + 1, z); } @@ -1232,21 +1287,23 @@ public class Plot { */ public Location getHome() { BlockLoc home = this.getPosition(); - if (home == null || home.x == 0 && home.z == 0) { + if (home == null || home.getX() == 0 && home.getZ() == 0) { return this.getDefaultHome(true); } else { - Location bot = this.getBottomAbs(); - Location loc = new Location(bot.getWorld(), bot.getX() + home.x, bot.getY() + home.y, - bot.getZ() + home.z, home.yaw, home.pitch); + Location bottom = this.getBottomAbs(); + Location location = + new Location(bottom.getWorld(), bottom.getX() + home.getX(), bottom.getY() + home + .getY(), + bottom.getZ() + home.getZ(), home.getYaw(), home.getPitch()); if (!isLoaded()) { - return loc; + return location; } - if (!WorldUtil.IMP.getBlock(loc).isAir()) { - loc.setY(Math.max( - 1 + WorldUtil.IMP.getHighestBlock(this.getWorldName(), loc.getX(), loc.getZ()), - bot.getY())); + if (!WorldUtil.IMP.getBlock(location).getBlockType().getMaterial().isAir()) { + location.setY(Math.max(1 + WorldUtil.IMP + .getHighestBlock(this.getWorldName(), location.getX(), location.getZ()), + bottom.getY())); } - return loc; + return location; } } @@ -1286,9 +1343,9 @@ public class Plot { int z; if (loc.getX() == Integer.MAX_VALUE && loc.getZ() == Integer.MAX_VALUE) { // center - RegionWrapper largest = plot.getLargestRegion(); - x = (largest.maxX >> 1) - (largest.minX >> 1) + largest.minX; - z = (largest.maxZ >> 1) - (largest.minZ >> 1) + largest.minZ; + CuboidRegion largest = plot.getLargestRegion(); + x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX(); + z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ() >> 1) + largest.getMinimumPoint().getZ(); } else { // specific Location bot = plot.getBottomAbs(); @@ -1306,9 +1363,9 @@ public class Plot { public double getVolume() { double count = 0; - for (RegionWrapper region : getRegions()) { + for (CuboidRegion region : getRegions()) { count += - (region.maxX - (double) region.minX + 1) * (region.maxZ - (double) region.minZ + 1) + (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * (region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1) * MAX_HEIGHT; } return count; @@ -1360,9 +1417,7 @@ public class Plot { public Map getLikes() { final Map map = new HashMap<>(); final Map ratings = this.getRatings(); - ratings.forEach((uuid, rating) -> { - map.put(uuid, rating.getLike()); - }); + ratings.forEach((uuid, rating) -> map.put(uuid, rating.getLike())); return map; } @@ -1395,11 +1450,11 @@ public class Plot { */ public void refreshChunks() { LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(getWorldName(), false); - HashSet chunks = new HashSet<>(); - for (RegionWrapper region : Plot.this.getRegions()) { - for (int x = region.minX >> 4; x <= region.maxX >> 4; x++) { - for (int z = region.minZ >> 4; z <= region.maxZ >> 4; z++) { - if (chunks.add(new ChunkLoc(x, z))) { + HashSet chunks = new HashSet<>(); + for (CuboidRegion region : Plot.this.getRegions()) { + for (int x = region.getMinimumPoint().getX() >> 4; x <= region.getMaximumPoint().getX() >> 4; x++) { + for (int z = region.getMinimumPoint().getZ() >> 4; z <= region.getMaximumPoint().getZ() >> 4; z++) { + if (chunks.add(BlockVector2.at(x, z))) { queue.refreshChunk(x, z); } } @@ -1415,9 +1470,9 @@ public class Plot { if (!this.area.ALLOW_SIGNS) { return; } - Location loc = manager.getSignLoc(this.area, this); + Location location = manager.getSignLoc(this); LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(getWorldName(), false); - queue.setBlock(loc.getX(), loc.getY(), loc.getZ(), PlotBlock.get("air")); + queue.setBlock(location.getX(), location.getY(), location.getZ(), BlockTypes.AIR.getDefaultState()); queue.flush(); } @@ -1498,7 +1553,7 @@ public class Plot { } }); } - plotworld.getPlotManager().claimPlot(plotworld, this); + plotworld.getPlotManager().claimPlot(this); return true; } @@ -1512,7 +1567,7 @@ public class Plot { * @param notify notify * @return true if plot was created successfully */ - public boolean create(@Nonnull UUID uuid, final boolean notify) { + public boolean create(@NotNull UUID uuid, final boolean notify) { this.owner = uuid; Plot existing = this.area.getOwnedPlotAbs(this.id); if (existing != null) { @@ -1534,7 +1589,7 @@ public class Plot { DBFunc.createPlotAndSettings(this, () -> { PlotArea plotworld = Plot.this.area; if (notify && plotworld.AUTO_MERGE) { - Plot.this.autoMerge(-1, Integer.MAX_VALUE, uuid, true); + Plot.this.autoMerge(Direction.ALL, Integer.MAX_VALUE, uuid, true); } }); return true; @@ -1546,9 +1601,13 @@ public class Plot { * Sets components such as border, wall, floor. * (components are generator specific) */ + @Deprecated public boolean setComponent(String component, String blocks) { BlockBucket parsed = Configuration.BLOCK_BUCKET.parseString(blocks); - return !(parsed == null || parsed.isEmpty()) && this.setComponent(component, parsed); + if (parsed != null && parsed.isEmpty()) { + return false; + } + return this.setComponent(component, parsed.toPattern()); } /** @@ -1556,9 +1615,9 @@ public class Plot { * * @return the name of the biome */ - public String getBiome() { - Location loc = this.getCenter(); - return WorldUtil.IMP.getBiome(loc.getWorld(), loc.getX(), loc.getZ()); + public BiomeType getBiome() { + Location location = this.getCenter(); + return WorldUtil.IMP.getBiome(location.getWorld(), location.getX(), location.getZ()); } //TODO Better documentation needed. @@ -1567,7 +1626,7 @@ public class Plot { * Returns the top location for the plot. */ public Location getTopAbs() { - Location top = this.area.getPlotManager().getPlotTopLocAbs(this.area, this.id); + Location top = getManager().getPlotTopLocAbs(this.id); top.setWorld(getWorldName()); return top; } @@ -1578,9 +1637,9 @@ public class Plot { * Returns the bottom location for the plot. */ public Location getBottomAbs() { - Location loc = this.area.getPlotManager().getPlotBottomLocAbs(this.area, this.id); - loc.setWorld(getWorldName()); - return loc; + Location location = getManager().getPlotBottomLocAbs(this.id); + location.setWorld(getWorldName()); + return location; } /** @@ -1629,7 +1688,7 @@ public class Plot { /** * Moves the settings for a plot. * - * @param plot the plot to move + * @param plot the plot to move * @param whenDone * @return */ @@ -1669,7 +1728,7 @@ public class Plot { top.setZ(this.getRelative(Direction.SOUTH).getBottomAbs().getZ() - 1); } if (this.getMerged(Direction.EAST)) { - top.setX(this.getRelative(Direction.SOUTH).getBottomAbs().getX() - 1); + top.setX(this.getRelative(Direction.EAST).getBottomAbs().getX() - 1); } return top; } @@ -1726,7 +1785,7 @@ public class Plot { Location pos2 = new Location(this.getWorldName(), bot.getX(), MAX_HEIGHT, top.getZ()); ChunkManager.manager.regenerateRegion(pos1, pos2, true, null); } else { - this.area.getPlotManager().removeRoadEast(this.area, this); + this.area.getPlotManager().removeRoadEast(this); } } @@ -2011,17 +2070,11 @@ public class Plot { * Sets the raw merge data
* - Updates DB
* - Does not modify terrain
- * ----------
- * 0 = north
- * 1 = east
- * 2 = south
- * 3 = west
- * ----------
* * @param direction * @param value */ - public void setMerged(int direction, boolean value) { + public void setMerged(Direction direction, boolean value) { if (this.getSettings().setMerged(direction, value)) { if (value) { Plot other = this.getRelative(direction).getBasePlot(false); @@ -2126,11 +2179,12 @@ public class Plot { return null; } try { - final Location loc = this.getManager().getSignLoc(this.area, this); + final Location location = this.getManager().getSignLoc(this); String[] lines = TaskManager.IMP.sync(new RunnableVal() { @Override public void run(String[] value) { - ChunkManager.manager.loadChunk(loc.getWorld(), loc.getChunkLoc(), false); - this.value = WorldUtil.IMP.getSign(loc); + ChunkManager.manager + .loadChunk(location.getWorld(), location.getBlockVector2(), false); + this.value = WorldUtil.IMP.getSign(location); } }); if (lines == null) { @@ -2138,7 +2192,7 @@ public class Plot { } loop: for (int i = 4; i > 0; i--) { - String caption = Captions.valueOf("OWNER_SIGN_LINE_" + i).s(); + String caption = Captions.valueOf("OWNER_SIGN_LINE_" + i).getTranslated(); int index = caption.indexOf("%plr%"); if (index < 0) { continue; @@ -2195,45 +2249,42 @@ public class Plot { Location pos2 = new Location(this.getWorldName(), top.getX(), MAX_HEIGHT, bot.getZ()); ChunkManager.manager.regenerateRegion(pos1, pos2, true, null); } else { - this.getManager().removeRoadSouth(this.area, this); + this.getManager().removeRoadSouth(this); } } /** - * Auto merge a plot in a specific direction
+ * Auto merge a plot in a specific direction. * - * @param dir The direction to merge
- * -1 = All directions
- * 0 = north
- * 1 = east
- * 2 = south
- * 3 = west
- * @param max The max number of merges to do - * @param uuid The UUID it is allowed to merge with - * @param removeRoads Whether to remove roads + * @param dir the direction to merge + * @param max the max number of merges to do + * @param uuid the UUID it is allowed to merge with + * @param removeRoads whether to remove roads * @return true if a merge takes place */ - public boolean autoMerge(int dir, int max, UUID uuid, boolean removeRoads) { + public boolean autoMerge(Direction dir, int max, UUID uuid, boolean removeRoads) { + //Ignore merging if there is no owner for the plot if (this.owner == null) { return false; } - if (!EventUtil.manager.callMerge(this, dir, max)) { + //Call the merge event + if (!EventUtil.manager.callMerge(this, dir.getIndex(), max)) { return false; } - HashSet visited = new HashSet<>(); - HashSet merged; Set connected = this.getConnectedPlots(); - merged = connected.stream().map(Plot::getId).collect(Collectors.toCollection(HashSet::new)); + HashSet merged = + connected.stream().map(Plot::getId).collect(Collectors.toCollection(HashSet::new)); ArrayDeque frontier = new ArrayDeque<>(connected); Plot current; boolean toReturn = false; + HashSet visited = new HashSet<>(); while ((current = frontier.poll()) != null && max >= 0) { if (visited.contains(current)) { continue; } visited.add(current); Set plots; - if ((dir == -1 || dir == 0) && !getMerged(Direction.NORTH)) { + if ((dir == Direction.ALL || dir == Direction.NORTH) && !getMerged(Direction.NORTH)) { Plot other = current.getRelative(Direction.NORTH); if (other != null && other.isOwner(uuid) && ( other.getBasePlot(false).equals(current.getBasePlot(false)) @@ -2243,9 +2294,17 @@ public class Plot { merged.add(current.getId()); merged.add(other.getId()); toReturn = true; + + if (removeRoads) { + ArrayList ids = new ArrayList<>(); + ids.add(current.getId()); + ids.add(other.getId()); + this.getManager().finishPlotMerge(ids); + } } } - if (max >= 0 && (dir == -1 || dir == 1) && !current.getMerged(Direction.EAST)) { + if (max >= 0 && (dir == Direction.ALL || dir == Direction.EAST) && !current + .getMerged(Direction.EAST)) { Plot other = current.getRelative(Direction.EAST); if (other != null && other.isOwner(uuid) && ( other.getBasePlot(false).equals(current.getBasePlot(false)) @@ -2255,9 +2314,17 @@ public class Plot { merged.add(current.getId()); merged.add(other.getId()); toReturn = true; + + if (removeRoads) { + ArrayList ids = new ArrayList<>(); + ids.add(current.getId()); + ids.add(other.getId()); + this.getManager().finishPlotMerge(ids); + } } } - if (max >= 0 && (dir == -1 || dir == 2) && !getMerged(Direction.SOUTH)) { + if (max >= 0 && (dir == Direction.ALL || dir == Direction.SOUTH) && !getMerged( + Direction.SOUTH)) { Plot other = current.getRelative(Direction.SOUTH); if (other != null && other.isOwner(uuid) && ( other.getBasePlot(false).equals(current.getBasePlot(false)) @@ -2267,9 +2334,17 @@ public class Plot { merged.add(current.getId()); merged.add(other.getId()); toReturn = true; + + if (removeRoads) { + ArrayList ids = new ArrayList<>(); + ids.add(current.getId()); + ids.add(other.getId()); + this.getManager().finishPlotMerge(ids); + } } } - if (max >= 0 && (dir == -1 || dir == 3) && !getMerged(Direction.WEST)) { + if (max >= 0 && (dir == Direction.ALL || dir == Direction.WEST) && !getMerged( + Direction.WEST)) { Plot other = current.getRelative(Direction.WEST); if (other != null && other.isOwner(uuid) && ( other.getBasePlot(false).equals(current.getBasePlot(false)) @@ -2279,13 +2354,16 @@ public class Plot { merged.add(current.getId()); merged.add(other.getId()); toReturn = true; + + if (removeRoads) { + ArrayList ids = new ArrayList<>(); + ids.add(current.getId()); + ids.add(other.getId()); + this.getManager().finishPlotMerge(ids); + } } } } - if (removeRoads && toReturn) { - ArrayList ids = new ArrayList<>(merged); - this.getManager().finishPlotMerge(this.area, ids); - } return toReturn; } @@ -2350,7 +2428,7 @@ public class Plot { pos2.setY(MAX_HEIGHT); ChunkManager.manager.regenerateRegion(pos1, pos2, true, null); } else { - this.area.getPlotManager().removeRoadSouthEast(this.area, this); + this.area.getPlotManager().removeRoadSouthEast(this); } } @@ -2381,20 +2459,16 @@ public class Plot { * @param direction * @return */ - public Plot getRelative(int direction) { + @Deprecated public Plot getRelative(int direction) { return this.area.getPlotAbs(this.id.getRelative(direction)); } /** - * Gets the plot in a relative direction
- * 0 = north
- * 1 = east
- * 2 = south
- * 3 = west
+ * Gets the plot in a relative direction * Note: May be null if the partial plot area does not include the relative location * * @param direction - * @return + * @return the plot relative to this one */ public Plot getRelative(Direction direction) { return this.area.getPlotAbs(this.id.getRelative(direction)); @@ -2404,15 +2478,13 @@ public class Plot { * Gets a set of plots connected (and including) this plot
* - This result is cached globally * - * @return + * @return a Set of Plots connected to this Plot */ public Set getConnectedPlots() { if (this.settings == null) { return Collections.singleton(this); } - boolean[] merged = this.getMerged(); - int hash = MainUtil.hash(merged); - if (hash == 0) { + if (!this.isMerged()) { return Collections.singleton(this); } if (connected_cache != null && connected_cache.contains(this)) { @@ -2421,68 +2493,68 @@ public class Plot { regions_cache = null; HashSet tmpSet = new HashSet<>(); - ArrayDeque frontier = new ArrayDeque<>(); - HashSet queuecache = new HashSet<>(); tmpSet.add(this); Plot tmp; - if (merged[0]) { + HashSet queuecache = new HashSet<>(); + ArrayDeque frontier = new ArrayDeque<>(); + if (this.getMerged(Direction.NORTH)) { tmp = this.area.getPlotAbs(this.id.getRelative(Direction.NORTH)); if (!tmp.getMerged(Direction.SOUTH)) { // invalid merge PlotSquared.debug("Fixing invalid merge: " + this); if (tmp.isOwnerAbs(this.owner)) { - tmp.getSettings().setMerged(2, true); + tmp.getSettings().setMerged(Direction.SOUTH, true); DBFunc.setMerged(tmp, tmp.getSettings().getMerged()); } else { - this.getSettings().setMerged(0, false); + this.getSettings().setMerged(Direction.NORTH, false); DBFunc.setMerged(this, this.getSettings().getMerged()); } } queuecache.add(tmp); frontier.add(tmp); } - if (merged[1]) { + if (this.getMerged(Direction.EAST)) { tmp = this.area.getPlotAbs(this.id.getRelative(Direction.EAST)); if (!tmp.getMerged(Direction.WEST)) { // invalid merge PlotSquared.debug("Fixing invalid merge: " + this); if (tmp.isOwnerAbs(this.owner)) { - tmp.getSettings().setMerged(3, true); + tmp.getSettings().setMerged(Direction.WEST, true); DBFunc.setMerged(tmp, tmp.getSettings().getMerged()); } else { - this.getSettings().setMerged(1, false); + this.getSettings().setMerged(Direction.EAST, false); DBFunc.setMerged(this, this.getSettings().getMerged()); } } queuecache.add(tmp); frontier.add(tmp); } - if (merged[2]) { + if (this.getMerged(Direction.SOUTH)) { tmp = this.area.getPlotAbs(this.id.getRelative(Direction.SOUTH)); if (!tmp.getMerged(Direction.NORTH)) { // invalid merge PlotSquared.debug("Fixing invalid merge: " + this); if (tmp.isOwnerAbs(this.owner)) { - tmp.getSettings().setMerged(0, true); + tmp.getSettings().setMerged(Direction.NORTH, true); DBFunc.setMerged(tmp, tmp.getSettings().getMerged()); } else { - this.getSettings().setMerged(2, false); + this.getSettings().setMerged(Direction.SOUTH, false); DBFunc.setMerged(this, this.getSettings().getMerged()); } } queuecache.add(tmp); frontier.add(tmp); } - if (merged[3]) { + if (this.getMerged(Direction.WEST)) { tmp = this.area.getPlotAbs(this.id.getRelative(Direction.WEST)); if (!tmp.getMerged(Direction.EAST)) { // invalid merge PlotSquared.debug("Fixing invalid merge: " + this); if (tmp.isOwnerAbs(this.owner)) { - tmp.getSettings().setMerged(1, true); + tmp.getSettings().setMerged(Direction.EAST, true); DBFunc.setMerged(tmp, tmp.getSettings().getMerged()); } else { - this.getSettings().setMerged(3, false); + this.getSettings().setMerged(Direction.WEST, false); DBFunc.setMerged(this, this.getSettings().getMerged()); } } @@ -2500,29 +2572,28 @@ public class Plot { } tmpSet.add(current); queuecache.remove(current); - merged = current.getMerged(); - if (merged[0]) { + if (current.getMerged(Direction.NORTH)) { tmp = current.area.getPlotAbs(current.id.getRelative(Direction.NORTH)); if (tmp != null && !queuecache.contains(tmp) && !tmpSet.contains(tmp)) { queuecache.add(tmp); frontier.add(tmp); } } - if (merged[1]) { + if (current.getMerged(Direction.EAST)) { tmp = current.area.getPlotAbs(current.id.getRelative(Direction.EAST)); if (tmp != null && !queuecache.contains(tmp) && !tmpSet.contains(tmp)) { queuecache.add(tmp); frontier.add(tmp); } } - if (merged[2]) { + if (current.getMerged(Direction.SOUTH)) { tmp = current.area.getPlotAbs(current.id.getRelative(Direction.SOUTH)); if (tmp != null && !queuecache.contains(tmp) && !tmpSet.contains(tmp)) { queuecache.add(tmp); frontier.add(tmp); } } - if (merged[3]) { + if (current.getMerged(Direction.WEST)) { tmp = current.area.getPlotAbs(current.id.getRelative(Direction.WEST)); if (tmp != null && !queuecache.contains(tmp) && !tmpSet.contains(tmp)) { queuecache.add(tmp); @@ -2541,7 +2612,7 @@ public class Plot { * * @return */ - @Nonnull public HashSet getRegions() { + @NotNull public Set getRegions() { if (regions_cache != null && connected_cache != null && connected_cache.contains(this)) { return regions_cache; } @@ -2549,14 +2620,13 @@ public class Plot { Location pos1 = this.getBottomAbs(); Location pos2 = this.getTopAbs(); connected_cache = Sets.newHashSet(this); - regions_cache = Sets.newHashSet( - new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getY(), pos2.getY(), pos1.getZ(), - pos2.getZ())); + CuboidRegion rg = new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()); + regions_cache = Collections.singleton(rg); return regions_cache; } Set plots = this.getConnectedPlots(); - HashSet regions = regions_cache = new HashSet<>(); - HashSet visited = new HashSet<>(); + Set regions = regions_cache = new HashSet<>(); + Set visited = new HashSet<>(); for (Plot current : plots) { if (visited.contains(current.getId())) { continue; @@ -2633,12 +2703,14 @@ public class Plot { Location toploc = plot.getExtendedTopAbs(); Location botabs = plot.getBottomAbs(); Location topabs = plot.getTopAbs(); - regions.add(new RegionWrapper(botabs.getX(), topabs.getX(), topabs.getZ() + 1, - toploc.getZ())); + BlockVector3 pos1 = BlockVector3.at(botabs.getX(), 0, topabs.getZ() + 1); + BlockVector3 pos2 = BlockVector3.at(topabs.getX(), Plot.MAX_HEIGHT - 1, toploc.getZ()); + regions.add(new CuboidRegion(pos1, pos2)); if (plot.getMerged(Direction.SOUTHEAST)) { + pos1 = BlockVector3.at(topabs.getX() + 1, 0, topabs.getZ() + 1); + pos2 = BlockVector3.at(toploc.getX(), Plot.MAX_HEIGHT - 1, toploc.getZ()); regions.add( - new RegionWrapper(topabs.getX() + 1, toploc.getX(), topabs.getZ() + 1, - toploc.getZ())); + new CuboidRegion(pos1, pos2)); // intersection } } @@ -2651,18 +2723,22 @@ public class Plot { Location toploc = plot.getExtendedTopAbs(); Location botabs = plot.getBottomAbs(); Location topabs = plot.getTopAbs(); - regions.add(new RegionWrapper(topabs.getX() + 1, toploc.getX(), botabs.getZ(), - topabs.getZ())); + BlockVector3 pos1 = BlockVector3.at(topabs.getX() + 1, 0, botabs.getZ()); + BlockVector3 pos2 = BlockVector3.at(toploc.getX(), Plot.MAX_HEIGHT - 1, topabs.getZ()); + regions.add(new CuboidRegion(pos1, pos2)); if (plot.getMerged(Direction.SOUTHEAST)) { + pos1 = BlockVector3.at(topabs.getX() + 1, 0, topabs.getZ() + 1); + pos2 = BlockVector3.at(toploc.getX(), Plot.MAX_HEIGHT - 1, toploc.getZ()); regions.add( - new RegionWrapper(topabs.getX() + 1, toploc.getX(), topabs.getZ() + 1, - toploc.getZ())); + new CuboidRegion(pos1, pos2)); // intersection } } } + BlockVector3 pos1 = BlockVector3.at(gbotabs.getX(), 0, gbotabs.getZ()); + BlockVector3 pos2 = BlockVector3.at(gtopabs.getX(), Plot.MAX_HEIGHT - 1, gtopabs.getZ()); regions.add( - new RegionWrapper(gbotabs.getX(), gtopabs.getX(), gbotabs.getZ(), gtopabs.getZ())); + new CuboidRegion(pos1, pos2)); } return regions; } @@ -2672,13 +2748,13 @@ public class Plot { * * @return */ - public RegionWrapper getLargestRegion() { - HashSet regions = this.getRegions(); - RegionWrapper max = null; + public CuboidRegion getLargestRegion() { + Set regions = this.getRegions(); + CuboidRegion max = null; double area = Double.NEGATIVE_INFINITY; - for (RegionWrapper region : regions) { + for (CuboidRegion region : regions) { double current = - (region.maxX - (double) region.minX + 1) * (region.maxZ - (double) region.minZ + 1); + (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * (region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1); if (current > area) { max = region; area = current; @@ -2707,9 +2783,9 @@ public class Plot { */ public List getAllCorners() { Area area = new Area(); - for (RegionWrapper region : this.getRegions()) { - Rectangle2D rect = new Rectangle2D.Double(region.minX - 0.6, region.minZ - 0.6, - region.maxX - region.minX + 1.2, region.maxZ - region.minZ + 1.2); + for (CuboidRegion region : this.getRegions()) { + Rectangle2D rect = new Rectangle2D.Double(region.getMinimumPoint().getX() - 0.6, region.getMinimumPoint().getZ() - 0.6, + region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + 1.2, region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + 1.2); Area rectArea = new Area(rect); area.add(rectArea); } @@ -2768,6 +2844,11 @@ public class Plot { return false; } + /** + * Checks if the owner of this Plot is online. + * + * @return true if the owner of the Plot is online + */ public boolean isOnline() { if (this.owner == null) { return false; @@ -2792,17 +2873,17 @@ public class Plot { * @param blocks * @return */ - public boolean setComponent(String component, BlockBucket blocks) { + public boolean setComponent(String component, Pattern blocks) { if (StringMan - .isEqualToAny(component, getManager().getPlotComponents(this.area, this.getId()))) { + .isEqualToAny(component, getManager().getPlotComponents(this.getId()))) { EventUtil.manager.callComponentSet(this, component); } - return this.getManager().setComponent(this.area, this.getId(), component, blocks); + return this.getManager().setComponent(this.getId(), component, blocks); } public int getDistanceFromOrigin() { - Location bot = getManager().getPlotBottomLocAbs(this.area, id); - Location top = getManager().getPlotTopLocAbs(this.area, id); + Location bot = getManager().getPlotBottomLocAbs(id); + Location top = getManager().getPlotTopLocAbs(id); return Math.max(Math.max(Math.abs(bot.getX()), Math.abs(bot.getZ())), Math.max(Math.abs(top.getX()), Math.abs(top.getZ()))); } @@ -2822,13 +2903,14 @@ public class Plot { } /** - * Merges 2 plots Removes the road in-between
- Assumes plots are directly next to each other
- saves to DB + * Merges two plots.
- Assumes plots are directly next to each other
- saves to DB * * @param lesserPlot * @param removeRoads */ public void mergePlot(Plot lesserPlot, boolean removeRoads) { Plot greaterPlot = this; + lesserPlot.removeSign(); if (lesserPlot.getId().x == greaterPlot.getId().x) { if (lesserPlot.getId().y > greaterPlot.getId().y) { Plot tmp = lesserPlot; @@ -2838,10 +2920,11 @@ public class Plot { if (!lesserPlot.getMerged(Direction.SOUTH)) { lesserPlot.clearRatings(); greaterPlot.clearRatings(); - lesserPlot.setMerged(2, true); - greaterPlot.setMerged(0, true); + lesserPlot.setMerged(Direction.SOUTH, true); + greaterPlot.setMerged(Direction.NORTH, true); lesserPlot.mergeData(greaterPlot); if (removeRoads) { + //lesserPlot.removeSign(); lesserPlot.removeRoadSouth(); Plot diagonal = greaterPlot.getRelative(Direction.EAST); if (diagonal.getMerged(Direction.NORTHWEST)) { @@ -2862,10 +2945,11 @@ public class Plot { if (!lesserPlot.getMerged(Direction.EAST)) { lesserPlot.clearRatings(); greaterPlot.clearRatings(); - lesserPlot.setMerged(1, true); - greaterPlot.setMerged(3, true); + lesserPlot.setMerged(Direction.EAST, true); + greaterPlot.setMerged(Direction.WEST, true); lesserPlot.mergeData(greaterPlot); if (removeRoads) { + //lesserPlot.removeSign(); Plot diagonal = greaterPlot.getRelative(Direction.SOUTH); if (diagonal.getMerged(Direction.NORTHWEST)) { lesserPlot.removeRoadSouthEast(); @@ -2878,6 +2962,7 @@ public class Plot { } } } + } /** @@ -2915,7 +3000,7 @@ public class Plot { } // world border destination.updateWorldBorder(); - final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); + final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); // move / swap data final PlotArea originArea = getArea(); for (Plot plot : plots) { @@ -2923,51 +3008,51 @@ public class Plot { plot.swapData(other, null); } // copy terrain - Runnable move = new Runnable() { - @Override public void run() { - if (regions.isEmpty()) { - Plot plot = destination.getRelative(0, 0); - for (Plot current : plot.getConnectedPlots()) { - getManager().claimPlot(current.getArea(), current); - Plot originPlot = originArea.getPlotAbs( - new PlotId(current.id.x - offset.x, current.id.y - offset.y)); - originPlot.getManager().unClaimPlot(originArea, originPlot, null); - } - plot.setSign(); - TaskManager.runTask(whenDone); - return; - } - final Runnable task = this; - RegionWrapper region = regions.poll(); - Location[] corners = region.getCorners(getWorldName()); - final Location pos1 = corners[0]; - final Location pos2 = corners[1]; - Location newPos = pos1.clone().add(offsetX, 0, offsetZ); - newPos.setWorld(destination.getWorldName()); - ChunkManager.manager.copyRegion(pos1, pos2, newPos, - () -> ChunkManager.manager.regenerateRegion(pos1, pos2, false, task)); - } - }; - Runnable swap = new Runnable() { - @Override public void run() { - if (regions.isEmpty()) { - TaskManager.runTask(whenDone); - return; - } - RegionWrapper region = regions.poll(); - Location[] corners = region.getCorners(getWorldName()); - Location pos1 = corners[0]; - Location pos2 = corners[1]; - Location pos3 = pos1.clone().add(offsetX, 0, offsetZ); - Location pos4 = pos2.clone().add(offsetX, 0, offsetZ); - pos3.setWorld(destination.getWorldName()); - pos4.setWorld(destination.getWorldName()); - ChunkManager.manager.swap(pos1, pos2, pos3, pos4, this); - } - }; if (occupied) { + Runnable swap = new Runnable() { + @Override public void run() { + if (regions.isEmpty()) { + TaskManager.runTask(whenDone); + return; + } + CuboidRegion region = regions.poll(); + Location[] corners = MainUtil.getCorners(getWorldName(), region); + Location pos1 = corners[0]; + Location pos2 = corners[1]; + Location pos3 = pos1.clone().add(offsetX, 0, offsetZ); + Location pos4 = pos2.clone().add(offsetX, 0, offsetZ); + pos3.setWorld(destination.getWorldName()); + pos4.setWorld(destination.getWorldName()); + ChunkManager.manager.swap(pos1, pos2, pos3, pos4, this); + } + }; swap.run(); } else { + Runnable move = new Runnable() { + @Override public void run() { + if (regions.isEmpty()) { + Plot plot = destination.getRelative(0, 0); + for (Plot current : plot.getConnectedPlots()) { + getManager().claimPlot(current); + Plot originPlot = originArea.getPlotAbs( + new PlotId(current.id.x - offset.x, current.id.y - offset.y)); + originPlot.getManager().unClaimPlot(originPlot, null); + } + plot.setSign(); + TaskManager.runTask(whenDone); + return; + } + final Runnable task = this; + CuboidRegion region = regions.poll(); + Location[] corners = MainUtil.getCorners(getWorldName(), region); + final Location pos1 = corners[0]; + final Location pos2 = corners[1]; + Location newPos = pos1.clone().add(offsetX, 0, offsetZ); + newPos.setWorld(destination.getWorldName()); + ChunkManager.manager.copyRegion(pos1, pos2, newPos, + () -> ChunkManager.manager.regenerateRegion(pos1, pos2, false, task)); + } + }; move.run(); } return true; @@ -3032,19 +3117,19 @@ public class Plot { } } // copy terrain - final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); + final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); Runnable run = new Runnable() { @Override public void run() { if (regions.isEmpty()) { for (Plot current : getConnectedPlots()) { - destination.getManager().claimPlot(destination.getArea(), destination); + destination.getManager().claimPlot(destination); } destination.setSign(); TaskManager.runTask(whenDone); return; } - RegionWrapper region = regions.poll(); - Location[] corners = region.getCorners(getWorldName()); + CuboidRegion region = regions.poll(); + Location[] corners = MainUtil.getCorners(getWorldName(), region); Location pos1 = corners[0]; Location pos2 = corners[1]; Location newPos = pos1.clone().add(offsetX, 0, offsetZ); @@ -3060,23 +3145,23 @@ public class Plot { return getFlags().containsKey(flag); } - @SuppressWarnings("deprecation") public boolean removeComment(PlotComment comment) { + public boolean removeComment(PlotComment comment) { return getSettings().removeComment(comment); } - @SuppressWarnings("deprecation") public void removeComments(List comments) { + public void removeComments(List comments) { getSettings().removeComments(comments); } - @SuppressWarnings("deprecation") public List getComments(String inbox) { + public List getComments(String inbox) { return getSettings().getComments(inbox); } - @SuppressWarnings("deprecation") public void addComment(PlotComment comment) { + public void addComment(PlotComment comment) { getSettings().addComment(comment); } - @SuppressWarnings("deprecation") public void setComments(List list) { + public void setComments(List list) { getSettings().setComments(list); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotArea.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotArea.java index 9cdd5a4bd..d0cf46d70 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotArea.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotArea.java @@ -10,17 +10,37 @@ import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.generator.GridPlotWorld; import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; import com.github.intellectualsites.plotsquared.plot.util.area.QuadMap; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.world.RegionUtil; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +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 com.sk89q.worldedit.world.biome.BiomeTypes; +import com.sk89q.worldedit.world.gamemode.GameMode; +import com.sk89q.worldedit.world.gamemode.GameModes; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; @@ -31,20 +51,19 @@ public abstract class PlotArea { public final String worldname; public final String id; - public final PlotManager manager; + @NotNull public final PlotManager manager; public final int worldhash; protected final ConcurrentHashMap plots = new ConcurrentHashMap<>(); private final PlotId min; private final PlotId max; - private final IndependentPlotGenerator generator; - private final BlockBucket[][] blockBucketChunk; + @NotNull private final IndependentPlotGenerator generator; public int MAX_PLOT_MEMBERS = 128; public boolean AUTO_MERGE = false; public boolean ALLOW_SIGNS = true; public boolean MISC_SPAWN_UNOWNED = false; public boolean MOB_SPAWNING = false; public boolean MOB_SPAWNER_SPAWNING = false; - public String PLOT_BIOME = "FOREST"; + public BiomeType PLOT_BIOME = BiomeTypes.FOREST; public boolean PLOT_CHAT = false; public boolean SCHEMATIC_CLAIM_SPECIFY = false; public boolean SCHEMATIC_ON_CLAIM = false; @@ -64,18 +83,18 @@ public abstract class PlotArea { public PlotLoc DEFAULT_HOME; public int MAX_BUILD_HEIGHT = 256; public int MIN_BUILD_HEIGHT = 1; - public PlotGameMode GAMEMODE = PlotGameMode.CREATIVE; + public GameMode GAMEMODE = GameModes.CREATIVE; private int hash; - private RegionWrapper region; + private CuboidRegion region; private ConcurrentHashMap meta; private QuadMap clusters; - public PlotArea(@Nonnull final String worldName, @Nullable final String id, - @Nullable IndependentPlotGenerator generator, @Nullable final PlotId min, + public PlotArea(@NotNull final String worldName, @Nullable final String id, + @NotNull IndependentPlotGenerator generator, @Nullable final PlotId min, @Nullable final PlotId max) { this.worldname = worldName; this.id = id; - this.manager = generator != null ? generator.getNewPlotManager() : null; + this.manager = createManager(); this.generator = generator; if (min == null || max == null) { if (min != max) { @@ -89,58 +108,25 @@ public abstract class PlotArea { this.max = max; } this.worldhash = worldName.hashCode(); - if (Settings.Enabled_Components.PLOT_EXPIRY && generator != null) { - blockBucketChunk = generator.generateBlockBucketChunk(this); - } else { - blockBucketChunk = null; - } } - /** - * Create a new PlotArea object with no functionality/information. - * - Mainly used during startup before worlds are created as a temporary object - */ - public static PlotArea createGeneric(@Nonnull final String world) { - return new PlotArea(world, null, null, null, null) { - @Override public void loadConfiguration(ConfigurationSection config) { - } - - @Override public ConfigurationNode[] getSettingNodes() { - return null; - } - }; - } + @NotNull protected abstract PlotManager createManager(); public LocalBlockQueue getQueue(final boolean autoQueue) { return GlobalBlockQueue.IMP.getNewQueue(worldname, autoQueue); } /** - * Get an array of BlockBuckets corresponding to a chunk of a plot - * - * @return BlockBucket[][] - */ - public BlockBucket[][] getBlockBucketChunk() { - if (blockBucketChunk != null) { - return blockBucketChunk; - } - if (generator != null) { - return generator.generateBlockBucketChunk(this); - } - return null; - } - - /** - * Returns the region for this PlotArea or a RegionWrapper encompassing + * Returns the region for this PlotArea, or a CuboidRegion encompassing * the whole world if none exists. * - * @return RegionWrapper + * @return CuboidRegion */ - public RegionWrapper getRegion() { + public CuboidRegion getRegion() { this.region = getRegionAbs(); if (this.region == null) { - return new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, - Integer.MAX_VALUE); + return new CuboidRegion(BlockVector3.at(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE), + BlockVector3.at(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE)); } return this.region; } @@ -148,15 +134,16 @@ public abstract class PlotArea { /** * Returns the region for this PlotArea. * - * @return RegionWrapper or null if no applicable region + * @return CuboidRegion or null if no applicable region */ - private RegionWrapper getRegionAbs() { + private CuboidRegion getRegionAbs() { if (this.region == null) { if (this.min != null) { - Location bot = getPlotManager().getPlotBottomLocAbs(this, this.min); - Location top = getPlotManager().getPlotTopLocAbs(this, this.max); - this.region = new RegionWrapper(bot.getX() - 1, top.getX() + 1, bot.getZ() - 1, - top.getZ() + 1); + Location bot = getPlotManager().getPlotBottomLocAbs(this.min); + Location top = getPlotManager().getPlotTopLocAbs(this.max); + BlockVector3 pos1 = bot.getBlockVector3().subtract(BlockVector3.ONE); + BlockVector3 pos2 = top.getBlockVector3().add(BlockVector3.ONE); + this.region = new CuboidRegion(pos1, pos2); } } return this.region; @@ -185,7 +172,7 @@ public abstract class PlotArea { * * @return the {@link IndependentPlotGenerator} */ - public IndependentPlotGenerator getGenerator() { + @NotNull public IndependentPlotGenerator getGenerator() { return this.generator; } @@ -262,27 +249,25 @@ public abstract class PlotArea { this.MIN_BUILD_HEIGHT = config.getInt("world.min_height"); switch (config.getString("world.gamemode").toLowerCase()) { - case "survival": - case "s": - case "0": - this.GAMEMODE = PlotGameMode.SURVIVAL; - break; case "creative": case "c": case "1": - this.GAMEMODE = PlotGameMode.CREATIVE; + this.GAMEMODE = GameModes.CREATIVE; break; case "adventure": case "a": case "2": - this.GAMEMODE = PlotGameMode.ADVENTURE; + this.GAMEMODE = GameModes.ADVENTURE; break; case "spectator": case "3": - this.GAMEMODE = PlotGameMode.SPECTATOR; + this.GAMEMODE = GameModes.SPECTATOR; break; + case "survival": + case "s": + case "0": default: - this.GAMEMODE = PlotGameMode.NOT_SET; + this.GAMEMODE = GameModes.SURVIVAL; break; } @@ -377,7 +362,7 @@ public abstract class PlotArea { options.put("home.nonmembers", position); options.put("world.max_height", this.MAX_BUILD_HEIGHT); options.put("world.min_height", this.MIN_BUILD_HEIGHT); - options.put("world.gamemode", this.GAMEMODE.name().toLowerCase()); + options.put("world.gamemode", this.GAMEMODE.getName().toLowerCase()); if (this.TYPE != 0) { options.put("generator.terrain", this.TERRAIN); @@ -401,7 +386,7 @@ public abstract class PlotArea { } } - @Nonnull @Override public String toString() { + @NotNull @Override public String toString() { if (this.id == null) { return this.worldname; } else { @@ -429,9 +414,9 @@ public abstract class PlotArea { * @param location the location * @return the {@code Plot} or null if none exists */ - @Nullable public Plot getPlotAbs(@Nonnull final Location location) { + @Nullable public Plot getPlotAbs(@NotNull final Location location) { final PlotId pid = - this.manager.getPlotId(this, location.getX(), location.getY(), location.getZ()); + this.manager.getPlotId(location.getX(), location.getY(), location.getZ()); if (pid == null) { return null; } @@ -444,9 +429,9 @@ public abstract class PlotArea { * @param location the location * @return base Plot */ - @Nullable public Plot getPlot(@Nonnull final Location location) { + @Nullable public Plot getPlot(@NotNull final Location location) { final PlotId pid = - this.manager.getPlotId(this, location.getX(), location.getY(), location.getZ()); + this.manager.getPlotId(location.getX(), location.getY(), location.getZ()); if (pid == null) { return null; } @@ -459,9 +444,9 @@ public abstract class PlotArea { * @param location the location * @return the base plot or null */ - @Nullable public Plot getOwnedPlot(@Nonnull final Location location) { + @Nullable public Plot getOwnedPlot(@NotNull final Location location) { final PlotId pid = - this.manager.getPlotId(this, location.getX(), location.getY(), location.getZ()); + this.manager.getPlotId(location.getX(), location.getY(), location.getZ()); if (pid == null) { return null; } @@ -475,9 +460,9 @@ public abstract class PlotArea { * @param location the location * @return Plot or null */ - @Nullable public Plot getOwnedPlotAbs(@Nonnull final Location location) { + @Nullable public Plot getOwnedPlotAbs(@NotNull final Location location) { final PlotId pid = - this.manager.getPlotId(this, location.getX(), location.getY(), location.getZ()); + this.manager.getPlotId(location.getX(), location.getY(), location.getZ()); if (pid == null) { return null; } @@ -490,30 +475,30 @@ public abstract class PlotArea { * @param id the {@code PlotId} * @return the plot or null */ - @Nullable public Plot getOwnedPlotAbs(@Nonnull final PlotId id) { + @Nullable public Plot getOwnedPlotAbs(@NotNull final PlotId id) { return this.plots.get(id); } - @Nullable public Plot getOwnedPlot(@Nonnull final PlotId id) { + @Nullable public Plot getOwnedPlot(@NotNull final PlotId id) { Plot plot = this.plots.get(id); return plot == null ? null : plot.getBasePlot(false); } public boolean contains(final int x, final int z) { - return this.TYPE != 2 || getRegionAbs().isIn(x, z); + return this.TYPE != 2 || RegionUtil.contains(getRegionAbs(), x, z); } - public boolean contains(@Nonnull final PlotId id) { + public boolean contains(@NotNull final PlotId id) { return this.min == null || (id.x >= this.min.x && id.x <= this.max.x && id.y >= this.min.y && id.y <= this.max.y); } - public boolean contains(@Nonnull final Location location) { + public boolean contains(@NotNull final Location location) { return StringMan.isEqual(location.getWorld(), this.worldname) && (getRegionAbs() == null - || this.region.isIn(location.getX(), location.getZ())); + || this.region.contains(location.getBlockVector3())); } - @Nonnull Set getPlotsAbs(final UUID uuid) { + @NotNull Set getPlotsAbs(final UUID uuid) { if (uuid == null) { return Collections.emptySet(); } @@ -526,7 +511,7 @@ public abstract class PlotArea { return myPlots; } - @Nonnull public Set getPlots(@Nonnull final UUID uuid) { + @NotNull public Set getPlots(@NotNull final UUID uuid) { return getPlots().stream().filter(plot -> plot.isBasePlot() && plot.isOwner(uuid)) .collect(ImmutableSet.toImmutableSet()); } @@ -540,7 +525,7 @@ public abstract class PlotArea { return this.plots.values(); } - public int getPlotCount(@Nonnull final UUID uuid) { + public int getPlotCount(@NotNull final UUID uuid) { if (!Settings.Done.COUNTS_TOWARDS_LIMIT) { return (int) getPlotsAbs(uuid).stream().filter(plot -> !plot.hasFlag(Flags.DONE)) .count(); @@ -553,11 +538,11 @@ public abstract class PlotArea { * * @deprecated Use {@link #getPlots(UUID)} */ - @Deprecated public Set getPlots(@Nonnull final PlotPlayer player) { + @Deprecated public Set getPlots(@NotNull final PlotPlayer player) { return getPlots(player.getUUID()); } - public boolean hasPlot(@Nonnull final UUID uuid) { + public boolean hasPlot(@NotNull final UUID uuid) { return this.plots.entrySet().stream().anyMatch(entry -> entry.getValue().isOwner(uuid)); } @@ -566,7 +551,7 @@ public abstract class PlotArea { return player != null ? getPlotCount(player.getUUID()) : 0; } - @Nullable public Plot getPlotAbs(@Nonnull final PlotId id) { + @Nullable public Plot getPlotAbs(@NotNull final PlotId id) { Plot plot = getOwnedPlotAbs(id); if (plot == null) { if (this.min != null && (id.x < this.min.x || id.x > this.max.x || id.y < this.min.y @@ -578,7 +563,7 @@ public abstract class PlotArea { return plot; } - @Nullable public Plot getPlot(@Nonnull final PlotId id) { + @Nullable public Plot getPlot(@NotNull final PlotId id) { final Plot plot = getOwnedPlotAbs(id); if (plot == null) { if (this.min != null && (id.x < this.min.x || id.x > this.max.x || id.y < this.min.y @@ -599,7 +584,7 @@ public abstract class PlotArea { return this.plots.size(); } - @Nullable public PlotCluster getCluster(@Nonnull final Location location) { + @Nullable public PlotCluster getCluster(@NotNull final Location location) { final Plot plot = getPlot(location); if (plot == null) { return null; @@ -607,8 +592,8 @@ public abstract class PlotArea { return this.clusters != null ? this.clusters.get(plot.getId().x, plot.getId().y) : null; } - @Nullable public PlotCluster getFirstIntersectingCluster(@Nonnull final PlotId pos1, - @Nonnull final PlotId pos2) { + @Nullable public PlotCluster getFirstIntersectingCluster(@NotNull final PlotId pos1, + @NotNull final PlotId pos2) { if (this.clusters == null) { return null; } @@ -620,11 +605,11 @@ public abstract class PlotArea { return null; } - @Nullable PlotCluster getCluster(@Nonnull final PlotId id) { + @Nullable PlotCluster getCluster(@NotNull final PlotId id) { return this.clusters != null ? this.clusters.get(id.x, id.y) : null; } - public PlotManager getPlotManager() { + @NotNull public PlotManager getPlotManager() { return this.manager; } @@ -635,14 +620,14 @@ public abstract class PlotArea { * * @see FlagManager */ - public void setMeta(@Nonnull final String key, @Nullable final Object value) { + public void setMeta(@NotNull final String key, @Nullable final Object value) { if (this.meta == null) { this.meta = new ConcurrentHashMap<>(); } this.meta.put(key, value); } - @Nullable public T getMeta(@Nullable final String key, @Nullable final T def) { + @NotNull public T getMeta(@NotNull final String key, @NotNull final T def) { final Object v = getMeta(key); return v == null ? def : (T) v; } @@ -652,14 +637,15 @@ public abstract class PlotArea { *
* For persistent metadata use the flag system */ - @Nullable public Object getMeta(@Nonnull final String key) { + @Nullable + public Object getMeta(@NotNull final String key) { if (this.meta != null) { return this.meta.get(key); } return null; } - @SuppressWarnings("unused") @Nonnull public Set getBasePlots() { + @SuppressWarnings("unused") @NotNull public Set getBasePlots() { final HashSet myPlots = new HashSet<>(getPlots()); myPlots.removeIf(plot -> !plot.isBasePlot()); return myPlots; @@ -692,15 +678,15 @@ public abstract class PlotArea { * @deprecated Use {@link #getPlotsMap()} */ //todo eventually remove - @Deprecated @Nonnull public Map getPlotsRaw() { + @Deprecated @NotNull public Map getPlotsRaw() { return ImmutableMap.copyOf(plots); } - @Nonnull public Set> getPlotEntries() { + @NotNull public Set> getPlotEntries() { return this.plots.entrySet(); } - public boolean addPlot(@Nonnull final Plot plot) { + public boolean addPlot(@NotNull final Plot plot) { for (PlotPlayer pp : plot.getPlayersInPlot()) { pp.setMeta(PlotPlayer.META_LAST_PLOT, plot); } @@ -714,7 +700,7 @@ public abstract class PlotArea { PlotId max = getMax(); if (TYPE == 2) { center = new PlotId(MathMan.average(min.x, max.x), MathMan.average(min.y, max.y)); - plots = Math.max(max.x - min.x, max.y - min.y) + 1; + plots = Math.max(max.x - min.x + 1, max.y - min.y + 1) + 1; if (start != null) { start = new PlotId(start.x - center.x, start.y - center.y); } @@ -731,14 +717,14 @@ public abstract class PlotArea { PlotId currentId = new PlotId(center.x + start.x, center.y + start.y); Plot plot = getPlotAbs(currentId); if (plot != null && plot.canClaim(player)) { - setMeta("lastPlot", currentId); + setMeta("lastPlot", start); return plot; } } return null; } - public boolean addPlotIfAbsent(@Nonnull final Plot plot) { + public boolean addPlotIfAbsent(@NotNull final Plot plot) { if (this.plots.putIfAbsent(plot.getId(), plot) == null) { for (PlotPlayer pp : plot.getPlayersInPlot()) { pp.setMeta(PlotPlayer.META_LAST_PLOT, plot); @@ -748,7 +734,7 @@ public abstract class PlotArea { return false; } - public boolean addPlotAbs(@Nonnull final Plot plot) { + public boolean addPlotAbs(@NotNull final Plot plot) { return this.plots.put(plot.getId(), plot) == null; } @@ -793,14 +779,14 @@ public abstract class PlotArea { * * @param key Meta data key */ - public void deleteMeta(@Nonnull final String key) { + public void deleteMeta(@NotNull final String key) { if (this.meta != null) { this.meta.remove(key); } } - public boolean canClaim(@Nullable final PlotPlayer player, @Nonnull final PlotId pos1, - @Nonnull final PlotId pos2) { + public boolean canClaim(@Nullable final PlotPlayer player, @NotNull final PlotId pos1, + @NotNull final PlotId pos2) { if (pos1.x == pos2.x && pos1.y == pos2.y) { if (getOwnedPlot(pos1) != null) { return false; @@ -826,11 +812,11 @@ public abstract class PlotArea { return true; } - public boolean removePlot(@Nonnull final PlotId id) { + public boolean removePlot(@NotNull final PlotId id) { return this.plots.remove(id) != null; } - public boolean mergePlots(@Nonnull final List plotIds, final boolean removeRoads) { + public boolean mergePlots(@NotNull final List plotIds, final boolean removeRoads) { if (plotIds.size() < 2) { return false; } @@ -844,11 +830,10 @@ public abstract class PlotArea { return false; } + manager.startPlotMerge(plotIds); final Set trusted = new HashSet<>(); final Set members = new HashSet<>(); final Set denied = new HashSet<>(); - - manager.startPlotMerge(this, plotIds); for (int x = pos1.x; x <= pos2.x; x++) { for (int y = pos1.y; y <= pos2.y; y++) { PlotId id = new PlotId(x, y); @@ -897,7 +882,7 @@ public abstract class PlotArea { } } } - manager.finishPlotMerge(this, plotIds); + manager.finishPlotMerge(plotIds); return true; } @@ -909,7 +894,7 @@ public abstract class PlotArea { * @param pos2 second corner of selection * @return the plots in the selection which are owned */ - public Set getPlotSelectionOwned(@Nonnull final PlotId pos1, @Nonnull final PlotId pos2) { + public Set getPlotSelectionOwned(@NotNull final PlotId pos1, @NotNull final PlotId pos2) { final int size = (1 + pos2.x - pos1.x) * (1 + pos2.y - pos1.y); final Set result = new HashSet<>(); if (size < 16 || size < getPlotCount()) { @@ -944,9 +929,10 @@ public abstract class PlotArea { public void addCluster(@Nullable final PlotCluster plotCluster) { if (this.clusters == null) { this.clusters = new QuadMap(Integer.MAX_VALUE, 0, 0, 62) { - @Override public RegionWrapper getRegion(PlotCluster value) { - return new RegionWrapper(value.getP1().x, value.getP2().x, value.getP1().y, - value.getP2().y); + @Override public CuboidRegion getRegion(PlotCluster value) { + BlockVector2 pos1 = BlockVector2.at(value.getP1().x, value.getP1().y); + BlockVector2 pos2 = BlockVector2.at(value.getP2().x, value.getP2().y); + return new CuboidRegion(pos1.toBlockVector3(), pos2.toBlockVector3(Plot.MAX_HEIGHT - 1)); } }; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotBlock.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotBlock.java deleted file mode 100644 index 79521908e..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotBlock.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.object; - -import com.github.intellectualsites.plotsquared.configuration.serialization.ConfigurationSerializable; -import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.google.common.collect.ImmutableMap; -import com.sk89q.worldedit.world.block.BaseBlock; -import lombok.NonNull; - -import java.util.Collection; -import java.util.Map; - -public abstract class PlotBlock implements ConfigurationSerializable { - - private static Class conversionType; - private static BlockRegistry blockRegistry; - - protected PlotBlock() { - } - - public static boolean isEverything(@NonNull final PlotBlock block) { - return block.equals(LegacyPlotBlock.EVERYTHING) || block.equals(StringPlotBlock.EVERYTHING); - } - - public static boolean containsEverything(@NonNull final Collection blocks) { - for (final PlotBlock block : blocks) { - if (isEverything(block)) { - return true; - } - } - return false; - } - - public static PlotBlock get(char combinedId) { - switch (combinedId) { - case 0: - return null; - case 1: - return get(0, 0); - default: - return get(combinedId >> 4, combinedId & 15); - } - } - - public static PlotBlock deserialize(@NonNull final Map map) { - if (map.containsKey("material")) { - final Object object = map.get("material"); - return get(object.toString()); - } - return null; - } - - public static StringPlotBlock get(@NonNull final String itemId) { - if (Settings.Enabled_Components.BLOCK_CACHE) { - return StringPlotBlock.getOrAdd(itemId); - } - return new StringPlotBlock(itemId); - } - - public static PlotBlock get(int id, int data) { - return Settings.Enabled_Components.BLOCK_CACHE && data > 0 ? - LegacyPlotBlock.CACHE[(id << 4) + data] : - new LegacyPlotBlock((short) id, (byte) data); - } - - public static PlotBlock getEmptyData(@NonNull final PlotBlock plotBlock) { - if (plotBlock instanceof StringPlotBlock) { - return plotBlock; - } - return get(((LegacyPlotBlock) plotBlock).getId(), (byte) 0); - } - - public static PlotBlock get(@NonNull final BaseBlock baseBlock) { - StringPlotBlock plotBlock = get(baseBlock.getBlockType().getId()); - plotBlock.setBaseBlock(baseBlock); - return plotBlock; - } - - public static PlotBlock get(@NonNull final Object type) { - if (blockRegistry == null) { - blockRegistry = PlotSquared.imp().getBlockRegistry(); - if (blockRegistry == null) { - throw new UnsupportedOperationException( - "The PlotSquared implementation has not registered a custom block registry." - + " This method can't be used."); - } - conversionType = blockRegistry.getType(); - } - if (!type.getClass().equals(conversionType)) { - throw new UnsupportedOperationException( - "The PlotSquared implementation has not registered a block registry for this object type"); - } - return blockRegistry.getPlotBlock(type); - } - - @Override public Map serialize() { - return ImmutableMap.of("material", this.getRawId()); - } - - public T to(@NonNull final Class clazz) { - if (blockRegistry == null) { - blockRegistry = PlotSquared.imp().getBlockRegistry(); - if (blockRegistry == null) { - throw new UnsupportedOperationException( - "The PlotSquared implementation has not registered a custom block registry." - + " This method can't be used."); - } - conversionType = blockRegistry.getType(); - } - if (!clazz.equals(conversionType)) { - throw new UnsupportedOperationException( - "The PlotSquared implementation has not registered a block registry for this object type"); - } - return clazz.cast(blockRegistry.getItem(this)); - } - - public abstract boolean isAir(); - - public final boolean equalsAny(final int id, @NonNull final String stringId) { - if (this instanceof StringPlotBlock) { - final StringPlotBlock stringPlotBlock = (StringPlotBlock) this; - return stringPlotBlock.idEquals(stringId); - } - final LegacyPlotBlock legacyPlotBlock = (LegacyPlotBlock) this; - return legacyPlotBlock.id == id; - } - - @Override public abstract boolean equals(Object obj); - - @Override public abstract int hashCode(); - - @Override public abstract String toString(); - - public abstract Object getRawId(); - -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotCluster.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotCluster.java index a1134cbce..4a653d8dd 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotCluster.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotCluster.java @@ -2,6 +2,8 @@ package com.github.intellectualsites.plotsquared.plot.object; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.world.RegionUtil; +import com.sk89q.worldedit.regions.CuboidRegion; import java.util.HashSet; import java.util.UUID; @@ -15,7 +17,7 @@ public class PlotCluster { public int temp; private PlotId pos1; private PlotId pos2; - private RegionWrapper region; + private CuboidRegion region; public PlotCluster(PlotArea area, PlotId pos1, PlotId pos2, UUID owner) { this.area = area; @@ -56,10 +58,10 @@ public class PlotCluster { } private void setRegion() { - this.region = new RegionWrapper(this.pos1.x, this.pos2.x, this.pos1.y, this.pos2.y); + this.region = RegionUtil.createRegion(this.pos1.x, this.pos2.x, this.pos1.y, this.pos2.y); } - public RegionWrapper getRegion() { + public CuboidRegion getRegion() { return this.region; } @@ -126,17 +128,17 @@ public class PlotCluster { public Location getHome() { BlockLoc home = this.settings.getPosition(); Location toReturn; - if (home.y == 0) { + if (home.getY() == 0) { // default pos Plot center = getCenterPlot(); toReturn = center.getHome(); if (toReturn.getY() == 0) { PlotManager manager = this.area.getPlotManager(); - Location loc = manager.getSignLoc(this.area, center); - toReturn.setY(loc.getY()); + Location location = manager.getSignLoc(center); + toReturn.setY(location.getY()); } } else { - toReturn = getClusterBottom().add(home.x, home.y, home.z); + toReturn = getClusterBottom().add(home.getX(), home.getY(), home.getZ()); } int max = MainUtil.getHeighestBlock(this.area.worldname, toReturn.getX(), toReturn.getZ()); if (max > toReturn.getY()) { @@ -157,12 +159,12 @@ public class PlotCluster { public Location getClusterBottom() { PlotManager manager = this.area.getPlotManager(); - return manager.getPlotBottomLocAbs(this.area, getP1()); + return manager.getPlotBottomLocAbs(getP1()); } public Location getClusterTop() { PlotManager manager = this.area.getPlotManager(); - return manager.getPlotTopLocAbs(this.area, getP2()); + return manager.getPlotTopLocAbs(getP2()); } public boolean intersects(PlotId pos1, PlotId pos2) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotId.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotId.java index 10b9e4c71..a777a6b6f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotId.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotId.java @@ -1,7 +1,7 @@ package com.github.intellectualsites.plotsquared.plot.object; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class PlotId { /** @@ -25,6 +25,14 @@ public class PlotId { this.y = y; } + public int getX() { + return x; + } + + public int getY() { + return y; + } + /** * Get a Plot Id based on a string * @@ -32,15 +40,15 @@ public class PlotId { * @return the PlotId representation of the arguement * @throws IllegalArgumentException if the string does not contain a valid PlotId */ - @Nonnull public static PlotId fromString(@Nonnull String string) { + @NotNull public static PlotId fromString(@NotNull String string) { PlotId plot = fromStringOrNull(string); if (plot == null) throw new IllegalArgumentException("Cannot create PlotID. String invalid."); return plot; } - @Nullable public static PlotId fromStringOrNull(@Nonnull String string) { - String[] parts = string.split("[;|,]"); + @Nullable public static PlotId fromStringOrNull(@NotNull String string) { + String[] parts = string.split("[;,.]"); if (parts.length < 2) { return null; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotItemStack.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotItemStack.java index c0a9d93d0..b142eda79 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotItemStack.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotItemStack.java @@ -1,7 +1,9 @@ package com.github.intellectualsites.plotsquared.plot.object; -import com.github.intellectualsites.plotsquared.plot.util.StringComparison; -import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.item.ItemType; +import com.sk89q.worldedit.world.item.ItemTypes; +import com.sk89q.worldedit.world.registry.LegacyMapper; import lombok.Getter; public class PlotItemStack { @@ -9,7 +11,7 @@ public class PlotItemStack { public final int amount; public final String name; public final String[] lore; - @Getter private final PlotBlock plotBlock; + @Getter private final ItemType type; /** * @param id Legacy numerical item ID @@ -21,10 +23,11 @@ public class PlotItemStack { */ @Deprecated public PlotItemStack(final int id, final short data, final int amount, final String name, final String... lore) { + this.amount = amount; this.name = name; this.lore = lore; - this.plotBlock = PlotBlock.get(id, data); + this.type = LegacyMapper.getInstance().getItemFromLegacy(id, data); } /** @@ -35,10 +38,13 @@ public class PlotItemStack { */ public PlotItemStack(final String id, final int amount, final String name, final String... lore) { - StringComparison.ComparisonResult match = WorldUtil.IMP.getClosestBlock(id); - this.plotBlock = match.best; + this.type = ItemTypes.get(id); this.amount = amount; this.name = name; this.lore = lore; } + + public BlockState getBlockState() { + return type.getBlockType().getDefaultState(); + } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotManager.java index 7dc4185c8..e0fc16ddb 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotManager.java @@ -2,6 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.object; import com.github.intellectualsites.plotsquared.plot.commands.Template; import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.sk89q.worldedit.function.pattern.Pattern; import java.io.IOException; import java.util.Collections; @@ -10,65 +11,76 @@ import java.util.List; public abstract class PlotManager { + private final PlotArea plotArea; + + public PlotManager(PlotArea plotArea) { + this.plotArea = plotArea; + } + /* * Plot locations (methods with Abs in them will not need to consider mega * plots). */ - public abstract PlotId getPlotIdAbs(PlotArea plotArea, int x, int y, int z); + public abstract PlotId getPlotIdAbs(int x, int y, int z); - public abstract PlotId getPlotId(PlotArea plotArea, int x, int y, int z); + public abstract PlotId getPlotId(int x, int y, int z); // If you have a circular plot, just return the corner if it were a square - public abstract Location getPlotBottomLocAbs(PlotArea plotArea, PlotId plotId); + public abstract Location getPlotBottomLocAbs(PlotId plotId); // the same applies here - public abstract Location getPlotTopLocAbs(PlotArea plotArea, PlotId plotId); + public abstract Location getPlotTopLocAbs(PlotId plotId); /* * Plot clearing (return false if you do not support some method) */ - public abstract boolean clearPlot(PlotArea plotArea, Plot plot, Runnable whenDone); + public abstract boolean clearPlot(Plot plot, Runnable whenDone); - public abstract boolean claimPlot(PlotArea plotArea, Plot plot); + public abstract boolean claimPlot(Plot plot); - public abstract boolean unClaimPlot(PlotArea plotArea, Plot plot, Runnable whenDone); + public abstract boolean unClaimPlot(Plot plot, Runnable whenDone); - public abstract Location getSignLoc(PlotArea plotArea, Plot plot); + /** + * Retrieves the location of where a sign should be for a plot. + * + * @param plot The plot + * @return The location where a sign should be + */ + public abstract Location getSignLoc(Plot plot); /* * Plot set functions (return false if you do not support the specific set * method). */ - public abstract String[] getPlotComponents(PlotArea plotArea, PlotId plotId); + public abstract String[] getPlotComponents(PlotId plotId); - public abstract boolean setComponent(PlotArea plotArea, PlotId plotId, String component, - BlockBucket blocks); + public abstract boolean setComponent(PlotId plotId, String component, Pattern blocks); /* * PLOT MERGING (return false if your generator does not support plot * merging). */ - public abstract boolean createRoadEast(PlotArea plotArea, Plot plot); + public abstract boolean createRoadEast(Plot plot); - public abstract boolean createRoadSouth(PlotArea plotArea, Plot plot); + public abstract boolean createRoadSouth(Plot plot); - public abstract boolean createRoadSouthEast(PlotArea plotArea, Plot plot); + public abstract boolean createRoadSouthEast(Plot plot); - public abstract boolean removeRoadEast(PlotArea plotArea, Plot plot); + public abstract boolean removeRoadEast(Plot plot); - public abstract boolean removeRoadSouth(PlotArea plotArea, Plot plot); + public abstract boolean removeRoadSouth(Plot plot); - public abstract boolean removeRoadSouthEast(PlotArea plotArea, Plot plot); + public abstract boolean removeRoadSouthEast(Plot plot); - public abstract boolean startPlotMerge(PlotArea plotArea, List plotIds); + public abstract boolean startPlotMerge(List plotIds); - public abstract boolean startPlotUnlink(PlotArea plotArea, List plotIds); + public abstract boolean startPlotUnlink(List plotIds); - public abstract boolean finishPlotMerge(PlotArea plotArea, List plotIds); + public abstract boolean finishPlotMerge(List plotIds); - public abstract boolean finishPlotUnlink(PlotArea plotArea, List plotIds); + public abstract boolean finishPlotUnlink(List plotIds); - public void exportTemplate(PlotArea plotArea) throws IOException { + public void exportTemplate() throws IOException { HashSet files = new HashSet<>(Collections.singletonList( new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", Template.getBytes(plotArea)))); @@ -79,4 +91,21 @@ public abstract class PlotManager { return 255; } + /** + * Sets all the blocks along all the plot walls to their correct state (claimed or unclaimed). + * + * @return true if the wall blocks were successfully set + */ + public boolean regenerateAllPlotWalls() { + boolean success = true; + for (Plot plot : plotArea.getPlots()) { + if (plot.hasOwner()) { + success &= claimPlot(plot); + } else { + success &= unClaimPlot(plot, null); + } + } + return success; + } + } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotPlayer.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotPlayer.java index dd2dc28b5..059f20559 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotPlayer.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotPlayer.java @@ -10,13 +10,26 @@ import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager; import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.PlotWeather; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; +import com.google.common.base.Preconditions; +import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.world.gamemode.GameMode; +import com.sk89q.worldedit.world.item.ItemType; import lombok.NonNull; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.nio.ByteBuffer; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @@ -74,6 +87,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { return UUIDHandler.getPlayer(name); } + public abstract Actor toActor(); + /** * Set some session only metadata for this player. * @@ -113,6 +128,9 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { return meta; } + public ConcurrentHashMap getMeta() { + return meta; + } /** * Delete the metadata for a key. * - metadata is session only @@ -166,15 +184,15 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { } public int hasPermissionRange(String stub, int range) { - if (hasPermission(Captions.PERMISSION_ADMIN.s())) { + if (hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { return Integer.MAX_VALUE; } String[] nodes = stub.split("\\."); StringBuilder builder = new StringBuilder(); for (int i = 0; i < (nodes.length - 1); i++) { builder.append(nodes[i]).append("."); - if (!stub.equals(builder + Captions.PERMISSION_STAR.s())) { - if (hasPermission(builder + Captions.PERMISSION_STAR.s())) { + if (!stub.equals(builder + Captions.PERMISSION_STAR.getTranslated())) { + if (hasPermission(builder + Captions.PERMISSION_STAR.getTranslated())) { return Integer.MAX_VALUE; } } @@ -298,7 +316,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { * * @return The location */ - public Location getLocation() { + @NotNull public Location getLocation() { Location location = getMeta("location"); if (location != null) { return location; @@ -327,19 +345,29 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { * * @return UUID */ - @Override @Nonnull public abstract UUID getUUID(); + @Override @NotNull public abstract UUID getUUID(); - public boolean canTeleport(Location loc) { - Location current = getLocationFull(); - teleport(loc); + public boolean canTeleport(@NotNull final Location location) { + Preconditions.checkNotNull(location, "Specified location cannot be null"); + final Location current = getLocationFull(); + teleport(location); boolean result = true; - if (!getLocation().equals(loc)) { + if (!getLocation().equals(location)) { result = false; } teleport(current); return result; } + public void sendTitle(String title, String subtitle) { + sendTitle(title, subtitle, 10, 50, 10); + } + + ; + + public abstract void sendTitle(String title, String subtitle, int fadeIn, int stay, + int fadeOut); + /** * Teleport this player to a location. * @@ -403,21 +431,21 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { * * @param weather the weather visible to the player */ - public abstract void setWeather(PlotWeather weather); + public abstract void setWeather(@NotNull PlotWeather weather); /** * Get this player's gamemode. * * @return the gamemode of the player. */ - public abstract PlotGameMode getGameMode(); + public abstract @NotNull GameMode getGameMode(); /** * Set this player's gameMode. * * @param gameMode the gamemode to set */ - public abstract void setGameMode(PlotGameMode gameMode); + public abstract void setGameMode(@NotNull GameMode gameMode); /** * Set this player's local time (ticks). @@ -446,7 +474,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { * @param location where to play the music * @param id the record item id */ - public abstract void playMusic(Location location, PlotBlock id); + public abstract void playMusic(@NotNull Location location, @NotNull ItemType id); /** * Check if this player is banned. @@ -475,10 +503,10 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { ByteBuffer buffer = ByteBuffer.allocate(13); buffer.putShort((short) x); buffer.putShort((short) z); - Location loc = getLocation(); - buffer.putInt(loc.getX()); - buffer.put((byte) loc.getY()); - buffer.putInt(loc.getZ()); + Location location = getLocation(); + buffer.putInt(location.getX()); + buffer.put((byte) location.getY()); + buffer.putInt(location.getZ()); setPersistentMeta("quitLoc", buffer.array()); } else if (hasPersistentMeta("quitLoc")) { removePersistentMeta("quitLoc"); @@ -578,13 +606,14 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { return; } - final Location loc = new Location(plot.getWorldName(), x, y, z); + final Location location = new Location(plot.getWorldName(), x, y, z); if (plot.isLoaded()) { TaskManager.runTask(() -> { if (getMeta("teleportOnLogin", true)) { - teleport(loc); + teleport(location); sendMessage( - Captions.TELEPORTED_TO_PLOT.f() + " (quitLoc) (" + plotX + Captions.format(Captions.TELEPORTED_TO_PLOT.getTranslated()) + + " (quitLoc) (" + plotX + "," + plotZ + ")"); } }); @@ -594,8 +623,9 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer { TaskManager.runTask(() -> { if (getMeta("teleportOnLogin", true)) { if (plot.isLoaded()) { - teleport(loc); - sendMessage(Captions.TELEPORTED_TO_PLOT.f() + teleport(location); + sendMessage(Captions.format( + Captions.TELEPORTED_TO_PLOT.getTranslated()) + " (quitLoc-unloaded) (" + plotX + "," + plotZ + ")"); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotSettings.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotSettings.java index 829e42dbd..8d7904690 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotSettings.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/PlotSettings.java @@ -5,7 +5,12 @@ import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.comment.PlotComment; import com.google.common.collect.ImmutableList; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; /** * Generic settings class. @@ -80,6 +85,17 @@ public class PlotSettings { return false; } + public boolean setMerged(Direction direction, boolean merged) { + if (Direction.ALL == direction) { + throw new IllegalArgumentException("You cannot use Direction.ALL in this method!"); + } + if (this.merged[direction.getIndex()] != merged) { + this.merged[direction.getIndex()] = merged; + return true; + } + return false; + } + public BlockLoc getPosition() { if (this.position == null) { return new BlockLoc(0, 0, 0); @@ -88,7 +104,7 @@ public class PlotSettings { } public void setPosition(BlockLoc position) { - if (position != null && position.x == 0 && position.y == 0 && position.z == 0) { + if (position != null && position.getX() == 0 && position.getY() == 0 && position.getZ() == 0) { position = null; } this.position = position; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Rating.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Rating.java index 00fe5bcc2..911b2e6c5 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Rating.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/Rating.java @@ -5,7 +5,6 @@ import com.github.intellectualsites.plotsquared.plot.config.Settings; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Map.Entry; import java.util.stream.IntStream; public class Rating { @@ -55,7 +54,7 @@ public class Rating { if (Settings.Ratings.USE_LIKES) { return getLike() ? 10 : 1; } - double total = this.ratingMap.entrySet().stream().mapToDouble(Entry::getValue).sum(); + double total = this.ratingMap.values().stream().mapToDouble(v -> v).sum(); return total / this.ratingMap.size(); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/RegionWrapper.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/RegionWrapper.java deleted file mode 100644 index ced127a22..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/RegionWrapper.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.object; - -public class RegionWrapper { - public final int minX; - public final int maxX; - public final int minY; - public final int maxY; - public final int minZ; - public final int maxZ; - - public RegionWrapper(int minX, int maxX, int minZ, int maxZ) { - this.maxX = maxX; - this.minX = minX; - this.maxZ = maxZ; - this.minZ = minZ; - this.minY = 0; - this.maxY = 256; - } - - public RegionWrapper(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { - this.maxX = maxX; - this.minX = minX; - this.maxZ = maxZ; - this.minZ = minZ; - this.minY = minY; - this.maxY = maxY; - } - - public boolean isIn(int x, int y, int z) { - return x >= this.minX && x <= this.maxX && z >= this.minZ && z <= this.maxZ - && y >= this.minY && y <= this.maxY; - } - - public boolean isIn(int x, int z) { - return x >= this.minX && x <= this.maxX && z >= this.minZ && z <= this.maxZ; - } - - public boolean intersects(RegionWrapper other) { - return other.minX <= this.maxX && other.maxX >= this.minX && other.minY <= this.maxY - && other.maxY >= this.minY; - } - - @Override public int hashCode() { - return this.minX + 13 * this.maxX + 23 * this.minZ + 39 * this.maxZ; - } - - @Override public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj instanceof RegionWrapper) { - RegionWrapper other = (RegionWrapper) obj; - return this.minX == other.minX && this.minZ == other.minZ && this.minY == other.minY - && this.maxX == other.maxX && this.maxZ == other.maxZ && this.maxY == other.maxY; - } - return false; - } - - @Override public String toString() { - return this.minX + "->" + this.maxX + "," + this.minZ + "->" + this.maxZ; - } - - public Location[] getCorners(String world) { - Location pos1 = new Location(world, this.minX, this.minY, this.minZ); - Location pos2 = new Location(world, this.maxX, this.maxY, this.maxZ); - return new Location[] {pos1, pos2}; - } -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/StringPlotBlock.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/StringPlotBlock.java deleted file mode 100644 index 706d1ae06..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/StringPlotBlock.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.object; - -import com.sk89q.worldedit.world.block.BaseBlock; -import lombok.Getter; -import lombok.NonNull; -import lombok.Setter; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -public class StringPlotBlock extends PlotBlock { - - public static final PlotBlock EVERYTHING = new StringPlotBlock("air"); - private static final Map STRING_PLOT_BLOCK_CACHE = new HashMap<>(); - @Getter private final String nameSpace; - @Getter private final String itemId; - @Getter @Setter private BaseBlock baseBlock = null; - private boolean isForeign = false; - - public StringPlotBlock(@NonNull final String nameSpace, @NonNull final String itemId) { - this.nameSpace = nameSpace.toLowerCase(Locale.ENGLISH); - this.itemId = itemId.toLowerCase(Locale.ENGLISH); - this.determineForeign(); - } - - public StringPlotBlock(@NonNull final String itemId) { - if (itemId.contains(":")) { - final String[] parts = itemId.split(":"); - if (parts.length < 2) { - throw new IllegalArgumentException(String.format("Cannot parse \"%s\"", itemId)); - } - this.nameSpace = parts[0].toLowerCase(Locale.ENGLISH); - this.itemId = parts[1].toLowerCase(Locale.ENGLISH); - } else { - this.nameSpace = "minecraft"; - if (itemId.isEmpty()) { - this.itemId = "air"; - } else { - this.itemId = itemId.toLowerCase(Locale.ENGLISH); - } - } - this.determineForeign(); - } - - public static StringPlotBlock getOrAdd(@NonNull final String itemId) { - // final String id = itemId.toLowerCase(Locale.ENGLISH); - - StringPlotBlock plotBlock = STRING_PLOT_BLOCK_CACHE.get(itemId); - if (plotBlock == null) { - plotBlock = new StringPlotBlock(itemId); - STRING_PLOT_BLOCK_CACHE.put(itemId, plotBlock); - } - - return plotBlock; - } - - private void determineForeign() { - this.isForeign = !this.nameSpace.equals("minecraft"); - } - - @Override public String toString() { - return this.isForeign ? String.format("%s:%s", nameSpace, itemId) : itemId; - } - - @Override public boolean isAir() { - return this.itemId.isEmpty() || this.itemId.equalsIgnoreCase("air"); - } - - @Override public int hashCode() { - return this.toString().hashCode(); - } - - public boolean idEquals(@NonNull final String id) { - return id.equalsIgnoreCase(this.itemId); - } - - @Override public Object getRawId() { - return this.getItemId(); - } - - @Override public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - StringPlotBlock other = (StringPlotBlock) obj; - return other.nameSpace.equals(this.nameSpace) && other.itemId.equals(this.itemId); - } -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/collection/FlatRandomCollection.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/collection/FlatRandomCollection.java index dd7803d66..341fbb4f3 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/collection/FlatRandomCollection.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/collection/FlatRandomCollection.java @@ -13,7 +13,7 @@ public class FlatRandomCollection extends RandomCollection { super(weights, random); int max = 0; int[] counts = new int[weights.size()]; - Double[] weightDoubles = weights.values().toArray(new Double[weights.size()]); + Double[] weightDoubles = weights.values().toArray(new Double[0]); for (int i = 0; i < weightDoubles.length; i++) { int weight = (int) (weightDoubles[i] * 100); counts[i] = weight; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/schematic/ItemType.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/schematic/ItemType.java deleted file mode 100644 index f558b5243..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/schematic/ItemType.java +++ /dev/null @@ -1,307 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.object.schematic; - -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -public enum ItemType { - AIR("air", 0), STONE("stone", 1), GRANITE("stone", 1, 1), POLISHED_GRANITE("stone", 1, - 2), DIORITE("stone", 1, 3), POLISHED_DIORITE("stone", 1, 4), ANDESITE("stone", 1, - 5), POLISHED_ANDESITE("stone", 1, 6), GRASS("grass", 2), DIRT("dirt", 3), COARSE_DIRT( - "dirt", 3, 1), PODZOL("dirt", 3, 2), COBBLESTONE("cobblestone", 4), OAK_WOOD_PLANK("planks", - 5), SPRUCE_WOOD_PLANK("planks", 5, 1), BIRCH_WOOD_PLANK("planks", 5, 2), JUNGLE_WOOD_PLANK( - "planks", 5, 3), ACACIA_WOOD_PLANK("planks", 5, 4), DARK_OAK_WOOD_PLANK("planks", 5, - 5), OAK_SAPLING("sapling", 6), SPRUCE_SAPLING("sapling", 6, 1), BIRCH_SAPLING("sapling", 6, - 2), JUNGLE_SAPLING("sapling", 6, 3), ACACIA_SAPLING("sapling", 6, 4), DARK_OAK_SAPLING( - "sapling", 6, 5), BEDROCK("bedrock", 7), FLOWING_WATER("flowing_water", 8), STILL_WATER( - "water", 9), FLOWING_LAVA("flowing_lava", 10), STILL_LAVA("lava", 11), SAND("sand", - 12), RED_SAND("sand", 12, 1), GRAVEL("gravel", 13), GOLD_ORE("gold_ore", 14), IRON_ORE( - "iron_ore", 15), COAL_ORE("coal_ore", 16), OAK_WOOD("log", 17), SPRUCE_WOOD("log", 17, - 1), BIRCH_WOOD("log", 17, 2), JUNGLE_WOOD("log", 17, 3), OAK_LEAVES("leaves", - 18), SPRUCE_LEAVES("leaves", 18, 1), BIRCH_LEAVES("leaves", 18, 2), JUNGLE_LEAVES("leaves", - 18, 3), SPONGE("sponge", 19), WET_SPONGE("sponge", 19, 1), GLASS("glass", - 20), LAPIS_LAZULI_ORE("lapis_ore", 21), LAPIS_LAZULI_BLOCK("lapis_block", 22), DISPENSER( - "dispenser", 23), SANDSTONE("sandstone", 24), CHISELED_SANDSTONE("sandstone", 24, - 1), SMOOTH_SANDSTONE("sandstone", 24, 2), NOTE_BLOCK("noteblock", 25), BED("bed", - 26), POWERED_RAIL("golden_rail", 27), DETECTOR_RAIL("detector_rail", 28), STICKY_PISTON( - "sticky_piston", 29), COBWEB("web", 30), DEAD_SHRUB("tallgrass", 31), TALLGRASS("tallgrass", - 31, 1), FERN("tallgrass", 31, 2), DEAD_SHRUB1("deadbush", 32), PISTON("piston", - 33), PISTON_HEAD("piston_head", 34), WHITE_WOOL("wool", 35), ORANGE_WOOL("wool", 35, - 1), MAGENTA_WOOL("wool", 35, 2), LIGHT_BLUE_WOOL("wool", 35, 3), YELLOW_WOOL("wool", 35, - 4), LIME_WOOL("wool", 35, 5), PINK_WOOL("wool", 35, 6), GRAY_WOOL("wool", 35, - 7), LIGHT_GRAY_WOOL("wool", 35, 8), CYAN_WOOL("wool", 35, 9), PURPLE_WOOL("wool", 35, - 10), BLUE_WOOL("wool", 35, 11), BROWN_WOOL("wool", 35, 12), GREEN_WOOL("wool", 35, - 13), RED_WOOL("wool", 35, 14), BLACK_WOOL("wool", 35, 15), DANDELION("yellow_flower", - 37), POPPY("red_flower", 38), BLUE_ORCHID("red_flower", 38, 1), ALLIUM("red_flower", 38, - 2), AZURE_BLUET("red_flower", 38, 3), RED_TULIP("red_flower", 38, 4), ORANGE_TULIP( - "red_flower", 38, 5), WHITE_TULIP("red_flower", 38, 6), PINK_TULIP("red_flower", 38, - 7), OXEYE_DAISY("red_flower", 38, 8), BROWN_MUSHROOM("brown_mushroom", 39), RED_MUSHROOM( - "red_mushroom", 40), GOLD_BLOCK("gold_block", 41), IRON_BLOCK("iron_block", - 42), DOUBLE_STONE_SLAB("double_stone_slab", 43), DOUBLE_SANDSTONE_SLAB("double_stone_slab", - 43, 1), DOUBLE_WOODEN_SLAB("double_stone_slab", 43, 2), DOUBLE_COBBLESTONE_SLAB( - "double_stone_slab", 43, 3), DOUBLE_BRICK_SLAB("double_stone_slab", 43, - 4), DOUBLE_STONE_BRICK_SLAB("double_stone_slab", 43, 5), DOUBLE_NETHER_BRICK_SLAB( - "double_stone_slab", 43, 6), DOUBLE_QUARTZ_SLAB("double_stone_slab", 43, 7), STONE_SLAB( - "stone_slab", 44), SANDSTONE_SLAB("stone_slab", 44, 1), WOODEN_SLAB("stone_slab", 44, - 2), COBBLESTONE_SLAB("stone_slab", 44, 3), BRICK_SLAB("stone_slab", 44, - 4), STONE_BRICK_SLAB("stone_slab", 44, 5), NETHER_BRICK_SLAB("stone_slab", 44, - 6), QUARTZ_SLAB("stone_slab", 44, 7), BRICKS("brick_block", 45), TNT("tnt", 46), BOOKSHELF( - "bookshelf", 47), MOSS_STONE("mossy_cobblestone", 48), OBSIDIAN("obsidian", 49), TORCH( - "torch", 50), FIRE("fire", 51), MONSTER_SPAWNER("mob_spawner", 52), OAK_WOOD_STAIRS( - "oak_stairs", 53), CHEST("chest", 54), REDSTONE_WIRE("redstone_wire", 55), DIAMOND_ORE( - "diamond_ore", 56), DIAMOND_BLOCK("diamond_block", 57), CRAFTING_TABLE("crafting_table", - 58), WHEAT_CROPS("wheat", 59), FARMLAND("farmland", 60), FURNACE("furnace", - 61), BURNING_FURNACE("lit_furnace", 62), STANDING_SIGN_BLOCK("standing_sign", - 63), OAK_DOOR_BLOCK("wooden_door", 64), LADDER("ladder", 65), RAIL("rail", - 66), COBBLESTONE_STAIRS("stone_stairs", 67), WALL_MOUNTED_SIGN_BLOCK("wall_sign", - 68), LEVER("lever", 69), STONE_PRESSURE_PLATE("stone_pressure_plate", 70), IRON_DOOR_BLOCK( - "iron_door", 71), WOODEN_PRESSURE_PLATE("wooden_pressure_plate", 72), REDSTONE_ORE( - "redstone_ore", 73), GLOWING_REDSTONE_ORE("lit_redstone_ore", 74), REDSTONE_TORCH_OFF( - "unlit_redstone_torch", 75), REDSTONE_TORCH_ON("redstone_torch", 76), STONE_BUTTON( - "stone_button", 77), SNOW("snow_layer", 78), ICE("ice", 79), SNOW_BLOCK("snow", 80), CACTUS( - "cactus", 81), CLAY("clay", 82), SUGAR_CANES("reeds", 83), JUKEBOX("jukebox", - 84), OAK_FENCE("fence", 85), PUMPKIN("pumpkin", 86), NETHERRACK("netherrack", - 87), SOUL_SAND("soul_sand", 88), GLOWSTONE("glowstone", 89), NETHER_PORTAL("portal", - 90), JACK_OLANTERN("lit_pumpkin", 91), CAKE_BLOCK("cake", 92), REDSTONE_REPEATER_BLOCK_OFF( - "unpowered_repeater", 93), REDSTONE_REPEATER_BLOCK_ON("powered_repeater", - 94), WHITE_STAINED_GLASS("stained_glass", 95), ORANGE_STAINED_GLASS("stained_glass", 95, - 1), MAGENTA_STAINED_GLASS("stained_glass", 95, 2), LIGHT_BLUE_STAINED_GLASS("stained_glass", - 95, 3), YELLOW_STAINED_GLASS("stained_glass", 95, 4), LIME_STAINED_GLASS("stained_glass", - 95, 5), PINK_STAINED_GLASS("stained_glass", 95, 6), GRAY_STAINED_GLASS("stained_glass", 95, - 7), LIGHT_GRAY_STAINED_GLASS("stained_glass", 95, 8), CYAN_STAINED_GLASS("stained_glass", - 95, 9), PURPLE_STAINED_GLASS("stained_glass", 95, 10), BLUE_STAINED_GLASS("stained_glass", - 95, 11), BROWN_STAINED_GLASS("stained_glass", 95, 12), GREEN_STAINED_GLASS("stained_glass", - 95, 13), RED_STAINED_GLASS("stained_glass", 95, 14), BLACK_STAINED_GLASS("stained_glass", - 95, 15), WOODEN_TRAPDOOR("trapdoor", 96), STONE_MONSTER_EGG("monster_egg", - 97), COBBLESTONE_MONSTER_EGG("monster_egg", 97, 1), STONE_BRICK_MONSTER_EGG("monster_egg", - 97, 2), MOSSY_STONE_BRICK_MONSTER_EGG("monster_egg", 97, - 3), CRACKED_STONE_BRICK_MONSTER_EGG("monster_egg", 97, 4), CHISELED_STONE_BRICK_MONSTER_EGG( - "monster_egg", 97, 5), STONE_BRICKS("stonebrick", 98), MOSSY_STONE_BRICKS("stonebrick", 98, - 1), CRACKED_STONE_BRICKS("stonebrick", 98, 2), CHISELED_STONE_BRICKS("stonebrick", 98, - 3), RED_MUSHROOM_CAP("stonebrick", 99), BROWN_MUSHROOM_CAP("stonebrick", 100), IRON_BARS( - "iron_bars", 101), GLASS_PANE("glass_pane", 102), MELON_BLOCK("melon_block", - 103), PUMPKIN_STEM("pumpkin_stem", 104), MELON_STEM("melon_stem", 105), VINES("vine", - 106), OAK_FENCE_GATE("fence_gate", 107), BRICK_STAIRS("brick_stairs", - 108), STONE_BRICK_STAIRS("stone_brick_stairs", 109), MYCELIUM("mycelium", 110), LILY_PAD( - "waterlily", 111), NETHER_BRICK("nether_brick", 112), NETHER_BRICK_FENCE( - "nether_brick_fence", 113), NETHER_BRICK_STAIRS("nether_brick_stairs", 114), NETHER_WART( - "nether_wart", 115), ENCHANTMENT_TABLE("enchanting_table", 116), BREWING_STAND( - "brewing_stand", 117), CAULDRON("cauldron", 118), END_PORTAL("end_portal", - 119), END_PORTAL_FRAME("end_portal_frame", 120), END_STONE("end_stone", 121), DRAGON_EGG( - "dragon_egg", 122), REDSTONE_LAMP_INACTIVE("redstone_lamp", 123), REDSTONE_LAMP_ACTIVE( - "lit_redstone_lamp", 124), DOUBLE_OAK_WOOD_SLAB("double_wooden_slab", - 125), DOUBLE_SPRUCE_WOOD_SLAB("double_wooden_slab", 125, 1), DOUBLE_BIRCH_WOOD_SLAB( - "double_wooden_slab", 125, 2), DOUBLE_JUNGLE_WOOD_SLAB("double_wooden_slab", 125, - 3), DOUBLE_ACACIA_WOOD_SLAB("double_wooden_slab", 125, 4), DOUBLE_DARK_OAK_WOOD_SLAB( - "double_wooden_slab", 125, 5), OAK_WOOD_SLAB("wooden_slab", 126), SPRUCE_WOOD_SLAB( - "wooden_slab", 126, 1), BIRCH_WOOD_SLAB("wooden_slab", 126, 2), JUNGLE_WOOD_SLAB( - "wooden_slab", 126, 3), ACACIA_WOOD_SLAB("wooden_slab", 126, 4), DARK_OAK_WOOD_SLAB( - "wooden_slab", 126, 5), COCOA("cocoa", 127), SANDSTONE_STAIRS("sandstone_stairs", - 128), EMERALD_ORE("emerald_ore", 129), ENDER_CHEST("ender_chest", 130), TRIPWIRE_HOOK( - "tripwire_hook", 131), TRIPWIRE("tripwire_hook", 132), EMERALD_BLOCK("emerald_block", - 133), SPRUCE_WOOD_STAIRS("spruce_stairs", 134), BIRCH_WOOD_STAIRS("birch_stairs", - 135), JUNGLE_WOOD_STAIRS("jungle_stairs", 136), COMMAND_BLOCK("command_block", 137), BEACON( - "beacon", 138), COBBLESTONE_WALL("cobblestone_wall", 139), MOSSY_COBBLESTONE_WALL( - "cobblestone_wall", 139, 1), FLOWER_POT("flower_pot", 140), CARROTS("carrots", - 141), POTATOES("potatoes", 142), WOODEN_BUTTON("wooden_button", 143), MOB_HEAD("skull", - 144), ANVIL("anvil", 145), TRAPPED_CHEST("trapped_chest", - 146), WEIGHTED_PRESSURE_PLATE_LIGHT("light_weighted_pressure_plate", - 147), WEIGHTED_PRESSURE_PLATE_HEAVY("heavy_weighted_pressure_plate", - 148), REDSTONE_COMPARATOR_INACTIVE("unpowered_comparator", 149), REDSTONE_COMPARATOR_ACTIVE( - "powered_comparator", 150), DAYLIGHT_SENSOR("daylight_detector", 151), REDSTONE_BLOCK( - "redstone_block", 152), NETHER_QUARTZ_ORE("quartz_ore", 153), HOPPER("hopper", - 154), QUARTZ_BLOCK("quartz_block", 155), CHISELED_QUARTZ_BLOCK("quartz_block", 155, - 1), PILLAR_QUARTZ_BLOCK("quartz_block", 155, 2), QUARTZ_STAIRS("quartz_stairs", - 156), ACTIVATOR_RAIL("activator_rail", 157), DROPPER("dropper", 158), WHITE_STAINED_CLAY( - "stained_hardened_clay", 159), ORANGE_STAINED_CLAY("stained_hardened_clay", 159, - 1), MAGENTA_STAINED_CLAY("stained_hardened_clay", 159, 2), LIGHT_BLUE_STAINED_CLAY( - "stained_hardened_clay", 159, 3), YELLOW_STAINED_CLAY("stained_hardened_clay", 159, - 4), LIME_STAINED_CLAY("stained_hardened_clay", 159, 5), PINK_STAINED_CLAY( - "stained_hardened_clay", 159, 6), GRAY_STAINED_CLAY("stained_hardened_clay", 159, - 7), LIGHT_GRAY_STAINED_CLAY("stained_hardened_clay", 159, 8), CYAN_STAINED_CLAY( - "stained_hardened_clay", 159, 9), PURPLE_STAINED_CLAY("stained_hardened_clay", 159, - 10), BLUE_STAINED_CLAY("stained_hardened_clay", 159, 11), BROWN_STAINED_CLAY( - "stained_hardened_clay", 159, 12), GREEN_STAINED_CLAY("stained_hardened_clay", 159, - 13), RED_STAINED_CLAY("stained_hardened_clay", 159, 14), BLACK_STAINED_CLAY( - "stained_hardened_clay", 159, 15), WHITE_STAINED_GLASS_PANE("stained_glass_pane", - 160), ORANGE_STAINED_GLASS_PANE("stained_glass_pane", 160, 1), MAGENTA_STAINED_GLASS_PANE( - "stained_glass_pane", 160, 2), LIGHT_BLUE_STAINED_GLASS_PANE("stained_glass_pane", 160, - 3), YELLOW_STAINED_GLASS_PANE("stained_glass_pane", 160, 4), LIME_STAINED_GLASS_PANE( - "stained_glass_pane", 160, 5), PINK_STAINED_GLASS_PANE("stained_glass_pane", 160, - 6), GRAY_STAINED_GLASS_PANE("stained_glass_pane", 160, 7), LIGHT_GRAY_STAINED_GLASS_PANE( - "stained_glass_pane", 160, 8), CYAN_STAINED_GLASS_PANE("stained_glass_pane", 160, - 9), PURPLE_STAINED_GLASS_PANE("stained_glass_pane", 160, 10), BLUE_STAINED_GLASS_PANE( - "stained_glass_pane", 160, 11), BROWN_STAINED_GLASS_PANE("stained_glass_pane", 160, - 12), GREEN_STAINED_GLASS_PANE("stained_glass_pane", 160, 13), RED_STAINED_GLASS_PANE( - "stained_glass_pane", 160, 14), BLACK_STAINED_GLASS_PANE("stained_glass_pane", 160, - 15), ACACIA_LEAVES("leaves2", 161), DARK_OAK_LEAVES("leaves2", 161, 1), ACACIA_WOOD("log2", - 162), DARK_OAK_WOOD("log2", 162, 1), ACACIA_WOOD_STAIRS("acacia_stairs", - 163), DARK_OAK_WOOD_STAIRS("dark_oak_stairs", 164), SLIME_BLOCK("slime", 165), BARRIER( - "barrier", 166), IRON_TRAPDOOR("iron_trapdoor", 167), PRISMARINE("prismarine", - 168), PRISMARINE_BRICKS("prismarine", 168, 1), DARK_PRISMARINE("prismarine", 168, - 2), SEA_LANTERN("sea_lantern", 169), HAY_BALE("hay_block", 170), WHITE_CARPET("carpet", - 171), ORANGE_CARPET("carpet", 171, 1), MAGENTA_CARPET("carpet", 171, 2), LIGHT_BLUE_CARPET( - "carpet", 171, 3), YELLOW_CARPET("carpet", 171, 4), LIME_CARPET("carpet", 171, - 5), PINK_CARPET("carpet", 171, 6), GRAY_CARPET("carpet", 171, 7), LIGHT_GRAY_CARPET( - "carpet", 171, 8), CYAN_CARPET("carpet", 171, 9), PURPLE_CARPET("carpet", 171, - 10), BLUE_CARPET("carpet", 171, 11), BROWN_CARPET("carpet", 171, 12), GREEN_CARPET("carpet", - 171, 13), RED_CARPET("carpet", 171, 14), BLACK_CARPET("carpet", 171, 15), HARDENED_CLAY( - "hardened_clay", 172), BLOCK_OF_COAL("coal_block", 173), PACKED_ICE("packed_ice", - 174), SUNFLOWER("double_plant", 175), LILAC("double_plant", 175, 1), DOUBLE_TALLGRASS( - "double_plant", 175, 2), LARGE_FERN("double_plant", 175, 3), ROSE_BUSH("double_plant", 175, - 4), PEONY("double_plant", 175, 5), FREE_STANDING_BANNER("standing_banner", - 176), WALL_MOUNTED_BANNER("wall_banner", 177), INVERTED_DAYLIGHT_SENSOR( - "daylight_detector_inverted", 178), RED_SANDSTONE("red_sandstone", - 179), SMOOTH_RED_SANDSTONE("red_sandstone", 179, 1), CHISELED_RED_SANDSTONE("red_sandstone", - 179, 2), RED_SANDSTONE_STAIRS("red_sandstone_stairs", 180), DOUBLE_RED_SANDSTONE_SLAB( - "stone_slab2", 181), RED_SANDSTONE_SLAB("double_stone_slab2", 182), SPRUCE_FENCE_GATE( - "spruce_fence_gate", 183), BIRCH_FENCE_GATE("birch_fence_gate", 184), JUNGLE_FENCE_GATE( - "jungle_fence_gate", 185), DARK_OAK_FENCE_GATE("dark_oak_fence_gate", - 186), ACACIA_FENCE_GATE("acacia_fence_gate", 187), SPRUCE_FENCE("spruce_fence", - 188), BIRCH_FENCE("birch_fence", 189), JUNGLE_FENCE("jungle_fence", 190), DARK_OAK_FENCE( - "dark_oak_fence", 191), ACACIA_FENCE("acacia_fence", 192), SPRUCE_DOOR_BLOCK("spruce_door", - 193), BIRCH_DOOR_BLOCK("birch_door", 194), JUNGLE_DOOR_BLOCK("jungle_door", - 195), ACACIA_DOOR_BLOCK("acacia_door", 196), DARK_OAK_DOOR_BLOCK("dark_oak_door", - 197), IRON_SHOVEL("iron_shovel", 256), IRON_PICKAXE("iron_pickaxe", 257), IRON_AXE( - "iron_axe", 258), FLINT_AND_STEEL("flint_and_steel", 259), APPLE("apple", 260), BOW("bow", - 261), ARROW("arrow", 262), COAL("coal", 263), CHARCOAL("coal", 263, 1), DIAMOND("diamond", - 264), IRON_INGOT("iron_ingot", 265), GOLD_INGOT("gold_ingot", 266), IRON_SWORD("iron_sword", - 267), WOODEN_SWORD("wooden_sword", 268), WOODEN_SHOVEL("wooden_shovel", - 269), WOODEN_PICKAXE("wooden_pickaxe", 270), WOODEN_AXE("wooden_axe", 271), STONE_SWORD( - "stone_sword", 272), STONE_SHOVEL("stone_shovel", 273), STONE_PICKAXE("stone_pickaxe", - 274), STONE_AXE("stone_axe", 275), DIAMOND_SWORD("diamond_sword", 276), DIAMOND_SHOVEL( - "diamond_shovel", 277), DIAMOND_PICKAXE("diamond_pickaxe", 278), DIAMOND_AXE("diamond_axe", - 279), STICK("stick", 280), BOWL("bowl", 281), MUSHROOM_STEW("mushroom_stew", - 282), GOLDEN_SWORD("golden_sword", 283), GOLDEN_SHOVEL("golden_shovel", - 284), GOLDEN_PICKAXE("golden_pickaxe", 285), GOLDEN_AXE("golden_axe", 286), STRING("string", - 287), FEATHER("feather", 288), GUNPOWDER("gunpowder", 289), WOODEN_HOE("wooden_hoe", - 290), STONE_HOE("stone_hoe", 291), IRON_HOE("iron_hoe", 292), DIAMOND_HOE("diamond_hoe", - 293), GOLDEN_HOE("golden_hoe", 294), WHEAT_SEEDS("wheat_seeds", 295), WHEAT("wheat", - 296), BREAD("bread", 297), LEATHER_HELMET("leather_helmet", 298), LEATHER_TUNIC( - "leather_chestplate", 299), LEATHER_PANTS("leather_leggings", 300), LEATHER_BOOTS( - "leather_boots", 301), CHAINMAIL_HELMET("chainmail_helmet", 302), CHAINMAIL_CHESTPLATE( - "chainmail_chestplate", 303), CHAINMAIL_LEGGINGS("chainmail_leggings", - 304), CHAINMAIL_BOOTS("chainmail_boots", 305), IRON_HELMET("iron_helmet", - 306), IRON_CHESTPLATE("iron_chestplate", 307), IRON_LEGGINGS("iron_leggings", - 308), IRON_BOOTS("iron_boots", 309), DIAMOND_HELMET("diamond_helmet", - 310), DIAMOND_CHESTPLATE("diamond_chestplate", 311), DIAMOND_LEGGINGS("diamond_leggings", - 312), DIAMOND_BOOTS("diamond_boots", 313), GOLDEN_HELMET("golden_helmet", - 314), GOLDEN_CHESTPLATE("golden_chestplate", 315), GOLDEN_LEGGINGS("golden_leggings", - 316), GOLDEN_BOOTS("golden_boots", 317), FLINT("flint_and_steel", 318), RAW_PORKCHOP( - "porkchop", 319), COOKED_PORKCHOP("cooked_porkchop", 320), PAINTING("painting", - 321), GOLDEN_APPLE("golden_apple", 322), ENCHANTED_GOLDEN_APPLE("golden_apple", 322, - 1), SIGN("sign", 323), OAK_DOOR("wooden_door", 324), BUCKET("bucket", 325), WATER_BUCKET( - "water_bucket", 326), LAVA_BUCKET("lava_bucket", 327), MINECART("minecart", 328), SADDLE( - "saddle", 329), IRON_DOOR("iron_door", 330), REDSTONE("redstone", 331), SNOWBALL("snowball", - 332), BOAT("boat", 333), LEATHER("leather", 334), MILK_BUCKET("milk_bucket", 335), BRICK( - "brick", 336), CLAY1("clay_ball", 337), SUGAR_CANES1("reeds", 338), PAPER("paper", - 339), BOOK("book", 340), SLIMEBALL("slime_ball", 341), MINECART_WITH_CHEST("chest_minecart", - 342), MINECART_WITH_FURNACE("furnace_minecart", 343), EGG("egg", 344), COMPASS("compass", - 345), FISHING_ROD("fishing_rod", 346), CLOCK("clock", 347), GLOWSTONE_DUST("glowstone_dust", - 348), RAW_FISH("fish", 349), RAW_SALMON("fish", 349, 1), CLOWNFISH("fish", 349, - 2), PUFFERFISH("fish", 349, 3), COOKED_FISH("cooked_fish", 350), COOKED_SALMON( - "cooked_fish", 350, 1), INK_SACK("dye", 351), ROSE_RED("dye", 351, 1), CACTUS_GREEN("dye", - 351, 2), COCO_BEANS("dye", 351, 3), LAPIS_LAZULI("dye", 351, 4), PURPLE_DYE("dye", 351, - 5), CYAN_DYE("dye", 351, 6), LIGHT_GRAY_DYE("dye", 351, 7), GRAY_DYE("dye", 351, - 8), PINK_DYE("dye", 351, 9), LIME_DYE("dye", 351, 10), DANDELION_YELLOW("dye", 351, - 11), LIGHT_BLUE_DYE("dye", 351, 12), MAGENTA_DYE("dye", 351, 13), ORANGE_DYE("dye", 351, - 14), BONE_MEAL("dye", 351, 15), BONE("bone", 352), SUGAR("sugar", 353), CAKE("cake", - 354), BED1("bed", 355), REDSTONE_REPEATER("repeater", 356), COOKIE("cookie", 357), MAP( - "filled_map", 358), SHEARS("shears", 359), MELON("melon", 360), PUMPKIN_SEEDS( - "pumpkin_seeds", 361), MELON_SEEDS("melon_seeds", 362), RAW_BEEF("beef", 363), STEAK( - "cooked_beef", 364), RAW_CHICKEN("chicken", 365), COOKED_CHICKEN("cooked_chicken", - 366), ROTTEN_FLESH("rotten_flesh", 367), ENDER_PEARL("ender_pearl", 368), BLAZE_ROD( - "blaze_rod", 369), GHAST_TEAR("ghast_tear", 370), GOLD_NUGGET("gold_nugget", - 371), NETHER_WART1("nether_wart", 372), POTION("potion", 373), GLASS_BOTTLE("glass_bottle", - 374), SPIDER_EYE("spider_eye", 375), FERMENTED_SPIDER_EYE("fermented_spider_eye", - 376), BLAZE_POWDER("blaze_powder", 377), MAGMA_CREAM("magma_cream", 378), BREWING_STAND1( - "brewing_stand", 379), CAULDRON1("cauldron", 380), EYE_OF_ENDER("ender_eye", - 381), GLISTERING_MELON("speckled_melon", 382), SPAWN_CREEPER("spawn_egg", 383, - 50), SPAWN_SKELETON("spawn_egg", 383, 51), SPAWN_SPIDER("spawn_egg", 383, 52), SPAWN_ZOMBIE( - "spawn_egg", 383, 54), SPAWN_SLIME("spawn_egg", 383, 55), SPAWN_GHAST("spawn_egg", 383, - 56), SPAWN_PIGMAN("spawn_egg", 383, 57), SPAWN_ENDERMAN("spawn_egg", 383, - 58), SPAWN_CAVE_SPIDER("spawn_egg", 383, 59), SPAWN_SILVERFISH("spawn_egg", 383, - 60), SPAWN_BLAZE("spawn_egg", 383, 61), SPAWN_MAGMA_CUBE("spawn_egg", 383, 62), SPAWN_BAT( - "spawn_egg", 383, 65), SPAWN_WITCH("spawn_egg", 383, 66), SPAWN_ENDERMITE("spawn_egg", 383, - 67), SPAWN_GUARDIAN("spawn_egg", 383, 68), SPAWN_PIG("spawn_egg", 383, 90), SPAWN_SHEEP( - "spawn_egg", 383, 91), SPAWN_COW("spawn_egg", 383, 92), SPAWN_CHICKEN("spawn_egg", 383, - 93), SPAWN_SQUID("spawn_egg", 383, 94), SPAWN_WOLF("spawn_egg", 383, 95), SPAWN_MOOSHROOM( - "spawn_egg", 383, 96), SPAWN_OCELOT("spawn_egg", 383, 98), SPAWN_HORSE("spawn_egg", 383, - 100), SPAWN_RABBIT("spawn_egg", 383, 101), SPAWN_VILLAGER("spawn_egg", 383, - 120), BOTTLE_O_ENCHANTING("experience_bottle", 384), FIRE_CHARGE("fire_charge", - 385), BOOK_AND_QUILL("writable_book", 386), WRITTEN_BOOK("written_book", 387), EMERALD( - "emerald", 388), ITEM_FRAME("item_frame", 389), FLOWER_POT1("flower_pot", 390), CARROT( - "carrot", 391), POTATO("potato", 392), BAKED_POTATO("baked_potato", 393), POISONOUS_POTATO( - "poisonous_potato", 394), EMPTY_MAP("map", 395), GOLDEN_CARROT("golden_carrot", - 396), MOB_HEAD_SKELETON("skull", 397), MOB_HEAD_WITHER_SKELETON("skull", 397, - 1), MOB_HEAD_ZOMBIE("skull", 397, 2), MOB_HEAD_HUMAN("skull", 397, 3), MOB_HEAD_CREEPER( - "skull", 397, 4), CARROT_ON_A_STICK("carrot_on_a_stick", 398), NETHER_STAR("nether_star", - 399), PUMPKIN_PIE("pumpkin_pie", 400), FIREWORK_ROCKET("fireworks", 401), FIREWORK_STAR( - "firework_charge", 402), ENCHANTED_BOOK("enchanted_book", 403), REDSTONE_COMPARATOR( - "comparator", 404), NETHER_BRICK1("netherbrick", 405), NETHER_QUARTZ("quartz", - 406), MINECART_WITH_TNT("tnt_minecart", 407), MINECART_WITH_HOPPER("hopper_minecart", - 408), PRISMARINE_SHARD("prismarine_shard", 409), PRISMARINE_CRYSTALS("prismarine_crystals", - 410), RAW_RABBIT("rabbit", 411), COOKED_RABBIT("cooked_rabbit", 412), RABBIT_STEW( - "rabbit_stew", 413), RABBITS_FOOT("rabbit_foot", 414), RABBIT_HIDE("rabbit_hide", - 415), ARMOR_STAND("armor_stand", 416), IRON_HORSE_ARMOR("iron_horse_armor", - 417), GOLDEN_HORSE_ARMOR("golden_horse_armor", 418), DIAMOND_HORSE_ARMOR( - "diamond_horse_armor", 419), LEAD("lead", 420), NAME_TAG("name_tag", - 421), MINECART_WITH_COMMAND_BLOCK("command_block_minecart", 422), RAW_MUTTON("mutton", - 423), COOKED_MUTTON("cooked_mutton", 424), BANNER("banner", 425), SPRUCE_DOOR("spruce_door", - 427), BIRCH_DOOR("birch_door", 428), JUNGLE_DOOR("jungle_door", 429), ACACIA_DOOR( - "acacia_door", 430), DARK_OAK_DOOR("dark_oak_door", 431), DISC_13("record_13", - 2256), CAT_DISC("record_cat", 2257), BLOCKS_DISC("record_blocks", 2258), CHIRP_DISC( - "record_chirp", 2259), FAR_DISC("record_far", 2260), MALL_DISC("record_mall", - 2261), MELLOHI_DISC("record_mellohi", 2262), STAL_DISC("record_stal", 2263), STRAD_DISC( - "record_strad", 2264), WARD_DISC("record_ward", 2265), DISC_11("record_11", - 2266), WAIT_DISC("record_wait", 2267), END_ROD("end_rod", 198), CHORUS_PLANT("chorus_plant", - 199), CHORUS_FLOWER("chorus_flower", 200), PURPUR_BLOCK("purpur_block", 201), PURPUR_PILLAR( - "purpur_pillar", 202), PURPUR_STAIRS("purpur_stairs", 203), PURPUR_DOUBLE_SLAB( - "purpur_double_slab", 204), PURPUR_SLAB("purpur_slab", 205), END_BRICKS("end_bricks", - 206), BEETROOTS("beetroots", 207), GRASS_PATH("grass_path", 208), END_GATEWAY("end_gateway", - 209), REPEATING_COMMAND_BLOCK("repeating_command_block", 210), CHAIN_COMMAND_BLOCK( - "chain_command_block", 211), FROSTED_ICE("frosted_ice", 212), STRUCTURE_BLOCK( - "structure_block", 255); - - private static final Map ids = new HashMap<>(); - private static final Map datas = new HashMap<>(); - - static { - for (ItemType type : EnumSet.allOf(ItemType.class)) { - ids.put(type.name, type.id); - datas.put(type.name, type.data); - } - } - - private final int id; - private final byte data; - private final String name; - - ItemType(String name, int id) { - this.id = id; - this.data = 0; - this.name = name; - } - - ItemType(String name, int id, int data) { - this.id = id; - this.data = (byte) data; - this.name = name; - } - - public static int getId(String name) { - Integer value = ids.get(name); - if (value == null) { - return 0; - } - return value; - } - - public static byte getData(String name) { - Byte value = datas.get(name); - if (value == null) { - return 0; - } - return value; - } -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/schematic/PlotItem.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/schematic/PlotItem.java index 2b7e31295..16397d0da 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/schematic/PlotItem.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/schematic/PlotItem.java @@ -1,6 +1,6 @@ package com.github.intellectualsites.plotsquared.plot.object.schematic; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.sk89q.worldedit.world.item.ItemType; public class PlotItem { @@ -9,10 +9,10 @@ public class PlotItem { public final int z; // public final short[] id; // public final byte[] data; - public final PlotBlock[] types; + public final ItemType[] types; public final byte[] amount; - public PlotItem(short x, short y, short z, PlotBlock[] types, byte[] amount) { + public PlotItem(short x, short y, short z, ItemType[] types, byte[] amount) { this.x = x; this.y = y; this.z = z; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/schematic/Schematic.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/schematic/Schematic.java index b67b16b58..cdd1f25f1 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/schematic/Schematic.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/schematic/Schematic.java @@ -3,7 +3,7 @@ package com.github.intellectualsites.plotsquared.plot.object.schematic; import com.sk89q.jnbt.NBTOutputStream; import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; +import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.SpongeSchematicWriter; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BaseBlock; @@ -17,10 +17,10 @@ import java.util.Map; public class Schematic { // Lossy but fast - @Getter private final BlockArrayClipboard clipboard; + @Getter private final Clipboard clipboard; @Getter private Map flags = new HashMap<>(); - public Schematic(BlockArrayClipboard clip) { + public Schematic(Clipboard clip) { this.clipboard = clip; } @@ -30,8 +30,8 @@ public class Schematic { public boolean setBlock(BlockVector3 position, BaseBlock block) throws WorldEditException { if (clipboard.getRegion().contains(position)) { - BlockVector3 v = position.subtract(clipboard.getRegion().getMinimumPoint()); - clipboard.setBlock(v, block); + BlockVector3 vector3 = position.subtract(clipboard.getRegion().getMinimumPoint()); + clipboard.setBlock(vector3, block); return true; } else { return false; @@ -39,9 +39,9 @@ public class Schematic { } public void save(File file) throws IOException { - try (SpongeSchematicWriter ssw = new SpongeSchematicWriter( + try (SpongeSchematicWriter schematicWriter = new SpongeSchematicWriter( new NBTOutputStream(new FileOutputStream(file)))) { - ssw.write(clipboard); + schematicWriter.write(clipboard); } } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/DefaultPlotAreaManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/DefaultPlotAreaManager.java index 9a9abca74..c504af4fb 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/DefaultPlotAreaManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/DefaultPlotAreaManager.java @@ -2,11 +2,17 @@ package com.github.intellectualsites.plotsquared.plot.object.worlds; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; -import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.github.intellectualsites.plotsquared.plot.util.StringMan; import com.github.intellectualsites.plotsquared.plot.util.area.QuadMap; +import com.sk89q.worldedit.regions.CuboidRegion; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; public class DefaultPlotAreaManager implements PlotAreaManager { @@ -93,7 +99,7 @@ public class DefaultPlotAreaManager implements PlotAreaManager { QuadMap map = this.plotAreaGrid.get(plotArea.worldname); if (map == null) { map = new QuadMap(Integer.MAX_VALUE, 0, 0) { - @Override public RegionWrapper getRegion(PlotArea value) { + @Override public CuboidRegion getRegion(PlotArea value) { return value.getRegion(); } }; @@ -139,7 +145,11 @@ public class DefaultPlotAreaManager implements PlotAreaManager { return null; case 1: PlotArea pa = this.plotAreas[0]; - return pa.contains(location) ? pa : null; + if (pa.contains(location)) { + return pa; + } else { + return null; + } case 2: case 3: case 4: @@ -191,7 +201,7 @@ public class DefaultPlotAreaManager implements PlotAreaManager { } } - @Override public PlotArea[] getPlotAreas(String world, RegionWrapper region) { + @Override public PlotArea[] getPlotAreas(String world, CuboidRegion region) { if (region == null) { PlotArea[] areas = this.plotAreaMap.get(world); if (areas == null) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/PlotAreaManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/PlotAreaManager.java index 7a59dab9d..b34ad2787 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/PlotAreaManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/PlotAreaManager.java @@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.object.worlds; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; -import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; +import com.sk89q.worldedit.regions.CuboidRegion; public interface PlotAreaManager { PlotArea getApplicablePlotArea(Location location); @@ -11,7 +11,7 @@ public interface PlotAreaManager { PlotArea getPlotArea(String world, String id); - PlotArea[] getPlotAreas(String world, RegionWrapper region); + PlotArea[] getPlotAreas(String world, CuboidRegion region); PlotArea[] getAllPlotAreas(); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlot.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlot.java index 36d23c8f6..1a8c88b9f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlot.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlot.java @@ -2,18 +2,26 @@ package com.github.intellectualsites.plotsquared.plot.object.worlds; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.flag.Flag; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.google.common.collect.Sets; +import com.github.intellectualsites.plotsquared.plot.object.BlockLoc; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Collection; +import java.util.Collections; import java.util.HashSet; +import java.util.Set; import java.util.UUID; public class SinglePlot extends Plot { - private HashSet regions = Sets.newHashSet( - new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, - Integer.MAX_VALUE)); + private Set regions = Collections.singleton( + new CuboidRegion(BlockVector3.at(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE), + BlockVector3.at(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE))); public SinglePlot(PlotArea area, PlotId id, UUID owner) { super(area, id, owner); @@ -35,7 +43,7 @@ public class SinglePlot extends Plot { } @Override public String getWorldName() { - return getId().toCommaSeparatedString(); + return getId().getX() + "." + getId().getY(); } @Override public SinglePlotArea getArea() { @@ -60,7 +68,7 @@ public class SinglePlot extends Plot { return super.isLoaded(); } - @Nonnull @Override public HashSet getRegions() { + @NotNull @Override public Set getRegions() { return regions; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotArea.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotArea.java index a51ef110b..f04d340eb 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotArea.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotArea.java @@ -5,13 +5,20 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Configuration; import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; import com.github.intellectualsites.plotsquared.plot.generator.GridPlotWorld; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotLoc; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; +import com.github.intellectualsites.plotsquared.plot.object.PlotSettings; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.object.SetupObject; import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -26,6 +33,11 @@ public class SinglePlotArea extends GridPlotWorld { this.DEFAULT_HOME = new PlotLoc(Integer.MAX_VALUE, Integer.MAX_VALUE); } + @NotNull @Override + protected PlotManager createManager() { + return new SinglePlotManager(this); + } + @Override public void loadConfiguration(ConfigurationSection config) { VOID = config.getBoolean("void", false); } @@ -35,7 +47,7 @@ public class SinglePlotArea extends GridPlotWorld { } public void loadWorld(final PlotId id) { - String worldName = id.toCommaSeparatedString(); + String worldName = id.getX() + "." + id.getY(); if (WorldUtil.IMP.isWorld(worldName)) { return; } @@ -47,32 +59,39 @@ public class SinglePlotArea extends GridPlotWorld { setup.step = new ConfigurationNode[0]; setup.world = worldName; + File container = PlotSquared.imp().getWorldContainer(); + File destination = new File(container, worldName); + + {// convert old + File oldFile = new File(container, id.toCommaSeparatedString()); + if (oldFile.exists()) { + oldFile.renameTo(destination); + } + } // Duplicate 0;0 if (setup.type != 0) { - File container = PlotSquared.imp().getWorldContainer(); - File dest = new File(container, worldName); - if (!dest.exists()) { - File src = new File(container, "0,0"); + if (!destination.exists()) { + File src = new File(container, "0.0"); if (src.exists()) { - if (!dest.exists()) { - dest.mkdirs(); + if (!destination.exists()) { + destination.mkdirs(); } File levelDat = new File(src, "level.dat"); if (levelDat.exists()) { try { Files.copy(levelDat.toPath(), - new File(dest, levelDat.getName()).toPath()); + new File(destination, levelDat.getName()).toPath()); File data = new File(src, "data"); if (data.exists()) { - File dataDest = new File(dest, "data"); + File dataDest = new File(destination, "data"); dataDest.mkdirs(); for (File file : data.listFiles()) { Files.copy(file.toPath(), new File(dataDest, file.getName()).toPath()); } } - } catch (IOException ignore) { - ignore.printStackTrace(); + } catch (IOException exception) { + exception.printStackTrace(); } } } @@ -81,7 +100,7 @@ public class SinglePlotArea extends GridPlotWorld { TaskManager.IMP.sync(new RunnableVal() { @Override public void run(Object value) { - String worldName = id.toCommaSeparatedString(); + String worldName = id.getX() + "." + id.getY(); if (WorldUtil.IMP.isWorld(worldName)) { return; } @@ -108,38 +127,38 @@ public class SinglePlotArea extends GridPlotWorld { new ConfigurationNode("void", this.VOID, "Void world", Configuration.BOOLEAN)}; } - @Nullable @Override public Plot getOwnedPlot(@Nonnull final Location location) { + @Nullable @Override public Plot getOwnedPlot(@NotNull final Location location) { PlotId pid = PlotId.fromStringOrNull(location.getWorld()); Plot plot = pid == null ? null : this.plots.get(pid); return plot == null ? null : plot.getBasePlot(false); } - @Nullable @Override public Plot getOwnedPlotAbs(@Nonnull Location location) { + @Nullable @Override public Plot getOwnedPlotAbs(@NotNull Location location) { PlotId pid = PlotId.fromStringOrNull(location.getWorld()); return pid == null ? null : plots.get(pid); } - @Nullable @Override public Plot getPlot(@Nonnull final Location location) { + @Nullable @Override public Plot getPlot(@NotNull final Location location) { PlotId pid = PlotId.fromStringOrNull(location.getWorld()); return pid == null ? null : getPlot(pid); } - @Nullable @Override public Plot getPlotAbs(@Nonnull final Location location) { + @Nullable @Override public Plot getPlotAbs(@NotNull final Location location) { final PlotId pid = PlotId.fromStringOrNull(location.getWorld()); return pid == null ? null : getPlotAbs(pid); } - public boolean addPlot(@Nonnull Plot plot) { + public boolean addPlot(@NotNull Plot plot) { plot = adapt(plot); return super.addPlot(plot); } - @Override public boolean addPlotAbs(@Nonnull Plot plot) { + @Override public boolean addPlotAbs(@NotNull Plot plot) { plot = adapt(plot); return super.addPlotAbs(plot); } - @Override public boolean addPlotIfAbsent(@Nonnull Plot plot) { + @Override public boolean addPlotIfAbsent(@NotNull Plot plot) { plot = adapt(plot); return super.addPlotIfAbsent(plot); } @@ -155,7 +174,7 @@ public class SinglePlotArea extends GridPlotWorld { return p; } - @Nullable public Plot getPlotAbs(@Nonnull final PlotId id) { + @Nullable public Plot getPlotAbs(@NotNull final PlotId id) { Plot plot = getOwnedPlotAbs(id); if (plot == null) { return new SinglePlot(this, id); @@ -163,7 +182,7 @@ public class SinglePlotArea extends GridPlotWorld { return plot; } - @Nullable public Plot getPlot(@Nonnull PlotId id) { + @Nullable public Plot getPlot(@NotNull PlotId id) { // TODO Plot plot = getOwnedPlotAbs(id); if (plot == null) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotAreaManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotAreaManager.java index 95b303eea..e54ab6964 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotAreaManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotAreaManager.java @@ -2,9 +2,9 @@ package com.github.intellectualsites.plotsquared.plot.object.worlds; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; -import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.github.intellectualsites.plotsquared.plot.util.ArrayUtil; import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; +import com.sk89q.worldedit.regions.CuboidRegion; public class SinglePlotAreaManager extends DefaultPlotAreaManager { private final SinglePlotArea[] array; @@ -35,8 +35,7 @@ public class SinglePlotAreaManager extends DefaultPlotAreaManager { return true; } int mode = 0; - for (int i = 0; i < chars.length; i++) { - char c = chars[i]; + for (char c : chars) { switch (mode) { case 0: mode = 1; @@ -45,7 +44,7 @@ public class SinglePlotAreaManager extends DefaultPlotAreaManager { } case 1: if ((c <= '/') || (c >= ':')) { - if (c == ';' || c == ',') { + if (c == '.') { mode = 2; continue; } @@ -91,7 +90,7 @@ public class SinglePlotAreaManager extends DefaultPlotAreaManager { return isWorld(location.getWorld()) || location.getWorld().equals("*") ? area : null; } - @Override public PlotArea[] getPlotAreas(String world, RegionWrapper region) { + @Override public PlotArea[] getPlotAreas(String world, CuboidRegion region) { PlotArea[] found = super.getPlotAreas(world, region); if (found != null && found.length != 0) { return found; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotManager.java index 7146a898b..d2aa10499 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SinglePlotManager.java @@ -1,32 +1,41 @@ package com.github.intellectualsites.plotsquared.plot.object.worlds; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.sk89q.worldedit.function.pattern.Pattern; import java.io.File; import java.util.List; public class SinglePlotManager extends PlotManager { - @Override public PlotId getPlotIdAbs(PlotArea plotArea, int x, int y, int z) { + public SinglePlotManager(PlotArea plotArea) { + super(plotArea); + } + + @Override public PlotId getPlotIdAbs(int x, int y, int z) { return new PlotId(0, 0); } - @Override public PlotId getPlotId(PlotArea plotArea, int x, int y, int z) { + @Override public PlotId getPlotId(int x, int y, int z) { return new PlotId(0, 0); } - @Override public Location getPlotBottomLocAbs(PlotArea plotArea, PlotId plotId) { + @Override public Location getPlotBottomLocAbs(PlotId plotId) { return new Location(plotId.toCommaSeparatedString(), -30000000, 0, -30000000); } - @Override public Location getPlotTopLocAbs(PlotArea plotArea, PlotId plotId) { + @Override public Location getPlotTopLocAbs(PlotId plotId) { return new Location(plotId.toCommaSeparatedString(), 30000000, 0, 30000000); } - @Override public boolean clearPlot(PlotArea plotArea, Plot plot, final Runnable whenDone) { + @Override public boolean clearPlot(Plot plot, final Runnable whenDone) { SetupUtils.manager.unload(plot.getWorldName(), false); final File worldFolder = new File(PlotSquared.get().IMP.getWorldContainer(), plot.getWorldName()); @@ -39,68 +48,70 @@ public class SinglePlotManager extends PlotManager { return true; } - @Override public boolean claimPlot(PlotArea plotArea, Plot plot) { + @Override public boolean claimPlot(Plot plot) { // TODO return true; } - @Override public boolean unClaimPlot(PlotArea plotArea, Plot plot, Runnable whenDone) { + @Override public boolean unClaimPlot(Plot plot, Runnable whenDone) { if (whenDone != null) { whenDone.run(); } return true; } - @Override public Location getSignLoc(PlotArea plotArea, Plot plot) { + @Override public Location getSignLoc(Plot plot) { return null; } - @Override public String[] getPlotComponents(PlotArea plotArea, PlotId plotId) { + @Override public String[] getPlotComponents(PlotId plotId) { return new String[0]; } - @Override public boolean setComponent(PlotArea plotArea, PlotId plotId, String component, - BlockBucket blocks) { + @Override public boolean setComponent(PlotId plotId, String component, + Pattern blocks) { return false; } - @Override public boolean createRoadEast(PlotArea plotArea, Plot plot) { + @Override public boolean createRoadEast(Plot plot) { return false; } - @Override public boolean createRoadSouth(PlotArea plotArea, Plot plot) { + @Override public boolean createRoadSouth(Plot plot) { return false; } - @Override public boolean createRoadSouthEast(PlotArea plotArea, Plot plot) { + @Override public boolean createRoadSouthEast(Plot plot) { return false; } - @Override public boolean removeRoadEast(PlotArea plotArea, Plot plot) { + @Override public boolean removeRoadEast(Plot plot) { return false; } - @Override public boolean removeRoadSouth(PlotArea plotArea, Plot plot) { + @Override public boolean removeRoadSouth(Plot plot) { return false; } - @Override public boolean removeRoadSouthEast(PlotArea plotArea, Plot plot) { + @Override public boolean removeRoadSouthEast(Plot plot) { return false; } - @Override public boolean startPlotMerge(PlotArea plotArea, List plotIds) { + @Override public boolean startPlotMerge(List plotIds) { return false; } - @Override public boolean startPlotUnlink(PlotArea plotArea, List plotIds) { + @Override public boolean startPlotUnlink(List plotIds) { return false; } - @Override public boolean finishPlotMerge(PlotArea plotArea, List plotIds) { + @Override public boolean finishPlotMerge(List plotIds) { return false; } - @Override public boolean finishPlotUnlink(PlotArea plotArea, List plotIds) { + @Override public boolean finishPlotUnlink(List plotIds) { return false; } + + @Override public boolean regenerateAllPlotWalls() { return false; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SingleWorldGenerator.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SingleWorldGenerator.java index ba498f971..89069173f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SingleWorldGenerator.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/object/worlds/SingleWorldGenerator.java @@ -2,8 +2,12 @@ package com.github.intellectualsites.plotsquared.plot.object.worlds; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; +import com.sk89q.worldedit.world.biome.BiomeTypes; +import com.sk89q.worldedit.world.block.BlockTypes; public class SingleWorldGenerator extends IndependentPlotGenerator { private Location bedrock1 = new Location(null, 0, 0, 0); @@ -17,74 +21,25 @@ public class SingleWorldGenerator extends IndependentPlotGenerator { return "PlotSquared:single"; } - @Override public BlockBucket[][] generateBlockBucketChunk(PlotArea settings) { - BlockBucket[][] blockBuckets = new BlockBucket[16][]; - SinglePlotArea area = (SinglePlotArea) settings; - if (area.VOID) { - return blockBuckets; - } - for (int x = bedrock1.getX(); x <= bedrock2.getX(); x++) { - for (int z = bedrock1.getZ(); z <= bedrock2.getZ(); z++) { - for (int y = bedrock1.getY(); y <= bedrock2.getY(); y++) { - int layer = y >> 4; - if (blockBuckets[layer] == null) { - blockBuckets[layer] = new BlockBucket[4096]; - } - blockBuckets[layer][((y & 0xF) << 8) | (z << 4) | x] = - BlockBucket.withSingle(PlotBlock.get("bedrock")); - } - } - } - for (int x = dirt1.getX(); x <= dirt2.getX(); x++) { - for (int z = dirt1.getZ(); z <= dirt2.getZ(); z++) { - for (int y = dirt1.getY(); y <= dirt2.getY(); y++) { - int layer = y >> 4; - if (blockBuckets[layer] == null) { - blockBuckets[layer] = new BlockBucket[4096]; - } - blockBuckets[layer][((y & 0xF) << 8) | (z << 4) | x] = - BlockBucket.withSingle(PlotBlock.get("dirt")); - } - } - } - for (int x = grass1.getX(); x <= grass2.getX(); x++) { - for (int z = grass1.getZ(); z <= grass2.getZ(); z++) { - for (int y = grass1.getY(); y <= grass2.getY(); y++) { - int layer = y >> 4; - if (blockBuckets[layer] == null) { - blockBuckets[layer] = new BlockBucket[4096]; - } - blockBuckets[layer][((y & 0xF) << 8) | (z << 4) | x] = - BlockBucket.withSingle(PlotBlock.get("grass_block")); - } - } - } - return blockBuckets; - } - @Override public void generateChunk(ScopedLocalBlockQueue result, PlotArea settings) { SinglePlotArea area = (SinglePlotArea) settings; if (area.VOID) { Location min = result.getMin(); if (min.getX() == 0 && min.getZ() == 0) { - result.setBlock(0, 0, 0, PlotBlock.get("bedrock")); + result.setBlock(0, 0, 0, BlockTypes.BEDROCK.getDefaultState()); } } else { - result.setCuboid(bedrock1, bedrock2, PlotBlock.get("bedrock")); - result.setCuboid(dirt1, dirt2, PlotBlock.get("dirt")); - result.setCuboid(grass1, grass2, PlotBlock.get("grass_block")); + result.setCuboid(bedrock1, bedrock2, BlockTypes.BEDROCK.getDefaultState()); + result.setCuboid(dirt1, dirt2, BlockTypes.DIRT.getDefaultState()); + result.setCuboid(grass1, grass2, BlockTypes.GRASS_BLOCK.getDefaultState()); } - result.fillBiome("PLAINS"); + result.fillBiome(BiomeTypes.PLAINS); } @Override public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) { return ((SinglePlotAreaManager) PlotSquared.get().getPlotAreaManager()).getArea(); } - @Override public PlotManager getNewPlotManager() { - return new SinglePlotManager(); - } - @Override public void initialize(PlotArea area) { } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/AbstractTitle.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/AbstractTitle.java deleted file mode 100644 index a5f75c96a..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/AbstractTitle.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.util; - -import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer; -import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; - -public abstract class AbstractTitle { - public static AbstractTitle TITLE_CLASS; - - public static void sendTitle(PlotPlayer player, String head, String sub) { - if (player instanceof ConsolePlayer) { - return; - } - if (TITLE_CLASS != null && !player.getAttribute("disabletitles")) { - TITLE_CLASS.sendTitle(player, head, sub, 1, 2, 1); - } - } - - public abstract void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, - int out); -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ByteArrayUtilities.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ByteArrayUtilities.java index ace8bb7e4..91059e240 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ByteArrayUtilities.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ByteArrayUtilities.java @@ -1,21 +1,9 @@ package com.github.intellectualsites.plotsquared.plot.util; +import com.google.common.primitives.Ints; + public class ByteArrayUtilities { - public static byte[] integerToBytes(int i) { - byte[] bytes = new byte[4]; - bytes[0] = (byte) (i >> 24); - bytes[1] = (byte) (i >> 16); - bytes[2] = (byte) (i >> 8); - bytes[3] = (byte) (i); - return bytes; - } - - public static int bytesToInteger(byte[] bytes) { - return (bytes[0] << 24) & 0xff000000 | (bytes[1] << 16) & 0x00ff0000 - | (bytes[2] << 8) & 0x0000ff00 | (bytes[3]) & 0x000000ff; - } - public static boolean bytesToBoolean(byte[] bytes) { return bytes[0] == 1; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ChunkManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ChunkManager.java index a7c39cf18..c4df0f04b 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ChunkManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ChunkManager.java @@ -1,42 +1,51 @@ package com.github.intellectualsites.plotsquared.plot.util; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.regions.CuboidRegion; import java.io.File; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; public abstract class ChunkManager { - private static final Map> forceChunks = + private static final Map> forceChunks = new ConcurrentHashMap<>(); - private static final Map> addChunks = + private static final Map> addChunks = new ConcurrentHashMap<>(); public static ChunkManager manager = null; - public static ChunkLoc getChunkChunk(Location location) { + public static BlockVector2 getRegion(Location location) { int x = location.getX() >> 9; int z = location.getZ() >> 9; - return new ChunkLoc(x, z); + return BlockVector2.at(x, z); } public static void setChunkInPlotArea(RunnableVal force, - RunnableVal add, String world, ChunkLoc loc) { + RunnableVal add, String world, BlockVector2 loc) { LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false); if (PlotSquared.get().isAugmented(world)) { - int bx = loc.x << 4; - int bz = loc.z << 4; + int blockX = loc.getX() << 4; + int blockZ = loc.getZ() << 4; ScopedLocalBlockQueue scoped = - new ScopedLocalBlockQueue(queue, new Location(world, bx, 0, bz), - new Location(world, bx + 15, 255, bz + 15)); + new ScopedLocalBlockQueue(queue, new Location(world, blockX, 0, blockZ), + new Location(world, blockX + 15, 255, blockZ + 15)); if (force != null) { force.run(scoped); } else { - scoped.regenChunk(loc.x, loc.z); + scoped.regenChunk(loc.getX(), loc.getZ()); if (add != null) { add.run(scoped); } @@ -45,13 +54,13 @@ public abstract class ChunkManager { } else { forceChunks.put(loc, force); addChunks.put(loc, add); - queue.regenChunk(loc.x, loc.z); + queue.regenChunk(loc.getX(), loc.getZ()); forceChunks.remove(loc); addChunks.remove(loc); } } - public static boolean preProcessChunk(ChunkLoc loc, ScopedLocalBlockQueue queue) { + public static boolean preProcessChunk(BlockVector2 loc, ScopedLocalBlockQueue queue) { final RunnableVal forceChunk = forceChunks.get(loc); if (forceChunk != null) { forceChunk.run(queue); @@ -61,7 +70,7 @@ public abstract class ChunkManager { return false; } - public static boolean postProcessChunk(ChunkLoc loc, ScopedLocalBlockQueue queue) { + public static boolean postProcessChunk(BlockVector2 loc, ScopedLocalBlockQueue queue) { final RunnableVal addChunk = forceChunks.get(loc); if (addChunk != null) { addChunk.run(queue); @@ -71,39 +80,37 @@ public abstract class ChunkManager { return false; } - public static void largeRegionTask(final String world, final RegionWrapper region, - final RunnableVal task, final Runnable whenDone) { + public static void largeRegionTask(final String world, final CuboidRegion region, + final RunnableVal task, final Runnable whenDone) { TaskManager.runTaskAsync(() -> { - HashSet chunks = new HashSet<>(); - Set mcrs = manager.getChunkChunks(world); - for (ChunkLoc mcr : mcrs) { - int bx = mcr.x << 9; - int bz = mcr.z << 9; + HashSet chunks = new HashSet<>(); + Set mcrs = manager.getChunkChunks(world); + for (BlockVector2 mcr : mcrs) { + int bx = mcr.getX() << 9; + int bz = mcr.getZ() << 9; int tx = bx + 511; int tz = bz + 511; - if (bx <= region.maxX && tx >= region.minX && bz <= region.maxZ - && tz >= region.minZ) { + if (bx <= region.getMaximumPoint().getX() && tx >= region.getMinimumPoint().getX() && bz <= region.getMaximumPoint().getZ() + && tz >= region.getMinimumPoint().getZ()) { for (int x = bx >> 4; x <= (tx >> 4); x++) { int cbx = x << 4; int ctx = cbx + 15; - if (cbx <= region.maxX && ctx >= region.minX) { + if (cbx <= region.getMaximumPoint().getX() && ctx >= region.getMinimumPoint().getX()) { for (int z = bz >> 4; z <= (tz >> 4); z++) { int cbz = z << 4; int ctz = cbz + 15; - if (cbz <= region.maxZ && ctz >= region.minZ) { - chunks.add(new ChunkLoc(x, z)); + if (cbz <= region.getMaximumPoint().getZ() && ctz >= region.getMinimumPoint().getZ()) { + chunks.add(BlockVector2.at(x, z)); } } } } } } - TaskManager.objectTask(chunks, new RunnableVal() { + TaskManager.objectTask(chunks, new RunnableVal() { - @Override public void run(ChunkLoc value) { - if (manager.loadChunk(world, value, false)) { - task.run(value); - } + @Override public void run(BlockVector2 value) { + manager.loadChunk(world, value, false).thenRun(()-> task.run(value)); } }, whenDone); }); @@ -111,16 +118,16 @@ public abstract class ChunkManager { public static void chunkTask(final Plot plot, final RunnableVal task, final Runnable whenDone, final int allocate) { - final ArrayList regions = new ArrayList<>(plot.getRegions()); + final ArrayList regions = new ArrayList<>(plot.getRegions()); Runnable smallTask = new Runnable() { @Override public void run() { if (regions.isEmpty()) { TaskManager.runTask(whenDone); return; } - RegionWrapper value = regions.remove(0); - Location pos1 = new Location(plot.getWorldName(), value.minX, 0, value.minZ); - Location pos2 = new Location(plot.getWorldName(), value.maxX, 0, value.maxZ); + CuboidRegion value = regions.remove(0); + Location pos1 = new Location(plot.getWorldName(), value.getMinimumPoint().getX(), 0, value.getMinimumPoint().getZ()); + Location pos2 = new Location(plot.getWorldName(), value.getMaximumPoint().getX(), 0, value.getMaximumPoint().getZ()); chunkTask(pos1, pos2, task, this, allocate); } }; @@ -128,7 +135,7 @@ public abstract class ChunkManager { } /** - * The int[] will be in the form: [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge] and will represent the bottom and top parts of the chunk + * The int[] will be in the form: [chunkX, chunkZ, pos1x, pos1z, pos2x, pos2z, isEdge] and will represent the bottom and top parts of the chunk * * @param pos1 * @param pos2 @@ -145,21 +152,21 @@ public abstract class ChunkManager { final int bcz = p1z >> 4; final int tcx = p2x >> 4; final int tcz = p2z >> 4; - final ArrayList chunks = new ArrayList<>(); + final ArrayList chunks = new ArrayList<>(); for (int x = bcx; x <= tcx; x++) { for (int z = bcz; z <= tcz; z++) { - chunks.add(new ChunkLoc(x, z)); + chunks.add(BlockVector2.at(x, z)); } } TaskManager.runTask(new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); while (!chunks.isEmpty() && ((System.currentTimeMillis() - start) < allocate)) { - ChunkLoc chunk = chunks.remove(0); + BlockVector2 chunk = chunks.remove(0); task.value = new int[7]; - task.value[0] = chunk.x; - task.value[1] = chunk.z; + task.value[0] = chunk.getX(); + task.value[1] = chunk.getZ(); task.value[2] = task.value[0] << 4; task.value[3] = task.value[1] << 4; task.value[4] = task.value[2] + 15; @@ -204,19 +211,19 @@ public abstract class ChunkManager { */ public abstract int[] countEntities(Plot plot); - public abstract boolean loadChunk(String world, ChunkLoc loc, boolean force); + public abstract CompletableFuture loadChunk(String world, BlockVector2 loc, boolean force); - public abstract void unloadChunk(String world, ChunkLoc loc, boolean save, boolean safe); + public abstract void unloadChunk(String world, BlockVector2 loc, boolean save); - public Set getChunkChunks(String world) { + public Set getChunkChunks(String world) { File folder = new File(PlotSquared.get().IMP.getWorldContainer(), world + File.separator + "region"); File[] regionFiles = folder.listFiles(); - HashSet chunks = new HashSet<>(); if (regionFiles == null) { throw new RuntimeException( "Could not find worlds folder: " + folder + " ? (no read access?)"); } + HashSet chunks = new HashSet<>(); for (File file : regionFiles) { String name = file.getName(); if (name.endsWith("mca")) { @@ -224,7 +231,7 @@ public abstract class ChunkManager { try { int x = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); - ChunkLoc loc = new ChunkLoc(x, z); + BlockVector2 loc = BlockVector2.at(x, z); chunks.add(loc); } catch (NumberFormatException ignored) { } @@ -233,16 +240,16 @@ public abstract class ChunkManager { return chunks; } - public void deleteRegionFiles(String world, Collection chunks) { + public void deleteRegionFiles(String world, Collection chunks) { deleteRegionFiles(world, chunks, null); } - public void deleteRegionFiles(final String world, final Collection chunks, + public void deleteRegionFiles(final String world, final Collection chunks, final Runnable whenDone) { TaskManager.runTaskAsync(() -> { - for (ChunkLoc loc : chunks) { + for (BlockVector2 loc : chunks) { String directory = - world + File.separator + "region" + File.separator + "r." + loc.x + "." + loc.z + world + File.separator + "region" + File.separator + "r." + loc.getX() + "." + loc.getZ() + ".mca"; File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory); PlotSquared.log("&6 - Deleting file: " + file.getName() + " (max 1024 chunks)"); @@ -254,9 +261,9 @@ public abstract class ChunkManager { }); } - public Plot hasPlot(String world, ChunkLoc chunk) { - int x1 = chunk.x << 4; - int z1 = chunk.z << 4; + public Plot hasPlot(String world, BlockVector2 chunk) { + int x1 = chunk.getX() << 4; + int z1 = chunk.getZ() << 4; int x2 = x1 + 15; int z2 = z1 + 15; Location bot = new Location(world, x1, 0, z1); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CommentManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CommentManager.java index 416f0aa46..4eff629d6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CommentManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/CommentManager.java @@ -5,7 +5,11 @@ import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; -import com.github.intellectualsites.plotsquared.plot.object.comment.*; +import com.github.intellectualsites.plotsquared.plot.object.comment.CommentInbox; +import com.github.intellectualsites.plotsquared.plot.object.comment.InboxOwner; +import com.github.intellectualsites.plotsquared.plot.object.comment.InboxPublic; +import com.github.intellectualsites.plotsquared.plot.object.comment.InboxReport; +import com.github.intellectualsites.plotsquared.plot.object.comment.PlotComment; import java.util.Collection; import java.util.HashMap; @@ -40,8 +44,8 @@ public class CommentManager { total = count.get(); } if ((size.decrementAndGet() == 0) && (total > 0)) { - AbstractTitle.sendTitle(player, "", - Captions.INBOX_NOTIFICATION.s().replaceAll("%s", "" + total)); + player.sendTitle("", Captions.INBOX_NOTIFICATION.getTranslated() + .replaceAll("%s", "" + total)); } } }); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ConsoleColors.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ConsoleColors.java index 5e9c87a7a..f8860887f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ConsoleColors.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ConsoleColors.java @@ -34,8 +34,6 @@ public class ConsoleColors { public static ConsoleColor chatColor(final String color) { switch (color) { - case "&r": - return ConsoleColor.RESET; case "&7": case "&8": return ConsoleColor.WHITE; @@ -65,6 +63,7 @@ public class ConsoleColors { return ConsoleColor.ITALIC; case "&l": return ConsoleColor.BOLD; + case "&r": default: return ConsoleColor.RESET; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EntityUtil.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EntityUtil.java index fa543b21a..51e093d46 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EntityUtil.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EntityUtil.java @@ -15,9 +15,6 @@ import lombok.experimental.UtilityClass; private static int capNumeral(@NonNull final String flagName) { int i; switch (flagName) { - case "entity-cap": - i = 0; - break; case "mob-cap": i = 3; break; @@ -33,6 +30,7 @@ import lombok.experimental.UtilityClass; case "misc-cap": i = 5; break; + case "entity-cap": default: i = 0; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EventUtil.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EventUtil.java index 6229e9332..0187f67b4 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EventUtil.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/EventUtil.java @@ -6,14 +6,22 @@ import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.listener.PlayerBlockEventType; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Rating; import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.block.BlockTypes; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; -import java.util.HashSet; import java.util.List; import java.util.Optional; +import java.util.Set; import java.util.UUID; public abstract class EventUtil { @@ -80,7 +88,7 @@ public abstract class EventUtil { .getArea() instanceof SinglePlotArea)) { TaskManager.runTask(() -> plot.teleportPlayer(player)); MainUtil.sendMessage(player, - Captions.TELEPORTED_TO_ROAD.f() + " (on-login) " + "(" + plot.getId().x + ";" + plot + Captions.format(Captions.TELEPORTED_TO_ROAD.getTranslated()) + " (on-login) " + "(" + plot.getId().x + ";" + plot .getId().y + ")"); } } @@ -93,8 +101,8 @@ public abstract class EventUtil { } } - public boolean checkPlayerBlockEvent(PlotPlayer player, PlayerBlockEventType type, - Location location, LazyBlock block, boolean notifyPerms) { + public boolean checkPlayerBlockEvent(PlotPlayer player, @NotNull PlayerBlockEventType type, + Location location, BlockType blockType, boolean notifyPerms) { PlotArea area = location.getPlotArea(); assert area != null; Plot plot = area.getPlot(location); @@ -106,168 +114,50 @@ public abstract class EventUtil { switch (type) { case TELEPORT_OBJECT: return false; - case EAT: case READ: return true; - case BREAK_BLOCK: - if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), - notifyPerms); - } - if (!plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), - notifyPerms); - } - Optional> use = plot.getFlag(Flags.USE); - if (use.isPresent()) { - HashSet value = use.get(); - if (PlotBlock.containsEverything(value) || value - .contains(block.getPlotBlock())) { - return true; - } - } - Optional> destroy = plot.getFlag(Flags.BREAK); - if (destroy.isPresent()) { - HashSet value = destroy.get(); - if (PlotBlock.containsEverything(value) || value - .contains(block.getPlotBlock())) { - return true; - } - } - if (Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), false)) { - return true; - } - return !(!notifyPerms || MainUtil.sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, - Captions.FLAG_USE.s() + '/' + Captions.FLAG_BREAK.s())); - case BREAK_HANGING: - if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), - notifyPerms); - } - if (plot.getFlag(Flags.HANGING_BREAK).orElse(false)) { - return true; - } - if (plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), false) - || !(!notifyPerms || MainUtil - .sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, - Captions.FLAG_HANGING_BREAK.s())); - } - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), - notifyPerms); - case BREAK_MISC: - if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), - notifyPerms); - } - if (plot.getFlag(Flags.MISC_BREAK).orElse(false)) { - return true; - } - if (plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), false) - || !(!notifyPerms || MainUtil - .sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, - Captions.FLAG_MISC_BREAK.s())); - } - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), - notifyPerms); - case BREAK_VEHICLE: - if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), - notifyPerms); - } - if (plot.getFlag(Flags.VEHICLE_BREAK).orElse(false)) { - return true; - } - if (plot.hasOwner()) { - if (Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), - false)) { - return true; - } - return !(!notifyPerms || MainUtil - .sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, - Captions.FLAG_VEHICLE_BREAK.s())); - } - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), - notifyPerms); case INTERACT_BLOCK: { if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), + return Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_ROAD.getTranslated(), notifyPerms); } if (!plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), + return Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.getTranslated(), notifyPerms); } - Optional> flagValue = plot.getFlag(Flags.USE); - HashSet value = flagValue.orElse(null); - if (value == null || !PlotBlock.containsEverything(value) && !value - .contains(block.getPlotBlock())) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), false) + Optional> flagValue = plot.getFlag(Flags.USE); + Set value = flagValue.orElse(null); + if (value == null || !value.contains(BlockTypes.AIR) && !value + .contains(blockType)) { + return Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_OTHER.getTranslated(), false) || !(!notifyPerms || MainUtil - .sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, Captions.FLAG_USE.s())); - } - return true; - } - case PLACE_BLOCK: { - if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_BUILD_ROAD.s(), - notifyPerms); - } - if (!plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_BUILD_UNOWNED.s(), - notifyPerms); - } - Optional> flagValue = plot.getFlag(Flags.PLACE); - HashSet value = flagValue.orElse(null); - if (value == null || !PlotBlock.containsEverything(value) && !value - .contains(block.getPlotBlock())) { - if (Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_BUILD_OTHER.s(), false)) { - return true; - } - return !(!notifyPerms || MainUtil .sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, - Captions.FLAG_PLACE.s())); + Captions.FLAG_USE.getTranslated())); } return true; } case TRIGGER_PHYSICAL: { if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), false); + return Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_ROAD.getTranslated(), false); } if (!plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), + return Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.getTranslated(), false); } if (plot.getFlag(Flags.DEVICE_INTERACT).orElse(false)) { return true; } - Optional> flagValue = plot.getFlag(Flags.USE); - HashSet value = flagValue.orElse(null); - if (value == null || !PlotBlock.containsEverything(value) && !value - .contains(block.getPlotBlock())) { - if (Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), + Optional> flagValue = plot.getFlag(Flags.USE); + Set value = flagValue.orElse(null); + if (value == null || !value.contains(BlockTypes.AIR) && !value + .contains(blockType)) { + if (Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_OTHER.getTranslated(), false)) { return true; } @@ -275,180 +165,80 @@ public abstract class EventUtil { } return true; } - case INTERACT_HANGING: { - if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), - notifyPerms); - } - if (!plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), - notifyPerms); - } - if (plot.getFlag(Flags.HOSTILE_INTERACT).orElse(false)) { - return true; - } - Optional> flagValue = plot.getFlag(Flags.USE); - HashSet value = flagValue.orElse(null); - if (value == null || !PlotBlock.containsEverything(value) && !value - .contains(block.getPlotBlock())) { - if (Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), - false)) { - return true; - } - return !(!notifyPerms || MainUtil - .sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, - Captions.FLAG_USE.s() + '/' + Captions.FLAG_HANGING_INTERACT.s())); - } - return true; - } - case INTERACT_MISC: { - if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), - notifyPerms); - } - if (!plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), - notifyPerms); - } - if (plot.getFlag(Flags.MISC_INTERACT).orElse(false)) { - return true; - } - Optional> flag = plot.getFlag(Flags.USE); - HashSet value = flag.orElse(null); - if (value == null || !PlotBlock.containsEverything(value) && !value - .contains(block.getPlotBlock())) { - if (Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), - false)) { - return true; - } - return !(!notifyPerms || MainUtil - .sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, - Captions.FLAG_USE.s() + '/' + Captions.FLAG_MISC_INTERACT.s())); - } - return true; - } - case INTERACT_VEHICLE: { - if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), - notifyPerms); - } - if (!plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), - notifyPerms); - } - if (plot.getFlag(Flags.VEHICLE_USE).orElse(false)) { - return true; - } - Optional> flag = plot.getFlag(Flags.USE); - HashSet value = flag.orElse(null); - if (value == null || !PlotBlock.containsEverything(value) && !value - .contains(block.getPlotBlock())) { - if (Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), - false)) { - return true; - } - return !(!notifyPerms || MainUtil - .sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, - Captions.FLAG_USE.s() + '/' + Captions.FLAG_VEHICLE_USE.s())); - } - return true; - } case SPAWN_MOB: { if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), + return Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_ROAD.getTranslated(), notifyPerms); } if (!plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), + return Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.getTranslated(), notifyPerms); } if (plot.getFlag(Flags.MOB_PLACE).orElse(false)) { return true; } - Optional> flagValue = plot.getFlag(Flags.PLACE); - HashSet value = flagValue.orElse(null); - if (value == null || !PlotBlock.containsEverything(value) && !value - .contains(block.getPlotBlock())) { - if (Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), + Optional> flagValue = plot.getFlag(Flags.PLACE); + Set value = flagValue.orElse(null); + if (value == null || !value.contains(BlockTypes.AIR) && !value + .contains(blockType)) { + if (Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_OTHER.getTranslated(), false)) { return true; } return !(!notifyPerms || MainUtil .sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, - Captions.FLAG_MOB_PLACE.s() + '/' + Captions.FLAG_PLACE.s())); + Captions.FLAG_MOB_PLACE.getTranslated() + '/' + Captions.FLAG_PLACE + .getTranslated())); } return true; } case PLACE_MISC: { if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), + return Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_ROAD.getTranslated(), notifyPerms); } if (!plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), + return Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.getTranslated(), notifyPerms); } if (plot.getFlag(Flags.MISC_PLACE).orElse(false)) { return true; } - Optional> flag = plot.getFlag(Flags.PLACE); - HashSet value = flag.orElse(null); - if (value == null || !PlotBlock.containsEverything(value) && !value - .contains(block.getPlotBlock())) { - if (Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), + Optional> flag = plot.getFlag(Flags.PLACE); + Set value = flag.orElse(null); + if (value == null || !value.contains(BlockTypes.AIR) && !value + .contains(blockType)) { + if (Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_OTHER.getTranslated(), false)) { return true; } return !(!notifyPerms || MainUtil .sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, - Captions.FLAG_MISC_PLACE.s() + '/' + Captions.FLAG_PLACE.s())); + Captions.FLAG_MISC_PLACE.getTranslated() + '/' + Captions.FLAG_PLACE + .getTranslated())); } return true; } case PLACE_VEHICLE: if (plot == null) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_ROAD.s(), + return Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_ROAD.getTranslated(), notifyPerms); } if (!plot.hasOwner()) { - return Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), + return Permissions.hasPermission(player, + Captions.PERMISSION_ADMIN_INTERACT_UNOWNED.getTranslated(), notifyPerms); } - if (plot.getFlag(Flags.VEHICLE_PLACE).orElse(false)) { - return true; - } - Optional> flag = plot.getFlag(Flags.PLACE); - HashSet value = flag.orElse(null); - if (value == null || !PlotBlock.containsEverything(value) && !value - .contains(block.getPlotBlock())) { - if (Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_INTERACT_OTHER.s(), - false)) { - return true; - } - return !(!notifyPerms || MainUtil - .sendMessage(player, Captions.FLAG_TUTORIAL_USAGE, - Captions.FLAG_VEHICLE_PLACE.s() + '/' + Captions.FLAG_PLACE.s())); - } - return true; + Optional flag1 = plot.getFlag(Flags.VEHICLE_PLACE); + return flag1.orElse(false); default: break; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/HastebinUtility.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/HastebinUtility.java deleted file mode 100644 index d2495b646..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/HastebinUtility.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.util; - -import java.io.*; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class HastebinUtility { - - public static final String BIN_URL = "https://hastebin.com/documents", USER_AGENT = - "Mozilla/5.0"; - public static final Pattern PATTERN = Pattern.compile("\\{\"key\":\"([\\S\\s]*)\"\\}"); - - public static String upload(final String string) throws IOException { - final URL url = new URL(BIN_URL); - final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - - connection.setRequestMethod("POST"); - connection.setRequestProperty("User-Agent", USER_AGENT); - connection.setDoOutput(true); - - try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(string.getBytes()); - outputStream.flush(); - } - - StringBuilder response; - try (BufferedReader in = new BufferedReader( - new InputStreamReader(connection.getInputStream()))) { - response = new StringBuilder(); - - String inputLine; - while ((inputLine = in.readLine()) != null) { - response.append(inputLine); - } - } - - Matcher matcher = PATTERN.matcher(response.toString()); - if (matcher.matches()) { - return "https://hastebin.com/" + matcher.group(1); - } else { - throw new RuntimeException("Couldn't read response!"); - } - } - - public static String upload(final File file) throws IOException { - final StringBuilder content = new StringBuilder(); - List lines = new ArrayList<>(); - try (BufferedReader reader = new BufferedReader(new FileReader(file))) { - String line; - int i = 0; - while ((line = reader.readLine()) != null) { - lines.add(line); - } - } - for (int i = Math.max(0, lines.size() - 1000); i < lines.size(); i++) { - content.append(lines.get(i)).append("\n"); - } - return upload(content.toString()); - } - -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/IncendoPaster.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/IncendoPaster.java index 1fec0e567..b5ebe5d17 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/IncendoPaster.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/IncendoPaster.java @@ -9,7 +9,12 @@ import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.Locale; /** * Single class paster for the Incendo paste service diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/LegacyConverter.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/LegacyConverter.java index 55d86ce5a..38db9b9f4 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/LegacyConverter.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/LegacyConverter.java @@ -4,7 +4,7 @@ import com.github.intellectualsites.plotsquared.configuration.ConfigurationSecti import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.BlockBucket; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.sk89q.worldedit.world.block.BlockState; import lombok.NonNull; import java.util.Collection; @@ -36,7 +36,7 @@ import java.util.Map; } private BlockBucket blockToBucket(@NonNull final String block) { - final PlotBlock plotBlock = WorldUtil.IMP.getClosestBlock(block).best; + final BlockState plotBlock = WorldUtil.IMP.getClosestBlock(block).best; return BlockBucket.withSingle(plotBlock); } @@ -48,12 +48,10 @@ import java.util.Map; section.set(string, blocks.toString()); } - private BlockBucket blockListToBucket(@NonNull final PlotBlock[] blocks) { - final Map counts = new HashMap<>(); - for (final PlotBlock block : blocks) { - if (!counts.containsKey(block)) { - counts.put(block, 0); - } + private BlockBucket blockListToBucket(@NonNull final BlockState[] blocks) { + final Map counts = new HashMap<>(); + for (final BlockState block : blocks) { + counts.putIfAbsent(block, 0); counts.put(block, counts.get(block) + 1); } boolean includeRatios = false; @@ -65,8 +63,8 @@ import java.util.Map; } final BlockBucket bucket = new BlockBucket(); if (includeRatios) { - for (final Map.Entry count : counts.entrySet()) { - bucket.addBlock(count.getKey(), (int) (count.getValue())); + for (final Map.Entry count : counts.entrySet()) { + bucket.addBlock(count.getKey(), count.getValue()); } } else { counts.keySet().forEach(bucket::addBlock); @@ -74,28 +72,30 @@ import java.util.Map; return bucket; } - private PlotBlock[] splitBlockList(@NonNull final List list) { + private BlockState[] splitBlockList(@NonNull final List list) { return list.stream().map(s -> WorldUtil.IMP.getClosestBlock(s).best) - .toArray(PlotBlock[]::new); + .toArray(BlockState[]::new); } private void convertBlock(@NonNull final ConfigurationSection section, @NonNull final String key, @NonNull final String block) { final BlockBucket bucket = this.blockToBucket(block); this.setString(section, key, bucket); - PlotSquared.log(Captions.LEGACY_CONFIG_REPLACED.f(block, bucket.toString())); + PlotSquared.log(Captions + .format(Captions.LEGACY_CONFIG_REPLACED.getTranslated(), block, bucket.toString())); } private void convertBlockList(@NonNull final ConfigurationSection section, @NonNull final String key, @NonNull final List blockList) { - final PlotBlock[] blocks = this.splitBlockList(blockList); + final BlockState[] blocks = this.splitBlockList(blockList); final BlockBucket bucket = this.blockListToBucket(blocks); this.setString(section, key, bucket); - PlotSquared.log( - Captions.LEGACY_CONFIG_REPLACED.f(plotBlockArrayString(blocks), bucket.toString())); + PlotSquared.log(Captions + .format(Captions.LEGACY_CONFIG_REPLACED.getTranslated(), plotBlockArrayString(blocks), + bucket.toString())); } - private String plotBlockArrayString(@NonNull final PlotBlock[] blocks) { + private String plotBlockArrayString(@NonNull final BlockState[] blocks) { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < blocks.length; i++) { builder.append(blocks[i].toString()); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/LegacyMappings.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/LegacyMappings.java deleted file mode 100644 index d79ad6653..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/LegacyMappings.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.util; - -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; - -public abstract class LegacyMappings { - - public abstract PlotBlock fromAny(final String string); - - public abstract PlotBlock fromLegacyToString(final int id, final int data); - - public abstract PlotBlock fromLegacyToString(final String id); - - public abstract PlotBlock fromStringToLegacy(final String id); - -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/MainUtil.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/MainUtil.java index cfc910748..15abc1bd6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/MainUtil.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/MainUtil.java @@ -10,12 +10,28 @@ import com.github.intellectualsites.plotsquared.plot.flag.DoubleFlag; import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; import com.github.intellectualsites.plotsquared.plot.flag.Flags; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.stream.AbstractDelegateOutputStream; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; +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.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; -import java.io.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.Reader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; @@ -23,8 +39,18 @@ import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.text.DecimalFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -88,7 +114,7 @@ public class MainUtil { public static void sendAdmin(final String s) { for (final PlotPlayer player : UUIDHandler.getPlayers().values()) { - if (player.hasPermission(Captions.PERMISSION_ADMIN.s())) { + if (player.hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { player.sendMessage(Captions.color(s)); } } @@ -193,10 +219,9 @@ public class MainUtil { * @return true if any changes were made */ public static boolean resetBiome(PlotArea area, Location pos1, Location pos2) { - String biome = area.PLOT_BIOME; - if (!StringMan.isEqual(WorldUtil.IMP - .getBiome(area.worldname, (pos1.getX() + pos2.getX()) / 2, - (pos1.getZ() + pos2.getZ()) / 2), biome)) { + BiomeType biome = area.PLOT_BIOME; + if (!Objects.equals(WorldUtil.IMP.getBiome(area.worldname, (pos1.getX() + pos2.getX()) / 2, + (pos1.getZ() + pos2.getZ()) / 2), biome)) { MainUtil.setBiome(area.worldname, pos1.getX(), pos1.getZ(), pos2.getX(), pos2.getZ(), biome); return true; @@ -329,19 +354,19 @@ public class MainUtil { * @param owner * @return The player's name, None, Everyone or Unknown */ - @Nonnull public static String getName(UUID owner) { + @NotNull public static String getName(UUID owner) { if (owner == null) { - return Captions.NONE.s(); + return Captions.NONE.getTranslated(); } if (owner.equals(DBFunc.EVERYONE)) { - return Captions.EVERYONE.s(); + return Captions.EVERYONE.getTranslated(); } if (owner.equals(DBFunc.SERVER)) { - return Captions.SERVER.s(); + return Captions.SERVER.getTranslated(); } String name = UUIDHandler.getName(owner); if (name == null) { - return Captions.UNKNOWN.s(); + return Captions.UNKNOWN.getTranslated(); } return name; } @@ -350,6 +375,14 @@ public class MainUtil { return plot.getFlag(Flags.SERVER_PLOT).orElse(false); } + @NotNull public static Location[] getCorners(String world, CuboidRegion region) { + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); + Location pos1 = new Location(world, min.getX(), min.getY(), min.getZ()); + Location pos2 = new Location(world, max.getX(), max.getY(), max.getZ()); + return new Location[] {pos1, pos2}; + } + /** * Get the corner locations for a list of regions. * @@ -358,11 +391,11 @@ public class MainUtil { * @return * @see Plot#getCorners() */ - @Nonnull public static Location[] getCorners(String world, Collection regions) { + @NotNull public static Location[] getCorners(String world, Collection regions) { Location min = null; Location max = null; - for (RegionWrapper region : regions) { - Location[] corners = region.getCorners(world); + for (CuboidRegion region : regions) { + Location[] corners = getCorners(world, region); if (min == null) { min = corners[0]; max = corners[1]; @@ -399,8 +432,6 @@ public class MainUtil { List uuids = new ArrayList<>(); PlotId id = null; - PlotArea area = null; - String alias = null; for (String term : split) { try { @@ -418,6 +449,8 @@ public class MainUtil { IntStream.range(0, size).mapToObj(i -> new ArrayList()) .collect(Collectors.toCollection(() -> new ArrayList<>(size))); + PlotArea area = null; + String alias = null; for (Plot plot : PlotSquared.get().getPlots()) { int count = 0; if (!uuids.isEmpty()) { @@ -500,7 +533,7 @@ public class MainUtil { } for (Plot p : plots) { String name = p.getAlias(); - if (!name.isEmpty() && StringMan.isEqualIgnoreCase(name, arg)) { + if (!name.isEmpty() && name.equalsIgnoreCase(arg)) { return p; } } @@ -535,8 +568,10 @@ public class MainUtil { * @param p2z * @param biome */ - public static void setBiome(String world, int p1x, int p1z, int p2x, int p2z, String biome) { - RegionWrapper region = new RegionWrapper(p1x, p2x, p1z, p2z); + 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); WorldUtil.IMP.setBiomes(world, region, biome); } @@ -560,11 +595,11 @@ public class MainUtil { * Send a message to the player. * * @param player Player to receive message - * @param msg Message to send + * @param message Message to send * @return true Can be used in things such as commands (return PlayerFunctions.sendMessage(...)) */ - public static boolean sendMessage(PlotPlayer player, String msg) { - return sendMessage(player, msg, true); + public static boolean sendMessage(PlotPlayer player, String message) { + return sendMessage(player, message, true); } /** @@ -585,13 +620,14 @@ public class MainUtil { * @param prefix If the message should be prefixed with the configured prefix * @return */ - public static boolean sendMessage(CommandCaller player, String msg, boolean prefix) { + public static boolean sendMessage(CommandCaller player, @NotNull String msg, boolean prefix) { if (!msg.isEmpty()) { if (player == null) { - String message = (prefix ? Captions.PREFIX.s() : "") + msg; + String message = (prefix ? Captions.PREFIX.getTranslated() : "") + msg; PlotSquared.log(message); } else { - player.sendMessage((prefix ? Captions.PREFIX.s() : "") + Captions.color(msg)); + player.sendMessage( + (prefix ? Captions.PREFIX.getTranslated() : "") + Captions.color(msg)); } } return true; @@ -617,7 +653,7 @@ public class MainUtil { */ public static boolean sendMessage(final CommandCaller player, final Captions caption, final Object... args) { - if (caption.s().isEmpty()) { + if (caption.getTranslated().isEmpty()) { return true; } TaskManager.runTaskAsync(() -> { @@ -713,37 +749,36 @@ public class MainUtil { public static void format(String info, final Plot plot, PlotPlayer player, final boolean full, final RunnableVal whenDone) { int num = plot.getConnectedPlots().size(); - String alias = !plot.getAlias().isEmpty() ? plot.getAlias() : Captions.NONE.s(); + String alias = !plot.getAlias().isEmpty() ? plot.getAlias() : Captions.NONE.getTranslated(); Location bot = plot.getCorners()[0]; - String biome = WorldUtil.IMP.getBiome(plot.getWorldName(), bot.getX(), bot.getZ()); + BiomeType biome = WorldUtil.IMP.getBiome(plot.getWorldName(), bot.getX(), bot.getZ()); 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.s(); + seen = Captions.NOW.getTranslated(); } else { int time = (int) (ExpireManager.IMP.getAge(plot) / 1000); if (time != 0) { seen = MainUtil.secToTime(time); } else { - seen = Captions.UNKNOWN.s(); + seen = Captions.UNKNOWN.getTranslated(); } } } else { - seen = Captions.NEVER.s(); + seen = Captions.NEVER.getTranslated(); } Optional descriptionFlag = plot.getFlag(Flags.DESCRIPTION); - String description = !descriptionFlag.isPresent() ? - Captions.NONE.s() : + String description = !descriptionFlag.isPresent() ? Captions.NONE.getTranslated() : Flags.DESCRIPTION.valueToString(descriptionFlag.get()); StringBuilder flags = new StringBuilder(); HashMap, Object> flagMap = FlagManager.getPlotFlags(plot.getArea(), plot.getSettings(), true); if (flagMap.isEmpty()) { - flags.append(Captions.NONE.s()); + flags.append(Captions.NONE.getTranslated()); } else { String prefix = ""; for (Entry, Object> entry : flagMap.entrySet()) { @@ -754,7 +789,9 @@ public class MainUtil { value = df.format(value); } flags.append(prefix) - .append(Captions.PLOT_FLAG_LIST.f(entry.getKey().getName(), value)); + .append(Captions + .format(Captions.PLOT_FLAG_LIST.getTranslated(), entry.getKey().getName(), + value)); prefix = ", "; } } @@ -764,7 +801,7 @@ public class MainUtil { info = info.replace("%alias%", alias); info = info.replace("%num%", String.valueOf(num)); info = info.replace("%desc%", description); - info = info.replace("%biome%", biome); + info = info.replace("%biome%", biome.toString().toLowerCase()); info = info.replace("%owner%", owner); info = info.replace("%members%", members); info = info.replace("%player%", player.getName()); @@ -837,11 +874,11 @@ public class MainUtil { public static String getPlayerList(Collection uuids) { ArrayList l = new ArrayList<>(uuids); if (l.size() < 1) { - return Captions.NONE.s(); + return Captions.NONE.getTranslated(); } List users = l.stream().map(MainUtil::getName).sorted().collect(Collectors.toList()); - String c = Captions.PLOT_USER_LIST.s(); + String c = Captions.PLOT_USER_LIST.getTranslated(); StringBuilder list = new StringBuilder(); for (int x = 0; x < users.size(); x++) { if (x + 1 == l.size()) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/Permissions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/Permissions.java index 82f3eb879..f11639813 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/Permissions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/Permissions.java @@ -15,7 +15,7 @@ import java.util.HashMap; public class Permissions { public static boolean hasPermission(PlotPlayer player, Captions caption, boolean notify) { - return hasPermission(player, caption.s(), notify); + return hasPermission(player, caption.getTranslated(), notify); } /** @@ -26,7 +26,7 @@ public class Permissions { * @return */ public static boolean hasPermission(PlotPlayer player, Captions caption) { - return hasPermission(player, caption.s()); + return hasPermission(player, caption.getTranslated()); } /** @@ -68,7 +68,7 @@ public class Permissions { } else if (caller.isPermissionSet(permission)) { return false; } - if (caller.hasPermission(Captions.PERMISSION_ADMIN.s())) { + if (caller.hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { return true; } permission = permission.toLowerCase().replaceAll("^[^a-z|0-9|\\.|_|-]", ""); @@ -76,7 +76,7 @@ public class Permissions { StringBuilder n = new StringBuilder(); for (int i = 0; i <= (nodes.length - 1); i++) { n.append(nodes[i] + "."); - String combined = n + Captions.PERMISSION_STAR.s(); + String combined = n + Captions.PERMISSION_STAR.getTranslated(); if (!permission.equals(combined)) { if (caller.hasPermission(combined)) { return true; @@ -89,7 +89,7 @@ public class Permissions { } /** - * Check if a PlotPlayer has a permission, and optionally send the no permission message if applicable. + * Checks if a PlotPlayer has a permission, and optionally send the no permission message if applicable. * * @param player * @param permission @@ -107,7 +107,7 @@ public class Permissions { } public static int hasPermissionRange(PlotPlayer player, Captions perm, int range) { - return hasPermissionRange(player, perm.s(), range); + return hasPermissionRange(player, perm.getTranslated(), range); } /** diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/PlotGameMode.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/PlotGameMode.java deleted file mode 100644 index b3b1fd5a7..000000000 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/PlotGameMode.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.github.intellectualsites.plotsquared.plot.util; - -public enum PlotGameMode { - NOT_SET(-1, ""), SURVIVAL(0, "survival"), CREATIVE(1, "creative"), ADVENTURE(2, - "adventure"), SPECTATOR(3, "spectator"); - - private final int id; - private final String name; - - PlotGameMode(int id, String name) { - this.id = id; - this.name = name; - } - - /** - * The magic-value id of the GameMode. - * - * @return the GameMode id - */ - public int getId() { - return this.id; - } - - /** - * Get the name of this GameMode - * - * @return the GameMode name - */ - public String getName() { - return this.name; - } -} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ReflectionUtils.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ReflectionUtils.java index cf6bbee2d..621766c17 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ReflectionUtils.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/ReflectionUtils.java @@ -1,7 +1,15 @@ package com.github.intellectualsites.plotsquared.plot.util; -import java.lang.reflect.*; -import java.util.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; /** * @author DPOH-VAR @@ -137,21 +145,22 @@ public class ReflectionUtils { } @SuppressWarnings("unchecked") - public static Constructor makeConstructor(Class clazz, Class... paramaterTypes) { + public static Constructor makeConstructor(Class clazz, Class... parameterTypes) { try { - return (Constructor) clazz.getConstructor(paramaterTypes); + return (Constructor) clazz.getConstructor(parameterTypes); } catch (NoSuchMethodException ignored) { + //todo print a constructor not found method return null; } } - public static T callConstructor(Constructor constructor, Object... paramaters) { + public static T callConstructor(Constructor constructor, Object... parameters) { if (constructor == null) { throw new RuntimeException("No such constructor"); } constructor.setAccessible(true); try { - return constructor.newInstance(paramaters); + return constructor.newInstance(parameters); } catch (InvocationTargetException ex) { throw new RuntimeException(ex.getCause()); } catch (IllegalAccessException | IllegalArgumentException | InstantiationException ex) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/SchematicHandler.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/SchematicHandler.java index cf04f7f94..64477915b 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/SchematicHandler.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/SchematicHandler.java @@ -7,21 +7,52 @@ import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.generator.ClassicPlotWorld; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.schematic.Schematic; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; -import com.sk89q.jnbt.*; -import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; -import com.sk89q.worldedit.extent.clipboard.io.*; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.NBTInputStream; +import com.sk89q.jnbt.NBTOutputStream; +import com.sk89q.jnbt.StringTag; +import com.sk89q.jnbt.Tag; +import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; +import com.sk89q.worldedit.extent.clipboard.io.MCEditSchematicReader; +import com.sk89q.worldedit.extent.clipboard.io.SpongeSchematicReader; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.block.BaseBlock; +import org.jetbrains.annotations.NotNull; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; @@ -51,15 +82,16 @@ public abstract class SchematicHandler { Iterator i = plots.iterator(); final Plot plot = i.next(); i.remove(); - String o = UUIDHandler.getName(plot.guessOwner()); - if (o == null) { - o = "unknown"; + String owner = UUIDHandler.getName(plot.guessOwner()); + if (owner == null) { + owner = "unknown"; } final String name; if (namingScheme == null) { - name = plot.getId().x + ";" + plot.getId().y + ',' + plot.getArea() + ',' + o; + name = + plot.getId().x + ";" + plot.getId().y + ',' + plot.getArea() + ',' + owner; } else { - name = namingScheme.replaceAll("%owner%", o) + name = namingScheme.replaceAll("%owner%", owner) .replaceAll("%id%", plot.getId().toString()) .replaceAll("%idx%", plot.getId().x + "") .replaceAll("%idy%", plot.getId().y + "") @@ -136,19 +168,19 @@ public abstract class SchematicHandler { final int LENGTH = dimension.getZ(); final int HEIGHT = dimension.getY(); // Validate dimensions - RegionWrapper region = plot.getLargestRegion(); - if (((region.maxX - region.minX + xOffset + 1) < WIDTH) || ( - (region.maxZ - region.minZ + zOffset + 1) < LENGTH) || (HEIGHT > 256)) { + CuboidRegion region = plot.getLargestRegion(); + if (((region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + xOffset + 1) < WIDTH) || ( + (region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + zOffset + 1) < LENGTH) || (HEIGHT > 256)) { PlotSquared.debug("Schematic is too large"); PlotSquared.debug( "(" + WIDTH + ',' + LENGTH + ',' + HEIGHT + ") is bigger than (" + ( - region.maxX - region.minX) + ',' + (region.maxZ - region.minZ) + region.getMaximumPoint().getX() - region.getMinimumPoint().getX()) + ',' + (region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ()) + ",256)"); TaskManager.runTask(whenDone); return; } // block type and data arrays - final BlockArrayClipboard blockArrayClipboard = schematic.getClipboard(); + final Clipboard blockArrayClipboard = schematic.getClipboard(); // Calculate the optimal height to paste the schematic at final int y_offset_actual; if (autoHeight) { @@ -160,16 +192,16 @@ public abstract class SchematicHandler { y_offset_actual = yOffset + ((ClassicPlotWorld) pw).PLOT_HEIGHT; } else { y_offset_actual = yOffset + 1 + MainUtil - .getHeighestBlock(plot.getWorldName(), region.minX + 1, - region.minZ + 1); + .getHeighestBlock(plot.getWorldName(), region.getMinimumPoint().getX() + 1, + region.getMinimumPoint().getZ() + 1); } } } else { y_offset_actual = yOffset; } Location pos1 = - new Location(plot.getWorldName(), region.minX + xOffset, y_offset_actual, - region.minZ + zOffset); + new Location(plot.getWorldName(), region.getMinimumPoint().getX() + xOffset, y_offset_actual, + region.getMinimumPoint().getZ() + zOffset); Location pos2 = pos1.clone().add(WIDTH - 1, HEIGHT - 1, LENGTH - 1); final int p1x = pos1.getX(); final int p1z = pos1.getZ(); @@ -182,9 +214,9 @@ public abstract class SchematicHandler { ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { @Override public void run(int[] value) { - ChunkLoc chunk = new ChunkLoc(value[0], value[1]); - int x = chunk.x; - int z = chunk.z; + BlockVector2 chunk = BlockVector2.at(value[0], value[1]); + int x = chunk.getX(); + int z = chunk.getZ(); int xxb = x << 4; int zzb = z << 4; int xxt = xxb + 15; @@ -267,7 +299,7 @@ public abstract class SchematicHandler { * * @return Immutable collection with schematic names */ - public Collection getShematicNames() { + public Collection getSchematicNames() { final File parent = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), Settings.Paths.SCHEMATICS); final List names = new ArrayList<>(); @@ -276,7 +308,7 @@ public abstract class SchematicHandler { parent.list((dir, name) -> name.endsWith(".schematic") || name.endsWith(".schem")); if (rawNames != null) { final List transformed = Arrays.stream(rawNames) - .map(rawName -> rawName.substring(0, rawName.length() - 10)) + //.map(rawName -> rawName.substring(0, rawName.length() - 10)) .collect(Collectors.toList()); names.addAll(transformed); } @@ -298,7 +330,7 @@ public abstract class SchematicHandler { ClipboardFormat format = ClipboardFormats.findByFile(file); if (format != null) { ClipboardReader reader = format.getReader(new FileInputStream(file)); - BlockArrayClipboard clip = (BlockArrayClipboard) reader.read(); + Clipboard clip = reader.read(); return new Schematic(clip); } else { throw new UnsupportedFormatException( @@ -310,31 +342,28 @@ public abstract class SchematicHandler { return null; } - public Schematic getSchematic(URL url) { + public Schematic getSchematic(@NotNull URL url) { try { - ReadableByteChannel rbc = Channels.newChannel(url.openStream()); - InputStream is = Channels.newInputStream(rbc); - return getSchematic(is); + ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream()); + InputStream inputStream = Channels.newInputStream(readableByteChannel); + return getSchematic(inputStream); } catch (IOException e) { e.printStackTrace(); } return null; } - public Schematic getSchematic(InputStream is) { - if (is == null) { - return null; - } + public Schematic getSchematic(@NotNull InputStream is) { try { - SpongeSchematicReader ssr = + SpongeSchematicReader schematicReader = new SpongeSchematicReader(new NBTInputStream(new GZIPInputStream(is))); - BlockArrayClipboard clip = (BlockArrayClipboard) ssr.read(); + Clipboard clip = schematicReader.read(); return new Schematic(clip); } catch (IOException ignored) { try { - MCEditSchematicReader msr = + MCEditSchematicReader schematicReader = new MCEditSchematicReader(new NBTInputStream(new GZIPInputStream(is))); - BlockArrayClipboard clip = (BlockArrayClipboard) msr.read(); + Clipboard clip = schematicReader.read(); return new Schematic(clip); } catch (IOException e) { e.printStackTrace(); @@ -416,7 +445,7 @@ public abstract class SchematicHandler { return true; } - public abstract void getCompoundTag(String world, Set regions, + public abstract void getCompoundTag(String world, Set regions, RunnableVal whenDone); public void getCompoundTag(final Plot plot, final RunnableVal whenDone) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/StringMan.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/StringMan.java index c7f30e1fa..047b4a71f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/StringMan.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/StringMan.java @@ -1,8 +1,15 @@ package com.github.intellectualsites.plotsquared.plot.util; +import org.jetbrains.annotations.NotNull; + import java.lang.reflect.Array; -import java.util.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.Iterator; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; public class StringMan { @@ -145,12 +152,7 @@ public class StringMan { public static String joinOrdered(Collection collection, String delimiter) { Object[] array = collection.toArray(); - Arrays.sort(array, new Comparator() { - @Override public int compare(Object a, Object b) { - return a.hashCode() - b.hashCode(); - } - - }); + Arrays.sort(array, Comparator.comparingInt(Object::hashCode)); return join(array, delimiter); } @@ -186,8 +188,8 @@ public class StringMan { n = m; m = t.length(); } - int p[] = new int[n + 1]; - int d[] = new int[n + 1]; + int[] p = new int[n + 1]; + int[] d = new int[n + 1]; int i; for (i = 0; i <= n; i++) { p[i] = i; @@ -235,9 +237,9 @@ public class StringMan { return false; } - public static boolean isEqualIgnoreCaseToAny(String a, String... args) { + public static boolean isEqualIgnoreCaseToAny(@NotNull String a, String... args) { for (String arg : args) { - if (StringMan.isEqualIgnoreCase(a, arg)) { + if (a.equalsIgnoreCase(arg)) { return true; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandler.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandler.java index 52e65a3fd..9967e88eb 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandler.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandler.java @@ -9,8 +9,9 @@ import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.StringWrapper; import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.google.common.collect.BiMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -85,7 +86,7 @@ public class UUIDHandler { implementation.add(toAdd); } - @Nonnull public static UUID getUUID(PlotPlayer player) { + @NotNull public static UUID getUUID(PlotPlayer player) { return implementation.getUUID(player); } @@ -96,12 +97,12 @@ public class UUIDHandler { return implementation.getUUID(player); } - public static String getName(UUID uuid) { + @Nullable public static String getName(UUID uuid) { if (implementation == null) { return null; } if (uuid != null && uuid.equals(DBFunc.SERVER)) { - return Captions.SERVER.s(); + return Captions.SERVER.getTranslated(); } return implementation.getName(uuid); } @@ -120,13 +121,13 @@ public class UUIDHandler { return check(implementation.getPlayer(name)); } - private static PlotPlayer check(PlotPlayer plr) { - if (plr != null && !plr.isOnline()) { - UUIDHandler.getPlayers().remove(plr.getName()); - PlotSquared.get().IMP.unregister(plr); - plr = null; + private static PlotPlayer check(@Nullable PlotPlayer player) { + if (player != null && !player.isOnline()) { + UUIDHandler.getPlayers().remove(player.getName()); + PlotSquared.get().IMP.unregister(player); + player = null; } - return plr; + return player; } public static UUID getUUIDFromString(String nameOrUUIDString) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandlerImplementation.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandlerImplementation.java index baf7523ca..57b70d263 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandlerImplementation.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/UUIDHandlerImplementation.java @@ -4,13 +4,23 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.object.StringWrapper; import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.google.common.base.Charsets; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public abstract class UUIDHandlerImplementation { @@ -20,7 +30,6 @@ public abstract class UUIDHandlerImplementation { protected UUIDWrapper uuidWrapper; private boolean cached = false; private BiMap uuidMap = HashBiMap.create(new HashMap<>()); - // private BiMap nameMap = uuidMap.inverse(); public UUIDHandlerImplementation(UUIDWrapper wrapper) { this.uuidWrapper = wrapper; @@ -152,19 +161,19 @@ public abstract class UUIDHandlerImplementation { }); } try { - UUID offline = this.uuidMap.put(name, uuid); - if (offline != null) { - if (!offline.equals(uuid)) { - Set plots = PlotSquared.get().getPlots(offline); + UUID existing = this.uuidMap.put(name, uuid); + if (existing != null) { + if (!existing.equals(uuid)) { + Set plots = PlotSquared.get().getPlots(existing); if (!plots.isEmpty()) { for (Plot plot : plots) { plot.owner = uuid; } - replace(offline, uuid, name.value); + replace(existing, uuid, name.value); } return true; } else { - StringWrapper oName = this.uuidMap.inverse().get(offline); + StringWrapper oName = this.uuidMap.inverse().get(existing); if (!oName.equals(name)) { this.uuidMap.remove(name); this.uuidMap.put(name, uuid); @@ -182,6 +191,13 @@ public abstract class UUIDHandlerImplementation { PlotPlayer player = getPlayer(uuid); if (player == null || player.getName().equalsIgnoreCase(name.value)) { rename(uuid, name); + return false; + } + StringWrapper newName = new StringWrapper(player.getName()); + UUID newUUID = player.getUUID(); + if (newUUID.equals(uuid) && !newName.equals(oldName)) { + inverse.remove(uuid); + this.uuidMap.put(newName, newUUID); } return false; } @@ -216,7 +232,7 @@ public abstract class UUIDHandlerImplementation { this.uuidMap.clear(); } - public String getName(UUID uuid) { + @Nullable public String getName(UUID uuid) { if (uuid == null) { return null; } @@ -227,7 +243,7 @@ public abstract class UUIDHandlerImplementation { return null; } - public UUID getUUID(String name, RunnableVal ifFetch) { + @Nullable public UUID getUUID(String name, RunnableVal ifFetch) { if (name.isEmpty()) { return null; } @@ -255,7 +271,7 @@ public abstract class UUIDHandlerImplementation { return null; } - public UUID getUUID(PlotPlayer player) { + @NotNull public UUID getUUID(PlotPlayer player) { return this.uuidWrapper.getUUID(player); } @@ -263,7 +279,7 @@ public abstract class UUIDHandlerImplementation { return this.uuidWrapper.getUUID(player); } - public PlotPlayer getPlayer(UUID uuid) { + @Nullable public PlotPlayer getPlayer(UUID uuid) { String name = getName(uuid); if (name != null) { return getPlayer(name); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/WorldUtil.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/WorldUtil.java index 2e05542aa..f2a37512f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/WorldUtil.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/WorldUtil.java @@ -1,11 +1,26 @@ package com.github.intellectualsites.plotsquared.plot.util; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.schematic.PlotItem; -import com.sk89q.jnbt.*; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.IntTag; +import com.sk89q.jnbt.NBTInputStream; +import com.sk89q.jnbt.NBTOutputStream; +import com.sk89q.jnbt.Tag; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.block.BlockState; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.OutputStream; import java.net.URL; import java.util.Map; import java.util.Set; @@ -18,10 +33,6 @@ import java.util.zip.ZipOutputStream; public abstract class WorldUtil { public static WorldUtil IMP; - public abstract int getBiomeFromString(String value); - - public abstract String[] getBiomeList(); - public abstract String getMainWorld(); public abstract boolean isWorld(String worldName); @@ -30,21 +41,19 @@ public abstract class WorldUtil { public abstract Location getSpawn(String world); - public abstract Location getSpawn(PlotPlayer pp); - public abstract void setSpawn(Location location); public abstract void saveWorld(String world); - public abstract String getClosestMatchingName(PlotBlock plotBlock); + public abstract String getClosestMatchingName(BlockState plotBlock); - public abstract boolean isBlockSolid(PlotBlock block); + public abstract boolean isBlockSolid(BlockState block); - public abstract StringComparison.ComparisonResult getClosestBlock(String name); + public abstract StringComparison.ComparisonResult getClosestBlock(String name); - public abstract String getBiome(String world, int x, int z); + public abstract BiomeType getBiome(String world, int x, int z); - public abstract PlotBlock getBlock(Location location); + public abstract BlockState getBlock(Location location); public abstract int getHighestBlock(String world, int x, int z); @@ -52,7 +61,7 @@ public abstract class WorldUtil { public abstract void setSign(String world, int x, int y, int z, String[] lines); - public abstract void setBiomes(String world, RegionWrapper region, String biome); + public abstract void setBiomes(String world, CuboidRegion region, BiomeType biome); public abstract com.sk89q.worldedit.world.World getWeWorld(String world); @@ -66,7 +75,6 @@ public abstract class WorldUtil { try (final ZipOutputStream zos = new ZipOutputStream(output)) { File dat = getDat(plot.getWorldName()); Location spawn = getSpawn(plot.getWorldName()); - byte[] buffer = new byte[1024]; if (dat != null) { ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName()); zos.putNextEntry(ze); @@ -89,6 +97,7 @@ public abstract class WorldUtil { } } setSpawn(spawn); + byte[] buffer = new byte[1024]; for (Plot current : plot.getConnectedPlots()) { Location bot = current.getBottomAbs(); Location top = current.getTopAbs(); @@ -96,10 +105,10 @@ public abstract class WorldUtil { int brz = bot.getZ() >> 9; int trx = top.getX() >> 9; int trz = top.getZ() >> 9; - Set files = ChunkManager.manager.getChunkChunks(bot.getWorld()); - for (ChunkLoc mca : files) { - if (mca.x >= brx && mca.x <= trx && mca.z >= brz && mca.z <= trz) { - final File file = getMcr(plot.getWorldName(), mca.x, mca.z); + Set files = ChunkManager.manager.getChunkChunks(bot.getWorld()); + for (BlockVector2 mca : files) { + if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz && mca.getZ() <= trz) { + final File file = getMcr(plot.getWorldName(), mca.getX(), mca.getZ()); if (file != null) { //final String name = "r." + (x - cx) + "." + (z - cz) + ".mca"; String name = file.getName(); @@ -107,12 +116,12 @@ public abstract class WorldUtil { "world" + File.separator + "region" + File.separator + name); zos.putNextEntry(ze); - final FileInputStream in = new FileInputStream(file); - int len; - while ((len = in.read(buffer)) > 0) { - zos.write(buffer, 0, len); + try (FileInputStream in = new FileInputStream(file)) { + int len; + while ((len = in.read(buffer)) > 0) { + zos.write(buffer, 0, len); + } } - in.close(); zos.closeEntry(); } } @@ -147,5 +156,5 @@ public abstract class WorldUtil { return null; } - public abstract boolean isBlockSame(PlotBlock block1, PlotBlock block2); + public abstract boolean isBlockSame(BlockState block1, BlockState block2); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/area/QuadMap.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/area/QuadMap.java index 133088a2e..e016cfeea 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/area/QuadMap.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/area/QuadMap.java @@ -1,6 +1,7 @@ package com.github.intellectualsites.plotsquared.plot.util.area; -import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; +import com.github.intellectualsites.plotsquared.plot.util.world.RegionUtil; +import com.sk89q.worldedit.regions.CuboidRegion; import java.util.HashSet; import java.util.Set; @@ -96,9 +97,9 @@ public class QuadMap { this.objects.add(area); return; } - RegionWrapper region = getRegion(area); - if (region.minX >= this.x) { - if (region.minZ >= this.z) { + CuboidRegion region = getRegion(area); + if (region.getMinimumPoint().getX() >= this.x) { + if (region.getMinimumPoint().getZ() >= this.z) { if (this.one == null) { this.one = newInstance(this.newsize, this.x + this.newsize, this.z + this.newsize, @@ -107,7 +108,7 @@ public class QuadMap { this.one.add(area); recalculateSkip(); return; - } else if (region.maxZ < this.z) { + } else if (region.getMaximumPoint().getZ() < this.z) { if (this.two == null) { this.two = newInstance(this.newsize, this.x + this.newsize, this.z - this.newsize, @@ -117,8 +118,8 @@ public class QuadMap { recalculateSkip(); return; } - } else if (region.maxX < this.x) { - if (region.minZ >= this.z) { + } else if (region.getMaximumPoint().getX() < this.x) { + if (region.getMinimumPoint().getZ() >= this.z) { if (this.four == null) { this.four = newInstance(this.newsize, this.x - this.newsize, this.z + this.newsize, @@ -127,7 +128,7 @@ public class QuadMap { this.four.add(area); recalculateSkip(); return; - } else if (region.maxZ < this.z) { + } else if (region.getMaximumPoint().getZ() < this.z) { if (this.three == null) { this.three = newInstance(this.newsize, this.x - this.newsize, this.z - this.newsize, @@ -144,14 +145,14 @@ public class QuadMap { this.objects.add(area); } - public RegionWrapper getRegion(T value) { + public CuboidRegion getRegion(T value) { return null; } public QuadMap newInstance(int newsize, int x, int z, int min) { try { return new QuadMap(newsize, x, z, min) { - @Override public RegionWrapper getRegion(T value) { + @Override public CuboidRegion getRegion(T value) { return QuadMap.this.getRegion(value); } }; @@ -172,9 +173,9 @@ public class QuadMap { this.skip = null; } } else { - RegionWrapper region = getRegion(area); - if (region.minX >= this.x) { - if (region.minZ >= this.z) { + CuboidRegion region = getRegion(area); + if (region.getMinimumPoint().getX() >= this.x) { + if (region.getMinimumPoint().getZ() >= this.z) { if (this.one != null) { if (this.one.remove(area)) { this.one = null; @@ -190,7 +191,7 @@ public class QuadMap { } } } else { - if (region.minZ >= this.z) { + if (region.getMinimumPoint().getZ() >= this.z) { if (this.four != null) { if (this.four.remove(area)) { this.four = null; @@ -224,11 +225,11 @@ public class QuadMap { this.skip = map.skip == null ? map : map.skip; } - public Set get(RegionWrapper region) { + public Set get(CuboidRegion region) { HashSet set = new HashSet<>(); if (this.objects != null) { for (T obj : this.objects) { - if (getRegion(obj).intersects(region)) { + if (RegionUtil.intersects(getRegion(obj), region)) { set.add(obj); } } @@ -254,15 +255,15 @@ public class QuadMap { return set; } - public boolean intersects(RegionWrapper other) { - return (other.minX <= this.x + this.size) && (other.maxX >= this.x - this.size) && ( - other.minZ <= this.z + this.size) && (other.maxZ >= this.z - this.size); + public boolean intersects(CuboidRegion other) { + return (other.getMinimumPoint().getX() <= this.x + this.size) && (other.getMaximumPoint().getX() >= this.x - this.size) && ( + other.getMinimumPoint().getZ() <= this.z + this.size) && (other.getMaximumPoint().getZ() >= this.z - this.size); } public T get(int x, int z) { if (this.objects != null) { for (T obj : this.objects) { - if (getRegion(obj).isIn(x, z)) { + if (RegionUtil.contains(getRegion(obj), x, z)) { return obj; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/BasicLocalBlockQueue.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/BasicLocalBlockQueue.java index 282c21bc4..72b6252a3 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/BasicLocalBlockQueue.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/BasicLocalBlockQueue.java @@ -1,17 +1,21 @@ package com.github.intellectualsites.plotsquared.plot.util.block; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.world.PatternUtil; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; -import lombok.Getter; +import com.sk89q.worldedit.world.block.BlockState; +import org.jetbrains.annotations.NotNull; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.ExecutionException; -public abstract class BasicLocalBlockQueue extends LocalBlockQueue { +public abstract class BasicLocalBlockQueue extends LocalBlockQueue { private final String world; private final ConcurrentHashMap blockChunks = new ConcurrentHashMap<>(); @@ -20,7 +24,6 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { private LocalChunk lastWrappedChunk; private int lastX = Integer.MIN_VALUE; private int lastZ = Integer.MIN_VALUE; - @Getter private boolean baseBlocks = false; public BasicLocalBlockQueue(String world) { super(world); @@ -30,9 +33,10 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { public abstract LocalChunk getLocalChunk(int x, int z); - @Override public abstract PlotBlock getBlock(int x, int y, int z); + @Override public abstract BlockState getBlock(int x, int y, int z); - public abstract void setComponents(LocalChunk lc); + public abstract void setComponents(LocalChunk lc) + throws ExecutionException, InterruptedException; @Override public final String getWorld() { return world; @@ -49,8 +53,7 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { LocalChunk chunk = chunks.poll(); if (chunk != null) { blockChunks.remove(chunk.longHash()); - this.execute(chunk); - return true; + return this.execute(chunk); } } } catch (Throwable e) { @@ -59,10 +62,8 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { return false; } - public final boolean execute(final LocalChunk lc) { - if (lc == null) { - return false; - } + public final boolean execute(@NotNull LocalChunk lc) + throws ExecutionException, InterruptedException { this.setComponents(lc); return true; } @@ -87,11 +88,14 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { this.modified = modified; } + @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { + return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z)); + } + @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { if ((y > 255) || (y < 0)) { return false; } - baseBlocks = true; int cx = x >> 4; int cz = z >> 4; if (cx != lastX || cz != lastZ) { @@ -104,8 +108,7 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { lastWrappedChunk.setBlock(x & 15, y, z & 15, id); LocalChunk previous = this.blockChunks.put(pair, lastWrappedChunk); if (previous == null) { - chunks.add(lastWrappedChunk); - return true; + return chunks.add(lastWrappedChunk); } this.blockChunks.put(pair, previous); lastWrappedChunk = previous; @@ -115,36 +118,14 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { return true; } - @Override public boolean setBlock(int x, int y, int z, PlotBlock id) { - if (y > 255) { - return false; - } else if (y < 0) { - return false; - } - int cx = x >> 4; - int cz = z >> 4; - if (cx != lastX || cz != lastZ) { - lastX = cx; - lastZ = cz; - long pair = (long) (cx) << 32 | (cz) & 0xFFFFFFFFL; - lastWrappedChunk = this.blockChunks.get(pair); - if (lastWrappedChunk == null) { - lastWrappedChunk = this.getLocalChunk(x >> 4, z >> 4); - lastWrappedChunk.setBlock(x & 15, y, z & 15, id); - LocalChunk previous = this.blockChunks.put(pair, lastWrappedChunk); - if (previous == null) { - chunks.add(lastWrappedChunk); - return true; - } - this.blockChunks.put(pair, previous); - lastWrappedChunk = previous; - } - } - lastWrappedChunk.setBlock(x & 15, y, z & 15, id); - return true; + @Override public boolean setBlock(int x, int y, int z, BlockState id) { + // Trying to mix BlockState and BaseBlock leads to all kinds of issues. + // Since BaseBlock has more features than BlockState, simply convert + // all BlockStates to BaseBlocks + return setBlock(x, y, z, id.toBaseBlock()); } - @Override public final boolean setBiome(int x, int z, String biome) { + @Override public final boolean setBiome(int x, int z, BiomeType biomeType) { long pair = (long) (x >> 4) << 32 | (z >> 4) & 0xFFFFFFFFL; LocalChunk result = this.blockChunks.get(pair); if (result == null) { @@ -157,11 +138,11 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { chunks.add(result); } } - result.setBiome(x & 15, z & 15, biome); + result.setBiome(x & 15, z & 15, biomeType); return true; } - public final void setChunk(LocalChunk chunk) { + public final void setChunk(LocalChunk chunk) { LocalChunk previous = this.blockChunks.put(chunk.longHash(), chunk); if (previous != null) { chunks.remove(previous); @@ -174,23 +155,21 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { TaskManager.IMP.sync(new RunnableVal() { @Override public void run(Object value) { while (next()) { - ; } } }); } - public abstract class LocalChunk { + public abstract class LocalChunk { public final BasicLocalBlockQueue parent; public final int z; public final int x; - public T[] blocks; public BaseBlock[][] baseblocks; - public String[][] biomes; + public BiomeType[][] biomes; - public LocalChunk(BasicLocalBlockQueue parent, int x, int z) { + public LocalChunk(BasicLocalBlockQueue parent, int x, int z) { this.parent = parent; this.x = x; this.z = z; @@ -213,19 +192,17 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { return z; } - public abstract void setBlock(final int x, final int y, final int z, final PlotBlock block); - public abstract void setBlock(final int x, final int y, final int z, final BaseBlock block); - public void setBiome(int x, int z, String biome) { + public void setBiome(int x, int z, BiomeType biomeType) { if (this.biomes == null) { - this.biomes = new String[16][]; + this.biomes = new BiomeType[16][]; } - String[] index = this.biomes[x]; + BiomeType[] index = this.biomes[x]; if (index == null) { - index = this.biomes[x] = new String[16]; + index = this.biomes[x] = new BiomeType[16]; } - index[z] = biome; + index[z] = biomeType; } public long longHash() { @@ -238,27 +215,12 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { } - public class BasicLocalChunk extends LocalChunk { + public class BasicLocalChunk extends LocalChunk { public BasicLocalChunk(BasicLocalBlockQueue parent, int x, int z) { super(parent, x, z); - blocks = new PlotBlock[16][]; baseblocks = new BaseBlock[16][]; } - @Override public void setBlock(int x, int y, int z, PlotBlock block) { - this.setInternal(x, y, z, block); - } - - private void setInternal(final int x, final int y, final int z, final PlotBlock plotBlock) { - final int i = MainUtil.CACHE_I[y][x][z]; - final int j = MainUtil.CACHE_J[y][x][z]; - PlotBlock[] array = blocks[i]; - if (array == null) { - array = (blocks[i] = new PlotBlock[4096]); - } - array[j] = plotBlock; - } - @Override public void setBlock(int x, int y, int z, BaseBlock block) { this.setInternal(x, y, z, block); } @@ -272,10 +234,5 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { } array[j] = baseBlock; } - - public void setBlock(final int x, final int y, final int z, final int id, final int data) { - final PlotBlock block = PlotBlock.get(id, data); - this.setInternal(x, y, z, block); - } } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/ChunkBlockQueue.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/ChunkBlockQueue.java new file mode 100644 index 000000000..0d7f9294d --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/ChunkBlockQueue.java @@ -0,0 +1,100 @@ +package com.github.intellectualsites.plotsquared.plot.util.block; + +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; + +public class ChunkBlockQueue extends ScopedLocalBlockQueue { + + public final BiomeType[] biomeGrid; + public final BlockState[][][] result; + private final int width; + private final int length; + @Deprecated private final int area; + private final BlockVector3 bot; + private final BlockVector3 top; + + public ChunkBlockQueue(BlockVector3 bot, BlockVector3 top, boolean biomes) { + super(null, new Location(null, 0, 0, 0), new Location(null, 15, 255, 15)); + this.width = top.getX() - bot.getX() + 1; + this.length = top.getZ() - bot.getZ() + 1; + this.area = width * length; + this.result = new BlockState[256][][]; + this.biomeGrid = biomes ? new BiomeType[width * length] : null; + this.bot = bot; + this.top = top; + } + + public BlockState[][][] getBlocks() { + return result; + } + + @Override public void fillBiome(BiomeType biomeType) { + if (biomeGrid == null) { + return; + } + Arrays.fill(biomeGrid, biomeType); + } + + @Override public boolean setBiome(int x, int z, BiomeType biomeType) { + if (this.biomeGrid != null) { + biomeGrid[(z * width) + x] = biomeType; + return true; + } + return false; + } + + @Override public boolean setBlock(int x, int y, int z, BlockState id) { + this.storeCache(x, y, z, id); + return true; + } + + private void storeCache(final int x, final int y, final int z, final BlockState id) { + BlockState[][] resultY = result[y]; + if (resultY == null) { + result[y] = resultY = new BlockState[length][]; + } + BlockState[] resultYZ = resultY[z]; + if (resultYZ == null) { + resultY[z] = resultYZ = new BlockState[width]; + } + resultYZ[x] = id; + } + + @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { + this.storeCache(x, y, z, id.toImmutableState()); + return true; + } + + @Override + @Nullable + public BlockState getBlock(int x, int y, int z) { + BlockState[][] blocksY = result[y]; + if (blocksY != null) { + BlockState[] blocksYZ = blocksY[z]; + if (blocksYZ != null) { + return blocksYZ[x]; + } + } + return null; + } + + @Override + @Nullable + public String getWorld() { + return null; + } + + @Override public Location getMax() { + return new Location(getWorld(), top.getX(), top.getY(), top.getZ()); + } + + @Override public Location getMin() { + return new Location(getWorld(), bot.getX(), bot.getY(), bot.getZ()); + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/DelegateLocalBlockQueue.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/DelegateLocalBlockQueue.java index 0c797c706..78e706b6b 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/DelegateLocalBlockQueue.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/DelegateLocalBlockQueue.java @@ -1,7 +1,9 @@ package com.github.intellectualsites.plotsquared.plot.util.block; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; public class DelegateLocalBlockQueue extends LocalBlockQueue { @@ -58,19 +60,23 @@ public class DelegateLocalBlockQueue extends LocalBlockQueue { } } + @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { + return parent.setBlock(x, y, z, pattern); + } + @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { return parent.setBlock(x, y, z, id); } - @Override public boolean setBlock(int x, int y, int z, PlotBlock id) { + @Override public boolean setBlock(int x, int y, int z, BlockState id) { return parent.setBlock(x, y, z, id); } - @Override public PlotBlock getBlock(int x, int y, int z) { + @Override public BlockState getBlock(int x, int y, int z) { return parent.getBlock(x, y, z); } - @Override public boolean setBiome(int x, int z, String biome) { + @Override public boolean setBiome(int x, int z, BiomeType biome) { return parent.setBiome(x, z, biome); } @@ -102,9 +108,10 @@ public class DelegateLocalBlockQueue extends LocalBlockQueue { } } - @Override public void enqueue() { + @Override public boolean enqueue() { if (parent != null) { - parent.enqueue(); + return parent.enqueue(); } + return false; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/GlobalBlockQueue.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/GlobalBlockQueue.java index a448eb127..049b13d32 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/GlobalBlockQueue.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/GlobalBlockQueue.java @@ -20,8 +20,10 @@ public class GlobalBlockQueue { private final ConcurrentLinkedDeque runnables; private final AtomicBoolean running; private QueueProvider provider; + /** - * Used to calculate elapsed time in milliseconds and ensure block placement doesn't lag the server + * Used to calculate elapsed time in milliseconds and ensure block placement doesn't lag the + * server */ private long last; private long secondLast; @@ -34,7 +36,7 @@ public class GlobalBlockQueue { if (!more) { lastSuccess = last; if (inactiveQueues.size() == 0 && activeQueues.size() == 0) { - tasks(); + runEmptyTasks(); } return; } @@ -45,10 +47,10 @@ public class GlobalBlockQueue { public GlobalBlockQueue(QueueProvider provider, int threads) { this.provider = provider; - activeQueues = new ConcurrentLinkedDeque<>(); - inactiveQueues = new ConcurrentLinkedDeque<>(); - runnables = new ConcurrentLinkedDeque<>(); - running = new AtomicBoolean(); + this.activeQueues = new ConcurrentLinkedDeque<>(); + this.inactiveQueues = new ConcurrentLinkedDeque<>(); + this.runnables = new ConcurrentLinkedDeque<>(); + this.running = new AtomicBoolean(); this.PARALLEL_THREADS = threads; } @@ -85,14 +87,14 @@ public class GlobalBlockQueue { @Override public void run() { if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) { lastSuccess = System.currentTimeMillis(); - tasks(); + GlobalBlockQueue.this.runEmptyTasks(); return; } SET_TASK.value1 = 50 + Math.min( (50 + GlobalBlockQueue.this.last) - (GlobalBlockQueue.this.last = System.currentTimeMillis()), GlobalBlockQueue.this.secondLast - System.currentTimeMillis()); - SET_TASK.value2 = getNextQueue(); + SET_TASK.value2 = GlobalBlockQueue.this.getNextQueue(); if (SET_TASK.value2 == null) { return; } @@ -153,12 +155,20 @@ public class GlobalBlockQueue { return false; } - public void enqueue(LocalBlockQueue queue) { - inactiveQueues.remove(queue); + /** + * TODO Documentation needed. + * + * @param queue todo + * @return true if added to queue, false otherwise + */ + public boolean enqueue(LocalBlockQueue queue) { + boolean success = false; + success = inactiveQueues.remove(queue); if (queue.size() > 0 && !activeQueues.contains(queue)) { queue.optimize(); - activeQueues.add(queue); + success = activeQueues.add(queue); } + return success; } public void dequeue(LocalBlockQueue queue) { @@ -199,7 +209,9 @@ public class GlobalBlockQueue { } else { ArrayList threads = new ArrayList<>(); for (int i = 0; i < PARALLEL_THREADS; i++) { - threads.add(new Thread(SET_TASK)); + Thread thread = new Thread(SET_TASK); + thread.setName("PlotSquared Flush Task"); + threads.add(thread); } for (Thread thread : threads) { thread.start(); @@ -223,7 +235,7 @@ public class GlobalBlockQueue { public LocalBlockQueue getNextQueue() { long now = System.currentTimeMillis(); - while (activeQueues.size() > 0) { + while (!activeQueues.isEmpty()) { LocalBlockQueue queue = activeQueues.peek(); if (queue != null && queue.size() > 0) { queue.setModified(now); @@ -243,7 +255,7 @@ public class GlobalBlockQueue { long age = now - queue.getModified(); total += queue.size(); if (queue.size() == 0) { - if (age > 1000) { + if (age > 60000) { iter.remove(); } continue; @@ -255,7 +267,7 @@ public class GlobalBlockQueue { firstNonEmpty.setModified(now); return firstNonEmpty; } - if (age > 60000) { + if (age > 1000) { queue.setModified(now); return queue; } @@ -271,10 +283,10 @@ public class GlobalBlockQueue { return activeQueues.size() == 0 && inactiveQueues.size() == 0; } - public boolean addTask(final Runnable whenDone) { + public boolean addEmptyTask(final Runnable whenDone) { if (this.isDone()) { // Run - this.tasks(); + this.runEmptyTasks(); if (whenDone != null) { whenDone.run(); } @@ -286,19 +298,18 @@ public class GlobalBlockQueue { return false; } - public synchronized boolean tasks() { + private synchronized void runEmptyTasks() { if (this.runnables.isEmpty()) { - return false; + return; } - final ArrayList tmp = new ArrayList<>(this.runnables); + final ConcurrentLinkedDeque tmp = new ConcurrentLinkedDeque<>(this.runnables); this.runnables.clear(); for (final Runnable runnable : tmp) { runnable.run(); } - return true; } public enum QueueStage { - INACTIVE, ACTIVE, NONE; + INACTIVE, ACTIVE, NONE } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/LocalBlockQueue.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/LocalBlockQueue.java index 16538784f..4778a1cae 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/LocalBlockQueue.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/LocalBlockQueue.java @@ -1,19 +1,29 @@ package com.github.intellectualsites.plotsquared.plot.util.block; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; import com.github.intellectualsites.plotsquared.plot.util.StringMan; import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import com.github.intellectualsites.plotsquared.plot.util.world.PatternUtil; import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; import java.util.Map; public abstract class LocalBlockQueue { - public LocalBlockQueue(String world) { - // Implement this elsewhere + /** + * Needed for compatibility with FAWE. + * + * @param world unused + */ + @Deprecated public LocalBlockQueue(String world) { } public ScopedLocalBlockQueue getForChunk(int x, int z) { @@ -45,18 +55,22 @@ public abstract class LocalBlockQueue { * @param z the z coordinate from 0 to 15 inclusive * @param id the id to set the block to */ - public abstract boolean setBlock(final int x, final int y, final int z, final PlotBlock id); + public abstract boolean setBlock(final int x, final int y, final int z, final BlockState id); public abstract boolean setBlock(final int x, final int y, final int z, final BaseBlock id); + public boolean setBlock(final int x, final int y, final int z, final Pattern pattern) { + return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z)); + } + public boolean setTile(int x, int y, int z, CompoundTag tag) { SchematicHandler.manager.restoreTile(this, tag, x, y, z); return true; } - public abstract PlotBlock getBlock(int x, int y, int z); + public abstract BlockState getBlock(int x, int y, int z); - public abstract boolean setBiome(int x, int z, String biome); + public abstract boolean setBiome(int x, int z, BiomeType biome); public abstract String getWorld(); @@ -75,11 +89,11 @@ public abstract class LocalBlockQueue { public final void regenChunkSafe(int x, int z) { regenChunk(x, z); fixChunkLighting(x, z); - ChunkLoc loc = new ChunkLoc(x, z); + BlockVector2 loc = BlockVector2.at(x, z); for (Map.Entry entry : UUIDHandler.getPlayers().entrySet()) { PlotPlayer pp = entry.getValue(); Location pLoc = pp.getLocation(); - if (!StringMan.isEqual(getWorld(), pLoc.getWorld()) || !pLoc.getChunkLoc() + if (!StringMan.isEqual(getWorld(), pLoc.getWorld()) || !pLoc.getBlockVector2() .equals(loc)) { continue; } @@ -88,27 +102,37 @@ public abstract class LocalBlockQueue { } } - public void enqueue() { - GlobalBlockQueue.IMP.enqueue(this); + public boolean enqueue() { + return GlobalBlockQueue.IMP.enqueue(this); } - public void setCuboid(Location pos1, Location pos2, PlotBlock block) { - for (int y = pos1.getY(); y <= Math.min(255, pos2.getY()); y++) { - for (int x = pos1.getX(); x <= pos2.getX(); x++) { - for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { + public void setCuboid(Location pos1, Location pos2, BlockState block) { + int yMin = Math.min(pos1.getY(), pos2.getY()); + int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); + int xMin = Math.min(pos1.getX(), pos2.getX()); + int xMax = Math.max(pos1.getX(), pos2.getX()); + int zMin = Math.min(pos1.getZ(), pos2.getZ()); + int zMax = Math.max(pos1.getZ(), pos2.getZ()); + for (int y = yMin; y <= yMax; y++) { + for (int x = xMin; x <= xMax; x++) { + for (int z = zMin; z <= zMax; z++) { setBlock(x, y, z, block); } } } } - public void setCuboid(Location pos1, Location pos2, BlockBucket blocks) { - for (int y = pos1.getY(); y <= Math.min(255, pos2.getY()); y++) { - for (int x = pos1.getX(); x <= pos2.getX(); x++) { - for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { - // int i = PseudoRandom.random.random(blocks.length); - // PlotBlock block = blocks[i]; - setBlock(x, y, z, blocks.getBlock()); + public void setCuboid(Location pos1, Location pos2, Pattern blocks) { + int yMin = Math.min(pos1.getY(), pos2.getY()); + int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); + int xMin = Math.min(pos1.getX(), pos2.getX()); + int xMax = Math.max(pos1.getX(), pos2.getX()); + int zMin = Math.min(pos1.getZ(), pos2.getZ()); + int zMax = Math.max(pos1.getZ(), pos2.getZ()); + for (int y = yMin; y <= yMax; y++) { + for (int x = xMin; x <= xMax; x++) { + for (int z = zMin; z <= zMax; z++) { + setBlock(x, y, z, blocks); } } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/OffsetLocalBlockQueue.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/OffsetLocalBlockQueue.java index d0a561111..37ac7fe5c 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/OffsetLocalBlockQueue.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/OffsetLocalBlockQueue.java @@ -1,5 +1,6 @@ package com.github.intellectualsites.plotsquared.plot.util.block; +import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; public class OffsetLocalBlockQueue extends DelegateLocalBlockQueue { @@ -14,7 +15,7 @@ public class OffsetLocalBlockQueue extends DelegateLocalBlockQueue { this.oz = oz; } - @Override public boolean setBiome(int x, int y, String biome) { + @Override public boolean setBiome(int x, int y, BiomeType biome) { return super.setBiome(ox + x, oy + y, biome); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/ScopedLocalBlockQueue.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/ScopedLocalBlockQueue.java index 352465aea..6a0e375c5 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/ScopedLocalBlockQueue.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/block/ScopedLocalBlockQueue.java @@ -1,8 +1,14 @@ package com.github.intellectualsites.plotsquared.plot.util.block; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; public class ScopedLocalBlockQueue extends DelegateLocalBlockQueue { private final int minX; @@ -33,11 +39,11 @@ public class ScopedLocalBlockQueue extends DelegateLocalBlockQueue { } - @Override public boolean setBiome(int x, int z, String biome) { + @Override public boolean setBiome(int x, int z, BiomeType biome) { return x >= 0 && x <= dx && z >= 0 && z <= dz && super.setBiome(x + minX, z + minZ, biome); } - public void fillBiome(String biome) { + public void fillBiome(BiomeType biome) { for (int x = 0; x <= dx; x++) { for (int z = 0; z < dz; z++) { setBiome(x, z, biome); @@ -50,7 +56,7 @@ public class ScopedLocalBlockQueue extends DelegateLocalBlockQueue { .setBlock(x + minX, y + minY, z + minZ, id); } - @Override public boolean setBlock(int x, int y, int z, PlotBlock id) { + @Override public boolean setBlock(int x, int y, int z, BlockState id) { return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super .setBlock(x + minX, y + minY, z + minZ, id); } @@ -75,22 +81,22 @@ public class ScopedLocalBlockQueue extends DelegateLocalBlockQueue { int bx = minX; int bz = minZ; PlotArea area = PlotSquared.get().getPlotArea(getWorld(), null); - Location loc = new Location(getWorld(), bx, 0, bz); + Location location = new Location(getWorld(), bx, 0, bz); if (area != null) { PlotManager manager = area.getPlotManager(); for (int x = 0; x < 16; x++) { - loc.setX(bx + x); + location.setX(bx + x); for (int z = 0; z < 16; z++) { - loc.setZ(bz + z); - task.run(area.getPlotAbs(loc), x, z); + location.setZ(bz + z); + task.run(area.getPlotAbs(location), x, z); } } } else { for (int x = 0; x < 16; x++) { - loc.setX(bx + x); + location.setX(bx + x); for (int z = 0; z < 16; z++) { - loc.setZ(bz + z); - task.run(loc.getPlotAbs(), x, z); + location.setZ(bz + z); + task.run(location.getPlotAbs(), x, z); } } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/ExpireManager.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/ExpireManager.java index cf4e025eb..dbd9773f0 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/ExpireManager.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/ExpireManager.java @@ -7,13 +7,28 @@ import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.StringMan; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; @@ -169,13 +184,12 @@ public class ExpireManager { return new ArrayList<>(); } - boolean shouldCheckAccountAge = false; - long diff = getAge(plot); if (diff == 0) { return new ArrayList<>(); } // Filter out non old plots + boolean shouldCheckAccountAge = false; for (int i = 0; i < applicable.size(); i++) { ExpiryTask et = applicable.poll(); if (et.applies(diff)) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/PlotAnalysis.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/PlotAnalysis.java index 429a71035..484759d66 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/PlotAnalysis.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/expiry/PlotAnalysis.java @@ -10,7 +10,12 @@ import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import java.lang.reflect.Array; -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; public class PlotAnalysis { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/helpmenu/HelpObject.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/helpmenu/HelpObject.java index f753b21e9..9981dd0f1 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/helpmenu/HelpObject.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/helpmenu/HelpObject.java @@ -10,7 +10,7 @@ public class HelpObject { private final String _rendered; public HelpObject(final Command command, final String label) { - _rendered = StringMan.replaceAll(Captions.HELP_ITEM.s(), "%usage%", + _rendered = StringMan.replaceAll(Captions.HELP_ITEM.getTranslated(), "%usage%", command.getUsage().replaceAll("\\{label\\}", label), "[%alias%]", !command.getAliases().isEmpty() ? "(" + StringMan.join(command.getAliases(), "|") + ")" : diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/helpmenu/HelpPage.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/helpmenu/HelpPage.java index 3f29aefb1..5b165d32a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/helpmenu/HelpPage.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/helpmenu/HelpPage.java @@ -16,7 +16,7 @@ public class HelpPage { public HelpPage(CommandCategory category, int currentPage, int maxPages) { this.helpObjects = new ArrayList<>(); - this.header = Captions.HELP_PAGE_HEADER.s() + this.header = Captions.HELP_PAGE_HEADER.getTranslated() .replace("%category%", category == null ? "ALL" : category.toString()) .replace("%current%", (currentPage + 1) + "").replace("%max%", (maxPages + 1) + ""); } @@ -25,8 +25,9 @@ public class HelpPage { if (this.helpObjects.size() < 1) { MainUtil.sendMessage(player, Captions.NOT_VALID_NUMBER, "(0)"); } else { - String message = Captions.HELP_HEADER.s() + "\n" + this.header + "\n" + StringMan - .join(this.helpObjects, "\n") + "\n" + Captions.HELP_FOOTER.s(); + String message = + Captions.HELP_HEADER.getTranslated() + "\n" + this.header + "\n" + StringMan + .join(this.helpObjects, "\n") + "\n" + Captions.HELP_FOOTER.getTranslated(); MainUtil.sendMessage(player, message, false); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/BlockUtil.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/BlockUtil.java new file mode 100644 index 000000000..ca5b8f777 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/BlockUtil.java @@ -0,0 +1,86 @@ +package com.github.intellectualsites.plotsquared.plot.util.world; + +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.input.InputParseException; +import com.sk89q.worldedit.extension.input.ParserContext; +import com.sk89q.worldedit.internal.registry.InputParser; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.world.block.FuzzyBlockState; +import com.sk89q.worldedit.world.registry.LegacyMapper; +import lombok.NonNull; + +import java.util.Map; + +public final class BlockUtil { + private BlockUtil(){} + + private static final ParserContext PARSER_CONTEXT = new ParserContext(); + + private static final InputParser PARSER; + + static { + PARSER_CONTEXT.setRestricted(false); + PARSER_CONTEXT.setPreferringWildcard(false); + PARSER_CONTEXT.setTryLegacy(true); + PARSER = WorldEdit.getInstance().getBlockFactory().getParsers().get(0); + } + + public static final BlockState get(int id) { + return LegacyMapper.getInstance().getBlockFromLegacy(id); + } + + public static final BlockState get(int id, int data) { + return LegacyMapper.getInstance().getBlockFromLegacy(id, data); + } + + public static final BlockState get(String id) { + if (id.length() == 1 && id.charAt(0) == '*') { + return FuzzyBlockState.builder().type(BlockTypes.AIR).build(); + } + id = id.toLowerCase(); + BlockType type = BlockTypes.get(id); + if (type != null) { + return type.getDefaultState(); + } + if (Character.isDigit(id.charAt(0))) { + String[] split = id.split(":"); + if (MathMan.isInteger(split[0])) { + if (split.length == 2) { + if (MathMan.isInteger(split[1])) { + return get(Integer.parseInt(split[0]), Integer.parseInt(split[1])); + } + } else { + return get(Integer.parseInt(split[0])); + } + } + } + try { + BaseBlock block = PARSER.parseFromInput(id, PARSER_CONTEXT); + return block.toImmutableState(); + } catch (InputParseException e) { + return null; + } + } + + public static final BlockState[] parse(String commaDelimited) { + String[] split = commaDelimited.split(",(?![^\\(\\[]*[\\]\\)])"); + BlockState[] result = new BlockState[split.length]; + for (int i = 0; i < split.length; i++) { + result[i] = get(split[i]); + } + return result; + } + + public static BlockState deserialize(@NonNull final Map map) { + if (map.containsKey("material")) { + final Object object = map.get("material"); + return get(object.toString()); + } + return null; + } + +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/ItemUtil.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/ItemUtil.java new file mode 100644 index 000000000..2d906a73a --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/ItemUtil.java @@ -0,0 +1,40 @@ +package com.github.intellectualsites.plotsquared.plot.util.world; + +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.item.ItemType; +import com.sk89q.worldedit.world.item.ItemTypes; +import com.sk89q.worldedit.world.registry.LegacyMapper; + +import java.util.Locale; + +public final class ItemUtil { + private ItemUtil(){} + + public static ItemType get(String input) { + input = input.toLowerCase(Locale.ROOT); + if (Character.isDigit(input.charAt(0))) { + String[] split = input.split(":"); + if (MathMan.isInteger(split[0])) { + if (split.length == 2) { + if (MathMan.isInteger(split[1])) { + return LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(split[0]), Integer.parseInt(split[1])); + } + } else { + return LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(split[0])); + } + } + } + if (!input.split("\\[", 2)[0].contains(":")) input = "minecraft:" + input; + return ItemTypes.get(input); + } + + public static final ItemType[] parse(String commaDelimited) { + String[] split = commaDelimited.split(",(?![^\\(\\[]*[\\]\\)])"); + ItemType[] result = new ItemType[split.length]; + for (int i = 0; i < split.length; i++) { + result[i] = get(split[i]); + } + return result; + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/OperationUtil.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/OperationUtil.java new file mode 100644 index 000000000..2cb336f52 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/OperationUtil.java @@ -0,0 +1,113 @@ +package com.github.intellectualsites.plotsquared.plot.util.world; + +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.extension.platform.Capability; +import com.sk89q.worldedit.extension.platform.Platform; +import com.sk89q.worldedit.world.World; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.concurrent.Future; +import java.util.function.Consumer; + +public class OperationUtil { + private static final boolean ASYNC; + + static { + boolean hasFawe = true; + try { + Class.forName("com.boydti.fawe.Fawe"); + } catch (ClassNotFoundException ignore) { + hasFawe = false; + } + ASYNC = hasFawe; + } + + public Future withEditSession(@NotNull PlotPlayer plotPlayer, @NotNull Consumer consumer, @Nullable Consumer exceptionHandler) { + if (ASYNC) { + ListeningExecutorService exec = WorldEdit.getInstance().getExecutorService(); + return exec.submit( + () -> withEditSessionOnThread(plotPlayer, consumer, exceptionHandler)); + } else { + withEditSessionOnThread(plotPlayer, consumer, exceptionHandler); + } + return Futures.immediateFuture(true); + } + + private void withEditSessionOnThread(PlotPlayer plotPlayer, Consumer consumer, Consumer exceptionHandler) { + Actor actor = plotPlayer.toActor(); + World weWorld = getWorld(plotPlayer, actor); + LocalSession session = getSession(actor); + try (EditSession ess = createEditSession(weWorld, actor, session)) { + try { + consumer.accept(ess); + } finally { + ess.close(); + session.remember(ess); + } + } catch (Throwable e) { + if (exceptionHandler != null) { + exceptionHandler.accept(e); + } else { + e.printStackTrace(); + } + } + } + + private static World getWorld(String worldName) { + Platform platform = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING); + List worlds = platform.getWorlds(); + for (World current : worlds) { + if (current.getName().equals(worldName)) { + return current; + } + } + return null; + } + + private static World getWorld(PlotPlayer plotPlayer, Actor actor) { + World weWorld; + if (actor instanceof Player) { + weWorld = ((Player) actor).getWorld(); + } else { + @NotNull Location loc = plotPlayer.getLocation(); + String world = loc.getWorld(); + weWorld = getWorld(world); + } + return weWorld; + } + + private static EditSession createEditSession(PlotPlayer plotPlayer) { + Actor actor = plotPlayer.toActor(); + World weWorld = getWorld(plotPlayer, actor); + return createEditSession(weWorld, actor); + } + + private static LocalSession getSession(Actor actor) { + return WorldEdit.getInstance().getSessionManager().get(actor); + } + + private static EditSession createEditSession(World world, Actor actor) { + return createEditSession(world, actor, getSession(actor)); + } + + private static EditSession createEditSession(World world, Actor actor, LocalSession session) { + EditSession editSession; + Player player = actor.isPlayer() ? (Player) actor : null; + editSession = WorldEdit.getInstance().getEditSessionFactory() + .getEditSession(world, -1, null, player); + + editSession.setFastMode(!actor.isPlayer()); + editSession.setReorderMode(EditSession.ReorderMode.FAST); + return editSession; + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/PatternUtil.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/PatternUtil.java new file mode 100644 index 000000000..4d3107eb0 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/PatternUtil.java @@ -0,0 +1,70 @@ +package com.github.intellectualsites.plotsquared.plot.util.world; + +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.plot.config.Captions; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.extension.input.InputParseException; +import com.sk89q.worldedit.extension.input.ParserContext; +import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.function.pattern.BlockPattern; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.function.pattern.RandomPattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockType; + +public class PatternUtil { + public static BaseBlock apply(Pattern pattern, int x, int y, int z) { + if (pattern instanceof BlockPattern + || pattern instanceof RandomPattern + || pattern instanceof BlockState + || pattern instanceof BlockType + || pattern instanceof BaseBlock) { + return pattern.apply(BlockVector3.ZERO); + } + return pattern.apply(BlockVector3.at(x, y, z)); + } + + public static Pattern parse(PlotPlayer plotPlayer, String input) { + ParserContext context = new ParserContext(); + if (plotPlayer != null) { + Actor actor = plotPlayer.toActor(); + context.setActor(actor); + if (actor instanceof Player) { + context.setWorld(((Player) actor).getWorld()); + } + context.setSession(WorldEdit.getInstance().getSessionManager().get(actor)); + context.setRestricted(true); + } else { + context.setRestricted(false); + } + context.setPreferringWildcard(false); + context.setTryLegacy(true); + try { + Pattern pattern = + WorldEdit.getInstance().getPatternFactory().parseFromInput(input, context); + return pattern; + } catch (InputParseException e) { + throw new Command.CommandException(Captions.NOT_VALID_BLOCK, e.getMessage()); + } + } + + public static boolean isAir(Pattern pattern) { + if (pattern instanceof BlockPattern) { + return ((BlockPattern) pattern).getBlock().getBlockType().getMaterial().isAir(); + } + if (pattern instanceof BlockState) { + return ((BlockState) pattern).getBlockType().getMaterial().isAir(); + } + if (pattern instanceof BlockType) { + return ((BlockType) pattern).getMaterial().isAir(); + } + if (pattern instanceof BaseBlock) { + return ((BaseBlock) pattern).getBlockType().getMaterial().isAir(); + } + return false; + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/RegionUtil.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/RegionUtil.java new file mode 100644 index 000000000..271f76dac --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/util/world/RegionUtil.java @@ -0,0 +1,40 @@ +package com.github.intellectualsites.plotsquared.plot.util.world; + +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; + +public class RegionUtil { + public static CuboidRegion createRegion(int pos1x, int pos2x, int pos1z, int pos2z) { + return createRegion(pos1x, pos2x, 0, Plot.MAX_HEIGHT - 1, pos1z, pos2z); + } + + public static CuboidRegion createRegion(int pos1x, int pos2x, int pos1y, int pos2y, int pos1z, int pos2z) { + BlockVector3 pos1 = BlockVector3.at(pos1x, pos1y, pos1z); + BlockVector3 pos2 = BlockVector3.at(pos2x, pos2y, pos2z); + return new CuboidRegion(pos1, pos2); + } + + public static boolean contains(CuboidRegion region, int x, int z) { + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); + return x >= min.getX() && x <= max.getX() && z >= min.getZ() && z <= max.getZ(); + } + + public static boolean contains(CuboidRegion region, int x, int y, int z) { + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); + return x >= min.getX() && x <= max.getX() && z >= min.getZ() && z <= max.getZ() && y >= min.getY() && y <= max.getY(); + } + + // Because WE (not fawe) lack this for CuboidRegion + public static boolean intersects(CuboidRegion region, CuboidRegion other) { + BlockVector3 regionMin = region.getMinimumPoint(); + BlockVector3 regionMax = region.getMaximumPoint(); + + BlockVector3 otherMin = other.getMinimumPoint(); + BlockVector3 otherMax = other.getMaximumPoint(); + + return otherMin.getX() <= regionMax.getX() && otherMax.getX() >= regionMin.getX() && otherMin.getZ() <= regionMax.getZ() && otherMax.getZ() >= regionMin.getZ(); + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/uuid/UUIDWrapper.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/uuid/UUIDWrapper.java index 235b51a34..c2a0af542 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/uuid/UUIDWrapper.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/uuid/UUIDWrapper.java @@ -2,12 +2,13 @@ package com.github.intellectualsites.plotsquared.plot.uuid; import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import org.jetbrains.annotations.NotNull; import java.util.UUID; public abstract class UUIDWrapper { - public abstract UUID getUUID(PlotPlayer player); + @NotNull public abstract UUID getUUID(PlotPlayer player); public abstract UUID getUUID(OfflinePlotPlayer player); diff --git a/Core/src/main/resources/addplots.js b/Core/src/main/resources/addplots.js index b45f8d4ff..f3696d7ff 100644 --- a/Core/src/main/resources/addplots.js +++ b/Core/src/main/resources/addplots.js @@ -1,6 +1,6 @@ /* This will increase a player's allowed plots by the provided value -/plot debugexec runasync addperm +/plot debugexec runasync addplots.js */ var uuid = UUIDHandler.getUUID('%s0', null); if (uuid === null) { diff --git a/Core/src/main/resources/addsigns.js b/Core/src/main/resources/addsigns.js index a1d2b8714..52f85a9d3 100644 --- a/Core/src/main/resources/addsigns.js +++ b/Core/src/main/resources/addsigns.js @@ -4,7 +4,7 @@ This script will fix all signs in the world. var plots = PS.sortPlotsByTemp(PS.getPlots()); for (var i = 0; i < plots.size(); i++) { var plot = plots.get(i); - if (!plot.isMerged() || !plot.getMerged(0)) { + if (plot.isBasePlot()) { plot.setSign(); PS.class.static.log('&cSetting sign for: ' + plot); } diff --git a/Core/src/main/resources/automerge.js b/Core/src/main/resources/automerge.js index 220a24867..e2846f87e 100644 --- a/Core/src/main/resources/automerge.js +++ b/Core/src/main/resources/automerge.js @@ -1,32 +1,6 @@ /* -Need to script something quick with PlotSquared? -/plot debugexec runasync automerge.js - This is an example script that will auto merge all plots - -The following utility classes are usable: - - PlotSquared - - TaskManager - - TitleManager - - ConsolePlayer - - SchematicHandler - - ChunkManager - - BlockManager - - SetupUtils - - EventUtil - - UUIDHandler - - DBFunc - - HybridUtils - - IMP ( BukkitMain or SpongeMain) - - MainCommand - - MainUtil - - Settings - - StringMan - - MathMan - - C ( use C_ ) - - Permissions ( use Permissions_ ) - - For more information see: https://github.com/IntellectualSites/PlotSquared/wiki/Scripting +/plot debugexec runasync automerge.js */ var plots = PS.sortPlotsByTemp(PS.getPlots()); PS.class.static.log("Attempting to auto merge " + plots.size() + " plots"); diff --git a/Core/src/main/resources/bridge.template b/Core/src/main/resources/bridge.template index d5f9ccd93..0e21a3a17 100644 Binary files a/Core/src/main/resources/bridge.template and b/Core/src/main/resources/bridge.template differ diff --git a/Core/src/main/resources/de-DE.yml b/Core/src/main/resources/de-DE.yml index 8a52ce9a6..db18eda66 100644 --- a/Core/src/main/resources/de-DE.yml +++ b/Core/src/main/resources/de-DE.yml @@ -130,8 +130,7 @@ setup: setup backn$2 - $1/plot setup cancel setup_invalid_generator: '$2Ungültiger Generarator. Mögliche Optionen: %s' schematics: - schematic_missing_arg: '$2Du musst einen Wert angeben. Gültige Werte: $1test $2 - , $1save$2 , $1paste $2, $1exportall' + schematic_missing_arg: '$2Du musst einen Wert angeben. Gültige Werte: $1save$2, $1paste $2, $1exportall' schematic_invalid: '$2Diese Schematic ist ungültig: $2%s' schematic_valid: $2Diese Schematic ist gültig. schematic_paste_failed: $2Einfügen der Schematic fehlgeschlagen. diff --git a/Core/src/main/resources/es-ES.yml b/Core/src/main/resources/es-ES.yml index f4459649d..5ce8ced99 100644 --- a/Core/src/main/resources/es-ES.yml +++ b/Core/src/main/resources/es-ES.yml @@ -145,7 +145,7 @@ setup: setup_invalid_generator: '$2Generador inválido. Opciones posibles: %s' schematics: schematic_missing_arg: '$2Necesitas especificar un argumento. Valores posibles: - $1test $2 , $1save$2 , $1paste $2, $1exportall' + $1save$2, $1paste $2, $1exportall' schematic_invalid: '$2Este no es un schematic valido. Razon: $2%s' schematic_valid: $2Este es un schematic valido. schematic_paste_failed: $2Fallo al pegar el schematic. diff --git a/Core/src/main/resources/fixborders.js b/Core/src/main/resources/fixborders.js new file mode 100644 index 000000000..1becaeb60 --- /dev/null +++ b/Core/src/main/resources/fixborders.js @@ -0,0 +1,10 @@ +/* +Fixes border around plots +/plot debugexec runasync fixborder.js +*/ +var plots = PS.sortPlotsByTemp(PS.getPlots()); +PS.class.static.log("Attempting to fix border for " + plots.size() + " plots"); +for (var i = 0; i < plots.size(); i++) { + var plot = plots.get(i); + plot.setComponent("border", "%s0"); +} diff --git a/Core/src/main/resources/fr-FR.yml b/Core/src/main/resources/fr-FR.yml index 4867aff98..3d71ea897 100644 --- a/Core/src/main/resources/fr-FR.yml +++ b/Core/src/main/resources/fr-FR.yml @@ -148,7 +148,7 @@ setup: setup_invalid_generator: '$2Générateur invalide. Options possibles: %s' schematics: schematic_too_large: $2Ce plot est trop grand pour cette action! - schematic_missing_arg: '$2Vous devez spécifier un argument. Valeurs possibles: $1test $2 , $1save$2 , $1paste $2, $1exportall' + schematic_missing_arg: '$2Vous devez spécifier un argument. Valeurs possibles: $1save$2, $1paste $2, $1exportall' schematic_invalid: '$2Ce n''est pas un schématic valide. Raison: $2%s' schematic_valid: '$2C''est un schématic valide' schematic_paste_failed: $2Impossible de coller le schématic diff --git a/Core/src/main/resources/it-IT.yml b/Core/src/main/resources/it-IT.yml index 6419a2234..d43771148 100644 --- a/Core/src/main/resources/it-IT.yml +++ b/Core/src/main/resources/it-IT.yml @@ -148,7 +148,7 @@ setup: setup_invalid_generator: '$2Generatore non valido. Opzioni possibili: %s' schematics: schematic_too_large: $2Il lotto è troppo grande per questa azione! - schematic_missing_arg: '$2Devi specificare un argomento. Valori possibili: $1test $2 , $1save$2 , $1paste $2, $1exportall' + schematic_missing_arg: '$2Devi specificare un argomento. Valori possibili: $1save$2, $1paste $2, $1exportall' schematic_invalid: '$2Quella non è una schematica valida. Motivo: $2%s' schematic_valid: $2Quella è una schematica valida schematic_paste_failed: $2L'incollaggio della schematica è fallito diff --git a/Core/src/main/resources/ko-KR.yml b/Core/src/main/resources/ko-KR.yml index 07d6caca5..62548ead4 100644 --- a/Core/src/main/resources/ko-KR.yml +++ b/Core/src/main/resources/ko-KR.yml @@ -151,8 +151,7 @@ setup: cancel setup_invalid_generator: '$2올바르지 않은 생성기 입니다. 가능한 옵션: %s' schematics: - schematic_missing_arg: '$2당신은 인수를 지정해야 합니다. 가능한 값: $1test $2 , $1save$2 , - $1paste $2, $1exportall' + schematic_missing_arg: '$2당신은 인수를 지정해야 합니다. 가능한 값: $1save$2, $1paste $2, $1exportall' schematic_invalid: '$2이것은 올바르지 않은 schematic파일 입니다. 사유: $2%s' schematic_valid: $2이것은 올바른 schematic파일 입니다 schematic_paste_failed: $2schematic 적용에 실패하엿습니다 diff --git a/Core/src/main/resources/skyblock.template b/Core/src/main/resources/skyblock.template deleted file mode 100644 index 1801175de..000000000 Binary files a/Core/src/main/resources/skyblock.template and /dev/null differ diff --git a/Core/src/main/resources/town.template b/Core/src/main/resources/town.template index f655fbd0a..5210fc432 100644 Binary files a/Core/src/main/resources/town.template and b/Core/src/main/resources/town.template differ diff --git a/Core/src/main/resources/zh-CN.yml b/Core/src/main/resources/zh-CN.yml index 4afc3564a..b22959f1a 100644 --- a/Core/src/main/resources/zh-CN.yml +++ b/Core/src/main/resources/zh-CN.yml @@ -160,8 +160,7 @@ setup: setup_invalid_generator: '$2无效的生成器。可能选项:%s' schematics: schematic_too_large: $2此地皮过大无法进行此操作! - schematic_missing_arg: '$2阁下需要指定参数。可能的值:$1test - <名称>$2 , $1save$2 , $1paste $2, $1exportall' + schematic_missing_arg: '$2阁下需要指定参数。可能的值:$1save$2, $1paste $2, $1exportall' schematic_invalid: '$2布局无效。理由:$2%s' schematic_valid: $2布局无效 schematic_paste_failed: $2粘贴布局失败 diff --git a/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/FlagTest.java b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/FlagTest.java index c2b81a729..b925ce2a2 100644 --- a/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/FlagTest.java +++ b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/FlagTest.java @@ -5,23 +5,26 @@ import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.Plot; -import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.object.PlotId; import com.github.intellectualsites.plotsquared.plot.util.EventUtil; import com.github.intellectualsites.plotsquared.plot.util.EventUtilTest; +import com.github.intellectualsites.plotsquared.plot.util.world.BlockUtil; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.item.ItemType; +import com.sk89q.worldedit.world.item.ItemTypes; import org.junit.Before; import org.junit.Test; import java.util.Collection; -import java.util.HashSet; import java.util.Optional; +import java.util.Set; import java.util.UUID; import static org.junit.Assert.assertEquals; public class FlagTest { - private Object testBlock; + private ItemType testBlock; private Flag> use = Flags.USE; @Before public void setUp() throws Exception { @@ -29,23 +32,23 @@ public class FlagTest { DBFunc.dbManager = new AbstractDBTest(); } - @Test public void flagTest() throws Exception { - Plot plot = new Plot(null, new PlotId(0, 0)); - 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 - Optional flag = plot.getFlag(use); - if (flag.isPresent()) { - System.out.println(Flags.USE.valueToString(flag.get())); - testBlock = PlotBlock.get((short) 1, (byte) 0); - flag.get().add(testBlock); - } - flag.ifPresent(collection -> System.out.println(Flags.USE.valueToString(collection))); - Optional> flag2 = plot.getFlag(Flags.USE); - if (flag2.isPresent()) { - // assertThat(flag2.get(), (Matcher>) IsCollectionContaining.hasItem(testBlock)); - } - if (flag.isPresent() && flag2.isPresent()) { - assertEquals(flag.get(), flag2.get()); - } - } +// @Test public void flagTest() throws Exception { +// Plot plot = new Plot(null, new PlotId(0, 0)); +// 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 +// Optional flag = plot.getFlag(use); +// if (flag.isPresent()) { +// System.out.println(Flags.USE.valueToString(flag.get())); +// testBlock = ItemTypes.BONE_BLOCK; +// flag.get().add(testBlock); +// } +// flag.ifPresent(collection -> System.out.println(Flags.USE.valueToString(collection))); +// Optional> flag2 = plot.getFlag(Flags.USE); +// if (flag2.isPresent()) { +// // assertThat(flag2.get(), (Matcher>) IsCollectionContaining.hasItem(testBlock)); +// } +// if (flag.isPresent() && flag2.isPresent()) { +// assertEquals(flag.get(), flag2.get()); +// } +// } } diff --git a/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/PlotVersionTest.java b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/PlotVersionTest.java new file mode 100644 index 000000000..069c886da --- /dev/null +++ b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/PlotVersionTest.java @@ -0,0 +1,13 @@ +package com.github.intellectualsites.plotsquared.plot; + +import org.junit.Test; + +public class PlotVersionTest { + + @Test public void tryParse() { + //These are all random values chosen to form the test class. + PlotVersion version = new PlotVersion("4.340", "f06903f", "19.08.05"); + System.out.println(version.build); + + } +} diff --git a/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDBTest.java b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDBTest.java index 1ef5c92ec..a2cc07d1b 100644 --- a/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDBTest.java +++ b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/database/AbstractDBTest.java @@ -1,11 +1,19 @@ package com.github.intellectualsites.plotsquared.plot.database; import com.github.intellectualsites.plotsquared.plot.flag.Flag; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotCluster; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.comment.PlotComment; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; public class AbstractDBTest implements AbstractDB { @@ -149,7 +157,7 @@ public class AbstractDBTest implements AbstractDB { @Override public void setComment(Plot plot, PlotComment comment) { } - @Override public void getComments(@Nonnull Plot plot, String inbox, + @Override public void getComments(@NotNull Plot plot, String inbox, RunnableVal> whenDone) { } diff --git a/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/util/EventUtilTest.java b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/util/EventUtilTest.java index 6ae75a86d..fd2a8db15 100644 --- a/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/util/EventUtilTest.java +++ b/Core/src/test/java/com/github/intellectualsites/plotsquared/plot/util/EventUtilTest.java @@ -1,7 +1,12 @@ package com.github.intellectualsites.plotsquared.plot.util; import com.github.intellectualsites.plotsquared.plot.flag.Flag; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Rating; import java.util.List; import java.util.UUID; diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/NukkitMain.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/NukkitMain.java index 1cc8b8246..c84a73b67 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/NukkitMain.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/NukkitMain.java @@ -25,19 +25,15 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.C; import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.generator.*; -import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.object.chat.PlainChatManager; import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager; import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; -import com.github.intellectualsites.plotsquared.plot.util.*; import com.github.intellectualsites.plotsquared.plot.util.block.QueueProvider; import com.sk89q.worldedit.WorldEdit; import java.io.File; import java.lang.reflect.Field; -import java.util.*; public final class NukkitMain extends PluginBase implements Listener, IPlotMain { diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/generator/NukkitPlotGenerator.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/generator/NukkitPlotGenerator.java index ef274cf2b..d1712993b 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/generator/NukkitPlotGenerator.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/generator/NukkitPlotGenerator.java @@ -9,7 +9,6 @@ import com.github.intellectualsites.plotsquared.nukkit.util.block.NukkitWrappedC import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; -import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/listeners/PlayerEvents.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/listeners/PlayerEvents.java index c429ba0fd..456cb97b2 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/listeners/PlayerEvents.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/listeners/PlayerEvents.java @@ -28,11 +28,8 @@ import com.github.intellectualsites.plotsquared.plot.config.C; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.listener.PlotListener; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; import com.google.common.base.Optional; -import java.util.*; import java.util.Map.Entry; import java.util.regex.Pattern; diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/object/NukkitPlayer.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/object/NukkitPlayer.java index fa6bf2a59..f53213d69 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/object/NukkitPlayer.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/object/NukkitPlayer.java @@ -10,7 +10,6 @@ import com.github.intellectualsites.plotsquared.nukkit.util.NukkitUtil; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import com.github.intellectualsites.plotsquared.plot.util.*; import java.util.Collections; import java.util.UUID; diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/Metrics.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/Metrics.java index 1a41b836d..9b2ffb10c 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/Metrics.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/Metrics.java @@ -6,12 +6,10 @@ import cn.nukkit.utils.LogLevel; import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; -import java.io.*; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; -import java.util.*; import java.util.zip.GZIPOutputStream; public class Metrics { diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitChunkManager.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitChunkManager.java index 5caea648f..32da16dc3 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitChunkManager.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitChunkManager.java @@ -1,8 +1,7 @@ package com.github.intellectualsites.plotsquared.nukkit.util; - import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; +import com.github.intellectualsites.plotsquared.plot.object.BlockVector2; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; @@ -16,11 +15,11 @@ public class NukkitChunkManager extends ChunkManager { return new int[0]; } - @Override public boolean loadChunk(String world, ChunkLoc loc, boolean force) { + @Override public boolean loadChunk(String world, BlockVector2 loc, boolean force) { return true; } - @Override public void unloadChunk(String world, ChunkLoc loc, boolean save, boolean safe) { + @Override public void unloadChunk(String world, BlockVector2 loc, boolean save, boolean safe) { } diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitEventUtil.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitEventUtil.java index 532870c43..d59e45ebf 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitEventUtil.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitEventUtil.java @@ -7,7 +7,6 @@ import com.github.intellectualsites.plotsquared.nukkit.NukkitMain; import com.github.intellectualsites.plotsquared.nukkit.events.*; import com.github.intellectualsites.plotsquared.nukkit.object.NukkitPlayer; import com.github.intellectualsites.plotsquared.plot.flag.Flag; -import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.EventUtil; import javax.annotation.Nullable; diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitSchematicHandler.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitSchematicHandler.java index 7e8fcf362..4a301101a 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitSchematicHandler.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitSchematicHandler.java @@ -6,7 +6,7 @@ import cn.nukkit.level.format.generic.BaseFullChunk; import cn.nukkit.math.Vector3; import com.github.intellectualsites.plotsquared.jnbt.*; import com.github.intellectualsites.plotsquared.nukkit.NukkitMain; -import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; +import com.github.intellectualsites.plotsquared.plot.object.BlockVector2; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; @@ -16,7 +16,6 @@ import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; import java.io.IOException; -import java.util.*; /** * Schematic Handler. @@ -98,10 +97,10 @@ public class NukkitSchematicHandler extends SchematicHandler { final int sy = pos1.getY(); final int ey = pos2.getY(); // Generate list of chunks - final ArrayList chunks = new ArrayList<>(); + final ArrayList chunks = new ArrayList<>(); for (int x = bcx; x <= tcx; x++) { for (int z = bcz; z <= tcz; z++) { - chunks.add(new ChunkLoc(x, z)); + chunks.add(BlockVector2.at(x, z)); } } final Level worldObj = plugin.getServer().getLevelByName(world); @@ -113,7 +112,7 @@ public class NukkitSchematicHandler extends SchematicHandler { while (!chunks.isEmpty() && System.currentTimeMillis() - start < 20) { // save schematics - ChunkLoc chunk = chunks.remove(0); + BlockVector2 chunk = chunks.remove(0); BaseFullChunk bc = worldObj.getChunk(chunk.x, chunk.z); try { bc.load(false); diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitUtil.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitUtil.java index 4712d129d..ad085dca3 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitUtil.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/NukkitUtil.java @@ -20,7 +20,6 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.github.intellectualsites.plotsquared.plot.object.schematic.PlotItem; -import com.github.intellectualsites.plotsquared.plot.util.*; import java.lang.reflect.Field; import java.util.ArrayList; diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitHybridGen.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitHybridGen.java index ccca6dfe8..6af270e63 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitHybridGen.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitHybridGen.java @@ -1,5 +1,7 @@ package com.github.intellectualsites.plotsquared.nukkit.util.block; +import com.sk89q.worldedit.math.BlockVector2; + import cn.nukkit.level.Level; import com.github.intellectualsites.plotsquared.nukkit.NukkitMain; import com.github.intellectualsites.plotsquared.nukkit.generator.NukkitPlotGenerator; diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitLocalQueue.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitLocalQueue.java index 0a8012691..297df7c6b 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitLocalQueue.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitLocalQueue.java @@ -1,5 +1,7 @@ package com.github.intellectualsites.plotsquared.nukkit.util.block; +import com.sk89q.worldedit.math.BlockVector2; + import cn.nukkit.block.Block; import cn.nukkit.level.Level; import cn.nukkit.level.biome.EnumBiome; diff --git a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitWrappedChunk.java b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitWrappedChunk.java index 1dcb029f5..bc5182947 100644 --- a/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitWrappedChunk.java +++ b/Nukkit/src/main/java/com/github/intellectualsites/plotsquared/nukkit/util/block/NukkitWrappedChunk.java @@ -1,5 +1,7 @@ package com.github.intellectualsites.plotsquared.nukkit.util.block; +import com.sk89q.worldedit.math.BlockVector2; + import cn.nukkit.level.biome.Biome; import cn.nukkit.level.biome.EnumBiome; import cn.nukkit.level.format.generic.BaseFullChunk; diff --git a/Nukkit/src/main/resources/plugin.yml b/Nukkit/src/main/resources/plugin.yml index a25e26cf9..d17737c50 100644 --- a/Nukkit/src/main/resources/plugin.yml +++ b/Nukkit/src/main/resources/plugin.yml @@ -119,6 +119,7 @@ permissions: plots.toggle: true plots.toggle.titles: true plots.toggle.chat: true + plots.toggle.time: true plots.set.biome: true plots.set.home: true plots.set.alias: true diff --git a/README.md b/README.md index a00ec16ee..fc5aec641 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,10 @@ --- +PlotSquared is a land and world management plugin for Minecraft. +It includes several highly configurable world generators. +You can create plots of land in existing worlds using plot clusters, or you can have a full world of plots. + For the end user, PlotSquared is packed with a tonne of cool features. It allows you to merge plots, and build together with your friends. You can also change a lot of plot specific settings in the form of @@ -20,37 +24,18 @@ is to provide a lag-free and smooth experience. * [[Jenkins (Dev Builds)](https://ci.athion.net/job/PlotSquared-Breaking/)] [[Jenkins (Releases)](https://ci.athion.net/job/PlotSquared-Releases/)] * [Spigot Page](https://www.spigotmc.org/resources/plotsquared.1177/) * [Discord](https://discord.gg/ngZCzbU) -* [Wiki](https://github.com/intellectualcrafters/plotsquared/wiki) +* [Wiki](https://github.com/IntellectualSites/PlotSquared/wiki) ### Developer Resources * [[JavaDoc](https://ci.athion.net/job/PlotSquared-Breaking/javadoc/)] * [[Maven Repo (CI)](http://ci.athion.net/job/PlotSquared-Breaking/ws/mvn/)] -* [API Documentation](https://github.com/IntellectualSites/PlotSquared/wiki/Developer-documentation-(WIP)) +* [API Documentation](https://github.com/IntellectualSites/PlotSquared/wiki/Developer-Documentation) # Building Gradle is the **recommended** way to build the project. Use `./gradlew build` in the main project directory to build the project. Gradle is required if you intend to build or develop the Sponge module. -If you prefer to use maven, a `pom.xml` file is provided for working with the Bukkit part of the plugin. # Contributing -If you feel like you can improve the plugin any way, then you are -more than welcome to contribute to PlotSquared. It would be highly -appreciated if you made sure to test your code before committing it, -as it will save us a lot of time and effort. - -### Code Style - -If you are planning to commit any changes to the project, -it would be highly appreciated if you were to follow the -project code style conventions. To make this easier we have -provided settings that can be imported into your IDE. - -**Eclipse:** -`Window > Preferences > Java > Code Style > Formatter` -Press `Import` and select `...path/to/project/code_style.xml` - -**IntelliJ:** -`File > Settings > Editor > Code Style`. Next to "Scheme" there is a cog wheel, press that and then -`Import Scheme > IntelliJ IDEA Code Style XML` and then select `..path/to/project/code_style.xml` +See [here](https://github.com/IntellectualSites/PlotSquared/blob/breaking/CONTRIBUTING.md) ## Suggestions Suggestions are welcome! We have a separate issue tracker for suggestions, that can be found in [this](https://github.com/IntellectualSites/PlotSquaredSuggestions) repository. @@ -65,3 +50,22 @@ Suggestions are welcome! We have a separate issue tracker for suggestions, that * [PlotSquaredMG](https://www.spigotmc.org/resources/plotsquaredmg.8025/) * [BasicPlots](https://www.spigotmc.org/resources/basicplots.6901/) * [HoloPlots](https://www.spigotmc.org/resources/holoplots.4880/) + +# Sponsors +


+IntelliJ IDEA is a Java integrated development environment (IDE) for developing computer software. It is developed by JetBrains and our top used development tool. Every aspect of IntelliJ IDEA is specifically designed to maximize developer productivity. +Together, the powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience.

+


+YourKit supports open source projects with innovative and intelligent tools for monitoring and profiling Java and .NET applications. +YourKit is the creator of YourKit Java Profiler, YourKit .NET Profiler, and YourKit YouMonitor. We are using YourKit to profile the performance of our plugins.

+


+Athion is the result of the merging of two of the oldest creative servers around in the community – Mithrintia and Pwego-Insomnia – fusing together to perfect a creative experience like no other to develop and harness your skills.

+


+Welcome to the Builders's Refuge. The refuge is a passion project we started to accommodate professional Minecraft builders who are looking for a personal or commercial space to build and create art. We offer premium services at no charge along with a network of other builders and resources to help you become successful. +

+


+The AJGaming Network is a modded and vanilla network. Either delve into magic on our magic servers, fight your enemies on our hardcore PvP modpacks or have a good time on our vanilla servers. The mods for our modpacks are handpicked by suggestions from our community making sure we can crate packs you love to play. +

+


+Pixel² is an indie games studio started out of Northern Ireland in 2017 and growing worldwide. We are partnered with Microsoft to provide you with thrilling adventure maps, stunning texture packs, and stylish skins, which can all be found on the official Minecraft Marketplace. +

diff --git a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/SpongeMain.java b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/SpongeMain.java index 0877e42fb..07e535040 100644 --- a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/SpongeMain.java +++ b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/SpongeMain.java @@ -18,7 +18,6 @@ import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManag import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; import com.github.intellectualsites.plotsquared.plot.object.worlds.SingleWorldGenerator; -import com.github.intellectualsites.plotsquared.plot.util.*; import com.github.intellectualsites.plotsquared.plot.util.block.QueueProvider; import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.github.intellectualsites.plotsquared.sponge.generator.SpongePlotGenerator; diff --git a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/listener/MainListener.java b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/listener/MainListener.java index 01dcfcd16..09f500103 100644 --- a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/listener/MainListener.java +++ b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/listener/MainListener.java @@ -4,8 +4,6 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.config.C; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.listener.PlotListener; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; import com.github.intellectualsites.plotsquared.sponge.SpongeMain; import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer; import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil; @@ -35,7 +33,6 @@ import org.spongepowered.api.event.world.ExplosionEvent.Detonate; import org.spongepowered.api.text.Text; import org.spongepowered.api.world.World; -import java.util.*; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Predicate; diff --git a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeChunkManager.java b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeChunkManager.java index 5de2ae309..f5a26c306 100644 --- a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeChunkManager.java +++ b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeChunkManager.java @@ -1,6 +1,6 @@ package com.github.intellectualsites.plotsquared.sponge.util; -import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; +import com.github.intellectualsites.plotsquared.plot.object.BlockVector2; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; @@ -53,12 +53,12 @@ public class SpongeChunkManager extends ChunkManager { return count; } - @Override public boolean loadChunk(String world, ChunkLoc loc, boolean force) { + @Override public boolean loadChunk(String world, BlockVector2 loc, boolean force) { World worldObj = SpongeUtil.getWorld(world); return worldObj.loadChunk(loc.x << 4, 0, loc.z << 4, force).isPresent(); } - @Override public Set getChunkChunks(String world) { + @Override public Set getChunkChunks(String world) { // TODO save world; return super.getChunkChunks(world); } @@ -100,7 +100,7 @@ public class SpongeChunkManager extends ChunkManager { throw new UnsupportedOperationException("NOT IMPLEMENTED YET"); } - @Override public void unloadChunk(String world, ChunkLoc loc, boolean save, boolean safe) { + @Override public void unloadChunk(String world, BlockVector2 loc, boolean save, boolean safe) { World worldObj = SpongeUtil.getWorld(world); Optional chunk = worldObj.getChunk(loc.x << 4, 0, loc.z << 4); if (chunk.isPresent()) { diff --git a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeCommand.java b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeCommand.java index 2c6b9b936..21ab4b19e 100644 --- a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeCommand.java +++ b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeCommand.java @@ -16,8 +16,6 @@ import org.spongepowered.api.text.Text; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; -import java.util.*; - public class SpongeCommand implements CommandCallable { @Override public CommandResult process(CommandSource source, String arguments) diff --git a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeEventUtil.java b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeEventUtil.java index d4c16e73d..a69f4c431 100644 --- a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeEventUtil.java +++ b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeEventUtil.java @@ -1,7 +1,6 @@ package com.github.intellectualsites.plotsquared.sponge.util; import com.github.intellectualsites.plotsquared.plot.flag.Flag; -import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.EventUtil; import com.github.intellectualsites.plotsquared.sponge.SpongeMain; import com.github.intellectualsites.plotsquared.sponge.events.*; diff --git a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeMetrics.java b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeMetrics.java index 4ea1bc19d..4a221d4e9 100644 --- a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeMetrics.java +++ b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeMetrics.java @@ -1,5 +1,24 @@ package com.github.intellectualsites.plotsquared.sponge.util; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.google.inject.Inject; +import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import ninja.leaping.configurate.hocon.HoconConfigurationLoader; +import ninja.leaping.configurate.loader.ConfigurationLoader; +import org.spongepowered.api.Game; +import org.spongepowered.api.plugin.PluginContainer; +import org.spongepowered.api.scheduler.Task; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.zip.GZIPOutputStream; + /* * Copyright 2011-2013 Tyler Blair. All rights reserved. * @@ -28,24 +47,6 @@ package com.github.intellectualsites.plotsquared.sponge.util; * either expressed or implied, of anybody else. */ -import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.google.inject.Inject; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.hocon.HoconConfigurationLoader; -import ninja.leaping.configurate.loader.ConfigurationLoader; -import org.spongepowered.api.Game; -import org.spongepowered.api.plugin.PluginContainer; -import org.spongepowered.api.scheduler.Task; - -import java.io.*; -import java.net.Proxy; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.zip.GZIPOutputStream; - public class SpongeMetrics { /** diff --git a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeSchematicHandler.java b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeSchematicHandler.java index 648a3ebd2..ecfe61fe4 100644 --- a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeSchematicHandler.java +++ b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeSchematicHandler.java @@ -1,17 +1,16 @@ package com.github.intellectualsites.plotsquared.sponge.util; import com.github.intellectualsites.plotsquared.jnbt.*; -import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; +import com.sk89q.worldedit.math.BlockVector2; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.item.inventory.Carrier; import org.spongepowered.api.item.inventory.type.CarriedInventory; import org.spongepowered.api.world.World; -import java.util.*; import java.util.Map.Entry; public class SpongeSchematicHandler extends SchematicHandler { @@ -92,10 +91,10 @@ public class SpongeSchematicHandler extends SchematicHandler { int sy = pos1.getY(); int ey = pos2.getY(); // Generate list of chunks - ArrayList chunks = new ArrayList<>(); + ArrayList chunks = new ArrayList<>(); for (int x = bcx; x <= tcx; x++) { for (int z = bcz; z <= tcz; z++) { - chunks.add(new ChunkLoc(x, z)); + chunks.add(BlockVector2.at(x, z)); } } World worldObj = SpongeUtil.getWorld(world); @@ -106,7 +105,7 @@ public class SpongeSchematicHandler extends SchematicHandler { while (!chunks.isEmpty() && System.currentTimeMillis() - start < 20) { // save schematics - ChunkLoc chunk = chunks.remove(0); + BlockVector2 chunk = chunks.remove(0); int X = chunk.x; int Z = chunk.z; if (!worldObj.getChunk(X, 0, Z).isPresent() && !worldObj diff --git a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeSetupUtils.java b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeSetupUtils.java index 3caf627bc..7a8cfc1a6 100644 --- a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeSetupUtils.java +++ b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeSetupUtils.java @@ -19,7 +19,6 @@ import org.spongepowered.api.world.gen.WorldGeneratorModifier; import org.spongepowered.api.world.storage.WorldProperties; import java.io.IOException; -import java.util.*; import java.util.Map.Entry; public class SpongeSetupUtils extends SetupUtils { diff --git a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeUtil.java b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeUtil.java index e1307f76d..404006678 100644 --- a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeUtil.java +++ b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/SpongeUtil.java @@ -9,7 +9,6 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.github.intellectualsites.plotsquared.plot.object.schematic.PlotItem; -import com.github.intellectualsites.plotsquared.plot.util.*; import com.github.intellectualsites.plotsquared.sponge.SpongeMain; import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer; import net.minecraft.block.Block; @@ -39,7 +38,6 @@ import org.spongepowered.api.world.extent.Extent; import java.io.IOException; import java.lang.reflect.Field; -import java.util.*; public class SpongeUtil extends WorldUtil { diff --git a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/block/GenChunk.java b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/block/GenChunk.java index f88e8fa0d..698befdf8 100644 --- a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/block/GenChunk.java +++ b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/block/GenChunk.java @@ -1,5 +1,7 @@ package com.github.intellectualsites.plotsquared.sponge.util.block; +import com.sk89q.worldedit.math.BlockVector2; + import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; diff --git a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/block/SpongeLocalQueue.java b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/block/SpongeLocalQueue.java index 00e294138..51efceeb2 100644 --- a/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/block/SpongeLocalQueue.java +++ b/Sponge/src/main/java/com/github/intellectualsites/plotsquared/sponge/util/block/SpongeLocalQueue.java @@ -1,5 +1,7 @@ package com.github.intellectualsites.plotsquared.sponge.util.block; +import com.sk89q.worldedit.math.BlockVector2; + import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.object.PseudoRandom; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; diff --git a/build.gradle b/build.gradle index dddfa3ffd..28988c1e5 100644 --- a/build.gradle +++ b/build.gradle @@ -7,35 +7,36 @@ buildscript { jcenter() } dependencies { - classpath 'com.github.jengelman.gradle.plugins:shadow:5.0.0' + classpath("com.github.jengelman.gradle.plugins:shadow:5.0.0") } configurations.all { resolutionStrategy { - force 'org.ow2.asm:asm:7.1' + force("org.ow2.asm:asm:7.2") + force("org.jetbrains:annotations:18.0.0") } } } plugins { - id 'maven-publish' - id "org.ajoberstar.grgit" version "3.1.1" + id "maven-publish" + id "org.ajoberstar.grgit" version "4.0.0" } -group = 'com.github.intellectualsites.plotsquared' +group = "com.github.intellectualsites.plotsquared" def rootVersion = "4" def revision = "" def buildNumber = "" def date = "" ext { - git = Grgit.open(dir: '.git') + git = Grgit.open(dir: new File(rootDir.toString() + "/.git")) date = git.head().getDate().format("yy.MM.dd") revision = "-${git.head().abbreviatedId}" - parents = git.head().parentIds; - if (project.hasProperty('buildnumber')) { + parents = git.head().parentIds + if (project.hasProperty("buildnumber")) { buildNumber = "$buildnumber" } else { - index = -2042; // Offset to match CI + index = -2042 // Offset to match CI for (; parents != null && !parents.isEmpty(); index++) { parents = git.getResolve().toCommit(parents.get(0)).getParentIds() } @@ -43,57 +44,87 @@ ext { } } -// version = String.format("%s.%s%s%s", rootVersion, date, revision, buildNumber) version = String.format("%s.%s", rootVersion, buildNumber) description = rootProject.name -subprojects { - apply plugin: 'java' - apply plugin: 'maven' - apply plugin: 'eclipse' - apply plugin: 'idea' - apply plugin: 'com.github.johnrengelman.shadow' +allprojects { + gradle.projectsEvaluated { + tasks.withType(JavaCompile) { + options.compilerArgs << "-Xmaxerrs" << "1000" + } + } +} - group = 'com.github.intellectualsites.plotsquared' +subprojects { + apply(plugin: "java") + apply(plugin: "maven") + apply(plugin: "eclipse") + apply(plugin: "idea") + apply(plugin: "com.github.johnrengelman.shadow") + + group = "com.github.intellectualsites.plotsquared" clean.doFirst { - delete "../target" + delete("../target") } dependencies { - implementation('com.sk89q.worldedit:worldedit-core:7.0.0-SNAPSHOT') { - exclude(module: 'bukkit-classloader-check') - exclude(module: 'mockito-core') - exclude(module: 'dummypermscompat') + implementation("com.sk89q.worldedit:worldedit-core:7.0.0") { + exclude(module: "bukkit-classloader-check") + exclude(module: "mockito-core") + exclude(module: "dummypermscompat") + } + implementation("net.kyori:text-api:3.0.2") + implementation("net.kyori:text-serializer-gson:3.0.2") + implementation("net.kyori:text-serializer-legacy:3.0.2") + implementation("net.kyori:text-serializer-plain:3.0.2") + implementation("com.google.guava:guava:21.0") { + because("Minecraft uses Guava 21 as of 1.13") + } + compileOnly("org.jetbrains:annotations:17.0.0") + compileClasspath("org.projectlombok:lombok:1.18.10") + testCompileOnly("org.projectlombok:lombok:1.18.8") + annotationProcessor("org.projectlombok:lombok:1.18.8") + testAnnotationProcessor("org.projectlombok:lombok:1.18.8") + testImplementation("junit:junit:4.12") + } + + configurations.all { + resolutionStrategy { + force("junit:junit:4.12") + force("com.google.guava:guava:21.0") + force("org.jetbrains:annotations:18.0.0") + force("com.google.code.findbugs:jsr305:3.0.2") } - //Minecraft uses Guava 21 as of 1.13. - compile 'com.google.guava:guava:21.0' - compileOnly 'org.jetbrains:annotations:17.0.0' - compile("org.projectlombok:lombok:1.18.6") - compileOnly("org.projectlombok:lombok:1.18.6") - testCompileOnly("org.projectlombok:lombok:1.18.6") - annotationProcessor("org.projectlombok:lombok:1.18.6") - testAnnotationProcessor("org.projectlombok:lombok:1.18.6") - testImplementation "junit:junit:4.12" } repositories { mavenCentral() - maven { url "http://maven.sk89q.com/repo/" } - maven { url "http://repo.maven.apache.org/maven2" } - maven { url 'https://jitpack.io' } + maven { url = "http://maven.sk89q.com/repo/" } + maven { url = "http://repo.maven.apache.org/maven2" } + maven { url = "https://jitpack.io" } + } + + shadowJar { + dependencies { + include(dependency("net.kyori:text-api:3.0.2")) + } + relocate("io.papermc.lib", "com.github.intellectualsites.plotsquared.bukkit.paperlib") + // relocate('org.mcstats', 'com.plotsquared.stats') + archiveFileName = "${parent.name}-${project.name}-${parent.version}.jar" + destinationDirectory = file "../target" } } -task aggregatedJavadocs(type: Javadoc, description: 'Generate javadocs from all child projects as if it was a single project', group: 'Documentation') { +task aggregatedJavadocs(type: Javadoc, description: "Generate javadocs from all child projects as if it was a single project", group: "Documentation") { destinationDir = file("./docs/javadoc") title = "$project.name $version API" options.author true - options.links 'http://docs.spring.io/spring/docs/4.3.x/javadoc-api/', 'http://docs.oracle.com/javase/8/docs/api/', 'http://docs.spring.io/spring-ws/docs/2.3.0.RELEASE/api/', 'http://docs.spring.io/spring-security/site/docs/4.0.4.RELEASE/apidocs/' - options.addStringOption('Xdoclint:none', '-quiet') + options.links "http://docs.spring.io/spring/docs/4.3.x/javadoc-api/", "http://docs.oracle.com/javase/8/docs/api/", "http://docs.spring.io/spring-ws/docs/2.3.0.RELEASE/api/", "http://docs.spring.io/spring-security/site/docs/4.0.4.RELEASE/apidocs/" + options.addStringOption("Xdoclint:none", "-quiet") - delete "./docs" + delete("./docs") subprojects.each { proj -> proj.tasks.withType(Javadoc).each { javadocTask -> diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 457aad0d9..5c2d1cf01 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index db5043d4e..94920145f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Fri Dec 21 16:11:33 EST 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index cccdd3d51..b0d6d0ab5 100755 --- a/gradlew +++ b/gradlew @@ -1,5 +1,21 @@ #!/usr/bin/env sh +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + ############################################################################## ## ## Gradle start up script for UN*X @@ -28,7 +44,7 @@ APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" diff --git a/gradlew.bat b/gradlew.bat index f9553162f..9991c5032 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,3 +1,19 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem http://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @@ -14,7 +30,7 @@ set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 498ef295f..000000000 --- a/pom.xml +++ /dev/null @@ -1,103 +0,0 @@ - - - 4.0.0 - com.intellectualcrafters - - UTF-8 - - PlotSquared - 3.5.1-SNAPSHOT - PlotSquared - jar - - PlotSquared-Bukkit-${project.version} - Bukkit/src - - - true - - **/*.* - - Bukkit/src/main/resources/ - - - true - - **/*.* - - Core/src/main/resources/ - - - - - maven-compiler-plugin - 2.3.2 - - - **/Sponge/src/main/**/*.* - - 1.7 - 1.7 - - - - org.codehaus.mojo - build-helper-maven-plugin - - - generate-sources - - add-source - - - - Core/src - - - - - - - - - - spigot-repo - http://hub.spigotmc.org/nexus/content/groups/public/ - - - sk80q - http://maven.sk89q.com/artifactory/repo/ - - - vault - http://nexus.hc.to/content/repositories/pub_releases/ - - - empcraft-repo - http://empcraft.com/maven2 - - - - - org.spigotmc - spigot-api - 1.12-R0.1-SNAPSHOT - provided - - - com.sk89q - worldedit - 6.0.0-SNAPSHOT - jar - compile - - - net.milkbowl.vault - VaultAPI - 1.5 - provided - - -