Formatting, mark nonnull, nullable etc

This commit is contained in:
dordsor21 2020-07-24 16:24:53 +01:00
parent 72c0021306
commit 1d0760c630
No known key found for this signature in database
GPG Key ID: 1E53E88969FFCF0B
39 changed files with 1172 additions and 1736 deletions

View File

@ -165,8 +165,7 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPlatform<Player> { public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPlatform<Player> {
private static final Logger logger = private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitPlatform.class.getSimpleName());
LoggerFactory.getLogger("P2/" + BukkitPlatform.class.getSimpleName());
private static final int BSTATS_ID = 1404; private static final int BSTATS_ID = 1404;
static { static {
@ -236,10 +235,8 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
final PlotSquared plotSquared = new PlotSquared(this, "Bukkit"); final PlotSquared plotSquared = new PlotSquared(this, "Bukkit");
if (PlotSquared.platform().getServerVersion()[1] < 13) { if (PlotSquared.platform().getServerVersion()[1] < 13) {
System.out.println( System.out.println("You can't use this version of PlotSquared on a server less than Minecraft 1.13.2.");
"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("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."); System.out.println("The server will now be shutdown to prevent any corruption.");
Bukkit.shutdown(); Bukkit.shutdown();
return; return;
@ -247,10 +244,8 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
// We create the injector after PlotSquared has been initialized, so that we have access // We create the injector after PlotSquared has been initialized, so that we have access
// to generated instances and settings // to generated instances and settings
this.injector = Guice.createInjector(Stage.PRODUCTION, new PermissionModule(), this.injector = Guice
new WorldManagerModule(), .createInjector(Stage.PRODUCTION, new PermissionModule(), new WorldManagerModule(), new PlotSquaredModule(), new BukkitModule(this),
new PlotSquaredModule(),
new BukkitModule(this),
new BackupModule()); new BackupModule());
this.injector.injectMembers(this); this.injector.injectMembers(this);
@ -296,8 +291,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
// Do stuff that was previously done in PlotSquared // Do stuff that was previously done in PlotSquared
// Kill entities // Kill entities
if (Settings.Enabled_Components.KILL_ROAD_MOBS if (Settings.Enabled_Components.KILL_ROAD_MOBS || Settings.Enabled_Components.KILL_ROAD_VEHICLES) {
|| Settings.Enabled_Components.KILL_ROAD_VEHICLES) {
this.runEntityTask(); this.runEntityTask();
} }
@ -305,35 +299,28 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
if (Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) { if (Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) {
try { try {
logger.info("[P2] {} hooked into WorldEdit", this.getPluginName()); logger.info("[P2] {} hooked into WorldEdit", this.getPluginName());
WorldEdit.getInstance().getEventBus() WorldEdit.getInstance().getEventBus().register(this.getInjector().getInstance(WESubscriber.class));
.register(this.getInjector().getInstance(WESubscriber.class));
if (Settings.Enabled_Components.COMMANDS) { if (Settings.Enabled_Components.COMMANDS) {
new WE_Anywhere(); new WE_Anywhere();
} }
} catch (Throwable e) { } catch (Throwable e) {
logger.error( logger.error("[P2] Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master");
"[P2] Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master");
} }
} }
if (Settings.Enabled_Components.EVENTS) { if (Settings.Enabled_Components.EVENTS) {
getServer().getPluginManager() getServer().getPluginManager().registerEvents(getInjector().getInstance(PlayerEvents.class), this);
.registerEvents(getInjector().getInstance(PlayerEvents.class), this); getServer().getPluginManager().registerEvents(getInjector().getInstance(EntitySpawnListener.class), this);
getServer().getPluginManager()
.registerEvents(getInjector().getInstance(EntitySpawnListener.class), this);
if (PaperLib.isPaper() && Settings.Paper_Components.PAPER_LISTENERS) { if (PaperLib.isPaper() && Settings.Paper_Components.PAPER_LISTENERS) {
getServer().getPluginManager() getServer().getPluginManager().registerEvents(getInjector().getInstance(PaperListener.class), this);
.registerEvents(getInjector().getInstance(PaperListener.class), this);
} }
this.plotListener.startRunnable(); this.plotListener.startRunnable();
} }
// Required // Required
getServer().getPluginManager() getServer().getPluginManager().registerEvents(getInjector().getInstance(WorldEvents.class), this);
.registerEvents(getInjector().getInstance(WorldEvents.class), this);
if (Settings.Enabled_Components.CHUNK_PROCESSOR) { if (Settings.Enabled_Components.CHUNK_PROCESSOR) {
getServer().getPluginManager() getServer().getPluginManager().registerEvents(getInjector().getInstance(ChunkListener.class), this);
.registerEvents(getInjector().getInstance(ChunkListener.class), this);
} }
// Commands // Commands
@ -361,8 +348,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
// World generators: // World generators:
final ConfigurationSection section = final ConfigurationSection section = this.worldConfiguration.getConfigurationSection("worlds");
this.worldConfiguration.getConfigurationSection("worlds");
final WorldUtil worldUtil = getInjector().getInstance(WorldUtil.class); final WorldUtil worldUtil = getInjector().getInstance(WorldUtil.class);
if (section != null) { if (section != null) {
@ -380,15 +366,11 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
continue; continue;
} }
if (!worldUtil.isWorld(world) && !world.equals("*")) { if (!worldUtil.isWorld(world) && !world.equals("*")) {
logger.warn( logger.warn("[P2] `{}` was not properly loaded - {} will now try to load it properly", world, this.getPluginName());
"[P2] `{}` was not properly loaded - {} will now try to load it properly",
world, this.getPluginName());
logger.warn( logger.warn(
"[P2] - Are you trying to delete this world? Remember to remove it from the worlds.yml, bukkit.yml and multiverse worlds.yml"); "[P2] - Are you trying to delete this world? Remember to remove it from the worlds.yml, bukkit.yml and multiverse worlds.yml");
logger.warn( logger.warn("[P2] - Your world management plugin may be faulty (or non existent)");
"[P2] - Your world management plugin may be faulty (or non existent)"); logger.warn("[P2] This message may also be a false positive and could be ignored.");
logger.warn(
"[P2] This message may also be a false positive and could be ignored.");
this.setGenerator(world); this.setGenerator(world);
} }
} }
@ -396,8 +378,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
// Services are accessed in order // Services are accessed in order
final CacheUUIDService cacheUUIDService = final CacheUUIDService cacheUUIDService = new CacheUUIDService(Settings.UUID.UUID_CACHE_SIZE);
new CacheUUIDService(Settings.UUID.UUID_CACHE_SIZE);
this.impromptuPipeline.registerService(cacheUUIDService); this.impromptuPipeline.registerService(cacheUUIDService);
this.backgroundPipeline.registerService(cacheUUIDService); this.backgroundPipeline.registerService(cacheUUIDService);
this.impromptuPipeline.registerConsumer(cacheUUIDService); this.impromptuPipeline.registerConsumer(cacheUUIDService);
@ -413,8 +394,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
if (Settings.UUID.SERVICE_BUKKIT) { if (Settings.UUID.SERVICE_BUKKIT) {
final OfflinePlayerUUIDService offlinePlayerUUIDService = final OfflinePlayerUUIDService offlinePlayerUUIDService = new OfflinePlayerUUIDService();
new OfflinePlayerUUIDService();
this.impromptuPipeline.registerService(offlinePlayerUUIDService); this.impromptuPipeline.registerService(offlinePlayerUUIDService);
this.backgroundPipeline.registerService(offlinePlayerUUIDService); this.backgroundPipeline.registerService(offlinePlayerUUIDService);
} }
@ -422,16 +402,14 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
final SQLiteUUIDService sqLiteUUIDService = new SQLiteUUIDService("user_cache.db"); final SQLiteUUIDService sqLiteUUIDService = new SQLiteUUIDService("user_cache.db");
final SQLiteUUIDService legacyUUIDService; final SQLiteUUIDService legacyUUIDService;
if (Settings.UUID.LEGACY_DATABASE_SUPPORT && if (Settings.UUID.LEGACY_DATABASE_SUPPORT && FileUtils.getFile(PlotSquared.platform().getDirectory(), "usercache.db").exists()) {
FileUtils.getFile(PlotSquared.platform().getDirectory(), "usercache.db").exists()) {
legacyUUIDService = new SQLiteUUIDService("usercache.db"); legacyUUIDService = new SQLiteUUIDService("usercache.db");
} else { } else {
legacyUUIDService = null; legacyUUIDService = null;
} }
final LuckPermsUUIDService luckPermsUUIDService; final LuckPermsUUIDService luckPermsUUIDService;
if (Settings.UUID.SERVICE_LUCKPERMS if (Settings.UUID.SERVICE_LUCKPERMS && Bukkit.getPluginManager().getPlugin("LuckPerms") != null) {
&& Bukkit.getPluginManager().getPlugin("LuckPerms") != null) {
luckPermsUUIDService = new LuckPermsUUIDService(); luckPermsUUIDService = new LuckPermsUUIDService();
logger.info("[P2] (UUID) Using LuckPerms as a complementary UUID service"); logger.info("[P2] (UUID) Using LuckPerms as a complementary UUID service");
} else { } else {
@ -439,8 +417,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
final BungeePermsUUIDService bungeePermsUUIDService; final BungeePermsUUIDService bungeePermsUUIDService;
if (Settings.UUID.SERVICE_BUNGEE_PERMS if (Settings.UUID.SERVICE_BUNGEE_PERMS && Bukkit.getPluginManager().getPlugin("BungeePerms") != null) {
&& Bukkit.getPluginManager().getPlugin("BungeePerms") != null) {
bungeePermsUUIDService = new BungeePermsUUIDService(); bungeePermsUUIDService = new BungeePermsUUIDService();
logger.info("[P2] (UUID) Using BungeePerms as a complementary UUID service"); logger.info("[P2] (UUID) Using BungeePerms as a complementary UUID service");
} else { } else {
@ -448,8 +425,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
final EssentialsUUIDService essentialsUUIDService; final EssentialsUUIDService essentialsUUIDService;
if (Settings.UUID.SERVICE_ESSENTIALSX if (Settings.UUID.SERVICE_ESSENTIALSX && Bukkit.getPluginManager().getPlugin("Essentials") != null) {
&& Bukkit.getPluginManager().getPlugin("Essentials") != null) {
essentialsUUIDService = new EssentialsUUIDService(); essentialsUUIDService = new EssentialsUUIDService();
logger.info("[P2] (UUID) Using EssentialsX as a complementary UUID service"); logger.info("[P2] (UUID) Using EssentialsX as a complementary UUID service");
} else { } else {
@ -489,11 +465,9 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
this.backgroundPipeline.registerService(essentialsUUIDService); this.backgroundPipeline.registerService(essentialsUUIDService);
} }
final SquirrelIdUUIDService impromptuMojangService = final SquirrelIdUUIDService impromptuMojangService = new SquirrelIdUUIDService(Settings.UUID.IMPROMPTU_LIMIT);
new SquirrelIdUUIDService(Settings.UUID.IMPROMPTU_LIMIT);
this.impromptuPipeline.registerService(impromptuMojangService); this.impromptuPipeline.registerService(impromptuMojangService);
final SquirrelIdUUIDService backgroundMojangService = final SquirrelIdUUIDService backgroundMojangService = new SquirrelIdUUIDService(Settings.UUID.BACKGROUND_LIMIT);
new SquirrelIdUUIDService(Settings.UUID.BACKGROUND_LIMIT);
this.backgroundPipeline.registerService(backgroundMojangService); this.backgroundPipeline.registerService(backgroundMojangService);
} else { } else {
this.impromptuPipeline.registerService(sqLiteUUIDService); this.impromptuPipeline.registerService(sqLiteUUIDService);
@ -536,10 +510,8 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
// Clean up potential memory leak // Clean up potential memory leak
Bukkit.getScheduler().runTaskTimer(this, () -> { Bukkit.getScheduler().runTaskTimer(this, () -> {
try { try {
for (final PlotPlayer<? extends Player> player : this.getPlayerManager() for (final PlotPlayer<? extends Player> player : this.getPlayerManager().getPlayers()) {
.getPlayers()) { if (player.getPlatformPlayer() == null || !player.getPlatformPlayer().isOnline()) {
if (player.getPlatformPlayer() == null || !player.getPlatformPlayer()
.isOnline()) {
this.getPlayerManager().removePlayer(player); this.getPlayerManager().removePlayer(player);
} }
} }
@ -554,8 +526,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
this.methodUnloadSetup = true; this.methodUnloadSetup = true;
try { try {
ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
this.methodUnloadChunk0 = classCraftWorld.getRealClass() this.methodUnloadChunk0 = classCraftWorld.getRealClass().getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class);
.getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class);
this.methodUnloadChunk0.setAccessible(true); this.methodUnloadChunk0.setAccessible(true);
} catch (Throwable event) { } catch (Throwable event) {
event.printStackTrace(); event.printStackTrace();
@ -586,8 +557,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
final Plot plot = area.getOwnedPlot(id); final Plot plot = area.getOwnedPlot(id);
if (plot != null) { if (plot != null) {
if (!plot.getFlag(ServerPlotFlag.class) || PlotSquared.platform().getPlayerManager() if (!plot.getFlag(ServerPlotFlag.class) || PlotSquared.platform().getPlayerManager().getPlayerIfExists(plot.getOwner()) == null) {
.getPlayerIfExists(plot.getOwner()) == null) {
if (world.getKeepSpawnInMemory()) { if (world.getKeepSpawnInMemory()) {
world.setKeepSpawnInMemory(false); world.setKeepSpawnInMemory(false);
return; return;
@ -605,8 +575,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
boolean result; boolean result;
if (methodUnloadChunk0 != null) { if (methodUnloadChunk0 != null) {
try { try {
result = (boolean) methodUnloadChunk0 result = (boolean) methodUnloadChunk0.invoke(world, chunkI.getX(), chunkI.getZ(), true);
.invoke(world, chunkI.getX(), chunkI.getZ(), true);
} catch (Throwable e) { } catch (Throwable e) {
methodUnloadChunk0 = null; methodUnloadChunk0 = null;
e.printStackTrace(); e.printStackTrace();
@ -629,8 +598,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
} }
private void startUuidCaching(@Nonnull final SQLiteUUIDService sqLiteUUIDService, private void startUuidCaching(@Nonnull final SQLiteUUIDService sqLiteUUIDService, @Nonnull final CacheUUIDService cacheUUIDService) {
@Nonnull final CacheUUIDService cacheUUIDService) {
// Load all uuids into a big chunky boi queue // Load all uuids into a big chunky boi queue
final Queue<UUID> uuidQueue = new LinkedBlockingQueue<>(); final Queue<UUID> uuidQueue = new LinkedBlockingQueue<>();
PlotSquared.get().forEachPlotRaw(plot -> { PlotSquared.get().forEachPlotRaw(plot -> {
@ -654,8 +622,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
// Now fetch names for all known UUIDs // Now fetch names for all known UUIDs
final int totalSize = uuidQueue.size(); final int totalSize = uuidQueue.size();
int read = 0; int read = 0;
logger.info("[P2] (UUID) PlotSquared will fetch UUIDs in groups of {}", logger.info("[P2] (UUID) PlotSquared will fetch UUIDs in groups of {}", Settings.UUID.BACKGROUND_LIMIT);
Settings.UUID.BACKGROUND_LIMIT);
final List<UUID> uuidList = new ArrayList<>(Settings.UUID.BACKGROUND_LIMIT); final List<UUID> uuidList = new ArrayList<>(Settings.UUID.BACKGROUND_LIMIT);
// Used to indicate that the second retrieval has been attempted // Used to indicate that the second retrieval has been attempted
@ -671,8 +638,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
// fresh batch // fresh batch
secondRun = false; secondRun = false;
// Populate the request list // Populate the request list
for (int i = 0; for (int i = 0; i < Settings.UUID.BACKGROUND_LIMIT && !uuidQueue.isEmpty(); i++) {
i < Settings.UUID.BACKGROUND_LIMIT && !uuidQueue.isEmpty(); i++) {
uuidList.add(uuidQueue.poll()); uuidList.add(uuidQueue.poll());
read++; read++;
} }
@ -688,8 +654,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
// Print progress // Print progress
final double percentage = ((double) read / (double) totalSize) * 100.0D; final double percentage = ((double) read / (double) totalSize) * 100.0D;
if (Settings.DEBUG) { if (Settings.DEBUG) {
logger.info("[P2] (UUID) PlotSquared has cached {} of UUIDs", logger.info("[P2] (UUID) PlotSquared has cached {} of UUIDs", String.format("%.1f%%", percentage));
String.format("%.1f%%", percentage));
} }
} catch (final InterruptedException | ExecutionException e) { } catch (final InterruptedException | ExecutionException e) {
logger.error("[P2] (UUID) Failed to retrieve last batch. Will try again", e); logger.error("[P2] (UUID) Failed to retrieve last batch. Will try again", e);
@ -791,8 +756,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
case "MINECART_TNT": case "MINECART_TNT":
case "BOAT": case "BOAT":
if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) {
com.plotsquared.core.location.Location location = com.plotsquared.core.location.Location location = BukkitUtil.adapt(entity.getLocation());
BukkitUtil.adapt(entity.getLocation());
Plot plot = location.getPlot(); Plot plot = location.getPlot();
if (plot == null) { if (plot == null) {
if (location.isPlotArea()) { if (location.isPlotArea()) {
@ -822,9 +786,8 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
case "FIREBALL": case "FIREBALL":
case "DRAGON_FIREBALL": case "DRAGON_FIREBALL":
case "DROPPED_ITEM": case "DROPPED_ITEM":
if (Settings.Enabled_Components.KILL_ROAD_ITEMS && plotArea if (Settings.Enabled_Components.KILL_ROAD_ITEMS
.getOwnedPlotAbs(BukkitUtil.adapt(entity.getLocation())) && plotArea.getOwnedPlotAbs(BukkitUtil.adapt(entity.getLocation())) == null) {
== null) {
entity.remove(); entity.remove();
} }
// dropped item // dropped item
@ -848,14 +811,11 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
PlotId originalPlotId = (PlotId) meta.get(0).value(); PlotId originalPlotId = (PlotId) meta.get(0).value();
if (originalPlotId != null) { if (originalPlotId != null) {
com.plotsquared.core.location.Location pLoc = com.plotsquared.core.location.Location pLoc = BukkitUtil.adapt(entity.getLocation());
BukkitUtil.adapt(entity.getLocation());
PlotArea area = pLoc.getPlotArea(); PlotArea area = pLoc.getPlotArea();
if (area != null) { if (area != null) {
PlotId currentPlotId = area.getPlotAbs(pLoc).getId(); PlotId currentPlotId = area.getPlotAbs(pLoc).getId();
if (!originalPlotId.equals(currentPlotId) && ( if (!originalPlotId.equals(currentPlotId) && (currentPlotId == null || !area.getPlot(originalPlotId)
currentPlotId == null || !area
.getPlot(originalPlotId)
.equals(area.getPlot(currentPlotId)))) { .equals(area.getPlot(currentPlotId)))) {
if (entity.hasMetadata("ps-tmp-teleport")) { if (entity.hasMetadata("ps-tmp-teleport")) {
continue; continue;
@ -867,16 +827,12 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
} else { } else {
//This is to apply the metadata to already spawned shulkers (see EntitySpawnListener.java) //This is to apply the metadata to already spawned shulkers (see EntitySpawnListener.java)
com.plotsquared.core.location.Location pLoc = com.plotsquared.core.location.Location pLoc = BukkitUtil.adapt(entity.getLocation());
BukkitUtil.adapt(entity.getLocation());
PlotArea area = pLoc.getPlotArea(); PlotArea area = pLoc.getPlotArea();
if (area != null) { if (area != null) {
PlotId currentPlotId = area.getPlotAbs(pLoc).getId(); PlotId currentPlotId = area.getPlotAbs(pLoc).getId();
if (currentPlotId != null) { if (currentPlotId != null) {
entity.setMetadata("shulkerPlot", entity.setMetadata("shulkerPlot", new FixedMetadataValue((Plugin) PlotSquared.platform(), currentPlotId));
new FixedMetadataValue(
(Plugin) PlotSquared.platform(),
currentPlotId));
} }
} }
} }
@ -957,11 +913,9 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
if (BukkitUtil.adapt(location).isPlotRoad()) { if (BukkitUtil.adapt(location).isPlotRoad()) {
if (entity instanceof LivingEntity) { if (entity instanceof LivingEntity) {
LivingEntity livingEntity = (LivingEntity) entity; LivingEntity livingEntity = (LivingEntity) entity;
if (!livingEntity.isLeashed() || !entity if (!livingEntity.isLeashed() || !entity.hasMetadata("keep")) {
.hasMetadata("keep")) {
Entity passenger = entity.getPassenger(); Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player) && entity if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) {
.getMetadata("keep").isEmpty()) {
if (entity.hasMetadata("ps-tmp-teleport")) { if (entity.hasMetadata("ps-tmp-teleport")) {
continue; continue;
} }
@ -972,8 +926,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
} else { } else {
Entity passenger = entity.getPassenger(); Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player) && entity if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) {
.getMetadata("keep").isEmpty()) {
if (entity.hasMetadata("ps-tmp-teleport")) { if (entity.hasMetadata("ps-tmp-teleport")) {
continue; continue;
} }
@ -994,15 +947,12 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
}), TaskTime.seconds(1L)); }), TaskTime.seconds(1L));
} }
@Override @Nullable @Override @Nullable public final ChunkGenerator getDefaultWorldGenerator(@Nonnull final String worldName, final String id) {
public final ChunkGenerator getDefaultWorldGenerator(@Nonnull final String worldName,
final String id) {
final IndependentPlotGenerator result; final IndependentPlotGenerator result;
if (id != null && id.equalsIgnoreCase("single")) { if (id != null && id.equalsIgnoreCase("single")) {
result = getInjector().getInstance(SingleWorldGenerator.class); result = getInjector().getInstance(SingleWorldGenerator.class);
} else { } else {
result = getInjector() result = getInjector().getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class));
.getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class));
if (!PlotSquared.get().setupPlotWorld(worldName, id, result)) { if (!PlotSquared.get().setupPlotWorld(worldName, id, result)) {
return null; return null;
} }
@ -1010,8 +960,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
return (ChunkGenerator) result.specify(worldName); return (ChunkGenerator) result.specify(worldName);
} }
@Override @Nullable public GeneratorWrapper<?> getGenerator(@Nonnull final String world, @Override @Nullable public GeneratorWrapper<?> getGenerator(@Nonnull final String world, @Nullable final String name) {
@Nullable final String name) {
if (name == null) { if (name == null) {
return null; return null;
} }
@ -1023,8 +972,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
return new BukkitPlotGenerator(world, gen, this.plotAreaManager); return new BukkitPlotGenerator(world, gen, this.plotAreaManager);
} else { } else {
return new BukkitPlotGenerator(world, getInjector() return new BukkitPlotGenerator(world, getInjector().getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)),
.getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)),
this.plotAreaManager); this.plotAreaManager);
} }
} }
@ -1045,19 +993,14 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
map.put(plotAreaType.name().toLowerCase(), terrainTypes); map.put(plotAreaType.name().toLowerCase(), terrainTypes);
} }
for (final PlotArea plotArea : this.plotAreaManager.getAllPlotAreas()) { for (final PlotArea plotArea : this.plotAreaManager.getAllPlotAreas()) {
final Map<String, Integer> terrainTypeMap = final Map<String, Integer> terrainTypeMap = map.get(plotArea.getType().name().toLowerCase());
map.get(plotArea.getType().name().toLowerCase()); terrainTypeMap.put(plotArea.getTerrain().name().toLowerCase(), terrainTypeMap.get(plotArea.getTerrain().name().toLowerCase()) + 1);
terrainTypeMap.put(plotArea.getTerrain().name().toLowerCase(),
terrainTypeMap.get(plotArea.getTerrain().name().toLowerCase()) + 1);
} }
return map; return map;
})); }));
metrics.addCustomChart(new Metrics.SimplePie("premium", metrics.addCustomChart(new Metrics.SimplePie("premium", () -> PremiumVerification.isPremium() ? "Premium" : "Non-Premium"));
() -> PremiumVerification.isPremium() ? "Premium" : "Non-Premium"));
metrics.addCustomChart(new Metrics.SimplePie("worldedit_implementation", metrics.addCustomChart(new Metrics.SimplePie("worldedit_implementation",
() -> Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit") != null ? () -> Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit") != null ? "FastAsyncWorldEdit" : "WorldEdit"));
"FastAsyncWorldEdit" :
"WorldEdit"));
} }
@Override public void unregister(@Nonnull final PlotPlayer<?> player) { @Override public void unregister(@Nonnull final PlotPlayer<?> player) {
@ -1068,15 +1011,12 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
World world = BukkitUtil.getWorld(worldName); World world = BukkitUtil.getWorld(worldName);
if (world == null) { if (world == null) {
// create world // create world
ConfigurationSection worldConfig = ConfigurationSection worldConfig = this.worldConfiguration.getConfigurationSection("worlds." + worldName);
this.worldConfiguration.getConfigurationSection("worlds." + worldName);
String manager = worldConfig.getString("generator.plugin", getPluginName()); String manager = worldConfig.getString("generator.plugin", getPluginName());
PlotAreaBuilder builder = PlotAreaBuilder.newBuilder().plotManager(manager) PlotAreaBuilder builder =
.generatorName(worldConfig.getString("generator.init", manager)) PlotAreaBuilder.newBuilder().plotManager(manager).generatorName(worldConfig.getString("generator.init", manager))
.plotAreaType(ConfigurationUtil.getType(worldConfig)) .plotAreaType(ConfigurationUtil.getType(worldConfig)).terrainType(ConfigurationUtil.getTerrain(worldConfig))
.terrainType(ConfigurationUtil.getTerrain(worldConfig)) .settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null)).worldName(worldName);
.settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null))
.worldName(worldName);
getInjector().getInstance(SetupUtils.class).setupWorld(builder); getInjector().getInstance(SetupUtils.class).setupWorld(builder);
world = Bukkit.getWorld(worldName); world = Bukkit.getWorld(worldName);
} else { } else {
@ -1095,8 +1035,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
if (gen instanceof BukkitPlotGenerator) { if (gen instanceof BukkitPlotGenerator) {
PlotSquared.get().loadWorld(worldName, (BukkitPlotGenerator) gen); PlotSquared.get().loadWorld(worldName, (BukkitPlotGenerator) gen);
} else if (gen != null) { } else if (gen != null) {
PlotSquared.get().loadWorld(worldName, PlotSquared.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen, this.plotAreaManager));
new BukkitPlotGenerator(worldName, gen, this.plotAreaManager));
} else if (this.worldConfiguration.contains("worlds." + worldName)) { } else if (this.worldConfiguration.contains("worlds." + worldName)) {
PlotSquared.get().loadWorld(worldName, null); PlotSquared.get().loadWorld(worldName, null);
} }
@ -1115,16 +1054,14 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
} }
@Override public GeneratorWrapper<?> wrapPlotGenerator(@Nullable final String world, @Override public GeneratorWrapper<?> wrapPlotGenerator(@Nullable final String world, @Nonnull final IndependentPlotGenerator generator) {
@Nonnull final IndependentPlotGenerator generator) {
return new BukkitPlotGenerator(world, generator, this.plotAreaManager); return new BukkitPlotGenerator(world, generator, this.plotAreaManager);
} }
@Override public List<Map.Entry<Map.Entry<String, String>, Boolean>> getPluginIds() { @Override public List<Map.Entry<Map.Entry<String, String>, Boolean>> getPluginIds() {
List<Map.Entry<Map.Entry<String, String>, Boolean>> names = new ArrayList<>(); List<Map.Entry<Map.Entry<String, String>, Boolean>> names = new ArrayList<>();
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
Map.Entry<String, String> id = new AbstractMap.SimpleEntry<>(plugin.getName(), Map.Entry<String, String> id = new AbstractMap.SimpleEntry<>(plugin.getName(), plugin.getDescription().getVersion());
plugin.getDescription().getVersion());
names.add(new AbstractMap.SimpleEntry<>(id, plugin.isEnabled())); names.add(new AbstractMap.SimpleEntry<>(id, plugin.isEnabled()));
} }
return names; return names;
@ -1135,11 +1072,11 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
} }
@Override @Nonnull public PlatformWorldManager<?> getWorldManager() { @Override @Nonnull public PlatformWorldManager<?> getWorldManager() {
return getInjector().getInstance(Key.get(new TypeLiteral<PlatformWorldManager<World>>() {})); return getInjector().getInstance(Key.get(new TypeLiteral<PlatformWorldManager<World>>() {
}));
} }
@Override @Nonnull @SuppressWarnings("ALL") @Override @Nonnull @SuppressWarnings("ALL") public PlayerManager<? extends PlotPlayer<Player>, ? extends Player> getPlayerManager() {
public PlayerManager<? extends PlotPlayer<Player>, ? extends Player> getPlayerManager() {
return (PlayerManager<BukkitPlayer, Player>) getInjector().getInstance(PlayerManager.class); return (PlayerManager<BukkitPlayer, Player>) getInjector().getInstance(PlayerManager.class);
} }

View File

@ -47,24 +47,20 @@ final class BlockStatePopulator extends BlockPopulator {
private QueueCoordinator queue; private QueueCoordinator queue;
public BlockStatePopulator(@Nonnull final IndependentPlotGenerator plotGenerator, public BlockStatePopulator(@Nonnull final IndependentPlotGenerator plotGenerator, @Nonnull final PlotAreaManager plotAreaManager) {
@Nonnull final PlotAreaManager plotAreaManager) {
this.plotGenerator = plotGenerator; this.plotGenerator = plotGenerator;
this.plotAreaManager = plotAreaManager; this.plotAreaManager = plotAreaManager;
} }
@Override public void populate(@Nonnull final World world, @Nonnull final Random random, @Override public void populate(@Nonnull final World world, @Nonnull final Random random, @Nonnull final Chunk source) {
@Nonnull final Chunk source) {
if (this.queue == null) { if (this.queue == null) {
this.queue = this.queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(new BukkitWorld(world));
PlotSquared.platform().getGlobalBlockQueue().getNewQueue(new BukkitWorld(world));
} }
final PlotArea area = this.plotAreaManager.getPlotArea(world.getName(), null); final PlotArea area = this.plotAreaManager.getPlotArea(world.getName(), null);
if (area == null) { if (area == null) {
return; return;
} }
final ChunkWrapper wrap = final ChunkWrapper wrap = new ChunkWrapper(area.getWorldName(), source.getX(), source.getZ());
new ChunkWrapper(area.getWorldName(), source.getX(), source.getZ());
final ScopedQueueCoordinator chunk = this.queue.getForChunk(wrap.x, wrap.z); final ScopedQueueCoordinator chunk = this.queue.getForChunk(wrap.x, wrap.z);
if (this.plotGenerator.populateChunk(chunk, area)) { if (this.plotGenerator.populateChunk(chunk, area)) {
this.queue.enqueue(); this.queue.enqueue();

View File

@ -82,19 +82,15 @@ public class BukkitModule extends AbstractModule {
bind(PlayerManager.class).to(BukkitPlayerManager.class); bind(PlayerManager.class).to(BukkitPlayerManager.class);
bind(JavaPlugin.class).toInstance(bukkitPlatform); bind(JavaPlugin.class).toInstance(bukkitPlatform);
bind(PlotPlatform.class).toInstance(bukkitPlatform); bind(PlotPlatform.class).toInstance(bukkitPlatform);
bind(IndependentPlotGenerator.class).annotatedWith(DefaultGenerator.class) bind(IndependentPlotGenerator.class).annotatedWith(DefaultGenerator.class).to(HybridGen.class);
.to(HybridGen.class);
// Console actor // Console actor
@Nonnull ConsoleCommandSender console = Bukkit.getServer().getConsoleSender(); @Nonnull ConsoleCommandSender console = Bukkit.getServer().getConsoleSender();
WorldEditPlugin wePlugin = WorldEditPlugin wePlugin = ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit"));
((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit")); bind(Actor.class).annotatedWith(ConsoleActor.class).toInstance(wePlugin.wrapCommandSender(console));
bind(Actor.class).annotatedWith(ConsoleActor.class)
.toInstance(wePlugin.wrapCommandSender(console));
bind(InventoryUtil.class).to(BukkitInventoryUtil.class); bind(InventoryUtil.class).to(BukkitInventoryUtil.class);
bind(SetupUtils.class).to(BukkitSetupUtils.class); bind(SetupUtils.class).to(BukkitSetupUtils.class);
bind(WorldUtil.class).to(BukkitUtil.class); bind(WorldUtil.class).to(BukkitUtil.class);
bind(GlobalBlockQueue.class) bind(GlobalBlockQueue.class).toInstance(new GlobalBlockQueue(QueueProvider.of(BukkitQueueCoordinator.class)));
.toInstance(new GlobalBlockQueue(QueueProvider.of(BukkitQueueCoordinator.class)));
bind(ChunkManager.class).to(BukkitChunkManager.class); bind(ChunkManager.class).to(BukkitChunkManager.class);
bind(RegionManager.class).to(BukkitRegionManager.class); bind(RegionManager.class).to(BukkitRegionManager.class);
bind(SchematicHandler.class).to(BukkitSchematicHandler.class); bind(SchematicHandler.class).to(BukkitSchematicHandler.class);
@ -104,9 +100,7 @@ public class BukkitModule extends AbstractModule {
bind(PlotAreaManager.class).to(DefaultPlotAreaManager.class); bind(PlotAreaManager.class).to(DefaultPlotAreaManager.class);
} }
install(new FactoryModuleBuilder().build(HybridPlotWorldFactory.class)); install(new FactoryModuleBuilder().build(HybridPlotWorldFactory.class));
install(new FactoryModuleBuilder() install(new FactoryModuleBuilder().implement(ChunkCoordinator.class, BukkitChunkCoordinator.class).build(ChunkCoordinatorFactory.class));
.implement(ChunkCoordinator.class, BukkitChunkCoordinator.class)
.build(ChunkCoordinatorFactory.class));
install(new FactoryModuleBuilder().build(ChunkCoordinatorBuilderFactory.class)); install(new FactoryModuleBuilder().build(ChunkCoordinatorBuilderFactory.class));
} }

View File

@ -104,8 +104,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator {
// Request initial batch // Request initial batch
this.requestBatch(); this.requestBatch();
// Wait until next tick to give the chunks a chance to be loaded // Wait until next tick to give the chunks a chance to be loaded
TaskManager.runTaskLater(() -> TaskManager.runTaskRepeat(this, TaskTime.ticks(1)), TaskManager.runTaskLater(() -> TaskManager.runTaskRepeat(this, TaskTime.ticks(1)), TaskTime.ticks(1));
TaskTime.ticks(1));
} }
@Override public void runTask() { @Override public void runTask() {
@ -129,8 +128,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator {
final long end = System.currentTimeMillis(); final long end = System.currentTimeMillis();
// Update iteration time // Update iteration time
iterationTime = end - start; iterationTime = end - start;
} while (2 * iterationTime /* last chunk + next chunk */ < this.maxIterationTime } while (2 * iterationTime /* last chunk + next chunk */ < this.maxIterationTime && (chunk = availableChunks.poll()) != null);
&& (chunk = availableChunks.poll()) != null);
if (processedChunks < this.batchSize) { if (processedChunks < this.batchSize) {
// Adjust batch size based on the amount of processed chunks per tick // Adjust batch size based on the amount of processed chunks per tick
this.batchSize = processedChunks; this.batchSize = processedChunks;
@ -157,12 +155,14 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator {
} }
} }
/**
* Requests a batch of chunks to be loaded
*/
private void requestBatch() { private void requestBatch() {
BlockVector2 chunk; BlockVector2 chunk;
for (int i = 0; i < this.batchSize && (chunk = this.requestedChunks.poll()) != null; i++) { for (int i = 0; i < this.batchSize && (chunk = this.requestedChunks.poll()) != null; i++) {
// This required PaperLib to be bumped to version 1.0.4 to mark the request as urgent // This required PaperLib to be bumped to version 1.0.4 to mark the request as urgent
PaperLib.getChunkAtAsync(this.bukkitWorld, chunk.getX(), chunk.getZ(), true, true) PaperLib.getChunkAtAsync(this.bukkitWorld, chunk.getX(), chunk.getZ(), true, true).whenComplete((chunkObject, throwable) -> {
.whenComplete((chunkObject, throwable) -> {
if (throwable != null) { if (throwable != null) {
throwable.printStackTrace(); throwable.printStackTrace();
// We want one less because this couldn't be processed // We want one less because this couldn't be processed
@ -174,19 +174,23 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator {
} }
} }
/**
* Once a chunk has been loaded, process it (add a plugin ticket and add to available chunks list)
*/
private void processChunk(@Nonnull final Chunk chunk) { private void processChunk(@Nonnull final Chunk chunk) {
if (!chunk.isLoaded()) { if (!chunk.isLoaded()) {
throw new IllegalArgumentException( throw new IllegalArgumentException(String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ()));
String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ()));
} }
chunk.addPluginChunkTicket(this.plugin); chunk.addPluginChunkTicket(this.plugin);
this.availableChunks.add(chunk); this.availableChunks.add(chunk);
} }
/**
* Once a chunk has been used, free it up for unload by removing the plugin ticket
*/
private void freeChunk(@Nonnull final Chunk chunk) { private void freeChunk(@Nonnull final Chunk chunk) {
if (!chunk.isLoaded()) { if (!chunk.isLoaded()) {
throw new IllegalArgumentException( throw new IllegalArgumentException(String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ()));
String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ()));
} }
chunk.removePluginChunkTicket(this.plugin); chunk.removePluginChunkTicket(this.plugin);
} }
@ -214,8 +218,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator {
* *
* @param subscriber Subscriber * @param subscriber Subscriber
*/ */
public void subscribeToProgress( public void subscribeToProgress(@Nonnull final BukkitChunkCoordinator.ProgressSubscriber subscriber) {
@Nonnull final BukkitChunkCoordinator.ProgressSubscriber subscriber) {
this.progressSubscribers.add(subscriber); this.progressSubscribers.add(subscriber);
} }
@ -228,8 +231,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator {
* @param coordinator Coordinator instance that triggered the notification * @param coordinator Coordinator instance that triggered the notification
* @param progress Progress in the range [0, 1] * @param progress Progress in the range [0, 1]
*/ */
void notifyProgress(@Nonnull final BukkitChunkCoordinator coordinator, void notifyProgress(@Nonnull final BukkitChunkCoordinator coordinator, final float progress);
final float progress);
} }

View File

@ -56,6 +56,7 @@ import org.bukkit.block.Block;
import org.bukkit.block.Container; import org.bukkit.block.Container;
import org.bukkit.block.data.BlockData; import org.bukkit.block.data.BlockData;
import javax.annotation.Nonnull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -69,10 +70,9 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator {
private Runnable whenDone; private Runnable whenDone;
private ChunkCoordinator chunkCoordinator; private ChunkCoordinator chunkCoordinator;
@Inject public BukkitQueueCoordinator(World world) { @Inject public BukkitQueueCoordinator(@Nonnull World world) {
super(world); super(world);
sideEffectSet = SideEffectSet.none().with(SideEffect.LIGHTING, SideEffect.State.OFF) sideEffectSet = SideEffectSet.none().with(SideEffect.LIGHTING, SideEffect.State.OFF).with(SideEffect.NEIGHBORS, SideEffect.State.OFF);
.with(SideEffect.NEIGHBORS, SideEffect.State.OFF);
} }
@Override public BlockState getBlock(int x, int y, int z) { @Override public BlockState getBlock(int x, int y, int z) {
@ -97,10 +97,8 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator {
@Override public boolean enqueue() { @Override public boolean enqueue() {
final Clipboard regenClipboard; final Clipboard regenClipboard;
if (isRegen()) { if (isRegen()) {
BlockVector3 start = BlockVector3 start = BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4);
BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4); BlockVector3 end = BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15);
BlockVector3 end =
BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15);
Region region = new CuboidRegion(start, end); Region region = new CuboidRegion(start, end);
regenClipboard = new BlockArrayClipboard(region); regenClipboard = new BlockArrayClipboard(region);
regenClipboard.setOrigin(start); regenClipboard.setOrigin(start);
@ -117,17 +115,14 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator {
consumer = blockVector2 -> { consumer = blockVector2 -> {
LocalChunk localChunk = getBlockChunks().get(blockVector2); LocalChunk localChunk = getBlockChunks().get(blockVector2);
boolean isRegenChunk = boolean isRegenChunk =
regenClipboard != null && blockVector2.getBlockX() > getRegenStart()[0] regenClipboard != null && blockVector2.getBlockX() > getRegenStart()[0] && blockVector2.getBlockZ() > getRegenStart()[1]
&& blockVector2.getBlockZ() > getRegenStart()[1] && blockVector2.getBlockX() < getRegenEnd()[0] && blockVector2.getBlockZ() < getRegenEnd()[1];
&& blockVector2.getBlockX() < getRegenEnd()[0]
&& blockVector2.getBlockZ() < getRegenEnd()[1];
if (isRegenChunk) { if (isRegenChunk) {
for (int layer = 0; layer < 16; layer++) { for (int layer = 0; layer < 16; layer++) {
for (int y = layer << 4; y < 16; y++) { for (int y = layer << 4; y < 16; y++) {
for (int x = 0; x < 16; x++) { for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) { for (int z = 0; z < 16; z++) {
BaseBlock block = BaseBlock block = regenClipboard.getFullBlock(BlockVector3.at(x, y, z));
regenClipboard.getFullBlock(BlockVector3.at(x, y, z));
if (block != null) { if (block != null) {
setWorldBlock(x, y, z, block, blockVector2); setWorldBlock(x, y, z, block, blockVector2);
} }
@ -186,8 +181,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator {
getWorld().setBlock(blockVector3, block, sideEffectSet); getWorld().setBlock(blockVector3, block, sideEffectSet);
} catch (WorldEditException ignored) { } catch (WorldEditException ignored) {
StateWrapper sw = new StateWrapper(tag); StateWrapper sw = new StateWrapper(tag);
sw.restoreTag(getWorld().getName(), blockVector3.getX(), sw.restoreTag(getWorld().getName(), blockVector3.getX(), blockVector3.getY(), blockVector3.getZ());
blockVector3.getY(), blockVector3.getZ());
} }
})); }));
} }
@ -203,15 +197,16 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator {
read.addAll(getReadChunks()); read.addAll(getReadChunks());
} }
chunkCoordinator = chunkCoordinator =
chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(getWorld()) chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(getWorld()).withChunks(getBlockChunks().keySet()).withChunks(read)
.withChunks(getBlockChunks().keySet()).withChunks(read).withInitialBatchSize(3) .withInitialBatchSize(3).withMaxIterationTime(40).withThrowableConsumer(Throwable::printStackTrace).withFinalAction(whenDone)
.withMaxIterationTime(40).withThrowableConsumer(Throwable::printStackTrace) .withConsumer(consumer).unloadAfter(isUnloadAfter()).build();
.withFinalAction(whenDone).withConsumer(consumer).unloadAfter(isUnloadAfter())
.build();
return super.enqueue(); return super.enqueue();
} }
private void setWorldBlock(int x, int y, int z, BaseBlock block, BlockVector2 blockVector2) { /**
* Set a block to the world. First tries WNA but defaults to normal block setting methods if that fails
*/
private void setWorldBlock(int x, int y, int z, @Nonnull BaseBlock block, @Nonnull BlockVector2 blockVector2) {
try { try {
getWorld().setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); getWorld().setBlock(BlockVector3.at(x, y, z), block, sideEffectSet);
} catch (WorldEditException ignored) { } catch (WorldEditException ignored) {
@ -225,8 +220,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator {
Block existing = chunk.getBlock(x, y, z); Block existing = chunk.getBlock(x, y, z);
final BlockState existingBaseBlock = BukkitAdapter.adapt(existing.getBlockData()); final BlockState existingBaseBlock = BukkitAdapter.adapt(existing.getBlockData());
if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing.getBlockData() if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing.getBlockData().matches(blockData)) {
.matches(blockData)) {
return; return;
} }
@ -240,8 +234,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator {
CompoundTag tag = block.getNbtData(); CompoundTag tag = block.getNbtData();
StateWrapper sw = new StateWrapper(tag); StateWrapper sw = new StateWrapper(tag);
sw.restoreTag(getWorld().getName(), existing.getX(), existing.getY(), sw.restoreTag(getWorld().getName(), existing.getX(), existing.getY(), existing.getZ());
existing.getZ());
} }
} }
} }

View File

@ -45,8 +45,10 @@ import org.bukkit.World;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
import org.bukkit.generator.ChunkGenerator.BiomeGrid; import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.generator.ChunkGenerator.ChunkData; import org.bukkit.generator.ChunkGenerator.ChunkData;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays; import java.util.Arrays;
public class GenChunk extends ScopedQueueCoordinator { public class GenChunk extends ScopedQueueCoordinator {
@ -65,15 +67,15 @@ public class GenChunk extends ScopedQueueCoordinator {
this.biomes = Biome.values(); this.biomes = Biome.values();
} }
public ChunkData getChunkData() { @Nullable public ChunkData getChunkData() {
return this.chunkData; return this.chunkData;
} }
public void setChunkData(ChunkData chunkData) { public void setChunkData(@Nonnull ChunkData chunkData) {
this.chunkData = chunkData; this.chunkData = chunkData;
} }
public Chunk getChunk() { @Nonnull public Chunk getChunk() {
if (chunk == null) { if (chunk == null) {
World worldObj = BukkitUtil.getWorld(world); World worldObj = BukkitUtil.getWorld(world);
if (worldObj != null) { if (worldObj != null) {
@ -83,18 +85,18 @@ public class GenChunk extends ScopedQueueCoordinator {
return chunk; return chunk;
} }
public void setChunk(Chunk chunk) { public void setChunk(@Nonnull Chunk chunk) {
this.chunk = chunk; this.chunk = chunk;
} }
public void setChunk(ChunkWrapper wrap) { public void setChunk(@Nonnull ChunkWrapper wrap) {
chunk = null; chunk = null;
world = wrap.world; world = wrap.world;
chunkX = wrap.x; chunkX = wrap.x;
chunkZ = wrap.z; chunkZ = wrap.z;
} }
@Override public void fillBiome(BiomeType biomeType) { @Override public void fillBiome(@Nonnull BiomeType biomeType) {
if (biomeGrid == null) { if (biomeGrid == null) {
return; return;
} }
@ -106,9 +108,8 @@ public class GenChunk extends ScopedQueueCoordinator {
} }
} }
@Override public void setCuboid(Location pos1, Location pos2, BlockState block) { @Override public void setCuboid(@NotNull Location pos1, @NotNull Location pos2, @NotNull BlockState block) {
if (result != null && pos1.getX() == 0 && pos1.getZ() == 0 && pos2.getX() == 15 if (result != null && pos1.getX() == 0 && pos1.getZ() == 0 && pos2.getX() == 15 && pos2.getZ() == 15) {
&& pos2.getZ() == 15) {
for (int y = pos1.getY(); y <= pos2.getY(); y++) { for (int y = pos1.getY(); y <= pos2.getY(); y++) {
int layer = y >> 4; int layer = y >> 4;
BlockState[] data = result[layer]; BlockState[] data = result[layer];
@ -126,15 +127,14 @@ public class GenChunk extends ScopedQueueCoordinator {
int maxX = Math.max(pos1.getX(), pos2.getX()); int maxX = Math.max(pos1.getX(), pos2.getX());
int maxY = Math.max(pos1.getY(), pos2.getY()); int maxY = Math.max(pos1.getY(), pos2.getY());
int maxZ = Math.max(pos1.getZ(), pos2.getZ()); int maxZ = Math.max(pos1.getZ(), pos2.getZ());
chunkData chunkData.setRegion(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1, BukkitAdapter.adapt(block));
.setRegion(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1, BukkitAdapter.adapt(block));
} }
@Override public boolean setBiome(int x, int z, BiomeType biomeType) { @Override public boolean setBiome(int x, int z, @NotNull BiomeType biomeType) {
return setBiome(x, z, BukkitAdapter.adapt(biomeType)); return setBiome(x, z, BukkitAdapter.adapt(biomeType));
} }
public boolean setBiome(int x, int z, Biome biome) { public boolean setBiome(int x, int z, @Nonnull Biome biome) {
if (this.biomeGrid != null) { if (this.biomeGrid != null) {
this.biomeGrid.setBiome(x, z, biome); this.biomeGrid.setBiome(x, z, biome);
return true; return true;
@ -142,12 +142,11 @@ public class GenChunk extends ScopedQueueCoordinator {
return false; return false;
} }
@Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { @Override public boolean setBlock(int x, int y, int z, @Nonnull @NotNull Pattern pattern) {
return setBlock(x, y, z, PatternUtil return setBlock(x, y, z, PatternUtil.apply(Preconditions.checkNotNull(pattern, "Pattern may not be null"), x, y, z));
.apply(Preconditions.checkNotNull(pattern, "Pattern may not be null"), x, y, z));
} }
@Override public boolean setBlock(int x, int y, int z, BlockState id) { @Override public boolean setBlock(int x, int y, int z, @NotNull BlockState id) {
if (this.result == null) { if (this.result == null) {
this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id));
return true; return true;
@ -157,7 +156,7 @@ public class GenChunk extends ScopedQueueCoordinator {
return true; return true;
} }
private void storeCache(final int x, final int y, final int z, final BlockState id) { private void storeCache(final int x, final int y, final int z, @Nonnull final BlockState id) {
int i = y >> 4; int i = y >> 4;
BlockState[] v = this.result[i]; BlockState[] v = this.result[i];
if (v == null) { if (v == null) {
@ -167,7 +166,7 @@ public class GenChunk extends ScopedQueueCoordinator {
v[j] = id; v[j] = id;
} }
@Override public boolean setBlock(int x, int y, int z, BaseBlock id) { @Override public boolean setBlock(int x, int y, int z, @NotNull BaseBlock id) {
if (this.result == null) { if (this.result == null) {
this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id));
return true; return true;
@ -177,7 +176,7 @@ public class GenChunk extends ScopedQueueCoordinator {
return true; return true;
} }
@Override public BlockState getBlock(int x, int y, int z) { @Override @Nullable public BlockState getBlock(int x, int y, int z) {
int i = y >> 4; int i = y >> 4;
if (result == null) { if (result == null) {
return BukkitBlockUtil.get(chunkData.getType(x, y, z)); return BukkitBlockUtil.get(chunkData.getType(x, y, z));
@ -198,21 +197,19 @@ public class GenChunk extends ScopedQueueCoordinator {
return chunk == null ? chunkZ : chunk.getZ(); return chunk == null ? chunkZ : chunk.getZ();
} }
@Override public com.sk89q.worldedit.world.World getWorld() { @Override @Nonnull public com.sk89q.worldedit.world.World getWorld() {
return chunk == null ? return chunk == null ? BukkitAdapter.adapt(Bukkit.getWorld(world)) : BukkitAdapter.adapt(chunk.getWorld());
BukkitAdapter.adapt(Bukkit.getWorld(world)) :
BukkitAdapter.adapt(chunk.getWorld());
} }
@Override public Location getMax() { @Override @Nonnull public Location getMax() {
return Location.at(getWorld().getName(), 15 + (getX() << 4), 255, 15 + (getZ() << 4)); return Location.at(getWorld().getName(), 15 + (getX() << 4), 255, 15 + (getZ() << 4));
} }
@Override public Location getMin() { @Override @Nonnull public Location getMin() {
return Location.at(getWorld().getName(), getX() << 4, 0, getZ() << 4); return Location.at(getWorld().getName(), getX() << 4, 0, getZ() << 4);
} }
public GenChunk clone() { @Nonnull public GenChunk clone() {
GenChunk toReturn = new GenChunk(); GenChunk toReturn = new GenChunk();
if (this.result != null) { if (this.result != null) {
for (int i = 0; i < this.result.length; i++) { for (int i = 0; i < this.result.length; i++) {

View File

@ -26,107 +26,23 @@
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.listener.WEExtent;
import com.plotsquared.core.queue.QueueCoordinator;
import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.entity.EntityCategories;
import com.plotsquared.core.util.task.TaskManager;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.block.BaseBlock;
import io.papermc.lib.PaperLib; import io.papermc.lib.PaperLib;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Entity;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_ANIMAL;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_ENTITY;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_MISC;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_MOB;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_MONSTER;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE;
@Singleton @Singleton
public class BukkitChunkManager extends ChunkManager { public class BukkitChunkManager extends ChunkManager {
public static boolean isIn(CuboidRegion region, int x, int z) { public static boolean isIn(CuboidRegion region, int x, int z) {
return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX() return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX() && z >= region.getMinimumPoint().getZ() && z <= region
&& z >= region.getMinimumPoint().getZ() && z <= region.getMaximumPoint().getZ(); .getMaximumPoint().getZ();
} }
public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2, @Override public CompletableFuture<?> loadChunk(String world, BlockVector2 chunkLoc, boolean force) {
CuboidRegion r1, CuboidRegion r2) { return PaperLib.getChunkAtAsync(BukkitUtil.getWorld(world), chunkLoc.getX(), chunkLoc.getZ(), force);
ContentMap map = new ContentMap();
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);
int sx = pos1.getX() << 4;
int sz = pos1.getZ() << 4;
BukkitWorld bukkitWorld1 = new BukkitWorld(world1);
BukkitWorld bukkitWorld2 = new BukkitWorld(world2);
QueueCoordinator queue1 =
PlotSquared.platform().getGlobalBlockQueue().getNewQueue(bukkitWorld1);
QueueCoordinator queue2 =
PlotSquared.platform().getGlobalBlockQueue().getNewQueue(bukkitWorld2);
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));
BlockData data1 = block1.getBlockData();
int xx = x + relX;
int zz = z + relZ;
Block block2 = world2.getBlockAt(xx, y, zz);
BaseBlock baseBlock2 = bukkitWorld2.getFullBlock(BlockVector3.at(xx, y, zz));
BlockData data2 = block2.getBlockData();
if (block1.isEmpty()) {
if (!block2.isEmpty()) {
queue1.setBlock(x, y, z, baseBlock2);
queue2.setBlock(xx, y, zz, WEExtent.AIRBASE);
}
} else if (block2.isEmpty()) {
queue1.setBlock(x, y, z, WEExtent.AIRBASE);
queue2.setBlock(xx, y, zz, baseBlock1);
} else if (block1.equals(block2)) {
if (!data1.matches(data2)) {
block1.setBlockData(data2);
block2.setBlockData(data1);
}
} else {
queue1.setBlock(x, y, z, baseBlock2);
queue2.setBlock(xx, y, zz, baseBlock1);
}
}
}
}
queue1.enqueue();
queue2.enqueue();
return map;
}
@Override
public CompletableFuture<?> loadChunk(String world, BlockVector2 chunkLoc, boolean force) {
return PaperLib
.getChunkAtAsync(BukkitUtil.getWorld(world), chunkLoc.getX(), chunkLoc.getZ(), force);
} }
} }

View File

@ -98,7 +98,6 @@ import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.IntConsumer; import java.util.function.IntConsumer;
@ -108,8 +107,7 @@ import java.util.stream.Stream;
@Singleton @Singleton
public class BukkitUtil extends WorldUtil { public class BukkitUtil extends WorldUtil {
private static final Logger logger = private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitUtil.class.getSimpleName());
LoggerFactory.getLogger("P2/" + BukkitUtil.class.getSimpleName());
private final Collection<BlockType> tileEntityTypes = new HashSet<>(); private final Collection<BlockType> tileEntityTypes = new HashSet<>();
/** /**
@ -131,8 +129,8 @@ public class BukkitUtil extends WorldUtil {
* @return PlotSquared location * @return PlotSquared location
*/ */
@Nonnull public static Location adapt(@Nonnull final org.bukkit.Location location) { @Nonnull public static Location adapt(@Nonnull final org.bukkit.Location location) {
return Location.at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), return Location
MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), .at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()),
MathMan.roundInt(location.getZ())); MathMan.roundInt(location.getZ()));
} }
@ -144,8 +142,8 @@ public class BukkitUtil extends WorldUtil {
* @return PlotSquared location * @return PlotSquared location
*/ */
@Nonnull public static Location adaptComplete(@Nonnull final org.bukkit.Location location) { @Nonnull public static Location adaptComplete(@Nonnull final org.bukkit.Location location) {
return Location.at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), return Location
MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), .at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()),
MathMan.roundInt(location.getZ()), location.getYaw(), location.getPitch()); MathMan.roundInt(location.getZ()), location.getYaw(), location.getPitch());
} }
@ -157,8 +155,7 @@ public class BukkitUtil extends WorldUtil {
* @return Bukkit location * @return Bukkit location
*/ */
@Nonnull public static org.bukkit.Location adapt(@Nonnull final Location location) { @Nonnull public static org.bukkit.Location adapt(@Nonnull final Location location) {
return new org.bukkit.Location((World) location.getWorld().getPlatformWorld(), return new org.bukkit.Location((World) location.getWorld().getPlatformWorld(), location.getX(), location.getY(), location.getZ());
location.getX(), location.getY(), location.getZ());
} }
/** /**
@ -171,30 +168,24 @@ public class BukkitUtil extends WorldUtil {
return Bukkit.getWorld(string); return Bukkit.getWorld(string);
} }
private static void ensureLoaded(@Nonnull final String world, final int x, final int z, private static void ensureLoaded(@Nonnull final String world, final int x, final int z, @Nonnull final Consumer<Chunk> chunkConsumer) {
@Nonnull final Consumer<Chunk> chunkConsumer) {
PaperLib.getChunkAtAsync(Objects.requireNonNull(getWorld(world)), x >> 4, z >> 4, true) PaperLib.getChunkAtAsync(Objects.requireNonNull(getWorld(world)), x >> 4, z >> 4, true)
.thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); .thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk));
} }
private static void ensureLoaded(@Nonnull final Location location, private static void ensureLoaded(@Nonnull final Location location, @Nonnull final Consumer<Chunk> chunkConsumer) {
@Nonnull final Consumer<Chunk> chunkConsumer) { PaperLib.getChunkAtAsync(adapt(location), true).thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk));
PaperLib.getChunkAtAsync(adapt(location), true)
.thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk));
} }
private static <T> void ensureMainThread(@Nonnull final Consumer<T> consumer, private static <T> void ensureMainThread(@Nonnull final Consumer<T> consumer, @Nonnull final T value) {
@Nonnull final T value) {
if (Bukkit.isPrimaryThread()) { if (Bukkit.isPrimaryThread()) {
consumer.accept(value); consumer.accept(value);
} else { } else {
Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> consumer.accept(value));
() -> consumer.accept(value));
} }
} }
@Override public boolean isBlockSame(@Nonnull final BlockState block1, @Override public boolean isBlockSame(@Nonnull final BlockState block1, @Nonnull final BlockState block2) {
@Nonnull final BlockState block2) {
if (block1.equals(block2)) { if (block1.equals(block2)) {
return true; return true;
} }
@ -207,19 +198,15 @@ public class BukkitUtil extends WorldUtil {
return getWorld(worldName) != null; return getWorld(worldName) != null;
} }
@Override public void getBiome(@Nonnull final String world, final int x, final int z, @Override public void getBiome(@Nonnull final String world, final int x, final int z, @Nonnull final Consumer<BiomeType> result) {
@Nonnull final Consumer<BiomeType> result) { ensureLoaded(world, x, z, chunk -> result.accept(BukkitAdapter.adapt(getWorld(world).getBiome(x, z))));
ensureLoaded(world, x, z,
chunk -> result.accept(BukkitAdapter.adapt(getWorld(world).getBiome(x, z))));
} }
@Override @Nonnull @Override @Nonnull public BiomeType getBiomeSynchronous(@Nonnull final String world, final int x, final int z) {
public BiomeType getBiomeSynchronous(@Nonnull final String world, final int x, final int z) {
return BukkitAdapter.adapt(Objects.requireNonNull(getWorld(world)).getBiome(x, z)); return BukkitAdapter.adapt(Objects.requireNonNull(getWorld(world)).getBiome(x, z));
} }
@Override public void getHighestBlock(@Nonnull final String world, final int x, final int z, @Override public void getHighestBlock(@Nonnull final String world, final int x, final int z, @Nonnull final IntConsumer result) {
@Nonnull final IntConsumer result) {
ensureLoaded(world, x, z, chunk -> { ensureLoaded(world, x, z, chunk -> {
final World bukkitWorld = Objects.requireNonNull(getWorld(world)); final World bukkitWorld = Objects.requireNonNull(getWorld(world));
// Skip top and bottom block // Skip top and bottom block
@ -245,8 +232,7 @@ public class BukkitUtil extends WorldUtil {
}); });
} }
@Override @Nonnegative @Override @Nonnegative public int getHighestBlockSynchronous(@Nonnull final String world, final int x, final int z) {
public int getHighestBlockSynchronous(@Nonnull final String world, final int x, final int z) {
final World bukkitWorld = Objects.requireNonNull(getWorld(world)); final World bukkitWorld = Objects.requireNonNull(getWorld(world));
// Skip top and bottom block // Skip top and bottom block
int air = 1; int air = 1;
@ -269,8 +255,7 @@ public class BukkitUtil extends WorldUtil {
} }
@Override @Nonnull public String[] getSignSynchronous(@Nonnull final Location location) { @Override @Nonnull public String[] getSignSynchronous(@Nonnull final Location location) {
Block block = Objects.requireNonNull(getWorld(location.getWorldName())) Block block = Objects.requireNonNull(getWorld(location.getWorldName())).getBlockAt(location.getX(), location.getY(), location.getZ());
.getBlockAt(location.getX(), location.getY(), location.getZ());
try { try {
return TaskManager.getPlatformImplementation().sync(() -> { return TaskManager.getPlatformImplementation().sync(() -> {
if (block.getState() instanceof Sign) { if (block.getState() instanceof Sign) {
@ -287,9 +272,7 @@ public class BukkitUtil extends WorldUtil {
@Override @Nonnull public Location getSpawn(@Nonnull final String world) { @Override @Nonnull public Location getSpawn(@Nonnull final String world) {
final org.bukkit.Location temp = getWorld(world).getSpawnLocation(); final org.bukkit.Location temp = getWorld(world).getSpawnLocation();
return Location return Location.at(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch());
.at(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(),
temp.getPitch());
} }
@Override public void setSpawn(@Nonnull final Location location) { @Override public void setSpawn(@Nonnull final Location location) {
@ -307,8 +290,7 @@ public class BukkitUtil extends WorldUtil {
} }
@Override @SuppressWarnings("deprecation") @Override @SuppressWarnings("deprecation")
public void setSign(@Nonnull final String worldName, final int x, final int y, final int z, public void setSign(@Nonnull final String worldName, final int x, final int y, final int z, @Nonnull final String[] lines) {
@Nonnull final String[] lines) {
ensureLoaded(worldName, x, z, chunk -> { ensureLoaded(worldName, x, z, chunk -> {
final World world = getWorld(worldName); final World world = getWorld(worldName);
final Block block = world.getBlockAt(x, y, z); final Block block = world.getBlockAt(x, y, z);
@ -346,25 +328,20 @@ public class BukkitUtil extends WorldUtil {
}); });
} }
@Override @Nonnull @Override @Nonnull public StringComparison<BlockState>.ComparisonResult getClosestBlock(@Nonnull String name) {
public StringComparison<BlockState>.ComparisonResult getClosestBlock(@Nonnull String name) {
BlockState state = BlockUtil.get(name); BlockState state = BlockUtil.get(name);
return new StringComparison<BlockState>().new ComparisonResult(1, state); return new StringComparison<BlockState>().new ComparisonResult(1, state);
} }
@Override @Override public void setBiomes(@Nonnull final String worldName, @Nonnull final CuboidRegion region, @Nonnull final BiomeType biomeType) {
public void setBiomes(@Nonnull final String worldName, @Nonnull final CuboidRegion region,
@Nonnull final BiomeType biomeType) {
final World world = getWorld(worldName); final World world = getWorld(worldName);
if (world == null) { if (world == null) {
logger.warn("[P2] An error occured while setting the biome because the world was null", logger.warn("[P2] An error occured while setting the biome because the world was null", new RuntimeException());
new RuntimeException());
return; return;
} }
final Biome biome = BukkitAdapter.adapt(biomeType); final Biome biome = BukkitAdapter.adapt(biomeType);
for (int x = region.getMinimumPoint().getX(); x <= region.getMaximumPoint().getX(); x++) { for (int x = region.getMinimumPoint().getX(); x <= region.getMaximumPoint().getX(); x++) {
for (int z = region.getMinimumPoint().getZ(); for (int z = region.getMinimumPoint().getZ(); z <= region.getMaximumPoint().getZ(); z++) {
z <= region.getMaximumPoint().getZ(); z++) {
if (world.getBiome(x, z) != biome) { if (world.getBiome(x, z) != biome) {
world.setBiome(x, z, biome); world.setBiome(x, z, biome);
} }
@ -372,8 +349,7 @@ public class BukkitUtil extends WorldUtil {
} }
} }
@Override @Nonnull @Override @Nonnull public com.sk89q.worldedit.world.World getWeWorld(@Nonnull final String world) {
public com.sk89q.worldedit.world.World getWeWorld(@Nonnull final String world) {
return new BukkitWorld(Bukkit.getWorld(world)); return new BukkitWorld(Bukkit.getWorld(world));
} }
@ -381,21 +357,17 @@ public class BukkitUtil extends WorldUtil {
Bukkit.getWorld(world).refreshChunk(x, z); Bukkit.getWorld(world).refreshChunk(x, z);
} }
@Override public void getBlock(@Nonnull final Location location, @Override public void getBlock(@Nonnull final Location location, @Nonnull final Consumer<BlockState> result) {
@Nonnull final Consumer<BlockState> result) {
ensureLoaded(location, chunk -> { ensureLoaded(location, chunk -> {
final World world = getWorld(location.getWorldName()); final World world = getWorld(location.getWorldName());
final Block block = Objects.requireNonNull(world) final Block block = Objects.requireNonNull(world).getBlockAt(location.getX(), location.getY(), location.getZ());
.getBlockAt(location.getX(), location.getY(), location.getZ()); result.accept(Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())).getDefaultState());
result.accept(Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType()))
.getDefaultState());
}); });
} }
@Override @Nonnull public BlockState getBlockSynchronous(@Nonnull final Location location) { @Override @Nonnull public BlockState getBlockSynchronous(@Nonnull final Location location) {
final World world = getWorld(location.getWorldName()); final World world = getWorld(location.getWorldName());
final Block block = Objects.requireNonNull(world) final Block block = Objects.requireNonNull(world).getBlockAt(location.getX(), location.getY(), location.getZ());
.getBlockAt(location.getX(), location.getY(), location.getZ());
return Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())).getDefaultState(); return Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())).getDefaultState();
} }
@ -407,18 +379,15 @@ public class BukkitUtil extends WorldUtil {
return Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).getFoodLevel(); return Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).getFoodLevel();
} }
@Override @Override public void setHealth(@Nonnull final PlotPlayer<?> player, @Nonnegative final double health) {
public void setHealth(@Nonnull final PlotPlayer<?> player, @Nonnegative final double health) {
Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).setHealth(health); Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).setHealth(health);
} }
@Override public void setFoodLevel(@Nonnull final PlotPlayer<?> player, @Override public void setFoodLevel(@Nonnull final PlotPlayer<?> player, @Nonnegative final int foodLevel) {
@Nonnegative final int foodLevel) {
Bukkit.getPlayer(player.getUUID()).setFoodLevel(foodLevel); Bukkit.getPlayer(player.getUUID()).setFoodLevel(foodLevel);
} }
@Override @Nonnull public Set<com.sk89q.worldedit.world.entity.EntityType> getTypesInCategory( @Override @Nonnull public Set<com.sk89q.worldedit.world.entity.EntityType> getTypesInCategory(@Nonnull final String category) {
@Nonnull final String category) {
final Collection<Class<?>> allowedInterfaces = new HashSet<>(); final Collection<Class<?>> allowedInterfaces = new HashSet<>();
switch (category) { switch (category) {
case "animal": { case "animal": {
@ -507,22 +476,17 @@ public class BukkitUtil extends WorldUtil {
tileEntityTypes.addAll(BlockCategories.FLOWER_POTS.getAll()); tileEntityTypes.addAll(BlockCategories.FLOWER_POTS.getAll());
// Individual Types // Individual Types
// Add these from strings // Add these from strings
Stream.of("barrel", "beacon", "beehive", "bee_nest", "bell", "blast_furnace", Stream.of("barrel", "beacon", "beehive", "bee_nest", "bell", "blast_furnace", "brewing_stand", "campfire", "chest", "ender_chest",
"brewing_stand", "campfire", "chest", "ender_chest", "trapped_chest", "trapped_chest", "command_block", "end_gateway", "hopper", "jigsaw", "jubekox", "lectern", "note_block", "black_shulker_box",
"command_block", "end_gateway", "hopper", "jigsaw", "jubekox", "lectern", "blue_shulker_box", "brown_shulker_box", "cyan_shulker_box", "gray_shulker_box", "green_shulker_box", "light_blue_shulker_box",
"note_block", "black_shulker_box", "blue_shulker_box", "brown_shulker_box", "light_gray_shulker_box", "lime_shulker_box", "magenta_shulker_box", "orange_shulker_box", "pink_shulker_box", "purple_shulker_box",
"cyan_shulker_box", "gray_shulker_box", "green_shulker_box", "red_shulker_box", "shulker_box", "white_shulker_box", "yellow_shulker_box", "smoker", "structure_block", "structure_void")
"light_blue_shulker_box", "light_gray_shulker_box", "lime_shulker_box",
"magenta_shulker_box", "orange_shulker_box", "pink_shulker_box",
"purple_shulker_box", "red_shulker_box", "shulker_box", "white_shulker_box",
"yellow_shulker_box", "smoker", "structure_block", "structure_void")
.map(BlockTypes::get).filter(Objects::nonNull).forEach(tileEntityTypes::add); .map(BlockTypes::get).filter(Objects::nonNull).forEach(tileEntityTypes::add);
} }
return this.tileEntityTypes; return this.tileEntityTypes;
} }
@Override @Nonnegative @Override @Nonnegative public int getTileEntityCount(@Nonnull final String world, @Nonnull final BlockVector2 chunk) {
public int getTileEntityCount(@Nonnull final String world, @Nonnull final BlockVector2 chunk) {
return Objects.requireNonNull(getWorld(world)). return Objects.requireNonNull(getWorld(world)).
getChunkAt(chunk.getBlockX(), chunk.getBlockZ()).getTileEntities().length; getChunkAt(chunk.getBlockX(), chunk.getBlockZ()).getTileEntities().length;
} }
@ -538,12 +502,9 @@ public class BukkitUtil extends WorldUtil {
final Semaphore semaphore = new Semaphore(1); final Semaphore semaphore = new Semaphore(1);
try { try {
semaphore.acquire(); semaphore.acquire();
Bukkit.getScheduler() Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> {
.runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> { for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)).getLoadedChunks()) {
for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)) BlockVector2 loc = BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5);
.getLoadedChunks()) {
BlockVector2 loc =
BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5);
chunks.add(loc); chunks.add(loc);
} }
semaphore.release(); semaphore.release();

View File

@ -62,20 +62,17 @@ import java.util.stream.Collectors;
public class ComponentPresetManager { public class ComponentPresetManager {
private static final Logger logger = private static final Logger logger = LoggerFactory.getLogger("P2/" + ComponentPresetManager.class.getSimpleName());
LoggerFactory.getLogger("P2/" + ComponentPresetManager.class.getSimpleName());
private final List<ComponentPreset> presets; private final List<ComponentPreset> presets;
private final String guiName; private final String guiName;
private final EconHandler econHandler; private final EconHandler econHandler;
private final InventoryUtil inventoryUtil; private final InventoryUtil inventoryUtil;
@Inject public ComponentPresetManager(@Nullable final EconHandler econHandler, @Inject public ComponentPresetManager(@Nullable final EconHandler econHandler, @Nonnull final InventoryUtil inventoryUtil) {
@Nonnull final InventoryUtil inventoryUtil) {
this.econHandler = econHandler; this.econHandler = econHandler;
this.inventoryUtil = inventoryUtil; this.inventoryUtil = inventoryUtil;
final File file = new File(Objects.requireNonNull(PlotSquared.platform()).getDirectory(), final File file = new File(Objects.requireNonNull(PlotSquared.platform()).getDirectory(), "components.yml");
"components.yml");
if (!file.exists()) { if (!file.exists()) {
boolean created = false; boolean created = false;
try { try {
@ -106,16 +103,13 @@ public class ComponentPresetManager {
this.guiName = yamlConfiguration.getString("title", "&6Plot Components"); this.guiName = yamlConfiguration.getString("title", "&6Plot Components");
if (yamlConfiguration.contains("presets")) { if (yamlConfiguration.contains("presets")) {
this.presets = this.presets = yamlConfiguration.getMapList("presets").stream().map(o -> (Map<String, Object>) o).map(ComponentPreset::deserialize)
yamlConfiguration.getMapList("presets").stream().map(o -> (Map<String, Object>) o) .collect(Collectors.toList());
.map(ComponentPreset::deserialize).collect(Collectors.toList());
} else { } else {
final List<ComponentPreset> defaultPreset = Collections.singletonList( final List<ComponentPreset> defaultPreset = Collections.singletonList(
new ComponentPreset(ClassicPlotManagerComponent.FLOOR, "##wool", 0, "", new ComponentPreset(ClassicPlotManagerComponent.FLOOR, "##wool", 0, "", "&6D&ai&cs&ec&bo &2F&3l&do&9o&4r",
"&6D&ai&cs&ec&bo &2F&3l&do&9o&4r", Arrays.asList("&6Spice up your plot floor"), Arrays.asList("&6Spice up your plot floor"), ItemTypes.YELLOW_WOOL));
ItemTypes.YELLOW_WOOL)); yamlConfiguration.set("presets", defaultPreset.stream().map(ComponentPreset::serialize).collect(Collectors.toList()));
yamlConfiguration.set("presets", defaultPreset.stream().map(ComponentPreset::serialize)
.collect(Collectors.toList()));
try { try {
yamlConfiguration.save(file); yamlConfiguration.save(file);
} catch (final IOException e) { } catch (final IOException e) {
@ -143,23 +137,20 @@ public class ComponentPresetManager {
} else if (!plot.hasOwner()) { } else if (!plot.hasOwner()) {
Captions.PLOT_UNOWNED.send(player); Captions.PLOT_UNOWNED.send(player);
return null; return null;
} else if (!plot.isOwner(player.getUUID()) && !plot.getTrusted() } else if (!plot.isOwner(player.getUUID()) && !plot.getTrusted().contains(player.getUUID())) {
.contains(player.getUUID())) {
Captions.NO_PLOT_PERMS.send(player); Captions.NO_PLOT_PERMS.send(player);
return null; return null;
} }
final List<ComponentPreset> allowedPresets = new ArrayList<>(this.presets.size()); final List<ComponentPreset> allowedPresets = new ArrayList<>(this.presets.size());
for (final ComponentPreset componentPreset : this.presets) { for (final ComponentPreset componentPreset : this.presets) {
if (!componentPreset.getPermission().isEmpty() && !Permissions if (!componentPreset.getPermission().isEmpty() && !Permissions.hasPermission(player, componentPreset.getPermission())) {
.hasPermission(player, componentPreset.getPermission())) {
continue; continue;
} }
allowedPresets.add(componentPreset); allowedPresets.add(componentPreset);
} }
final int size = (int) Math.ceil((double) allowedPresets.size() / 9.0D); final int size = (int) Math.ceil((double) allowedPresets.size() / 9.0D);
final PlotInventory plotInventory = final PlotInventory plotInventory = new PlotInventory(this.inventoryUtil, player, size, this.guiName) {
new PlotInventory(this.inventoryUtil, player, size, this.guiName) {
@Override public boolean onClick(final int index) { @Override public boolean onClick(final int index) {
if (!player.getCurrentPlot().equals(plot)) { if (!player.getCurrentPlot().equals(plot)) {
return false; return false;
@ -179,15 +170,13 @@ public class ComponentPresetManager {
return false; return false;
} }
final Pattern pattern = final Pattern pattern = PatternUtil.parse(null, componentPreset.getPattern(), false);
PatternUtil.parse(null, componentPreset.getPattern(), false);
if (pattern == null) { if (pattern == null) {
Captions.PRESET_INVALID.send(player); Captions.PRESET_INVALID.send(player);
return false; return false;
} }
if (componentPreset.getCost() > 0.0D && econHandler != null && plot.getArea() if (componentPreset.getCost() > 0.0D && econHandler != null && plot.getArea().useEconomy()) {
.useEconomy()) {
if (econHandler.getMoney(player) < componentPreset.getCost()) { if (econHandler.getMoney(player) < componentPreset.getCost()) {
Captions.PRESET_CANNOT_AFFORD.send(player); Captions.PRESET_CANNOT_AFFORD.send(player);
return false; return false;
@ -201,8 +190,7 @@ public class ComponentPresetManager {
plot.addRunning(); plot.addRunning();
QueueCoordinator queue = plot.getArea().getQueue(); QueueCoordinator queue = plot.getArea().getQueue();
for (Plot current : plot.getConnectedPlots()) { for (Plot current : plot.getConnectedPlots()) {
current.setComponent(componentPreset.getComponent().name(), pattern, current.setComponent(componentPreset.getComponent().name(), pattern, queue);
queue);
} }
queue.setCompleteTask(plot::removeRunning); queue.setCompleteTask(plot::removeRunning);
queue.enqueue(); queue.enqueue();
@ -217,19 +205,16 @@ public class ComponentPresetManager {
final ComponentPreset preset = allowedPresets.get(i); final ComponentPreset preset = allowedPresets.get(i);
final List<String> lore = new ArrayList<>(); final List<String> lore = new ArrayList<>();
if (preset.getCost() > 0 && this.econHandler != null && plot.getArea().useEconomy()) { if (preset.getCost() > 0 && this.econHandler != null && plot.getArea().useEconomy()) {
lore.add(Captions.PRESET_LORE_COST.getTranslated() lore.add(Captions.PRESET_LORE_COST.getTranslated().replace("%cost%", String.format("%.2f", preset.getCost())));
.replace("%cost%", String.format("%.2f", preset.getCost())));
} }
lore.add(Captions.PRESET_LORE_COMPONENT.getTranslated() lore.add(Captions.PRESET_LORE_COMPONENT.getTranslated().replace("%component%", preset.getComponent().name().toLowerCase()));
.replace("%component%", preset.getComponent().name().toLowerCase()));
lore.removeIf(String::isEmpty); lore.removeIf(String::isEmpty);
if (!lore.isEmpty()) { if (!lore.isEmpty()) {
lore.add("&6"); lore.add("&6");
} }
lore.addAll(preset.getDescription()); lore.addAll(preset.getDescription());
plotInventory.setItem(i, plotInventory.setItem(i,
new PlotItemStack(preset.getIcon().getId().replace("minecraft:", ""), 1, new PlotItemStack(preset.getIcon().getId().replace("minecraft:", ""), 1, preset.getDisplayName(), lore.toArray(new String[0])));
preset.getDisplayName(), lore.toArray(new String[0])));
} }
return plotInventory; return plotInventory;

View File

@ -54,8 +54,11 @@ public class AugmentedUtils {
enabled = true; enabled = true;
} }
public static boolean generate(@Nullable Object chunkObject, @Nonnull final String world, public static boolean generate(@Nullable Object chunkObject,
final int chunkX, final int chunkZ, QueueCoordinator queue) { @Nonnull final String world,
final int chunkX,
final int chunkZ,
QueueCoordinator queue) {
if (!enabled) { if (!enabled) {
return false; return false;
} }
@ -67,8 +70,7 @@ public class AugmentedUtils {
// entire chunk // entire chunk
CuboidRegion region = RegionUtil.createRegion(blockX, blockX + 15, blockZ, blockZ + 15); CuboidRegion region = RegionUtil.createRegion(blockX, blockX + 15, blockZ, blockZ + 15);
// Query for plot areas in the chunk // Query for plot areas in the chunk
final Set<PlotArea> areas = final Set<PlotArea> areas = PlotSquared.get().getPlotAreaManager().getPlotAreasSet(world, region);
PlotSquared.get().getPlotAreaManager().getPlotAreasSet(world, region);
if (areas.isEmpty()) { if (areas.isEmpty()) {
return false; return false;
} }
@ -89,8 +91,7 @@ public class AugmentedUtils {
// Mask // Mask
if (queue == null) { if (queue == null) {
enqueue = true; enqueue = true;
queue = PlotSquared.platform().getGlobalBlockQueue() queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world));
.getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world));
if (chunkObject != null) { if (chunkObject != null) {
queue.setChunkObject(chunkObject); queue.setChunkObject(chunkObject);
} }
@ -138,8 +139,7 @@ public class AugmentedUtils {
continue; continue;
} }
generationResult = true; generationResult = true;
secondaryMask = new LocationOffsetDelegateQueueCoordinator(canPlace, blockX, blockZ, secondaryMask = new LocationOffsetDelegateQueueCoordinator(canPlace, blockX, blockZ, primaryMask);
primaryMask);
} else { } else {
secondaryMask = primaryMask; secondaryMask = primaryMask;
for (int x = relativeBottomX; x <= relativeTopX; x++) { for (int x = relativeBottomX; x <= relativeTopX; x++) {
@ -159,8 +159,7 @@ public class AugmentedUtils {
} }
ScopedQueueCoordinator scoped = ScopedQueueCoordinator scoped =
new ScopedQueueCoordinator(secondaryMask, Location.at(world, blockX, 0, blockZ), new ScopedQueueCoordinator(secondaryMask, Location.at(world, blockX, 0, blockZ), Location.at(world, blockX + 15, 255, blockZ + 15));
Location.at(world, blockX + 15, 255, blockZ + 15));
generator.generateChunk(scoped, area); generator.generateChunk(scoped, area);
generator.populateChunk(scoped, area); generator.populateChunk(scoped, area);
} }

View File

@ -40,6 +40,7 @@ import com.plotsquared.core.util.task.TaskManager;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypes;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -54,17 +55,15 @@ public class ClassicPlotManager extends SquarePlotManager {
private final ClassicPlotWorld classicPlotWorld; private final ClassicPlotWorld classicPlotWorld;
private final RegionManager regionManager; private final RegionManager regionManager;
public ClassicPlotManager(@Nonnull final ClassicPlotWorld classicPlotWorld, public ClassicPlotManager(@Nonnull final ClassicPlotWorld classicPlotWorld, @Nonnull final RegionManager regionManager) {
@Nonnull final RegionManager regionManager) {
super(classicPlotWorld, regionManager); super(classicPlotWorld, regionManager);
this.classicPlotWorld = classicPlotWorld; this.classicPlotWorld = classicPlotWorld;
this.regionManager = regionManager; this.regionManager = regionManager;
} }
@Override public boolean setComponent(PlotId plotId, String component, Pattern blocks, @Override
@Nullable QueueCoordinator queue) { public boolean setComponent(@NotNull PlotId plotId, @NotNull String component, @NotNull Pattern blocks, @Nullable QueueCoordinator queue) {
final Optional<ClassicPlotManagerComponent> componentOptional = final Optional<ClassicPlotManagerComponent> componentOptional = ClassicPlotManagerComponent.fromString(component);
ClassicPlotManagerComponent.fromString(component);
if (componentOptional.isPresent()) { if (componentOptional.isPresent()) {
switch (componentOptional.get()) { switch (componentOptional.get()) {
case FLOOR: case FLOOR:
@ -88,55 +87,50 @@ public class ClassicPlotManager extends SquarePlotManager {
return false; return false;
} }
@Override public boolean unClaimPlot(Plot plot, @Nullable Runnable whenDone, @Override public boolean unClaimPlot(@NotNull Plot plot, @Nullable Runnable whenDone, @Nullable QueueCoordinator queue) {
@Nullable QueueCoordinator queue) {
setWallFilling(plot.getId(), classicPlotWorld.WALL_FILLING.toPattern(), queue); setWallFilling(plot.getId(), classicPlotWorld.WALL_FILLING.toPattern(), queue);
if (!classicPlotWorld.WALL_BLOCK.isAir() || !classicPlotWorld.WALL_BLOCK if (!classicPlotWorld.WALL_BLOCK.isAir() || !classicPlotWorld.WALL_BLOCK.equals(classicPlotWorld.CLAIMED_WALL_BLOCK)) {
.equals(classicPlotWorld.CLAIMED_WALL_BLOCK)) {
setWall(plot.getId(), classicPlotWorld.WALL_BLOCK.toPattern(), queue); setWall(plot.getId(), classicPlotWorld.WALL_BLOCK.toPattern(), queue);
} }
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
return true; return true;
} }
public boolean setFloor(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { public boolean setFloor(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) {
Plot plot = classicPlotWorld.getPlotAbs(plotId);
if (plot != null && plot.isBasePlot()) {
return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks,
classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.PLOT_HEIGHT, queue);
}
return false;
}
public boolean setAll(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) {
Plot plot = classicPlotWorld.getPlotAbs(plotId); Plot plot = classicPlotWorld.getPlotAbs(plotId);
if (plot != null && plot.isBasePlot()) { if (plot != null && plot.isBasePlot()) {
return this.regionManager return this.regionManager
.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, getWorldHeight(), .setCuboids(classicPlotWorld, plot.getRegions(), blocks, classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.PLOT_HEIGHT, queue);
queue);
} }
return false; return false;
} }
public boolean setAir(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { public boolean setAll(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) {
Plot plot = classicPlotWorld.getPlotAbs(plotId); Plot plot = classicPlotWorld.getPlotAbs(plotId);
if (plot != null && plot.isBasePlot()) { if (plot != null && plot.isBasePlot()) {
return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, getWorldHeight(), queue);
classicPlotWorld.PLOT_HEIGHT + 1, getWorldHeight(), queue);
} }
return false; return false;
} }
public boolean setMain(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { public boolean setAir(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) {
Plot plot = classicPlotWorld.getPlotAbs(plotId);
if (plot != null && plot.isBasePlot()) {
return this.regionManager
.setCuboids(classicPlotWorld, plot.getRegions(), blocks, classicPlotWorld.PLOT_HEIGHT + 1, getWorldHeight(), queue);
}
return false;
}
public boolean setMain(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) {
Plot plot = classicPlotWorld.getPlotAbs(plotId); Plot plot = classicPlotWorld.getPlotAbs(plotId);
if (plot == null || plot.isBasePlot()) { if (plot == null || plot.isBasePlot()) {
return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, classicPlotWorld.PLOT_HEIGHT - 1, queue);
classicPlotWorld.PLOT_HEIGHT - 1, queue);
} }
return false; return false;
} }
public boolean setMiddle(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { public boolean setMiddle(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) {
Plot plot = classicPlotWorld.getPlotAbs(plotId); Plot plot = classicPlotWorld.getPlotAbs(plotId);
if (plot == null || !plot.isBasePlot()) { if (plot == null || !plot.isBasePlot()) {
return false; return false;
@ -155,7 +149,7 @@ public class ClassicPlotManager extends SquarePlotManager {
return !enqueue || queue.enqueue(); return !enqueue || queue.enqueue();
} }
public boolean setOutline(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { public boolean setOutline(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) {
if (classicPlotWorld.ROAD_WIDTH == 0) { if (classicPlotWorld.ROAD_WIDTH == 0) {
return false; return false;
} }
@ -214,19 +208,15 @@ public class ClassicPlotManager extends SquarePlotManager {
} }
if (plot.isBasePlot()) { if (plot.isBasePlot()) {
for (CuboidRegion region : plot.getRegions()) { for (CuboidRegion region : plot.getRegions()) {
Location pos1 = Location Location pos1 = Location.at(classicPlotWorld.getWorldName(), region.getMinimumPoint().getX(), maxY, region.getMinimumPoint().getZ());
.at(classicPlotWorld.getWorldName(), region.getMinimumPoint().getX(), maxY, Location pos2 = Location.at(classicPlotWorld.getWorldName(), region.getMaximumPoint().getX(), maxY, region.getMaximumPoint().getZ());
region.getMinimumPoint().getZ());
Location pos2 = Location
.at(classicPlotWorld.getWorldName(), region.getMaximumPoint().getX(), maxY,
region.getMaximumPoint().getZ());
queue.setCuboid(pos1, pos2, blocks); queue.setCuboid(pos1, pos2, blocks);
} }
} }
return !enqueue || queue.enqueue(); return !enqueue || queue.enqueue();
} }
public boolean setWallFilling(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { public boolean setWallFilling(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) {
if (classicPlotWorld.ROAD_WIDTH == 0) { if (classicPlotWorld.ROAD_WIDTH == 0) {
return false; return false;
} }
@ -240,9 +230,7 @@ public class ClassicPlotManager extends SquarePlotManager {
if (plot == null) { if (plot == null) {
return false; return false;
} }
Location bot = plot.getExtendedBottomAbs() Location bot = plot.getExtendedBottomAbs().subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1);
.subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0,
plot.getMerged(Direction.NORTH) ? 0 : 1);
Location top = plot.getExtendedTopAbs().add(1, 0, 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1);
boolean enqueue = false; boolean enqueue = false;
@ -269,8 +257,7 @@ public class ClassicPlotManager extends SquarePlotManager {
} }
if (!plot.getMerged(Direction.SOUTH)) { if (!plot.getMerged(Direction.SOUTH)) {
int z = top.getZ(); int z = top.getZ();
for (int x = bot.getX(); for (int x = bot.getX(); x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) {
x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) {
for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) { for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) {
queue.setBlock(x, y, z, blocks); queue.setBlock(x, y, z, blocks);
} }
@ -278,8 +265,7 @@ public class ClassicPlotManager extends SquarePlotManager {
} }
if (!plot.getMerged(Direction.EAST)) { if (!plot.getMerged(Direction.EAST)) {
int x = top.getX(); int x = top.getX();
for (int z = bot.getZ(); for (int z = bot.getZ(); z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) {
z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) {
for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) { for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) {
queue.setBlock(x, y, z, blocks); queue.setBlock(x, y, z, blocks);
} }
@ -288,7 +274,7 @@ public class ClassicPlotManager extends SquarePlotManager {
return !enqueue || queue.enqueue(); return !enqueue || queue.enqueue();
} }
public boolean setWall(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { public boolean setWall(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) {
if (classicPlotWorld.ROAD_WIDTH == 0) { if (classicPlotWorld.ROAD_WIDTH == 0) {
return false; return false;
} }
@ -302,9 +288,7 @@ public class ClassicPlotManager extends SquarePlotManager {
if (plot == null) { if (plot == null) {
return false; return false;
} }
Location bot = plot.getExtendedBottomAbs() Location bot = plot.getExtendedBottomAbs().subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1);
.subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0,
plot.getMerged(Direction.NORTH) ? 0 : 1);
Location top = plot.getExtendedTopAbs().add(1, 0, 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1);
boolean enqueue = false; boolean enqueue = false;
@ -328,15 +312,13 @@ public class ClassicPlotManager extends SquarePlotManager {
} }
if (!plot.getMerged(Direction.SOUTH)) { if (!plot.getMerged(Direction.SOUTH)) {
int z = top.getZ(); int z = top.getZ();
for (int x = bot.getX(); for (int x = bot.getX(); x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) {
x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) {
queue.setBlock(x, y, z, blocks); queue.setBlock(x, y, z, blocks);
} }
} }
if (!plot.getMerged(Direction.EAST)) { if (!plot.getMerged(Direction.EAST)) {
int x = top.getX(); int x = top.getX();
for (int z = bot.getZ(); for (int z = bot.getZ(); z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) {
z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) {
queue.setBlock(x, y, z, blocks); queue.setBlock(x, y, z, blocks);
} }
} }
@ -346,7 +328,7 @@ public class ClassicPlotManager extends SquarePlotManager {
/** /**
* PLOT MERGING. * PLOT MERGING.
*/ */
@Override public boolean createRoadEast(Plot plot, @Nullable QueueCoordinator queue) { @Override public boolean createRoadEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos1 = getPlotBottomLocAbs(plot.getId());
Location pos2 = getPlotTopLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId());
int sx = pos2.getX() + 1; int sx = pos2.getX() + 1;
@ -361,36 +343,25 @@ public class ClassicPlotManager extends SquarePlotManager {
} }
int maxY = getWorldHeight(); int maxY = getWorldHeight();
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, queue.setCuboid(
Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz + 1), Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex, maxY, ez - 1), Location.at(classicPlotWorld.getWorldName(), ex, maxY, ez - 1), BlockTypes.AIR.getDefaultState());
BlockTypes.AIR.getDefaultState()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 0, sz + 1), Location.at(classicPlotWorld.getWorldName(), ex, 0, ez - 1),
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 0, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex, 0, ez - 1),
BlockUtil.get((short) 7, (byte) 0)); BlockUtil.get((short) 7, (byte) 0));
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1), queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1),
Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT, ez - 1), Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern());
classicPlotWorld.WALL_FILLING.toPattern()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, sz + 1),
queue.setCuboid(Location Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, ez - 1), classicPlotWorld.WALL_BLOCK.toPattern());
.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, sz + 1),
Location
.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, ez - 1),
classicPlotWorld.WALL_BLOCK.toPattern());
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), ex, 1, sz + 1), queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), ex, 1, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT, ez - 1), Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern());
classicPlotWorld.WALL_FILLING.toPattern()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, sz + 1),
queue.setCuboid(Location Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, ez - 1), classicPlotWorld.WALL_BLOCK.toPattern());
.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, sz + 1), queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1),
Location Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern());
.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, ez - 1),
classicPlotWorld.WALL_BLOCK.toPattern());
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), Location
.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1),
classicPlotWorld.ROAD_BLOCK.toPattern());
return !enqueue || queue.enqueue(); return !enqueue || queue.enqueue();
} }
@Override public boolean createRoadSouth(Plot plot, @Nullable QueueCoordinator queue) { @Override public boolean createRoadSouth(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos1 = getPlotBottomLocAbs(plot.getId());
Location pos2 = getPlotTopLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId());
int sz = pos2.getZ() + 1; int sz = pos2.getZ() + 1;
@ -404,37 +375,26 @@ public class ClassicPlotManager extends SquarePlotManager {
enqueue = true; enqueue = true;
} }
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, queue.setCuboid(
Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location Location.at(classicPlotWorld.getWorldName(), sx + 1, Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz),
.at(classicPlotWorld.getWorldName(), ex - 1, Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.getPlotManager().getWorldHeight(), ez),
classicPlotWorld.getPlotManager().getWorldHeight(), ez),
BlockTypes.AIR.getDefaultState()); BlockTypes.AIR.getDefaultState());
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz), queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz), Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez),
Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez),
BlockUtil.get((short) 7, (byte) 0)); BlockUtil.get((short) 7, (byte) 0));
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz), queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz),
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, sz), Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, sz), classicPlotWorld.WALL_FILLING.toPattern());
classicPlotWorld.WALL_FILLING.toPattern()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, sz),
queue.setCuboid(Location Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, sz), classicPlotWorld.WALL_BLOCK.toPattern());
.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, sz),
Location
.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, sz),
classicPlotWorld.WALL_BLOCK.toPattern());
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, ez), queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, ez),
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, ez), Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, ez), classicPlotWorld.WALL_FILLING.toPattern());
classicPlotWorld.WALL_FILLING.toPattern()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, ez),
queue.setCuboid(Location Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, ez), classicPlotWorld.WALL_BLOCK.toPattern());
.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, ez), queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1),
Location Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern());
.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, ez),
classicPlotWorld.WALL_BLOCK.toPattern());
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), Location
.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1),
classicPlotWorld.ROAD_BLOCK.toPattern());
return !enqueue || queue.enqueue(); return !enqueue || queue.enqueue();
} }
@Override public boolean createRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { @Override public boolean createRoadSouthEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
Location pos2 = getPlotTopLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId());
int sx = pos2.getX() + 1; int sx = pos2.getX() + 1;
int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int ex = sx + classicPlotWorld.ROAD_WIDTH - 1;
@ -447,21 +407,17 @@ public class ClassicPlotManager extends SquarePlotManager {
enqueue = true; enqueue = true;
} }
queue.setCuboid(Location queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.ROAD_HEIGHT + 1, sz + 1),
.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.ROAD_HEIGHT + 1, sz + 1), Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.getPlotManager().getWorldHeight(), ez - 1),
Location.at(classicPlotWorld.getWorldName(), ex - 1,
classicPlotWorld.getPlotManager().getWorldHeight(), ez - 1),
BlockTypes.AIR.getDefaultState()); BlockTypes.AIR.getDefaultState());
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz + 1), queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez - 1), Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez - 1), BlockUtil.get((short) 7, (byte) 0));
BlockUtil.get((short) 7, (byte) 0)); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1),
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), Location Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern());
.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1),
classicPlotWorld.ROAD_BLOCK.toPattern());
return !enqueue || queue.enqueue(); return !enqueue || queue.enqueue();
} }
@Override public boolean removeRoadEast(Plot plot, @Nullable QueueCoordinator queue) { @Override public boolean removeRoadEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos1 = getPlotBottomLocAbs(plot.getId());
Location pos2 = getPlotTopLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId());
int sx = pos2.getX() + 1; int sx = pos2.getX() + 1;
@ -475,22 +431,18 @@ public class ClassicPlotManager extends SquarePlotManager {
enqueue = true; enqueue = true;
} }
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, queue
Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location .setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz),
.at(classicPlotWorld.getWorldName(), ex, Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez),
classicPlotWorld.getPlotManager().getWorldHeight(), ez),
BlockTypes.AIR.getDefaultState()); BlockTypes.AIR.getDefaultState());
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1), Location queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1),
.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez - 1), Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez - 1), classicPlotWorld.MAIN_BLOCK.toPattern());
classicPlotWorld.MAIN_BLOCK.toPattern()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz + 1),
queue.setCuboid( Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez - 1), classicPlotWorld.TOP_BLOCK.toPattern());
Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez - 1),
classicPlotWorld.TOP_BLOCK.toPattern());
return !enqueue || queue.enqueue(); return !enqueue || queue.enqueue();
} }
@Override public boolean removeRoadSouth(Plot plot, @Nullable QueueCoordinator queue) { @Override public boolean removeRoadSouth(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos1 = getPlotBottomLocAbs(plot.getId());
Location pos2 = getPlotTopLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId());
int sz = pos2.getZ() + 1; int sz = pos2.getZ() + 1;
@ -504,22 +456,18 @@ public class ClassicPlotManager extends SquarePlotManager {
enqueue = true; enqueue = true;
} }
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, queue
Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location .setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz),
.at(classicPlotWorld.getWorldName(), ex, Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez),
classicPlotWorld.getPlotManager().getWorldHeight(), ez),
BlockTypes.AIR.getDefaultState()); BlockTypes.AIR.getDefaultState());
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz), Location queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz),
.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT - 1, ez), Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT - 1, ez), classicPlotWorld.MAIN_BLOCK.toPattern());
classicPlotWorld.MAIN_BLOCK.toPattern()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.PLOT_HEIGHT, sz),
queue.setCuboid( Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT, ez), classicPlotWorld.TOP_BLOCK.toPattern());
Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.PLOT_HEIGHT, sz),
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT, ez),
classicPlotWorld.TOP_BLOCK.toPattern());
return !enqueue || queue.enqueue(); return !enqueue || queue.enqueue();
} }
@Override public boolean removeRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { @Override public boolean removeRoadSouthEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
Location location = getPlotTopLocAbs(plot.getId()); Location location = getPlotTopLocAbs(plot.getId());
int sx = location.getX() + 1; int sx = location.getX() + 1;
int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int ex = sx + classicPlotWorld.ROAD_WIDTH - 1;
@ -532,18 +480,14 @@ public class ClassicPlotManager extends SquarePlotManager {
enqueue = true; enqueue = true;
} }
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, queue
Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location .setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz),
.at(classicPlotWorld.getWorldName(), ex, Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez),
classicPlotWorld.getPlotManager().getWorldHeight(), ez),
BlockTypes.AIR.getDefaultState()); BlockTypes.AIR.getDefaultState());
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz), queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz),
Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez), Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez), classicPlotWorld.MAIN_BLOCK.toPattern());
classicPlotWorld.MAIN_BLOCK.toPattern()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz),
queue.setCuboid( Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez), classicPlotWorld.TOP_BLOCK.toPattern());
Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz),
Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez),
classicPlotWorld.TOP_BLOCK.toPattern());
return !enqueue || queue.enqueue(); return !enqueue || queue.enqueue();
} }
@ -552,8 +496,7 @@ public class ClassicPlotManager extends SquarePlotManager {
* *
* @return false if part of the merge failed, otherwise true if successful. * @return false if part of the merge failed, otherwise true if successful.
*/ */
@Override public boolean finishPlotMerge(List<PlotId> plotIds, @Override public boolean finishPlotMerge(@NotNull List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
@Nullable QueueCoordinator queue) {
final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK;
if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) {
for (PlotId plotId : plotIds) { for (PlotId plotId : plotIds) {
@ -569,8 +512,7 @@ public class ClassicPlotManager extends SquarePlotManager {
return true; return true;
} }
@Override @Override public boolean finishPlotUnlink(@NotNull List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
public boolean finishPlotUnlink(List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK;
if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) {
for (PlotId id : plotIds) { for (PlotId id : plotIds) {
@ -580,17 +522,15 @@ public class ClassicPlotManager extends SquarePlotManager {
return true; // return false if unlink has been denied return true; // return false if unlink has been denied
} }
@Override @Override public boolean startPlotMerge(@NotNull List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
public boolean startPlotMerge(List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
return true; return true;
} }
@Override @Override public boolean startPlotUnlink(@NotNull List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
public boolean startPlotUnlink(List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
return true; return true;
} }
@Override public boolean claimPlot(Plot plot, @Nullable QueueCoordinator queue) { @Override public boolean claimPlot(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK;
if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) {
return setWall(plot.getId(), claim.toPattern(), queue); return setWall(plot.getId(), claim.toPattern(), queue);
@ -598,7 +538,7 @@ public class ClassicPlotManager extends SquarePlotManager {
return true; return true;
} }
@Override public String[] getPlotComponents(PlotId plotId) { @Override public String[] getPlotComponents(@NotNull PlotId plotId) {
return ClassicPlotManagerComponent.stringValues(); return ClassicPlotManagerComponent.stringValues();
} }
@ -608,12 +548,10 @@ public class ClassicPlotManager extends SquarePlotManager {
* @param plot The plot * @param plot The plot
* @return The location where a sign should be * @return The location where a sign should be
*/ */
@Override public Location getSignLoc(Plot plot) { @Override public Location getSignLoc(@NotNull Plot plot) {
plot = plot.getBasePlot(false); plot = plot.getBasePlot(false);
final Location bot = plot.getBottomAbs(); final Location bot = plot.getBottomAbs();
return Location return Location.at(classicPlotWorld.getWorldName(), bot.getX() - 1, classicPlotWorld.ROAD_HEIGHT + 1, bot.getZ() - 2);
.at(classicPlotWorld.getWorldName(), bot.getX() - 1, classicPlotWorld.ROAD_HEIGHT + 1,
bot.getZ() - 2);
} }
} }

View File

@ -47,8 +47,10 @@ import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypes;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@ -62,37 +64,26 @@ public class HybridPlotManager extends ClassicPlotManager {
@Getter private final HybridPlotWorld hybridPlotWorld; @Getter private final HybridPlotWorld hybridPlotWorld;
private final RegionManager regionManager; private final RegionManager regionManager;
public HybridPlotManager(@Nonnull final HybridPlotWorld hybridPlotWorld, public HybridPlotManager(@Nonnull final HybridPlotWorld hybridPlotWorld, @Nonnull final RegionManager regionManager) {
@Nonnull final RegionManager regionManager) {
super(hybridPlotWorld, regionManager); super(hybridPlotWorld, regionManager);
this.hybridPlotWorld = hybridPlotWorld; this.hybridPlotWorld = hybridPlotWorld;
this.regionManager = regionManager; this.regionManager = regionManager;
} }
@Override public void exportTemplate() throws IOException { @Override public void exportTemplate() throws IOException {
HashSet<FileBytes> files = Sets.newHashSet( HashSet<FileBytes> files = Sets.newHashSet(new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", Template.getBytes(hybridPlotWorld)));
new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", String dir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + hybridPlotWorld.getWorldName() + File.separator;
Template.getBytes(hybridPlotWorld)));
String dir =
"schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + hybridPlotWorld
.getWorldName() + File.separator;
try { try {
File sideRoad = File sideRoad = FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "sideroad.schem");
FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "sideroad.schem"); String newDir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + "__TEMP_DIR__" + File.separator;
String newDir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator
+ "__TEMP_DIR__" + File.separator;
if (sideRoad.exists()) { if (sideRoad.exists()) {
files.add(new FileBytes(newDir + "sideroad.schem", files.add(new FileBytes(newDir + "sideroad.schem", Files.readAllBytes(sideRoad.toPath())));
Files.readAllBytes(sideRoad.toPath())));
} }
File intersection = FileUtils File intersection = FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "intersection.schem");
.getFile(PlotSquared.platform().getDirectory(), dir + "intersection.schem");
if (intersection.exists()) { if (intersection.exists()) {
files.add(new FileBytes(newDir + "intersection.schem", files.add(new FileBytes(newDir + "intersection.schem", Files.readAllBytes(intersection.toPath())));
Files.readAllBytes(intersection.toPath())));
} }
File plot = File plot = FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "plot.schem");
FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "plot.schem");
if (plot.exists()) { if (plot.exists()) {
files.add(new FileBytes(newDir + "plot.schem", Files.readAllBytes(plot.toPath()))); files.add(new FileBytes(newDir + "plot.schem", Files.readAllBytes(plot.toPath())));
} }
@ -102,17 +93,14 @@ public class HybridPlotManager extends ClassicPlotManager {
Template.zipAll(hybridPlotWorld.getWorldName(), files); Template.zipAll(hybridPlotWorld.getWorldName(), files);
} }
@Override public boolean createRoadEast(Plot plot) { @Override public boolean createRoadEast(@Nonnull final Plot plot) {
super.createRoadEast(plot); super.createRoadEast(plot);
PlotId id = plot.getId(); PlotId id = plot.getId();
PlotId id2 = PlotId.of(id.getX() + 1, id.getY()); PlotId id2 = PlotId.of(id.getX() + 1, id.getY());
Location bot = getPlotBottomLocAbs(id2); Location bot = getPlotBottomLocAbs(id2);
Location top = getPlotTopLocAbs(id); Location top = getPlotTopLocAbs(id);
Location pos1 = Location pos1 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, 0, bot.getZ() - 1);
Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, 0, bot.getZ() - 1); Location pos2 = Location.at(hybridPlotWorld.getWorldName(), bot.getX(), Math.min(getWorldHeight(), 255), top.getZ() + 1);
Location pos2 = Location
.at(hybridPlotWorld.getWorldName(), bot.getX(), Math.min(getWorldHeight(), 255),
top.getZ() + 1);
this.resetBiome(hybridPlotWorld, pos1, pos2); this.resetBiome(hybridPlotWorld, pos1, pos2);
if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) {
return true; return true;
@ -123,24 +111,18 @@ public class HybridPlotManager extends ClassicPlotManager {
return true; return true;
} }
private void resetBiome(@Nonnull final HybridPlotWorld hybridPlotWorld, private void resetBiome(@Nonnull final HybridPlotWorld hybridPlotWorld, @Nonnull final Location pos1, @Nonnull final Location pos2) {
@Nonnull final Location pos1, @Nonnull final Location pos2) {
BiomeType biome = hybridPlotWorld.getPlotBiome(); BiomeType biome = hybridPlotWorld.getPlotBiome();
if (!Objects.equals(PlotSquared.platform().getWorldUtil() if (!Objects.equals(PlotSquared.platform().getWorldUtil()
.getBiomeSynchronous(hybridPlotWorld.getWorldName(), (pos1.getX() + pos2.getX()) / 2, .getBiomeSynchronous(hybridPlotWorld.getWorldName(), (pos1.getX() + pos2.getX()) / 2, (pos1.getZ() + pos2.getZ()) / 2), biome)) {
(pos1.getZ() + pos2.getZ()) / 2), biome)) { WorldUtil.setBiome(hybridPlotWorld.getWorldName(), pos1.getX(), pos1.getZ(), pos2.getX(), pos2.getZ(), biome);
WorldUtil
.setBiome(hybridPlotWorld.getWorldName(), pos1.getX(), pos1.getZ(), pos2.getX(),
pos2.getZ(), biome);
} }
} }
private void createSchemAbs(QueueCoordinator queue, Location pos1, Location pos2, private void createSchemAbs(@Nonnull final QueueCoordinator queue, @Nonnull final Location pos1, @Nonnull final Location pos2, boolean isRoad) {
boolean isRoad) {
int size = hybridPlotWorld.SIZE; int size = hybridPlotWorld.SIZE;
int minY; int minY;
if ((isRoad && Settings.Schematics.PASTE_ROAD_ON_TOP) || (!isRoad if ((isRoad && Settings.Schematics.PASTE_ROAD_ON_TOP) || (!isRoad && Settings.Schematics.PASTE_ON_TOP)) {
&& Settings.Schematics.PASTE_ON_TOP)) {
minY = hybridPlotWorld.SCHEM_Y; minY = hybridPlotWorld.SCHEM_Y;
} else { } else {
minY = 1; minY = 1;
@ -177,17 +159,14 @@ public class HybridPlotManager extends ClassicPlotManager {
} }
} }
@Override public boolean createRoadSouth(Plot plot) { @Override public boolean createRoadSouth(@Nonnull final Plot plot) {
super.createRoadSouth(plot); super.createRoadSouth(plot);
PlotId id = plot.getId(); PlotId id = plot.getId();
PlotId id2 = PlotId.of(id.getX(), id.getY() + 1); PlotId id2 = PlotId.of(id.getX(), id.getY() + 1);
Location bot = getPlotBottomLocAbs(id2); Location bot = getPlotBottomLocAbs(id2);
Location top = getPlotTopLocAbs(id); Location top = getPlotTopLocAbs(id);
Location pos1 = Location pos1 = Location.at(hybridPlotWorld.getWorldName(), bot.getX() - 1, 0, top.getZ() + 1);
Location.at(hybridPlotWorld.getWorldName(), bot.getX() - 1, 0, top.getZ() + 1); Location pos2 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, Math.min(getWorldHeight(), 255), bot.getZ());
Location pos2 = Location
.at(hybridPlotWorld.getWorldName(), top.getX() + 1, Math.min(getWorldHeight(), 255),
bot.getZ());
this.resetBiome(hybridPlotWorld, pos1, pos2); this.resetBiome(hybridPlotWorld, pos1, pos2);
if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) {
return true; return true;
@ -198,7 +177,7 @@ public class HybridPlotManager extends ClassicPlotManager {
return true; return true;
} }
@Override public boolean createRoadSouthEast(Plot plot) { @Override public boolean createRoadSouthEast(@Nonnull final Plot plot) {
super.createRoadSouthEast(plot); super.createRoadSouthEast(plot);
PlotId id = plot.getId(); PlotId id = plot.getId();
PlotId id2 = PlotId.of(id.getX() + 1, id.getY() + 1); PlotId id2 = PlotId.of(id.getX() + 1, id.getY() + 1);
@ -219,7 +198,7 @@ public class HybridPlotManager extends ClassicPlotManager {
* don't need to do something quite as complex unless you happen to have 512x512 sized plots. * don't need to do something quite as complex unless you happen to have 512x512 sized plots.
* </p> * </p>
*/ */
@Override public boolean clearPlot(Plot plot, final Runnable whenDone) { @Override public boolean clearPlot(@Nonnull final Plot plot, @Nullable final Runnable whenDone) {
if (this.regionManager.notifyClear(this)) { if (this.regionManager.notifyClear(this)) {
//If this returns false, the clear didn't work //If this returns false, the clear didn't work
if (this.regionManager.handleClear(plot, whenDone, this)) { if (this.regionManager.handleClear(plot, whenDone, this)) {
@ -231,8 +210,7 @@ public class HybridPlotManager extends ClassicPlotManager {
final Location pos2 = plot.getExtendedTopAbs(); final Location pos2 = plot.getExtendedTopAbs();
// If augmented // If augmented
final boolean canRegen = final boolean canRegen =
(hybridPlotWorld.getType() == PlotAreaType.AUGMENTED) && (hybridPlotWorld.getTerrain() (hybridPlotWorld.getType() == PlotAreaType.AUGMENTED) && (hybridPlotWorld.getTerrain() != PlotAreaTerrainType.NONE) && REGENERATIVE_CLEAR;
!= PlotAreaTerrainType.NONE) && REGENERATIVE_CLEAR;
// The component blocks // The component blocks
final Pattern plotfloor = hybridPlotWorld.TOP_BLOCK.toPattern(); final Pattern plotfloor = hybridPlotWorld.TOP_BLOCK.toPattern();
final Pattern filling = hybridPlotWorld.MAIN_BLOCK.toPattern(); final Pattern filling = hybridPlotWorld.MAIN_BLOCK.toPattern();
@ -251,10 +229,8 @@ public class HybridPlotManager extends ClassicPlotManager {
queue.setCuboid(pos1.withY(0), pos2.withY(0), bedrock); queue.setCuboid(pos1.withY(0), pos2.withY(0), bedrock);
// Each component has a different layer // Each component has a different layer
queue.setCuboid(pos1.withY(1), pos2.withY(hybridPlotWorld.PLOT_HEIGHT - 1), filling); queue.setCuboid(pos1.withY(1), pos2.withY(hybridPlotWorld.PLOT_HEIGHT - 1), filling);
queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT), queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT), pos2.withY(hybridPlotWorld.PLOT_HEIGHT), plotfloor);
pos2.withY(hybridPlotWorld.PLOT_HEIGHT), plotfloor); queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT + 1), pos2.withY(getWorldHeight()), air);
queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT + 1),
pos2.withY(getWorldHeight()), air);
queue.setBiomeCuboid(pos1, pos2, biome); queue.setBiomeCuboid(pos1, pos2, biome);
} else { } else {
queue.setRegenRegion(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3())); queue.setRegenRegion(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()));
@ -264,7 +240,7 @@ public class HybridPlotManager extends ClassicPlotManager {
return queue.enqueue(); return queue.enqueue();
} }
public void pastePlotSchematic(QueueCoordinator queue, Location bottom, Location top) { public void pastePlotSchematic(@Nonnull final QueueCoordinator queue, @Nonnull final Location bottom, @Nonnull final Location top) {
if (!hybridPlotWorld.PLOT_SCHEMATIC) { if (!hybridPlotWorld.PLOT_SCHEMATIC) {
return; return;
} }
@ -277,7 +253,7 @@ public class HybridPlotManager extends ClassicPlotManager {
* @param plot The plot * @param plot The plot
* @return The location where a sign should be * @return The location where a sign should be
*/ */
@Override public Location getSignLoc(Plot plot) { @Override public Location getSignLoc(@Nonnull final @NotNull Plot plot) {
return hybridPlotWorld.getSignLocation(plot); return hybridPlotWorld.getSignLocation(plot);
} }
} }

View File

@ -41,7 +41,6 @@ import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.FileUtils; import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.SchematicHandler; import com.plotsquared.core.util.SchematicHandler;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.CompoundTagBuilder; import com.sk89q.jnbt.CompoundTagBuilder;
@ -124,11 +123,9 @@ public class HybridPlotWorld extends ClassicPlotWorld {
Direction direction = MCDirections.fromRotation(rot); Direction direction = MCDirections.fromRotation(rot);
if (direction != null) { if (direction != null) {
Vector3 vector = transform.apply(direction.toVector()) Vector3 vector = transform.apply(direction.toVector()).subtract(transform.apply(Vector3.ZERO)).normalize();
.subtract(transform.apply(Vector3.ZERO)).normalize(); Direction newDirection =
Direction newDirection = Direction.findClosest(vector, Direction.findClosest(vector, Direction.Flag.CARDINAL | Direction.Flag.ORDINAL | Direction.Flag.SECONDARY_ORDINAL);
Direction.Flag.CARDINAL | Direction.Flag.ORDINAL
| Direction.Flag.SECONDARY_ORDINAL);
if (newDirection != null) { if (newDirection != null) {
CompoundTagBuilder builder = tag.createBuilder(); CompoundTagBuilder builder = tag.createBuilder();
@ -215,21 +212,24 @@ public class HybridPlotWorld extends ClassicPlotWorld {
// Try to determine root. This means that plot areas can have separate schematic // Try to determine root. This means that plot areas can have separate schematic
// directories // directories
if (!(root = FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" + if (!(root =
this.getWorldName() + "/" + this.getId())).exists()) { FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName() + "/" + this.getId()))
root = FileUtils.getFile(PlotSquared.platform().getDirectory(), .exists()) {
"schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName()); root = FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName());
} }
File schematic1File = new File(root, "sideroad.schem"); File schematic1File = new File(root, "sideroad.schem");
if (!schematic1File.exists()) if (!schematic1File.exists()) {
schematic1File = new File(root, "sideroad.schematic"); schematic1File = new File(root, "sideroad.schematic");
}
File schematic2File = new File(root, "intersection.schem"); File schematic2File = new File(root, "intersection.schem");
if (!schematic2File.exists()) if (!schematic2File.exists()) {
schematic2File = new File(root, "intersection.schematic"); schematic2File = new File(root, "intersection.schematic");
}
File schematic3File = new File(root, "plot.schem"); File schematic3File = new File(root, "plot.schem");
if (!schematic3File.exists()) if (!schematic3File.exists()) {
schematic3File = new File(root, "plot.schematic"); schematic3File = new File(root, "plot.schematic");
}
Schematic schematic1 = this.schematicHandler.getSchematic(schematic1File); Schematic schematic1 = this.schematicHandler.getSchematic(schematic1File);
Schematic schematic2 = this.schematicHandler.getSchematic(schematic2File); Schematic schematic2 = this.schematicHandler.getSchematic(schematic2File);
Schematic schematic3 = this.schematicHandler.getSchematic(schematic3File); Schematic schematic3 = this.schematicHandler.getSchematic(schematic3File);
@ -282,18 +282,15 @@ public class HybridPlotWorld extends ClassicPlotWorld {
for (short x = 0; x < w3; x++) { for (short x = 0; x < w3; x++) {
for (short z = 0; z < l3; z++) { for (short z = 0; z < l3; z++) {
for (short y = 0; y < h3; y++) { for (short y = 0; y < h3; y++) {
BaseBlock id = blockArrayClipboard3.getFullBlock(BlockVector3 BaseBlock id =
.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); blockArrayClipboard3.getFullBlock(BlockVector3.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ()));
if (!id.getBlockType().getMaterial().isAir()) { if (!id.getBlockType().getMaterial().isAir()) {
addOverlayBlock((short) (x + shift + oddshift + centerShiftX), addOverlayBlock((short) (x + shift + oddshift + centerShiftX), (short) (y + plotY),
(short) (y + plotY), (short) (z + shift + oddshift + centerShiftZ), (short) (z + shift + oddshift + centerShiftZ), id, false, h3);
id, false, h3);
} }
} }
BiomeType biome = blockArrayClipboard3 BiomeType biome = blockArrayClipboard3.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ()));
.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); addOverlayBiome((short) (x + shift + oddshift + centerShiftX), (short) (z + shift + oddshift + centerShiftZ), biome);
addOverlayBiome((short) (x + shift + oddshift + centerShiftX),
(short) (z + shift + oddshift + centerShiftZ), biome);
} }
} }
@ -322,20 +319,15 @@ public class HybridPlotWorld extends ClassicPlotWorld {
for (short x = 0; x < w1; x++) { for (short x = 0; x < w1; x++) {
for (short z = 0; z < l1; z++) { for (short z = 0; z < l1; z++) {
for (short y = 0; y < h1; y++) { for (short y = 0; y < h1; y++) {
BaseBlock id = blockArrayClipboard1.getFullBlock(BlockVector3 BaseBlock id = blockArrayClipboard1.getFullBlock(BlockVector3.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ()));
.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ()));
if (!id.getBlockType().getMaterial().isAir()) { if (!id.getBlockType().getMaterial().isAir()) {
addOverlayBlock((short) (x - shift), (short) (y + roadY), addOverlayBlock((short) (x - shift), (short) (y + roadY), (short) (z + shift + oddshift), id, false, h1);
(short) (z + shift + oddshift), id, false, h1); addOverlayBlock((short) (z + shift + oddshift), (short) (y + roadY), (short) (shift - x + (oddshift - 1)), id, true, h1);
addOverlayBlock((short) (z + shift + oddshift), (short) (y + roadY),
(short) (shift - x + (oddshift - 1)), id, true, h1);
} }
} }
BiomeType biome = blockArrayClipboard1 BiomeType biome = blockArrayClipboard1.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ()));
.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ()));
addOverlayBiome((short) (x - shift), (short) (z + shift + oddshift), biome); addOverlayBiome((short) (x - shift), (short) (z + shift + oddshift), biome);
addOverlayBiome((short) (z + shift + oddshift), addOverlayBiome((short) (z + shift + oddshift), (short) (shift - x + (oddshift - 1)), biome);
(short) (shift - x + (oddshift - 1)), biome);
} }
} }
@ -348,22 +340,18 @@ public class HybridPlotWorld extends ClassicPlotWorld {
for (short x = 0; x < w2; x++) { for (short x = 0; x < w2; x++) {
for (short z = 0; z < l2; z++) { for (short z = 0; z < l2; z++) {
for (short y = 0; y < h2; y++) { for (short y = 0; y < h2; y++) {
BaseBlock id = blockArrayClipboard2.getFullBlock(BlockVector3 BaseBlock id = blockArrayClipboard2.getFullBlock(BlockVector3.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ()));
.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ()));
if (!id.getBlockType().getMaterial().isAir()) { if (!id.getBlockType().getMaterial().isAir()) {
addOverlayBlock((short) (x - shift), (short) (y + roadY), addOverlayBlock((short) (x - shift), (short) (y + roadY), (short) (z - shift), id, false, h2);
(short) (z - shift), id, false, h2);
} }
} }
BiomeType biome = blockArrayClipboard2 BiomeType biome = blockArrayClipboard2.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ()));
.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ()));
addOverlayBiome((short) (x - shift), (short) (z - shift), biome); addOverlayBiome((short) (x - shift), (short) (z - shift), biome);
} }
} }
} }
public void addOverlayBlock(short x, short y, short z, BaseBlock id, boolean rotate, public void addOverlayBlock(short x, short y, short z, BaseBlock id, boolean rotate, int height) {
int height) {
if (z < 0) { if (z < 0) {
z += this.SIZE; z += this.SIZE;
} else if (z >= this.SIZE) { } else if (z >= this.SIZE) {

View File

@ -80,8 +80,7 @@ import java.util.concurrent.atomic.AtomicInteger;
public class HybridUtils { public class HybridUtils {
private static final Logger logger = private static final Logger logger = LoggerFactory.getLogger("P2/" + HybridUtils.class.getSimpleName());
LoggerFactory.getLogger("P2/" + HybridUtils.class.getSimpleName());
public static HybridUtils manager; public static HybridUtils manager;
public static Set<BlockVector2> regions; public static Set<BlockVector2> regions;
@ -94,18 +93,17 @@ public class HybridUtils {
private final ChunkManager chunkManager; private final ChunkManager chunkManager;
private final GlobalBlockQueue blockQueue; private final GlobalBlockQueue blockQueue;
private final WorldUtil worldUtil; private final WorldUtil worldUtil;
private final RegionManager regionManager;
private final SchematicHandler schematicHandler; private final SchematicHandler schematicHandler;
@Inject public HybridUtils(@Nonnull final PlotAreaManager plotAreaManager, @Inject public HybridUtils(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final ChunkManager chunkManager, @Nonnull final GlobalBlockQueue blockQueue, @Nonnull final ChunkManager chunkManager,
@Nonnull final WorldUtil worldUtil, @Nonnull final RegionManager regionManager, @Nonnull final GlobalBlockQueue blockQueue,
@Nonnull final WorldUtil worldUtil,
@Nonnull final SchematicHandler schematicHandler) { @Nonnull final SchematicHandler schematicHandler) {
this.plotAreaManager = plotAreaManager; this.plotAreaManager = plotAreaManager;
this.chunkManager = chunkManager; this.chunkManager = chunkManager;
this.blockQueue = blockQueue; this.blockQueue = blockQueue;
this.worldUtil = worldUtil; this.worldUtil = worldUtil;
this.regionManager = regionManager;
this.schematicHandler = schematicHandler; this.schematicHandler = schematicHandler;
} }
@ -114,8 +112,7 @@ public class HybridUtils {
plotManager.regenerateAllPlotWalls(); plotManager.regenerateAllPlotWalls();
} }
public void analyzeRegion(final String world, final CuboidRegion region, public void analyzeRegion(final String world, final CuboidRegion region, final RunnableVal<PlotAnalysis> whenDone) {
final RunnableVal<PlotAnalysis> whenDone) {
// int diff, int variety, int vertices, int rotation, int height_sd // int diff, int variety, int vertices, int rotation, int height_sd
/* /*
* diff: compare to base by looping through all blocks * diff: compare to base by looping through all blocks
@ -235,30 +232,23 @@ public class HybridUtils {
} else { } else {
// check vertices // check vertices
// modifications_adjacent // modifications_adjacent
if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 && y < 255) {
&& y < 255) { if (newBlocks[y - 1][x][z].getBlockType().getMaterial().isAir()) {
if (newBlocks[y - 1][x][z].getBlockType().getMaterial()
.isAir()) {
faces[i]++; faces[i]++;
} }
if (newBlocks[y][x - 1][z].getBlockType().getMaterial() if (newBlocks[y][x - 1][z].getBlockType().getMaterial().isAir()) {
.isAir()) {
faces[i]++; faces[i]++;
} }
if (newBlocks[y][x][z - 1].getBlockType().getMaterial() if (newBlocks[y][x][z - 1].getBlockType().getMaterial().isAir()) {
.isAir()) {
faces[i]++; faces[i]++;
} }
if (newBlocks[y + 1][x][z].getBlockType().getMaterial() if (newBlocks[y + 1][x][z].getBlockType().getMaterial().isAir()) {
.isAir()) {
faces[i]++; faces[i]++;
} }
if (newBlocks[y][x + 1][z].getBlockType().getMaterial() if (newBlocks[y][x + 1][z].getBlockType().getMaterial().isAir()) {
.isAir()) {
faces[i]++; faces[i]++;
} }
if (newBlocks[y][x][z + 1].getBlockType().getMaterial() if (newBlocks[y][x][z + 1].getBlockType().getMaterial().isAir()) {
.isAir()) {
faces[i]++; faces[i]++;
} }
} }
@ -347,9 +337,7 @@ public class HybridUtils {
result.add(whenDone.value.data_sd); result.add(whenDone.value.data_sd);
result.add(whenDone.value.air_sd); result.add(whenDone.value.air_sd);
result.add(whenDone.value.variety_sd); result.add(whenDone.value.variety_sd);
PlotFlag<?, ?> plotFlag = PlotFlag<?, ?> plotFlag = GlobalFlagContainer.getInstance().getFlag(AnalysisFlag.class).createFlagInstance(result);
GlobalFlagContainer.getInstance().getFlag(AnalysisFlag.class)
.createFlagInstance(result);
PlotFlagAddEvent event = new PlotFlagAddEvent(plotFlag, origin); PlotFlagAddEvent event = new PlotFlagAddEvent(plotFlag, origin);
if (event.getEventResult() == Result.DENY) { if (event.getEventResult() == Result.DENY) {
return; return;
@ -371,15 +359,13 @@ public class HybridUtils {
run.run(); run.run();
} }
public int checkModified(QueueCoordinator queue, int x1, int x2, int y1, int y2, int z1, int z2, public int checkModified(QueueCoordinator queue, int x1, int x2, int y1, int y2, int z1, int z2, BlockState[] blocks) {
BlockState[] blocks) {
int count = 0; int count = 0;
for (int y = y1; y <= y2; y++) { for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) { for (int x = x1; x <= x2; x++) {
for (int z = z1; z <= z2; z++) { for (int z = z1; z <= z2; z++) {
BlockState block = queue.getBlock(x, y, z); BlockState block = queue.getBlock(x, y, z);
boolean same = boolean same = Arrays.stream(blocks).anyMatch(p -> this.worldUtil.isBlockSame(block, p));
Arrays.stream(blocks).anyMatch(p -> this.worldUtil.isBlockSame(block, p));
if (!same) { if (!same) {
count++; count++;
} }
@ -420,8 +406,7 @@ public class HybridUtils {
return scheduleRoadUpdate(plot.getArea(), regions, extend, new HashSet<>()); return scheduleRoadUpdate(plot.getArea(), regions, extend, new HashSet<>());
} }
public boolean scheduleRoadUpdate(final PlotArea area, Set<BlockVector2> regions, public boolean scheduleRoadUpdate(final PlotArea area, Set<BlockVector2> regions, final int extend, Set<BlockVector2> chunks) {
final int extend, Set<BlockVector2> chunks) {
HybridUtils.regions = regions; HybridUtils.regions = regions;
HybridUtils.area = area; HybridUtils.area = area;
HybridUtils.height = extend; HybridUtils.height = extend;
@ -460,16 +445,12 @@ public class HybridUtils {
try { try {
if (chunks.size() < 1024) { if (chunks.size() < 1024) {
if (!HybridUtils.regions.isEmpty()) { if (!HybridUtils.regions.isEmpty()) {
Iterator<BlockVector2> iterator = Iterator<BlockVector2> iterator = HybridUtils.regions.iterator();
HybridUtils.regions.iterator();
BlockVector2 loc = iterator.next(); BlockVector2 loc = iterator.next();
iterator.remove(); iterator.remove();
if (Settings.DEBUG) { if (Settings.DEBUG) {
logger logger.info("[P2] Updating .mcr: {}, {} (approx 1024 chunks)", loc.getX(), loc.getZ());
.info("[P2] Updating .mcr: {}, {} (approx 1024 chunks)", logger.info("[P2] - Remaining: {}", HybridUtils.regions.size());
loc.getX(), loc.getZ());
logger.info("[P2] - Remaining: {}",
HybridUtils.regions.size());
} }
chunks.addAll(getChunks(loc)); chunks.addAll(getChunks(loc));
System.gc(); System.gc();
@ -479,8 +460,7 @@ public class HybridUtils {
TaskManager.getPlatformImplementation().sync(() -> { TaskManager.getPlatformImplementation().sync(() -> {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
Iterator<BlockVector2> iterator = chunks.iterator(); Iterator<BlockVector2> iterator = chunks.iterator();
while (System.currentTimeMillis() - start < 20 && !chunks while (System.currentTimeMillis() - start < 20 && !chunks.isEmpty()) {
.isEmpty()) {
final BlockVector2 chunk = iterator.next(); final BlockVector2 chunk = iterator.next();
iterator.remove(); iterator.remove();
boolean regenedRoads = regenerateRoad(area, chunk, extend); boolean regenedRoads = regenerateRoad(area, chunk, extend);
@ -496,9 +476,8 @@ public class HybridUtils {
Iterator<BlockVector2> iterator = HybridUtils.regions.iterator(); Iterator<BlockVector2> iterator = HybridUtils.regions.iterator();
BlockVector2 loc = iterator.next(); BlockVector2 loc = iterator.next();
iterator.remove(); iterator.remove();
logger.error( logger.error("[P2] Error! Could not update '{}/region/r.{}.{}.mca' (Corrupt chunk?)", area.getWorldHash(), loc.getX(),
"[P2] Error! Could not update '{}/region/r.{}.{}.mca' (Corrupt chunk?)", loc.getZ());
area.getWorldHash(), loc.getX(), loc.getZ());
} }
TaskManager.runTaskLater(task, TaskTime.seconds(1L)); TaskManager.runTaskLater(task, TaskTime.seconds(1L));
}); });
@ -525,20 +504,15 @@ public class HybridUtils {
int tz = sz - 1; int tz = sz - 1;
int ty = get_ey(plotManager, queue, sx, ex, bz, tz, sy); int ty = get_ey(plotManager, queue, sx, ex, bz, tz, sy);
Set<CuboidRegion> sideRoad = new HashSet<>( Set<CuboidRegion> sideRoad = new HashSet<>(Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ey, sz, ez)));
Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ey, sz, ez))); final Set<CuboidRegion> intersection = new HashSet<>(Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ty, bz, tz)));
final Set<CuboidRegion> intersection = new HashSet<>(
Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ty, bz, tz)));
final String dir = final String dir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + plot.getArea().toString() + File.separator;
"schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + plot.getArea()
.toString() + File.separator;
this.schematicHandler.getCompoundTag(world, sideRoad, new RunnableVal<CompoundTag>() { this.schematicHandler.getCompoundTag(world, sideRoad, new RunnableVal<CompoundTag>() {
@Override public void run(CompoundTag value) { @Override public void run(CompoundTag value) {
schematicHandler.save(value, dir + "sideroad.schem"); schematicHandler.save(value, dir + "sideroad.schem");
schematicHandler schematicHandler.getCompoundTag(world, intersection, new RunnableVal<CompoundTag>() {
.getCompoundTag(world, intersection, new RunnableVal<CompoundTag>() {
@Override public void run(CompoundTag value) { @Override public void run(CompoundTag value) {
schematicHandler.save(value, dir + "intersection.schem"); schematicHandler.save(value, dir + "intersection.schem");
plotworld.ROAD_SCHEMATIC_ENABLED = true; plotworld.ROAD_SCHEMATIC_ENABLED = true;
@ -554,8 +528,7 @@ public class HybridUtils {
return true; return true;
} }
public int get_ey(final PlotManager pm, QueueCoordinator queue, int sx, int ex, int sz, int ez, public int get_ey(final PlotManager pm, QueueCoordinator queue, int sx, int ex, int sz, int ez, int sy) {
int sy) {
int ey = sy; int ey = sy;
for (int x = sx; x <= ex; x++) { for (int x = sx; x <= ex; x++) {
for (int z = sz; z <= ez; z++) { for (int z = sz; z <= ez; z++) {
@ -598,8 +571,7 @@ public class HybridUtils {
z -= plotWorld.ROAD_OFFSET_Z; z -= plotWorld.ROAD_OFFSET_Z;
final int finalX = x; final int finalX = x;
final int finalZ = z; final int finalZ = z;
QueueCoordinator queue = QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(plotWorld.getWorldName()));
this.blockQueue.getNewQueue(worldUtil.getWeWorld(plotWorld.getWorldName()));
if (id1 == null || id2 == null || id1 != id2) { if (id1 == null || id2 == null || id1 != id2) {
this.chunkManager.loadChunk(area.getWorldName(), chunk, false).thenRun(() -> { this.chunkManager.loadChunk(area.getWorldName(), chunk, false).thenRun(() -> {
if (id1 != null) { if (id1 != null) {
@ -627,8 +599,7 @@ public class HybridUtils {
} }
boolean condition; boolean condition;
if (toCheck.get()) { if (toCheck.get()) {
condition = manager.getPlotId(finalX + X + plotWorld.ROAD_OFFSET_X, 1, condition = manager.getPlotId(finalX + X + plotWorld.ROAD_OFFSET_X, 1, finalZ + Z + plotWorld.ROAD_OFFSET_Z) == null;
finalZ + Z + plotWorld.ROAD_OFFSET_Z) == null;
} else { } else {
boolean gx = absX > plotWorld.PATH_WIDTH_LOWER; boolean gx = absX > plotWorld.PATH_WIDTH_LOWER;
boolean gz = absZ > plotWorld.PATH_WIDTH_LOWER; boolean gz = absZ > plotWorld.PATH_WIDTH_LOWER;
@ -638,32 +609,27 @@ public class HybridUtils {
} }
if (condition) { if (condition) {
BaseBlock[] blocks = plotWorld.G_SCH.get(MathMan.pair(absX, absZ)); BaseBlock[] blocks = plotWorld.G_SCH.get(MathMan.pair(absX, absZ));
int minY = int minY = Settings.Schematics.PASTE_ROAD_ON_TOP ? plotWorld.SCHEM_Y : 1;
Settings.Schematics.PASTE_ROAD_ON_TOP ? plotWorld.SCHEM_Y : 1;
int maxY = Math.max(extend, blocks.length); int maxY = Math.max(extend, blocks.length);
for (int y = 0; y < maxY; y++) { for (int y = 0; y < maxY; y++) {
if (y > blocks.length - 1) { if (y > blocks.length - 1) {
queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z,
finalZ + Z + plotWorld.ROAD_OFFSET_Z, WEExtent.AIRBASE); WEExtent.AIRBASE);
} else { } else {
BaseBlock block = blocks[y]; BaseBlock block = blocks[y];
if (block != null) { if (block != null) {
queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, block);
minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, block);
} else { } else {
queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z,
minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z,
WEExtent.AIRBASE); WEExtent.AIRBASE);
} }
} }
} }
BiomeType biome = plotWorld.G_SCH_B.get(MathMan.pair(absX, absZ)); BiomeType biome = plotWorld.G_SCH_B.get(MathMan.pair(absX, absZ));
if (biome != null) { if (biome != null) {
queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, finalZ + Z + plotWorld.ROAD_OFFSET_Z, biome);
finalZ + Z + plotWorld.ROAD_OFFSET_Z, biome);
} else { } else {
queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, finalZ + Z + plotWorld.ROAD_OFFSET_Z, plotWorld.getPlotBiome());
finalZ + Z + plotWorld.ROAD_OFFSET_Z, plotWorld.getPlotBiome());
} }
} }
} }

View File

@ -34,6 +34,7 @@ import com.plotsquared.core.queue.QueueCoordinator;
import com.plotsquared.core.util.HashUtil; import com.plotsquared.core.util.HashUtil;
import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.RegionManager;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -47,26 +48,25 @@ import java.util.Set;
*/ */
public abstract class SquarePlotManager extends GridPlotManager { public abstract class SquarePlotManager extends GridPlotManager {
private static final Logger logger = private static final Logger logger = LoggerFactory.getLogger("P2/" + SquarePlotManager.class.getSimpleName());
LoggerFactory.getLogger("P2/" + SquarePlotManager.class.getSimpleName());
private final SquarePlotWorld squarePlotWorld; private final SquarePlotWorld squarePlotWorld;
private final RegionManager regionManager; private final RegionManager regionManager;
public SquarePlotManager(@Nonnull final SquarePlotWorld squarePlotWorld, public SquarePlotManager(@Nonnull final SquarePlotWorld squarePlotWorld, @Nonnull final RegionManager regionManager) {
@Nonnull final RegionManager regionManager) {
super(squarePlotWorld); super(squarePlotWorld);
this.squarePlotWorld = squarePlotWorld; this.squarePlotWorld = squarePlotWorld;
this.regionManager = regionManager; this.regionManager = regionManager;
} }
@Override public boolean clearPlot(final Plot plot, final Runnable whenDone, @Override public boolean clearPlot(final @NotNull Plot plot, final @Nullable Runnable whenDone, @Nullable QueueCoordinator queue) {
@Nullable QueueCoordinator queue) {
final Set<CuboidRegion> regions = plot.getRegions(); final Set<CuboidRegion> regions = plot.getRegions();
Runnable run = new Runnable() { Runnable run = new Runnable() {
@Override public void run() { @Override public void run() {
if (regions.isEmpty()) { if (regions.isEmpty()) {
if (whenDone != null) {
whenDone.run(); whenDone.run();
}
return; return;
} }
Iterator<CuboidRegion> iterator = regions.iterator(); Iterator<CuboidRegion> iterator = regions.iterator();
@ -81,13 +81,13 @@ public abstract class SquarePlotManager extends GridPlotManager {
return true; return true;
} }
@Override public Location getPlotTopLocAbs(PlotId plotId) { @Override public Location getPlotTopLocAbs(@NotNull PlotId plotId) {
int px = plotId.getX(); int px = plotId.getX();
int pz = plotId.getY(); int pz = plotId.getY();
int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - (int) Math
+ squarePlotWorld.PLOT_WIDTH))) - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; .floor(squarePlotWorld.ROAD_WIDTH / 2) - 1;
int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - (int) Math
+ squarePlotWorld.PLOT_WIDTH))) - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; .floor(squarePlotWorld.ROAD_WIDTH / 2) - 1;
return Location.at(squarePlotWorld.getWorldName(), x, Math.min(getWorldHeight(), 255), z); return Location.at(squarePlotWorld.getWorldName(), x, Math.min(getWorldHeight(), 255), z);
} }
@ -135,7 +135,7 @@ public abstract class SquarePlotManager extends GridPlotManager {
} }
} }
public PlotId getNearestPlotId(PlotArea plotArea, int x, int y, int z) { public PlotId getNearestPlotId(@Nonnull PlotArea plotArea, int x, int y, int z) {
SquarePlotWorld dpw = (SquarePlotWorld) plotArea; SquarePlotWorld dpw = (SquarePlotWorld) plotArea;
if (dpw.ROAD_OFFSET_X != 0) { if (dpw.ROAD_OFFSET_X != 0) {
x -= dpw.ROAD_OFFSET_X; x -= dpw.ROAD_OFFSET_X;
@ -196,8 +196,7 @@ public abstract class SquarePlotManager extends GridPlotManager {
rz = z % size; rz = z % size;
} }
PlotId id = PlotId.of(dx, dz); PlotId id = PlotId.of(dx, dz);
boolean[] merged = boolean[] merged = new boolean[] {rz <= pathWidthLower, rx > end, rz > end, rx <= pathWidthLower};
new boolean[] {rz <= pathWidthLower, rx > end, rz > end, rx <= pathWidthLower};
int hash = HashUtil.hash(merged); int hash = HashUtil.hash(merged);
// Not merged, and no need to check if it is // Not merged, and no need to check if it is
if (hash == 0) { if (hash == 0) {
@ -235,8 +234,7 @@ public abstract class SquarePlotManager extends GridPlotManager {
return plot.getMerged(Direction.NORTHWEST) ? id : null; return plot.getMerged(Direction.NORTHWEST) ? id : null;
} }
} catch (Exception ignored) { } catch (Exception ignored) {
logger.error("Invalid plot / road width in settings.yml for world: {}", logger.error("Invalid plot / road width in settings.yml for world: {}", squarePlotWorld.getWorldName());
squarePlotWorld.getWorldName());
} }
return null; return null;
} }
@ -244,16 +242,13 @@ public abstract class SquarePlotManager extends GridPlotManager {
/** /**
* Get the bottom plot loc (some basic math). * Get the bottom plot loc (some basic math).
*/ */
@Override public Location getPlotBottomLocAbs(PlotId plotId) { @Override public Location getPlotBottomLocAbs(@NotNull PlotId plotId) {
int px = plotId.getX(); int px = plotId.getX();
int pz = plotId.getY(); int pz = plotId.getY();
int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH
+ squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH - (int) Math - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2);
.floor(squarePlotWorld.ROAD_WIDTH / 2); int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH
int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2);
+ squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH - (int) Math return Location.at(squarePlotWorld.getWorldName(), x, squarePlotWorld.getMinBuildHeight(), z);
.floor(squarePlotWorld.ROAD_WIDTH / 2);
return Location
.at(squarePlotWorld.getWorldName(), x, squarePlotWorld.getMinBuildHeight(), z);
} }
} }

View File

@ -1,39 +0,0 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.inject.annotations;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
public @interface QueuePipeline {
}

View File

@ -34,7 +34,6 @@ import javax.annotation.Nonnull;
public interface ChunkCoordinatorBuilderFactory { public interface ChunkCoordinatorBuilderFactory {
@Inject @Nonnull ChunkCoordinatorBuilder create( @Inject @Nonnull ChunkCoordinatorBuilder create(@Assisted @NotNull ChunkCoordinatorFactory chunkCoordinatorFactory);
@Assisted @NotNull ChunkCoordinatorFactory chunkCoordinatorFactory);
} }

View File

@ -35,9 +35,13 @@ import java.util.function.Consumer;
public interface ChunkCoordinatorFactory { public interface ChunkCoordinatorFactory {
@Nonnull ChunkCoordinator create(final long maxIterationTime, final int initialBatchSize, @Nonnull ChunkCoordinator create(final long maxIterationTime,
@Nonnull final Consumer<BlockVector2> chunkConsumer, @Nonnull final World world, final int initialBatchSize,
@Nonnull final Collection<BlockVector2> requestedChunks, @Nonnull final Runnable whenDone, @Nonnull final Consumer<BlockVector2> chunkConsumer,
@Nonnull final Consumer<Throwable> throwableConsumer, final boolean unloadAfter); @Nonnull final World world,
@Nonnull final Collection<BlockVector2> requestedChunks,
@Nonnull final Runnable whenDone,
@Nonnull final Consumer<Throwable> throwableConsumer,
final boolean unloadAfter);
} }

View File

@ -140,14 +140,13 @@ public class Plot {
private static final Logger logger = LoggerFactory.getLogger("P2/" + Plot.class.getSimpleName()); private static final Logger logger = LoggerFactory.getLogger("P2/" + Plot.class.getSimpleName());
private static final DecimalFormat FLAG_DECIMAL_FORMAT = new DecimalFormat("0"); private static final DecimalFormat FLAG_DECIMAL_FORMAT = new DecimalFormat("0");
private static Set<Plot> connected_cache;
private static Set<CuboidRegion> regions_cache;
static { static {
FLAG_DECIMAL_FORMAT.setMaximumFractionDigits(340); FLAG_DECIMAL_FORMAT.setMaximumFractionDigits(340);
} }
private static Set<Plot> connected_cache;
private static Set<CuboidRegion> regions_cache;
/** /**
* Plot flag container * Plot flag container
*/ */
@ -272,9 +271,18 @@ public class Plot {
* @param merged an array giving merged plots * @param merged an array giving merged plots
* @see Plot#getPlot(Location) for existing plots * @see Plot#getPlot(Location) for existing plots
*/ */
public Plot(@Nonnull PlotId id, UUID owner, HashSet<UUID> trusted, HashSet<UUID> members, public Plot(@Nonnull PlotId id,
HashSet<UUID> denied, String alias, BlockLoc position, Collection<PlotFlag<?, ?>> flags, UUID owner,
PlotArea area, boolean[] merged, long timestamp, int temp) { HashSet<UUID> trusted,
HashSet<UUID> members,
HashSet<UUID> denied,
String alias,
BlockLoc position,
Collection<PlotFlag<?, ?>> flags,
PlotArea area,
boolean[] merged,
long timestamp,
int temp) {
this.id = id; this.id = id;
this.area = area; this.area = area;
this.owner = owner; this.owner = owner;
@ -306,8 +314,7 @@ public class Plot {
* @param message If a message should be sent to the player if a plot cannot be found * @param message If a message should be sent to the player if a plot cannot be found
* @return The plot if only 1 result is found, or null * @return The plot if only 1 result is found, or null
*/ */
@Nullable public static Plot getPlotFromString(PlotPlayer<?> player, String arg, @Nullable public static Plot getPlotFromString(PlotPlayer<?> player, String arg, boolean message) {
boolean message) {
if (arg == null) { if (arg == null) {
if (player == null) { if (player == null) {
if (message) { if (message) {
@ -329,8 +336,7 @@ public class Plot {
String[] split = arg.split(";|,"); String[] split = arg.split(";|,");
PlotId id; PlotId id;
if (split.length == 4) { if (split.length == 4) {
area = PlotSquared.get().getPlotAreaManager() area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(split[0] + ';' + split[1]);
.getPlotAreaByString(split[0] + ';' + split[1]);
id = PlotId.fromString(split[2] + ';' + split[3]); id = PlotId.fromString(split[2] + ';' + split[3]);
} else if (split.length == 3) { } else if (split.length == 3) {
area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(split[0]); area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(split[0]);
@ -409,8 +415,7 @@ public class Plot {
return null; return null;
} }
@Nonnull private static Location[] getCorners(@Nonnull final String world, @Nonnull private static Location[] getCorners(@Nonnull final String world, @Nonnull final CuboidRegion region) {
@Nonnull final CuboidRegion region) {
final BlockVector3 min = region.getMinimumPoint(); final BlockVector3 min = region.getMinimumPoint();
final BlockVector3 max = region.getMaximumPoint(); final BlockVector3 max = region.getMaximumPoint();
return new Location[] {Location.at(world, min), Location.at(world, max)}; return new Location[] {Location.at(world, min), Location.at(world, max)};
@ -609,8 +614,7 @@ public class Plot {
UUID last = this.getOwner(); UUID last = this.getOwner();
owners.add(this.getOwner()); owners.add(this.getOwner());
for (Plot current : array) { for (Plot current : array) {
if (last == null || current.getOwner().getMostSignificantBits() != last if (last == null || current.getOwner().getMostSignificantBits() != last.getMostSignificantBits()) {
.getMostSignificantBits()) {
owners.add(current.getOwner()); owners.add(current.getOwner());
last = current.getOwner(); last = current.getOwner();
} }
@ -652,8 +656,8 @@ public class Plot {
* @return boolean false if the player is allowed to enter * @return boolean false if the player is allowed to enter
*/ */
public boolean isDenied(UUID uuid) { public boolean isDenied(UUID uuid) {
return this.denied != null && (this.denied.contains(DBFunc.EVERYONE) && !this.isAdded(uuid) return this.denied != null && (this.denied.contains(DBFunc.EVERYONE) && !this.isAdded(uuid) || !this.isAdded(uuid) && this.denied
|| !this.isAdded(uuid) && this.denied.contains(uuid)); .contains(uuid));
} }
/** /**
@ -777,8 +781,7 @@ public class Plot {
* @return true if this plot is merged, otherwise false * @return true if this plot is merged, otherwise false
*/ */
public boolean isMerged() { public boolean isMerged() {
return getSettings().getMerged(0) || getSettings().getMerged(2) || getSettings() return getSettings().getMerged(0) || getSettings().getMerged(2) || getSettings().getMerged(1) || getSettings().getMerged(3);
.getMerged(1) || getSettings().getMerged(3);
} }
/** /**
@ -829,10 +832,8 @@ public class Plot {
int i2 = 0; int i2 = 0;
if (this.getSettings().getMerged(i2)) { if (this.getSettings().getMerged(i2)) {
if (this.getSettings().getMerged(i)) { if (this.getSettings().getMerged(i)) {
if (this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))) if (this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))).getMerged(i2)) {
.getMerged(i2)) { return this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2))).getMerged(i);
return this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2)))
.getMerged(i);
} }
} }
} }
@ -842,9 +843,8 @@ public class Plot {
case 6: case 6:
i = dir - 4; i = dir - 4;
i2 = dir - 3; i2 = dir - 3;
return this.getSettings().getMerged(i2) && this.getSettings().getMerged(i) return this.getSettings().getMerged(i2) && this.getSettings().getMerged(i) && this.area
&& this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))) .getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))).getMerged(i2) && this.area
.getMerged(i2) && this.area
.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2))).getMerged(i); .getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2))).getMerged(i);
} }
@ -1045,8 +1045,8 @@ public class Plot {
if (isDelete) { if (isDelete) {
this.removeSign(); this.removeSign();
} }
PlotUnlinkEvent event = this.eventDispatcher.callUnlink(getArea(), this, true, !isDelete, PlotUnlinkEvent event = this.eventDispatcher
isDelete ? PlotUnlinkEvent.REASON.DELETE : PlotUnlinkEvent.REASON.CLEAR); .callUnlink(getArea(), this, true, !isDelete, isDelete ? PlotUnlinkEvent.REASON.DELETE : PlotUnlinkEvent.REASON.CLEAR);
if (event.getEventResult() != Result.DENY) { if (event.getEventResult() != Result.DENY) {
this.unlinkPlot(event.isCreateRoad(), event.isCreateSign()); this.unlinkPlot(event.isCreateRoad(), event.isCreateSign());
} }
@ -1074,9 +1074,7 @@ public class Plot {
Plot current = queue.poll(); Plot current = queue.poll();
if (Plot.this.area.getTerrain() != PlotAreaTerrainType.NONE) { if (Plot.this.area.getTerrain() != PlotAreaTerrainType.NONE) {
try { try {
regionManager regionManager.regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, this);
.regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false,
this);
} catch (UnsupportedOperationException exception) { } catch (UnsupportedOperationException exception) {
MainUtil.sendMessage(null, MainUtil.sendMessage(null,
"Please ask md_5 to fix regenerateChunk() because it breaks plugins. We apologize for the inconvenience"); "Please ask md_5 to fix regenerateChunk() because it breaks plugins. We apologize for the inconvenience");
@ -1191,17 +1189,11 @@ public class Plot {
if (this.area.allowSigns()) { if (this.area.allowSigns()) {
Location location = manager.getSignLoc(this); Location location = manager.getSignLoc(this);
String id = this.id.toString(); String id = this.id.toString();
String[] lines = String[] lines = new String[] {Captions.OWNER_SIGN_LINE_1.formatted().replaceAll("%id%", id),
new String[] {Captions.OWNER_SIGN_LINE_1.formatted().replaceAll("%id%", id), Captions.OWNER_SIGN_LINE_2.formatted().replaceAll("%id%", id).replaceAll("%plr%", name),
Captions.OWNER_SIGN_LINE_2.formatted().replaceAll("%id%", id).replaceAll( Captions.OWNER_SIGN_LINE_3.formatted().replaceAll("%id%", id).replaceAll("%plr%", name),
"%plr%", name), Captions.OWNER_SIGN_LINE_4.formatted().replaceAll("%id%", id).replaceAll("%plr%", name)};
Captions.OWNER_SIGN_LINE_3.formatted().replaceAll("%id%", id).replaceAll( this.worldUtil.setSign(this.getWorldName(), location.getX(), location.getY(), location.getZ(), lines);
"%plr%", name),
Captions.OWNER_SIGN_LINE_4.formatted().replaceAll("%id%", id).replaceAll(
"%plr%", name)};
this.worldUtil
.setSign(this.getWorldName(), location.getX(), location.getY(), location.getZ(),
lines);
} }
} }
@ -1284,14 +1276,12 @@ public class Plot {
* @param ignorePluginFlags Whether or not to ignore {@link InternalFlag internal flags} * @param ignorePluginFlags Whether or not to ignore {@link InternalFlag internal flags}
* @return Collection containing all the flags that matched the given criteria * @return Collection containing all the flags that matched the given criteria
*/ */
public Collection<PlotFlag<?, ?>> getApplicableFlags(final boolean plotOnly, public Collection<PlotFlag<?, ?>> getApplicableFlags(final boolean plotOnly, final boolean ignorePluginFlags) {
final boolean ignorePluginFlags) {
if (!hasOwner()) { if (!hasOwner()) {
return Collections.emptyList(); return Collections.emptyList();
} }
final Map<Class<?>, PlotFlag<?, ?>> flags = new HashMap<>(); final Map<Class<?>, PlotFlag<?, ?>> flags = new HashMap<>();
if (!plotOnly && getArea() != null && !getArea().getFlagContainer().getFlagMap() if (!plotOnly && getArea() != null && !getArea().getFlagContainer().getFlagMap().isEmpty()) {
.isEmpty()) {
final Map<Class<?>, PlotFlag<?, ?>> flagMap = getArea().getFlagContainer().getFlagMap(); final Map<Class<?>, PlotFlag<?, ?>> flagMap = getArea().getFlagContainer().getFlagMap();
flags.putAll(flagMap); flags.putAll(flagMap);
} }
@ -1449,8 +1439,7 @@ public class Plot {
if (Settings.Backup.DELETE_ON_UNCLAIM) { if (Settings.Backup.DELETE_ON_UNCLAIM) {
// Destroy all backups when the plot is unclaimed // Destroy all backups when the plot is unclaimed
Objects.requireNonNull(PlotSquared.platform()).getBackupManager() Objects.requireNonNull(PlotSquared.platform()).getBackupManager().getProfile(current).destroy();
.getProfile(current).destroy();
} }
getArea().removePlot(getId()); getArea().removePlot(getId());
@ -1478,9 +1467,8 @@ public class Plot {
Location[] corners = getCorners(); Location[] corners = getCorners();
Location top = corners[0]; Location top = corners[0];
Location bot = corners[1]; Location bot = corners[1];
Location location = Location Location location = Location.at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), MathMan.average(bot.getY(), top.getY()),
.at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), MathMan.average(bot.getZ(), top.getZ()));
MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ()));
if (!isLoaded()) { if (!isLoaded()) {
result.accept(location); result.accept(location);
return; return;
@ -1501,14 +1489,12 @@ public class Plot {
Location[] corners = getCorners(); Location[] corners = getCorners();
Location top = corners[0]; Location top = corners[0];
Location bot = corners[1]; Location bot = corners[1];
Location location = Location Location location = Location.at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), MathMan.average(bot.getY(), top.getY()),
.at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), MathMan.average(bot.getZ(), top.getZ()));
MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ()));
if (!isLoaded()) { if (!isLoaded()) {
return location; return location;
} }
int y = this.worldUtil int y = this.worldUtil.getHighestBlockSynchronous(getWorldName(), location.getX(), location.getZ());
.getHighestBlockSynchronous(getWorldName(), location.getX(), location.getZ());
if (area.allowSigns()) { if (area.allowSigns()) {
y = Math.max(y, getManager().getSignLoc(this).getY()); y = Math.max(y, getManager().getSignLoc(this).getY());
} }
@ -1520,8 +1506,7 @@ public class Plot {
*/ */
@Deprecated public Location getSideSynchronous() { @Deprecated public Location getSideSynchronous() {
CuboidRegion largest = getLargestRegion(); CuboidRegion largest = getLargestRegion();
int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX();
+ largest.getMinimumPoint().getX();
int z = largest.getMinimumPoint().getZ() - 1; int z = largest.getMinimumPoint().getZ() - 1;
PlotManager manager = getManager(); PlotManager manager = getManager();
int y = isLoaded() ? this.worldUtil.getHighestBlockSynchronous(getWorldName(), x, z) : 62; int y = isLoaded() ? this.worldUtil.getHighestBlockSynchronous(getWorldName(), x, z) : 62;
@ -1533,8 +1518,7 @@ public class Plot {
public void getSide(Consumer<Location> result) { public void getSide(Consumer<Location> result) {
CuboidRegion largest = getLargestRegion(); CuboidRegion largest = getLargestRegion();
int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX();
+ largest.getMinimumPoint().getX();
int z = largest.getMinimumPoint().getZ() - 1; int z = largest.getMinimumPoint().getZ() - 1;
PlotManager manager = getManager(); PlotManager manager = getManager();
if (isLoaded()) { if (isLoaded()) {
@ -1564,16 +1548,14 @@ public class Plot {
} else { } else {
Location bottom = this.getBottomAbs(); Location bottom = this.getBottomAbs();
Location location = Location Location location = Location
.at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), bottom.getZ() + home.getZ(), home.getYaw(),
bottom.getZ() + home.getZ(), home.getYaw(), home.getPitch()); home.getPitch());
if (!isLoaded()) { if (!isLoaded()) {
return location; return location;
} }
if (!this.worldUtil.getBlockSynchronous(location).getBlockType().getMaterial() if (!this.worldUtil.getBlockSynchronous(location).getBlockType().getMaterial().isAir()) {
.isAir()) { location = location.withY(
location = location.withY(Math.max(1 + this.worldUtil Math.max(1 + this.worldUtil.getHighestBlockSynchronous(this.getWorldName(), location.getX(), location.getZ()), bottom.getY()));
.getHighestBlockSynchronous(this.getWorldName(), location.getX(),
location.getZ()), bottom.getY()));
} }
return location; return location;
} }
@ -1589,16 +1571,15 @@ public class Plot {
} else { } else {
Location bottom = this.getBottomAbs(); Location bottom = this.getBottomAbs();
Location location = Location Location location = Location
.at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), bottom.getZ() + home.getZ(), home.getYaw(),
bottom.getZ() + home.getZ(), home.getYaw(), home.getPitch()); home.getPitch());
if (!isLoaded()) { if (!isLoaded()) {
result.accept(location); result.accept(location);
return; return;
} }
this.worldUtil.getBlock(location, block -> { this.worldUtil.getBlock(location, block -> {
if (!block.getBlockType().getMaterial().isAir()) { if (!block.getBlockType().getMaterial().isAir()) {
this.worldUtil this.worldUtil.getHighestBlock(this.getWorldName(), location.getX(), location.getZ(),
.getHighestBlock(this.getWorldName(), location.getX(), location.getZ(),
y -> result.accept(location.withY(Math.max(1 + y, bottom.getY())))); y -> result.accept(location.withY(Math.max(1 + y, bottom.getY()))));
} else { } else {
result.accept(location); result.accept(location);
@ -1645,21 +1626,15 @@ public class Plot {
if (loc.getX() == Integer.MAX_VALUE && loc.getZ() == Integer.MAX_VALUE) { if (loc.getX() == Integer.MAX_VALUE && loc.getZ() == Integer.MAX_VALUE) {
// center // center
CuboidRegion largest = plot.getLargestRegion(); CuboidRegion largest = plot.getLargestRegion();
x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX();
>> 1) + largest.getMinimumPoint().getX(); z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ() >> 1) + largest.getMinimumPoint().getZ();
z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ()
>> 1) + largest.getMinimumPoint().getZ();
} else { } else {
// specific // specific
Location bot = plot.getBottomAbs(); Location bot = plot.getBottomAbs();
x = bot.getX() + loc.getX(); x = bot.getX() + loc.getX();
z = bot.getZ() + loc.getZ(); z = bot.getZ() + loc.getZ();
} }
int y = loc.getY() < 1 ? int y = loc.getY() < 1 ? (isLoaded() ? this.worldUtil.getHighestBlockSynchronous(plot.getWorldName(), x, z) + 1 : 63) : loc.getY();
(isLoaded() ?
this.worldUtil.getHighestBlockSynchronous(plot.getWorldName(), x, z) + 1 :
63) :
loc.getY();
return Location.at(plot.getWorldName(), x, y, z); return Location.at(plot.getWorldName(), x, y, z);
} }
// Side // Side
@ -1675,10 +1650,8 @@ public class Plot {
if (loc.getX() == Integer.MAX_VALUE && loc.getZ() == Integer.MAX_VALUE) { if (loc.getX() == Integer.MAX_VALUE && loc.getZ() == Integer.MAX_VALUE) {
// center // center
CuboidRegion largest = plot.getLargestRegion(); CuboidRegion largest = plot.getLargestRegion();
x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX();
>> 1) + largest.getMinimumPoint().getX(); z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ() >> 1) + largest.getMinimumPoint().getZ();
z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ()
>> 1) + largest.getMinimumPoint().getZ();
} else { } else {
// specific // specific
Location bot = plot.getBottomAbs(); Location bot = plot.getBottomAbs();
@ -1687,8 +1660,7 @@ public class Plot {
} }
if (loc.getY() < 1) { if (loc.getY() < 1) {
if (isLoaded()) { if (isLoaded()) {
this.worldUtil.getHighestBlock(plot.getWorldName(), x, z, this.worldUtil.getHighestBlock(plot.getWorldName(), x, z, y -> result.accept(Location.at(plot.getWorldName(), x, y + 1, z)));
y -> result.accept(Location.at(plot.getWorldName(), x, y + 1, z)));
} else { } else {
result.accept(Location.at(plot.getWorldName(), x, 63, z)); result.accept(Location.at(plot.getWorldName(), x, 63, z));
} }
@ -1704,10 +1676,8 @@ public class Plot {
public double getVolume() { public double getVolume() {
double count = 0; double count = 0;
for (CuboidRegion region : getRegions()) { for (CuboidRegion region : getRegions()) {
count += count += (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * (
(region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * ( region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1) * MAX_HEIGHT;
region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1)
* MAX_HEIGHT;
} }
return count; return count;
} }
@ -1790,14 +1760,11 @@ public class Plot {
* This should not need to be called * This should not need to be called
*/ */
public void refreshChunks() { public void refreshChunks() {
QueueCoordinator queue = this.blockQueue QueueCoordinator queue = this.blockQueue.getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(getWorldName()));
.getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(getWorldName()));
HashSet<BlockVector2> chunks = new HashSet<>(); HashSet<BlockVector2> chunks = new HashSet<>();
for (CuboidRegion region : Plot.this.getRegions()) { for (CuboidRegion region : Plot.this.getRegions()) {
for (int x = region.getMinimumPoint().getX() >> 4; for (int x = region.getMinimumPoint().getX() >> 4; x <= region.getMaximumPoint().getX() >> 4; x++) {
x <= region.getMaximumPoint().getX() >> 4; x++) { for (int z = region.getMinimumPoint().getZ() >> 4; z <= region.getMaximumPoint().getZ() >> 4; z++) {
for (int z = region.getMinimumPoint().getZ() >> 4;
z <= region.getMaximumPoint().getZ() >> 4; z++) {
if (chunks.add(BlockVector2.at(x, z))) { if (chunks.add(BlockVector2.at(x, z))) {
worldUtil.refreshChunk(x, z, getWorldName()); worldUtil.refreshChunk(x, z, getWorldName());
} }
@ -1816,8 +1783,7 @@ public class Plot {
} }
Location location = manager.getSignLoc(this); Location location = manager.getSignLoc(this);
QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(getWorldName())); QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(getWorldName()));
queue.setBlock(location.getX(), location.getY(), location.getZ(), queue.setBlock(location.getX(), location.getY(), location.getZ(), BlockTypes.AIR.getDefaultState());
BlockTypes.AIR.getDefaultState());
queue.enqueue(); queue.enqueue();
} }
@ -1829,8 +1795,7 @@ public class Plot {
this.setSign("unknown"); this.setSign("unknown");
return; return;
} }
this.impromptuPipeline this.impromptuPipeline.getSingle(this.getOwnerAbs(), (username, sign) -> this.setSign(username));
.getSingle(this.getOwnerAbs(), (username, sign) -> this.setSign(username));
} }
/** /**
@ -1852,14 +1817,12 @@ public class Plot {
return claim(player, teleport, schematic, true); return claim(player, teleport, schematic, true);
} }
public boolean claim(@Nonnull final PlotPlayer player, boolean teleport, String schematic, public boolean claim(@Nonnull final PlotPlayer player, boolean teleport, String schematic, boolean updateDB) {
boolean updateDB) {
if (updateDB) { if (updateDB) {
if (!create(player.getUUID(), true)) { if (!create(player.getUUID(), true)) {
logger.error( logger.error("[P2] Player {} attempted to claim plot {}, but the database failed to update", player.getName(),
"[P2] Player {} attempted to claim plot {}, but the database failed to update", this.getId().toCommaSeparatedString());
player.getName(), this.getId().toCommaSeparatedString());
return false; return false;
} }
} else { } else {
@ -1888,8 +1851,7 @@ public class Plot {
e.printStackTrace(); e.printStackTrace();
return true; return true;
} }
schematicHandler.paste(sch, this, 0, 1, 0, Settings.Schematics.PASTE_ON_TOP, schematicHandler.paste(sch, this, 0, 1, 0, Settings.Schematics.PASTE_ON_TOP, new RunnableVal<Boolean>() {
new RunnableVal<Boolean>() {
@Override public void run(Boolean value) { @Override public void run(Boolean value) {
if (value) { if (value) {
MainUtil.sendMessage(player, Captions.SCHEMATIC_PASTE_SUCCESS); MainUtil.sendMessage(player, Captions.SCHEMATIC_PASTE_SUCCESS);
@ -1935,11 +1897,9 @@ public class Plot {
DBFunc.createPlotAndSettings(this, () -> { DBFunc.createPlotAndSettings(this, () -> {
PlotArea plotworld = Plot.this.area; PlotArea plotworld = Plot.this.area;
if (notify && plotworld.isAutoMerge()) { if (notify && plotworld.isAutoMerge()) {
final PlotPlayer<?> player = PlotSquared.platform().getPlayerManager() final PlotPlayer<?> player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid);
.getPlayerIfExists(uuid);
PlotMergeEvent event = this.eventDispatcher PlotMergeEvent event = this.eventDispatcher.callMerge(this, Direction.ALL, Integer.MAX_VALUE, player);
.callMerge(this, Direction.ALL, Integer.MAX_VALUE, player);
if (event.getEventResult() == Result.DENY) { if (event.getEventResult() == Result.DENY) {
if (player != null) { if (player != null) {
@ -1952,8 +1912,7 @@ public class Plot {
}); });
return true; return true;
} }
logger.info("[P2] Failed to add plot {} to plot area {}", logger.info("[P2] Failed to add plot {} to plot area {}", this.getId().toCommaSeparatedString(), this.area.toString());
this.getId().toCommaSeparatedString(), this.area.toString());
return false; return false;
} }
@ -1961,8 +1920,7 @@ public class Plot {
* Sets components such as border, wall, floor. * Sets components such as border, wall, floor.
* (components are generator specific) * (components are generator specific)
*/ */
@Deprecated public boolean setComponent(String component, String blocks, @Deprecated public boolean setComponent(String component, String blocks, QueueCoordinator queue) {
QueueCoordinator queue) {
BlockBucket parsed = ConfigurationUtil.BLOCK_BUCKET.parseString(blocks); BlockBucket parsed = ConfigurationUtil.BLOCK_BUCKET.parseString(blocks);
if (parsed != null && parsed.isEmpty()) { if (parsed != null && parsed.isEmpty()) {
return false; return false;
@ -1976,8 +1934,7 @@ public class Plot {
* Retrieve the biome of the plot. * Retrieve the biome of the plot.
*/ */
public void getBiome(Consumer<BiomeType> result) { public void getBiome(Consumer<BiomeType> result) {
this.getCenter(location -> this.worldUtil this.getCenter(location -> this.worldUtil.getBiome(location.getWorldName(), location.getX(), location.getZ(), result));
.getBiome(location.getWorldName(), location.getX(), location.getZ(), result));
} }
//TODO Better documentation needed. //TODO Better documentation needed.
@ -1987,8 +1944,7 @@ public class Plot {
*/ */
@Deprecated public BiomeType getBiomeSynchronous() { @Deprecated public BiomeType getBiomeSynchronous() {
final Location location = this.getCenterSynchronous(); final Location location = this.getCenterSynchronous();
return this.worldUtil return this.worldUtil.getBiomeSynchronous(location.getWorldName(), location.getX(), location.getZ());
.getBiomeSynchronous(location.getWorldName(), location.getX(), location.getZ());
} }
/** /**
@ -2120,16 +2076,14 @@ public class Plot {
* - Used when a plot is merged<br> * - Used when a plot is merged<br>
*/ */
public void removeRoadEast() { public void removeRoadEast() {
if (this.area.getType() != PlotAreaType.NORMAL if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) {
&& this.area.getTerrain() == PlotAreaTerrainType.ROAD) {
Plot other = this.getRelative(Direction.EAST); Plot other = this.getRelative(Direction.EAST);
Location bot = other.getBottomAbs(); Location bot = other.getBottomAbs();
Location top = this.getTopAbs(); Location top = this.getTopAbs();
Location pos1 = Location.at(this.getWorldName(), top.getX(), 0, bot.getZ()); Location pos1 = Location.at(this.getWorldName(), top.getX(), 0, bot.getZ());
Location pos2 = Location.at(this.getWorldName(), bot.getX(), MAX_HEIGHT, top.getZ()); Location pos2 = Location.at(this.getWorldName(), bot.getX(), MAX_HEIGHT, top.getZ());
this.regionManager.regenerateRegion(pos1, pos2, true, null); this.regionManager.regenerateRegion(pos1, pos2, true, null);
} else if (this.area.getTerrain() } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove
!= PlotAreaTerrainType.ALL) { // no road generated => no road to remove
this.area.getPlotManager().removeRoadEast(this); this.area.getPlotManager().removeRoadEast(this);
} }
} }
@ -2289,10 +2243,8 @@ public class Plot {
} }
} else { } else {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(() -> {
String name = Plot.this.id + "," + Plot.this.area + ',' + String name = Plot.this.id + "," + Plot.this.area + ',' + PlayerManager.getName(Plot.this.getOwnerAbs());
PlayerManager.getName(Plot.this.getOwnerAbs()); boolean result = schematicHandler.save(value, Settings.Paths.SCHEMATICS + File.separator + name + ".schem");
boolean result = schematicHandler.save(value,
Settings.Paths.SCHEMATICS + File.separator + name + ".schem");
if (whenDone != null) { if (whenDone != null) {
whenDone.value = result; whenDone.value = result;
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
@ -2339,8 +2291,7 @@ public class Plot {
return false; return false;
} }
Plot other = (Plot) obj; Plot other = (Plot) obj;
return this.hashCode() == other.hashCode() && this.id.equals(other.id) return this.hashCode() == other.hashCode() && this.id.equals(other.id) && this.area == other.area;
&& this.area == other.area;
} }
/** /**
@ -2400,8 +2351,9 @@ public class Plot {
if (value) { if (value) {
Plot other = this.getRelative(direction).getBasePlot(false); Plot other = this.getRelative(direction).getBasePlot(false);
if (!other.equals(this.getBasePlot(false))) { if (!other.equals(this.getBasePlot(false))) {
Plot base = other.id.getY() < this.id.getY() Plot base = other.id.getY() < this.id.getY() || other.id.getY() == this.id.getY() && other.id.getX() < this.id.getX() ?
|| other.id.getY() == this.id.getY() && other.id.getX() < this.id.getX() ? other : this.origin; other :
this.origin;
this.origin.origin = base; this.origin.origin = base;
other.origin = base; other.origin = base;
this.origin = base; this.origin = base;
@ -2474,8 +2426,7 @@ public class Plot {
public boolean canClaim(@Nonnull PlotPlayer player) { public boolean canClaim(@Nonnull PlotPlayer player) {
PlotCluster cluster = this.getCluster(); PlotCluster cluster = this.getCluster();
if (cluster != null) { if (cluster != null) {
if (!cluster.isAdded(player.getUUID()) && !Permissions if (!cluster.isAdded(player.getUUID()) && !Permissions.hasPermission(player, "plots.admin.command.claim")) {
.hasPermission(player, "plots.admin.command.claim")) {
return false; return false;
} }
} }
@ -2491,16 +2442,14 @@ public class Plot {
* - Used when a plot is merged<br> * - Used when a plot is merged<br>
*/ */
public void removeRoadSouth() { public void removeRoadSouth() {
if (this.area.getType() != PlotAreaType.NORMAL if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) {
&& this.area.getTerrain() == PlotAreaTerrainType.ROAD) {
Plot other = this.getRelative(Direction.SOUTH); Plot other = this.getRelative(Direction.SOUTH);
Location bot = other.getBottomAbs(); Location bot = other.getBottomAbs();
Location top = this.getTopAbs(); Location top = this.getTopAbs();
Location pos1 = Location.at(this.getWorldName(), bot.getX(), 0, top.getZ()); Location pos1 = Location.at(this.getWorldName(), bot.getX(), 0, top.getZ());
Location pos2 = Location.at(this.getWorldName(), top.getX(), MAX_HEIGHT, bot.getZ()); Location pos2 = Location.at(this.getWorldName(), top.getX(), MAX_HEIGHT, bot.getZ());
this.regionManager.regenerateRegion(pos1, pos2, true, null); this.regionManager.regenerateRegion(pos1, pos2, true, null);
} else if (this.area.getTerrain() } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove
!= PlotAreaTerrainType.ALL) { // no road generated => no road to remove
this.getManager().removeRoadSouth(this); this.getManager().removeRoadSouth(this);
} }
} }
@ -2520,8 +2469,7 @@ public class Plot {
return false; return false;
} }
Set<Plot> connected = this.getConnectedPlots(); Set<Plot> connected = this.getConnectedPlots();
HashSet<PlotId> merged = HashSet<PlotId> merged = connected.stream().map(Plot::getId).collect(Collectors.toCollection(HashSet::new));
connected.stream().map(Plot::getId).collect(Collectors.toCollection(HashSet::new));
ArrayDeque<Plot> frontier = new ArrayDeque<>(connected); ArrayDeque<Plot> frontier = new ArrayDeque<>(connected);
Plot current; Plot current;
boolean toReturn = false; boolean toReturn = false;
@ -2534,10 +2482,8 @@ public class Plot {
Set<Plot> plots; Set<Plot> plots;
if ((dir == Direction.ALL || dir == Direction.NORTH) && !getMerged(Direction.NORTH)) { if ((dir == Direction.ALL || dir == Direction.NORTH) && !getMerged(Direction.NORTH)) {
Plot other = current.getRelative(Direction.NORTH); Plot other = current.getRelative(Direction.NORTH);
if (other != null && other.isOwner(uuid) && ( if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false))
other.getBasePlot(false).equals(current.getBasePlot(false)) || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) {
|| (plots = other.getConnectedPlots()).size() <= max && frontier
.addAll(plots) && (max -= plots.size()) != -1)) {
current.mergePlot(other, removeRoads); current.mergePlot(other, removeRoads);
merged.add(current.getId()); merged.add(current.getId());
merged.add(other.getId()); merged.add(other.getId());
@ -2551,13 +2497,10 @@ public class Plot {
} }
} }
} }
if (max >= 0 && (dir == Direction.ALL || dir == Direction.EAST) && !current if (max >= 0 && (dir == Direction.ALL || dir == Direction.EAST) && !current.getMerged(Direction.EAST)) {
.getMerged(Direction.EAST)) {
Plot other = current.getRelative(Direction.EAST); Plot other = current.getRelative(Direction.EAST);
if (other != null && other.isOwner(uuid) && ( if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false))
other.getBasePlot(false).equals(current.getBasePlot(false)) || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) {
|| (plots = other.getConnectedPlots()).size() <= max && frontier
.addAll(plots) && (max -= plots.size()) != -1)) {
current.mergePlot(other, removeRoads); current.mergePlot(other, removeRoads);
merged.add(current.getId()); merged.add(current.getId());
merged.add(other.getId()); merged.add(other.getId());
@ -2571,13 +2514,10 @@ public class Plot {
} }
} }
} }
if (max >= 0 && (dir == Direction.ALL || dir == Direction.SOUTH) && !getMerged( if (max >= 0 && (dir == Direction.ALL || dir == Direction.SOUTH) && !getMerged(Direction.SOUTH)) {
Direction.SOUTH)) {
Plot other = current.getRelative(Direction.SOUTH); Plot other = current.getRelative(Direction.SOUTH);
if (other != null && other.isOwner(uuid) && ( if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false))
other.getBasePlot(false).equals(current.getBasePlot(false)) || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) {
|| (plots = other.getConnectedPlots()).size() <= max && frontier
.addAll(plots) && (max -= plots.size()) != -1)) {
current.mergePlot(other, removeRoads); current.mergePlot(other, removeRoads);
merged.add(current.getId()); merged.add(current.getId());
merged.add(other.getId()); merged.add(other.getId());
@ -2591,13 +2531,10 @@ public class Plot {
} }
} }
} }
if (max >= 0 && (dir == Direction.ALL || dir == Direction.WEST) && !getMerged( if (max >= 0 && (dir == Direction.ALL || dir == Direction.WEST) && !getMerged(Direction.WEST)) {
Direction.WEST)) {
Plot other = current.getRelative(Direction.WEST); Plot other = current.getRelative(Direction.WEST);
if (other != null && other.isOwner(uuid) && ( if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false))
other.getBasePlot(false).equals(current.getBasePlot(false)) || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) {
|| (plots = other.getConnectedPlots()).size() <= max && frontier
.addAll(plots) && (max -= plots.size()) != -1)) {
current.mergePlot(other, removeRoads); current.mergePlot(other, removeRoads);
merged.add(current.getId()); merged.add(current.getId());
merged.add(other.getId()); merged.add(other.getId());
@ -2625,8 +2562,7 @@ public class Plot {
final FlagContainer flagContainer1 = this.getFlagContainer(); final FlagContainer flagContainer1 = this.getFlagContainer();
final FlagContainer flagContainer2 = plot.getFlagContainer(); final FlagContainer flagContainer2 = plot.getFlagContainer();
if (!flagContainer1.equals(flagContainer2)) { if (!flagContainer1.equals(flagContainer2)) {
boolean greater = boolean greater = flagContainer1.getFlagMap().size() > flagContainer2.getFlagMap().size();
flagContainer1.getFlagMap().size() > flagContainer2.getFlagMap().size();
if (greater) { if (greater) {
flagContainer1.addAll(flagContainer2.getFlagMap().values()); flagContainer1.addAll(flagContainer2.getFlagMap().values());
} else { } else {
@ -2669,14 +2605,12 @@ public class Plot {
* Remove the SE road (only effects terrain) * Remove the SE road (only effects terrain)
*/ */
public void removeRoadSouthEast() { public void removeRoadSouthEast() {
if (this.area.getType() != PlotAreaType.NORMAL if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) {
&& this.area.getTerrain() == PlotAreaTerrainType.ROAD) {
Plot other = this.getRelative(1, 1); Plot other = this.getRelative(1, 1);
Location pos1 = this.getTopAbs().add(1, 0, 1).withY(0); Location pos1 = this.getTopAbs().add(1, 0, 1).withY(0);
Location pos2 = other.getBottomAbs().subtract(1, 0, 1).withY(MAX_HEIGHT); Location pos2 = other.getBottomAbs().subtract(1, 0, 1).withY(MAX_HEIGHT);
this.regionManager.regenerateRegion(pos1, pos2, true, null); this.regionManager.regenerateRegion(pos1, pos2, true, null);
} else if (this.area.getTerrain() } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove
!= PlotAreaTerrainType.ALL) { // no road generated => no road to remove
this.area.getPlotManager().removeRoadSouthEast(this); this.area.getPlotManager().removeRoadSouthEast(this);
} }
} }
@ -2864,14 +2798,12 @@ public class Plot {
PlotId top = PlotId.of(current.getId().getX(), current.getId().getY()); PlotId top = PlotId.of(current.getId().getX(), current.getId().getY());
while (merge) { while (merge) {
merge = false; merge = false;
List<PlotId> ids = Lists.newArrayList((Iterable<? extends PlotId>) List<PlotId> ids = Lists.newArrayList((Iterable<? extends PlotId>) PlotId.PlotRangeIterator
PlotId.PlotRangeIterator.range(PlotId.of(bot.getX(), bot.getY() - 1), .range(PlotId.of(bot.getX(), bot.getY() - 1), PlotId.of(top.getX(), bot.getY() - 1)));
PlotId.of(top.getX(), bot.getY() - 1)));
boolean tmp = true; boolean tmp = true;
for (PlotId id : ids) { for (PlotId id : ids) {
Plot plot = this.area.getPlotAbs(id); Plot plot = this.area.getPlotAbs(id);
if (plot == null || !plot.getMerged(Direction.SOUTH) || visited if (plot == null || !plot.getMerged(Direction.SOUTH) || visited.contains(plot.getId())) {
.contains(plot.getId())) {
tmp = false; tmp = false;
} }
} }
@ -2879,14 +2811,12 @@ public class Plot {
merge = true; merge = true;
bot = PlotId.of(bot.getX(), bot.getY() - 1); bot = PlotId.of(bot.getX(), bot.getY() - 1);
} }
ids = Lists.newArrayList((Iterable<? extends PlotId>) ids = Lists.newArrayList((Iterable<? extends PlotId>) PlotId.PlotRangeIterator
PlotId.PlotRangeIterator.range(PlotId.of(top.getX() + 1, bot.getY()), .range(PlotId.of(top.getX() + 1, bot.getY()), PlotId.of(top.getX() + 1, top.getY())));
PlotId.of(top.getX() + 1, top.getY())));
tmp = true; tmp = true;
for (PlotId id : ids) { for (PlotId id : ids) {
Plot plot = this.area.getPlotAbs(id); Plot plot = this.area.getPlotAbs(id);
if (plot == null || !plot.getMerged(Direction.WEST) || visited if (plot == null || !plot.getMerged(Direction.WEST) || visited.contains(plot.getId())) {
.contains(plot.getId())) {
tmp = false; tmp = false;
} }
} }
@ -2894,14 +2824,12 @@ public class Plot {
merge = true; merge = true;
top = PlotId.of(top.getX() + 1, top.getY()); top = PlotId.of(top.getX() + 1, top.getY());
} }
ids = Lists.newArrayList((Iterable<? extends PlotId>) ids = Lists.newArrayList((Iterable<? extends PlotId>) PlotId.PlotRangeIterator
PlotId.PlotRangeIterator.range(PlotId.of(bot.getX(), top.getY() + 1), .range(PlotId.of(bot.getX(), top.getY() + 1), PlotId.of(top.getX(), top.getY() + 1)));
PlotId.of(top.getX(), top.getY() + 1)));
tmp = true; tmp = true;
for (PlotId id : ids) { for (PlotId id : ids) {
Plot plot = this.area.getPlotAbs(id); Plot plot = this.area.getPlotAbs(id);
if (plot == null || !plot.getMerged(Direction.NORTH) || visited if (plot == null || !plot.getMerged(Direction.NORTH) || visited.contains(plot.getId())) {
.contains(plot.getId())) {
tmp = false; tmp = false;
} }
} }
@ -2909,14 +2837,12 @@ public class Plot {
merge = true; merge = true;
top = PlotId.of(top.getX(), top.getY() + 1); top = PlotId.of(top.getX(), top.getY() + 1);
} }
ids = Lists.newArrayList((Iterable<? extends PlotId>) ids = Lists.newArrayList((Iterable<? extends PlotId>) PlotId.PlotRangeIterator
PlotId.PlotRangeIterator.range(PlotId.of(bot.getX() - 1, bot.getY()), .range(PlotId.of(bot.getX() - 1, bot.getY()), PlotId.of(bot.getX() - 1, top.getY())));
PlotId.of(bot.getX() - 1, top.getY())));
tmp = true; tmp = true;
for (PlotId id : ids) { for (PlotId id : ids) {
Plot plot = this.area.getPlotAbs(id); Plot plot = this.area.getPlotAbs(id);
if (plot == null || !plot.getMerged(Direction.EAST) || visited if (plot == null || !plot.getMerged(Direction.EAST) || visited.contains(plot.getId())) {
.contains(plot.getId())) {
tmp = false; tmp = false;
} }
} }
@ -2927,8 +2853,7 @@ public class Plot {
} }
Location gtopabs = this.area.getPlotAbs(top).getTopAbs(); Location gtopabs = this.area.getPlotAbs(top).getTopAbs();
Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs(); Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs();
visited.addAll(Lists.newArrayList((Iterable<? extends PlotId>) visited.addAll(Lists.newArrayList((Iterable<? extends PlotId>) PlotId.PlotRangeIterator.range(bot, top)));
PlotId.PlotRangeIterator.range(bot, top)));
for (int x = bot.getX(); x <= top.getX(); x++) { for (int x = bot.getX(); x <= top.getX(); x++) {
Plot plot = this.area.getPlotAbs(PlotId.of(x, top.getY())); Plot plot = this.area.getPlotAbs(PlotId.of(x, top.getY()));
if (plot.getMerged(Direction.SOUTH)) { if (plot.getMerged(Direction.SOUTH)) {
@ -2937,8 +2862,7 @@ public class Plot {
Location botabs = plot.getBottomAbs(); Location botabs = plot.getBottomAbs();
Location topabs = plot.getTopAbs(); Location topabs = plot.getTopAbs();
BlockVector3 pos1 = BlockVector3.at(botabs.getX(), 0, topabs.getZ() + 1); BlockVector3 pos1 = BlockVector3.at(botabs.getX(), 0, topabs.getZ() + 1);
BlockVector3 pos2 = BlockVector3 pos2 = BlockVector3.at(topabs.getX(), Plot.MAX_HEIGHT - 1, toploc.getZ());
BlockVector3.at(topabs.getX(), Plot.MAX_HEIGHT - 1, toploc.getZ());
regions.add(new CuboidRegion(pos1, pos2)); regions.add(new CuboidRegion(pos1, pos2));
if (plot.getMerged(Direction.SOUTHEAST)) { if (plot.getMerged(Direction.SOUTHEAST)) {
pos1 = BlockVector3.at(topabs.getX() + 1, 0, topabs.getZ() + 1); pos1 = BlockVector3.at(topabs.getX() + 1, 0, topabs.getZ() + 1);
@ -2957,8 +2881,7 @@ public class Plot {
Location botabs = plot.getBottomAbs(); Location botabs = plot.getBottomAbs();
Location topabs = plot.getTopAbs(); Location topabs = plot.getTopAbs();
BlockVector3 pos1 = BlockVector3.at(topabs.getX() + 1, 0, botabs.getZ()); BlockVector3 pos1 = BlockVector3.at(topabs.getX() + 1, 0, botabs.getZ());
BlockVector3 pos2 = BlockVector3 pos2 = BlockVector3.at(toploc.getX(), Plot.MAX_HEIGHT - 1, topabs.getZ());
BlockVector3.at(toploc.getX(), Plot.MAX_HEIGHT - 1, topabs.getZ());
regions.add(new CuboidRegion(pos1, pos2)); regions.add(new CuboidRegion(pos1, pos2));
if (plot.getMerged(Direction.SOUTHEAST)) { if (plot.getMerged(Direction.SOUTHEAST)) {
pos1 = BlockVector3.at(topabs.getX() + 1, 0, topabs.getZ() + 1); pos1 = BlockVector3.at(topabs.getX() + 1, 0, topabs.getZ() + 1);
@ -2969,8 +2892,7 @@ public class Plot {
} }
} }
BlockVector3 pos1 = BlockVector3.at(gbotabs.getX(), 0, gbotabs.getZ()); BlockVector3 pos1 = BlockVector3.at(gbotabs.getX(), 0, gbotabs.getZ());
BlockVector3 pos2 = BlockVector3 pos2 = BlockVector3.at(gtopabs.getX(), Plot.MAX_HEIGHT - 1, gtopabs.getZ());
BlockVector3.at(gtopabs.getX(), Plot.MAX_HEIGHT - 1, gtopabs.getZ());
regions.add(new CuboidRegion(pos1, pos2)); regions.add(new CuboidRegion(pos1, pos2));
} }
return regions; return regions;
@ -2986,8 +2908,7 @@ public class Plot {
CuboidRegion max = null; CuboidRegion max = null;
double area = Double.NEGATIVE_INFINITY; double area = Double.NEGATIVE_INFINITY;
for (CuboidRegion region : regions) { for (CuboidRegion region : regions) {
double current = double current = (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * (
(region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * (
region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1); region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1);
if (current > area) { if (current > area) {
max = region; max = region;
@ -3016,12 +2937,9 @@ public class Plot {
if (players.isEmpty()) { if (players.isEmpty()) {
return; return;
} }
final String string = final String string = Captions.PLOT_DEBUG.getTranslated().replace("%plot%", this.toString()).replace("%message%", message);
Captions.PLOT_DEBUG.getTranslated().replace("%plot%", this.toString())
.replace("%message%", message);
for (final PlotPlayer<?> player : players) { for (final PlotPlayer<?> player : players) {
if (isOwner(player.getUUID()) || Permissions if (isOwner(player.getUUID()) || Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_DEBUG_OTHER)) {
.hasPermission(player, Captions.PERMISSION_ADMIN_DEBUG_OTHER)) {
player.sendMessage(string); player.sendMessage(string);
} }
} }
@ -3037,8 +2955,7 @@ public class Plot {
public List<Location> getAllCorners() { public List<Location> getAllCorners() {
Area area = new Area(); Area area = new Area();
for (CuboidRegion region : this.getRegions()) { for (CuboidRegion region : this.getRegions()) {
Rectangle2D rect = new Rectangle2D.Double(region.getMinimumPoint().getX() - 0.6, Rectangle2D rect = new Rectangle2D.Double(region.getMinimumPoint().getX() - 0.6, region.getMinimumPoint().getZ() - 0.6,
region.getMinimumPoint().getZ() - 0.6,
region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + 1.2, region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + 1.2,
region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + 1.2); region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + 1.2);
Area rectArea = new Area(rect); Area rectArea = new Area(rect);
@ -3074,26 +2991,22 @@ public class Plot {
* @param cause the cause of the teleport * @param cause the cause of the teleport
* @param resultConsumer Called with the result of the teleportation * @param resultConsumer Called with the result of the teleportation
*/ */
public void teleportPlayer(final PlotPlayer player, TeleportCause cause, public void teleportPlayer(final PlotPlayer player, TeleportCause cause, Consumer<Boolean> resultConsumer) {
Consumer<Boolean> resultConsumer) {
Plot plot = this.getBasePlot(false); Plot plot = this.getBasePlot(false);
Result result = Result result = this.eventDispatcher.callTeleport(player, player.getLocation(), plot).getEventResult();
this.eventDispatcher.callTeleport(player, player.getLocation(), plot).getEventResult();
if (result == Result.DENY) { if (result == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Teleport"); sendMessage(player, Captions.EVENT_DENIED, "Teleport");
resultConsumer.accept(false); resultConsumer.accept(false);
return; return;
} }
final Consumer<Location> locationConsumer = location -> { final Consumer<Location> locationConsumer = location -> {
if (Settings.Teleport.DELAY == 0 || Permissions if (Settings.Teleport.DELAY == 0 || Permissions.hasPermission(player, "plots.teleport.delay.bypass")) {
.hasPermission(player, "plots.teleport.delay.bypass")) {
MainUtil.sendMessage(player, Captions.TELEPORTED_TO_PLOT); MainUtil.sendMessage(player, Captions.TELEPORTED_TO_PLOT);
player.teleport(location, cause); player.teleport(location, cause);
resultConsumer.accept(true); resultConsumer.accept(true);
return; return;
} }
MainUtil MainUtil.sendMessage(player, Captions.TELEPORT_IN_SECONDS, Settings.Teleport.DELAY + "");
.sendMessage(player, Captions.TELEPORT_IN_SECONDS, Settings.Teleport.DELAY + "");
final String name = player.getName(); final String name = player.getName();
TaskManager.addToTeleportQueue(name); TaskManager.addToTeleportQueue(name);
TaskManager.runTaskLater(() -> { TaskManager.runTaskLater(() -> {
@ -3103,7 +3016,8 @@ public class Plot {
try { try {
MainUtil.sendMessage(player, Captions.TELEPORTED_TO_PLOT); MainUtil.sendMessage(player, Captions.TELEPORTED_TO_PLOT);
player.teleport(location, cause); player.teleport(location, cause);
} catch (final Exception ignored) {} } catch (final Exception ignored) {
}
}, TaskTime.seconds(Settings.Teleport.DELAY)); }, TaskTime.seconds(Settings.Teleport.DELAY));
resultConsumer.accept(true); resultConsumer.accept(true);
}; };
@ -3124,12 +3038,11 @@ public class Plot {
return false; return false;
} }
if (!isMerged()) { if (!isMerged()) {
return PlotSquared.platform().getPlayerManager() return PlotSquared.platform().getPlayerManager().getPlayerIfExists(Objects.requireNonNull(this.getOwnerAbs())) != null;
.getPlayerIfExists(Objects.requireNonNull(this.getOwnerAbs())) != null;
} }
for (final Plot current : getConnectedPlots()) { for (final Plot current : getConnectedPlots()) {
if (current.hasOwner() && PlotSquared.platform().getPlayerManager() if (current.hasOwner()
.getPlayerIfExists(Objects.requireNonNull(current.getOwnerAbs())) != null) { && PlotSquared.platform().getPlayerManager().getPlayerIfExists(Objects.requireNonNull(current.getOwnerAbs())) != null) {
return true; return true;
} }
} }
@ -3145,10 +3058,8 @@ public class Plot {
* @param blocks Pattern to use the generation * @param blocks Pattern to use the generation
* @return True if the component was set successfully * @return True if the component was set successfully
*/ */
public boolean setComponent(String component, Pattern blocks, public boolean setComponent(String component, Pattern blocks, @Nullable QueueCoordinator queue) {
@Nullable QueueCoordinator queue) { PlotComponentSetEvent event = this.eventDispatcher.callComponentSet(this, component, blocks);
PlotComponentSetEvent event =
this.eventDispatcher.callComponentSet(this, component, blocks);
component = event.getComponent(); component = event.getComponent();
blocks = event.getPattern(); blocks = event.getPattern();
return this.getManager().setComponent(this.getId(), component, blocks, queue); return this.getManager().setComponent(this.getId(), component, blocks, queue);
@ -3157,8 +3068,7 @@ public class Plot {
public int getDistanceFromOrigin() { public int getDistanceFromOrigin() {
Location bot = getManager().getPlotBottomLocAbs(id); Location bot = getManager().getPlotBottomLocAbs(id);
Location top = getManager().getPlotTopLocAbs(id); Location top = getManager().getPlotTopLocAbs(id);
return Math.max(Math.max(Math.abs(bot.getX()), Math.abs(bot.getZ())), return Math.max(Math.max(Math.abs(bot.getX()), Math.abs(bot.getZ())), Math.max(Math.abs(top.getX()), Math.abs(top.getZ())));
Math.max(Math.abs(top.getX()), Math.abs(top.getZ())));
} }
/** /**
@ -3246,10 +3156,8 @@ public class Plot {
* @param allowSwap whether to swap plots * @param allowSwap whether to swap plots
* @return success * @return success
*/ */
public CompletableFuture<Boolean> move(final Plot destination, final Runnable whenDone, public CompletableFuture<Boolean> move(final Plot destination, final Runnable whenDone, boolean allowSwap) {
boolean allowSwap) { final PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(), destination.getId().getY() - this.getId().getY());
final PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(),
destination.getId().getY() - this.getId().getY());
Location db = destination.getBottomAbs(); Location db = destination.getBottomAbs();
Location ob = this.getBottomAbs(); Location ob = this.getBottomAbs();
final int offsetX = db.getX() - ob.getX(); final int offsetX = db.getX() - ob.getX();
@ -3315,8 +3223,7 @@ public class Plot {
Location[] corners = getCorners(getWorldName(), region); Location[] corners = getCorners(getWorldName(), region);
Location pos1 = corners[0]; Location pos1 = corners[0];
Location pos2 = corners[1]; Location pos2 = corners[1];
Location pos3 = Location pos3 = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName());
pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName());
regionManager.swap(pos1, pos2, pos3, this); regionManager.swap(pos1, pos2, pos3, this);
} }
} }
@ -3326,8 +3233,7 @@ public class Plot {
@Override public void run() { @Override public void run() {
if (regions.isEmpty()) { if (regions.isEmpty()) {
Plot plot = destination.getRelative(0, 0); Plot plot = destination.getRelative(0, 0);
Plot originPlot = originArea Plot originPlot = originArea.getPlotAbs(PlotId.of(plot.id.getX() - offset.getX(), plot.id.getY() - offset.getY()));
.getPlotAbs(PlotId.of(plot.id.getX() - offset.getX(), plot.id.getY() - offset.getY()));
final Runnable clearDone = () -> { final Runnable clearDone = () -> {
for (final Plot current : plot.getConnectedPlots()) { for (final Plot current : plot.getConnectedPlots()) {
getManager().claimPlot(current); getManager().claimPlot(current);
@ -3347,8 +3253,7 @@ public class Plot {
Location[] corners = getCorners(getWorldName(), region); Location[] corners = getCorners(getWorldName(), region);
final Location pos1 = corners[0]; final Location pos1 = corners[0];
final Location pos2 = corners[1]; final Location pos2 = corners[1];
Location newPos = Location newPos = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName());
pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName());
regionManager.copyRegion(pos1, pos2, newPos, task); regionManager.copyRegion(pos1, pos2, newPos, task);
} }
}.run(); }.run();
@ -3365,8 +3270,7 @@ public class Plot {
* @return * @return
*/ */
public boolean copy(final Plot destination, final Runnable whenDone) { public boolean copy(final Plot destination, final Runnable whenDone) {
PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(), PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(), destination.getId().getY() - this.getId().getY());
destination.getId().getY() - this.getId().getY());
Location db = destination.getBottomAbs(); Location db = destination.getBottomAbs();
Location ob = this.getBottomAbs(); Location ob = this.getBottomAbs();
final int offsetX = db.getX() - ob.getX(); final int offsetX = db.getX() - ob.getX();
@ -3395,8 +3299,7 @@ public class Plot {
other.getFlagContainer().addAll(plot.getFlagContainer().getFlagMap().values()); other.getFlagContainer().addAll(plot.getFlagContainer().getFlagMap().values());
// Update the database // Update the database
for (final PlotFlag<?, ?> flag : existingFlags) { for (final PlotFlag<?, ?> flag : existingFlags) {
final PlotFlag<?, ?> newFlag = final PlotFlag<?, ?> newFlag = other.getFlagContainer().queryLocal(flag.getClass());
other.getFlagContainer().queryLocal(flag.getClass());
if (other.getFlagContainer().queryLocal(flag.getClass()) == null) { if (other.getFlagContainer().queryLocal(flag.getClass()) == null) {
DBFunc.removeFlag(other, flag); DBFunc.removeFlag(other, flag);
} else { } else {
@ -3442,8 +3345,7 @@ public class Plot {
Location[] corners = getCorners(getWorldName(), region); Location[] corners = getCorners(getWorldName(), region);
Location pos1 = corners[0]; Location pos1 = corners[0];
Location pos2 = corners[1]; Location pos2 = corners[1];
Location newPos = Location newPos = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName());
pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName());
regionManager.copyRegion(pos1, pos2, newPos, this); regionManager.copyRegion(pos1, pos2, newPos, this);
} }
}; };
@ -3506,8 +3408,7 @@ public class Plot {
int num = this.getConnectedPlots().size(); int num = this.getConnectedPlots().size();
String alias = !this.getAlias().isEmpty() ? this.getAlias() : Captions.NONE.getTranslated(); String alias = !this.getAlias().isEmpty() ? this.getAlias() : Captions.NONE.getTranslated();
Location bot = this.getCorners()[0]; Location bot = this.getCorners()[0];
PlotSquared.platform().getWorldUtil() PlotSquared.platform().getWorldUtil().getBiome(this.getWorldName(), bot.getX(), bot.getZ(), biome -> {
.getBiome(this.getWorldName(), bot.getX(), bot.getZ(), biome -> {
String info = iInfo; String info = iInfo;
String trusted = PlayerManager.getPlayerList(this.getTrusted()); String trusted = PlayerManager.getPlayerList(this.getTrusted());
String members = PlayerManager.getPlayerList(this.getMembers()); String members = PlayerManager.getPlayerList(this.getMembers());
@ -3546,8 +3447,7 @@ public class Plot {
} else { } else {
value = flag.toString(); value = flag.toString();
} }
flags.append(prefix).append(CaptionUtility flags.append(prefix).append(CaptionUtility.format(player, Captions.PLOT_FLAG_LIST.getTranslated(), flag.getName(),
.format(player, Captions.PLOT_FLAG_LIST.getTranslated(), flag.getName(),
CaptionUtility.formatRaw(player, value.toString(), ""))); CaptionUtility.formatRaw(player, value.toString(), "")));
prefix = ", "; prefix = ", ";
} }
@ -3556,9 +3456,7 @@ public class Plot {
String owner = this.getOwners().isEmpty() ? "unowned" : PlayerManager.getPlayerList(this.getOwners()); String owner = this.getOwners().isEmpty() ? "unowned" : PlayerManager.getPlayerList(this.getOwners());
if (this.getArea() != null) { if (this.getArea() != null) {
info = info.replace("%area%", info = info.replace("%area%",
this.getArea().getWorldName() + (this.getArea().getId() == null ? this.getArea().getWorldName() + (this.getArea().getId() == null ? "" : "(" + this.getArea().getId() + ")"));
"" :
"(" + this.getArea().getId() + ")"));
} else { } else {
info = info.replace("%area%", Captions.NONE.getTranslated()); info = info.replace("%area%", Captions.NONE.getTranslated());
} }
@ -3581,29 +3479,23 @@ public class Plot {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(() -> {
String info1; String info1;
if (Settings.Ratings.USE_LIKES) { if (Settings.Ratings.USE_LIKES) {
info1 = newInfo.replaceAll("%rating%", info1 = newInfo.replaceAll("%rating%", String.format("%.0f%%", Like.getLikesPercentage(this) * 100D));
String.format("%.0f%%", Like.getLikesPercentage(this) * 100D));
} else { } else {
int max = 10; int max = 10;
if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) {
.isEmpty()) {
max = 8; max = 8;
} }
if (full && Settings.Ratings.CATEGORIES != null if (full && Settings.Ratings.CATEGORIES != null && Settings.Ratings.CATEGORIES.size() > 1) {
&& Settings.Ratings.CATEGORIES.size() > 1) {
double[] ratings = this.getAverageRatings(); double[] ratings = this.getAverageRatings();
String rating = ""; String rating = "";
String prefix = ""; String prefix = "";
for (int i = 0; i < ratings.length; i++) { for (int i = 0; i < ratings.length; i++) {
rating += rating += prefix + Settings.Ratings.CATEGORIES.get(i) + '=' + String.format("%.1f", ratings[i]);
prefix + Settings.Ratings.CATEGORIES.get(i) + '=' + String
.format("%.1f", ratings[i]);
prefix = ","; prefix = ",";
} }
info1 = newInfo.replaceAll("%rating%", rating); info1 = newInfo.replaceAll("%rating%", rating);
} else { } else {
info1 = newInfo.replaceAll("%rating%", info1 = newInfo.replaceAll("%rating%", String.format("%.1f", this.getAverageRating()) + '/' + max);
String.format("%.1f", this.getAverageRating()) + '/' + max);
} }
} }
future.complete(info1); future.complete(info1);

View File

@ -32,6 +32,7 @@ import com.plotsquared.core.queue.QueueCoordinator;
import com.plotsquared.core.util.FileBytes; import com.plotsquared.core.util.FileBytes;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.io.IOException; import java.io.IOException;
import java.util.Collections; import java.util.Collections;
@ -42,7 +43,7 @@ public abstract class PlotManager {
private final PlotArea plotArea; private final PlotArea plotArea;
public PlotManager(PlotArea plotArea) { public PlotManager(@Nonnull PlotArea plotArea) {
this.plotArea = plotArea; this.plotArea = plotArea;
} }
@ -55,35 +56,33 @@ public abstract class PlotManager {
public abstract PlotId getPlotId(int x, int y, int z); public abstract PlotId getPlotId(int x, int y, int z);
// If you have a circular plot, just return the corner if it were a square // If you have a circular plot, just return the corner if it were a square
public abstract Location getPlotBottomLocAbs(PlotId plotId); public abstract Location getPlotBottomLocAbs(@Nonnull PlotId plotId);
// the same applies here // the same applies here
public abstract Location getPlotTopLocAbs(PlotId plotId); public abstract Location getPlotTopLocAbs(@Nonnull PlotId plotId);
/* /*
* Plot clearing (return false if you do not support some method) * Plot clearing (return false if you do not support some method)
*/ */
public boolean clearPlot(Plot plot, Runnable whenDone) { public boolean clearPlot(@Nonnull Plot plot, @Nullable Runnable whenDone) {
return clearPlot(plot, whenDone, null); return clearPlot(plot, whenDone, null);
} }
public boolean claimPlot(Plot plot) { public boolean claimPlot(@Nonnull Plot plot) {
return claimPlot(plot, null); return claimPlot(plot, null);
} }
public boolean unClaimPlot(Plot plot, Runnable whenDone) { public boolean unClaimPlot(@Nonnull Plot plot, @Nullable Runnable whenDone) {
return unClaimPlot(plot, whenDone, null); return unClaimPlot(plot, whenDone, null);
} }
public abstract boolean clearPlot(Plot plot, Runnable whenDone, public abstract boolean clearPlot(@Nonnull Plot plot, @Nullable Runnable whenDone, @Nullable QueueCoordinator queue);
@Nullable QueueCoordinator queue);
public abstract boolean claimPlot(Plot plot, @Nullable QueueCoordinator queue); public abstract boolean claimPlot(@Nonnull Plot plot, @Nullable QueueCoordinator queue);
public abstract boolean unClaimPlot(Plot plot, Runnable whenDone, public abstract boolean unClaimPlot(@Nonnull Plot plot, @Nullable Runnable whenDone, @Nullable QueueCoordinator queue);
@Nullable QueueCoordinator queue);
/** /**
* Retrieves the location of where a sign should be for a plot. * Retrieves the location of where a sign should be for a plot.
@ -91,90 +90,90 @@ public abstract class PlotManager {
* @param plot The plot * @param plot The plot
* @return The location where a sign should be * @return The location where a sign should be
*/ */
public abstract Location getSignLoc(Plot plot); public abstract Location getSignLoc(@Nonnull Plot plot);
/* /*
* Plot set functions (return false if you do not support the specific set * Plot set functions (return false if you do not support the specific set
* method). * method).
*/ */
public abstract String[] getPlotComponents(PlotId plotId); public abstract String[] getPlotComponents(@Nonnull PlotId plotId);
public boolean setComponent(PlotId plotId, String component, Pattern blocks) { public boolean setComponent(@Nonnull PlotId plotId, @Nonnull String component, @Nonnull Pattern blocks) {
return setComponent(plotId, component, blocks, null); return setComponent(plotId, component, blocks, null);
} }
public abstract boolean setComponent(PlotId plotId, String component, Pattern blocks, public abstract boolean setComponent(@Nonnull PlotId plotId,
@Nonnull String component,
@Nonnull Pattern blocks,
@Nullable QueueCoordinator queue); @Nullable QueueCoordinator queue);
/* /*
* PLOT MERGING (return false if your generator does not support plot * PLOT MERGING (return false if your generator does not support plot
* merging). * merging).
*/ */
public boolean createRoadEast(Plot plot) { public boolean createRoadEast(@Nonnull Plot plot) {
return createRoadEast(plot, null); return createRoadEast(plot, null);
} }
public boolean createRoadSouth(Plot plot) { public boolean createRoadSouth(@Nonnull Plot plot) {
return createRoadSouth(plot, null); return createRoadSouth(plot, null);
} }
public boolean createRoadSouthEast(Plot plot) { public boolean createRoadSouthEast(@Nonnull Plot plot) {
return createRoadSouthEast(plot, null); return createRoadSouthEast(plot, null);
} }
public boolean removeRoadEast(Plot plot) { public boolean removeRoadEast(@Nonnull Plot plot) {
return removeRoadEast(plot, null); return removeRoadEast(plot, null);
} }
public boolean removeRoadSouth(Plot plot) { public boolean removeRoadSouth(@Nonnull Plot plot) {
return removeRoadSouth(plot, null); return removeRoadSouth(plot, null);
} }
public boolean removeRoadSouthEast(Plot plot) { public boolean removeRoadSouthEast(@Nonnull Plot plot) {
return removeRoadSouthEast(plot, null); return removeRoadSouthEast(plot, null);
} }
public boolean startPlotMerge(List<PlotId> plotIds) { public boolean startPlotMerge(@Nonnull List<PlotId> plotIds) {
return startPlotMerge(plotIds, null); return startPlotMerge(plotIds, null);
} }
public boolean startPlotUnlink(List<PlotId> plotIds) { public boolean startPlotUnlink(@Nonnull List<PlotId> plotIds) {
return startPlotUnlink(plotIds, null); return startPlotUnlink(plotIds, null);
} }
public boolean finishPlotMerge(List<PlotId> plotIds) { public boolean finishPlotMerge(@Nonnull List<PlotId> plotIds) {
return finishPlotMerge(plotIds, null); return finishPlotMerge(plotIds, null);
} }
public boolean finishPlotUnlink(List<PlotId> plotIds) { public boolean finishPlotUnlink(@Nonnull List<PlotId> plotIds) {
return finishPlotUnlink(plotIds, null); return finishPlotUnlink(plotIds, null);
} }
public abstract boolean createRoadEast(Plot plot, @Nullable QueueCoordinator queue); public abstract boolean createRoadEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue);
public abstract boolean createRoadSouth(Plot plot, @Nullable QueueCoordinator queue); public abstract boolean createRoadSouth(@Nonnull Plot plot, @Nullable QueueCoordinator queue);
public abstract boolean createRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue); public abstract boolean createRoadSouthEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue);
public abstract boolean removeRoadEast(Plot plot, @Nullable QueueCoordinator queue); public abstract boolean removeRoadEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue);
public abstract boolean removeRoadSouth(Plot plot, @Nullable QueueCoordinator queue); public abstract boolean removeRoadSouth(@Nonnull Plot plot, @Nullable QueueCoordinator queue);
public abstract boolean removeRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue); public abstract boolean removeRoadSouthEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue);
public abstract boolean startPlotMerge(List<PlotId> plotIds, @Nullable QueueCoordinator queue); public abstract boolean startPlotMerge(@Nonnull List<PlotId> plotIds, @Nullable QueueCoordinator queue);
public abstract boolean startPlotUnlink(List<PlotId> plotIds, @Nullable QueueCoordinator queue); public abstract boolean startPlotUnlink(@Nonnull List<PlotId> plotIds, @Nullable QueueCoordinator queue);
public abstract boolean finishPlotMerge(List<PlotId> plotIds, @Nullable QueueCoordinator queue); public abstract boolean finishPlotMerge(@Nonnull List<PlotId> plotIds, @Nullable QueueCoordinator queue);
public abstract boolean finishPlotUnlink(List<PlotId> plotIds, public abstract boolean finishPlotUnlink(@Nonnull List<PlotId> plotIds, @Nullable QueueCoordinator queue);
@Nullable QueueCoordinator queue);
public void exportTemplate() throws IOException { public void exportTemplate() throws IOException {
HashSet<FileBytes> files = new HashSet<>(Collections.singletonList( HashSet<FileBytes> files =
new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", new HashSet<>(Collections.singletonList(new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", Template.getBytes(plotArea))));
Template.getBytes(plotArea))));
Template.zipAll(plotArea.getWorldName(), files); Template.zipAll(plotArea.getWorldName(), files);
} }

View File

@ -35,6 +35,7 @@ import com.plotsquared.core.queue.QueueCoordinator;
import com.plotsquared.core.util.FileUtils; import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -55,19 +56,17 @@ public class SinglePlotManager extends PlotManager {
return PlotId.of(0, 0); return PlotId.of(0, 0);
} }
@Override public Location getPlotBottomLocAbs(@Nonnull final PlotId plotId) { @Override public Location getPlotBottomLocAbs(@Nonnull final @NotNull PlotId plotId) {
return Location.at(plotId.toCommaSeparatedString(), -30000000, 0, -30000000); return Location.at(plotId.toCommaSeparatedString(), -30000000, 0, -30000000);
} }
@Override public Location getPlotTopLocAbs(@Nonnull final PlotId plotId) { @Override public Location getPlotTopLocAbs(@Nonnull final @NotNull PlotId plotId) {
return Location.at(plotId.toCommaSeparatedString(), 30000000, 0, 30000000); return Location.at(plotId.toCommaSeparatedString(), 30000000, 0, 30000000);
} }
@Override @Override public boolean clearPlot(@NotNull Plot plot, final Runnable whenDone, @Nullable QueueCoordinator queue) {
public boolean clearPlot(Plot plot, final Runnable whenDone, @Nullable QueueCoordinator queue) {
PlotSquared.platform().getSetupUtils().unload(plot.getWorldName(), false); PlotSquared.platform().getSetupUtils().unload(plot.getWorldName(), false);
final File worldFolder = final File worldFolder = new File(PlotSquared.platform().getWorldContainer(), plot.getWorldName());
new File(PlotSquared.platform().getWorldContainer(), plot.getWorldName());
TaskManager.getPlatformImplementation().taskAsync(() -> { TaskManager.getPlatformImplementation().taskAsync(() -> {
FileUtils.deleteDirectory(worldFolder); FileUtils.deleteDirectory(worldFolder);
if (whenDone != null) { if (whenDone != null) {
@ -77,73 +76,68 @@ public class SinglePlotManager extends PlotManager {
return true; return true;
} }
@Override public boolean claimPlot(Plot plot, @Nullable QueueCoordinator queue) { @Override public boolean claimPlot(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
// TODO // TODO
return true; return true;
} }
@Override @Override public boolean unClaimPlot(@NotNull Plot plot, Runnable whenDone, @Nullable QueueCoordinator queue) {
public boolean unClaimPlot(Plot plot, Runnable whenDone, @Nullable QueueCoordinator queue) {
if (whenDone != null) { if (whenDone != null) {
whenDone.run(); whenDone.run();
} }
return true; return true;
} }
@Override public Location getSignLoc(Plot plot) { @Override public Location getSignLoc(@NotNull Plot plot) {
return null; return null;
} }
@Override public String[] getPlotComponents(PlotId plotId) { @Override public String[] getPlotComponents(@NotNull PlotId plotId) {
return new String[0]; return new String[0];
} }
@Override public boolean setComponent(PlotId plotId, String component, Pattern blocks,
@Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean createRoadEast(Plot plot, @Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean createRoadSouth(Plot plot, @Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean createRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean removeRoadEast(Plot plot, @Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean removeRoadSouth(Plot plot, @Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean removeRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) {
return false;
}
@Override @Override
public boolean startPlotMerge(List<PlotId> plotIds, @Nullable QueueCoordinator queue) { public boolean setComponent(@NotNull PlotId plotId, @NotNull String component, @NotNull Pattern blocks, @Nullable QueueCoordinator queue) {
return false; return false;
} }
@Override @Override public boolean createRoadEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
public boolean startPlotUnlink(List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
return false; return false;
} }
@Override @Override public boolean createRoadSouth(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
public boolean finishPlotMerge(List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
return false; return false;
} }
@Override @Override public boolean createRoadSouthEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
public boolean finishPlotUnlink(List<PlotId> plotIds, @Nullable QueueCoordinator queue) { return false;
}
@Override public boolean removeRoadEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean removeRoadSouth(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean removeRoadSouthEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean startPlotMerge(@NotNull List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean startPlotUnlink(@NotNull List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean finishPlotMerge(@NotNull List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
return false;
}
@Override public boolean finishPlotUnlink(@NotNull List<PlotId> plotIds, @Nullable QueueCoordinator queue) {
return false; return false;
} }

View File

@ -40,8 +40,7 @@ public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator
private final PlotArea area; private final PlotArea area;
public AreaBoundDelegateQueueCoordinator(@Nonnull final PlotArea area, public AreaBoundDelegateQueueCoordinator(@Nonnull final PlotArea area, @Nullable final QueueCoordinator parent) {
@Nullable final QueueCoordinator parent) {
super(parent); super(parent);
this.area = Objects.requireNonNull(area); this.area = Objects.requireNonNull(area);
} }
@ -50,42 +49,42 @@ public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator
return this.area; return this.area;
} }
@Override public boolean setBlock(int x, int y, int z, BlockState id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) {
if (area.contains(x, z)) { if (area.contains(x, z)) {
return super.setBlock(x, y, z, id); return super.setBlock(x, y, z, id);
} }
return false; return false;
} }
@Override public boolean setBlock(int x, int y, int z, BaseBlock id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) {
if (area.contains(x, z)) { if (area.contains(x, z)) {
return super.setBlock(x, y, z, id); return super.setBlock(x, y, z, id);
} }
return false; return false;
} }
@Override public boolean setBlock(int x, int y, int z, Pattern pattern) { @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) {
if (area.contains(x, z)) { if (area.contains(x, z)) {
return super.setBlock(x, y, z, pattern); return super.setBlock(x, y, z, pattern);
} }
return false; return false;
} }
@Override public boolean setBiome(int x, int z, BiomeType biome) { @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biome) {
if (area.contains(x, z)) { if (area.contains(x, z)) {
return super.setBiome(x, z, biome); return super.setBiome(x, z, biome);
} }
return false; return false;
} }
@Override public boolean setBiome(int x, int y, int z, BiomeType biome) { @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome) {
if (area.contains(x, z)) { if (area.contains(x, z)) {
return super.setBiome(x, y, z, biome); return super.setBiome(x, y, z, biome);
} }
return false; return false;
} }
@Override public boolean setTile(int x, int y, int z, CompoundTag tag) { @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) {
if (area.contains(x, z)) { if (area.contains(x, z)) {
return super.setTile(x, y, z, tag); return super.setTile(x, y, z, tag);
} }

View File

@ -48,8 +48,7 @@ import java.util.function.Consumer;
public abstract class BasicQueueCoordinator extends QueueCoordinator { public abstract class BasicQueueCoordinator extends QueueCoordinator {
private final World world; private final World world;
private final ConcurrentHashMap<BlockVector2, LocalChunk> blockChunks = private final ConcurrentHashMap<BlockVector2, LocalChunk> blockChunks = new ConcurrentHashMap<>();
new ConcurrentHashMap<>();
private final List<BlockVector2> readRegion = new ArrayList<>(); private final List<BlockVector2> readRegion = new ArrayList<>();
private long modified; private long modified;
private LocalChunk lastWrappedChunk; private LocalChunk lastWrappedChunk;
@ -63,16 +62,15 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator {
private CuboidRegion regenRegion = null; private CuboidRegion regenRegion = null;
private Consumer<BlockVector2> consumer = null; private Consumer<BlockVector2> consumer = null;
private boolean unloadAfter = true; private boolean unloadAfter = true;
private GlobalBlockQueue globalBlockQueue;
public BasicQueueCoordinator(World world) { public BasicQueueCoordinator(@Nonnull World world) {
this.world = world; this.world = world;
this.modified = System.currentTimeMillis(); this.modified = System.currentTimeMillis();
} }
@Override public abstract BlockState getBlock(int x, int y, int z); @Override public abstract BlockState getBlock(int x, int y, int z);
@Override public final World getWorld() { @Override public final @Nonnull World getWorld() {
return world; return world;
} }
@ -88,7 +86,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator {
return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z)); return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z));
} }
@Override public boolean setBlock(int x, int y, int z, BaseBlock id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) {
if ((y > 255) || (y < 0)) { if ((y > 255) || (y < 0)) {
return false; return false;
} }
@ -97,14 +95,14 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator {
return true; return true;
} }
@Override public boolean setBlock(int x, int y, int z, BlockState id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) {
// Trying to mix BlockState and BaseBlock leads to all kinds of issues. // Trying to mix BlockState and BaseBlock leads to all kinds of issues.
// Since BaseBlock has more features than BlockState, simply convert // Since BaseBlock has more features than BlockState, simply convert
// all BlockStates to BaseBlocks // all BlockStates to BaseBlocks
return setBlock(x, y, z, id.toBaseBlock()); return setBlock(x, y, z, id.toBaseBlock());
} }
@Override public boolean setBiome(int x, int z, BiomeType biomeType) { @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biomeType) {
LocalChunk chunk = getChunk(x >> 4, z >> 4); LocalChunk chunk = getChunk(x >> 4, z >> 4);
for (int y = 0; y < 256; y++) { for (int y = 0; y < 256; y++) {
chunk.setBiome(x & 15, y, z & 15, biomeType); chunk.setBiome(x & 15, y, z & 15, biomeType);
@ -113,7 +111,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator {
return true; return true;
} }
@Override public final boolean setBiome(int x, int y, int z, BiomeType biomeType) { @Override public final boolean setBiome(int x, int y, int z, @Nonnull BiomeType biomeType) {
LocalChunk chunk = getChunk(x >> 4, z >> 4); LocalChunk chunk = getChunk(x >> 4, z >> 4);
chunk.setBiome(x & 15, y, z & 15, biomeType); chunk.setBiome(x & 15, y, z & 15, biomeType);
settingBiomes = true; settingBiomes = true;
@ -124,7 +122,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator {
return this.settingBiomes; return this.settingBiomes;
} }
@Override public boolean setTile(int x, int y, int z, CompoundTag tag) { @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) {
LocalChunk chunk = getChunk(x >> 4, z >> 4); LocalChunk chunk = getChunk(x >> 4, z >> 4);
chunk.setTile(x, y, z, tag); chunk.setTile(x, y, z, tag);
settingTiles = true; settingTiles = true;
@ -135,7 +133,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator {
return this.settingTiles; return this.settingTiles;
} }
@Override public boolean setEntity(Entity entity) { @Override public boolean setEntity(@Nonnull Entity entity) {
if (entity.getState() == null || entity.getState().getType() == EntityTypes.PLAYER) { if (entity.getState() == null || entity.getState().getType() == EntityTypes.PLAYER) {
return false; return false;
} }
@ -145,15 +143,15 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator {
return true; return true;
} }
@Override public List<BlockVector2> getReadChunks() { @Override public @Nonnull List<BlockVector2> getReadChunks() {
return this.readRegion; return this.readRegion;
} }
@Override public void addReadChunk(BlockVector2 chunk) { @Override public void addReadChunk(@Nonnull BlockVector2 chunk) {
this.readRegion.add(chunk); this.readRegion.add(chunk);
} }
@Override public void addReadChunks(Set<BlockVector2> readRegion) { @Override public void addReadChunks(@Nonnull Set<BlockVector2> readRegion) {
this.readRegion.addAll(readRegion); this.readRegion.addAll(readRegion);
} }
@ -161,7 +159,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator {
return this.regenRegion != null ? this.regenRegion.clone() : null; return this.regenRegion != null ? this.regenRegion.clone() : null;
} }
@Override public void setRegenRegion(CuboidRegion regenRegion) { @Override public void setRegenRegion(@Nonnull CuboidRegion regenRegion) {
this.regenRegion = regenRegion; this.regenRegion = regenRegion;
} }
@ -219,7 +217,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator {
return this.consumer; return this.consumer;
} }
public final void setChunkConsumer(Consumer<BlockVector2> consumer) { public final void setChunkConsumer(@Nonnull Consumer<BlockVector2> consumer) {
this.consumer = consumer; this.consumer = consumer;
} }

View File

@ -53,8 +53,7 @@ public class ChunkCoordinatorBuilder {
private int initialBatchSize = 4; private int initialBatchSize = 4;
private boolean unloadAfter = true; private boolean unloadAfter = true;
@Inject @Inject public ChunkCoordinatorBuilder(@Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory) {
public ChunkCoordinatorBuilder(@Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory) {
this.chunkCoordinatorFactory = chunkCoordinatorFactory; this.chunkCoordinatorFactory = chunkCoordinatorFactory;
} }
@ -64,18 +63,16 @@ public class ChunkCoordinatorBuilder {
} }
@Nonnull public ChunkCoordinatorBuilder withChunk(@Nonnull final BlockVector2 chunkLocation) { @Nonnull public ChunkCoordinatorBuilder withChunk(@Nonnull final BlockVector2 chunkLocation) {
this.requestedChunks this.requestedChunks.add(Preconditions.checkNotNull(chunkLocation, "Chunk location may not be null"));
.add(Preconditions.checkNotNull(chunkLocation, "Chunk location may not be null"));
return this; return this;
} }
@Nonnull public ChunkCoordinatorBuilder withChunks( @Nonnull public ChunkCoordinatorBuilder withChunks(@Nonnull final Collection<BlockVector2> chunkLocations) {
@Nonnull final Collection<BlockVector2> chunkLocations) {
chunkLocations.forEach(this::withChunk); chunkLocations.forEach(this::withChunk);
return this; return this;
} }
@Nonnull public ChunkCoordinatorBuilder withRegion(Location pos1, Location pos2) { @Nonnull public ChunkCoordinatorBuilder withRegion(@Nonnull Location pos1, @Nonnull Location pos2) {
final int p1x = pos1.getX(); final int p1x = pos1.getX();
final int p1z = pos1.getZ(); final int p1z = pos1.getZ();
final int p2x = pos2.getX(); final int p2x = pos2.getX();
@ -96,10 +93,8 @@ public class ChunkCoordinatorBuilder {
return this; return this;
} }
@Nonnull public ChunkCoordinatorBuilder withConsumer( @Nonnull public ChunkCoordinatorBuilder withConsumer(@Nonnull final Consumer<BlockVector2> chunkConsumer) {
@Nonnull final Consumer<BlockVector2> chunkConsumer) { this.chunkConsumer = Preconditions.checkNotNull(chunkConsumer, "Chunk consumer may not be null");
this.chunkConsumer =
Preconditions.checkNotNull(chunkConsumer, "Chunk consumer may not be null");
return this; return this;
} }
@ -123,10 +118,8 @@ public class ChunkCoordinatorBuilder {
return this; return this;
} }
@Nonnull public ChunkCoordinatorBuilder withThrowableConsumer( @Nonnull public ChunkCoordinatorBuilder withThrowableConsumer(@Nonnull final Consumer<Throwable> throwableConsumer) {
@Nonnull final Consumer<Throwable> throwableConsumer) { this.throwableConsumer = Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null");
this.throwableConsumer =
Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null");
return this; return this;
} }
@ -141,8 +134,8 @@ public class ChunkCoordinatorBuilder {
Preconditions.checkNotNull(this.whenDone, "No final action was supplied"); Preconditions.checkNotNull(this.whenDone, "No final action was supplied");
Preconditions.checkNotNull(this.throwableConsumer, "No throwable consumer was supplied"); Preconditions.checkNotNull(this.throwableConsumer, "No throwable consumer was supplied");
return chunkCoordinatorFactory return chunkCoordinatorFactory
.create(this.maxIterationTime, this.initialBatchSize, this.chunkConsumer, this.world, .create(this.maxIterationTime, this.initialBatchSize, this.chunkConsumer, this.world, this.requestedChunks, this.whenDone,
this.requestedChunks, this.whenDone, this.throwableConsumer, this.unloadAfter); this.throwableConsumer, this.unloadAfter);
} }
} }

View File

@ -45,7 +45,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator {
private final BlockVector3 bot; private final BlockVector3 bot;
private final BlockVector3 top; private final BlockVector3 top;
public ChunkQueueCoordinator(BlockVector3 bot, BlockVector3 top, boolean biomes) { public ChunkQueueCoordinator(@Nonnull BlockVector3 bot, @Nonnull BlockVector3 top, boolean biomes) {
super(null, Location.at("", 0, 0, 0), Location.at("", 15, 255, 15)); super(null, Location.at("", 0, 0, 0), Location.at("", 15, 255, 15));
this.width = top.getX() - bot.getX() + 1; this.width = top.getX() - bot.getX() + 1;
this.length = top.getZ() - bot.getZ() + 1; this.length = top.getZ() - bot.getZ() + 1;
@ -55,11 +55,11 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator {
this.top = top; this.top = top;
} }
public BlockState[][][] getBlocks() { @Nonnull public BlockState[][][] getBlocks() {
return result; return result;
} }
@Override public boolean setBiome(int x, int z, BiomeType biomeType) { @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biomeType) {
if (this.biomeResult != null) { if (this.biomeResult != null) {
for (int y = 0; y < 256; y++) { for (int y = 0; y < 256; y++) {
this.storeCacheBiome(x, y, z, biomeType); this.storeCacheBiome(x, y, z, biomeType);
@ -69,7 +69,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator {
return false; return false;
} }
@Override public boolean setBiome(int x, int y, int z, BiomeType biomeType) { @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biomeType) {
if (this.biomeResult != null) { if (this.biomeResult != null) {
this.storeCacheBiome(x, y, z, biomeType); this.storeCacheBiome(x, y, z, biomeType);
return true; return true;
@ -77,17 +77,17 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator {
return false; return false;
} }
@Override public boolean setBlock(int x, int y, int z, BlockState id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) {
this.storeCache(x, y, z, id); this.storeCache(x, y, z, id);
return true; return true;
} }
@Override public boolean setBlock(int x, int y, int z, Pattern pattern) { @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) {
this.storeCache(x, y, z, pattern.apply(BlockVector3.at(x, y, z)).toImmutableState()); this.storeCache(x, y, z, pattern.apply(BlockVector3.at(x, y, z)).toImmutableState());
return true; return true;
} }
private void storeCache(final int x, final int y, final int z, final BlockState id) { private void storeCache(final int x, final int y, final int z, @Nonnull final BlockState id) {
BlockState[][] resultY = result[y]; BlockState[][] resultY = result[y];
if (resultY == null) { if (resultY == null) {
result[y] = resultY = new BlockState[length][]; result[y] = resultY = new BlockState[length][];
@ -99,7 +99,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator {
resultYZ[x] = id; resultYZ[x] = id;
} }
private void storeCacheBiome(final int x, final int y, final int z, final BiomeType id) { private void storeCacheBiome(final int x, final int y, final int z, @Nonnull final BiomeType id) {
BiomeType[][] resultY = biomeResult[y]; BiomeType[][] resultY = biomeResult[y];
if (resultY == null) { if (resultY == null) {
biomeResult[y] = resultY = new BiomeType[length][]; biomeResult[y] = resultY = new BiomeType[length][];
@ -111,7 +111,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator {
resultYZ[x] = id; resultYZ[x] = id;
} }
@Override public boolean setBlock(int x, int y, int z, BaseBlock id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull final BaseBlock id) {
this.storeCache(x, y, z, id.toImmutableState()); this.storeCache(x, y, z, id.toImmutableState());
return true; return true;
} }
@ -131,11 +131,11 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator {
return super.getWorld(); return super.getWorld();
} }
@Override public Location getMax() { @Override @Nonnull public Location getMax() {
return Location.at(getWorld().getName(), top.getX(), top.getY(), top.getZ()); return Location.at(getWorld().getName(), top.getX(), top.getY(), top.getZ());
} }
@Override public Location getMin() { @Override @Nonnull public Location getMin() {
return Location.at(getWorld().getName(), bot.getX(), bot.getY(), bot.getZ()); return Location.at(getWorld().getName(), bot.getX(), bot.getY(), bot.getZ());
} }
} }

View File

@ -34,7 +34,11 @@ import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -68,42 +72,42 @@ public class DelegateQueueCoordinator extends QueueCoordinator {
} }
} }
@Override public boolean setBlock(int x, int y, int z, Pattern pattern) { @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) {
if (parent != null) { if (parent != null) {
return parent.setBlock(x, y, z, pattern); return parent.setBlock(x, y, z, pattern);
} }
return false; return false;
} }
@Override public boolean setBlock(int x, int y, int z, BaseBlock id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) {
if (parent != null) { if (parent != null) {
return parent.setBlock(x, y, z, id); return parent.setBlock(x, y, z, id);
} }
return false; return false;
} }
@Override public boolean setBlock(int x, int y, int z, BlockState id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) {
if (parent != null) { if (parent != null) {
return parent.setBlock(x, y, z, id); return parent.setBlock(x, y, z, id);
} }
return false; return false;
} }
@Override public BlockState getBlock(int x, int y, int z) { @Override @Nullable public BlockState getBlock(int x, int y, int z) {
if (parent != null) { if (parent != null) {
return parent.getBlock(x, y, z); return parent.getBlock(x, y, z);
} }
return null; return null;
} }
@Override public boolean setBiome(int x, int z, BiomeType biome) { @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biome) {
if (parent != null) { if (parent != null) {
return parent.setBiome(x, z, biome); return parent.setBiome(x, z, biome);
} }
return false; return false;
} }
@Override public boolean setBiome(int x, int y, int z, BiomeType biome) { @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome) {
if (parent != null) { if (parent != null) {
return parent.setBiome(x, y, z, biome); return parent.setBiome(x, y, z, biome);
} }
@ -117,7 +121,7 @@ public class DelegateQueueCoordinator extends QueueCoordinator {
return false; return false;
} }
@Override public boolean setEntity(Entity entity) { @Override public boolean setEntity(@Nonnull Entity entity) {
if (parent != null) { if (parent != null) {
return parent.setEntity(entity); return parent.setEntity(entity);
} }
@ -130,14 +134,14 @@ public class DelegateQueueCoordinator extends QueueCoordinator {
} }
} }
@Override public World getWorld() { @Override @Nullable public World getWorld() {
if (parent != null) { if (parent != null) {
return parent.getWorld(); return parent.getWorld();
} }
return null; return null;
} }
@Override public boolean setTile(int x, int y, int z, CompoundTag tag) { @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) {
if (parent != null) { if (parent != null) {
return parent.setTile(x, y, z, tag); return parent.setTile(x, y, z, tag);
} }
@ -176,26 +180,26 @@ public class DelegateQueueCoordinator extends QueueCoordinator {
} }
} }
@Override public void setChunkConsumer(Consumer<BlockVector2> consumer) { @Override public void setChunkConsumer(@Nonnull Consumer<BlockVector2> consumer) {
if (parent != null) { if (parent != null) {
parent.setChunkConsumer(consumer); parent.setChunkConsumer(consumer);
} }
} }
@Override public List<BlockVector2> getReadChunks() { @Override @Nonnull public List<BlockVector2> getReadChunks() {
if (parent != null) { if (parent != null) {
return parent.getReadChunks(); return parent.getReadChunks();
} }
return null; return new ArrayList<>();
} }
@Override public void addReadChunks(Set<BlockVector2> readChunks) { @Override public void addReadChunks(@Nonnull Set<BlockVector2> readChunks) {
if (parent != null) { if (parent != null) {
parent.addReadChunks(readChunks); parent.addReadChunks(readChunks);
} }
} }
@Override public void addReadChunk(BlockVector2 chunk) { @Override public void addReadChunk(@Nonnull BlockVector2 chunk) {
if (parent != null) { if (parent != null) {
parent.addReadChunk(chunk); parent.addReadChunk(chunk);
} }
@ -214,14 +218,14 @@ public class DelegateQueueCoordinator extends QueueCoordinator {
} }
} }
@Override public CuboidRegion getRegenRegion() { @Override @Nullable public CuboidRegion getRegenRegion() {
if (parent != null) { if (parent != null) {
return parent.getRegenRegion(); return parent.getRegenRegion();
} }
return null; return null;
} }
@Override public void setRegenRegion(CuboidRegion regenRegion) { @Override public void setRegenRegion(@Nonnull CuboidRegion regenRegion) {
if (parent != null) { if (parent != null) {
parent.setRegenRegion(regenRegion); parent.setRegenRegion(regenRegion);
} }

View File

@ -28,6 +28,7 @@ package com.plotsquared.core.queue;
import com.plotsquared.core.PlotSquared; import com.plotsquared.core.PlotSquared;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import javax.annotation.Nonnull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentLinkedDeque;
@ -37,12 +38,12 @@ public class GlobalBlockQueue {
private final ConcurrentLinkedDeque<QueueCoordinator> activeQueues; private final ConcurrentLinkedDeque<QueueCoordinator> activeQueues;
private QueueProvider provider; private QueueProvider provider;
public GlobalBlockQueue(QueueProvider provider) { public GlobalBlockQueue(@Nonnull QueueProvider provider) {
this.provider = provider; this.provider = provider;
this.activeQueues = new ConcurrentLinkedDeque<>(); this.activeQueues = new ConcurrentLinkedDeque<>();
} }
public QueueCoordinator getNewQueue(World world) { @Nonnull public QueueCoordinator getNewQueue(@Nonnull World world) {
QueueCoordinator queue = provider.getNewQueue(world); QueueCoordinator queue = provider.getNewQueue(world);
// Auto-inject into the queue // Auto-inject into the queue
PlotSquared.platform().getInjector().injectMembers(queue); PlotSquared.platform().getInjector().injectMembers(queue);
@ -53,7 +54,7 @@ public class GlobalBlockQueue {
return this.provider; return this.provider;
} }
public void setQueueProvider(QueueProvider provider) { public void setQueueProvider(@Nonnull QueueProvider provider) {
this.provider = provider; this.provider = provider;
} }
@ -64,7 +65,7 @@ public class GlobalBlockQueue {
* @param queue {@link QueueCoordinator} instance to start. * @param queue {@link QueueCoordinator} instance to start.
* @return true if added to queue, false otherwise * @return true if added to queue, false otherwise
*/ */
public boolean enqueue(QueueCoordinator queue) { public boolean enqueue(@Nonnull QueueCoordinator queue) {
boolean success = false; boolean success = false;
if (queue.size() > 0 && !activeQueues.contains(queue)) { if (queue.size() > 0 && !activeQueues.contains(queue)) {
success = activeQueues.add(queue); success = activeQueues.add(queue);
@ -73,12 +74,12 @@ public class GlobalBlockQueue {
return success; return success;
} }
public void dequeue(QueueCoordinator queue) { public void dequeue(@Nonnull QueueCoordinator queue) {
queue.cancel(); queue.cancel();
activeQueues.remove(queue); activeQueues.remove(queue);
} }
public List<QueueCoordinator> getActiveQueues() { @Nonnull public List<QueueCoordinator> getActiveQueues() {
return new ArrayList<>(activeQueues); return new ArrayList<>(activeQueues);
} }

View File

@ -34,6 +34,7 @@ import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import javax.annotation.Nonnull;
import java.util.HashMap; import java.util.HashMap;
public class LocalChunk { public class LocalChunk {
@ -46,7 +47,7 @@ public class LocalChunk {
private final HashMap<BlockVector3, CompoundTag> tiles = new HashMap<>(); private final HashMap<BlockVector3, CompoundTag> tiles = new HashMap<>();
private final HashMap<Location, BaseEntity> entities = new HashMap<>(); private final HashMap<Location, BaseEntity> entities = new HashMap<>();
public LocalChunk(QueueCoordinator parent, int x, int z) { public LocalChunk(@Nonnull QueueCoordinator parent, int x, int z) {
this.parent = parent; this.parent = parent;
this.x = x; this.x = x;
this.z = z; this.z = z;
@ -54,7 +55,7 @@ public class LocalChunk {
biomes = new BiomeType[16][]; biomes = new BiomeType[16][];
} }
public QueueCoordinator getParent() { @Nonnull public QueueCoordinator getParent() {
return this.parent; return this.parent;
} }
@ -66,19 +67,19 @@ public class LocalChunk {
return this.z; return this.z;
} }
public BaseBlock[][] getBaseblocks() { @Nonnull public BaseBlock[][] getBaseblocks() {
return this.baseblocks; return this.baseblocks;
} }
public BiomeType[][] getBiomes() { @Nonnull public BiomeType[][] getBiomes() {
return this.biomes; return this.biomes;
} }
public HashMap<BlockVector3, CompoundTag> getTiles() { @Nonnull public HashMap<BlockVector3, CompoundTag> getTiles() {
return this.tiles; return this.tiles;
} }
public void setBiome(final int x, final int y, final int z, final BiomeType biomeType) { public void setBiome(final int x, final int y, final int z, @Nonnull final BiomeType biomeType) {
final int i = y >> 4; final int i = y >> 4;
final int j = ChunkUtil.getJ(x, y, z); final int j = ChunkUtil.getJ(x, y, z);
BiomeType[] array = this.biomes[i]; BiomeType[] array = this.biomes[i];
@ -92,7 +93,7 @@ public class LocalChunk {
return MathMan.pair((short) x, (short) z); return MathMan.pair((short) x, (short) z);
} }
public void setBlock(final int x, final int y, final int z, final BaseBlock baseBlock) { public void setBlock(final int x, final int y, final int z, @Nonnull final BaseBlock baseBlock) {
final int i = y >> 4; final int i = y >> 4;
final int j = ChunkUtil.getJ(x, y, z); final int j = ChunkUtil.getJ(x, y, z);
BaseBlock[] array = baseblocks[i]; BaseBlock[] array = baseblocks[i];
@ -102,15 +103,15 @@ public class LocalChunk {
array[j] = baseBlock; array[j] = baseBlock;
} }
public void setTile(final int x, final int y, final int z, final CompoundTag tag) { public void setTile(final int x, final int y, final int z, @Nonnull final CompoundTag tag) {
tiles.put(BlockVector3.at(x, y, z), tag); tiles.put(BlockVector3.at(x, y, z), tag);
} }
public void setEntity(Location location, BaseEntity entity) { public void setEntity(@Nonnull Location location, @Nonnull BaseEntity entity) {
this.entities.put(location, entity); this.entities.put(location, entity);
} }
public HashMap<Location, BaseEntity> getEntities() { @Nonnull public HashMap<Location, BaseEntity> getEntities() {
return this.entities; return this.entities;
} }
} }

View File

@ -32,6 +32,7 @@ import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordinator { public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordinator {
@ -40,22 +41,14 @@ public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordin
private final int blockX; private final int blockX;
private final int blockZ; private final int blockZ;
public LocationOffsetDelegateQueueCoordinator(final boolean[][] canPlace, final int blockX, public LocationOffsetDelegateQueueCoordinator(final boolean[][] canPlace, final int blockX, final int blockZ, @Nullable QueueCoordinator parent) {
final int blockZ, @Nullable QueueCoordinator parent) {
super(parent); super(parent);
this.canPlace = canPlace; this.canPlace = canPlace;
this.blockX = blockX; this.blockX = blockX;
this.blockZ = blockZ; this.blockZ = blockZ;
} }
@Override public boolean setBlock(int x, int y, int z, BlockState id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) {
if (canPlace[x - blockX][z - blockZ]) {
return super.setBlock(x, y, z, id);
}
return false;
}
@Override public boolean setBlock(int x, int y, int z, BaseBlock id) {
try { try {
if (canPlace[x - blockX][z - blockZ]) { if (canPlace[x - blockX][z - blockZ]) {
return super.setBlock(x, y, z, id); return super.setBlock(x, y, z, id);
@ -66,20 +59,49 @@ public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordin
return false; return false;
} }
@Override public boolean setBlock(int x, int y, int z, Pattern pattern) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) {
try {
if (canPlace[x - blockX][z - blockZ]) {
return super.setBlock(x, y, z, id);
}
} catch (final Exception e) {
throw e;
}
return false;
}
@Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) {
final BlockVector3 blockVector3 = BlockVector3.at(x + blockX, y, z + blockZ); final BlockVector3 blockVector3 = BlockVector3.at(x + blockX, y, z + blockZ);
return this.setBlock(x, y, z, pattern.apply(blockVector3)); return this.setBlock(x, y, z, pattern.apply(blockVector3));
} }
@Override public boolean setBiome(int x, int z, BiomeType biome) { @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biome) {
return super.setBiome(x, z, biome); boolean result = true;
for (int y = 0; y < 256; y++) {
result &= this.setBiome(x, z, biome);
}
return result;
} }
@Override public boolean setBiome(int x, int y, int z, BiomeType biome) { @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome) {
try {
if (canPlace[x - blockX][z - blockZ]) {
return super.setBiome(x, y, z, biome); return super.setBiome(x, y, z, biome);
} }
} catch (final Exception e) {
throw e;
}
return false;
}
@Override public boolean setTile(int x, int y, int z, CompoundTag tag) { @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) {
try {
if (canPlace[x - blockX][z - blockZ]) {
return super.setTile(x, y, z, tag); return super.setTile(x, y, z, tag);
} }
} catch (final Exception e) {
throw e;
}
return false;
}
} }

View File

@ -30,35 +30,37 @@ import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import javax.annotation.Nonnull;
public class OffsetQueueCoordinator extends DelegateQueueCoordinator { public class OffsetQueueCoordinator extends DelegateQueueCoordinator {
private final int ox; private final int ox;
private final int oy; private final int oy;
private final int oz; private final int oz;
public OffsetQueueCoordinator(QueueCoordinator parent, int ox, int oy, int oz) { public OffsetQueueCoordinator(@Nonnull QueueCoordinator parent, int ox, int oy, int oz) {
super(parent); super(parent);
this.ox = ox; this.ox = ox;
this.oy = oy; this.oy = oy;
this.oz = oz; this.oz = oz;
} }
@Override public boolean setBiome(int x, int z, BiomeType biome) { @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biome) {
return super.setBiome(ox + x, oz + z, biome); return super.setBiome(ox + x, oz + z, biome);
} }
@Override public boolean setBiome(int x, int y, int z, BiomeType biome) { @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome) {
return super.setBiome(ox + x, oy + y, oz + z, biome); return super.setBiome(ox + x, oy + y, oz + z, biome);
} }
@Override public boolean setBlock(int x, int y, int z, BaseBlock id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) {
return super.setBlock(ox + x, oy + y, oz + z, id); return super.setBlock(ox + x, oy + y, oz + z, id);
} }
@Override public boolean setBlock(int x, int y, int z, Pattern pattern) { @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) {
return super.setBlock(ox + x, oy + y, oz + z, pattern); return super.setBlock(ox + x, oy + y, oz + z, pattern);
} }
@Override public boolean setTile(int x, int y, int z, CompoundTag tag) { @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) {
return super.setTile(ox + x, oy + y, oz + z, tag); return super.setTile(ox + x, oy + y, oz + z, tag);
} }
} }

View File

@ -38,7 +38,6 @@ import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -80,7 +79,7 @@ public abstract class QueueCoordinator {
return chunkObject; return chunkObject;
} }
public void setChunkObject(@NotNull Object chunkObject) { public void setChunkObject(@Nonnull Object chunkObject) {
this.chunkObject = chunkObject; this.chunkObject = chunkObject;
} }
@ -92,51 +91,51 @@ public abstract class QueueCoordinator {
* @param z the z coordinate from 0 to 15 inclusive * @param z the z coordinate from 0 to 15 inclusive
* @param id the id to set the block to * @param id the id to set the block to
*/ */
public abstract boolean setBlock(final int x, final int y, final int z, final BlockState id); public abstract boolean setBlock(final int x, final int y, final int z, @Nonnull final BlockState id);
public abstract boolean setBlock(final int x, final int y, final int z, final BaseBlock id); public abstract boolean setBlock(final int x, final int y, final int z, @Nonnull final BaseBlock id);
public boolean setBlock(final int x, final int y, final int z, @Nonnull final Pattern pattern) { public boolean setBlock(final int x, final int y, final int z, @Nonnull final Pattern pattern) {
return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z)); return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z));
} }
public abstract boolean setTile(int x, int y, int z, CompoundTag tag); public abstract boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag);
public abstract boolean isSettingTiles(); public abstract boolean isSettingTiles();
public abstract BlockState getBlock(int x, int y, int z); @Nullable public abstract BlockState getBlock(int x, int y, int z);
@Deprecated public abstract boolean setBiome(int x, int z, BiomeType biome); @Deprecated public abstract boolean setBiome(int x, int z, @Nonnull BiomeType biome);
public abstract boolean setBiome(int x, int y, int z, BiomeType biome); public abstract boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome);
public abstract boolean isSettingBiomes(); public abstract boolean isSettingBiomes();
public void addEntities(List<? extends Entity> entities) { public void addEntities(@Nonnull List<? extends Entity> entities) {
for (Entity e : entities) { for (Entity e : entities) {
this.setEntity(e); this.setEntity(e);
} }
} }
public abstract boolean setEntity(Entity entity); public abstract boolean setEntity(@Nonnull Entity entity);
public abstract List<BlockVector2> getReadChunks(); @Nonnull public abstract List<BlockVector2> getReadChunks();
public abstract void addReadChunks(Set<BlockVector2> readChunks); public abstract void addReadChunks(@Nonnull Set<BlockVector2> readChunks);
public abstract void addReadChunk(BlockVector2 chunk); public abstract void addReadChunk(@Nonnull BlockVector2 chunk);
public abstract boolean isUnloadAfter(); public abstract boolean isUnloadAfter();
public abstract void setUnloadAfter(boolean unloadAfter); public abstract void setUnloadAfter(boolean unloadAfter);
public abstract CuboidRegion getRegenRegion(); @Nullable public abstract CuboidRegion getRegenRegion();
public abstract void setRegenRegion(CuboidRegion regenRegion); public abstract void setRegenRegion(@Nonnull CuboidRegion regenRegion);
public abstract void regenChunk(int x, int z); public abstract void regenChunk(int x, int z);
public abstract World getWorld(); @Nullable public abstract World getWorld();
public final void setModified() { public final void setModified() {
setModified(System.currentTimeMillis()); setModified(System.currentTimeMillis());
@ -150,11 +149,11 @@ public abstract class QueueCoordinator {
public abstract void cancel(); public abstract void cancel();
public abstract void setCompleteTask(Runnable whenDone); public abstract void setCompleteTask(@Nullable Runnable whenDone);
public abstract void setChunkConsumer(Consumer<BlockVector2> consumer); public abstract void setChunkConsumer(@Nonnull Consumer<BlockVector2> consumer);
public void setCuboid(Location pos1, Location pos2, BlockState block) { public void setCuboid(@Nonnull Location pos1, @Nonnull Location pos2, @Nonnull BlockState block) {
int yMin = Math.min(pos1.getY(), pos2.getY()); int yMin = Math.min(pos1.getY(), pos2.getY());
int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY()));
int xMin = Math.min(pos1.getX(), pos2.getX()); int xMin = Math.min(pos1.getX(), pos2.getX());
@ -170,7 +169,7 @@ public abstract class QueueCoordinator {
} }
} }
public void setCuboid(Location pos1, Location pos2, Pattern blocks) { public void setCuboid(@Nonnull Location pos1, @Nonnull Location pos2, @Nonnull Pattern blocks) {
int yMin = Math.min(pos1.getY(), pos2.getY()); int yMin = Math.min(pos1.getY(), pos2.getY());
int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY()));
int xMin = Math.min(pos1.getX(), pos2.getX()); int xMin = Math.min(pos1.getX(), pos2.getX());
@ -186,7 +185,7 @@ public abstract class QueueCoordinator {
} }
} }
public void setBiomeCuboid(Location pos1, Location pos2, BiomeType biome) { public void setBiomeCuboid(@Nonnull Location pos1, @Nonnull Location pos2, @Nonnull BiomeType biome) {
int yMin = Math.min(pos1.getY(), pos2.getY()); int yMin = Math.min(pos1.getY(), pos2.getY());
int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY()));
int xMin = Math.min(pos1.getX(), pos2.getX()); int xMin = Math.min(pos1.getX(), pos2.getX());

View File

@ -27,11 +27,13 @@ package com.plotsquared.core.queue;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import javax.annotation.Nonnull;
public abstract class QueueProvider { public abstract class QueueProvider {
public static QueueProvider of(final Class<? extends QueueCoordinator> primary) { public static QueueProvider of(@Nonnull final Class<? extends QueueCoordinator> primary) {
return new QueueProvider() { return new QueueProvider() {
@Override public QueueCoordinator getNewQueue(World world) { @Override public QueueCoordinator getNewQueue(@Nonnull World world) {
try { try {
return (QueueCoordinator) primary.getConstructors()[0].newInstance(world); return (QueueCoordinator) primary.getConstructors()[0].newInstance(world);
} catch (Throwable e) { } catch (Throwable e) {
@ -42,5 +44,5 @@ public abstract class QueueProvider {
}; };
} }
public abstract QueueCoordinator getNewQueue(World world); public abstract QueueCoordinator getNewQueue(@Nonnull World world);
} }

View File

@ -32,6 +32,9 @@ import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class ScopedQueueCoordinator extends DelegateQueueCoordinator { public class ScopedQueueCoordinator extends DelegateQueueCoordinator {
private final int minX; private final int minX;
private final int minY; private final int minY;
@ -45,7 +48,7 @@ public class ScopedQueueCoordinator extends DelegateQueueCoordinator {
private final int dy; private final int dy;
private final int dz; private final int dz;
public ScopedQueueCoordinator(QueueCoordinator parent, Location min, Location max) { public ScopedQueueCoordinator(@Nullable QueueCoordinator parent, @Nonnull Location min, @Nonnull Location max) {
super(parent); super(parent);
this.minX = min.getX(); this.minX = min.getX();
this.minY = min.getY(); this.minY = min.getY();
@ -60,13 +63,12 @@ public class ScopedQueueCoordinator extends DelegateQueueCoordinator {
this.dz = maxZ - minZ; this.dz = maxZ - minZ;
} }
@Override public boolean setBiome(int x, int z, BiomeType biome) { @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biome) {
return x >= 0 && x <= dx && z >= 0 && z <= dz && super.setBiome(x + minX, z + minZ, biome); return x >= 0 && x <= dx && z >= 0 && z <= dz && super.setBiome(x + minX, z + minZ, biome);
} }
@Override public boolean setBiome(int x, int y, int z, BiomeType biome) { @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome) {
return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super.setBiome(x + minX, y + minY, z + minZ, biome);
.setBiome(x + minX, y + minY, z + minZ, biome);
} }
public void fillBiome(BiomeType biome) { public void fillBiome(BiomeType biome) {
@ -79,31 +81,27 @@ public class ScopedQueueCoordinator extends DelegateQueueCoordinator {
} }
} }
@Override public boolean setBlock(int x, int y, int z, BaseBlock id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) {
return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super.setBlock(x + minX, y + minY, z + minZ, id);
.setBlock(x + minX, y + minY, z + minZ, id);
} }
@Override public boolean setBlock(int x, int y, int z, BlockState id) { @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) {
return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super.setBlock(x + minX, y + minY, z + minZ, id);
.setBlock(x + minX, y + minY, z + minZ, id);
} }
@Override public boolean setBlock(int x, int y, int z, Pattern pattern) { @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) {
return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super.setBlock(x + minX, y + minY, z + minZ, pattern);
.setBlock(x + minX, y + minY, z + minZ, pattern);
} }
@Override public boolean setTile(int x, int y, int z, CompoundTag tag) { @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) {
return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super.setTile(x + minX, y + minY, z + minZ, tag);
.setTile(x + minX, y + minY, z + minZ, tag);
} }
public Location getMin() { @Nonnull public Location getMin() {
return Location.at(this.getWorld().getName(), this.minX, this.minY, this.minZ); return Location.at(this.getWorld().getName(), this.minX, this.minY, this.minZ);
} }
public Location getMax() { @Nonnull public Location getMax() {
return Location.at(this.getWorld().getName(), this.maxX, this.maxY, this.maxZ); return Location.at(this.getWorld().getName(), this.maxX, this.maxY, this.maxZ);
} }

View File

@ -38,22 +38,19 @@ import java.util.concurrent.ConcurrentHashMap;
public abstract class ChunkManager { public abstract class ChunkManager {
private static final Map<BlockVector2, RunnableVal<ScopedQueueCoordinator>> forceChunks = private static final Map<BlockVector2, RunnableVal<ScopedQueueCoordinator>> forceChunks = new ConcurrentHashMap<>();
new ConcurrentHashMap<>(); private static final Map<BlockVector2, RunnableVal<ScopedQueueCoordinator>> addChunks = new ConcurrentHashMap<>();
private static final Map<BlockVector2, RunnableVal<ScopedQueueCoordinator>> addChunks =
new ConcurrentHashMap<>();
public static void setChunkInPlotArea(RunnableVal<ScopedQueueCoordinator> force, public static void setChunkInPlotArea(RunnableVal<ScopedQueueCoordinator> force,
RunnableVal<ScopedQueueCoordinator> add, String world, BlockVector2 loc) { RunnableVal<ScopedQueueCoordinator> add,
QueueCoordinator queue = PlotSquared.platform().getGlobalBlockQueue() String world,
.getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); BlockVector2 loc) {
if (PlotSquared.get().getPlotAreaManager().isAugmented(world) && PlotSquared.get() QueueCoordinator queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world));
.isNonStandardGeneration(world, loc)) { if (PlotSquared.get().getPlotAreaManager().isAugmented(world) && PlotSquared.get().isNonStandardGeneration(world, loc)) {
int blockX = loc.getX() << 4; int blockX = loc.getX() << 4;
int blockZ = loc.getZ() << 4; int blockZ = loc.getZ() << 4;
ScopedQueueCoordinator scoped = ScopedQueueCoordinator scoped =
new ScopedQueueCoordinator(queue, Location.at(world, blockX, 0, blockZ), new ScopedQueueCoordinator(queue, Location.at(world, blockX, 0, blockZ), Location.at(world, blockX + 15, 255, blockZ + 15));
Location.at(world, blockX + 15, 255, blockZ + 15));
if (force != null) { if (force != null) {
force.run(scoped); force.run(scoped);
} else { } else {
@ -94,7 +91,6 @@ public abstract class ChunkManager {
return false; return false;
} }
@Deprecated @Deprecated public abstract CompletableFuture loadChunk(String world, BlockVector2 loc, boolean force);
public abstract CompletableFuture loadChunk(String world, BlockVector2 loc, boolean force);
} }

View File

@ -30,6 +30,8 @@ import com.sk89q.worldedit.math.BlockVector2;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
import org.jetbrains.annotations.Range; import org.jetbrains.annotations.Range;
import javax.annotation.Nonnull;
/** /**
* This cache is used for world generation and just saves a bit of calculation time when checking if something is in the plot area. * This cache is used for world generation and just saves a bit of calculation time when checking if something is in the plot area.
*/ */
@ -41,10 +43,10 @@ public class ChunkUtil {
* Cache of mapping x,y,z coordinates to the chunk array<br> * Cache of mapping x,y,z coordinates to the chunk array<br>
* - Used for efficient world generation<br> * - Used for efficient world generation<br>
*/ */
private static short[] x_loc; private static final short[] x_loc;
private static short[][] y_loc; private static final short[][] y_loc;
private static short[] z_loc; private static final short[] z_loc;
private static short[][][] CACHE_J = null; private static final short[][][] CACHE_J;
static { static {
x_loc = new short[4096]; x_loc = new short[4096];
@ -126,7 +128,7 @@ public class ChunkUtil {
* @param chunk BlockVector2 of chunk coordinates * @param chunk BlockVector2 of chunk coordinates
* @return true if the region pos1-pos2 contains the chunk * @return true if the region pos1-pos2 contains the chunk
*/ */
public static boolean isWholeChunk(Location pos1, Location pos2, BlockVector2 chunk) { public static boolean isWholeChunk(@Nonnull Location pos1, @Nonnull Location pos2, @Nonnull BlockVector2 chunk) {
int x1 = pos1.getX(); int x1 = pos1.getX();
int z1 = pos1.getZ(); int z1 = pos1.getZ();
int x2 = pos2.getX(); int x2 = pos2.getX();

View File

@ -54,15 +54,13 @@ import java.util.Set;
public abstract class RegionManager { public abstract class RegionManager {
private static final Logger logger = private static final Logger logger = LoggerFactory.getLogger("P2/" + RegionManager.class.getSimpleName());
LoggerFactory.getLogger("P2/" + RegionManager.class.getSimpleName());
public static RegionManager manager = null; public static RegionManager manager = null;
private final WorldUtil worldUtil; private final WorldUtil worldUtil;
private final GlobalBlockQueue blockQueue; private final GlobalBlockQueue blockQueue;
@Inject @Inject public RegionManager(@Nonnull WorldUtil worldUtil, @Nonnull GlobalBlockQueue blockQueue) {
public RegionManager(@Nonnull WorldUtil worldUtil, @Nonnull GlobalBlockQueue blockQueue) {
this.worldUtil = worldUtil; this.worldUtil = worldUtil;
this.blockQueue = blockQueue; this.blockQueue = blockQueue;
} }
@ -83,13 +81,10 @@ public abstract class RegionManager {
*/ */
public abstract int[] countEntities(Plot plot); public abstract int[] countEntities(Plot plot);
public void deleteRegionFiles(final String world, final Collection<BlockVector2> chunks, public void deleteRegionFiles(final String world, final Collection<BlockVector2> chunks, final Runnable whenDone) {
final Runnable whenDone) {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(() -> {
for (BlockVector2 loc : chunks) { for (BlockVector2 loc : chunks) {
String directory = String directory = world + File.separator + "region" + File.separator + "r." + loc.getX() + "." + loc.getZ() + ".mca";
world + File.separator + "region" + File.separator + "r." + loc.getX() + "."
+ loc.getZ() + ".mca";
File file = new File(PlotSquared.platform().getWorldContainer(), directory); File file = new File(PlotSquared.platform().getWorldContainer(), directory);
logger.info("[P2] - Deleting file: {} (max 1024 chunks)", file.getName()); logger.info("[P2] - Deleting file: {} (max 1024 chunks)", file.getName());
if (file.exists()) { if (file.exists()) {
@ -100,18 +95,20 @@ public abstract class RegionManager {
}); });
} }
public boolean setCuboids(final PlotArea area, final Set<CuboidRegion> regions, public boolean setCuboids(final PlotArea area,
final Pattern blocks, int minY, int maxY, @Nullable QueueCoordinator queue) { final Set<CuboidRegion> regions,
final Pattern blocks,
int minY,
int maxY,
@Nullable QueueCoordinator queue) {
boolean enqueue = false; boolean enqueue = false;
if (queue == null) { if (queue == null) {
queue = area.getQueue(); queue = area.getQueue();
enqueue = true; enqueue = true;
} }
for (CuboidRegion region : regions) { for (CuboidRegion region : regions) {
Location pos1 = Location.at(area.getWorldName(), region.getMinimumPoint().getX(), minY, Location pos1 = Location.at(area.getWorldName(), region.getMinimumPoint().getX(), minY, region.getMinimumPoint().getZ());
region.getMinimumPoint().getZ()); Location pos2 = Location.at(area.getWorldName(), region.getMaximumPoint().getX(), maxY, region.getMaximumPoint().getZ());
Location pos2 = Location.at(area.getWorldName(), region.getMaximumPoint().getX(), maxY,
region.getMaximumPoint().getZ());
queue.setCuboid(pos1, pos2, blocks); queue.setCuboid(pos1, pos2, blocks);
} }
return !enqueue || queue.enqueue(); return !enqueue || queue.enqueue();
@ -136,20 +133,17 @@ public abstract class RegionManager {
/** /**
* Copy a region to a new location (in the same world) * Copy a region to a new location (in the same world)
*/ */
public boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, public boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, final Runnable whenDone) {
final Runnable whenDone) {
final int relX = newPos.getX() - pos1.getX(); final int relX = newPos.getX() - pos1.getX();
final int relZ = newPos.getZ() - pos1.getZ(); final int relZ = newPos.getZ() - pos1.getZ();
final com.sk89q.worldedit.world.World oldWorld = worldUtil.getWeWorld(pos1.getWorldName()); final com.sk89q.worldedit.world.World oldWorld = worldUtil.getWeWorld(pos1.getWorldName());
final com.sk89q.worldedit.world.World newWorld = final com.sk89q.worldedit.world.World newWorld = worldUtil.getWeWorld(newPos.getWorldName());
worldUtil.getWeWorld(newPos.getWorldName());
final QueueCoordinator copyFrom = blockQueue.getNewQueue(oldWorld); final QueueCoordinator copyFrom = blockQueue.getNewQueue(oldWorld);
final BasicQueueCoordinator copyTo = final BasicQueueCoordinator copyTo = (BasicQueueCoordinator) blockQueue.getNewQueue(newWorld);
(BasicQueueCoordinator) blockQueue.getNewQueue(newWorld);
copyFromTo(pos1, pos2, relX, relZ, oldWorld, copyFrom, copyTo, false); copyFromTo(pos1, pos2, relX, relZ, oldWorld, copyFrom, copyTo, false);
copyFrom.setCompleteTask(copyTo::enqueue); copyFrom.setCompleteTask(copyTo::enqueue);
copyFrom.addReadChunks(new CuboidRegion(BlockVector3.at(pos1.getX(), 0, pos1.getZ()), copyFrom
BlockVector3.at(pos2.getX(), 0, pos2.getZ())).getChunks()); .addReadChunks(new CuboidRegion(BlockVector3.at(pos1.getX(), 0, pos1.getZ()), BlockVector3.at(pos2.getX(), 0, pos2.getZ())).getChunks());
copyTo.setCompleteTask(whenDone); copyTo.setCompleteTask(whenDone);
copyFrom.enqueue(); copyFrom.enqueue();
return true; return true;
@ -160,8 +154,7 @@ public abstract class RegionManager {
* - pos1 and pos2 are in the same plot<br> * - pos1 and pos2 are in the same plot<br>
* It can be harmful to the world if parameters outside this scope are provided * It can be harmful to the world if parameters outside this scope are provided
*/ */
public abstract boolean regenerateRegion(Location pos1, Location pos2, boolean ignoreAugment, public abstract boolean regenerateRegion(Location pos1, Location pos2, boolean ignoreAugment, Runnable whenDone);
Runnable whenDone);
public abstract void clearAllEntities(Location pos1, Location pos2); public abstract void clearAllEntities(Location pos1, Location pos2);
@ -176,11 +169,9 @@ public abstract class RegionManager {
QueueCoordinator fromQueue2 = blockQueue.getNewQueue(world2); QueueCoordinator fromQueue2 = blockQueue.getNewQueue(world2);
fromQueue1.setUnloadAfter(false); fromQueue1.setUnloadAfter(false);
fromQueue2.setUnloadAfter(false); fromQueue2.setUnloadAfter(false);
fromQueue1.addReadChunks( fromQueue1.addReadChunks(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks());
new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks()); fromQueue2.addReadChunks(new CuboidRegion(swapPos.getBlockVector3(),
fromQueue2.addReadChunks(new CuboidRegion(swapPos.getBlockVector3(), BlockVector3 BlockVector3.at(swapPos.getX() + pos2.getX() - pos1.getX(), 0, swapPos.getZ() + pos2.getZ() - pos1.getZ())).getChunks());
.at(swapPos.getX() + pos2.getX() - pos1.getX(), 0,
swapPos.getZ() + pos2.getZ() - pos1.getZ())).getChunks());
QueueCoordinator toQueue1 = blockQueue.getNewQueue(world1); QueueCoordinator toQueue1 = blockQueue.getNewQueue(world1);
QueueCoordinator toQueue2 = blockQueue.getNewQueue(world2); QueueCoordinator toQueue2 = blockQueue.getNewQueue(world2);
@ -192,8 +183,14 @@ public abstract class RegionManager {
toQueue2.setCompleteTask(whenDone); toQueue2.setCompleteTask(whenDone);
} }
private void copyFromTo(Location pos1, Location pos2, int relX, int relZ, World world1, private void copyFromTo(Location pos1,
QueueCoordinator fromQueue, QueueCoordinator toQueue, boolean removeEntities) { Location pos2,
int relX,
int relZ,
World world1,
QueueCoordinator fromQueue,
QueueCoordinator toQueue,
boolean removeEntities) {
fromQueue.setChunkConsumer(chunk -> { fromQueue.setChunkConsumer(chunk -> {
int cx = chunk.getX(); int cx = chunk.getX();
int cz = chunk.getZ(); int cz = chunk.getZ();
@ -214,8 +211,7 @@ public abstract class RegionManager {
} }
} }
} }
Region region = new CuboidRegion(BlockVector3.at(cbx + bx, 0, cbz + bz), Region region = new CuboidRegion(BlockVector3.at(cbx + bx, 0, cbz + bz), BlockVector3.at(cbx + tx, 255, cbz + tz));
BlockVector3.at(cbx + tx, 255, cbz + tz));
toQueue.addEntities(world1.getEntities(region)); toQueue.addEntities(world1.getEntities(region));
if (removeEntities) { if (removeEntities) {
for (Entity entity : world1.getEntities(region)) { for (Entity entity : world1.getEntities(region)) {
@ -225,12 +221,11 @@ public abstract class RegionManager {
}); });
} }
public void setBiome(final CuboidRegion region, final int extendBiome, final BiomeType biome, public void setBiome(final CuboidRegion region, final int extendBiome, final BiomeType biome, final String world, final Runnable whenDone) {
final String world, final Runnable whenDone) { Location pos1 = Location
Location pos1 = Location.at(world, region.getMinimumPoint().getX() - extendBiome, .at(world, region.getMinimumPoint().getX() - extendBiome, region.getMinimumPoint().getY(), region.getMinimumPoint().getZ() - extendBiome);
region.getMinimumPoint().getY(), region.getMinimumPoint().getZ() - extendBiome); Location pos2 = Location
Location pos2 = Location.at(world, region.getMaximumPoint().getX() + extendBiome, .at(world, region.getMaximumPoint().getX() + extendBiome, region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome);
region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome);
final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world)); final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world));
final int minX = pos1.getX(); final int minX = pos1.getX();
@ -241,9 +236,7 @@ public abstract class RegionManager {
queue.setChunkConsumer(blockVector2 -> { queue.setChunkConsumer(blockVector2 -> {
final int cx = blockVector2.getX() << 4; final int cx = blockVector2.getX() << 4;
final int cz = blockVector2.getZ() << 4; final int cz = blockVector2.getZ() << 4;
WorldUtil WorldUtil.setBiome(world, Math.max(minX, cx), Math.max(minZ, cz), Math.min(maxX, cx + 15), Math.min(maxZ, cz + 15), biome);
.setBiome(world, Math.max(minX, cx), Math.max(minZ, cz), Math.min(maxX, cx + 15),
Math.min(maxZ, cz + 15), biome);
worldUtil.refreshChunk(blockVector2.getBlockX(), blockVector2.getBlockZ(), world); worldUtil.refreshChunk(blockVector2.getBlockX(), blockVector2.getBlockZ(), world);
}); });
queue.setCompleteTask(whenDone); queue.setCompleteTask(whenDone);

View File

@ -105,8 +105,7 @@ import java.util.zip.GZIPOutputStream;
public abstract class SchematicHandler { public abstract class SchematicHandler {
private static final Logger logger = private static final Logger logger = LoggerFactory.getLogger("P2/" + SchematicHandler.class.getSimpleName());
LoggerFactory.getLogger("P2/" + SchematicHandler.class.getSimpleName());
public static SchematicHandler manager; public static SchematicHandler manager;
private final WorldUtil worldUtil; private final WorldUtil worldUtil;
private boolean exportAll = false; private boolean exportAll = false;
@ -115,8 +114,10 @@ public abstract class SchematicHandler {
this.worldUtil = worldUtil; this.worldUtil = worldUtil;
} }
public static void upload(@Nullable UUID uuid, @Nullable final String file, public static void upload(@Nullable UUID uuid,
@Nonnull final String extension, @Nullable final RunnableVal<OutputStream> writeTask, @Nullable final String file,
@Nonnull final String extension,
@Nullable final RunnableVal<OutputStream> writeTask,
@Nonnull final RunnableVal<URL> whenDone) { @Nonnull final RunnableVal<URL> whenDone) {
if (writeTask == null) { if (writeTask == null) {
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
@ -147,23 +148,16 @@ public abstract class SchematicHandler {
con.setDoOutput(true); con.setDoOutput(true);
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (OutputStream output = con.getOutputStream(); try (OutputStream output = con.getOutputStream();
PrintWriter writer = new PrintWriter( PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) {
new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) {
String CRLF = "\r\n"; String CRLF = "\r\n";
writer.append("--" + boundary).append(CRLF); writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append( writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName()).append(CRLF);
"Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName())
.append(CRLF);
String param = "value"; String param = "value";
writer.append(CRLF).append(param).append(CRLF).flush(); writer.append(CRLF).append(param).append(CRLF).flush();
writer.append("--" + boundary).append(CRLF); writer.append("--" + boundary).append(CRLF);
writer.append( writer.append("Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" + filename + '"').append(CRLF);
"Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(filename)).append(CRLF);
+ filename + '"').append(CRLF);
writer
.append("Content-Type: " + URLConnection.guessContentTypeFromName(filename))
.append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush(); writer.append(CRLF).flush();
writeTask.value = new AbstractDelegateOutputStream(output) { writeTask.value = new AbstractDelegateOutputStream(output) {
@ -193,8 +187,7 @@ public abstract class SchematicHandler {
}); });
} }
public boolean exportAll(Collection<Plot> collection, final File outputDir, public boolean exportAll(Collection<Plot> collection, final File outputDir, final String namingScheme, final Runnable ifSuccess) {
final String namingScheme, final Runnable ifSuccess) {
if (this.exportAll) { if (this.exportAll) {
return false; return false;
} }
@ -223,14 +216,10 @@ public abstract class SchematicHandler {
final String name; final String name;
if (namingScheme == null) { if (namingScheme == null) {
name = name = plot.getId().getX() + ";" + plot.getId().getY() + ',' + plot.getArea() + ',' + owner;
plot.getId().getX() + ";" + plot.getId().getY() + ',' + plot.getArea() + ','
+ owner;
} else { } else {
name = namingScheme.replaceAll("%id%", plot.getId().toString()) name = namingScheme.replaceAll("%id%", plot.getId().toString()).replaceAll("%idx%", plot.getId().getX() + "")
.replaceAll("%idx%", plot.getId().getX() + "") .replaceAll("%idy%", plot.getId().getY() + "").replaceAll("%world%", plot.getArea().toString());
.replaceAll("%idy%", plot.getId().getY() + "")
.replaceAll("%world%", plot.getArea().toString());
} }
final String directory; final String directory;
@ -245,8 +234,7 @@ public abstract class SchematicHandler {
@Override public void run(final CompoundTag value) { @Override public void run(final CompoundTag value) {
if (value != null) { if (value != null) {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(() -> {
boolean result = boolean result = save(value, directory + File.separator + name + ".schem");
save(value, directory + File.separator + name + ".schem");
if (!result) { if (!result) {
logger.error("[P2] Failed to save {}", plot.getId()); logger.error("[P2] Failed to save {}", plot.getId());
} }
@ -268,8 +256,12 @@ public abstract class SchematicHandler {
* @param xOffset offset x to paste it from plot origin * @param xOffset offset x to paste it from plot origin
* @param zOffset offset z to paste it from plot origin * @param zOffset offset z to paste it from plot origin
*/ */
public void paste(final Schematic schematic, final Plot plot, final int xOffset, public void paste(final Schematic schematic,
final int yOffset, final int zOffset, final boolean autoHeight, final Plot plot,
final int xOffset,
final int yOffset,
final int zOffset,
final boolean autoHeight,
final RunnableVal<Boolean> whenDone) { final RunnableVal<Boolean> whenDone) {
TaskManager.runTask(() -> { TaskManager.runTask(() -> {
@ -287,10 +279,8 @@ public abstract class SchematicHandler {
final int HEIGHT = dimension.getY(); final int HEIGHT = dimension.getY();
// Validate dimensions // Validate dimensions
CuboidRegion region = plot.getLargestRegion(); CuboidRegion region = plot.getLargestRegion();
if (((region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + xOffset if (((region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + xOffset + 1) < WIDTH) || (
+ 1) < WIDTH) || ( (region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + zOffset + 1) < LENGTH) || (HEIGHT > 256)) {
(region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + zOffset
+ 1) < LENGTH) || (HEIGHT > 256)) {
TaskManager.runTask(whenDone); TaskManager.runTask(whenDone);
return; return;
} }
@ -307,8 +297,7 @@ public abstract class SchematicHandler {
y_offset_actual = yOffset + ((ClassicPlotWorld) pw).PLOT_HEIGHT; y_offset_actual = yOffset + ((ClassicPlotWorld) pw).PLOT_HEIGHT;
} else { } else {
y_offset_actual = yOffset + 1 + this.worldUtil y_offset_actual = yOffset + 1 + this.worldUtil
.getHighestBlockSynchronous(plot.getWorldName(), .getHighestBlockSynchronous(plot.getWorldName(), region.getMinimumPoint().getX() + 1,
region.getMinimumPoint().getX() + 1,
region.getMinimumPoint().getZ() + 1); region.getMinimumPoint().getZ() + 1);
} }
} }
@ -317,8 +306,7 @@ public abstract class SchematicHandler {
} }
final Location pos1 = Location final Location pos1 = Location
.at(plot.getWorldName(), region.getMinimumPoint().getX() + xOffset, .at(plot.getWorldName(), region.getMinimumPoint().getX() + xOffset, y_offset_actual, region.getMinimumPoint().getZ() + zOffset);
y_offset_actual, region.getMinimumPoint().getZ() + zOffset);
final Location pos2 = pos1.add(WIDTH - 1, HEIGHT - 1, LENGTH - 1); final Location pos2 = pos1.add(WIDTH - 1, HEIGHT - 1, LENGTH - 1);
final int p1x = pos1.getX(); final int p1x = pos1.getX();
@ -341,12 +329,10 @@ public abstract class SchematicHandler {
for (int rx = 0; rx < blockArrayClipboard.getDimensions().getX(); rx++) { for (int rx = 0; rx < blockArrayClipboard.getDimensions().getX(); rx++) {
int xx = p1x + xOffset + rx; int xx = p1x + xOffset + rx;
int zz = p1z + zOffset + rz; int zz = p1z + zOffset + rz;
BaseBlock id = BaseBlock id = blockArrayClipboard.getFullBlock(BlockVector3.at(rx, ry, rz));
blockArrayClipboard.getFullBlock(BlockVector3.at(rx, ry, rz));
queue.setBlock(xx, yy, zz, id); queue.setBlock(xx, yy, zz, id);
if (ry == 0) { if (ry == 0) {
BiomeType biome = BiomeType biome = blockArrayClipboard.getBiome(BlockVector3.at(rx, ry, rz));
blockArrayClipboard.getBiome(BlockVector3.at(rx, ry, rz));
queue.setBiome(xx, yy, zz, biome); queue.setBiome(xx, yy, zz, biome);
} }
} }
@ -364,8 +350,7 @@ public abstract class SchematicHandler {
}); });
} }
public abstract boolean restoreTile(QueueCoordinator queue, CompoundTag tag, int x, int y, public abstract boolean restoreTile(QueueCoordinator queue, CompoundTag tag, int x, int y, int z);
int z);
/** /**
* Get a schematic * Get a schematic
@ -374,8 +359,7 @@ public abstract class SchematicHandler {
* @return schematic if found, else null * @return schematic if found, else null
*/ */
public Schematic getSchematic(String name) throws UnsupportedFormatException { public Schematic getSchematic(String name) throws UnsupportedFormatException {
File parent = File parent = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS);
FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS);
if (!parent.exists()) { if (!parent.exists()) {
if (!parent.mkdir()) { if (!parent.mkdir()) {
throw new RuntimeException("Could not create schematic parent directory"); throw new RuntimeException("Could not create schematic parent directory");
@ -384,11 +368,9 @@ public abstract class SchematicHandler {
if (!name.endsWith(".schem") && !name.endsWith(".schematic")) { if (!name.endsWith(".schem") && !name.endsWith(".schematic")) {
name = name + ".schem"; name = name + ".schem";
} }
File file = FileUtils.getFile(PlotSquared.platform().getDirectory(), File file = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS + File.separator + name);
Settings.Paths.SCHEMATICS + File.separator + name);
if (!file.exists()) { if (!file.exists()) {
file = FileUtils.getFile(PlotSquared.platform().getDirectory(), file = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS + File.separator + name);
Settings.Paths.SCHEMATICS + File.separator + name);
} }
return getSchematic(file); return getSchematic(file);
} }
@ -399,12 +381,10 @@ public abstract class SchematicHandler {
* @return Immutable collection with schematic names * @return Immutable collection with schematic names
*/ */
public Collection<String> getSchematicNames() { public Collection<String> getSchematicNames() {
final File parent = final File parent = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS);
FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS);
final List<String> names = new ArrayList<>(); final List<String> names = new ArrayList<>();
if (parent.exists()) { if (parent.exists()) {
final String[] rawNames = final String[] rawNames = parent.list((dir, name) -> name.endsWith(".schematic") || name.endsWith(".schem"));
parent.list((dir, name) -> name.endsWith(".schematic") || name.endsWith(".schem"));
if (rawNames != null) { if (rawNames != null) {
final List<String> transformed = Arrays.stream(rawNames) final List<String> transformed = Arrays.stream(rawNames)
//.map(rawName -> rawName.substring(0, rawName.length() - 10)) //.map(rawName -> rawName.substring(0, rawName.length() - 10))
@ -434,8 +414,7 @@ public abstract class SchematicHandler {
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
throw new UnsupportedFormatException( throw new UnsupportedFormatException("This schematic format is not recognised or supported.");
"This schematic format is not recognised or supported.");
} }
return null; return null;
} }
@ -453,14 +432,12 @@ public abstract class SchematicHandler {
public Schematic getSchematic(@Nonnull InputStream is) { public Schematic getSchematic(@Nonnull InputStream is) {
try { try {
SpongeSchematicReader schematicReader = SpongeSchematicReader schematicReader = new SpongeSchematicReader(new NBTInputStream(new GZIPInputStream(is)));
new SpongeSchematicReader(new NBTInputStream(new GZIPInputStream(is)));
Clipboard clip = schematicReader.read(); Clipboard clip = schematicReader.read();
return new Schematic(clip); return new Schematic(clip);
} catch (IOException ignored) { } catch (IOException ignored) {
try { try {
MCEditSchematicReader schematicReader = MCEditSchematicReader schematicReader = new MCEditSchematicReader(new NBTInputStream(new GZIPInputStream(is)));
new MCEditSchematicReader(new NBTInputStream(new GZIPInputStream(is)));
Clipboard clip = schematicReader.read(); Clipboard clip = schematicReader.read();
return new Schematic(clip); return new Schematic(clip);
} catch (IOException e) { } catch (IOException e) {
@ -477,8 +454,7 @@ public abstract class SchematicHandler {
URL url = new URL(website); URL url = new URL(website);
URLConnection connection = new URL(url.toString()).openConnection(); URLConnection connection = new URL(url.toString()).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setRequestProperty("User-Agent", "Mozilla/5.0");
try (BufferedReader reader = new BufferedReader( try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
new InputStreamReader(connection.getInputStream()))) {
rawJSON = reader.lines().collect(Collectors.joining()); rawJSON = reader.lines().collect(Collectors.joining());
} }
JSONArray array = new JSONArray(rawJSON); JSONArray array = new JSONArray(rawJSON);
@ -501,8 +477,7 @@ public abstract class SchematicHandler {
} }
upload(uuid, file, "schem", new RunnableVal<OutputStream>() { upload(uuid, file, "schem", new RunnableVal<OutputStream>() {
@Override public void run(OutputStream output) { @Override public void run(OutputStream output) {
try (NBTOutputStream nos = new NBTOutputStream( try (NBTOutputStream nos = new NBTOutputStream(new GZIPOutputStream(output, true))) {
new GZIPOutputStream(output, true))) {
nos.writeNamedTag("Schematic", tag); nos.writeNamedTag("Schematic", tag);
} catch (IOException e1) { } catch (IOException e1) {
e1.printStackTrace(); e1.printStackTrace();
@ -525,8 +500,7 @@ public abstract class SchematicHandler {
try { try {
File tmp = FileUtils.getFile(PlotSquared.platform().getDirectory(), path); File tmp = FileUtils.getFile(PlotSquared.platform().getDirectory(), path);
tmp.getParentFile().mkdirs(); tmp.getParentFile().mkdirs();
try (NBTOutputStream nbtStream = new NBTOutputStream( try (NBTOutputStream nbtStream = new NBTOutputStream(new GZIPOutputStream(new FileOutputStream(tmp)))) {
new GZIPOutputStream(new FileOutputStream(tmp)))) {
nbtStream.writeNamedTag("Schematic", tag); nbtStream.writeNamedTag("Schematic", tag);
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
@ -538,8 +512,7 @@ public abstract class SchematicHandler {
return true; return true;
} }
public void getCompoundTag(final String world, final Set<CuboidRegion> regions, public void getCompoundTag(final String world, final Set<CuboidRegion> regions, final RunnableVal<CompoundTag> whenDone) {
final RunnableVal<CompoundTag> whenDone) {
// async // async
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(() -> {
// Main positions // Main positions
@ -547,17 +520,15 @@ public abstract class SchematicHandler {
final Location bot = corners[0]; final Location bot = corners[0];
final Location top = corners[1]; final Location top = corners[1];
CuboidRegion cuboidRegion = CuboidRegion cuboidRegion = new CuboidRegion(this.worldUtil.getWeWorld(world), bot.getBlockVector3(), top.getBlockVector3());
new CuboidRegion(this.worldUtil.getWeWorld(world), bot.getBlockVector3(),
top.getBlockVector3());
final int width = cuboidRegion.getWidth(); final int width = cuboidRegion.getWidth();
int height = cuboidRegion.getHeight(); int height = cuboidRegion.getHeight();
final int length = cuboidRegion.getLength(); final int length = cuboidRegion.getLength();
Map<String, Tag> schematic = new HashMap<>(); Map<String, Tag> schematic = new HashMap<>();
schematic.put("Version", new IntTag(2)); schematic.put("Version", new IntTag(2));
schematic.put("DataVersion", new IntTag(WorldEdit.getInstance().getPlatformManager() schematic.put("DataVersion",
.queryCapability(Capability.WORLD_EDITING).getDataVersion())); new IntTag(WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).getDataVersion()));
Map<String, Tag> metadata = new HashMap<>(); Map<String, Tag> metadata = new HashMap<>();
metadata.put("WEOffsetX", new IntTag(0)); metadata.put("WEOffsetX", new IntTag(0));
@ -592,14 +563,12 @@ public abstract class SchematicHandler {
schematic.put("Palette", new CompoundTag(paletteTag)); schematic.put("Palette", new CompoundTag(paletteTag));
schematic.put("BlockData", new ByteArrayTag(buffer.toByteArray())); schematic.put("BlockData", new ByteArrayTag(buffer.toByteArray()));
schematic schematic.put("TileEntities", new ListTag(CompoundTag.class, tileEntities));
.put("TileEntities", new ListTag(CompoundTag.class, tileEntities));
schematic.put("BiomePaletteMax", new IntTag(biomePalette.size())); schematic.put("BiomePaletteMax", new IntTag(biomePalette.size()));
Map<String, Tag> biomePaletteTag = new HashMap<>(); Map<String, Tag> biomePaletteTag = new HashMap<>();
biomePalette.forEach( biomePalette.forEach((key, value) -> biomePaletteTag.put(key, new IntTag(value)));
(key, value) -> biomePaletteTag.put(key, new IntTag(value)));
schematic.put("BiomePalette", new CompoundTag(biomePaletteTag)); schematic.put("BiomePalette", new CompoundTag(biomePaletteTag));
schematic.put("BiomeData", new ByteArrayTag(biomeBuffer.toByteArray())); schematic.put("BiomeData", new ByteArrayTag(biomeBuffer.toByteArray()));
@ -630,33 +599,23 @@ public abstract class SchematicHandler {
final Runnable zTask = new Runnable() { final Runnable zTask = new Runnable() {
@Override public void run() { @Override public void run() {
long zstart = System.currentTimeMillis(); long zstart = System.currentTimeMillis();
while (ziter.hasNext() while (ziter.hasNext() && System.currentTimeMillis() - zstart < 20) {
&& System.currentTimeMillis() - zstart < 20) {
final int z = ziter.next(); final int z = ziter.next();
Iterator<Integer> xiter = Iterator<Integer> xiter = IntStream.range(p1x, p2x + 1).iterator();
IntStream.range(p1x, p2x + 1).iterator();
final Runnable xTask = new Runnable() { final Runnable xTask = new Runnable() {
@Override public void run() { @Override public void run() {
long xstart = System.currentTimeMillis(); long xstart = System.currentTimeMillis();
final int ry = y - sy; final int ry = y - sy;
final int rz = z - p1z; final int rz = z - p1z;
while (xiter.hasNext() while (xiter.hasNext() && System.currentTimeMillis() - xstart < 20) {
&& System.currentTimeMillis() - xstart
< 20) {
final int x = xiter.next(); final int x = xiter.next();
final int rx = x - p1x; final int rx = x - p1x;
BlockVector3 point = BlockVector3 point = BlockVector3.at(x, y, z);
BlockVector3.at(x, y, z); BaseBlock block = cuboidRegion.getWorld().getFullBlock(point);
BaseBlock block = cuboidRegion.getWorld()
.getFullBlock(point);
if (block.getNbtData() != null) { if (block.getNbtData() != null) {
Map<String, Tag> values = Map<String, Tag> values = new HashMap<>();
new HashMap<>(); for (Map.Entry<String, Tag> entry : block.getNbtData().getValue().entrySet()) {
for (Map.Entry<String, Tag> entry : block values.put(entry.getKey(), entry.getValue());
.getNbtData().getValue()
.entrySet()) {
values.put(entry.getKey(),
entry.getValue());
} }
// Remove 'id' if it exists. We want 'Id' // Remove 'id' if it exists. We want 'Id'
values.remove("id"); values.remove("id");
@ -666,16 +625,12 @@ public abstract class SchematicHandler {
values.remove("y"); values.remove("y");
values.remove("z"); values.remove("z");
values.put("Id", values.put("Id", new StringTag(block.getNbtId()));
new StringTag(block.getNbtId())); values.put("Pos", new IntArrayTag(new int[] {rx, ry, rz}));
values.put("Pos", new IntArrayTag(
new int[] {rx, ry, rz}));
tileEntities tileEntities.add(new CompoundTag(values));
.add(new CompoundTag(values));
} }
String blockKey = String blockKey = block.toImmutableState().getAsString();
block.toImmutableState().getAsString();
int blockId; int blockId;
if (palette.containsKey(blockKey)) { if (palette.containsKey(blockKey)) {
blockId = palette.get(blockKey); blockId = palette.get(blockKey);
@ -694,8 +649,7 @@ public abstract class SchematicHandler {
continue; continue;
} }
BlockVector2 pt = BlockVector2.at(x, z); BlockVector2 pt = BlockVector2.at(x, z);
BiomeType biome = BiomeType biome = cuboidRegion.getWorld().getBiome(pt);
cuboidRegion.getWorld().getBiome(pt);
String biomeStr = biome.getId(); String biomeStr = biome.getId();
int biomeId; int biomeId;
if (biomePalette.containsKey(biomeStr)) { if (biomePalette.containsKey(biomeStr)) {

View File

@ -127,8 +127,7 @@ public abstract class WorldUtil {
* @param name Block name * @param name Block name
* @return Comparison result containing the closets matching block * @return Comparison result containing the closets matching block
*/ */
@Nonnull public abstract StringComparison<BlockState>.ComparisonResult getClosestBlock( @Nonnull public abstract StringComparison<BlockState>.ComparisonResult getClosestBlock(@Nonnull String name);
@Nonnull String name);
/** /**
* Get the biome in a given chunk, asynchronously * Get the biome in a given chunk, asynchronously
@ -138,8 +137,7 @@ public abstract class WorldUtil {
* @param z Chunk Z coordinate * @param z Chunk Z coordinate
* @param result Result consumer * @param result Result consumer
*/ */
public abstract void getBiome(@Nonnull String world, int x, int z, public abstract void getBiome(@Nonnull String world, int x, int z, @Nonnull Consumer<BiomeType> result);
@Nonnull Consumer<BiomeType> result);
/** /**
* Get the biome in a given chunk, asynchronously * Get the biome in a given chunk, asynchronously
@ -150,8 +148,7 @@ public abstract class WorldUtil {
* @return Biome * @return Biome
* @deprecated Use {@link #getBiome(String, int, int, Consumer)} * @deprecated Use {@link #getBiome(String, int, int, Consumer)}
*/ */
@Deprecated @Nonnull public abstract BiomeType getBiomeSynchronous(@Nonnull String world, int x, @Deprecated @Nonnull public abstract BiomeType getBiomeSynchronous(@Nonnull String world, int x, int z);
int z);
/** /**
* Get the block at a given location (asynchronously) * Get the block at a given location (asynchronously)
@ -178,8 +175,7 @@ public abstract class WorldUtil {
* @param z Z coordinate * @param z Z coordinate
* @param result Result consumer * @param result Result consumer
*/ */
public abstract void getHighestBlock(@Nonnull String world, int x, int z, public abstract void getHighestBlock(@Nonnull String world, int x, int z, @Nonnull IntConsumer result);
@Nonnull IntConsumer result);
/** /**
@ -191,8 +187,7 @@ public abstract class WorldUtil {
* @return Result * @return Result
* @deprecated Use {@link #getHighestBlock(String, int, int, IntConsumer)} * @deprecated Use {@link #getHighestBlock(String, int, int, IntConsumer)}
*/ */
@Deprecated @Nonnegative public abstract int getHighestBlockSynchronous(@Nonnull String world, @Deprecated @Nonnegative public abstract int getHighestBlockSynchronous(@Nonnull String world, int x, int z);
int x, int z);
/** /**
* Set the text in a sign * Set the text in a sign
@ -203,8 +198,7 @@ public abstract class WorldUtil {
* @param z Z coordinate * @param z Z coordinate
* @param lines Sign text * @param lines Sign text
*/ */
public abstract void setSign(@Nonnull String world, int x, int y, int z, public abstract void setSign(@Nonnull String world, int x, int y, int z, @Nonnull String[] lines);
@Nonnull String[] lines);
/** /**
* Set the biome in a region * Set the biome in a region
@ -213,8 +207,7 @@ public abstract class WorldUtil {
* @param region Region * @param region Region
* @param biome New biome * @param biome New biome
*/ */
public abstract void setBiomes(@Nonnull String world, @Nonnull CuboidRegion region, public abstract void setBiomes(@Nonnull String world, @Nonnull CuboidRegion region, @Nonnull BiomeType biome);
@Nonnull BiomeType biome);
/** /**
* Get the WorldEdit {@link com.sk89q.worldedit.world.World} corresponding to a world name * Get the WorldEdit {@link com.sk89q.worldedit.world.World} corresponding to a world name
@ -233,10 +226,8 @@ public abstract class WorldUtil {
*/ */
public abstract void refreshChunk(int x, int z, String world); public abstract void refreshChunk(int x, int z, String world);
public void upload(@Nonnull final Plot plot, @Nullable final UUID uuid, public void upload(@Nonnull final Plot plot, @Nullable final UUID uuid, @Nullable final String file, @Nonnull final RunnableVal<URL> whenDone) {
@Nullable final String file, @Nonnull final RunnableVal<URL> whenDone) { plot.getHome(home -> SchematicHandler.upload(uuid, file, "zip", new RunnableVal<OutputStream>() {
plot.getHome(
home -> SchematicHandler.upload(uuid, file, "zip", new RunnableVal<OutputStream>() {
@Override public void run(OutputStream output) { @Override public void run(OutputStream output) {
try (final ZipOutputStream zos = new ZipOutputStream(output)) { try (final ZipOutputStream zos = new ZipOutputStream(output)) {
File dat = getDat(plot.getWorldName()); File dat = getDat(plot.getWorldName());
@ -244,8 +235,7 @@ public abstract class WorldUtil {
if (dat != null) { if (dat != null) {
ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName()); ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName());
zos.putNextEntry(ze); zos.putNextEntry(ze);
try (NBTInputStream nis = new NBTInputStream( try (NBTInputStream nis = new NBTInputStream(new GZIPInputStream(new FileInputStream(dat)))) {
new GZIPInputStream(new FileInputStream(dat)))) {
CompoundTag tag = (CompoundTag) nis.readNamedTag().getTag(); CompoundTag tag = (CompoundTag) nis.readNamedTag().getTag();
CompoundTag data = (CompoundTag) tag.getValue().get("Data"); CompoundTag data = (CompoundTag) tag.getValue().get("Data");
Map<String, Tag> map = ReflectionUtils.getMap(data.getValue()); Map<String, Tag> map = ReflectionUtils.getMap(data.getValue());
@ -253,8 +243,7 @@ public abstract class WorldUtil {
map.put("SpawnY", new IntTag(home.getY())); map.put("SpawnY", new IntTag(home.getY()));
map.put("SpawnZ", new IntTag(home.getZ())); map.put("SpawnZ", new IntTag(home.getZ()));
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
try (NBTOutputStream out = new NBTOutputStream( try (NBTOutputStream out = new NBTOutputStream(new GZIPOutputStream(baos, true))) {
new GZIPOutputStream(baos, true))) {
//TODO Find what this should be called //TODO Find what this should be called
out.writeNamedTag("Schematic????", tag); out.writeNamedTag("Schematic????", tag);
} }
@ -273,16 +262,12 @@ public abstract class WorldUtil {
int trz = top.getZ() >> 9; int trz = top.getZ() >> 9;
Set<BlockVector2> files = getChunkChunks(bot.getWorldName()); Set<BlockVector2> files = getChunkChunks(bot.getWorldName());
for (BlockVector2 mca : files) { for (BlockVector2 mca : files) {
if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz && mca.getZ() <= trz) {
&& mca.getZ() <= trz) { final File file = getMcr(plot.getWorldName(), mca.getX(), mca.getZ());
final File file =
getMcr(plot.getWorldName(), mca.getX(), mca.getZ());
if (file != null) { if (file != null) {
//final String name = "r." + (x - cx) + "." + (z - cz) + ".mca"; //final String name = "r." + (x - cx) + "." + (z - cz) + ".mca";
String name = file.getName(); String name = file.getName();
final ZipEntry ze = new ZipEntry( final ZipEntry ze = new ZipEntry("world" + File.separator + "region" + File.separator + name);
"world" + File.separator + "region" + File.separator
+ name);
zos.putNextEntry(ze); zos.putNextEntry(ze);
try (FileInputStream in = new FileInputStream(file)) { try (FileInputStream in = new FileInputStream(file)) {
int len; int len;
@ -306,9 +291,7 @@ public abstract class WorldUtil {
} }
@Nullable final File getDat(@Nonnull final String world) { @Nullable final File getDat(@Nonnull final String world) {
File file = new File( File file = new File(PlotSquared.platform().getWorldContainer() + File.separator + world + File.separator + "level.dat");
PlotSquared.platform().getWorldContainer() + File.separator + world + File.separator
+ "level.dat");
if (file.exists()) { if (file.exists()) {
return file; return file;
} }
@ -316,8 +299,8 @@ public abstract class WorldUtil {
} }
@Nullable private File getMcr(@Nonnull final String world, final int x, final int z) { @Nullable private File getMcr(@Nonnull final String world, final int x, final int z) {
final File file = new File(PlotSquared.platform().getWorldContainer(), final File file =
world + File.separator + "region" + File.separator + "r." + x + '.' + z + ".mca"); new File(PlotSquared.platform().getWorldContainer(), world + File.separator + "region" + File.separator + "r." + x + '.' + z + ".mca");
if (file.exists()) { if (file.exists()) {
return file; return file;
} }
@ -326,12 +309,10 @@ public abstract class WorldUtil {
public Set<BlockVector2> getChunkChunks(String world) { public Set<BlockVector2> getChunkChunks(String world) {
File folder = File folder = new File(PlotSquared.platform().getWorldContainer(), world + File.separator + "region");
new File(PlotSquared.platform().getWorldContainer(), world + File.separator + "region");
File[] regionFiles = folder.listFiles(); File[] regionFiles = folder.listFiles();
if (regionFiles == null) { if (regionFiles == null) {
throw new RuntimeException( throw new RuntimeException("Could not find worlds folder: " + folder + " ? (no read access?)");
"Could not find worlds folder: " + folder + " ? (no read access?)");
} }
HashSet<BlockVector2> chunks = new HashSet<>(); HashSet<BlockVector2> chunks = new HashSet<>();
for (File file : regionFiles) { for (File file : regionFiles) {
@ -413,7 +394,6 @@ public abstract class WorldUtil {
* @param chunk Chunk coordinates * @param chunk Chunk coordinates
* @return Tile entity count * @return Tile entity count
*/ */
@Nonnegative public abstract int getTileEntityCount(@Nonnull String world, @Nonnegative public abstract int getTileEntityCount(@Nonnull String world, @Nonnull BlockVector2 chunk);
@Nonnull BlockVector2 chunk);
} }