From 1d0760c63097189938f6035ee1c2163cbeaf5378 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 24 Jul 2020 16:24:53 +0100 Subject: [PATCH] Formatting, mark nonnull, nullable etc --- .../plotsquared/bukkit/BukkitPlatform.java | 195 ++---- .../bukkit/generator/BlockStatePopulator.java | 12 +- .../bukkit/generator/BukkitPlotGenerator.java | 2 +- .../bukkit/inject/BukkitModule.java | 16 +- .../bukkit/queue/BukkitChunkCoordinator.java | 60 +- .../bukkit/queue/BukkitQueueCoordinator.java | 43 +- .../plotsquared/bukkit/queue/GenChunk.java | 51 +- .../bukkit/util/BukkitChunkManager.java | 92 +-- .../plotsquared/bukkit/util/BukkitUtil.java | 133 ++-- .../components/ComponentPresetManager.java | 135 ++-- .../core/generator/AugmentedUtils.java | 19 +- .../core/generator/ClassicPlotManager.java | 262 +++----- .../core/generator/HybridPlotManager.java | 82 +-- .../core/generator/HybridPlotWorld.java | 68 +- .../core/generator/HybridUtils.java | 126 ++-- .../core/generator/SquarePlotManager.java | 47 +- .../inject/annotations/QueuePipeline.java | 39 -- .../ChunkCoordinatorBuilderFactory.java | 3 +- .../factory/ChunkCoordinatorFactory.java | 12 +- .../java/com/plotsquared/core/plot/Plot.java | 588 +++++++----------- .../plotsquared/core/plot/PlotManager.java | 79 ++- .../core/plot/world/SinglePlotManager.java | 88 ++- .../AreaBoundDelegateQueueCoordinator.java | 15 +- .../core/queue/BasicQueueCoordinator.java | 30 +- .../core/queue/ChunkCoordinatorBuilder.java | 27 +- .../core/queue/ChunkQueueCoordinator.java | 22 +- .../core/queue/DelegateQueueCoordinator.java | 36 +- .../core/queue/GlobalBlockQueue.java | 13 +- .../plotsquared/core/queue/LocalChunk.java | 21 +- ...ocationOffsetDelegateQueueCoordinator.java | 56 +- .../core/queue/OffsetQueueCoordinator.java | 14 +- .../core/queue/QueueCoordinator.java | 41 +- .../plotsquared/core/queue/QueueProvider.java | 8 +- .../core/queue/ScopedQueueCoordinator.java | 36 +- .../plotsquared/core/util/ChunkManager.java | 22 +- .../com/plotsquared/core/util/ChunkUtil.java | 12 +- .../plotsquared/core/util/RegionManager.java | 79 ++- .../core/util/SchematicHandler.java | 164 ++--- .../com/plotsquared/core/util/WorldUtil.java | 160 +++-- 39 files changed, 1172 insertions(+), 1736 deletions(-) delete mode 100644 Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index ea5f45430..1b824c3b4 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -165,8 +165,7 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; @SuppressWarnings("unused") public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPlatform { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + BukkitPlatform.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitPlatform.class.getSimpleName()); private static final int BSTATS_ID = 1404; static { @@ -236,10 +235,8 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl final PlotSquared plotSquared = new PlotSquared(this, "Bukkit"); if (PlotSquared.platform().getServerVersion()[1] < 13) { - System.out.println( - "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("You can't use this version of PlotSquared on a server less than Minecraft 1.13.2."); + System.out.println("Please check the download page for the link to the legacy versions."); System.out.println("The server will now be shutdown to prevent any corruption."); Bukkit.shutdown(); return; @@ -247,11 +244,9 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl // We create the injector after PlotSquared has been initialized, so that we have access // to generated instances and settings - this.injector = Guice.createInjector(Stage.PRODUCTION, new PermissionModule(), - new WorldManagerModule(), - new PlotSquaredModule(), - new BukkitModule(this), - new BackupModule()); + this.injector = Guice + .createInjector(Stage.PRODUCTION, new PermissionModule(), new WorldManagerModule(), new PlotSquaredModule(), new BukkitModule(this), + new BackupModule()); this.injector.injectMembers(this); if (PremiumVerification.isPremium() && Settings.Enabled_Components.UPDATE_NOTIFICATIONS) { @@ -296,8 +291,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl // Do stuff that was previously done in PlotSquared // Kill entities - if (Settings.Enabled_Components.KILL_ROAD_MOBS - || Settings.Enabled_Components.KILL_ROAD_VEHICLES) { + if (Settings.Enabled_Components.KILL_ROAD_MOBS || Settings.Enabled_Components.KILL_ROAD_VEHICLES) { this.runEntityTask(); } @@ -305,35 +299,28 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl if (Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) { try { logger.info("[P2] {} hooked into WorldEdit", this.getPluginName()); - WorldEdit.getInstance().getEventBus() - .register(this.getInjector().getInstance(WESubscriber.class)); + WorldEdit.getInstance().getEventBus().register(this.getInjector().getInstance(WESubscriber.class)); if (Settings.Enabled_Components.COMMANDS) { new WE_Anywhere(); } } catch (Throwable e) { - logger.error( - "[P2] Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master"); + logger.error("[P2] Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master"); } } if (Settings.Enabled_Components.EVENTS) { - getServer().getPluginManager() - .registerEvents(getInjector().getInstance(PlayerEvents.class), this); - getServer().getPluginManager() - .registerEvents(getInjector().getInstance(EntitySpawnListener.class), this); + getServer().getPluginManager().registerEvents(getInjector().getInstance(PlayerEvents.class), this); + getServer().getPluginManager().registerEvents(getInjector().getInstance(EntitySpawnListener.class), this); if (PaperLib.isPaper() && Settings.Paper_Components.PAPER_LISTENERS) { - getServer().getPluginManager() - .registerEvents(getInjector().getInstance(PaperListener.class), this); + getServer().getPluginManager().registerEvents(getInjector().getInstance(PaperListener.class), this); } this.plotListener.startRunnable(); } // Required - getServer().getPluginManager() - .registerEvents(getInjector().getInstance(WorldEvents.class), this); + getServer().getPluginManager().registerEvents(getInjector().getInstance(WorldEvents.class), this); if (Settings.Enabled_Components.CHUNK_PROCESSOR) { - getServer().getPluginManager() - .registerEvents(getInjector().getInstance(ChunkListener.class), this); + getServer().getPluginManager().registerEvents(getInjector().getInstance(ChunkListener.class), this); } // Commands @@ -361,8 +348,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } // World generators: - final ConfigurationSection section = - this.worldConfiguration.getConfigurationSection("worlds"); + final ConfigurationSection section = this.worldConfiguration.getConfigurationSection("worlds"); final WorldUtil worldUtil = getInjector().getInstance(WorldUtil.class); if (section != null) { @@ -380,15 +366,11 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl continue; } if (!worldUtil.isWorld(world) && !world.equals("*")) { - logger.warn( - "[P2] `{}` was not properly loaded - {} will now try to load it properly", - world, this.getPluginName()); + logger.warn("[P2] `{}` was not properly loaded - {} will now try to load it properly", world, this.getPluginName()); logger.warn( "[P2] - Are you trying to delete this world? Remember to remove it from the worlds.yml, bukkit.yml and multiverse worlds.yml"); - logger.warn( - "[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] - 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."); this.setGenerator(world); } } @@ -396,8 +378,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } // Services are accessed in order - final CacheUUIDService cacheUUIDService = - new CacheUUIDService(Settings.UUID.UUID_CACHE_SIZE); + final CacheUUIDService cacheUUIDService = new CacheUUIDService(Settings.UUID.UUID_CACHE_SIZE); this.impromptuPipeline.registerService(cacheUUIDService); this.backgroundPipeline.registerService(cacheUUIDService); this.impromptuPipeline.registerConsumer(cacheUUIDService); @@ -413,8 +394,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } if (Settings.UUID.SERVICE_BUKKIT) { - final OfflinePlayerUUIDService offlinePlayerUUIDService = - new OfflinePlayerUUIDService(); + final OfflinePlayerUUIDService offlinePlayerUUIDService = new OfflinePlayerUUIDService(); this.impromptuPipeline.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 legacyUUIDService; - if (Settings.UUID.LEGACY_DATABASE_SUPPORT && - FileUtils.getFile(PlotSquared.platform().getDirectory(), "usercache.db").exists()) { + if (Settings.UUID.LEGACY_DATABASE_SUPPORT && FileUtils.getFile(PlotSquared.platform().getDirectory(), "usercache.db").exists()) { legacyUUIDService = new SQLiteUUIDService("usercache.db"); } else { legacyUUIDService = null; } final LuckPermsUUIDService luckPermsUUIDService; - if (Settings.UUID.SERVICE_LUCKPERMS - && Bukkit.getPluginManager().getPlugin("LuckPerms") != null) { + if (Settings.UUID.SERVICE_LUCKPERMS && Bukkit.getPluginManager().getPlugin("LuckPerms") != null) { luckPermsUUIDService = new LuckPermsUUIDService(); logger.info("[P2] (UUID) Using LuckPerms as a complementary UUID service"); } else { @@ -439,8 +417,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } final BungeePermsUUIDService bungeePermsUUIDService; - if (Settings.UUID.SERVICE_BUNGEE_PERMS - && Bukkit.getPluginManager().getPlugin("BungeePerms") != null) { + if (Settings.UUID.SERVICE_BUNGEE_PERMS && Bukkit.getPluginManager().getPlugin("BungeePerms") != null) { bungeePermsUUIDService = new BungeePermsUUIDService(); logger.info("[P2] (UUID) Using BungeePerms as a complementary UUID service"); } else { @@ -448,8 +425,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } final EssentialsUUIDService essentialsUUIDService; - if (Settings.UUID.SERVICE_ESSENTIALSX - && Bukkit.getPluginManager().getPlugin("Essentials") != null) { + if (Settings.UUID.SERVICE_ESSENTIALSX && Bukkit.getPluginManager().getPlugin("Essentials") != null) { essentialsUUIDService = new EssentialsUUIDService(); logger.info("[P2] (UUID) Using EssentialsX as a complementary UUID service"); } else { @@ -489,11 +465,9 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl this.backgroundPipeline.registerService(essentialsUUIDService); } - final SquirrelIdUUIDService impromptuMojangService = - new SquirrelIdUUIDService(Settings.UUID.IMPROMPTU_LIMIT); + final SquirrelIdUUIDService impromptuMojangService = new SquirrelIdUUIDService(Settings.UUID.IMPROMPTU_LIMIT); this.impromptuPipeline.registerService(impromptuMojangService); - final SquirrelIdUUIDService backgroundMojangService = - new SquirrelIdUUIDService(Settings.UUID.BACKGROUND_LIMIT); + final SquirrelIdUUIDService backgroundMojangService = new SquirrelIdUUIDService(Settings.UUID.BACKGROUND_LIMIT); this.backgroundPipeline.registerService(backgroundMojangService); } else { this.impromptuPipeline.registerService(sqLiteUUIDService); @@ -536,10 +510,8 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl // Clean up potential memory leak Bukkit.getScheduler().runTaskTimer(this, () -> { try { - for (final PlotPlayer player : this.getPlayerManager() - .getPlayers()) { - if (player.getPlatformPlayer() == null || !player.getPlatformPlayer() - .isOnline()) { + for (final PlotPlayer player : this.getPlayerManager().getPlayers()) { + if (player.getPlatformPlayer() == null || !player.getPlatformPlayer().isOnline()) { this.getPlayerManager().removePlayer(player); } } @@ -554,8 +526,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl this.methodUnloadSetup = true; try { ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); - this.methodUnloadChunk0 = classCraftWorld.getRealClass() - .getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class); + this.methodUnloadChunk0 = classCraftWorld.getRealClass().getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class); this.methodUnloadChunk0.setAccessible(true); } catch (Throwable event) { event.printStackTrace(); @@ -586,8 +557,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } final Plot plot = area.getOwnedPlot(id); if (plot != null) { - if (!plot.getFlag(ServerPlotFlag.class) || PlotSquared.platform().getPlayerManager() - .getPlayerIfExists(plot.getOwner()) == null) { + if (!plot.getFlag(ServerPlotFlag.class) || PlotSquared.platform().getPlayerManager().getPlayerIfExists(plot.getOwner()) == null) { if (world.getKeepSpawnInMemory()) { world.setKeepSpawnInMemory(false); return; @@ -605,8 +575,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl boolean result; if (methodUnloadChunk0 != null) { try { - result = (boolean) methodUnloadChunk0 - .invoke(world, chunkI.getX(), chunkI.getZ(), true); + result = (boolean) methodUnloadChunk0.invoke(world, chunkI.getX(), chunkI.getZ(), true); } catch (Throwable e) { methodUnloadChunk0 = null; e.printStackTrace(); @@ -629,8 +598,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } } - private void startUuidCaching(@Nonnull final SQLiteUUIDService sqLiteUUIDService, - @Nonnull final CacheUUIDService cacheUUIDService) { + private void startUuidCaching(@Nonnull final SQLiteUUIDService sqLiteUUIDService, @Nonnull final CacheUUIDService cacheUUIDService) { // Load all uuids into a big chunky boi queue final Queue uuidQueue = new LinkedBlockingQueue<>(); PlotSquared.get().forEachPlotRaw(plot -> { @@ -654,8 +622,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl // Now fetch names for all known UUIDs final int totalSize = uuidQueue.size(); int read = 0; - logger.info("[P2] (UUID) PlotSquared will fetch UUIDs in groups of {}", - Settings.UUID.BACKGROUND_LIMIT); + logger.info("[P2] (UUID) PlotSquared will fetch UUIDs in groups of {}", Settings.UUID.BACKGROUND_LIMIT); final List uuidList = new ArrayList<>(Settings.UUID.BACKGROUND_LIMIT); // 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 secondRun = false; // Populate the request list - for (int i = 0; - i < Settings.UUID.BACKGROUND_LIMIT && !uuidQueue.isEmpty(); i++) { + for (int i = 0; i < Settings.UUID.BACKGROUND_LIMIT && !uuidQueue.isEmpty(); i++) { uuidList.add(uuidQueue.poll()); read++; } @@ -688,8 +654,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl // Print progress final double percentage = ((double) read / (double) totalSize) * 100.0D; if (Settings.DEBUG) { - logger.info("[P2] (UUID) PlotSquared has cached {} of UUIDs", - String.format("%.1f%%", percentage)); + logger.info("[P2] (UUID) PlotSquared has cached {} of UUIDs", String.format("%.1f%%", percentage)); } } catch (final InterruptedException | ExecutionException 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 "BOAT": if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { - com.plotsquared.core.location.Location location = - BukkitUtil.adapt(entity.getLocation()); + com.plotsquared.core.location.Location location = BukkitUtil.adapt(entity.getLocation()); Plot plot = location.getPlot(); if (plot == null) { if (location.isPlotArea()) { @@ -822,9 +786,8 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl case "FIREBALL": case "DRAGON_FIREBALL": case "DROPPED_ITEM": - if (Settings.Enabled_Components.KILL_ROAD_ITEMS && plotArea - .getOwnedPlotAbs(BukkitUtil.adapt(entity.getLocation())) - == null) { + if (Settings.Enabled_Components.KILL_ROAD_ITEMS + && plotArea.getOwnedPlotAbs(BukkitUtil.adapt(entity.getLocation())) == null) { entity.remove(); } // dropped item @@ -848,15 +811,12 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl PlotId originalPlotId = (PlotId) meta.get(0).value(); if (originalPlotId != null) { - com.plotsquared.core.location.Location pLoc = - BukkitUtil.adapt(entity.getLocation()); + com.plotsquared.core.location.Location pLoc = BukkitUtil.adapt(entity.getLocation()); PlotArea area = pLoc.getPlotArea(); if (area != null) { PlotId currentPlotId = area.getPlotAbs(pLoc).getId(); - if (!originalPlotId.equals(currentPlotId) && ( - currentPlotId == null || !area - .getPlot(originalPlotId) - .equals(area.getPlot(currentPlotId)))) { + if (!originalPlotId.equals(currentPlotId) && (currentPlotId == null || !area.getPlot(originalPlotId) + .equals(area.getPlot(currentPlotId)))) { if (entity.hasMetadata("ps-tmp-teleport")) { continue; } @@ -867,16 +827,12 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } } else { //This is to apply the metadata to already spawned shulkers (see EntitySpawnListener.java) - com.plotsquared.core.location.Location pLoc = - BukkitUtil.adapt(entity.getLocation()); + com.plotsquared.core.location.Location pLoc = BukkitUtil.adapt(entity.getLocation()); PlotArea area = pLoc.getPlotArea(); if (area != null) { PlotId currentPlotId = area.getPlotAbs(pLoc).getId(); if (currentPlotId != null) { - entity.setMetadata("shulkerPlot", - new FixedMetadataValue( - (Plugin) PlotSquared.platform(), - currentPlotId)); + entity.setMetadata("shulkerPlot", 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 (entity instanceof LivingEntity) { LivingEntity livingEntity = (LivingEntity) entity; - if (!livingEntity.isLeashed() || !entity - .hasMetadata("keep")) { + if (!livingEntity.isLeashed() || !entity.hasMetadata("keep")) { Entity passenger = entity.getPassenger(); - if (!(passenger instanceof Player) && entity - .getMetadata("keep").isEmpty()) { + if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) { if (entity.hasMetadata("ps-tmp-teleport")) { continue; } @@ -972,8 +926,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } } else { Entity passenger = entity.getPassenger(); - if (!(passenger instanceof Player) && entity - .getMetadata("keep").isEmpty()) { + if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) { if (entity.hasMetadata("ps-tmp-teleport")) { continue; } @@ -994,15 +947,12 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl }), TaskTime.seconds(1L)); } - @Override @Nullable - public final ChunkGenerator getDefaultWorldGenerator(@Nonnull final String worldName, - final String id) { + @Override @Nullable public final ChunkGenerator getDefaultWorldGenerator(@Nonnull final String worldName, final String id) { final IndependentPlotGenerator result; if (id != null && id.equalsIgnoreCase("single")) { result = getInjector().getInstance(SingleWorldGenerator.class); } else { - result = getInjector() - .getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)); + result = getInjector().getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)); if (!PlotSquared.get().setupPlotWorld(worldName, id, result)) { return null; } @@ -1010,8 +960,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl return (ChunkGenerator) result.specify(worldName); } - @Override @Nullable public GeneratorWrapper getGenerator(@Nonnull final String world, - @Nullable final String name) { + @Override @Nullable public GeneratorWrapper getGenerator(@Nonnull final String world, @Nullable final String name) { if (name == null) { return null; } @@ -1023,8 +972,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } return new BukkitPlotGenerator(world, gen, this.plotAreaManager); } else { - return new BukkitPlotGenerator(world, getInjector() - .getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)), + return new BukkitPlotGenerator(world, getInjector().getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)), this.plotAreaManager); } } @@ -1045,19 +993,14 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl map.put(plotAreaType.name().toLowerCase(), terrainTypes); } for (final PlotArea plotArea : this.plotAreaManager.getAllPlotAreas()) { - final Map terrainTypeMap = - map.get(plotArea.getType().name().toLowerCase()); - terrainTypeMap.put(plotArea.getTerrain().name().toLowerCase(), - terrainTypeMap.get(plotArea.getTerrain().name().toLowerCase()) + 1); + final Map terrainTypeMap = map.get(plotArea.getType().name().toLowerCase()); + terrainTypeMap.put(plotArea.getTerrain().name().toLowerCase(), terrainTypeMap.get(plotArea.getTerrain().name().toLowerCase()) + 1); } return map; })); - metrics.addCustomChart(new Metrics.SimplePie("premium", - () -> PremiumVerification.isPremium() ? "Premium" : "Non-Premium")); + metrics.addCustomChart(new Metrics.SimplePie("premium", () -> PremiumVerification.isPremium() ? "Premium" : "Non-Premium")); metrics.addCustomChart(new Metrics.SimplePie("worldedit_implementation", - () -> Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit") != null ? - "FastAsyncWorldEdit" : - "WorldEdit")); + () -> Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit") != null ? "FastAsyncWorldEdit" : "WorldEdit")); } @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); if (world == null) { // create world - ConfigurationSection worldConfig = - this.worldConfiguration.getConfigurationSection("worlds." + worldName); + ConfigurationSection worldConfig = this.worldConfiguration.getConfigurationSection("worlds." + worldName); String manager = worldConfig.getString("generator.plugin", getPluginName()); - PlotAreaBuilder builder = PlotAreaBuilder.newBuilder().plotManager(manager) - .generatorName(worldConfig.getString("generator.init", manager)) - .plotAreaType(ConfigurationUtil.getType(worldConfig)) - .terrainType(ConfigurationUtil.getTerrain(worldConfig)) - .settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null)) - .worldName(worldName); + PlotAreaBuilder builder = + PlotAreaBuilder.newBuilder().plotManager(manager).generatorName(worldConfig.getString("generator.init", manager)) + .plotAreaType(ConfigurationUtil.getType(worldConfig)).terrainType(ConfigurationUtil.getTerrain(worldConfig)) + .settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null)).worldName(worldName); getInjector().getInstance(SetupUtils.class).setupWorld(builder); world = Bukkit.getWorld(worldName); } else { @@ -1095,8 +1035,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl if (gen instanceof BukkitPlotGenerator) { PlotSquared.get().loadWorld(worldName, (BukkitPlotGenerator) gen); } else if (gen != null) { - PlotSquared.get().loadWorld(worldName, - new BukkitPlotGenerator(worldName, gen, this.plotAreaManager)); + PlotSquared.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen, this.plotAreaManager)); } else if (this.worldConfiguration.contains("worlds." + worldName)) { PlotSquared.get().loadWorld(worldName, null); } @@ -1115,31 +1054,29 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } } - @Override public GeneratorWrapper wrapPlotGenerator(@Nullable final String world, - @Nonnull final IndependentPlotGenerator generator) { + @Override public GeneratorWrapper wrapPlotGenerator(@Nullable final String world, @Nonnull final IndependentPlotGenerator generator) { return new BukkitPlotGenerator(world, generator, this.plotAreaManager); } @Override public List, Boolean>> getPluginIds() { List, Boolean>> names = new ArrayList<>(); for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - Map.Entry id = new AbstractMap.SimpleEntry<>(plugin.getName(), - plugin.getDescription().getVersion()); + Map.Entry id = new AbstractMap.SimpleEntry<>(plugin.getName(), plugin.getDescription().getVersion()); names.add(new AbstractMap.SimpleEntry<>(id, plugin.isEnabled())); } return names; } - + @Override @Nonnull public com.plotsquared.core.location.World getPlatformWorld(@Nonnull final String worldName) { return BukkitWorld.of(worldName); } @Override @Nonnull public PlatformWorldManager getWorldManager() { - return getInjector().getInstance(Key.get(new TypeLiteral>() {})); + return getInjector().getInstance(Key.get(new TypeLiteral>() { + })); } - @Override @Nonnull @SuppressWarnings("ALL") - public PlayerManager, ? extends Player> getPlayerManager() { + @Override @Nonnull @SuppressWarnings("ALL") public PlayerManager, ? extends Player> getPlayerManager() { return (PlayerManager) getInjector().getInstance(PlayerManager.class); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java index 935ef3fde..9a05dd773 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java @@ -47,24 +47,20 @@ final class BlockStatePopulator extends BlockPopulator { private QueueCoordinator queue; - public BlockStatePopulator(@Nonnull final IndependentPlotGenerator plotGenerator, - @Nonnull final PlotAreaManager plotAreaManager) { + public BlockStatePopulator(@Nonnull final IndependentPlotGenerator plotGenerator, @Nonnull final PlotAreaManager plotAreaManager) { this.plotGenerator = plotGenerator; this.plotAreaManager = plotAreaManager; } - @Override public void populate(@Nonnull final World world, @Nonnull final Random random, - @Nonnull final Chunk source) { + @Override public void populate(@Nonnull final World world, @Nonnull final Random random, @Nonnull final Chunk source) { if (this.queue == null) { - this.queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(new BukkitWorld(world)); + this.queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(new BukkitWorld(world)); } final PlotArea area = this.plotAreaManager.getPlotArea(world.getName(), null); if (area == null) { return; } - final ChunkWrapper wrap = - new ChunkWrapper(area.getWorldName(), source.getX(), source.getZ()); + final ChunkWrapper wrap = new ChunkWrapper(area.getWorldName(), source.getX(), source.getZ()); final ScopedQueueCoordinator chunk = this.queue.getForChunk(wrap.x, wrap.z); if (this.plotGenerator.populateChunk(chunk, area)) { this.queue.enqueue(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java index 3e42530c4..bd9959461 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java @@ -63,7 +63,7 @@ public class BukkitPlotGenerator extends ChunkGenerator @Getter private final String levelName; - public BukkitPlotGenerator(@Nonnull final String name, + public BukkitPlotGenerator(@Nonnull final String name, @Nonnull final IndependentPlotGenerator generator, @Nonnull final PlotAreaManager plotAreaManager) { this.plotAreaManager = plotAreaManager; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java index db2e311a0..4d568842e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java @@ -82,19 +82,15 @@ public class BukkitModule extends AbstractModule { bind(PlayerManager.class).to(BukkitPlayerManager.class); bind(JavaPlugin.class).toInstance(bukkitPlatform); bind(PlotPlatform.class).toInstance(bukkitPlatform); - bind(IndependentPlotGenerator.class).annotatedWith(DefaultGenerator.class) - .to(HybridGen.class); + bind(IndependentPlotGenerator.class).annotatedWith(DefaultGenerator.class).to(HybridGen.class); // Console actor @Nonnull ConsoleCommandSender console = Bukkit.getServer().getConsoleSender(); - WorldEditPlugin wePlugin = - ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit")); - bind(Actor.class).annotatedWith(ConsoleActor.class) - .toInstance(wePlugin.wrapCommandSender(console)); + WorldEditPlugin wePlugin = ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit")); + bind(Actor.class).annotatedWith(ConsoleActor.class).toInstance(wePlugin.wrapCommandSender(console)); bind(InventoryUtil.class).to(BukkitInventoryUtil.class); bind(SetupUtils.class).to(BukkitSetupUtils.class); bind(WorldUtil.class).to(BukkitUtil.class); - bind(GlobalBlockQueue.class) - .toInstance(new GlobalBlockQueue(QueueProvider.of(BukkitQueueCoordinator.class))); + bind(GlobalBlockQueue.class).toInstance(new GlobalBlockQueue(QueueProvider.of(BukkitQueueCoordinator.class))); bind(ChunkManager.class).to(BukkitChunkManager.class); bind(RegionManager.class).to(BukkitRegionManager.class); bind(SchematicHandler.class).to(BukkitSchematicHandler.class); @@ -104,9 +100,7 @@ public class BukkitModule extends AbstractModule { bind(PlotAreaManager.class).to(DefaultPlotAreaManager.class); } install(new FactoryModuleBuilder().build(HybridPlotWorldFactory.class)); - install(new FactoryModuleBuilder() - .implement(ChunkCoordinator.class, BukkitChunkCoordinator.class) - .build(ChunkCoordinatorFactory.class)); + install(new FactoryModuleBuilder().implement(ChunkCoordinator.class, BukkitChunkCoordinator.class).build(ChunkCoordinatorFactory.class)); install(new FactoryModuleBuilder().build(ChunkCoordinatorBuilderFactory.class)); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java index 3961cbdac..3f15fc6f3 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java @@ -76,13 +76,13 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { private int batchSize; @Inject private BukkitChunkCoordinator(@Assisted final long maxIterationTime, - @Assisted final int initialBatchSize, - @Assisted @Nonnull final Consumer chunkConsumer, - @Assisted @Nonnull final World world, - @Assisted @Nonnull final Collection requestedChunks, - @Assisted @Nonnull final Runnable whenDone, - @Assisted @Nonnull final Consumer throwableConsumer, - @Assisted final boolean unloadAfter) { + @Assisted final int initialBatchSize, + @Assisted @Nonnull final Consumer chunkConsumer, + @Assisted @Nonnull final World world, + @Assisted @Nonnull final Collection requestedChunks, + @Assisted @Nonnull final Runnable whenDone, + @Assisted @Nonnull final Consumer throwableConsumer, + @Assisted final boolean unloadAfter) { this.requestedChunks = new LinkedBlockingQueue<>(requestedChunks); this.availableChunks = new LinkedBlockingQueue<>(); this.totalSize = requestedChunks.size(); @@ -104,8 +104,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { // Request initial batch this.requestBatch(); // Wait until next tick to give the chunks a chance to be loaded - TaskManager.runTaskLater(() -> TaskManager.runTaskRepeat(this, TaskTime.ticks(1)), - TaskTime.ticks(1)); + TaskManager.runTaskLater(() -> TaskManager.runTaskRepeat(this, TaskTime.ticks(1)), TaskTime.ticks(1)); } @Override public void runTask() { @@ -129,8 +128,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { final long end = System.currentTimeMillis(); // Update iteration time iterationTime = end - start; - } while (2 * iterationTime /* last chunk + next chunk */ < this.maxIterationTime - && (chunk = availableChunks.poll()) != null); + } while (2 * iterationTime /* last chunk + next chunk */ < this.maxIterationTime && (chunk = availableChunks.poll()) != null); if (processedChunks < this.batchSize) { // Adjust batch size based on the amount of processed chunks per tick this.batchSize = processedChunks; @@ -157,36 +155,42 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { } } + /** + * Requests a batch of chunks to be loaded + */ private void requestBatch() { BlockVector2 chunk; 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 - PaperLib.getChunkAtAsync(this.bukkitWorld, chunk.getX(), chunk.getZ(), true, true) - .whenComplete((chunkObject, throwable) -> { - if (throwable != null) { - throwable.printStackTrace(); - // We want one less because this couldn't be processed - this.expectedSize.decrementAndGet(); - } else { - this.processChunk(chunkObject); - } - }); + PaperLib.getChunkAtAsync(this.bukkitWorld, chunk.getX(), chunk.getZ(), true, true).whenComplete((chunkObject, throwable) -> { + if (throwable != null) { + throwable.printStackTrace(); + // We want one less because this couldn't be processed + this.expectedSize.decrementAndGet(); + } else { + this.processChunk(chunkObject); + } + }); } } + /** + * 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) { if (!chunk.isLoaded()) { - throw new IllegalArgumentException( - String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ())); + throw new IllegalArgumentException(String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ())); } chunk.addPluginChunkTicket(this.plugin); 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) { if (!chunk.isLoaded()) { - throw new IllegalArgumentException( - String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ())); + throw new IllegalArgumentException(String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ())); } chunk.removePluginChunkTicket(this.plugin); } @@ -214,8 +218,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { * * @param subscriber Subscriber */ - public void subscribeToProgress( - @Nonnull final BukkitChunkCoordinator.ProgressSubscriber subscriber) { + public void subscribeToProgress(@Nonnull final BukkitChunkCoordinator.ProgressSubscriber subscriber) { this.progressSubscribers.add(subscriber); } @@ -228,8 +231,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { * @param coordinator Coordinator instance that triggered the notification * @param progress Progress in the range [0, 1] */ - void notifyProgress(@Nonnull final BukkitChunkCoordinator coordinator, - final float progress); + void notifyProgress(@Nonnull final BukkitChunkCoordinator coordinator, final float progress); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index 791071e09..510b63e7a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -56,6 +56,7 @@ import org.bukkit.block.Block; import org.bukkit.block.Container; import org.bukkit.block.data.BlockData; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collection; import java.util.function.Consumer; @@ -69,10 +70,9 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { private Runnable whenDone; private ChunkCoordinator chunkCoordinator; - @Inject public BukkitQueueCoordinator(World world) { + @Inject public BukkitQueueCoordinator(@Nonnull World world) { super(world); - sideEffectSet = SideEffectSet.none().with(SideEffect.LIGHTING, SideEffect.State.OFF) - .with(SideEffect.NEIGHBORS, SideEffect.State.OFF); + sideEffectSet = SideEffectSet.none().with(SideEffect.LIGHTING, SideEffect.State.OFF).with(SideEffect.NEIGHBORS, SideEffect.State.OFF); } @Override public BlockState getBlock(int x, int y, int z) { @@ -97,10 +97,8 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { @Override public boolean enqueue() { final Clipboard regenClipboard; if (isRegen()) { - BlockVector3 start = - BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4); - BlockVector3 end = - BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15); + BlockVector3 start = BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4); + BlockVector3 end = BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15); Region region = new CuboidRegion(start, end); regenClipboard = new BlockArrayClipboard(region); regenClipboard.setOrigin(start); @@ -117,17 +115,14 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { consumer = blockVector2 -> { LocalChunk localChunk = getBlockChunks().get(blockVector2); boolean isRegenChunk = - regenClipboard != null && blockVector2.getBlockX() > getRegenStart()[0] - && blockVector2.getBlockZ() > getRegenStart()[1] - && blockVector2.getBlockX() < getRegenEnd()[0] - && blockVector2.getBlockZ() < getRegenEnd()[1]; + regenClipboard != null && blockVector2.getBlockX() > getRegenStart()[0] && blockVector2.getBlockZ() > getRegenStart()[1] + && blockVector2.getBlockX() < getRegenEnd()[0] && blockVector2.getBlockZ() < getRegenEnd()[1]; if (isRegenChunk) { for (int layer = 0; layer < 16; layer++) { for (int y = layer << 4; y < 16; y++) { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { - BaseBlock block = - regenClipboard.getFullBlock(BlockVector3.at(x, y, z)); + BaseBlock block = regenClipboard.getFullBlock(BlockVector3.at(x, y, z)); if (block != null) { setWorldBlock(x, y, z, block, blockVector2); } @@ -186,8 +181,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { getWorld().setBlock(blockVector3, block, sideEffectSet); } catch (WorldEditException ignored) { StateWrapper sw = new StateWrapper(tag); - sw.restoreTag(getWorld().getName(), blockVector3.getX(), - blockVector3.getY(), blockVector3.getZ()); + sw.restoreTag(getWorld().getName(), blockVector3.getX(), blockVector3.getY(), blockVector3.getZ()); } })); } @@ -203,15 +197,16 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { read.addAll(getReadChunks()); } chunkCoordinator = - chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(getWorld()) - .withChunks(getBlockChunks().keySet()).withChunks(read).withInitialBatchSize(3) - .withMaxIterationTime(40).withThrowableConsumer(Throwable::printStackTrace) - .withFinalAction(whenDone).withConsumer(consumer).unloadAfter(isUnloadAfter()) - .build(); + chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(getWorld()).withChunks(getBlockChunks().keySet()).withChunks(read) + .withInitialBatchSize(3).withMaxIterationTime(40).withThrowableConsumer(Throwable::printStackTrace).withFinalAction(whenDone) + .withConsumer(consumer).unloadAfter(isUnloadAfter()).build(); 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 { getWorld().setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); } catch (WorldEditException ignored) { @@ -225,8 +220,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { Block existing = chunk.getBlock(x, y, z); final BlockState existingBaseBlock = BukkitAdapter.adapt(existing.getBlockData()); - if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing.getBlockData() - .matches(blockData)) { + if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing.getBlockData().matches(blockData)) { return; } @@ -240,8 +234,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { CompoundTag tag = block.getNbtData(); StateWrapper sw = new StateWrapper(tag); - sw.restoreTag(getWorld().getName(), existing.getX(), existing.getY(), - existing.getZ()); + sw.restoreTag(getWorld().getName(), existing.getX(), existing.getY(), existing.getZ()); } } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java index ddfa03033..195882d81 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java @@ -45,8 +45,10 @@ import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.ChunkGenerator.BiomeGrid; import org.bukkit.generator.ChunkGenerator.ChunkData; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Arrays; public class GenChunk extends ScopedQueueCoordinator { @@ -65,15 +67,15 @@ public class GenChunk extends ScopedQueueCoordinator { this.biomes = Biome.values(); } - public ChunkData getChunkData() { + @Nullable public ChunkData getChunkData() { return this.chunkData; } - public void setChunkData(ChunkData chunkData) { + public void setChunkData(@Nonnull ChunkData chunkData) { this.chunkData = chunkData; } - public Chunk getChunk() { + @Nonnull public Chunk getChunk() { if (chunk == null) { World worldObj = BukkitUtil.getWorld(world); if (worldObj != null) { @@ -83,18 +85,18 @@ public class GenChunk extends ScopedQueueCoordinator { return chunk; } - public void setChunk(Chunk chunk) { + public void setChunk(@Nonnull Chunk chunk) { this.chunk = chunk; } - public void setChunk(ChunkWrapper wrap) { + public void setChunk(@Nonnull ChunkWrapper wrap) { chunk = null; world = wrap.world; chunkX = wrap.x; chunkZ = wrap.z; } - @Override public void fillBiome(BiomeType biomeType) { + @Override public void fillBiome(@Nonnull BiomeType biomeType) { if (biomeGrid == null) { return; } @@ -106,9 +108,8 @@ public class GenChunk extends ScopedQueueCoordinator { } } - @Override public void setCuboid(Location pos1, Location pos2, BlockState block) { - if (result != null && pos1.getX() == 0 && pos1.getZ() == 0 && pos2.getX() == 15 - && pos2.getZ() == 15) { + @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 && pos2.getZ() == 15) { for (int y = pos1.getY(); y <= pos2.getY(); y++) { int layer = y >> 4; BlockState[] data = result[layer]; @@ -126,15 +127,14 @@ public class GenChunk extends ScopedQueueCoordinator { int maxX = Math.max(pos1.getX(), pos2.getX()); int maxY = Math.max(pos1.getY(), pos2.getY()); int maxZ = Math.max(pos1.getZ(), pos2.getZ()); - chunkData - .setRegion(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1, BukkitAdapter.adapt(block)); + chunkData.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)); } - public boolean setBiome(int x, int z, Biome biome) { + public boolean setBiome(int x, int z, @Nonnull Biome biome) { if (this.biomeGrid != null) { this.biomeGrid.setBiome(x, z, biome); return true; @@ -142,12 +142,11 @@ public class GenChunk extends ScopedQueueCoordinator { return false; } - @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { - return setBlock(x, y, z, PatternUtil - .apply(Preconditions.checkNotNull(pattern, "Pattern may not be null"), x, y, z)); + @Override public boolean setBlock(int x, int y, int z, @Nonnull @NotNull Pattern pattern) { + return setBlock(x, y, z, PatternUtil.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) { this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); return true; @@ -157,7 +156,7 @@ public class GenChunk extends ScopedQueueCoordinator { 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; BlockState[] v = this.result[i]; if (v == null) { @@ -167,7 +166,7 @@ public class GenChunk extends ScopedQueueCoordinator { 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) { this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); return true; @@ -177,7 +176,7 @@ public class GenChunk extends ScopedQueueCoordinator { 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; if (result == null) { return BukkitBlockUtil.get(chunkData.getType(x, y, z)); @@ -198,21 +197,19 @@ public class GenChunk extends ScopedQueueCoordinator { return chunk == null ? chunkZ : chunk.getZ(); } - @Override public com.sk89q.worldedit.world.World getWorld() { - return chunk == null ? - BukkitAdapter.adapt(Bukkit.getWorld(world)) : - BukkitAdapter.adapt(chunk.getWorld()); + @Override @Nonnull public com.sk89q.worldedit.world.World getWorld() { + return chunk == null ? 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)); } - @Override public Location getMin() { + @Override @Nonnull public Location getMin() { return Location.at(getWorld().getName(), getX() << 4, 0, getZ() << 4); } - public GenChunk clone() { + @Nonnull public GenChunk clone() { GenChunk toReturn = new GenChunk(); if (this.result != null) { for (int i = 0; i < this.result.length; i++) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java index 4e5bfb49b..8086d805a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java @@ -26,107 +26,23 @@ package com.plotsquared.bukkit.util; 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.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.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; -import com.sk89q.worldedit.world.block.BaseBlock; 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 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 public class BukkitChunkManager extends ChunkManager { public static boolean isIn(CuboidRegion region, int x, int z) { - return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX() - && z >= region.getMinimumPoint().getZ() && z <= region.getMaximumPoint().getZ(); + return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX() && z >= region.getMinimumPoint().getZ() && z <= region + .getMaximumPoint().getZ(); } - public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2, - CuboidRegion r1, CuboidRegion r2) { - 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); + @Override public CompletableFuture loadChunk(String world, BlockVector2 chunkLoc, boolean force) { + return PaperLib.getChunkAtAsync(BukkitUtil.getWorld(world), chunkLoc.getX(), chunkLoc.getZ(), force); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 790b322de..61a215272 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -98,7 +98,6 @@ import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; -import java.util.UUID; import java.util.concurrent.Semaphore; import java.util.function.Consumer; import java.util.function.IntConsumer; @@ -108,8 +107,7 @@ import java.util.stream.Stream; @Singleton public class BukkitUtil extends WorldUtil { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + BukkitUtil.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitUtil.class.getSimpleName()); private final Collection tileEntityTypes = new HashSet<>(); /** @@ -131,9 +129,9 @@ public class BukkitUtil extends WorldUtil { * @return PlotSquared location */ @Nonnull public static Location adapt(@Nonnull final org.bukkit.Location location) { - return Location.at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), - MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), - MathMan.roundInt(location.getZ())); + return Location + .at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), + MathMan.roundInt(location.getZ())); } /** @@ -144,9 +142,9 @@ public class BukkitUtil extends WorldUtil { * @return PlotSquared location */ @Nonnull public static Location adaptComplete(@Nonnull final org.bukkit.Location location) { - return Location.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()); + return Location + .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()); } /** @@ -157,8 +155,7 @@ public class BukkitUtil extends WorldUtil { * @return Bukkit location */ @Nonnull public static org.bukkit.Location adapt(@Nonnull final Location location) { - return new org.bukkit.Location((World) location.getWorld().getPlatformWorld(), - location.getX(), location.getY(), location.getZ()); + return new org.bukkit.Location((World) location.getWorld().getPlatformWorld(), location.getX(), location.getY(), location.getZ()); } /** @@ -171,30 +168,24 @@ public class BukkitUtil extends WorldUtil { return Bukkit.getWorld(string); } - private static void ensureLoaded(@Nonnull final String world, final int x, final int z, - @Nonnull final Consumer chunkConsumer) { + private static void ensureLoaded(@Nonnull final String world, final int x, final int z, @Nonnull final Consumer chunkConsumer) { PaperLib.getChunkAtAsync(Objects.requireNonNull(getWorld(world)), x >> 4, z >> 4, true) .thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); } - private static void ensureLoaded(@Nonnull final Location location, - @Nonnull final Consumer chunkConsumer) { - PaperLib.getChunkAtAsync(adapt(location), true) - .thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); + private static void ensureLoaded(@Nonnull final Location location, @Nonnull final Consumer chunkConsumer) { + PaperLib.getChunkAtAsync(adapt(location), true).thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); } - private static void ensureMainThread(@Nonnull final Consumer consumer, - @Nonnull final T value) { + private static void ensureMainThread(@Nonnull final Consumer consumer, @Nonnull final T value) { if (Bukkit.isPrimaryThread()) { consumer.accept(value); } else { - Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), - () -> consumer.accept(value)); + Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> consumer.accept(value)); } } - @Override public boolean isBlockSame(@Nonnull final BlockState block1, - @Nonnull final BlockState block2) { + @Override public boolean isBlockSame(@Nonnull final BlockState block1, @Nonnull final BlockState block2) { if (block1.equals(block2)) { return true; } @@ -207,19 +198,15 @@ public class BukkitUtil extends WorldUtil { return getWorld(worldName) != null; } - @Override public void getBiome(@Nonnull final String world, final int x, final int z, - @Nonnull final Consumer result) { - ensureLoaded(world, x, z, - chunk -> result.accept(BukkitAdapter.adapt(getWorld(world).getBiome(x, z)))); + @Override public void getBiome(@Nonnull final String world, final int x, final int z, @Nonnull final Consumer result) { + ensureLoaded(world, x, z, chunk -> result.accept(BukkitAdapter.adapt(getWorld(world).getBiome(x, z)))); } - @Override @Nonnull - public BiomeType getBiomeSynchronous(@Nonnull final String world, final int x, final int z) { + @Override @Nonnull public BiomeType getBiomeSynchronous(@Nonnull final String world, final int x, final int 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, - @Nonnull final IntConsumer result) { + @Override public void getHighestBlock(@Nonnull final String world, final int x, final int z, @Nonnull final IntConsumer result) { ensureLoaded(world, x, z, chunk -> { final World bukkitWorld = Objects.requireNonNull(getWorld(world)); // Skip top and bottom block @@ -245,8 +232,7 @@ public class BukkitUtil extends WorldUtil { }); } - @Override @Nonnegative - public int getHighestBlockSynchronous(@Nonnull final String world, final int x, final int z) { + @Override @Nonnegative public int getHighestBlockSynchronous(@Nonnull final String world, final int x, final int z) { final World bukkitWorld = Objects.requireNonNull(getWorld(world)); // Skip top and bottom block int air = 1; @@ -269,8 +255,7 @@ public class BukkitUtil extends WorldUtil { } @Override @Nonnull public String[] getSignSynchronous(@Nonnull final Location location) { - Block block = Objects.requireNonNull(getWorld(location.getWorldName())) - .getBlockAt(location.getX(), location.getY(), location.getZ()); + Block block = Objects.requireNonNull(getWorld(location.getWorldName())).getBlockAt(location.getX(), location.getY(), location.getZ()); try { return TaskManager.getPlatformImplementation().sync(() -> { if (block.getState() instanceof Sign) { @@ -287,9 +272,7 @@ public class BukkitUtil extends WorldUtil { @Override @Nonnull public Location getSpawn(@Nonnull final String world) { final org.bukkit.Location temp = getWorld(world).getSpawnLocation(); - return Location - .at(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), - temp.getPitch()); + return Location.at(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch()); } @Override public void setSpawn(@Nonnull final Location location) { @@ -307,8 +290,7 @@ public class BukkitUtil extends WorldUtil { } @Override @SuppressWarnings("deprecation") - public void setSign(@Nonnull final String worldName, final int x, final int y, final int z, - @Nonnull final String[] lines) { + public void setSign(@Nonnull final String worldName, final int x, final int y, final int z, @Nonnull final String[] lines) { ensureLoaded(worldName, x, z, chunk -> { final World world = getWorld(worldName); final Block block = world.getBlockAt(x, y, z); @@ -346,25 +328,20 @@ public class BukkitUtil extends WorldUtil { }); } - @Override @Nonnull - public StringComparison.ComparisonResult getClosestBlock(@Nonnull String name) { + @Override @Nonnull public StringComparison.ComparisonResult getClosestBlock(@Nonnull String name) { BlockState state = BlockUtil.get(name); return new StringComparison().new ComparisonResult(1, state); } - @Override - public void setBiomes(@Nonnull final String worldName, @Nonnull final CuboidRegion region, - @Nonnull final BiomeType biomeType) { + @Override public void setBiomes(@Nonnull final String worldName, @Nonnull final CuboidRegion region, @Nonnull final BiomeType biomeType) { final World world = getWorld(worldName); if (world == null) { - logger.warn("[P2] An error occured while setting the biome because the world was null", - new RuntimeException()); + logger.warn("[P2] An error occured while setting the biome because the world was null", new RuntimeException()); return; } final Biome biome = BukkitAdapter.adapt(biomeType); for (int x = region.getMinimumPoint().getX(); x <= region.getMaximumPoint().getX(); x++) { - for (int z = region.getMinimumPoint().getZ(); - z <= region.getMaximumPoint().getZ(); z++) { + for (int z = region.getMinimumPoint().getZ(); z <= region.getMaximumPoint().getZ(); z++) { if (world.getBiome(x, z) != biome) { world.setBiome(x, z, biome); } @@ -372,8 +349,7 @@ public class BukkitUtil extends WorldUtil { } } - @Override @Nonnull - public com.sk89q.worldedit.world.World getWeWorld(@Nonnull final String world) { + @Override @Nonnull public com.sk89q.worldedit.world.World getWeWorld(@Nonnull final String world) { return new BukkitWorld(Bukkit.getWorld(world)); } @@ -381,21 +357,17 @@ public class BukkitUtil extends WorldUtil { Bukkit.getWorld(world).refreshChunk(x, z); } - @Override public void getBlock(@Nonnull final Location location, - @Nonnull final Consumer result) { + @Override public void getBlock(@Nonnull final Location location, @Nonnull final Consumer result) { ensureLoaded(location, chunk -> { final World world = getWorld(location.getWorldName()); - final Block block = Objects.requireNonNull(world) - .getBlockAt(location.getX(), location.getY(), location.getZ()); - result.accept(Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())) - .getDefaultState()); + final Block block = Objects.requireNonNull(world).getBlockAt(location.getX(), location.getY(), location.getZ()); + result.accept(Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())).getDefaultState()); }); } @Override @Nonnull public BlockState getBlockSynchronous(@Nonnull final Location location) { final World world = getWorld(location.getWorldName()); - final Block block = Objects.requireNonNull(world) - .getBlockAt(location.getX(), location.getY(), location.getZ()); + final Block block = Objects.requireNonNull(world).getBlockAt(location.getX(), location.getY(), location.getZ()); 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(); } - @Override - public void setHealth(@Nonnull final PlotPlayer player, @Nonnegative final double health) { + @Override public void setHealth(@Nonnull final PlotPlayer player, @Nonnegative final double health) { Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).setHealth(health); } - @Override public void setFoodLevel(@Nonnull final PlotPlayer player, - @Nonnegative final int foodLevel) { + @Override public void setFoodLevel(@Nonnull final PlotPlayer player, @Nonnegative final int foodLevel) { Bukkit.getPlayer(player.getUUID()).setFoodLevel(foodLevel); } - @Override @Nonnull public Set getTypesInCategory( - @Nonnull final String category) { + @Override @Nonnull public Set getTypesInCategory(@Nonnull final String category) { final Collection> allowedInterfaces = new HashSet<>(); switch (category) { case "animal": { @@ -507,22 +476,17 @@ public class BukkitUtil extends WorldUtil { tileEntityTypes.addAll(BlockCategories.FLOWER_POTS.getAll()); // Individual Types // Add these from strings - Stream.of("barrel", "beacon", "beehive", "bee_nest", "bell", "blast_furnace", - "brewing_stand", "campfire", "chest", "ender_chest", "trapped_chest", - "command_block", "end_gateway", "hopper", "jigsaw", "jubekox", "lectern", - "note_block", "black_shulker_box", "blue_shulker_box", "brown_shulker_box", - "cyan_shulker_box", "gray_shulker_box", "green_shulker_box", - "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") + Stream.of("barrel", "beacon", "beehive", "bee_nest", "bell", "blast_furnace", "brewing_stand", "campfire", "chest", "ender_chest", + "trapped_chest", "command_block", "end_gateway", "hopper", "jigsaw", "jubekox", "lectern", "note_block", "black_shulker_box", + "blue_shulker_box", "brown_shulker_box", "cyan_shulker_box", "gray_shulker_box", "green_shulker_box", "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); } return this.tileEntityTypes; } - @Override @Nonnegative - public int getTileEntityCount(@Nonnull final String world, @Nonnull final BlockVector2 chunk) { + @Override @Nonnegative public int getTileEntityCount(@Nonnull final String world, @Nonnull final BlockVector2 chunk) { return Objects.requireNonNull(getWorld(world)). getChunkAt(chunk.getBlockX(), chunk.getBlockZ()).getTileEntities().length; } @@ -538,16 +502,13 @@ public class BukkitUtil extends WorldUtil { final Semaphore semaphore = new Semaphore(1); try { semaphore.acquire(); - Bukkit.getScheduler() - .runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> { - for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)) - .getLoadedChunks()) { - BlockVector2 loc = - BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5); - chunks.add(loc); - } - semaphore.release(); - }); + Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> { + for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)).getLoadedChunks()) { + BlockVector2 loc = BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5); + chunks.add(loc); + } + semaphore.release(); + }); semaphore.acquireUninterruptibly(); } catch (final Exception e) { e.printStackTrace(); diff --git a/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java b/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java index 9c620c148..3d5e9897e 100644 --- a/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java +++ b/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java @@ -62,20 +62,17 @@ import java.util.stream.Collectors; public class ComponentPresetManager { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + ComponentPresetManager.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + ComponentPresetManager.class.getSimpleName()); private final List presets; private final String guiName; private final EconHandler econHandler; private final InventoryUtil inventoryUtil; - @Inject public ComponentPresetManager(@Nullable final EconHandler econHandler, - @Nonnull final InventoryUtil inventoryUtil) { + @Inject public ComponentPresetManager(@Nullable final EconHandler econHandler, @Nonnull final InventoryUtil inventoryUtil) { this.econHandler = econHandler; this.inventoryUtil = inventoryUtil; - final File file = new File(Objects.requireNonNull(PlotSquared.platform()).getDirectory(), - "components.yml"); + final File file = new File(Objects.requireNonNull(PlotSquared.platform()).getDirectory(), "components.yml"); if (!file.exists()) { boolean created = false; try { @@ -106,16 +103,13 @@ public class ComponentPresetManager { this.guiName = yamlConfiguration.getString("title", "&6Plot Components"); if (yamlConfiguration.contains("presets")) { - this.presets = - yamlConfiguration.getMapList("presets").stream().map(o -> (Map) o) - .map(ComponentPreset::deserialize).collect(Collectors.toList()); + this.presets = yamlConfiguration.getMapList("presets").stream().map(o -> (Map) o).map(ComponentPreset::deserialize) + .collect(Collectors.toList()); } else { final List defaultPreset = Collections.singletonList( - new ComponentPreset(ClassicPlotManagerComponent.FLOOR, "##wool", 0, "", - "&6D&ai&cs&ec&bo &2F&3l&do&9o&4r", Arrays.asList("&6Spice up your plot floor"), - ItemTypes.YELLOW_WOOL)); - yamlConfiguration.set("presets", defaultPreset.stream().map(ComponentPreset::serialize) - .collect(Collectors.toList())); + new ComponentPreset(ClassicPlotManagerComponent.FLOOR, "##wool", 0, "", "&6D&ai&cs&ec&bo &2F&3l&do&9o&4r", + Arrays.asList("&6Spice up your plot floor"), ItemTypes.YELLOW_WOOL)); + yamlConfiguration.set("presets", defaultPreset.stream().map(ComponentPreset::serialize).collect(Collectors.toList())); try { yamlConfiguration.save(file); } catch (final IOException e) { @@ -143,93 +137,84 @@ public class ComponentPresetManager { } else if (!plot.hasOwner()) { Captions.PLOT_UNOWNED.send(player); return null; - } else if (!plot.isOwner(player.getUUID()) && !plot.getTrusted() - .contains(player.getUUID())) { + } else if (!plot.isOwner(player.getUUID()) && !plot.getTrusted().contains(player.getUUID())) { Captions.NO_PLOT_PERMS.send(player); return null; } final List allowedPresets = new ArrayList<>(this.presets.size()); for (final ComponentPreset componentPreset : this.presets) { - if (!componentPreset.getPermission().isEmpty() && !Permissions - .hasPermission(player, componentPreset.getPermission())) { + if (!componentPreset.getPermission().isEmpty() && !Permissions.hasPermission(player, componentPreset.getPermission())) { continue; } allowedPresets.add(componentPreset); } final int size = (int) Math.ceil((double) allowedPresets.size() / 9.0D); - final PlotInventory plotInventory = - new PlotInventory(this.inventoryUtil, player, size, this.guiName) { - @Override public boolean onClick(final int index) { - if (!player.getCurrentPlot().equals(plot)) { - return false; - } - - if (index < 0 || index >= allowedPresets.size()) { - return false; - } - - final ComponentPreset componentPreset = allowedPresets.get(index); - if (componentPreset == null) { - return false; - } - - if (plot.getRunning() > 0) { - Captions.WAIT_FOR_TIMER.send(player); - return false; - } - - final Pattern pattern = - PatternUtil.parse(null, componentPreset.getPattern(), false); - if (pattern == null) { - Captions.PRESET_INVALID.send(player); - return false; - } - - if (componentPreset.getCost() > 0.0D && econHandler != null && plot.getArea() - .useEconomy()) { - if (econHandler.getMoney(player) < componentPreset.getCost()) { - Captions.PRESET_CANNOT_AFFORD.send(player); - return false; - } else { - econHandler.withdrawMoney(player, componentPreset.getCost()); - Captions.REMOVED_BALANCE.send(player, componentPreset.getCost() + ""); - } - } - - BackupManager.backup(player, plot, () -> { - plot.addRunning(); - QueueCoordinator queue = plot.getArea().getQueue(); - for (Plot current : plot.getConnectedPlots()) { - current.setComponent(componentPreset.getComponent().name(), pattern, - queue); - } - queue.setCompleteTask(plot::removeRunning); - queue.enqueue(); - MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); - }); + final PlotInventory plotInventory = new PlotInventory(this.inventoryUtil, player, size, this.guiName) { + @Override public boolean onClick(final int index) { + if (!player.getCurrentPlot().equals(plot)) { return false; } - }; + + if (index < 0 || index >= allowedPresets.size()) { + return false; + } + + final ComponentPreset componentPreset = allowedPresets.get(index); + if (componentPreset == null) { + return false; + } + + if (plot.getRunning() > 0) { + Captions.WAIT_FOR_TIMER.send(player); + return false; + } + + final Pattern pattern = PatternUtil.parse(null, componentPreset.getPattern(), false); + if (pattern == null) { + Captions.PRESET_INVALID.send(player); + return false; + } + + if (componentPreset.getCost() > 0.0D && econHandler != null && plot.getArea().useEconomy()) { + if (econHandler.getMoney(player) < componentPreset.getCost()) { + Captions.PRESET_CANNOT_AFFORD.send(player); + return false; + } else { + econHandler.withdrawMoney(player, componentPreset.getCost()); + Captions.REMOVED_BALANCE.send(player, componentPreset.getCost() + ""); + } + } + + BackupManager.backup(player, plot, () -> { + plot.addRunning(); + QueueCoordinator queue = plot.getArea().getQueue(); + for (Plot current : plot.getConnectedPlots()) { + current.setComponent(componentPreset.getComponent().name(), pattern, queue); + } + queue.setCompleteTask(plot::removeRunning); + queue.enqueue(); + MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); + }); + return false; + } + }; for (int i = 0; i < allowedPresets.size(); i++) { final ComponentPreset preset = allowedPresets.get(i); final List lore = new ArrayList<>(); if (preset.getCost() > 0 && this.econHandler != null && plot.getArea().useEconomy()) { - lore.add(Captions.PRESET_LORE_COST.getTranslated() - .replace("%cost%", String.format("%.2f", preset.getCost()))); + lore.add(Captions.PRESET_LORE_COST.getTranslated().replace("%cost%", String.format("%.2f", preset.getCost()))); } - lore.add(Captions.PRESET_LORE_COMPONENT.getTranslated() - .replace("%component%", preset.getComponent().name().toLowerCase())); + lore.add(Captions.PRESET_LORE_COMPONENT.getTranslated().replace("%component%", preset.getComponent().name().toLowerCase())); lore.removeIf(String::isEmpty); if (!lore.isEmpty()) { lore.add("&6"); } lore.addAll(preset.getDescription()); plotInventory.setItem(i, - new PlotItemStack(preset.getIcon().getId().replace("minecraft:", ""), 1, - preset.getDisplayName(), lore.toArray(new String[0]))); + new PlotItemStack(preset.getIcon().getId().replace("minecraft:", ""), 1, preset.getDisplayName(), lore.toArray(new String[0]))); } return plotInventory; diff --git a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java index 8c797ba45..f888f9bd9 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java @@ -54,8 +54,11 @@ public class AugmentedUtils { enabled = true; } - public static boolean generate(@Nullable Object chunkObject, @Nonnull final String world, - final int chunkX, final int chunkZ, QueueCoordinator queue) { + public static boolean generate(@Nullable Object chunkObject, + @Nonnull final String world, + final int chunkX, + final int chunkZ, + QueueCoordinator queue) { if (!enabled) { return false; } @@ -67,8 +70,7 @@ public class AugmentedUtils { // entire chunk CuboidRegion region = RegionUtil.createRegion(blockX, blockX + 15, blockZ, blockZ + 15); // Query for plot areas in the chunk - final Set areas = - PlotSquared.get().getPlotAreaManager().getPlotAreasSet(world, region); + final Set areas = PlotSquared.get().getPlotAreaManager().getPlotAreasSet(world, region); if (areas.isEmpty()) { return false; } @@ -89,8 +91,7 @@ public class AugmentedUtils { // Mask if (queue == null) { enqueue = true; - queue = PlotSquared.platform().getGlobalBlockQueue() - .getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); + queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); if (chunkObject != null) { queue.setChunkObject(chunkObject); } @@ -138,8 +139,7 @@ public class AugmentedUtils { continue; } generationResult = true; - secondaryMask = new LocationOffsetDelegateQueueCoordinator(canPlace, blockX, blockZ, - primaryMask); + secondaryMask = new LocationOffsetDelegateQueueCoordinator(canPlace, blockX, blockZ, primaryMask); } else { secondaryMask = primaryMask; for (int x = relativeBottomX; x <= relativeTopX; x++) { @@ -159,8 +159,7 @@ public class AugmentedUtils { } ScopedQueueCoordinator scoped = - new ScopedQueueCoordinator(secondaryMask, Location.at(world, blockX, 0, blockZ), - Location.at(world, blockX + 15, 255, blockZ + 15)); + new ScopedQueueCoordinator(secondaryMask, Location.at(world, blockX, 0, blockZ), Location.at(world, blockX + 15, 255, blockZ + 15)); generator.generateChunk(scoped, area); generator.populateChunk(scoped, area); } diff --git a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java index c1de3c0c5..7c2263954 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java @@ -40,6 +40,7 @@ import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.block.BlockTypes; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -54,17 +55,15 @@ public class ClassicPlotManager extends SquarePlotManager { private final ClassicPlotWorld classicPlotWorld; private final RegionManager regionManager; - public ClassicPlotManager(@Nonnull final ClassicPlotWorld classicPlotWorld, - @Nonnull final RegionManager regionManager) { + public ClassicPlotManager(@Nonnull final ClassicPlotWorld classicPlotWorld, @Nonnull final RegionManager regionManager) { super(classicPlotWorld, regionManager); this.classicPlotWorld = classicPlotWorld; this.regionManager = regionManager; } - @Override public boolean setComponent(PlotId plotId, String component, Pattern blocks, - @Nullable QueueCoordinator queue) { - final Optional componentOptional = - ClassicPlotManagerComponent.fromString(component); + @Override + public boolean setComponent(@NotNull PlotId plotId, @NotNull String component, @NotNull Pattern blocks, @Nullable QueueCoordinator queue) { + final Optional componentOptional = ClassicPlotManagerComponent.fromString(component); if (componentOptional.isPresent()) { switch (componentOptional.get()) { case FLOOR: @@ -88,55 +87,50 @@ public class ClassicPlotManager extends SquarePlotManager { return false; } - @Override public boolean unClaimPlot(Plot plot, @Nullable Runnable whenDone, - @Nullable QueueCoordinator queue) { + @Override public boolean unClaimPlot(@NotNull Plot plot, @Nullable Runnable whenDone, @Nullable QueueCoordinator queue) { setWallFilling(plot.getId(), classicPlotWorld.WALL_FILLING.toPattern(), queue); - if (!classicPlotWorld.WALL_BLOCK.isAir() || !classicPlotWorld.WALL_BLOCK - .equals(classicPlotWorld.CLAIMED_WALL_BLOCK)) { + if (!classicPlotWorld.WALL_BLOCK.isAir() || !classicPlotWorld.WALL_BLOCK.equals(classicPlotWorld.CLAIMED_WALL_BLOCK)) { setWall(plot.getId(), classicPlotWorld.WALL_BLOCK.toPattern(), queue); } TaskManager.runTask(whenDone); return true; } - public boolean setFloor(PlotId plotId, 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) { + 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, 1, getWorldHeight(), - queue); + .setCuboids(classicPlotWorld, plot.getRegions(), blocks, classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.PLOT_HEIGHT, queue); } 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); if (plot != null && plot.isBasePlot()) { - return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, - classicPlotWorld.PLOT_HEIGHT + 1, getWorldHeight(), queue); + return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, getWorldHeight(), queue); } 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); if (plot == null || plot.isBasePlot()) { - return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, - classicPlotWorld.PLOT_HEIGHT - 1, queue); + return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, classicPlotWorld.PLOT_HEIGHT - 1, queue); } 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); if (plot == null || !plot.isBasePlot()) { return false; @@ -155,7 +149,7 @@ public class ClassicPlotManager extends SquarePlotManager { 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) { return false; } @@ -214,19 +208,15 @@ public class ClassicPlotManager extends SquarePlotManager { } if (plot.isBasePlot()) { for (CuboidRegion region : plot.getRegions()) { - Location pos1 = Location - .at(classicPlotWorld.getWorldName(), region.getMinimumPoint().getX(), maxY, - region.getMinimumPoint().getZ()); - Location pos2 = Location - .at(classicPlotWorld.getWorldName(), region.getMaximumPoint().getX(), maxY, - region.getMaximumPoint().getZ()); + Location pos1 = Location.at(classicPlotWorld.getWorldName(), region.getMinimumPoint().getX(), maxY, region.getMinimumPoint().getZ()); + Location pos2 = Location.at(classicPlotWorld.getWorldName(), region.getMaximumPoint().getX(), maxY, region.getMaximumPoint().getZ()); queue.setCuboid(pos1, pos2, blocks); } } 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) { return false; } @@ -240,9 +230,7 @@ public class ClassicPlotManager extends SquarePlotManager { if (plot == null) { return false; } - Location bot = plot.getExtendedBottomAbs() - .subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, - plot.getMerged(Direction.NORTH) ? 0 : 1); + Location bot = plot.getExtendedBottomAbs().subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1); boolean enqueue = false; @@ -269,8 +257,7 @@ public class ClassicPlotManager extends SquarePlotManager { } if (!plot.getMerged(Direction.SOUTH)) { int z = top.getZ(); - for (int x = bot.getX(); - x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) { + for (int x = bot.getX(); x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) { for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) { queue.setBlock(x, y, z, blocks); } @@ -278,8 +265,7 @@ public class ClassicPlotManager extends SquarePlotManager { } if (!plot.getMerged(Direction.EAST)) { int x = top.getX(); - for (int z = bot.getZ(); - z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) { + for (int z = bot.getZ(); z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) { for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) { queue.setBlock(x, y, z, blocks); } @@ -288,7 +274,7 @@ public class ClassicPlotManager extends SquarePlotManager { 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) { return false; } @@ -302,9 +288,7 @@ public class ClassicPlotManager extends SquarePlotManager { if (plot == null) { return false; } - Location bot = plot.getExtendedBottomAbs() - .subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, - plot.getMerged(Direction.NORTH) ? 0 : 1); + Location bot = plot.getExtendedBottomAbs().subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1); boolean enqueue = false; @@ -328,15 +312,13 @@ public class ClassicPlotManager extends SquarePlotManager { } if (!plot.getMerged(Direction.SOUTH)) { int z = top.getZ(); - for (int x = bot.getX(); - x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) { + for (int x = bot.getX(); x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) { queue.setBlock(x, y, z, blocks); } } if (!plot.getMerged(Direction.EAST)) { int x = top.getX(); - for (int z = bot.getZ(); - z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) { + for (int z = bot.getZ(); z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) { queue.setBlock(x, y, z, blocks); } } @@ -346,7 +328,7 @@ public class ClassicPlotManager extends SquarePlotManager { /** * 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 pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; @@ -361,36 +343,25 @@ public class ClassicPlotManager extends SquarePlotManager { } int maxY = getWorldHeight(); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex, maxY, ez - 1), - 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, Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex, maxY, ez - 1), BlockTypes.AIR.getDefaultState()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 0, sz + 1), Location.at(classicPlotWorld.getWorldName(), ex, 0, ez - 1), BlockUtil.get((short) 7, (byte) 0)); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1), - Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT, ez - 1), - classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid(Location - .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()); + Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(Location.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), - Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT, ez - 1), - classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid(Location - .at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, sz + 1), - Location - .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()); + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, sz + 1), + Location.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(); } - @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 pos2 = getPlotTopLocAbs(plot.getId()); int sz = pos2.getZ() + 1; @@ -404,37 +375,26 @@ public class ClassicPlotManager extends SquarePlotManager { enqueue = true; } - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, - Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location - .at(classicPlotWorld.getWorldName(), ex - 1, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), + queue.setCuboid( + Location.at(classicPlotWorld.getWorldName(), sx + 1, Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.getPlotManager().getWorldHeight(), ez), BlockTypes.AIR.getDefaultState()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz), - Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez), + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz), Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez), BlockUtil.get((short) 7, (byte) 0)); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, sz), - classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid(Location - .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()); + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, sz), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(Location.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), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, ez), - classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid(Location - .at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, ez), - Location - .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()); + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, ez), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, ez), + Location.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(); } - @Override public boolean createRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { + @Override public boolean createRoadSouthEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) { Location pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; @@ -447,21 +407,17 @@ public class ClassicPlotManager extends SquarePlotManager { enqueue = true; } - queue.setCuboid(Location - .at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.ROAD_HEIGHT + 1, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex - 1, - classicPlotWorld.getPlotManager().getWorldHeight(), ez - 1), + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.ROAD_HEIGHT + 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.getPlotManager().getWorldHeight(), ez - 1), BlockTypes.AIR.getDefaultState()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez - 1), - BlockUtil.get((short) 7, (byte) 0)); - 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()); + Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez - 1), BlockUtil.get((short) 7, (byte) 0)); + 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(); } - @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 pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; @@ -475,22 +431,18 @@ public class ClassicPlotManager extends SquarePlotManager { enqueue = true; } - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location - .at(classicPlotWorld.getWorldName(), ex, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), - BlockTypes.AIR.getDefaultState()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1), Location - .at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez - 1), - classicPlotWorld.MAIN_BLOCK.toPattern()); - queue.setCuboid( - Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez - 1), - classicPlotWorld.TOP_BLOCK.toPattern()); + queue + .setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez), + BlockTypes.AIR.getDefaultState()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez - 1), classicPlotWorld.MAIN_BLOCK.toPattern()); + queue.setCuboid(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(); } - @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 pos2 = getPlotTopLocAbs(plot.getId()); int sz = pos2.getZ() + 1; @@ -504,22 +456,18 @@ public class ClassicPlotManager extends SquarePlotManager { enqueue = true; } - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location - .at(classicPlotWorld.getWorldName(), ex, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), - BlockTypes.AIR.getDefaultState()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz), Location - .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT - 1, ez), - classicPlotWorld.MAIN_BLOCK.toPattern()); - queue.setCuboid( - Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.PLOT_HEIGHT, sz), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT, ez), - classicPlotWorld.TOP_BLOCK.toPattern()); + queue + .setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez), + BlockTypes.AIR.getDefaultState()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT - 1, ez), classicPlotWorld.MAIN_BLOCK.toPattern()); + queue.setCuboid(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(); } - @Override public boolean removeRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { + @Override public boolean removeRoadSouthEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) { Location location = getPlotTopLocAbs(plot.getId()); int sx = location.getX() + 1; int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; @@ -532,18 +480,14 @@ public class ClassicPlotManager extends SquarePlotManager { enqueue = true; } - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location - .at(classicPlotWorld.getWorldName(), ex, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), - BlockTypes.AIR.getDefaultState()); + queue + .setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez), + BlockTypes.AIR.getDefaultState()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz), - Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez), - classicPlotWorld.MAIN_BLOCK.toPattern()); - queue.setCuboid( - Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz), - Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez), - classicPlotWorld.TOP_BLOCK.toPattern()); + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez), classicPlotWorld.MAIN_BLOCK.toPattern()); + queue.setCuboid(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(); } @@ -552,8 +496,7 @@ public class ClassicPlotManager extends SquarePlotManager { * * @return false if part of the merge failed, otherwise true if successful. */ - @Override public boolean finishPlotMerge(List plotIds, - @Nullable QueueCoordinator queue) { + @Override public boolean finishPlotMerge(@NotNull List plotIds, @Nullable QueueCoordinator queue) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { for (PlotId plotId : plotIds) { @@ -569,8 +512,7 @@ public class ClassicPlotManager extends SquarePlotManager { return true; } - @Override - public boolean finishPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean finishPlotUnlink(@NotNull List plotIds, @Nullable QueueCoordinator queue) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { for (PlotId id : plotIds) { @@ -580,17 +522,15 @@ public class ClassicPlotManager extends SquarePlotManager { return true; // return false if unlink has been denied } - @Override - public boolean startPlotMerge(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean startPlotMerge(@NotNull List plotIds, @Nullable QueueCoordinator queue) { return true; } - @Override - public boolean startPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean startPlotUnlink(@NotNull List plotIds, @Nullable QueueCoordinator queue) { 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; if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { return setWall(plot.getId(), claim.toPattern(), queue); @@ -598,7 +538,7 @@ public class ClassicPlotManager extends SquarePlotManager { return true; } - @Override public String[] getPlotComponents(PlotId plotId) { + @Override public String[] getPlotComponents(@NotNull PlotId plotId) { return ClassicPlotManagerComponent.stringValues(); } @@ -608,12 +548,10 @@ public class ClassicPlotManager extends SquarePlotManager { * @param plot The plot * @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); final Location bot = plot.getBottomAbs(); - return Location - .at(classicPlotWorld.getWorldName(), bot.getX() - 1, classicPlotWorld.ROAD_HEIGHT + 1, - bot.getZ() - 2); + return Location.at(classicPlotWorld.getWorldName(), bot.getX() - 1, classicPlotWorld.ROAD_HEIGHT + 1, bot.getZ() - 2); } } diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java index 55b6091f5..64acf40ad 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java @@ -47,8 +47,10 @@ import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockTypes; import lombok.Getter; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -62,37 +64,26 @@ public class HybridPlotManager extends ClassicPlotManager { @Getter private final HybridPlotWorld hybridPlotWorld; private final RegionManager regionManager; - public HybridPlotManager(@Nonnull final HybridPlotWorld hybridPlotWorld, - @Nonnull final RegionManager regionManager) { + public HybridPlotManager(@Nonnull final HybridPlotWorld hybridPlotWorld, @Nonnull final RegionManager regionManager) { super(hybridPlotWorld, regionManager); this.hybridPlotWorld = hybridPlotWorld; this.regionManager = regionManager; } @Override public void exportTemplate() throws IOException { - HashSet files = Sets.newHashSet( - new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", - Template.getBytes(hybridPlotWorld))); - String dir = - "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + hybridPlotWorld - .getWorldName() + File.separator; + HashSet files = Sets.newHashSet(new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", Template.getBytes(hybridPlotWorld))); + String dir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + hybridPlotWorld.getWorldName() + File.separator; try { - File sideRoad = - FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "sideroad.schem"); - String newDir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator - + "__TEMP_DIR__" + File.separator; + File sideRoad = FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "sideroad.schem"); + String newDir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + "__TEMP_DIR__" + File.separator; if (sideRoad.exists()) { - files.add(new FileBytes(newDir + "sideroad.schem", - Files.readAllBytes(sideRoad.toPath()))); + files.add(new FileBytes(newDir + "sideroad.schem", Files.readAllBytes(sideRoad.toPath()))); } - File intersection = FileUtils - .getFile(PlotSquared.platform().getDirectory(), dir + "intersection.schem"); + File intersection = FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "intersection.schem"); if (intersection.exists()) { - files.add(new FileBytes(newDir + "intersection.schem", - Files.readAllBytes(intersection.toPath()))); + files.add(new FileBytes(newDir + "intersection.schem", Files.readAllBytes(intersection.toPath()))); } - File plot = - FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "plot.schem"); + File plot = FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "plot.schem"); if (plot.exists()) { 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); } - @Override public boolean createRoadEast(Plot plot) { + @Override public boolean createRoadEast(@Nonnull final Plot plot) { super.createRoadEast(plot); PlotId id = plot.getId(); PlotId id2 = PlotId.of(id.getX() + 1, id.getY()); Location bot = getPlotBottomLocAbs(id2); Location top = getPlotTopLocAbs(id); - Location pos1 = - 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 pos1 = 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); this.resetBiome(hybridPlotWorld, pos1, pos2); if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; @@ -123,24 +111,18 @@ public class HybridPlotManager extends ClassicPlotManager { return true; } - private void resetBiome(@Nonnull final HybridPlotWorld hybridPlotWorld, - @Nonnull final Location pos1, @Nonnull final Location pos2) { + private void resetBiome(@Nonnull final HybridPlotWorld hybridPlotWorld, @Nonnull final Location pos1, @Nonnull final Location pos2) { BiomeType biome = hybridPlotWorld.getPlotBiome(); if (!Objects.equals(PlotSquared.platform().getWorldUtil() - .getBiomeSynchronous(hybridPlotWorld.getWorldName(), (pos1.getX() + pos2.getX()) / 2, - (pos1.getZ() + pos2.getZ()) / 2), biome)) { - WorldUtil - .setBiome(hybridPlotWorld.getWorldName(), pos1.getX(), pos1.getZ(), pos2.getX(), - pos2.getZ(), biome); + .getBiomeSynchronous(hybridPlotWorld.getWorldName(), (pos1.getX() + pos2.getX()) / 2, (pos1.getZ() + pos2.getZ()) / 2), biome)) { + WorldUtil.setBiome(hybridPlotWorld.getWorldName(), pos1.getX(), pos1.getZ(), pos2.getX(), pos2.getZ(), biome); } } - private void createSchemAbs(QueueCoordinator queue, Location pos1, Location pos2, - boolean isRoad) { + private void createSchemAbs(@Nonnull final QueueCoordinator queue, @Nonnull final Location pos1, @Nonnull final Location pos2, boolean isRoad) { int size = hybridPlotWorld.SIZE; int minY; - if ((isRoad && Settings.Schematics.PASTE_ROAD_ON_TOP) || (!isRoad - && Settings.Schematics.PASTE_ON_TOP)) { + if ((isRoad && Settings.Schematics.PASTE_ROAD_ON_TOP) || (!isRoad && Settings.Schematics.PASTE_ON_TOP)) { minY = hybridPlotWorld.SCHEM_Y; } else { 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); PlotId id = plot.getId(); PlotId id2 = PlotId.of(id.getX(), id.getY() + 1); Location bot = getPlotBottomLocAbs(id2); Location top = getPlotTopLocAbs(id); - Location pos1 = - 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 pos1 = 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()); this.resetBiome(hybridPlotWorld, pos1, pos2); if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; @@ -198,7 +177,7 @@ public class HybridPlotManager extends ClassicPlotManager { return true; } - @Override public boolean createRoadSouthEast(Plot plot) { + @Override public boolean createRoadSouthEast(@Nonnull final Plot plot) { super.createRoadSouthEast(plot); PlotId id = plot.getId(); 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. *

*/ - @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 returns false, the clear didn't work if (this.regionManager.handleClear(plot, whenDone, this)) { @@ -231,8 +210,7 @@ public class HybridPlotManager extends ClassicPlotManager { final Location pos2 = plot.getExtendedTopAbs(); // If augmented final boolean canRegen = - (hybridPlotWorld.getType() == PlotAreaType.AUGMENTED) && (hybridPlotWorld.getTerrain() - != PlotAreaTerrainType.NONE) && REGENERATIVE_CLEAR; + (hybridPlotWorld.getType() == PlotAreaType.AUGMENTED) && (hybridPlotWorld.getTerrain() != PlotAreaTerrainType.NONE) && REGENERATIVE_CLEAR; // The component blocks final Pattern plotfloor = hybridPlotWorld.TOP_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); // Each component has a different layer queue.setCuboid(pos1.withY(1), pos2.withY(hybridPlotWorld.PLOT_HEIGHT - 1), filling); - queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT), - 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), pos2.withY(hybridPlotWorld.PLOT_HEIGHT), plotfloor); + queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT + 1), pos2.withY(getWorldHeight()), air); queue.setBiomeCuboid(pos1, pos2, biome); } else { queue.setRegenRegion(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3())); @@ -264,7 +240,7 @@ public class HybridPlotManager extends ClassicPlotManager { 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) { return; } @@ -277,7 +253,7 @@ public class HybridPlotManager extends ClassicPlotManager { * @param plot The plot * @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); } } diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java index b89838836..1a878f290 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java @@ -41,7 +41,6 @@ import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.FileUtils; import com.plotsquared.core.util.MathMan; -import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.SchematicHandler; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTagBuilder; @@ -124,11 +123,9 @@ public class HybridPlotWorld extends ClassicPlotWorld { Direction direction = MCDirections.fromRotation(rot); if (direction != null) { - Vector3 vector = transform.apply(direction.toVector()) - .subtract(transform.apply(Vector3.ZERO)).normalize(); - Direction newDirection = Direction.findClosest(vector, - Direction.Flag.CARDINAL | Direction.Flag.ORDINAL - | Direction.Flag.SECONDARY_ORDINAL); + Vector3 vector = transform.apply(direction.toVector()).subtract(transform.apply(Vector3.ZERO)).normalize(); + Direction newDirection = + Direction.findClosest(vector, Direction.Flag.CARDINAL | Direction.Flag.ORDINAL | Direction.Flag.SECONDARY_ORDINAL); if (newDirection != null) { 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 // directories - if (!(root = FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" + - this.getWorldName() + "/" + this.getId())).exists()) { - root = FileUtils.getFile(PlotSquared.platform().getDirectory(), - "schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName()); + if (!(root = + FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName() + "/" + this.getId())) + .exists()) { + root = FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName()); } File schematic1File = new File(root, "sideroad.schem"); - if (!schematic1File.exists()) + if (!schematic1File.exists()) { schematic1File = new File(root, "sideroad.schematic"); + } File schematic2File = new File(root, "intersection.schem"); - if (!schematic2File.exists()) + if (!schematic2File.exists()) { schematic2File = new File(root, "intersection.schematic"); + } File schematic3File = new File(root, "plot.schem"); - if (!schematic3File.exists()) + if (!schematic3File.exists()) { schematic3File = new File(root, "plot.schematic"); + } Schematic schematic1 = this.schematicHandler.getSchematic(schematic1File); Schematic schematic2 = this.schematicHandler.getSchematic(schematic2File); Schematic schematic3 = this.schematicHandler.getSchematic(schematic3File); @@ -282,18 +282,15 @@ public class HybridPlotWorld extends ClassicPlotWorld { for (short x = 0; x < w3; x++) { for (short z = 0; z < l3; z++) { for (short y = 0; y < h3; y++) { - BaseBlock id = blockArrayClipboard3.getFullBlock(BlockVector3 - .at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); + BaseBlock id = + blockArrayClipboard3.getFullBlock(BlockVector3.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); if (!id.getBlockType().getMaterial().isAir()) { - addOverlayBlock((short) (x + shift + oddshift + centerShiftX), - (short) (y + plotY), (short) (z + shift + oddshift + centerShiftZ), - id, false, h3); + addOverlayBlock((short) (x + shift + oddshift + centerShiftX), (short) (y + plotY), + (short) (z + shift + oddshift + centerShiftZ), id, false, h3); } } - BiomeType biome = blockArrayClipboard3 - .getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); - addOverlayBiome((short) (x + shift + oddshift + centerShiftX), - (short) (z + shift + oddshift + centerShiftZ), biome); + BiomeType biome = blockArrayClipboard3.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); + 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 z = 0; z < l1; z++) { for (short y = 0; y < h1; y++) { - BaseBlock id = blockArrayClipboard1.getFullBlock(BlockVector3 - .at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); + BaseBlock id = blockArrayClipboard1.getFullBlock(BlockVector3.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); if (!id.getBlockType().getMaterial().isAir()) { - addOverlayBlock((short) (x - shift), (short) (y + roadY), - (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) (x - shift), (short) (y + roadY), (short) (z + shift + oddshift), id, false, h1); + addOverlayBlock((short) (z + shift + oddshift), (short) (y + roadY), (short) (shift - x + (oddshift - 1)), id, true, h1); } } - BiomeType biome = blockArrayClipboard1 - .getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); + BiomeType biome = blockArrayClipboard1.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); addOverlayBiome((short) (x - shift), (short) (z + shift + oddshift), biome); - addOverlayBiome((short) (z + shift + oddshift), - (short) (shift - x + (oddshift - 1)), biome); + addOverlayBiome((short) (z + shift + oddshift), (short) (shift - x + (oddshift - 1)), biome); } } @@ -348,22 +340,18 @@ public class HybridPlotWorld extends ClassicPlotWorld { for (short x = 0; x < w2; x++) { for (short z = 0; z < l2; z++) { for (short y = 0; y < h2; y++) { - BaseBlock id = blockArrayClipboard2.getFullBlock(BlockVector3 - .at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); + BaseBlock id = blockArrayClipboard2.getFullBlock(BlockVector3.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); if (!id.getBlockType().getMaterial().isAir()) { - addOverlayBlock((short) (x - shift), (short) (y + roadY), - (short) (z - shift), id, false, h2); + addOverlayBlock((short) (x - shift), (short) (y + roadY), (short) (z - shift), id, false, h2); } } - BiomeType biome = blockArrayClipboard2 - .getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); + BiomeType biome = blockArrayClipboard2.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); addOverlayBiome((short) (x - shift), (short) (z - shift), biome); } } } - public void addOverlayBlock(short x, short y, short z, BaseBlock id, boolean rotate, - int height) { + public void addOverlayBlock(short x, short y, short z, BaseBlock id, boolean rotate, int height) { if (z < 0) { z += this.SIZE; } else if (z >= this.SIZE) { diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index 7936a6029..384eecdcd 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -80,8 +80,7 @@ import java.util.concurrent.atomic.AtomicInteger; public class HybridUtils { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + HybridUtils.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + HybridUtils.class.getSimpleName()); public static HybridUtils manager; public static Set regions; @@ -94,18 +93,17 @@ public class HybridUtils { private final ChunkManager chunkManager; private final GlobalBlockQueue blockQueue; private final WorldUtil worldUtil; - private final RegionManager regionManager; private final SchematicHandler schematicHandler; @Inject public HybridUtils(@Nonnull final PlotAreaManager plotAreaManager, - @Nonnull final ChunkManager chunkManager, @Nonnull final GlobalBlockQueue blockQueue, - @Nonnull final WorldUtil worldUtil, @Nonnull final RegionManager regionManager, - @Nonnull final SchematicHandler schematicHandler) { + @Nonnull final ChunkManager chunkManager, + @Nonnull final GlobalBlockQueue blockQueue, + @Nonnull final WorldUtil worldUtil, + @Nonnull final SchematicHandler schematicHandler) { this.plotAreaManager = plotAreaManager; this.chunkManager = chunkManager; this.blockQueue = blockQueue; this.worldUtil = worldUtil; - this.regionManager = regionManager; this.schematicHandler = schematicHandler; } @@ -114,8 +112,7 @@ public class HybridUtils { plotManager.regenerateAllPlotWalls(); } - public void analyzeRegion(final String world, final CuboidRegion region, - final RunnableVal whenDone) { + public void analyzeRegion(final String world, final CuboidRegion region, final RunnableVal whenDone) { // int diff, int variety, int vertices, int rotation, int height_sd /* * diff: compare to base by looping through all blocks @@ -235,30 +232,23 @@ public class HybridUtils { } else { // check vertices // modifications_adjacent - if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 - && y < 255) { - if (newBlocks[y - 1][x][z].getBlockType().getMaterial() - .isAir()) { + if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 && y < 255) { + if (newBlocks[y - 1][x][z].getBlockType().getMaterial().isAir()) { faces[i]++; } - if (newBlocks[y][x - 1][z].getBlockType().getMaterial() - .isAir()) { + if (newBlocks[y][x - 1][z].getBlockType().getMaterial().isAir()) { faces[i]++; } - if (newBlocks[y][x][z - 1].getBlockType().getMaterial() - .isAir()) { + if (newBlocks[y][x][z - 1].getBlockType().getMaterial().isAir()) { faces[i]++; } - if (newBlocks[y + 1][x][z].getBlockType().getMaterial() - .isAir()) { + if (newBlocks[y + 1][x][z].getBlockType().getMaterial().isAir()) { faces[i]++; } - if (newBlocks[y][x + 1][z].getBlockType().getMaterial() - .isAir()) { + if (newBlocks[y][x + 1][z].getBlockType().getMaterial().isAir()) { faces[i]++; } - if (newBlocks[y][x][z + 1].getBlockType().getMaterial() - .isAir()) { + if (newBlocks[y][x][z + 1].getBlockType().getMaterial().isAir()) { faces[i]++; } } @@ -347,9 +337,7 @@ public class HybridUtils { result.add(whenDone.value.data_sd); result.add(whenDone.value.air_sd); result.add(whenDone.value.variety_sd); - PlotFlag plotFlag = - GlobalFlagContainer.getInstance().getFlag(AnalysisFlag.class) - .createFlagInstance(result); + PlotFlag plotFlag = GlobalFlagContainer.getInstance().getFlag(AnalysisFlag.class).createFlagInstance(result); PlotFlagAddEvent event = new PlotFlagAddEvent(plotFlag, origin); if (event.getEventResult() == Result.DENY) { return; @@ -371,15 +359,13 @@ public class HybridUtils { run.run(); } - public int checkModified(QueueCoordinator queue, int x1, int x2, int y1, int y2, int z1, int z2, - BlockState[] blocks) { + public int checkModified(QueueCoordinator queue, int x1, int x2, int y1, int y2, int z1, int z2, BlockState[] blocks) { int count = 0; for (int y = y1; y <= y2; y++) { for (int x = x1; x <= x2; x++) { for (int z = z1; z <= z2; z++) { BlockState block = queue.getBlock(x, y, z); - boolean same = - Arrays.stream(blocks).anyMatch(p -> this.worldUtil.isBlockSame(block, p)); + boolean same = Arrays.stream(blocks).anyMatch(p -> this.worldUtil.isBlockSame(block, p)); if (!same) { count++; } @@ -420,8 +406,7 @@ public class HybridUtils { return scheduleRoadUpdate(plot.getArea(), regions, extend, new HashSet<>()); } - public boolean scheduleRoadUpdate(final PlotArea area, Set regions, - final int extend, Set chunks) { + public boolean scheduleRoadUpdate(final PlotArea area, Set regions, final int extend, Set chunks) { HybridUtils.regions = regions; HybridUtils.area = area; HybridUtils.height = extend; @@ -460,16 +445,12 @@ public class HybridUtils { try { if (chunks.size() < 1024) { if (!HybridUtils.regions.isEmpty()) { - Iterator iterator = - HybridUtils.regions.iterator(); + Iterator iterator = HybridUtils.regions.iterator(); BlockVector2 loc = iterator.next(); iterator.remove(); if (Settings.DEBUG) { - logger - .info("[P2] Updating .mcr: {}, {} (approx 1024 chunks)", - loc.getX(), loc.getZ()); - logger.info("[P2] - Remaining: {}", - HybridUtils.regions.size()); + logger.info("[P2] Updating .mcr: {}, {} (approx 1024 chunks)", loc.getX(), loc.getZ()); + logger.info("[P2] - Remaining: {}", HybridUtils.regions.size()); } chunks.addAll(getChunks(loc)); System.gc(); @@ -479,8 +460,7 @@ public class HybridUtils { TaskManager.getPlatformImplementation().sync(() -> { long start = System.currentTimeMillis(); Iterator iterator = chunks.iterator(); - while (System.currentTimeMillis() - start < 20 && !chunks - .isEmpty()) { + while (System.currentTimeMillis() - start < 20 && !chunks.isEmpty()) { final BlockVector2 chunk = iterator.next(); iterator.remove(); boolean regenedRoads = regenerateRoad(area, chunk, extend); @@ -496,9 +476,8 @@ public class HybridUtils { Iterator iterator = HybridUtils.regions.iterator(); BlockVector2 loc = iterator.next(); iterator.remove(); - logger.error( - "[P2] Error! Could not update '{}/region/r.{}.{}.mca' (Corrupt chunk?)", - area.getWorldHash(), loc.getX(), loc.getZ()); + logger.error("[P2] Error! Could not update '{}/region/r.{}.{}.mca' (Corrupt chunk?)", area.getWorldHash(), loc.getX(), + loc.getZ()); } TaskManager.runTaskLater(task, TaskTime.seconds(1L)); }); @@ -525,37 +504,31 @@ public class HybridUtils { int tz = sz - 1; int ty = get_ey(plotManager, queue, sx, ex, bz, tz, sy); - Set sideRoad = new HashSet<>( - Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ey, sz, ez))); - final Set intersection = new HashSet<>( - Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ty, bz, tz))); + Set sideRoad = new HashSet<>(Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ey, sz, ez))); + final Set intersection = new HashSet<>(Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ty, bz, tz))); - final String dir = - "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + plot.getArea() - .toString() + File.separator; + final String dir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + plot.getArea().toString() + File.separator; this.schematicHandler.getCompoundTag(world, sideRoad, new RunnableVal() { @Override public void run(CompoundTag value) { schematicHandler.save(value, dir + "sideroad.schem"); - schematicHandler - .getCompoundTag(world, intersection, new RunnableVal() { - @Override public void run(CompoundTag value) { - schematicHandler.save(value, dir + "intersection.schem"); - plotworld.ROAD_SCHEMATIC_ENABLED = true; - try { - plotworld.setupSchematics(); - } catch (SchematicHandler.UnsupportedFormatException e) { - e.printStackTrace(); - } + schematicHandler.getCompoundTag(world, intersection, new RunnableVal() { + @Override public void run(CompoundTag value) { + schematicHandler.save(value, dir + "intersection.schem"); + plotworld.ROAD_SCHEMATIC_ENABLED = true; + try { + plotworld.setupSchematics(); + } catch (SchematicHandler.UnsupportedFormatException e) { + e.printStackTrace(); } - }); + } + }); } }); return true; } - public int get_ey(final PlotManager pm, QueueCoordinator queue, int sx, int ex, int sz, int ez, - int sy) { + public int get_ey(final PlotManager pm, QueueCoordinator queue, int sx, int ex, int sz, int ez, int sy) { int ey = sy; for (int x = sx; x <= ex; x++) { for (int z = sz; z <= ez; z++) { @@ -598,8 +571,7 @@ public class HybridUtils { z -= plotWorld.ROAD_OFFSET_Z; final int finalX = x; final int finalZ = z; - QueueCoordinator queue = - this.blockQueue.getNewQueue(worldUtil.getWeWorld(plotWorld.getWorldName())); + QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(plotWorld.getWorldName())); if (id1 == null || id2 == null || id1 != id2) { this.chunkManager.loadChunk(area.getWorldName(), chunk, false).thenRun(() -> { if (id1 != null) { @@ -627,8 +599,7 @@ public class HybridUtils { } boolean condition; if (toCheck.get()) { - condition = manager.getPlotId(finalX + X + plotWorld.ROAD_OFFSET_X, 1, - finalZ + Z + plotWorld.ROAD_OFFSET_Z) == null; + condition = manager.getPlotId(finalX + X + plotWorld.ROAD_OFFSET_X, 1, finalZ + Z + plotWorld.ROAD_OFFSET_Z) == null; } else { boolean gx = absX > plotWorld.PATH_WIDTH_LOWER; boolean gz = absZ > plotWorld.PATH_WIDTH_LOWER; @@ -638,32 +609,27 @@ public class HybridUtils { } if (condition) { BaseBlock[] blocks = plotWorld.G_SCH.get(MathMan.pair(absX, absZ)); - int minY = - Settings.Schematics.PASTE_ROAD_ON_TOP ? plotWorld.SCHEM_Y : 1; + int minY = Settings.Schematics.PASTE_ROAD_ON_TOP ? plotWorld.SCHEM_Y : 1; int maxY = Math.max(extend, blocks.length); for (int y = 0; y < maxY; y++) { if (y > blocks.length - 1) { - queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, - finalZ + Z + plotWorld.ROAD_OFFSET_Z, WEExtent.AIRBASE); + queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, + WEExtent.AIRBASE); } else { BaseBlock block = blocks[y]; if (block != null) { - queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, - minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, block); + queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, block); } else { - queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, - minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, + queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, WEExtent.AIRBASE); } } } BiomeType biome = plotWorld.G_SCH_B.get(MathMan.pair(absX, absZ)); if (biome != null) { - queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, - finalZ + Z + plotWorld.ROAD_OFFSET_Z, biome); + queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, finalZ + Z + plotWorld.ROAD_OFFSET_Z, biome); } else { - queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, - finalZ + Z + plotWorld.ROAD_OFFSET_Z, plotWorld.getPlotBiome()); + queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, finalZ + Z + plotWorld.ROAD_OFFSET_Z, plotWorld.getPlotBiome()); } } } diff --git a/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java index 32ea8154e..0cfc21a95 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java @@ -34,6 +34,7 @@ import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.HashUtil; import com.plotsquared.core.util.RegionManager; import com.sk89q.worldedit.regions.CuboidRegion; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,26 +48,25 @@ import java.util.Set; */ public abstract class SquarePlotManager extends GridPlotManager { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + SquarePlotManager.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + SquarePlotManager.class.getSimpleName()); private final SquarePlotWorld squarePlotWorld; private final RegionManager regionManager; - public SquarePlotManager(@Nonnull final SquarePlotWorld squarePlotWorld, - @Nonnull final RegionManager regionManager) { + public SquarePlotManager(@Nonnull final SquarePlotWorld squarePlotWorld, @Nonnull final RegionManager regionManager) { super(squarePlotWorld); this.squarePlotWorld = squarePlotWorld; this.regionManager = regionManager; } - @Override public boolean clearPlot(final Plot plot, final Runnable whenDone, - @Nullable QueueCoordinator queue) { + @Override public boolean clearPlot(final @NotNull Plot plot, final @Nullable Runnable whenDone, @Nullable QueueCoordinator queue) { final Set regions = plot.getRegions(); Runnable run = new Runnable() { @Override public void run() { if (regions.isEmpty()) { - whenDone.run(); + if (whenDone != null) { + whenDone.run(); + } return; } Iterator iterator = regions.iterator(); @@ -81,13 +81,13 @@ public abstract class SquarePlotManager extends GridPlotManager { return true; } - @Override public Location getPlotTopLocAbs(PlotId plotId) { + @Override public Location getPlotTopLocAbs(@NotNull PlotId plotId) { int px = plotId.getX(); int pz = plotId.getY(); - int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH - + squarePlotWorld.PLOT_WIDTH))) - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; - int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH - + squarePlotWorld.PLOT_WIDTH))) - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; + int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - (int) Math + .floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; + int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - (int) Math + .floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; return 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; if (dpw.ROAD_OFFSET_X != 0) { x -= dpw.ROAD_OFFSET_X; @@ -196,8 +196,7 @@ public abstract class SquarePlotManager extends GridPlotManager { rz = z % size; } PlotId id = PlotId.of(dx, dz); - boolean[] merged = - new boolean[] {rz <= pathWidthLower, rx > end, rz > end, rx <= pathWidthLower}; + boolean[] merged = new boolean[] {rz <= pathWidthLower, rx > end, rz > end, rx <= pathWidthLower}; int hash = HashUtil.hash(merged); // Not merged, and no need to check if it is if (hash == 0) { @@ -235,8 +234,7 @@ public abstract class SquarePlotManager extends GridPlotManager { return plot.getMerged(Direction.NORTHWEST) ? id : null; } } catch (Exception ignored) { - logger.error("Invalid plot / road width in settings.yml for world: {}", - squarePlotWorld.getWorldName()); + logger.error("Invalid plot / road width in settings.yml for world: {}", squarePlotWorld.getWorldName()); } return null; } @@ -244,16 +242,13 @@ public abstract class SquarePlotManager extends GridPlotManager { /** * 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 pz = plotId.getY(); - int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH - + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH - (int) Math - .floor(squarePlotWorld.ROAD_WIDTH / 2); - int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH - + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH - (int) Math - .floor(squarePlotWorld.ROAD_WIDTH / 2); - return Location - .at(squarePlotWorld.getWorldName(), x, squarePlotWorld.getMinBuildHeight(), z); + int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH + - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2); + int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH + - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2); + return Location.at(squarePlotWorld.getWorldName(), x, squarePlotWorld.getMinBuildHeight(), z); } } diff --git a/Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java b/Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java deleted file mode 100644 index 96ce1e242..000000000 --- a/Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java +++ /dev/null @@ -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 . - */ -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 { -} diff --git a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorBuilderFactory.java b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorBuilderFactory.java index bfcbe206d..c526ae731 100644 --- a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorBuilderFactory.java +++ b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorBuilderFactory.java @@ -34,7 +34,6 @@ import javax.annotation.Nonnull; public interface ChunkCoordinatorBuilderFactory { - @Inject @Nonnull ChunkCoordinatorBuilder create( - @Assisted @NotNull ChunkCoordinatorFactory chunkCoordinatorFactory); + @Inject @Nonnull ChunkCoordinatorBuilder create(@Assisted @NotNull ChunkCoordinatorFactory chunkCoordinatorFactory); } diff --git a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java index df87be525..aeb62d659 100644 --- a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java +++ b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java @@ -35,9 +35,13 @@ import java.util.function.Consumer; public interface ChunkCoordinatorFactory { - @Nonnull ChunkCoordinator create(final long maxIterationTime, final int initialBatchSize, - @Nonnull final Consumer chunkConsumer, @Nonnull final World world, - @Nonnull final Collection requestedChunks, @Nonnull final Runnable whenDone, - @Nonnull final Consumer throwableConsumer, final boolean unloadAfter); + @Nonnull ChunkCoordinator create(final long maxIterationTime, + final int initialBatchSize, + @Nonnull final Consumer chunkConsumer, + @Nonnull final World world, + @Nonnull final Collection requestedChunks, + @Nonnull final Runnable whenDone, + @Nonnull final Consumer throwableConsumer, + final boolean unloadAfter); } diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index 9636b2c7e..2c3c462e3 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -140,14 +140,13 @@ public class Plot { private static final Logger logger = LoggerFactory.getLogger("P2/" + Plot.class.getSimpleName()); private static final DecimalFormat FLAG_DECIMAL_FORMAT = new DecimalFormat("0"); + private static Set connected_cache; + private static Set regions_cache; static { FLAG_DECIMAL_FORMAT.setMaximumFractionDigits(340); } - private static Set connected_cache; - private static Set regions_cache; - /** * Plot flag container */ @@ -272,9 +271,18 @@ public class Plot { * @param merged an array giving merged plots * @see Plot#getPlot(Location) for existing plots */ - public Plot(@Nonnull PlotId id, UUID owner, HashSet trusted, HashSet members, - HashSet denied, String alias, BlockLoc position, Collection> flags, - PlotArea area, boolean[] merged, long timestamp, int temp) { + public Plot(@Nonnull PlotId id, + UUID owner, + HashSet trusted, + HashSet members, + HashSet denied, + String alias, + BlockLoc position, + Collection> flags, + PlotArea area, + boolean[] merged, + long timestamp, + int temp) { this.id = id; this.area = area; 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 * @return The plot if only 1 result is found, or null */ - @Nullable public static Plot getPlotFromString(PlotPlayer player, String arg, - boolean message) { + @Nullable public static Plot getPlotFromString(PlotPlayer player, String arg, boolean message) { if (arg == null) { if (player == null) { if (message) { @@ -329,8 +336,7 @@ public class Plot { String[] split = arg.split(";|,"); PlotId id; if (split.length == 4) { - area = PlotSquared.get().getPlotAreaManager() - .getPlotAreaByString(split[0] + ';' + split[1]); + area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(split[0] + ';' + split[1]); id = PlotId.fromString(split[2] + ';' + split[3]); } else if (split.length == 3) { area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(split[0]); @@ -409,8 +415,7 @@ public class Plot { return null; } - @Nonnull private static Location[] getCorners(@Nonnull final String world, - @Nonnull final CuboidRegion region) { + @Nonnull private static Location[] getCorners(@Nonnull final String world, @Nonnull final CuboidRegion region) { final BlockVector3 min = region.getMinimumPoint(); final BlockVector3 max = region.getMaximumPoint(); return new Location[] {Location.at(world, min), Location.at(world, max)}; @@ -609,8 +614,7 @@ public class Plot { UUID last = this.getOwner(); owners.add(this.getOwner()); for (Plot current : array) { - if (last == null || current.getOwner().getMostSignificantBits() != last - .getMostSignificantBits()) { + if (last == null || current.getOwner().getMostSignificantBits() != last.getMostSignificantBits()) { owners.add(current.getOwner()); last = current.getOwner(); } @@ -652,8 +656,8 @@ public class Plot { * @return boolean false if the player is allowed to enter */ public boolean isDenied(UUID uuid) { - return this.denied != null && (this.denied.contains(DBFunc.EVERYONE) && !this.isAdded(uuid) - || !this.isAdded(uuid) && this.denied.contains(uuid)); + return this.denied != null && (this.denied.contains(DBFunc.EVERYONE) && !this.isAdded(uuid) || !this.isAdded(uuid) && this.denied + .contains(uuid)); } /** @@ -777,8 +781,7 @@ public class Plot { * @return true if this plot is merged, otherwise false */ public boolean isMerged() { - return getSettings().getMerged(0) || getSettings().getMerged(2) || getSettings() - .getMerged(1) || getSettings().getMerged(3); + return getSettings().getMerged(0) || getSettings().getMerged(2) || getSettings().getMerged(1) || getSettings().getMerged(3); } /** @@ -829,10 +832,8 @@ public class Plot { int i2 = 0; if (this.getSettings().getMerged(i2)) { if (this.getSettings().getMerged(i)) { - if (this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))) - .getMerged(i2)) { - return this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2))) - .getMerged(i); + if (this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))).getMerged(i2)) { + return this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2))).getMerged(i); } } } @@ -842,9 +843,8 @@ public class Plot { case 6: i = dir - 4; i2 = dir - 3; - return this.getSettings().getMerged(i2) && this.getSettings().getMerged(i) - && this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))) - .getMerged(i2) && this.area + return this.getSettings().getMerged(i2) && this.getSettings().getMerged(i) && this.area + .getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))).getMerged(i2) && this.area .getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2))).getMerged(i); } @@ -1045,8 +1045,8 @@ public class Plot { if (isDelete) { this.removeSign(); } - PlotUnlinkEvent event = this.eventDispatcher.callUnlink(getArea(), this, true, !isDelete, - isDelete ? PlotUnlinkEvent.REASON.DELETE : PlotUnlinkEvent.REASON.CLEAR); + PlotUnlinkEvent event = this.eventDispatcher + .callUnlink(getArea(), this, true, !isDelete, isDelete ? PlotUnlinkEvent.REASON.DELETE : PlotUnlinkEvent.REASON.CLEAR); if (event.getEventResult() != Result.DENY) { this.unlinkPlot(event.isCreateRoad(), event.isCreateSign()); } @@ -1074,9 +1074,7 @@ public class Plot { Plot current = queue.poll(); if (Plot.this.area.getTerrain() != PlotAreaTerrainType.NONE) { try { - regionManager - .regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, - this); + regionManager.regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, this); } catch (UnsupportedOperationException exception) { MainUtil.sendMessage(null, "Please ask md_5 to fix regenerateChunk() because it breaks plugins. We apologize for the inconvenience"); @@ -1191,17 +1189,11 @@ public class Plot { if (this.area.allowSigns()) { Location location = manager.getSignLoc(this); String id = this.id.toString(); - String[] lines = - 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_3.formatted().replaceAll("%id%", id).replaceAll( - "%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); + String[] lines = 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_3.formatted().replaceAll("%id%", id).replaceAll("%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} * @return Collection containing all the flags that matched the given criteria */ - public Collection> getApplicableFlags(final boolean plotOnly, - final boolean ignorePluginFlags) { + public Collection> getApplicableFlags(final boolean plotOnly, final boolean ignorePluginFlags) { if (!hasOwner()) { return Collections.emptyList(); } final Map, PlotFlag> flags = new HashMap<>(); - if (!plotOnly && getArea() != null && !getArea().getFlagContainer().getFlagMap() - .isEmpty()) { + if (!plotOnly && getArea() != null && !getArea().getFlagContainer().getFlagMap().isEmpty()) { final Map, PlotFlag> flagMap = getArea().getFlagContainer().getFlagMap(); flags.putAll(flagMap); } @@ -1449,8 +1439,7 @@ public class Plot { if (Settings.Backup.DELETE_ON_UNCLAIM) { // Destroy all backups when the plot is unclaimed - Objects.requireNonNull(PlotSquared.platform()).getBackupManager() - .getProfile(current).destroy(); + Objects.requireNonNull(PlotSquared.platform()).getBackupManager().getProfile(current).destroy(); } getArea().removePlot(getId()); @@ -1478,9 +1467,8 @@ public class Plot { Location[] corners = getCorners(); Location top = corners[0]; Location bot = corners[1]; - Location location = Location - .at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), - MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ())); + Location location = Location.at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), MathMan.average(bot.getY(), top.getY()), + MathMan.average(bot.getZ(), top.getZ())); if (!isLoaded()) { result.accept(location); return; @@ -1501,14 +1489,12 @@ public class Plot { Location[] corners = getCorners(); Location top = corners[0]; Location bot = corners[1]; - Location location = Location - .at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), - MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ())); + Location location = Location.at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), MathMan.average(bot.getY(), top.getY()), + MathMan.average(bot.getZ(), top.getZ())); if (!isLoaded()) { return location; } - int y = this.worldUtil - .getHighestBlockSynchronous(getWorldName(), location.getX(), location.getZ()); + int y = this.worldUtil.getHighestBlockSynchronous(getWorldName(), location.getX(), location.getZ()); if (area.allowSigns()) { y = Math.max(y, getManager().getSignLoc(this).getY()); } @@ -1520,8 +1506,7 @@ public class Plot { */ @Deprecated public Location getSideSynchronous() { CuboidRegion largest = getLargestRegion(); - int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) - + largest.getMinimumPoint().getX(); + int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX(); int z = largest.getMinimumPoint().getZ() - 1; PlotManager manager = getManager(); int y = isLoaded() ? this.worldUtil.getHighestBlockSynchronous(getWorldName(), x, z) : 62; @@ -1533,8 +1518,7 @@ public class Plot { public void getSide(Consumer result) { CuboidRegion largest = getLargestRegion(); - int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) - + largest.getMinimumPoint().getX(); + int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX(); int z = largest.getMinimumPoint().getZ() - 1; PlotManager manager = getManager(); if (isLoaded()) { @@ -1564,16 +1548,14 @@ public class Plot { } else { Location bottom = this.getBottomAbs(); Location location = Location - .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), - bottom.getZ() + home.getZ(), home.getYaw(), home.getPitch()); + .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), bottom.getZ() + home.getZ(), home.getYaw(), + home.getPitch()); if (!isLoaded()) { return location; } - if (!this.worldUtil.getBlockSynchronous(location).getBlockType().getMaterial() - .isAir()) { - location = location.withY(Math.max(1 + this.worldUtil - .getHighestBlockSynchronous(this.getWorldName(), location.getX(), - location.getZ()), bottom.getY())); + if (!this.worldUtil.getBlockSynchronous(location).getBlockType().getMaterial().isAir()) { + location = location.withY( + Math.max(1 + this.worldUtil.getHighestBlockSynchronous(this.getWorldName(), location.getX(), location.getZ()), bottom.getY())); } return location; } @@ -1589,17 +1571,16 @@ public class Plot { } else { Location bottom = this.getBottomAbs(); Location location = Location - .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), - bottom.getZ() + home.getZ(), home.getYaw(), home.getPitch()); + .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), bottom.getZ() + home.getZ(), home.getYaw(), + home.getPitch()); if (!isLoaded()) { result.accept(location); return; } this.worldUtil.getBlock(location, block -> { if (!block.getBlockType().getMaterial().isAir()) { - this.worldUtil - .getHighestBlock(this.getWorldName(), location.getX(), location.getZ(), - y -> result.accept(location.withY(Math.max(1 + y, bottom.getY())))); + this.worldUtil.getHighestBlock(this.getWorldName(), location.getX(), location.getZ(), + y -> result.accept(location.withY(Math.max(1 + y, bottom.getY())))); } else { result.accept(location); } @@ -1645,21 +1626,15 @@ public class Plot { if (loc.getX() == Integer.MAX_VALUE && loc.getZ() == Integer.MAX_VALUE) { // center CuboidRegion largest = plot.getLargestRegion(); - x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() - >> 1) + largest.getMinimumPoint().getX(); - z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ() - >> 1) + largest.getMinimumPoint().getZ(); + x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX(); + z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ() >> 1) + largest.getMinimumPoint().getZ(); } else { // specific Location bot = plot.getBottomAbs(); x = bot.getX() + loc.getX(); z = bot.getZ() + loc.getZ(); } - int y = loc.getY() < 1 ? - (isLoaded() ? - this.worldUtil.getHighestBlockSynchronous(plot.getWorldName(), x, z) + 1 : - 63) : - loc.getY(); + int y = loc.getY() < 1 ? (isLoaded() ? this.worldUtil.getHighestBlockSynchronous(plot.getWorldName(), x, z) + 1 : 63) : loc.getY(); return Location.at(plot.getWorldName(), x, y, z); } // Side @@ -1675,10 +1650,8 @@ public class Plot { if (loc.getX() == Integer.MAX_VALUE && loc.getZ() == Integer.MAX_VALUE) { // center CuboidRegion largest = plot.getLargestRegion(); - x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() - >> 1) + largest.getMinimumPoint().getX(); - z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ() - >> 1) + largest.getMinimumPoint().getZ(); + x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX(); + z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ() >> 1) + largest.getMinimumPoint().getZ(); } else { // specific Location bot = plot.getBottomAbs(); @@ -1687,8 +1660,7 @@ public class Plot { } if (loc.getY() < 1) { if (isLoaded()) { - this.worldUtil.getHighestBlock(plot.getWorldName(), x, z, - y -> result.accept(Location.at(plot.getWorldName(), x, y + 1, z))); + this.worldUtil.getHighestBlock(plot.getWorldName(), x, z, y -> result.accept(Location.at(plot.getWorldName(), x, y + 1, z))); } else { result.accept(Location.at(plot.getWorldName(), x, 63, z)); } @@ -1704,10 +1676,8 @@ public class Plot { public double getVolume() { double count = 0; for (CuboidRegion region : getRegions()) { - count += - (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * ( - region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1) - * MAX_HEIGHT; + count += (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * ( + region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1) * MAX_HEIGHT; } return count; } @@ -1790,14 +1760,11 @@ public class Plot { * This should not need to be called */ public void refreshChunks() { - QueueCoordinator queue = this.blockQueue - .getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(getWorldName())); + QueueCoordinator queue = this.blockQueue.getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(getWorldName())); HashSet chunks = new HashSet<>(); for (CuboidRegion region : Plot.this.getRegions()) { - for (int x = region.getMinimumPoint().getX() >> 4; - x <= region.getMaximumPoint().getX() >> 4; x++) { - for (int z = region.getMinimumPoint().getZ() >> 4; - z <= region.getMaximumPoint().getZ() >> 4; z++) { + for (int x = region.getMinimumPoint().getX() >> 4; x <= region.getMaximumPoint().getX() >> 4; x++) { + for (int z = region.getMinimumPoint().getZ() >> 4; z <= region.getMaximumPoint().getZ() >> 4; z++) { if (chunks.add(BlockVector2.at(x, z))) { worldUtil.refreshChunk(x, z, getWorldName()); } @@ -1816,8 +1783,7 @@ public class Plot { } Location location = manager.getSignLoc(this); QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(getWorldName())); - queue.setBlock(location.getX(), location.getY(), location.getZ(), - BlockTypes.AIR.getDefaultState()); + queue.setBlock(location.getX(), location.getY(), location.getZ(), BlockTypes.AIR.getDefaultState()); queue.enqueue(); } @@ -1829,8 +1795,7 @@ public class Plot { this.setSign("unknown"); return; } - this.impromptuPipeline - .getSingle(this.getOwnerAbs(), (username, sign) -> this.setSign(username)); + this.impromptuPipeline.getSingle(this.getOwnerAbs(), (username, sign) -> this.setSign(username)); } /** @@ -1852,14 +1817,12 @@ public class Plot { return claim(player, teleport, schematic, true); } - public boolean claim(@Nonnull final PlotPlayer player, boolean teleport, String schematic, - boolean updateDB) { + public boolean claim(@Nonnull final PlotPlayer player, boolean teleport, String schematic, boolean updateDB) { if (updateDB) { if (!create(player.getUUID(), true)) { - logger.error( - "[P2] Player {} attempted to claim plot {}, but the database failed to update", - player.getName(), this.getId().toCommaSeparatedString()); + logger.error("[P2] Player {} attempted to claim plot {}, but the database failed to update", player.getName(), + this.getId().toCommaSeparatedString()); return false; } } else { @@ -1888,16 +1851,15 @@ public class Plot { e.printStackTrace(); return true; } - schematicHandler.paste(sch, this, 0, 1, 0, Settings.Schematics.PASTE_ON_TOP, - new RunnableVal() { - @Override public void run(Boolean value) { - if (value) { - MainUtil.sendMessage(player, Captions.SCHEMATIC_PASTE_SUCCESS); - } else { - MainUtil.sendMessage(player, Captions.SCHEMATIC_PASTE_FAILED); - } + schematicHandler.paste(sch, this, 0, 1, 0, Settings.Schematics.PASTE_ON_TOP, new RunnableVal() { + @Override public void run(Boolean value) { + if (value) { + MainUtil.sendMessage(player, Captions.SCHEMATIC_PASTE_SUCCESS); + } else { + MainUtil.sendMessage(player, Captions.SCHEMATIC_PASTE_FAILED); } - }); + } + }); } plotworld.getPlotManager().claimPlot(this); return true; @@ -1935,11 +1897,9 @@ public class Plot { DBFunc.createPlotAndSettings(this, () -> { PlotArea plotworld = Plot.this.area; if (notify && plotworld.isAutoMerge()) { - final PlotPlayer player = PlotSquared.platform().getPlayerManager() - .getPlayerIfExists(uuid); + final PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); - PlotMergeEvent event = this.eventDispatcher - .callMerge(this, Direction.ALL, Integer.MAX_VALUE, player); + PlotMergeEvent event = this.eventDispatcher.callMerge(this, Direction.ALL, Integer.MAX_VALUE, player); if (event.getEventResult() == Result.DENY) { if (player != null) { @@ -1952,8 +1912,7 @@ public class Plot { }); return true; } - logger.info("[P2] Failed to add plot {} to plot area {}", - this.getId().toCommaSeparatedString(), this.area.toString()); + logger.info("[P2] Failed to add plot {} to plot area {}", this.getId().toCommaSeparatedString(), this.area.toString()); return false; } @@ -1961,8 +1920,7 @@ public class Plot { * Sets components such as border, wall, floor. * (components are generator specific) */ - @Deprecated public boolean setComponent(String component, String blocks, - QueueCoordinator queue) { + @Deprecated public boolean setComponent(String component, String blocks, QueueCoordinator queue) { BlockBucket parsed = ConfigurationUtil.BLOCK_BUCKET.parseString(blocks); if (parsed != null && parsed.isEmpty()) { return false; @@ -1976,8 +1934,7 @@ public class Plot { * Retrieve the biome of the plot. */ public void getBiome(Consumer result) { - this.getCenter(location -> this.worldUtil - .getBiome(location.getWorldName(), location.getX(), location.getZ(), result)); + this.getCenter(location -> this.worldUtil.getBiome(location.getWorldName(), location.getX(), location.getZ(), result)); } //TODO Better documentation needed. @@ -1987,8 +1944,7 @@ public class Plot { */ @Deprecated public BiomeType getBiomeSynchronous() { final Location location = this.getCenterSynchronous(); - return this.worldUtil - .getBiomeSynchronous(location.getWorldName(), location.getX(), location.getZ()); + return this.worldUtil.getBiomeSynchronous(location.getWorldName(), location.getX(), location.getZ()); } /** @@ -2120,16 +2076,14 @@ public class Plot { * - Used when a plot is merged
*/ public void removeRoadEast() { - if (this.area.getType() != PlotAreaType.NORMAL - && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { + if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { Plot other = this.getRelative(Direction.EAST); Location bot = other.getBottomAbs(); Location top = this.getTopAbs(); Location pos1 = Location.at(this.getWorldName(), top.getX(), 0, bot.getZ()); Location pos2 = Location.at(this.getWorldName(), bot.getX(), MAX_HEIGHT, top.getZ()); this.regionManager.regenerateRegion(pos1, pos2, true, null); - } else if (this.area.getTerrain() - != PlotAreaTerrainType.ALL) { // no road generated => no road to remove + } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove this.area.getPlotManager().removeRoadEast(this); } } @@ -2289,10 +2243,8 @@ public class Plot { } } else { TaskManager.runTaskAsync(() -> { - String name = Plot.this.id + "," + Plot.this.area + ',' + - PlayerManager.getName(Plot.this.getOwnerAbs()); - boolean result = schematicHandler.save(value, - Settings.Paths.SCHEMATICS + File.separator + name + ".schem"); + String name = Plot.this.id + "," + Plot.this.area + ',' + PlayerManager.getName(Plot.this.getOwnerAbs()); + boolean result = schematicHandler.save(value, Settings.Paths.SCHEMATICS + File.separator + name + ".schem"); if (whenDone != null) { whenDone.value = result; TaskManager.runTask(whenDone); @@ -2339,8 +2291,7 @@ public class Plot { return false; } Plot other = (Plot) obj; - return this.hashCode() == other.hashCode() && this.id.equals(other.id) - && this.area == other.area; + return this.hashCode() == other.hashCode() && this.id.equals(other.id) && this.area == other.area; } /** @@ -2400,8 +2351,9 @@ public class Plot { if (value) { Plot other = this.getRelative(direction).getBasePlot(false); if (!other.equals(this.getBasePlot(false))) { - Plot base = other.id.getY() < this.id.getY() - || other.id.getY() == this.id.getY() && other.id.getX() < this.id.getX() ? other : this.origin; + Plot base = other.id.getY() < this.id.getY() || other.id.getY() == this.id.getY() && other.id.getX() < this.id.getX() ? + other : + this.origin; this.origin.origin = base; other.origin = base; this.origin = base; @@ -2474,8 +2426,7 @@ public class Plot { public boolean canClaim(@Nonnull PlotPlayer player) { PlotCluster cluster = this.getCluster(); if (cluster != null) { - if (!cluster.isAdded(player.getUUID()) && !Permissions - .hasPermission(player, "plots.admin.command.claim")) { + if (!cluster.isAdded(player.getUUID()) && !Permissions.hasPermission(player, "plots.admin.command.claim")) { return false; } } @@ -2491,16 +2442,14 @@ public class Plot { * - Used when a plot is merged
*/ public void removeRoadSouth() { - if (this.area.getType() != PlotAreaType.NORMAL - && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { + if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { Plot other = this.getRelative(Direction.SOUTH); Location bot = other.getBottomAbs(); Location top = this.getTopAbs(); Location pos1 = Location.at(this.getWorldName(), bot.getX(), 0, top.getZ()); Location pos2 = Location.at(this.getWorldName(), top.getX(), MAX_HEIGHT, bot.getZ()); this.regionManager.regenerateRegion(pos1, pos2, true, null); - } else if (this.area.getTerrain() - != PlotAreaTerrainType.ALL) { // no road generated => no road to remove + } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove this.getManager().removeRoadSouth(this); } } @@ -2520,8 +2469,7 @@ public class Plot { return false; } Set connected = this.getConnectedPlots(); - HashSet merged = - connected.stream().map(Plot::getId).collect(Collectors.toCollection(HashSet::new)); + HashSet merged = connected.stream().map(Plot::getId).collect(Collectors.toCollection(HashSet::new)); ArrayDeque frontier = new ArrayDeque<>(connected); Plot current; boolean toReturn = false; @@ -2534,10 +2482,8 @@ public class Plot { Set plots; if ((dir == Direction.ALL || dir == Direction.NORTH) && !getMerged(Direction.NORTH)) { Plot other = current.getRelative(Direction.NORTH); - if (other != null && other.isOwner(uuid) && ( - other.getBasePlot(false).equals(current.getBasePlot(false)) - || (plots = other.getConnectedPlots()).size() <= max && frontier - .addAll(plots) && (max -= plots.size()) != -1)) { + if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) + || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { current.mergePlot(other, removeRoads); merged.add(current.getId()); merged.add(other.getId()); @@ -2551,13 +2497,10 @@ public class Plot { } } } - if (max >= 0 && (dir == Direction.ALL || dir == Direction.EAST) && !current - .getMerged(Direction.EAST)) { + if (max >= 0 && (dir == Direction.ALL || dir == Direction.EAST) && !current.getMerged(Direction.EAST)) { Plot other = current.getRelative(Direction.EAST); - if (other != null && other.isOwner(uuid) && ( - other.getBasePlot(false).equals(current.getBasePlot(false)) - || (plots = other.getConnectedPlots()).size() <= max && frontier - .addAll(plots) && (max -= plots.size()) != -1)) { + if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) + || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { current.mergePlot(other, removeRoads); merged.add(current.getId()); merged.add(other.getId()); @@ -2571,13 +2514,10 @@ public class Plot { } } } - if (max >= 0 && (dir == Direction.ALL || dir == Direction.SOUTH) && !getMerged( - Direction.SOUTH)) { + if (max >= 0 && (dir == Direction.ALL || dir == Direction.SOUTH) && !getMerged(Direction.SOUTH)) { Plot other = current.getRelative(Direction.SOUTH); - if (other != null && other.isOwner(uuid) && ( - other.getBasePlot(false).equals(current.getBasePlot(false)) - || (plots = other.getConnectedPlots()).size() <= max && frontier - .addAll(plots) && (max -= plots.size()) != -1)) { + if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) + || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { current.mergePlot(other, removeRoads); merged.add(current.getId()); merged.add(other.getId()); @@ -2591,13 +2531,10 @@ public class Plot { } } } - if (max >= 0 && (dir == Direction.ALL || dir == Direction.WEST) && !getMerged( - Direction.WEST)) { + if (max >= 0 && (dir == Direction.ALL || dir == Direction.WEST) && !getMerged(Direction.WEST)) { Plot other = current.getRelative(Direction.WEST); - if (other != null && other.isOwner(uuid) && ( - other.getBasePlot(false).equals(current.getBasePlot(false)) - || (plots = other.getConnectedPlots()).size() <= max && frontier - .addAll(plots) && (max -= plots.size()) != -1)) { + if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) + || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { current.mergePlot(other, removeRoads); merged.add(current.getId()); merged.add(other.getId()); @@ -2625,8 +2562,7 @@ public class Plot { final FlagContainer flagContainer1 = this.getFlagContainer(); final FlagContainer flagContainer2 = plot.getFlagContainer(); if (!flagContainer1.equals(flagContainer2)) { - boolean greater = - flagContainer1.getFlagMap().size() > flagContainer2.getFlagMap().size(); + boolean greater = flagContainer1.getFlagMap().size() > flagContainer2.getFlagMap().size(); if (greater) { flagContainer1.addAll(flagContainer2.getFlagMap().values()); } else { @@ -2669,14 +2605,12 @@ public class Plot { * Remove the SE road (only effects terrain) */ public void removeRoadSouthEast() { - if (this.area.getType() != PlotAreaType.NORMAL - && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { + if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { Plot other = this.getRelative(1, 1); Location pos1 = this.getTopAbs().add(1, 0, 1).withY(0); Location pos2 = other.getBottomAbs().subtract(1, 0, 1).withY(MAX_HEIGHT); this.regionManager.regenerateRegion(pos1, pos2, true, null); - } else if (this.area.getTerrain() - != PlotAreaTerrainType.ALL) { // no road generated => no road to remove + } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove this.area.getPlotManager().removeRoadSouthEast(this); } } @@ -2864,14 +2798,12 @@ public class Plot { PlotId top = PlotId.of(current.getId().getX(), current.getId().getY()); while (merge) { merge = false; - List ids = Lists.newArrayList((Iterable) - PlotId.PlotRangeIterator.range(PlotId.of(bot.getX(), bot.getY() - 1), - PlotId.of(top.getX(), bot.getY() - 1))); + List ids = Lists.newArrayList((Iterable) PlotId.PlotRangeIterator + .range(PlotId.of(bot.getX(), bot.getY() - 1), PlotId.of(top.getX(), bot.getY() - 1))); boolean tmp = true; for (PlotId id : ids) { Plot plot = this.area.getPlotAbs(id); - if (plot == null || !plot.getMerged(Direction.SOUTH) || visited - .contains(plot.getId())) { + if (plot == null || !plot.getMerged(Direction.SOUTH) || visited.contains(plot.getId())) { tmp = false; } } @@ -2879,14 +2811,12 @@ public class Plot { merge = true; bot = PlotId.of(bot.getX(), bot.getY() - 1); } - ids = Lists.newArrayList((Iterable) - PlotId.PlotRangeIterator.range(PlotId.of(top.getX() + 1, bot.getY()), - PlotId.of(top.getX() + 1, top.getY()))); + ids = Lists.newArrayList((Iterable) PlotId.PlotRangeIterator + .range(PlotId.of(top.getX() + 1, bot.getY()), PlotId.of(top.getX() + 1, top.getY()))); tmp = true; for (PlotId id : ids) { Plot plot = this.area.getPlotAbs(id); - if (plot == null || !plot.getMerged(Direction.WEST) || visited - .contains(plot.getId())) { + if (plot == null || !plot.getMerged(Direction.WEST) || visited.contains(plot.getId())) { tmp = false; } } @@ -2894,14 +2824,12 @@ public class Plot { merge = true; top = PlotId.of(top.getX() + 1, top.getY()); } - ids = Lists.newArrayList((Iterable) - PlotId.PlotRangeIterator.range(PlotId.of(bot.getX(), top.getY() + 1), - PlotId.of(top.getX(), top.getY() + 1))); + ids = Lists.newArrayList((Iterable) PlotId.PlotRangeIterator + .range(PlotId.of(bot.getX(), top.getY() + 1), PlotId.of(top.getX(), top.getY() + 1))); tmp = true; for (PlotId id : ids) { Plot plot = this.area.getPlotAbs(id); - if (plot == null || !plot.getMerged(Direction.NORTH) || visited - .contains(plot.getId())) { + if (plot == null || !plot.getMerged(Direction.NORTH) || visited.contains(plot.getId())) { tmp = false; } } @@ -2909,14 +2837,12 @@ public class Plot { merge = true; top = PlotId.of(top.getX(), top.getY() + 1); } - ids = Lists.newArrayList((Iterable) - PlotId.PlotRangeIterator.range(PlotId.of(bot.getX() - 1, bot.getY()), - PlotId.of(bot.getX() - 1, top.getY()))); + ids = Lists.newArrayList((Iterable) PlotId.PlotRangeIterator + .range(PlotId.of(bot.getX() - 1, bot.getY()), PlotId.of(bot.getX() - 1, top.getY()))); tmp = true; for (PlotId id : ids) { Plot plot = this.area.getPlotAbs(id); - if (plot == null || !plot.getMerged(Direction.EAST) || visited - .contains(plot.getId())) { + if (plot == null || !plot.getMerged(Direction.EAST) || visited.contains(plot.getId())) { tmp = false; } } @@ -2927,8 +2853,7 @@ public class Plot { } Location gtopabs = this.area.getPlotAbs(top).getTopAbs(); Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs(); - visited.addAll(Lists.newArrayList((Iterable) - PlotId.PlotRangeIterator.range(bot, top))); + visited.addAll(Lists.newArrayList((Iterable) PlotId.PlotRangeIterator.range(bot, top))); for (int x = bot.getX(); x <= top.getX(); x++) { Plot plot = this.area.getPlotAbs(PlotId.of(x, top.getY())); if (plot.getMerged(Direction.SOUTH)) { @@ -2937,8 +2862,7 @@ public class Plot { Location botabs = plot.getBottomAbs(); Location topabs = plot.getTopAbs(); BlockVector3 pos1 = BlockVector3.at(botabs.getX(), 0, topabs.getZ() + 1); - BlockVector3 pos2 = - BlockVector3.at(topabs.getX(), Plot.MAX_HEIGHT - 1, toploc.getZ()); + BlockVector3 pos2 = BlockVector3.at(topabs.getX(), Plot.MAX_HEIGHT - 1, toploc.getZ()); regions.add(new CuboidRegion(pos1, pos2)); if (plot.getMerged(Direction.SOUTHEAST)) { pos1 = BlockVector3.at(topabs.getX() + 1, 0, topabs.getZ() + 1); @@ -2957,8 +2881,7 @@ public class Plot { Location botabs = plot.getBottomAbs(); Location topabs = plot.getTopAbs(); BlockVector3 pos1 = BlockVector3.at(topabs.getX() + 1, 0, botabs.getZ()); - BlockVector3 pos2 = - BlockVector3.at(toploc.getX(), Plot.MAX_HEIGHT - 1, topabs.getZ()); + BlockVector3 pos2 = BlockVector3.at(toploc.getX(), Plot.MAX_HEIGHT - 1, topabs.getZ()); regions.add(new CuboidRegion(pos1, pos2)); if (plot.getMerged(Direction.SOUTHEAST)) { pos1 = BlockVector3.at(topabs.getX() + 1, 0, topabs.getZ() + 1); @@ -2969,8 +2892,7 @@ public class Plot { } } BlockVector3 pos1 = BlockVector3.at(gbotabs.getX(), 0, gbotabs.getZ()); - BlockVector3 pos2 = - BlockVector3.at(gtopabs.getX(), Plot.MAX_HEIGHT - 1, gtopabs.getZ()); + BlockVector3 pos2 = BlockVector3.at(gtopabs.getX(), Plot.MAX_HEIGHT - 1, gtopabs.getZ()); regions.add(new CuboidRegion(pos1, pos2)); } return regions; @@ -2986,9 +2908,8 @@ public class Plot { CuboidRegion max = null; double area = Double.NEGATIVE_INFINITY; for (CuboidRegion region : regions) { - double current = - (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * ( - region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1); + double current = (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * ( + region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1); if (current > area) { max = region; area = current; @@ -3016,12 +2937,9 @@ public class Plot { if (players.isEmpty()) { return; } - final String string = - Captions.PLOT_DEBUG.getTranslated().replace("%plot%", this.toString()) - .replace("%message%", message); + final String string = Captions.PLOT_DEBUG.getTranslated().replace("%plot%", this.toString()).replace("%message%", message); for (final PlotPlayer player : players) { - if (isOwner(player.getUUID()) || Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_DEBUG_OTHER)) { + if (isOwner(player.getUUID()) || Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_DEBUG_OTHER)) { player.sendMessage(string); } } @@ -3037,8 +2955,7 @@ public class Plot { public List getAllCorners() { Area area = new Area(); for (CuboidRegion region : this.getRegions()) { - Rectangle2D rect = new Rectangle2D.Double(region.getMinimumPoint().getX() - 0.6, - region.getMinimumPoint().getZ() - 0.6, + Rectangle2D rect = new Rectangle2D.Double(region.getMinimumPoint().getX() - 0.6, region.getMinimumPoint().getZ() - 0.6, region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + 1.2, region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + 1.2); Area rectArea = new Area(rect); @@ -3074,26 +2991,22 @@ public class Plot { * @param cause the cause of the teleport * @param resultConsumer Called with the result of the teleportation */ - public void teleportPlayer(final PlotPlayer player, TeleportCause cause, - Consumer resultConsumer) { + public void teleportPlayer(final PlotPlayer player, TeleportCause cause, Consumer resultConsumer) { Plot plot = this.getBasePlot(false); - Result result = - this.eventDispatcher.callTeleport(player, player.getLocation(), plot).getEventResult(); + Result result = this.eventDispatcher.callTeleport(player, player.getLocation(), plot).getEventResult(); if (result == Result.DENY) { sendMessage(player, Captions.EVENT_DENIED, "Teleport"); resultConsumer.accept(false); return; } final Consumer locationConsumer = location -> { - if (Settings.Teleport.DELAY == 0 || Permissions - .hasPermission(player, "plots.teleport.delay.bypass")) { + if (Settings.Teleport.DELAY == 0 || Permissions.hasPermission(player, "plots.teleport.delay.bypass")) { MainUtil.sendMessage(player, Captions.TELEPORTED_TO_PLOT); player.teleport(location, cause); resultConsumer.accept(true); return; } - MainUtil - .sendMessage(player, Captions.TELEPORT_IN_SECONDS, Settings.Teleport.DELAY + ""); + MainUtil.sendMessage(player, Captions.TELEPORT_IN_SECONDS, Settings.Teleport.DELAY + ""); final String name = player.getName(); TaskManager.addToTeleportQueue(name); TaskManager.runTaskLater(() -> { @@ -3103,7 +3016,8 @@ public class Plot { try { MainUtil.sendMessage(player, Captions.TELEPORTED_TO_PLOT); player.teleport(location, cause); - } catch (final Exception ignored) {} + } catch (final Exception ignored) { + } }, TaskTime.seconds(Settings.Teleport.DELAY)); resultConsumer.accept(true); }; @@ -3124,12 +3038,11 @@ public class Plot { return false; } if (!isMerged()) { - return PlotSquared.platform().getPlayerManager() - .getPlayerIfExists(Objects.requireNonNull(this.getOwnerAbs())) != null; + return PlotSquared.platform().getPlayerManager().getPlayerIfExists(Objects.requireNonNull(this.getOwnerAbs())) != null; } for (final Plot current : getConnectedPlots()) { - if (current.hasOwner() && PlotSquared.platform().getPlayerManager() - .getPlayerIfExists(Objects.requireNonNull(current.getOwnerAbs())) != null) { + if (current.hasOwner() + && PlotSquared.platform().getPlayerManager().getPlayerIfExists(Objects.requireNonNull(current.getOwnerAbs())) != null) { return true; } } @@ -3145,10 +3058,8 @@ public class Plot { * @param blocks Pattern to use the generation * @return True if the component was set successfully */ - public boolean setComponent(String component, Pattern blocks, - @Nullable QueueCoordinator queue) { - PlotComponentSetEvent event = - this.eventDispatcher.callComponentSet(this, component, blocks); + public boolean setComponent(String component, Pattern blocks, @Nullable QueueCoordinator queue) { + PlotComponentSetEvent event = this.eventDispatcher.callComponentSet(this, component, blocks); component = event.getComponent(); blocks = event.getPattern(); return this.getManager().setComponent(this.getId(), component, blocks, queue); @@ -3157,8 +3068,7 @@ public class Plot { public int getDistanceFromOrigin() { Location bot = getManager().getPlotBottomLocAbs(id); Location top = getManager().getPlotTopLocAbs(id); - return Math.max(Math.max(Math.abs(bot.getX()), Math.abs(bot.getZ())), - Math.max(Math.abs(top.getX()), Math.abs(top.getZ()))); + return Math.max(Math.max(Math.abs(bot.getX()), Math.abs(bot.getZ())), Math.max(Math.abs(top.getX()), Math.abs(top.getZ()))); } /** @@ -3246,10 +3156,8 @@ public class Plot { * @param allowSwap whether to swap plots * @return success */ - public CompletableFuture move(final Plot destination, final Runnable whenDone, - boolean allowSwap) { - final PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(), - destination.getId().getY() - this.getId().getY()); + public CompletableFuture move(final Plot destination, final Runnable whenDone, boolean allowSwap) { + final PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(), destination.getId().getY() - this.getId().getY()); Location db = destination.getBottomAbs(); Location ob = this.getBottomAbs(); final int offsetX = db.getX() - ob.getX(); @@ -3315,8 +3223,7 @@ public class Plot { Location[] corners = getCorners(getWorldName(), region); Location pos1 = corners[0]; Location pos2 = corners[1]; - Location pos3 = - pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); + Location pos3 = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); regionManager.swap(pos1, pos2, pos3, this); } } @@ -3326,8 +3233,7 @@ public class Plot { @Override public void run() { if (regions.isEmpty()) { Plot plot = destination.getRelative(0, 0); - Plot originPlot = originArea - .getPlotAbs(PlotId.of(plot.id.getX() - offset.getX(), plot.id.getY() - offset.getY())); + Plot originPlot = originArea.getPlotAbs(PlotId.of(plot.id.getX() - offset.getX(), plot.id.getY() - offset.getY())); final Runnable clearDone = () -> { for (final Plot current : plot.getConnectedPlots()) { getManager().claimPlot(current); @@ -3347,8 +3253,7 @@ public class Plot { Location[] corners = getCorners(getWorldName(), region); final Location pos1 = corners[0]; final Location pos2 = corners[1]; - Location newPos = - pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); + Location newPos = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); regionManager.copyRegion(pos1, pos2, newPos, task); } }.run(); @@ -3365,8 +3270,7 @@ public class Plot { * @return */ public boolean copy(final Plot destination, final Runnable whenDone) { - PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(), - destination.getId().getY() - this.getId().getY()); + PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(), destination.getId().getY() - this.getId().getY()); Location db = destination.getBottomAbs(); Location ob = this.getBottomAbs(); final int offsetX = db.getX() - ob.getX(); @@ -3395,8 +3299,7 @@ public class Plot { other.getFlagContainer().addAll(plot.getFlagContainer().getFlagMap().values()); // Update the database for (final PlotFlag flag : existingFlags) { - final PlotFlag newFlag = - other.getFlagContainer().queryLocal(flag.getClass()); + final PlotFlag newFlag = other.getFlagContainer().queryLocal(flag.getClass()); if (other.getFlagContainer().queryLocal(flag.getClass()) == null) { DBFunc.removeFlag(other, flag); } else { @@ -3442,8 +3345,7 @@ public class Plot { Location[] corners = getCorners(getWorldName(), region); Location pos1 = corners[0]; Location pos2 = corners[1]; - Location newPos = - pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); + Location newPos = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); regionManager.copyRegion(pos1, pos2, newPos, this); } }; @@ -3506,112 +3408,102 @@ public class Plot { int num = this.getConnectedPlots().size(); String alias = !this.getAlias().isEmpty() ? this.getAlias() : Captions.NONE.getTranslated(); Location bot = this.getCorners()[0]; - PlotSquared.platform().getWorldUtil() - .getBiome(this.getWorldName(), bot.getX(), bot.getZ(), biome -> { - String info = iInfo; - String trusted = PlayerManager.getPlayerList(this.getTrusted()); - String members = PlayerManager.getPlayerList(this.getMembers()); - String denied = PlayerManager.getPlayerList(this.getDenied()); - String seen; - if (Settings.Enabled_Components.PLOT_EXPIRY && ExpireManager.IMP != null) { - if (this.isOnline()) { - seen = Captions.NOW.getTranslated(); + PlotSquared.platform().getWorldUtil().getBiome(this.getWorldName(), bot.getX(), bot.getZ(), biome -> { + String info = iInfo; + String trusted = PlayerManager.getPlayerList(this.getTrusted()); + String members = PlayerManager.getPlayerList(this.getMembers()); + String denied = PlayerManager.getPlayerList(this.getDenied()); + String seen; + if (Settings.Enabled_Components.PLOT_EXPIRY && ExpireManager.IMP != null) { + if (this.isOnline()) { + seen = Captions.NOW.getTranslated(); + } else { + int time = (int) (ExpireManager.IMP.getAge(this) / 1000); + if (time != 0) { + seen = TimeUtil.secToTime(time); } else { - int time = (int) (ExpireManager.IMP.getAge(this) / 1000); - if (time != 0) { - seen = TimeUtil.secToTime(time); - } else { - seen = Captions.UNKNOWN.getTranslated(); - } - } - } else { - seen = Captions.NEVER.getTranslated(); - } - - String description = this.getFlag(DescriptionFlag.class); - if (description.isEmpty()) { - description = Captions.PLOT_NO_DESCRIPTION.getTranslated(); - } - - StringBuilder flags = new StringBuilder(); - Collection> flagCollection = this.getApplicableFlags(true); - if (flagCollection.isEmpty()) { - flags.append(Captions.NONE.getTranslated()); - } else { - String prefix = " "; - for (final PlotFlag flag : flagCollection) { - Object value; - if (flag instanceof DoubleFlag && !Settings.General.SCIENTIFIC) { - value = FLAG_DECIMAL_FORMAT.format(flag.getValue()); - } else { - value = flag.toString(); - } - flags.append(prefix).append(CaptionUtility - .format(player, Captions.PLOT_FLAG_LIST.getTranslated(), flag.getName(), - CaptionUtility.formatRaw(player, value.toString(), ""))); - prefix = ", "; + seen = Captions.UNKNOWN.getTranslated(); } } - boolean build = this.isAdded(player.getUUID()); - String owner = this.getOwners().isEmpty() ? "unowned" : PlayerManager.getPlayerList(this.getOwners()); - if (this.getArea() != null) { - info = info.replace("%area%", - this.getArea().getWorldName() + (this.getArea().getId() == null ? - "" : - "(" + this.getArea().getId() + ")")); - } else { - info = info.replace("%area%", Captions.NONE.getTranslated()); + } else { + seen = Captions.NEVER.getTranslated(); + } + + String description = this.getFlag(DescriptionFlag.class); + if (description.isEmpty()) { + description = Captions.PLOT_NO_DESCRIPTION.getTranslated(); + } + + StringBuilder flags = new StringBuilder(); + Collection> flagCollection = this.getApplicableFlags(true); + if (flagCollection.isEmpty()) { + flags.append(Captions.NONE.getTranslated()); + } else { + String prefix = " "; + for (final PlotFlag flag : flagCollection) { + Object value; + if (flag instanceof DoubleFlag && !Settings.General.SCIENTIFIC) { + value = FLAG_DECIMAL_FORMAT.format(flag.getValue()); + } else { + value = flag.toString(); + } + flags.append(prefix).append(CaptionUtility.format(player, Captions.PLOT_FLAG_LIST.getTranslated(), flag.getName(), + CaptionUtility.formatRaw(player, value.toString(), ""))); + prefix = ", "; } - info = info.replace("%id%", this.getId().toString()); - info = info.replace("%alias%", alias); - info = info.replace("%num%", String.valueOf(num)); - info = info.replace("%desc%", description); - info = info.replace("%biome%", biome.toString().toLowerCase()); - info = info.replace("%owner%", owner); - info = info.replace("%members%", members); - info = info.replace("%player%", player.getName()); - info = info.replace("%trusted%", trusted); - info = info.replace("%helpers%", members); - info = info.replace("%denied%", denied); - info = info.replace("%seen%", seen); - info = info.replace("%flags%", flags); - info = info.replace("%build%", String.valueOf(build)); - if (info.contains("%rating%")) { - final String newInfo = info; - TaskManager.runTaskAsync(() -> { - String info1; - if (Settings.Ratings.USE_LIKES) { - info1 = newInfo.replaceAll("%rating%", - String.format("%.0f%%", Like.getLikesPercentage(this) * 100D)); - } else { - int max = 10; - if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES - .isEmpty()) { - max = 8; - } - if (full && Settings.Ratings.CATEGORIES != null - && Settings.Ratings.CATEGORIES.size() > 1) { - double[] ratings = this.getAverageRatings(); - String rating = ""; - String prefix = ""; - for (int i = 0; i < ratings.length; i++) { - rating += - prefix + Settings.Ratings.CATEGORIES.get(i) + '=' + String - .format("%.1f", ratings[i]); - prefix = ","; - } - info1 = newInfo.replaceAll("%rating%", rating); - } else { - info1 = newInfo.replaceAll("%rating%", - String.format("%.1f", this.getAverageRating()) + '/' + max); - } + } + boolean build = this.isAdded(player.getUUID()); + String owner = this.getOwners().isEmpty() ? "unowned" : PlayerManager.getPlayerList(this.getOwners()); + if (this.getArea() != null) { + info = info.replace("%area%", + this.getArea().getWorldName() + (this.getArea().getId() == null ? "" : "(" + this.getArea().getId() + ")")); + } else { + info = info.replace("%area%", Captions.NONE.getTranslated()); + } + info = info.replace("%id%", this.getId().toString()); + info = info.replace("%alias%", alias); + info = info.replace("%num%", String.valueOf(num)); + info = info.replace("%desc%", description); + info = info.replace("%biome%", biome.toString().toLowerCase()); + info = info.replace("%owner%", owner); + info = info.replace("%members%", members); + info = info.replace("%player%", player.getName()); + info = info.replace("%trusted%", trusted); + info = info.replace("%helpers%", members); + info = info.replace("%denied%", denied); + info = info.replace("%seen%", seen); + info = info.replace("%flags%", flags); + info = info.replace("%build%", String.valueOf(build)); + if (info.contains("%rating%")) { + final String newInfo = info; + TaskManager.runTaskAsync(() -> { + String info1; + if (Settings.Ratings.USE_LIKES) { + info1 = newInfo.replaceAll("%rating%", String.format("%.0f%%", Like.getLikesPercentage(this) * 100D)); + } else { + int max = 10; + if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) { + max = 8; } - future.complete(info1); - }); - return; - } - future.complete(info); - }); + if (full && Settings.Ratings.CATEGORIES != null && Settings.Ratings.CATEGORIES.size() > 1) { + double[] ratings = this.getAverageRatings(); + String rating = ""; + String prefix = ""; + for (int i = 0; i < ratings.length; i++) { + rating += prefix + Settings.Ratings.CATEGORIES.get(i) + '=' + String.format("%.1f", ratings[i]); + prefix = ","; + } + info1 = newInfo.replaceAll("%rating%", rating); + } else { + info1 = newInfo.replaceAll("%rating%", String.format("%.1f", this.getAverageRating()) + '/' + max); + } + } + future.complete(info1); + }); + return; + } + future.complete(info); + }); return future; } diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java b/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java index b42c66e19..8a1413a35 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java @@ -32,6 +32,7 @@ import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.FileBytes; import com.sk89q.worldedit.function.pattern.Pattern; +import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.Collections; @@ -42,7 +43,7 @@ public abstract class PlotManager { private final PlotArea plotArea; - public PlotManager(PlotArea plotArea) { + public PlotManager(@Nonnull PlotArea plotArea) { this.plotArea = plotArea; } @@ -55,35 +56,33 @@ public abstract class PlotManager { public abstract PlotId getPlotId(int x, int y, int z); // If you have a circular plot, just return the corner if it were a square - public abstract Location getPlotBottomLocAbs(PlotId plotId); + public abstract Location getPlotBottomLocAbs(@Nonnull PlotId plotId); // 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) */ - public boolean clearPlot(Plot plot, Runnable whenDone) { + public boolean clearPlot(@Nonnull Plot plot, @Nullable Runnable whenDone) { return clearPlot(plot, whenDone, null); } - public boolean claimPlot(Plot plot) { + public boolean claimPlot(@Nonnull Plot plot) { 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); } - public abstract boolean clearPlot(Plot plot, Runnable whenDone, - @Nullable QueueCoordinator queue); + public abstract boolean clearPlot(@Nonnull Plot plot, @Nullable Runnable whenDone, @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, - @Nullable QueueCoordinator queue); + public abstract boolean unClaimPlot(@Nonnull Plot plot, @Nullable Runnable whenDone, @Nullable QueueCoordinator queue); /** * Retrieves the location of where a sign should be for a plot. @@ -91,90 +90,90 @@ public abstract class PlotManager { * @param plot The plot * @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 * 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); } - public abstract boolean setComponent(PlotId plotId, String component, Pattern blocks, - @Nullable QueueCoordinator queue); + public abstract boolean setComponent(@Nonnull PlotId plotId, + @Nonnull String component, + @Nonnull Pattern blocks, + @Nullable QueueCoordinator queue); /* * PLOT MERGING (return false if your generator does not support plot * merging). */ - public boolean createRoadEast(Plot plot) { + public boolean createRoadEast(@Nonnull Plot plot) { return createRoadEast(plot, null); } - public boolean createRoadSouth(Plot plot) { + public boolean createRoadSouth(@Nonnull Plot plot) { return createRoadSouth(plot, null); } - public boolean createRoadSouthEast(Plot plot) { + public boolean createRoadSouthEast(@Nonnull Plot plot) { return createRoadSouthEast(plot, null); } - public boolean removeRoadEast(Plot plot) { + public boolean removeRoadEast(@Nonnull Plot plot) { return removeRoadEast(plot, null); } - public boolean removeRoadSouth(Plot plot) { + public boolean removeRoadSouth(@Nonnull Plot plot) { return removeRoadSouth(plot, null); } - public boolean removeRoadSouthEast(Plot plot) { + public boolean removeRoadSouthEast(@Nonnull Plot plot) { return removeRoadSouthEast(plot, null); } - public boolean startPlotMerge(List plotIds) { + public boolean startPlotMerge(@Nonnull List plotIds) { return startPlotMerge(plotIds, null); } - public boolean startPlotUnlink(List plotIds) { + public boolean startPlotUnlink(@Nonnull List plotIds) { return startPlotUnlink(plotIds, null); } - public boolean finishPlotMerge(List plotIds) { + public boolean finishPlotMerge(@Nonnull List plotIds) { return finishPlotMerge(plotIds, null); } - public boolean finishPlotUnlink(List plotIds) { + public boolean finishPlotUnlink(@Nonnull List plotIds) { 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 plotIds, @Nullable QueueCoordinator queue); + public abstract boolean startPlotMerge(@Nonnull List plotIds, @Nullable QueueCoordinator queue); - public abstract boolean startPlotUnlink(List plotIds, @Nullable QueueCoordinator queue); + public abstract boolean startPlotUnlink(@Nonnull List plotIds, @Nullable QueueCoordinator queue); - public abstract boolean finishPlotMerge(List plotIds, @Nullable QueueCoordinator queue); + public abstract boolean finishPlotMerge(@Nonnull List plotIds, @Nullable QueueCoordinator queue); - public abstract boolean finishPlotUnlink(List plotIds, - @Nullable QueueCoordinator queue); + public abstract boolean finishPlotUnlink(@Nonnull List plotIds, @Nullable QueueCoordinator queue); public void exportTemplate() throws IOException { - HashSet files = new HashSet<>(Collections.singletonList( - new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", - Template.getBytes(plotArea)))); + HashSet files = + new HashSet<>(Collections.singletonList(new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", Template.getBytes(plotArea)))); Template.zipAll(plotArea.getWorldName(), files); } diff --git a/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java b/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java index f35f164ee..cffa305a1 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java @@ -35,6 +35,7 @@ import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.FileUtils; import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.function.pattern.Pattern; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -55,19 +56,17 @@ public class SinglePlotManager extends PlotManager { 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); } - @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); } - @Override - public boolean clearPlot(Plot plot, final Runnable whenDone, @Nullable QueueCoordinator queue) { + @Override public boolean clearPlot(@NotNull Plot plot, final Runnable whenDone, @Nullable QueueCoordinator queue) { PlotSquared.platform().getSetupUtils().unload(plot.getWorldName(), false); - final File worldFolder = - new File(PlotSquared.platform().getWorldContainer(), plot.getWorldName()); + final File worldFolder = new File(PlotSquared.platform().getWorldContainer(), plot.getWorldName()); TaskManager.getPlatformImplementation().taskAsync(() -> { FileUtils.deleteDirectory(worldFolder); if (whenDone != null) { @@ -77,73 +76,68 @@ public class SinglePlotManager extends PlotManager { return true; } - @Override public boolean claimPlot(Plot plot, @Nullable QueueCoordinator queue) { + @Override public boolean claimPlot(@NotNull Plot plot, @Nullable QueueCoordinator queue) { // TODO return true; } - @Override - public boolean unClaimPlot(Plot plot, Runnable whenDone, @Nullable QueueCoordinator queue) { + @Override public boolean unClaimPlot(@NotNull Plot plot, Runnable whenDone, @Nullable QueueCoordinator queue) { if (whenDone != null) { whenDone.run(); } return true; } - @Override public Location getSignLoc(Plot plot) { + @Override public Location getSignLoc(@NotNull Plot plot) { return null; } - @Override public String[] getPlotComponents(PlotId plotId) { + @Override public String[] getPlotComponents(@NotNull PlotId plotId) { 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 - public boolean startPlotMerge(List plotIds, @Nullable QueueCoordinator queue) { + public boolean setComponent(@NotNull PlotId plotId, @NotNull String component, @NotNull Pattern blocks, @Nullable QueueCoordinator queue) { return false; } - @Override - public boolean startPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean createRoadEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) { return false; } - @Override - public boolean finishPlotMerge(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean createRoadSouth(@NotNull Plot plot, @Nullable QueueCoordinator queue) { return false; } - @Override - public boolean finishPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean createRoadSouthEast(@NotNull Plot plot, @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 plotIds, @Nullable QueueCoordinator queue) { + return false; + } + + @Override public boolean startPlotUnlink(@NotNull List plotIds, @Nullable QueueCoordinator queue) { + return false; + } + + @Override public boolean finishPlotMerge(@NotNull List plotIds, @Nullable QueueCoordinator queue) { + return false; + } + + @Override public boolean finishPlotUnlink(@NotNull List plotIds, @Nullable QueueCoordinator queue) { return false; } diff --git a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java index 87fe6d634..beb1ae0ea 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java @@ -40,8 +40,7 @@ public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator private final PlotArea area; - public AreaBoundDelegateQueueCoordinator(@Nonnull final PlotArea area, - @Nullable final QueueCoordinator parent) { + public AreaBoundDelegateQueueCoordinator(@Nonnull final PlotArea area, @Nullable final QueueCoordinator parent) { super(parent); this.area = Objects.requireNonNull(area); } @@ -50,42 +49,42 @@ public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator 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)) { return super.setBlock(x, y, z, id); } 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)) { return super.setBlock(x, y, z, id); } 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)) { return super.setBlock(x, y, z, pattern); } 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)) { return super.setBiome(x, z, biome); } 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)) { return super.setBiome(x, y, z, biome); } 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)) { return super.setTile(x, y, z, tag); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index 3e00deee5..8a4ae98ec 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -48,8 +48,7 @@ import java.util.function.Consumer; public abstract class BasicQueueCoordinator extends QueueCoordinator { private final World world; - private final ConcurrentHashMap blockChunks = - new ConcurrentHashMap<>(); + private final ConcurrentHashMap blockChunks = new ConcurrentHashMap<>(); private final List readRegion = new ArrayList<>(); private long modified; private LocalChunk lastWrappedChunk; @@ -63,16 +62,15 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { private CuboidRegion regenRegion = null; private Consumer consumer = null; private boolean unloadAfter = true; - private GlobalBlockQueue globalBlockQueue; - public BasicQueueCoordinator(World world) { + public BasicQueueCoordinator(@Nonnull World world) { this.world = world; this.modified = System.currentTimeMillis(); } @Override public abstract BlockState getBlock(int x, int y, int z); - @Override public final World getWorld() { + @Override public final @Nonnull World getWorld() { return world; } @@ -88,7 +86,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { 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)) { return false; } @@ -97,14 +95,14 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { 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. // Since BaseBlock has more features than BlockState, simply convert // all BlockStates to BaseBlocks 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); for (int y = 0; y < 256; y++) { chunk.setBiome(x & 15, y, z & 15, biomeType); @@ -113,7 +111,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { 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); chunk.setBiome(x & 15, y, z & 15, biomeType); settingBiomes = true; @@ -124,7 +122,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { 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); chunk.setTile(x, y, z, tag); settingTiles = true; @@ -135,7 +133,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { 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) { return false; } @@ -145,15 +143,15 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return true; } - @Override public List getReadChunks() { + @Override public @Nonnull List getReadChunks() { return this.readRegion; } - @Override public void addReadChunk(BlockVector2 chunk) { + @Override public void addReadChunk(@Nonnull BlockVector2 chunk) { this.readRegion.add(chunk); } - @Override public void addReadChunks(Set readRegion) { + @Override public void addReadChunks(@Nonnull Set readRegion) { this.readRegion.addAll(readRegion); } @@ -161,7 +159,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return this.regenRegion != null ? this.regenRegion.clone() : null; } - @Override public void setRegenRegion(CuboidRegion regenRegion) { + @Override public void setRegenRegion(@Nonnull CuboidRegion regenRegion) { this.regenRegion = regenRegion; } @@ -219,7 +217,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return this.consumer; } - public final void setChunkConsumer(Consumer consumer) { + public final void setChunkConsumer(@Nonnull Consumer consumer) { this.consumer = consumer; } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java index 980e8ee78..2eac2ba2b 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java @@ -53,8 +53,7 @@ public class ChunkCoordinatorBuilder { private int initialBatchSize = 4; private boolean unloadAfter = true; - @Inject - public ChunkCoordinatorBuilder(@Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory) { + @Inject public ChunkCoordinatorBuilder(@Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory) { this.chunkCoordinatorFactory = chunkCoordinatorFactory; } @@ -64,18 +63,16 @@ public class ChunkCoordinatorBuilder { } @Nonnull public ChunkCoordinatorBuilder withChunk(@Nonnull final BlockVector2 chunkLocation) { - this.requestedChunks - .add(Preconditions.checkNotNull(chunkLocation, "Chunk location may not be null")); + this.requestedChunks.add(Preconditions.checkNotNull(chunkLocation, "Chunk location may not be null")); return this; } - @Nonnull public ChunkCoordinatorBuilder withChunks( - @Nonnull final Collection chunkLocations) { + @Nonnull public ChunkCoordinatorBuilder withChunks(@Nonnull final Collection chunkLocations) { chunkLocations.forEach(this::withChunk); 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 p1z = pos1.getZ(); final int p2x = pos2.getX(); @@ -96,10 +93,8 @@ public class ChunkCoordinatorBuilder { return this; } - @Nonnull public ChunkCoordinatorBuilder withConsumer( - @Nonnull final Consumer chunkConsumer) { - this.chunkConsumer = - Preconditions.checkNotNull(chunkConsumer, "Chunk consumer may not be null"); + @Nonnull public ChunkCoordinatorBuilder withConsumer(@Nonnull final Consumer chunkConsumer) { + this.chunkConsumer = Preconditions.checkNotNull(chunkConsumer, "Chunk consumer may not be null"); return this; } @@ -123,10 +118,8 @@ public class ChunkCoordinatorBuilder { return this; } - @Nonnull public ChunkCoordinatorBuilder withThrowableConsumer( - @Nonnull final Consumer throwableConsumer) { - this.throwableConsumer = - Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null"); + @Nonnull public ChunkCoordinatorBuilder withThrowableConsumer(@Nonnull final Consumer throwableConsumer) { + this.throwableConsumer = Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null"); return this; } @@ -141,8 +134,8 @@ public class ChunkCoordinatorBuilder { Preconditions.checkNotNull(this.whenDone, "No final action was supplied"); Preconditions.checkNotNull(this.throwableConsumer, "No throwable consumer was supplied"); return chunkCoordinatorFactory - .create(this.maxIterationTime, this.initialBatchSize, this.chunkConsumer, this.world, - this.requestedChunks, this.whenDone, this.throwableConsumer, this.unloadAfter); + .create(this.maxIterationTime, this.initialBatchSize, this.chunkConsumer, this.world, this.requestedChunks, this.whenDone, + this.throwableConsumer, this.unloadAfter); } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java index 820cffa61..f03c8f25c 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java @@ -45,7 +45,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { private final BlockVector3 bot; 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)); this.width = top.getX() - bot.getX() + 1; this.length = top.getZ() - bot.getZ() + 1; @@ -55,11 +55,11 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { this.top = top; } - public BlockState[][][] getBlocks() { + @Nonnull public BlockState[][][] getBlocks() { 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) { for (int y = 0; y < 256; y++) { this.storeCacheBiome(x, y, z, biomeType); @@ -69,7 +69,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { 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) { this.storeCacheBiome(x, y, z, biomeType); return true; @@ -77,17 +77,17 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { 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); 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()); 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]; if (resultY == null) { result[y] = resultY = new BlockState[length][]; @@ -99,7 +99,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { 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]; if (resultY == null) { biomeResult[y] = resultY = new BiomeType[length][]; @@ -111,7 +111,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { 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()); return true; } @@ -131,11 +131,11 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { return super.getWorld(); } - @Override public Location getMax() { + @Override @Nonnull public Location getMax() { 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()); } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index 23af47151..86a21c874 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -34,7 +34,11 @@ import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import org.jetbrains.annotations.NotNull; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; import java.util.List; import java.util.Set; 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) { return parent.setBlock(x, y, z, pattern); } 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) { return parent.setBlock(x, y, z, id); } 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) { return parent.setBlock(x, y, z, id); } 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) { return parent.getBlock(x, y, z); } 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) { return parent.setBiome(x, z, biome); } 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) { return parent.setBiome(x, y, z, biome); } @@ -117,7 +121,7 @@ public class DelegateQueueCoordinator extends QueueCoordinator { return false; } - @Override public boolean setEntity(Entity entity) { + @Override public boolean setEntity(@Nonnull Entity entity) { if (parent != null) { 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) { return parent.getWorld(); } 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) { return parent.setTile(x, y, z, tag); } @@ -176,26 +180,26 @@ public class DelegateQueueCoordinator extends QueueCoordinator { } } - @Override public void setChunkConsumer(Consumer consumer) { + @Override public void setChunkConsumer(@Nonnull Consumer consumer) { if (parent != null) { parent.setChunkConsumer(consumer); } } - @Override public List getReadChunks() { + @Override @Nonnull public List getReadChunks() { if (parent != null) { return parent.getReadChunks(); } - return null; + return new ArrayList<>(); } - @Override public void addReadChunks(Set readChunks) { + @Override public void addReadChunks(@Nonnull Set readChunks) { if (parent != null) { parent.addReadChunks(readChunks); } } - @Override public void addReadChunk(BlockVector2 chunk) { + @Override public void addReadChunk(@Nonnull BlockVector2 chunk) { if (parent != null) { parent.addReadChunk(chunk); } @@ -214,14 +218,14 @@ public class DelegateQueueCoordinator extends QueueCoordinator { } } - @Override public CuboidRegion getRegenRegion() { + @Override @Nullable public CuboidRegion getRegenRegion() { if (parent != null) { return parent.getRegenRegion(); } return null; } - @Override public void setRegenRegion(CuboidRegion regenRegion) { + @Override public void setRegenRegion(@Nonnull CuboidRegion regenRegion) { if (parent != null) { parent.setRegenRegion(regenRegion); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java index e5d69406e..23385bd65 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java @@ -28,6 +28,7 @@ package com.plotsquared.core.queue; import com.plotsquared.core.PlotSquared; import com.sk89q.worldedit.world.World; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; @@ -37,12 +38,12 @@ public class GlobalBlockQueue { private final ConcurrentLinkedDeque activeQueues; private QueueProvider provider; - public GlobalBlockQueue(QueueProvider provider) { + public GlobalBlockQueue(@Nonnull QueueProvider provider) { this.provider = provider; this.activeQueues = new ConcurrentLinkedDeque<>(); } - public QueueCoordinator getNewQueue(World world) { + @Nonnull public QueueCoordinator getNewQueue(@Nonnull World world) { QueueCoordinator queue = provider.getNewQueue(world); // Auto-inject into the queue PlotSquared.platform().getInjector().injectMembers(queue); @@ -53,7 +54,7 @@ public class GlobalBlockQueue { return this.provider; } - public void setQueueProvider(QueueProvider provider) { + public void setQueueProvider(@Nonnull QueueProvider provider) { this.provider = provider; } @@ -64,7 +65,7 @@ public class GlobalBlockQueue { * @param queue {@link QueueCoordinator} instance to start. * @return true if added to queue, false otherwise */ - public boolean enqueue(QueueCoordinator queue) { + public boolean enqueue(@Nonnull QueueCoordinator queue) { boolean success = false; if (queue.size() > 0 && !activeQueues.contains(queue)) { success = activeQueues.add(queue); @@ -73,12 +74,12 @@ public class GlobalBlockQueue { return success; } - public void dequeue(QueueCoordinator queue) { + public void dequeue(@Nonnull QueueCoordinator queue) { queue.cancel(); activeQueues.remove(queue); } - public List getActiveQueues() { + @Nonnull public List getActiveQueues() { return new ArrayList<>(activeQueues); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java index 59a10f943..999f36ccb 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java @@ -34,6 +34,7 @@ import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; +import javax.annotation.Nonnull; import java.util.HashMap; public class LocalChunk { @@ -46,7 +47,7 @@ public class LocalChunk { private final HashMap tiles = new HashMap<>(); private final HashMap entities = new HashMap<>(); - public LocalChunk(QueueCoordinator parent, int x, int z) { + public LocalChunk(@Nonnull QueueCoordinator parent, int x, int z) { this.parent = parent; this.x = x; this.z = z; @@ -54,7 +55,7 @@ public class LocalChunk { biomes = new BiomeType[16][]; } - public QueueCoordinator getParent() { + @Nonnull public QueueCoordinator getParent() { return this.parent; } @@ -66,19 +67,19 @@ public class LocalChunk { return this.z; } - public BaseBlock[][] getBaseblocks() { + @Nonnull public BaseBlock[][] getBaseblocks() { return this.baseblocks; } - public BiomeType[][] getBiomes() { + @Nonnull public BiomeType[][] getBiomes() { return this.biomes; } - public HashMap getTiles() { + @Nonnull public HashMap getTiles() { 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 j = ChunkUtil.getJ(x, y, z); BiomeType[] array = this.biomes[i]; @@ -92,7 +93,7 @@ public class LocalChunk { 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 j = ChunkUtil.getJ(x, y, z); BaseBlock[] array = baseblocks[i]; @@ -102,15 +103,15 @@ public class LocalChunk { 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); } - public void setEntity(Location location, BaseEntity entity) { + public void setEntity(@Nonnull Location location, @Nonnull BaseEntity entity) { this.entities.put(location, entity); } - public HashMap getEntities() { + @Nonnull public HashMap getEntities() { return this.entities; } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java index e9766a53c..c2f95a875 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java @@ -32,6 +32,7 @@ import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import javax.annotation.Nonnull; import javax.annotation.Nullable; public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordinator { @@ -40,22 +41,14 @@ public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordin private final int blockX; private final int blockZ; - public LocationOffsetDelegateQueueCoordinator(final boolean[][] canPlace, final int blockX, - final int blockZ, @Nullable QueueCoordinator parent) { + public LocationOffsetDelegateQueueCoordinator(final boolean[][] canPlace, final int blockX, final int blockZ, @Nullable QueueCoordinator parent) { super(parent); this.canPlace = canPlace; this.blockX = blockX; this.blockZ = blockZ; } - @Override public boolean setBlock(int x, int y, int z, BlockState id) { - if (canPlace[x - blockX][z - blockZ]) { - return super.setBlock(x, y, z, id); - } - return false; - } - - @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) { try { if (canPlace[x - blockX][z - blockZ]) { return super.setBlock(x, y, z, id); @@ -66,20 +59,49 @@ public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordin 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); return this.setBlock(x, y, z, pattern.apply(blockVector3)); } - @Override public boolean setBiome(int x, int z, BiomeType biome) { - return super.setBiome(x, z, biome); + @Override public boolean setBiome(int x, int z, @Nonnull BiomeType 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) { - return super.setBiome(x, y, z, 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); + } + } catch (final Exception e) { + throw e; + } + return false; } - @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { - return super.setTile(x, y, z, 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); + } + } catch (final Exception e) { + throw e; + } + return false; } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java index e69ea308b..c352efd4c 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java @@ -30,35 +30,37 @@ import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; +import javax.annotation.Nonnull; + public class OffsetQueueCoordinator extends DelegateQueueCoordinator { private final int ox; private final int oy; 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); this.ox = ox; this.oy = oy; 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); } - @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); } - @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); } - @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); } - @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); } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index f3b0f63c1..0dc596cb6 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -38,7 +38,6 @@ import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -80,7 +79,7 @@ public abstract class QueueCoordinator { return chunkObject; } - public void setChunkObject(@NotNull Object chunkObject) { + public void setChunkObject(@Nonnull Object chunkObject) { this.chunkObject = chunkObject; } @@ -92,51 +91,51 @@ public abstract class QueueCoordinator { * @param z the z coordinate from 0 to 15 inclusive * @param id the id to set the block to */ - public abstract boolean setBlock(final int x, final int y, final int z, final 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) { 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 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 void addEntities(List entities) { + public void addEntities(@Nonnull List entities) { for (Entity e : entities) { this.setEntity(e); } } - public abstract boolean setEntity(Entity entity); + public abstract boolean setEntity(@Nonnull Entity entity); - public abstract List getReadChunks(); + @Nonnull public abstract List getReadChunks(); - public abstract void addReadChunks(Set readChunks); + public abstract void addReadChunks(@Nonnull Set readChunks); - public abstract void addReadChunk(BlockVector2 chunk); + public abstract void addReadChunk(@Nonnull BlockVector2 chunk); public abstract boolean isUnloadAfter(); 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 World getWorld(); + @Nullable public abstract World getWorld(); public final void setModified() { setModified(System.currentTimeMillis()); @@ -150,11 +149,11 @@ public abstract class QueueCoordinator { public abstract void cancel(); - public abstract void setCompleteTask(Runnable whenDone); + public abstract void setCompleteTask(@Nullable Runnable whenDone); - public abstract void setChunkConsumer(Consumer consumer); + public abstract void setChunkConsumer(@Nonnull Consumer 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 yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); 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 yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); 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 yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); int xMin = Math.min(pos1.getX(), pos2.getX()); diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java index 4c234b0c7..412883f0b 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java @@ -27,11 +27,13 @@ package com.plotsquared.core.queue; import com.sk89q.worldedit.world.World; +import javax.annotation.Nonnull; + public abstract class QueueProvider { - public static QueueProvider of(final Class primary) { + public static QueueProvider of(@Nonnull final Class primary) { return new QueueProvider() { - @Override public QueueCoordinator getNewQueue(World world) { + @Override public QueueCoordinator getNewQueue(@Nonnull World world) { try { return (QueueCoordinator) primary.getConstructors()[0].newInstance(world); } catch (Throwable e) { @@ -42,5 +44,5 @@ public abstract class QueueProvider { }; } - public abstract QueueCoordinator getNewQueue(World world); + public abstract QueueCoordinator getNewQueue(@Nonnull World world); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java index 6a4589b4f..396119763 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java @@ -32,6 +32,9 @@ import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + public class ScopedQueueCoordinator extends DelegateQueueCoordinator { private final int minX; private final int minY; @@ -45,7 +48,7 @@ public class ScopedQueueCoordinator extends DelegateQueueCoordinator { private final int dy; 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); this.minX = min.getX(); this.minY = min.getY(); @@ -60,13 +63,12 @@ public class ScopedQueueCoordinator extends DelegateQueueCoordinator { 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); } - @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { - return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super - .setBiome(x + minX, y + minY, z + minZ, 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.setBiome(x + minX, y + minY, z + minZ, 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) { - return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super - .setBlock(x + minX, y + minY, z + minZ, 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.setBlock(x + minX, y + minY, z + minZ, id); } - @Override public boolean setBlock(int x, int y, int z, BlockState id) { - return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super - .setBlock(x + minX, y + minY, z + minZ, id); + @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.setBlock(x + minX, y + minY, z + minZ, id); } - @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { - return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super - .setBlock(x + minX, y + minY, z + minZ, 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.setBlock(x + minX, y + minY, z + minZ, pattern); } - @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { - return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super - .setTile(x + minX, y + minY, z + minZ, 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.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); } - public Location getMax() { + @Nonnull public Location getMax() { return Location.at(this.getWorld().getName(), this.maxX, this.maxY, this.maxZ); } diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java index d9bfb4cd3..91d7a282f 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java @@ -38,22 +38,19 @@ import java.util.concurrent.ConcurrentHashMap; public abstract class ChunkManager { - private static final Map> forceChunks = - new ConcurrentHashMap<>(); - private static final Map> addChunks = - new ConcurrentHashMap<>(); + private static final Map> forceChunks = new ConcurrentHashMap<>(); + private static final Map> addChunks = new ConcurrentHashMap<>(); public static void setChunkInPlotArea(RunnableVal force, - RunnableVal add, String world, BlockVector2 loc) { - QueueCoordinator queue = PlotSquared.platform().getGlobalBlockQueue() - .getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); - if (PlotSquared.get().getPlotAreaManager().isAugmented(world) && PlotSquared.get() - .isNonStandardGeneration(world, loc)) { + RunnableVal add, + String world, + BlockVector2 loc) { + QueueCoordinator queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); + if (PlotSquared.get().getPlotAreaManager().isAugmented(world) && PlotSquared.get().isNonStandardGeneration(world, loc)) { int blockX = loc.getX() << 4; int blockZ = loc.getZ() << 4; ScopedQueueCoordinator scoped = - new ScopedQueueCoordinator(queue, Location.at(world, blockX, 0, blockZ), - Location.at(world, blockX + 15, 255, blockZ + 15)); + new ScopedQueueCoordinator(queue, Location.at(world, blockX, 0, blockZ), Location.at(world, blockX + 15, 255, blockZ + 15)); if (force != null) { force.run(scoped); } else { @@ -94,7 +91,6 @@ public abstract class ChunkManager { return false; } - @Deprecated - public abstract CompletableFuture loadChunk(String world, BlockVector2 loc, boolean force); + @Deprecated public abstract CompletableFuture loadChunk(String world, BlockVector2 loc, boolean force); } diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java index d60cb0f6b..c602b1691 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java @@ -30,6 +30,8 @@ import com.sk89q.worldedit.math.BlockVector2; import lombok.experimental.UtilityClass; 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. */ @@ -41,10 +43,10 @@ public class ChunkUtil { * Cache of mapping x,y,z coordinates to the chunk array
* - Used for efficient world generation
*/ - private static short[] x_loc; - private static short[][] y_loc; - private static short[] z_loc; - private static short[][][] CACHE_J = null; + private static final short[] x_loc; + private static final short[][] y_loc; + private static final short[] z_loc; + private static final short[][][] CACHE_J; static { x_loc = new short[4096]; @@ -126,7 +128,7 @@ public class ChunkUtil { * @param chunk BlockVector2 of chunk coordinates * @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 z1 = pos1.getZ(); int x2 = pos2.getX(); diff --git a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java index 537425ba6..e2d6255d8 100644 --- a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java @@ -54,15 +54,13 @@ import java.util.Set; public abstract class RegionManager { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + RegionManager.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + RegionManager.class.getSimpleName()); public static RegionManager manager = null; private final WorldUtil worldUtil; private final GlobalBlockQueue blockQueue; - @Inject - public RegionManager(@Nonnull WorldUtil worldUtil, @Nonnull GlobalBlockQueue blockQueue) { + @Inject public RegionManager(@Nonnull WorldUtil worldUtil, @Nonnull GlobalBlockQueue blockQueue) { this.worldUtil = worldUtil; this.blockQueue = blockQueue; } @@ -83,13 +81,10 @@ public abstract class RegionManager { */ public abstract int[] countEntities(Plot plot); - public void deleteRegionFiles(final String world, final Collection chunks, - final Runnable whenDone) { + public void deleteRegionFiles(final String world, final Collection chunks, final Runnable whenDone) { TaskManager.runTaskAsync(() -> { for (BlockVector2 loc : chunks) { - String directory = - world + File.separator + "region" + File.separator + "r." + loc.getX() + "." - + loc.getZ() + ".mca"; + String directory = world + File.separator + "region" + File.separator + "r." + loc.getX() + "." + loc.getZ() + ".mca"; File file = new File(PlotSquared.platform().getWorldContainer(), directory); logger.info("[P2] - Deleting file: {} (max 1024 chunks)", file.getName()); if (file.exists()) { @@ -100,18 +95,20 @@ public abstract class RegionManager { }); } - public boolean setCuboids(final PlotArea area, final Set regions, - final Pattern blocks, int minY, int maxY, @Nullable QueueCoordinator queue) { + public boolean setCuboids(final PlotArea area, + final Set regions, + final Pattern blocks, + int minY, + int maxY, + @Nullable QueueCoordinator queue) { boolean enqueue = false; if (queue == null) { queue = area.getQueue(); enqueue = true; } for (CuboidRegion region : regions) { - Location pos1 = Location.at(area.getWorldName(), region.getMinimumPoint().getX(), minY, - region.getMinimumPoint().getZ()); - Location pos2 = Location.at(area.getWorldName(), region.getMaximumPoint().getX(), maxY, - region.getMaximumPoint().getZ()); + Location pos1 = Location.at(area.getWorldName(), region.getMinimumPoint().getX(), minY, region.getMinimumPoint().getZ()); + Location pos2 = Location.at(area.getWorldName(), region.getMaximumPoint().getX(), maxY, region.getMaximumPoint().getZ()); queue.setCuboid(pos1, pos2, blocks); } return !enqueue || queue.enqueue(); @@ -136,20 +133,17 @@ public abstract class RegionManager { /** * Copy a region to a new location (in the same world) */ - public boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, - final Runnable whenDone) { + public boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, final Runnable whenDone) { final int relX = newPos.getX() - pos1.getX(); final int relZ = newPos.getZ() - pos1.getZ(); final com.sk89q.worldedit.world.World oldWorld = worldUtil.getWeWorld(pos1.getWorldName()); - final com.sk89q.worldedit.world.World newWorld = - worldUtil.getWeWorld(newPos.getWorldName()); + final com.sk89q.worldedit.world.World newWorld = worldUtil.getWeWorld(newPos.getWorldName()); final QueueCoordinator copyFrom = blockQueue.getNewQueue(oldWorld); - final BasicQueueCoordinator copyTo = - (BasicQueueCoordinator) blockQueue.getNewQueue(newWorld); + final BasicQueueCoordinator copyTo = (BasicQueueCoordinator) blockQueue.getNewQueue(newWorld); copyFromTo(pos1, pos2, relX, relZ, oldWorld, copyFrom, copyTo, false); copyFrom.setCompleteTask(copyTo::enqueue); - copyFrom.addReadChunks(new CuboidRegion(BlockVector3.at(pos1.getX(), 0, pos1.getZ()), - BlockVector3.at(pos2.getX(), 0, pos2.getZ())).getChunks()); + copyFrom + .addReadChunks(new CuboidRegion(BlockVector3.at(pos1.getX(), 0, pos1.getZ()), BlockVector3.at(pos2.getX(), 0, pos2.getZ())).getChunks()); copyTo.setCompleteTask(whenDone); copyFrom.enqueue(); return true; @@ -160,8 +154,7 @@ public abstract class RegionManager { * - pos1 and pos2 are in the same plot
* It can be harmful to the world if parameters outside this scope are provided */ - public abstract boolean regenerateRegion(Location pos1, Location pos2, boolean ignoreAugment, - Runnable whenDone); + public abstract boolean regenerateRegion(Location pos1, Location pos2, boolean ignoreAugment, Runnable whenDone); public abstract void clearAllEntities(Location pos1, Location pos2); @@ -176,11 +169,9 @@ public abstract class RegionManager { QueueCoordinator fromQueue2 = blockQueue.getNewQueue(world2); fromQueue1.setUnloadAfter(false); fromQueue2.setUnloadAfter(false); - fromQueue1.addReadChunks( - new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks()); - fromQueue2.addReadChunks(new CuboidRegion(swapPos.getBlockVector3(), BlockVector3 - .at(swapPos.getX() + pos2.getX() - pos1.getX(), 0, - swapPos.getZ() + pos2.getZ() - pos1.getZ())).getChunks()); + fromQueue1.addReadChunks(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks()); + fromQueue2.addReadChunks(new CuboidRegion(swapPos.getBlockVector3(), + BlockVector3.at(swapPos.getX() + pos2.getX() - pos1.getX(), 0, swapPos.getZ() + pos2.getZ() - pos1.getZ())).getChunks()); QueueCoordinator toQueue1 = blockQueue.getNewQueue(world1); QueueCoordinator toQueue2 = blockQueue.getNewQueue(world2); @@ -192,8 +183,14 @@ public abstract class RegionManager { toQueue2.setCompleteTask(whenDone); } - private void copyFromTo(Location pos1, Location pos2, int relX, int relZ, World world1, - QueueCoordinator fromQueue, QueueCoordinator toQueue, boolean removeEntities) { + private void copyFromTo(Location pos1, + Location pos2, + int relX, + int relZ, + World world1, + QueueCoordinator fromQueue, + QueueCoordinator toQueue, + boolean removeEntities) { fromQueue.setChunkConsumer(chunk -> { int cx = chunk.getX(); int cz = chunk.getZ(); @@ -214,8 +211,7 @@ public abstract class RegionManager { } } } - Region region = new CuboidRegion(BlockVector3.at(cbx + bx, 0, cbz + bz), - BlockVector3.at(cbx + tx, 255, cbz + tz)); + Region region = new CuboidRegion(BlockVector3.at(cbx + bx, 0, cbz + bz), BlockVector3.at(cbx + tx, 255, cbz + tz)); toQueue.addEntities(world1.getEntities(region)); if (removeEntities) { 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, - final String world, final Runnable whenDone) { - Location pos1 = Location.at(world, region.getMinimumPoint().getX() - extendBiome, - region.getMinimumPoint().getY(), region.getMinimumPoint().getZ() - extendBiome); - Location pos2 = Location.at(world, region.getMaximumPoint().getX() + extendBiome, - region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome); + public void setBiome(final CuboidRegion region, final int extendBiome, final BiomeType biome, final String world, final Runnable whenDone) { + Location pos1 = Location + .at(world, region.getMinimumPoint().getX() - extendBiome, region.getMinimumPoint().getY(), region.getMinimumPoint().getZ() - extendBiome); + Location pos2 = Location + .at(world, region.getMaximumPoint().getX() + extendBiome, region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome); final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world)); final int minX = pos1.getX(); @@ -241,9 +236,7 @@ public abstract class RegionManager { queue.setChunkConsumer(blockVector2 -> { final int cx = blockVector2.getX() << 4; final int cz = blockVector2.getZ() << 4; - WorldUtil - .setBiome(world, Math.max(minX, cx), Math.max(minZ, cz), Math.min(maxX, cx + 15), - Math.min(maxZ, cz + 15), biome); + WorldUtil.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); }); queue.setCompleteTask(whenDone); diff --git a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java index 3c8bec5c6..d02284930 100644 --- a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java +++ b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java @@ -105,8 +105,7 @@ import java.util.zip.GZIPOutputStream; public abstract class SchematicHandler { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + SchematicHandler.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + SchematicHandler.class.getSimpleName()); public static SchematicHandler manager; private final WorldUtil worldUtil; private boolean exportAll = false; @@ -115,9 +114,11 @@ public abstract class SchematicHandler { this.worldUtil = worldUtil; } - public static void upload(@Nullable UUID uuid, @Nullable final String file, - @Nonnull final String extension, @Nullable final RunnableVal writeTask, - @Nonnull final RunnableVal whenDone) { + public static void upload(@Nullable UUID uuid, + @Nullable final String file, + @Nonnull final String extension, + @Nullable final RunnableVal writeTask, + @Nonnull final RunnableVal whenDone) { if (writeTask == null) { TaskManager.runTask(whenDone); return; @@ -147,23 +148,16 @@ public abstract class SchematicHandler { con.setDoOutput(true); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try (OutputStream output = con.getOutputStream(); - PrintWriter writer = new PrintWriter( - new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) { + PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) { String CRLF = "\r\n"; writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); - writer.append( - "Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName()) - .append(CRLF); + writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName()).append(CRLF); String param = "value"; writer.append(CRLF).append(param).append(CRLF).flush(); writer.append("--" + boundary).append(CRLF); - writer.append( - "Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" - + filename + '"').append(CRLF); - writer - .append("Content-Type: " + URLConnection.guessContentTypeFromName(filename)) - .append(CRLF); + writer.append("Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" + filename + '"').append(CRLF); + writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(filename)).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); writeTask.value = new AbstractDelegateOutputStream(output) { @@ -193,8 +187,7 @@ public abstract class SchematicHandler { }); } - public boolean exportAll(Collection collection, final File outputDir, - final String namingScheme, final Runnable ifSuccess) { + public boolean exportAll(Collection collection, final File outputDir, final String namingScheme, final Runnable ifSuccess) { if (this.exportAll) { return false; } @@ -223,14 +216,10 @@ public abstract class SchematicHandler { final String name; if (namingScheme == null) { - name = - plot.getId().getX() + ";" + plot.getId().getY() + ',' + plot.getArea() + ',' - + owner; + name = plot.getId().getX() + ";" + plot.getId().getY() + ',' + plot.getArea() + ',' + owner; } else { - name = namingScheme.replaceAll("%id%", plot.getId().toString()) - .replaceAll("%idx%", plot.getId().getX() + "") - .replaceAll("%idy%", plot.getId().getY() + "") - .replaceAll("%world%", plot.getArea().toString()); + name = namingScheme.replaceAll("%id%", plot.getId().toString()).replaceAll("%idx%", plot.getId().getX() + "") + .replaceAll("%idy%", plot.getId().getY() + "").replaceAll("%world%", plot.getArea().toString()); } final String directory; @@ -245,8 +234,7 @@ public abstract class SchematicHandler { @Override public void run(final CompoundTag value) { if (value != null) { TaskManager.runTaskAsync(() -> { - boolean result = - save(value, directory + File.separator + name + ".schem"); + boolean result = save(value, directory + File.separator + name + ".schem"); if (!result) { logger.error("[P2] Failed to save {}", plot.getId()); } @@ -268,9 +256,13 @@ public abstract class SchematicHandler { * @param xOffset offset x 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, - final int yOffset, final int zOffset, final boolean autoHeight, - final RunnableVal whenDone) { + public void paste(final Schematic schematic, + final Plot plot, + final int xOffset, + final int yOffset, + final int zOffset, + final boolean autoHeight, + final RunnableVal whenDone) { TaskManager.runTask(() -> { if (whenDone != null) { @@ -287,10 +279,8 @@ public abstract class SchematicHandler { final int HEIGHT = dimension.getY(); // Validate dimensions CuboidRegion region = plot.getLargestRegion(); - if (((region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + xOffset - + 1) < WIDTH) || ( - (region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + zOffset - + 1) < LENGTH) || (HEIGHT > 256)) { + if (((region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + xOffset + 1) < WIDTH) || ( + (region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + zOffset + 1) < LENGTH) || (HEIGHT > 256)) { TaskManager.runTask(whenDone); return; } @@ -307,8 +297,7 @@ public abstract class SchematicHandler { y_offset_actual = yOffset + ((ClassicPlotWorld) pw).PLOT_HEIGHT; } else { y_offset_actual = yOffset + 1 + this.worldUtil - .getHighestBlockSynchronous(plot.getWorldName(), - region.getMinimumPoint().getX() + 1, + .getHighestBlockSynchronous(plot.getWorldName(), region.getMinimumPoint().getX() + 1, region.getMinimumPoint().getZ() + 1); } } @@ -317,8 +306,7 @@ public abstract class SchematicHandler { } final Location pos1 = Location - .at(plot.getWorldName(), region.getMinimumPoint().getX() + xOffset, - y_offset_actual, region.getMinimumPoint().getZ() + zOffset); + .at(plot.getWorldName(), region.getMinimumPoint().getX() + xOffset, y_offset_actual, region.getMinimumPoint().getZ() + zOffset); final Location pos2 = pos1.add(WIDTH - 1, HEIGHT - 1, LENGTH - 1); final int p1x = pos1.getX(); @@ -341,12 +329,10 @@ public abstract class SchematicHandler { for (int rx = 0; rx < blockArrayClipboard.getDimensions().getX(); rx++) { int xx = p1x + xOffset + rx; int zz = p1z + zOffset + rz; - BaseBlock id = - blockArrayClipboard.getFullBlock(BlockVector3.at(rx, ry, rz)); + BaseBlock id = blockArrayClipboard.getFullBlock(BlockVector3.at(rx, ry, rz)); queue.setBlock(xx, yy, zz, id); if (ry == 0) { - BiomeType biome = - blockArrayClipboard.getBiome(BlockVector3.at(rx, ry, rz)); + BiomeType biome = blockArrayClipboard.getBiome(BlockVector3.at(rx, ry, rz)); 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, - int z); + public abstract boolean restoreTile(QueueCoordinator queue, CompoundTag tag, int x, int y, int z); /** * Get a schematic @@ -374,8 +359,7 @@ public abstract class SchematicHandler { * @return schematic if found, else null */ public Schematic getSchematic(String name) throws UnsupportedFormatException { - File parent = - FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS); + File parent = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS); if (!parent.exists()) { if (!parent.mkdir()) { throw new RuntimeException("Could not create schematic parent directory"); @@ -384,11 +368,9 @@ public abstract class SchematicHandler { if (!name.endsWith(".schem") && !name.endsWith(".schematic")) { name = name + ".schem"; } - File file = FileUtils.getFile(PlotSquared.platform().getDirectory(), - Settings.Paths.SCHEMATICS + File.separator + name); + File file = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS + File.separator + name); if (!file.exists()) { - file = FileUtils.getFile(PlotSquared.platform().getDirectory(), - Settings.Paths.SCHEMATICS + File.separator + name); + file = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS + File.separator + name); } return getSchematic(file); } @@ -399,12 +381,10 @@ public abstract class SchematicHandler { * @return Immutable collection with schematic names */ public Collection getSchematicNames() { - final File parent = - FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS); + final File parent = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS); final List names = new ArrayList<>(); if (parent.exists()) { - final String[] rawNames = - parent.list((dir, name) -> name.endsWith(".schematic") || name.endsWith(".schem")); + final String[] rawNames = parent.list((dir, name) -> name.endsWith(".schematic") || name.endsWith(".schem")); if (rawNames != null) { final List transformed = Arrays.stream(rawNames) //.map(rawName -> rawName.substring(0, rawName.length() - 10)) @@ -434,8 +414,7 @@ public abstract class SchematicHandler { e.printStackTrace(); } } else { - throw new UnsupportedFormatException( - "This schematic format is not recognised or supported."); + throw new UnsupportedFormatException("This schematic format is not recognised or supported."); } return null; } @@ -453,14 +432,12 @@ public abstract class SchematicHandler { public Schematic getSchematic(@Nonnull InputStream is) { try { - SpongeSchematicReader schematicReader = - new SpongeSchematicReader(new NBTInputStream(new GZIPInputStream(is))); + SpongeSchematicReader schematicReader = new SpongeSchematicReader(new NBTInputStream(new GZIPInputStream(is))); Clipboard clip = schematicReader.read(); return new Schematic(clip); } catch (IOException ignored) { try { - MCEditSchematicReader schematicReader = - new MCEditSchematicReader(new NBTInputStream(new GZIPInputStream(is))); + MCEditSchematicReader schematicReader = new MCEditSchematicReader(new NBTInputStream(new GZIPInputStream(is))); Clipboard clip = schematicReader.read(); return new Schematic(clip); } catch (IOException e) { @@ -477,8 +454,7 @@ public abstract class SchematicHandler { URL url = new URL(website); URLConnection connection = new URL(url.toString()).openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); - try (BufferedReader reader = new BufferedReader( - new InputStreamReader(connection.getInputStream()))) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { rawJSON = reader.lines().collect(Collectors.joining()); } JSONArray array = new JSONArray(rawJSON); @@ -501,8 +477,7 @@ public abstract class SchematicHandler { } upload(uuid, file, "schem", new RunnableVal() { @Override public void run(OutputStream output) { - try (NBTOutputStream nos = new NBTOutputStream( - new GZIPOutputStream(output, true))) { + try (NBTOutputStream nos = new NBTOutputStream(new GZIPOutputStream(output, true))) { nos.writeNamedTag("Schematic", tag); } catch (IOException e1) { e1.printStackTrace(); @@ -525,8 +500,7 @@ public abstract class SchematicHandler { try { File tmp = FileUtils.getFile(PlotSquared.platform().getDirectory(), path); tmp.getParentFile().mkdirs(); - try (NBTOutputStream nbtStream = new NBTOutputStream( - new GZIPOutputStream(new FileOutputStream(tmp)))) { + try (NBTOutputStream nbtStream = new NBTOutputStream(new GZIPOutputStream(new FileOutputStream(tmp)))) { nbtStream.writeNamedTag("Schematic", tag); } } catch (FileNotFoundException e) { @@ -538,8 +512,7 @@ public abstract class SchematicHandler { return true; } - public void getCompoundTag(final String world, final Set regions, - final RunnableVal whenDone) { + public void getCompoundTag(final String world, final Set regions, final RunnableVal whenDone) { // async TaskManager.runTaskAsync(() -> { // Main positions @@ -547,17 +520,15 @@ public abstract class SchematicHandler { final Location bot = corners[0]; final Location top = corners[1]; - CuboidRegion cuboidRegion = - new CuboidRegion(this.worldUtil.getWeWorld(world), bot.getBlockVector3(), - top.getBlockVector3()); + CuboidRegion cuboidRegion = new CuboidRegion(this.worldUtil.getWeWorld(world), bot.getBlockVector3(), top.getBlockVector3()); final int width = cuboidRegion.getWidth(); int height = cuboidRegion.getHeight(); final int length = cuboidRegion.getLength(); Map schematic = new HashMap<>(); schematic.put("Version", new IntTag(2)); - schematic.put("DataVersion", new IntTag(WorldEdit.getInstance().getPlatformManager() - .queryCapability(Capability.WORLD_EDITING).getDataVersion())); + schematic.put("DataVersion", + new IntTag(WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).getDataVersion())); Map metadata = new HashMap<>(); metadata.put("WEOffsetX", new IntTag(0)); @@ -592,14 +563,12 @@ public abstract class SchematicHandler { schematic.put("Palette", new CompoundTag(paletteTag)); schematic.put("BlockData", new ByteArrayTag(buffer.toByteArray())); - schematic - .put("TileEntities", new ListTag(CompoundTag.class, tileEntities)); + schematic.put("TileEntities", new ListTag(CompoundTag.class, tileEntities)); schematic.put("BiomePaletteMax", new IntTag(biomePalette.size())); Map biomePaletteTag = new HashMap<>(); - biomePalette.forEach( - (key, value) -> biomePaletteTag.put(key, new IntTag(value))); + biomePalette.forEach((key, value) -> biomePaletteTag.put(key, new IntTag(value))); schematic.put("BiomePalette", new CompoundTag(biomePaletteTag)); schematic.put("BiomeData", new ByteArrayTag(biomeBuffer.toByteArray())); @@ -630,33 +599,23 @@ public abstract class SchematicHandler { final Runnable zTask = new Runnable() { @Override public void run() { long zstart = System.currentTimeMillis(); - while (ziter.hasNext() - && System.currentTimeMillis() - zstart < 20) { + while (ziter.hasNext() && System.currentTimeMillis() - zstart < 20) { final int z = ziter.next(); - Iterator xiter = - IntStream.range(p1x, p2x + 1).iterator(); + Iterator xiter = IntStream.range(p1x, p2x + 1).iterator(); final Runnable xTask = new Runnable() { @Override public void run() { long xstart = System.currentTimeMillis(); final int ry = y - sy; final int rz = z - p1z; - while (xiter.hasNext() - && System.currentTimeMillis() - xstart - < 20) { + while (xiter.hasNext() && System.currentTimeMillis() - xstart < 20) { final int x = xiter.next(); final int rx = x - p1x; - BlockVector3 point = - BlockVector3.at(x, y, z); - BaseBlock block = cuboidRegion.getWorld() - .getFullBlock(point); + BlockVector3 point = BlockVector3.at(x, y, z); + BaseBlock block = cuboidRegion.getWorld().getFullBlock(point); if (block.getNbtData() != null) { - Map values = - new HashMap<>(); - for (Map.Entry entry : block - .getNbtData().getValue() - .entrySet()) { - values.put(entry.getKey(), - entry.getValue()); + Map values = new HashMap<>(); + for (Map.Entry entry : block.getNbtData().getValue().entrySet()) { + values.put(entry.getKey(), entry.getValue()); } // Remove 'id' if it exists. We want 'Id' values.remove("id"); @@ -666,16 +625,12 @@ public abstract class SchematicHandler { values.remove("y"); values.remove("z"); - values.put("Id", - new StringTag(block.getNbtId())); - values.put("Pos", new IntArrayTag( - new int[] {rx, ry, rz})); + values.put("Id", new StringTag(block.getNbtId())); + values.put("Pos", new IntArrayTag(new int[] {rx, ry, rz})); - tileEntities - .add(new CompoundTag(values)); + tileEntities.add(new CompoundTag(values)); } - String blockKey = - block.toImmutableState().getAsString(); + String blockKey = block.toImmutableState().getAsString(); int blockId; if (palette.containsKey(blockKey)) { blockId = palette.get(blockKey); @@ -694,8 +649,7 @@ public abstract class SchematicHandler { continue; } BlockVector2 pt = BlockVector2.at(x, z); - BiomeType biome = - cuboidRegion.getWorld().getBiome(pt); + BiomeType biome = cuboidRegion.getWorld().getBiome(pt); String biomeStr = biome.getId(); int biomeId; if (biomePalette.containsKey(biomeStr)) { diff --git a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java index 35b3bc5ef..5f7d64e83 100644 --- a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java @@ -127,8 +127,7 @@ public abstract class WorldUtil { * @param name Block name * @return Comparison result containing the closets matching block */ - @Nonnull public abstract StringComparison.ComparisonResult getClosestBlock( - @Nonnull String name); + @Nonnull public abstract StringComparison.ComparisonResult getClosestBlock(@Nonnull String name); /** * Get the biome in a given chunk, asynchronously @@ -138,8 +137,7 @@ public abstract class WorldUtil { * @param z Chunk Z coordinate * @param result Result consumer */ - public abstract void getBiome(@Nonnull String world, int x, int z, - @Nonnull Consumer result); + public abstract void getBiome(@Nonnull String world, int x, int z, @Nonnull Consumer result); /** * Get the biome in a given chunk, asynchronously @@ -150,8 +148,7 @@ public abstract class WorldUtil { * @return Biome * @deprecated Use {@link #getBiome(String, int, int, Consumer)} */ - @Deprecated @Nonnull public abstract BiomeType getBiomeSynchronous(@Nonnull String world, int x, - int z); + @Deprecated @Nonnull public abstract BiomeType getBiomeSynchronous(@Nonnull String world, int x, int z); /** * Get the block at a given location (asynchronously) @@ -178,8 +175,7 @@ public abstract class WorldUtil { * @param z Z coordinate * @param result Result consumer */ - public abstract void getHighestBlock(@Nonnull String world, int x, int z, - @Nonnull IntConsumer result); + public abstract void getHighestBlock(@Nonnull String world, int x, int z, @Nonnull IntConsumer result); /** @@ -191,8 +187,7 @@ public abstract class WorldUtil { * @return Result * @deprecated Use {@link #getHighestBlock(String, int, int, IntConsumer)} */ - @Deprecated @Nonnegative public abstract int getHighestBlockSynchronous(@Nonnull String world, - int x, int z); + @Deprecated @Nonnegative public abstract int getHighestBlockSynchronous(@Nonnull String world, int x, int z); /** * Set the text in a sign @@ -203,8 +198,7 @@ public abstract class WorldUtil { * @param z Z coordinate * @param lines Sign text */ - public abstract void setSign(@Nonnull String world, int x, int y, int z, - @Nonnull String[] lines); + public abstract void setSign(@Nonnull String world, int x, int y, int z, @Nonnull String[] lines); /** * Set the biome in a region @@ -213,8 +207,7 @@ public abstract class WorldUtil { * @param region Region * @param biome New biome */ - public abstract void setBiomes(@Nonnull String world, @Nonnull CuboidRegion region, - @Nonnull BiomeType biome); + public abstract void setBiomes(@Nonnull String world, @Nonnull CuboidRegion region, @Nonnull BiomeType biome); /** * Get the WorldEdit {@link com.sk89q.worldedit.world.World} corresponding to a world name @@ -233,82 +226,72 @@ public abstract class WorldUtil { */ public abstract void refreshChunk(int x, int z, String world); - public void upload(@Nonnull final Plot plot, @Nullable final UUID uuid, - @Nullable final String file, @Nonnull final RunnableVal whenDone) { - plot.getHome( - home -> SchematicHandler.upload(uuid, file, "zip", new RunnableVal() { - @Override public void run(OutputStream output) { - try (final ZipOutputStream zos = new ZipOutputStream(output)) { - File dat = getDat(plot.getWorldName()); - Location spawn = getSpawn(plot.getWorldName()); - if (dat != null) { - ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName()); - zos.putNextEntry(ze); - try (NBTInputStream nis = new NBTInputStream( - new GZIPInputStream(new FileInputStream(dat)))) { - CompoundTag tag = (CompoundTag) nis.readNamedTag().getTag(); - CompoundTag data = (CompoundTag) tag.getValue().get("Data"); - Map map = ReflectionUtils.getMap(data.getValue()); - map.put("SpawnX", new IntTag(home.getX())); - map.put("SpawnY", new IntTag(home.getY())); - map.put("SpawnZ", new IntTag(home.getZ())); - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - try (NBTOutputStream out = new NBTOutputStream( - new GZIPOutputStream(baos, true))) { - //TODO Find what this should be called - out.writeNamedTag("Schematic????", tag); - } - zos.write(baos.toByteArray()); + public void upload(@Nonnull final Plot plot, @Nullable final UUID uuid, @Nullable final String file, @Nonnull final RunnableVal whenDone) { + plot.getHome(home -> SchematicHandler.upload(uuid, file, "zip", new RunnableVal() { + @Override public void run(OutputStream output) { + try (final ZipOutputStream zos = new ZipOutputStream(output)) { + File dat = getDat(plot.getWorldName()); + Location spawn = getSpawn(plot.getWorldName()); + if (dat != null) { + ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName()); + zos.putNextEntry(ze); + try (NBTInputStream nis = new NBTInputStream(new GZIPInputStream(new FileInputStream(dat)))) { + CompoundTag tag = (CompoundTag) nis.readNamedTag().getTag(); + CompoundTag data = (CompoundTag) tag.getValue().get("Data"); + Map map = ReflectionUtils.getMap(data.getValue()); + map.put("SpawnX", new IntTag(home.getX())); + map.put("SpawnY", new IntTag(home.getY())); + map.put("SpawnZ", new IntTag(home.getZ())); + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + try (NBTOutputStream out = new NBTOutputStream(new GZIPOutputStream(baos, true))) { + //TODO Find what this should be called + out.writeNamedTag("Schematic????", tag); } + zos.write(baos.toByteArray()); } } - setSpawn(spawn); - byte[] buffer = new byte[1024]; - for (Plot current : plot.getConnectedPlots()) { - Location bot = current.getBottomAbs(); - Location top = current.getTopAbs(); - int brx = bot.getX() >> 9; - int brz = bot.getZ() >> 9; - int trx = top.getX() >> 9; - int trz = top.getZ() >> 9; - Set files = getChunkChunks(bot.getWorldName()); - for (BlockVector2 mca : files) { - if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz - && mca.getZ() <= trz) { - final File file = - getMcr(plot.getWorldName(), mca.getX(), mca.getZ()); - if (file != null) { - //final String name = "r." + (x - cx) + "." + (z - cz) + ".mca"; - String name = file.getName(); - final ZipEntry ze = new ZipEntry( - "world" + File.separator + "region" + File.separator - + name); - zos.putNextEntry(ze); - try (FileInputStream in = new FileInputStream(file)) { - int len; - while ((len = in.read(buffer)) > 0) { - zos.write(buffer, 0, len); - } - } - zos.closeEntry(); - } - } - } - } - zos.closeEntry(); - zos.flush(); - zos.finish(); - } catch (IOException e) { - e.printStackTrace(); } + setSpawn(spawn); + byte[] buffer = new byte[1024]; + for (Plot current : plot.getConnectedPlots()) { + Location bot = current.getBottomAbs(); + Location top = current.getTopAbs(); + int brx = bot.getX() >> 9; + int brz = bot.getZ() >> 9; + int trx = top.getX() >> 9; + int trz = top.getZ() >> 9; + Set files = getChunkChunks(bot.getWorldName()); + for (BlockVector2 mca : files) { + if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz && mca.getZ() <= trz) { + final File file = getMcr(plot.getWorldName(), mca.getX(), mca.getZ()); + if (file != null) { + //final String name = "r." + (x - cx) + "." + (z - cz) + ".mca"; + String name = file.getName(); + final ZipEntry ze = new ZipEntry("world" + File.separator + "region" + File.separator + name); + zos.putNextEntry(ze); + try (FileInputStream in = new FileInputStream(file)) { + int len; + while ((len = in.read(buffer)) > 0) { + zos.write(buffer, 0, len); + } + } + zos.closeEntry(); + } + } + } + } + zos.closeEntry(); + zos.flush(); + zos.finish(); + } catch (IOException e) { + e.printStackTrace(); } - }, whenDone)); + } + }, whenDone)); } @Nullable final File getDat(@Nonnull final String world) { - File file = new File( - PlotSquared.platform().getWorldContainer() + File.separator + world + File.separator - + "level.dat"); + File file = new File(PlotSquared.platform().getWorldContainer() + File.separator + world + File.separator + "level.dat"); if (file.exists()) { return file; } @@ -316,8 +299,8 @@ public abstract class WorldUtil { } @Nullable private File getMcr(@Nonnull final String world, final int x, final int z) { - final File file = new File(PlotSquared.platform().getWorldContainer(), - world + File.separator + "region" + File.separator + "r." + x + '.' + z + ".mca"); + final File file = + new File(PlotSquared.platform().getWorldContainer(), world + File.separator + "region" + File.separator + "r." + x + '.' + z + ".mca"); if (file.exists()) { return file; } @@ -326,12 +309,10 @@ public abstract class WorldUtil { public Set getChunkChunks(String world) { - File folder = - new File(PlotSquared.platform().getWorldContainer(), world + File.separator + "region"); + File folder = new File(PlotSquared.platform().getWorldContainer(), world + File.separator + "region"); File[] regionFiles = folder.listFiles(); if (regionFiles == null) { - throw new RuntimeException( - "Could not find worlds folder: " + folder + " ? (no read access?)"); + throw new RuntimeException("Could not find worlds folder: " + folder + " ? (no read access?)"); } HashSet chunks = new HashSet<>(); for (File file : regionFiles) { @@ -413,7 +394,6 @@ public abstract class WorldUtil { * @param chunk Chunk coordinates * @return Tile entity count */ - @Nonnegative public abstract int getTileEntityCount(@Nonnull String world, - @Nonnull BlockVector2 chunk); + @Nonnegative public abstract int getTileEntityCount(@Nonnull String world, @Nonnull BlockVector2 chunk); }