Merge pull request #1 from IntellectualSites/v4

Merge from upstream
This commit is contained in:
zombachu 2019-12-31 15:24:42 -10:00 committed by GitHub
commit a17588199f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
304 changed files with 6832 additions and 8959 deletions

View File

@ -1,2 +0,0 @@
### Bugs
Please provide a `/plot debugpaste` if you are reporting a bug.

View File

@ -3,15 +3,13 @@ __*NOTICE: Bukkit/Spigot versions 1.7.10 to 1.12.2 are considered legacy and wil
<!--- In order to create a valid issue report you have to follow this template. -->
<!--- Incomplete reports might be marked as invalid. -->
<!-- Feature requests and enhancements may be suggested at https://github.com/IntellectualSites/PlotSquaredSuggestions. -->
**[REQUIRED] PlotSquared Version Number:** <!--- Enter /plot version in game or in your console and copy the output here -->
**Debug paste link:**
<!--- Enter /plot debugpaste in game or in your console and copy the output here -->
**[REQUIRED] Spigot/Paper Version Number:**
**[REQUIRED] Minecraft Version Number:**
**Links to worlds.yml file and settings.yml file:**
<!--- Copy and paste the information to the service of your choosing and provide the link here. -->
**[REQUIRED] Description of the problem:**
**Any relevant console output or screenshots:**

View File

@ -0,0 +1,98 @@
---
name: Bug/Issue report for PlotSquared
about: Bug / Issue report about this plugin
title: ''
labels: "[?] Testing Required"
assignees: ''
---
<!--- READ THIS BEFORE SUBMITTING AN ISSUE REPORT!!! -->
<!--- ##### DO NOT REMOVE THIS TEMPLATE! YOUR ISSUE *WILL* FIT IN IT! ##### -->
<!--- # NOTICE:
```diff
! PlotSquared for Minecraft Java Edition versions between 1.7 through to 1.12.2 are considered
! legacy, and will receive limited to no support. Please consider upgrading to 1.13+ for
! future support. Plugins exist for 1.13+ which bring back behaviors found in 1.8.8
! All versions of PlotSquared for Sponge and Nukkit(X) will receive limited to no support
! due to lack of developer interest and time. Additionally, NukkitX has not had feature
! updates since the Better Together, which prevents some PlotSquared features from ever
! functioning. Contributions are always welcome however!
```
**Feature requests & Suggestions are to be submitted at the [PlotSquared Suggestions tracker](https://github.com/IntellectualSites/PlotSquaredSuggestions)**
**Code contributions are to be done through [PRs](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request), tagging the specific issue ticket(s) if applicable.**
**[DISCORD INVITE LINK](https://discord.gg/cSMxtGn)** and please, for the love of the little sanity we have left, use the correct channels!
-->
# Bug Report Template:
<!--- Incomplete reports will most likely be marked as invalid, and closed, with few exceptions.-->
## Required Information section:
> ALL FIELDS IN THIS SECTION ARE REQUIRED, and must contain appropriate information
### Server config info (/plot debugpaste / file paste links):
<!--- Issue /plot debugpaste in game or in your console and copy the supplied URL here -->
<!--- If you cannot perform the above, we require logs/latest.log; settings.yml; worlds.yml and possibly PlotSquared.use_THIS.yml -->
<!--- If you are unwilling to supply the information we need, we reserve the right to not assist you. Redact IP addresses if you need to. -->
### Server type:
**Select one**
<!-- Select the type you are reporting the issue for (put an "X" between of brackets): -->
- [] 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**
<!-- Select the type you are reporting the issue for (put an "X" between of brackets):
The maintained versions are 1.14.4 and 1.15.x -->
- [] 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:
<!--- Run /version in-game or in console & paste the full output here: -->
```
Paste the output here, between the tick marks, replacing this text
```
### WorldEdit/FAWE versions:
<!--- Specify which plugin you are using, and add its version -->
- [] FAWE *version*:
- [] WorldEdit *version*:
### Description of the problem:
<!--- Be as specific as possible. Don't lie, redact information, or use false names/situations. -->
<!--- Who, What, When, Where, Why, How, Expected behavior, Resultant behavior, etc -->
### How to replicate:
<!--- If you can reproduce the issue please tell us as detailed as possible step by step how to do that -->
## 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:
<!--- Optional but recommended - issue "/plugins" in-game or in console and copy/paste the list -->
### Relevant console output, log lines, and/or screenshots:
<!--- Please use in-line code insertion
```
like this
```
for short (20 lines or less) text blobs, or a paste service for large blobs -->
### Additional relevant comments/remarks:
<!--- Use this space to give us any additional information which may be relevant to this issue, such as: if you are using a Minecraft hosting provider; unusual installation environment; etc -->
# AFFIRMATION OF COMPLETION:
<!-- Make sure you have completed the following steps (put an "X" between of brackets): -->
- [] 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.

5
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -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

17
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,17 @@
## Overview
<!-- Please describe which issue this Pull Request targets
If there is no issue, please create one so we can look into it before approving your PR.
You can do so here: https://github.com/IntellectualSites/PlotSquared/issues/new/choose
-->
**Fixes #{issue number}**
## Description
## Checklist
<!-- Make sure you have completed the following steps (put an "X" between of brackets): -->
- [] 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)

View File

@ -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!

24
.github/workflows/gradle.yml vendored Normal file
View File

@ -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

View File

@ -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)

View File

@ -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<Material> 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<String> getPluginIds() {
final List<String> names = new ArrayList<>();
@Override public List<Map.Entry<Map.Entry<String, String>, Boolean>> getPluginIds() {
List<Map.Entry<Map.Entry<String, String>, Boolean>> names = new ArrayList<>();
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
names.add(plugin.getName() + ';' + plugin.getDescription().getVersion() + ':' + plugin
.isEnabled());
Map.Entry<String, String> id = new AbstractMap.SimpleEntry<>(plugin.getName(), plugin.getDescription().getVersion());
names.add(new AbstractMap.SimpleEntry<>(id, plugin.isEnabled()));
}
return names;
}
@Override public BlockRegistry<Material> 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);
}
}

View File

@ -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;
/**

View File

@ -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);

View File

@ -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<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames =
_loadedMethods.get(clazz);
if (!loadedMethodNames.containsKey(name)) {
loadedMethodNames.put(name, new HashMap<>());
}
loadedMethodNames.computeIfAbsent(name, k -> new HashMap<>());
Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name);
ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<>(args);

View File

@ -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 <lower|offline|online>",
@ -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");

View File

@ -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();

View File

@ -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<PlotId> plots) {
public PlotAutoMergeEvent(@NotNull final World world, @NotNull final Plot plot,
@NotNull final List<PlotId> plots) {
super(plot);
this.world = world;
this.plots = plots;

View File

@ -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;

View File

@ -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<PlotId> plots) {
public PlotUnlinkEvent(@NotNull final World world, @NotNull final PlotArea area,
@NotNull final List<PlotId> plots) {
this.plots = plots;
this.world = world;
this.area = area;

View File

@ -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);
}
}

View File

@ -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<BlockPopulator> getDefaultPopulators(@NotNull World world) {
@Override
@NotNull
public List<BlockPopulator> 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();

View File

@ -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));
}
}

View File

@ -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);
}

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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);
}

View File

@ -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<ItemType> supplyItem(Block block) {
return new Supplier<ItemType>() {
@Override public ItemType get() {
return BukkitAdapter.asItemType(block.getType());
}
};
}
public static Supplier<ItemType> 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();
}
}

View File

@ -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;
}
}

View File

@ -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();
}

View File

@ -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 {
* <p>Please do not use this method. Instead use
* BukkitUtil.getPlayer(Player), as it caches player objects.</p>
*
* @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<PermissionAttachmentInfo> effective = player.getEffectivePermissions();
final Set<PermissionAttachmentInfo> 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.<Long>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);
}
}

View File

@ -1,6 +1,5 @@
package com.github.intellectualsites.plotsquared.bukkit.object.entity;
class EntityBaseStats {
EntityWrapper passenger;

View File

@ -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:

View File

@ -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":

View File

@ -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);
}
}

View File

@ -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<Material> {
public BukkitBlockRegistry(final Material... preInitializedItems) {
super(Material.class, preInitializedItems);
}
@Override public PlotBlock getPlotBlock(@NonNull final Material item) {
return PlotBlock.get(item.name());
}
}

View File

@ -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<ChunkLoc> getChunkChunks(String world) {
Set<ChunkLoc> chunks = super.getChunkChunks(world);
for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) {
ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5);
@Override public Set<BlockVector2> getChunkChunks(String world) {
Set<BlockVector2> 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<PlotLoc, BaseBlock[]> 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<ChunkLoc> chunks = new ArrayList<>();
final List<BlockVector2> 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<ScopedLocalBlockQueue>() {
@ -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;

View File

@ -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<com.github.intellectualsites.plotsquared.commands.Command> objects = MainCommand.getInstance().tab(player, args, s.endsWith(" "));
if (objects == null) {
return null;
}
List<String> 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;

View File

@ -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<PlotId> plots) {
return callEvent(new PlotAutoMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, plots));
}
@Override public boolean callUnlink(PlotArea area, List<PlotId> 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<PlotId> plots) {
return callEvent(
new PlotAutoMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, plots));
}
@Override public boolean callUnlink(PlotArea area, List<PlotId> 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();
}
}

View File

@ -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<PlotAnalysis> 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<int[]>() {
@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<PlotBlock> 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<int[]>() {
@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);
});
}
}

View File

@ -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<String> 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<String> 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<String> 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<String> 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;
}
}

View File

@ -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:
* <p>
* Minecraft ID mappings Copyright (C) 2017 Max Lee (https://github.com/Phoenix616)
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License along with this program. If
* not, see <http://www.gnu.org/licenses/>.
*/
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<IdDataPair, PlotBlock> LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK =
new HashMap<>();
private static final Map<String, PlotBlock> NEW_STRING_TO_LEGACY_PLOT_BLOCK = new HashMap<>();
private static final Map<String, PlotBlock> 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<LegacyBlock> 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<LegacyBlock> 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<PlotBlock> getPlotBlocks() {
return Arrays.stream(BLOCKS).map(block -> PlotBlock.get(block.getNewName()))
.collect(Collectors.toList());
}
public StringComparison<PlotBlock>.ComparisonResult getClosestsMatch(
@NonNull final String string) {
final StringComparison<PlotBlock> 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;
}
}
}

View File

@ -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<RegionWrapper> regions,
@Override public void getCompoundTag(final String world, final Set<CuboidRegion> regions,
final RunnableVal<CompoundTag> whenDone) {
// async
TaskManager.runTaskAsync(new Runnable() {
@ -61,7 +73,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
List<CompoundTag> tileEntities = new ArrayList<>();
ByteArrayOutputStream buffer = new ByteArrayOutputStream(width * height * length);
// Queue
final ArrayDeque<RegionWrapper> queue = new ArrayDeque<>(regions);
final ArrayDeque<CuboidRegion> 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();

View File

@ -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()) {

View File

@ -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) {

View File

@ -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<Entity> getEntities(@NonNull final String worldName) {
World world = getWorld(worldName);
return world != null ? world.getEntities() : new ArrayList<Entity>();
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<String[]>() {
@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<PlotBlock>.ComparisonResult getClosestBlock(String name) {
final PlotBlock plotBlock = BukkitUtil.getBukkitLegacyMappings().fromAny(name);
if (plotBlock != null) {
return new StringComparison<PlotBlock>().new ComparisonResult(1, plotBlock);
}
return BukkitUtil.getBukkitLegacyMappings().getClosestsMatch(name);
public StringComparison<BlockState>.ComparisonResult getClosestBlock(String name) {
BlockState state = BlockUtil.get(name);
return new StringComparison<BlockState>().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() {

View File

@ -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};
}

View File

@ -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!");
}

View File

@ -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;

View File

@ -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<ChunkLoc> chunkLocations) {
public void sendChunk(String worldName, Collection<BlockVector2> chunkLocations) {
World myWorld = Bukkit.getWorld(worldName);
ArrayList<Chunk> 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);

View File

@ -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<T> extends BasicLocalBlockQueue<T> {
private Field fieldNeighbors;
private Method chunkGetHandle;
public class BukkitLocalQueue extends BasicLocalBlockQueue {
public BukkitLocalQueue(String world) {
super(world);
}
@Override public LocalChunk<T> getLocalChunk(int x, int z) {
return (LocalChunk<T>) 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<T> extends BasicLocalBlockQueue<T> {
}
@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<T> extends BasicLocalBlockQueue<T> {
@Override public final void regenChunk(int x, int z) {
World worldObj = Bukkit.getWorld(getWorld());
worldObj.regenerateChunk(x, z);
}
@Override public final void setComponents(LocalChunk<T> 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<T> 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<T> 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<T> 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<T> extends BasicLocalBlockQueue<T> {
}
}
/**
* 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) {
}
}
}
}

View File

@ -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;
}
}

View File

@ -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();
}

View File

@ -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<World> 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<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> 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<String, Tag> compoundMap = compound.getValue();
CompoundTag bukkit = (CompoundTag) compoundMap.get("bukkit");
Map<String, Tag> 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<String, Tag> compoundMap = compound.getValue();
CompoundTag bukkit = (CompoundTag) compoundMap.get("bukkit");
Map<String, Tag> 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);
}

View File

@ -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) {

View File

@ -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) {

View File

@ -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);

View File

@ -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

9
CONTRIBUTING.md Normal file
View File

@ -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`

View File

@ -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)

View File

@ -165,7 +165,7 @@ import java.util.UUID;
* @see Captions
*/
public void sendConsoleMessage(Captions caption) {
sendConsoleMessage(caption.s());
sendConsoleMessage(caption.getTranslated());
}
/**

View File

@ -33,7 +33,7 @@ public abstract class Argument<T> {
}
};
public static final Argument<String> PlayerName =
new Argument<String>("PlayerName", "Dinnerbone") {
new Argument<String>("PlayerName", "<player>") {
@Override public String parse(String in) {
return in.length() <= 16 ? in : null;
}

View File

@ -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<Boolean> execute(PlotPlayer player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> 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<String, Object> options = new HashMap<>();
List<String> aliasOptions = new ArrayList<>();
aliasOptions.add(this.id);
aliasOptions.addAll(Arrays.asList(declaration.aliases()));
HashMap<String, Object> 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<Boolean> execute(PlotPlayer player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> 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<String> 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<Command> 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(" ");

View File

@ -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.
*
* <p>This value does not affect how the {@link Configuration} is stored,
* only in how you access the data. The default value is '.'.
* <p> This value is always '.'.
*
* @return Path separator
*/
public char pathSeparator() {
return pathSeparator;
}
/**
* Sets the char that will be used to separate {@link
* ConfigurationSection}s.
*
* <p>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 '.';
}
/**

View File

@ -18,8 +18,4 @@ public class MemoryConfigurationOptions extends ConfigurationOptions {
return this;
}
@Override public MemoryConfigurationOptions pathSeparator(char value) {
super.pathSeparator(value);
return this;
}
}

View File

@ -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.

View File

@ -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;

View File

@ -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.
*

View File

@ -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.
*
* <p>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;
}
}

View File

@ -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;

View File

@ -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<String, Object>) 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();

View File

@ -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

View File

@ -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<String> getPluginIds();
BlockRegistry<?> getBlockRegistry();
LegacyMappings getLegacyMappings();
List<Map.Entry<Map.Entry<String, String>, Boolean>> getPluginIds();
Actor getConsole();
}

View File

@ -1,6 +1,6 @@
package com.github.intellectualsites.plotsquared.plot;
public enum Platform {
Bukkit, Sponge, Spigot
Bukkit, Sponge, Spigot, Paper
}

View File

@ -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<Plot> EMPTY_SET = Collections.
unmodifiableSet(Collections.emptySet());
private static final Set<Plot> 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<Plot>[] 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<String, Object> 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<String, Object> 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<String, Object> node : o.entrySet()) {
for (Entry<String, Object> 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<PlotArea> getPlotAreas(final String world, final RegionWrapper region) {
public Set<PlotArea> getPlotAreas(final String world, final CuboidRegion region) {
final PlotArea[] areas = plotAreaManager.getPlotAreas(world, region);
final Set<PlotArea> set = new HashSet<>();
Collections.addAll(set, areas);

View File

@ -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";

View File

@ -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<Boolean> execute(final PlotPlayer player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> 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<UUID> uuids = MainUtil.getUUIDsFromString(args[0]);
checkTrue(!uuids.isEmpty(), Captions.INVALID_PLAYER, args[0]);
Iterator<UUID> iter = uuids.iterator();
Iterator<UUID> 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);
}
}

View File

@ -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 <set|remove> <value>");
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 <set|remove> <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;
}

View File

@ -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<PlotArea> 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<ChunkLoc>() {
@Override public void run(ChunkLoc value) {
new RunnableVal<BlockVector2>() {
@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<ChunkLoc>() {
@Override public void run(ChunkLoc value) {
AugmentedUtils.generate(area.worldname, value.x, value.z, null);
.largeRegionTask(area.worldname, area.getRegion(), new RunnableVal<BlockVector2>() {
@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()));
}

View File

@ -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<Plot> 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<Plot>() {
@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);
}
}

View File

@ -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;
}

View File

@ -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<Boolean> execute(final PlotPlayer player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
final RunnableVal2<Command, CommandResult> whenDone) {
@ -65,5 +66,6 @@ import java.util.Set;
player.deposit(price);
whenDone.run(Buy.this, CommandResult.FAILURE);
});
return CompletableFuture.completedFuture(true);
}
}

View File

@ -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));

View File

@ -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<Boolean> execute(final PlotPlayer player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> 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);
}
}

View File

@ -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);

View File

@ -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();
}
}

View File

@ -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) {

View File

@ -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 <area> <start|stop|info> [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 <area> <start|stop|info> [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;
}

View File

@ -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();

View File

@ -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;
}

View File

@ -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;
}
}

View File

@ -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] <sqlite|mysql|import>");
MainUtil.sendMessage(player, getUsage());
return false;
}
List<Plot> 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] <sqlite|mysql|import>");
MainUtil.sendMessage(player, getUsage());
MainUtil.sendMessage(player, "[arg] indicates an optional argument");
return false;
}
@ -87,8 +87,8 @@ import java.util.Map.Entry;
HashMap<String, HashMap<PlotId, Plot>> map = manager.getPlots();
plots = new ArrayList<>();
for (Entry<String, HashMap<PlotId, Plot>> 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<PlotId, Plot> entry2 : entry.getValue().entrySet()) {
Plot plot = entry2.getValue();
@ -123,9 +123,9 @@ import java.util.Map.Entry;
plots.add(plot);
}
} else {
HashMap<PlotId, Plot> plotmap = PlotSquared.get().plots_tmp
.computeIfAbsent(areaname, k -> new HashMap<>());
plotmap.putAll(entry.getValue());
HashMap<PlotId, Plot> plotMap = PlotSquared.get().plots_tmp
.computeIfAbsent(areaName, k -> new HashMap<>());
plotMap.putAll(entry.getValue());
}
}
DBFunc.createPlotsAndData(plots,

View File

@ -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<String, Object> 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(

View File

@ -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<StringWrapper, UUID> map = UUIDHandler.getUuidMap();
UUID uuid = map.get(new StringWrapper(line));
if (uuid == null) {
for (Map.Entry<StringWrapper, UUID> 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<StringWrapper, UUID> map = UUIDHandler.getUuidMap();
UUID uuid = map.get(new StringWrapper(line));
if (uuid == null) {
for (Map.Entry<StringWrapper, UUID> 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;
}

View File

@ -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<Boolean> execute(PlotPlayer player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> 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);

View File

@ -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<Boolean> execute(PlotPlayer player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> 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);
}
}

View File

@ -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<String> 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<Map.Entry<String, String>, Boolean> pluginInfo : PlotSquared.get().IMP.getPluginIds()) {
Map.Entry<String, String> 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

View File

@ -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 <plot|region [height]>";
@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;
}
}

View File

@ -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 <plot> delete
// The syntax also works with any command: /plot <plot> <command>
@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<Plot> 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) {

View File

@ -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<UUID> 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);
}

View File

@ -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);
}

Some files were not shown because too many files have changed in this diff Show More