Formatting, mark nonnull, nullable etc

This commit is contained in:
dordsor21
2020-07-24 16:24:53 +01:00
parent 72c0021306
commit 1d0760c630
39 changed files with 1172 additions and 1736 deletions

View File

@ -165,8 +165,7 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass;
@SuppressWarnings("unused")
public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPlatform<Player> {
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<? extends Player> player : this.getPlayerManager()
.getPlayers()) {
if (player.getPlatformPlayer() == null || !player.getPlatformPlayer()
.isOnline()) {
for (final PlotPlayer<? extends Player> 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<UUID> 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<UUID> 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<String, Integer> terrainTypeMap =
map.get(plotArea.getType().name().toLowerCase());
terrainTypeMap.put(plotArea.getTerrain().name().toLowerCase(),
terrainTypeMap.get(plotArea.getTerrain().name().toLowerCase()) + 1);
final Map<String, Integer> 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<Map.Entry<Map.Entry<String, String>, Boolean>> getPluginIds() {
List<Map.Entry<Map.Entry<String, String>, Boolean>> names = new ArrayList<>();
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
Map.Entry<String, String> id = new AbstractMap.SimpleEntry<>(plugin.getName(),
plugin.getDescription().getVersion());
Map.Entry<String, String> 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<PlatformWorldManager<World>>() {}));
return getInjector().getInstance(Key.get(new TypeLiteral<PlatformWorldManager<World>>() {
}));
}
@Override @Nonnull @SuppressWarnings("ALL")
public PlayerManager<? extends PlotPlayer<Player>, ? extends Player> getPlayerManager() {
@Override @Nonnull @SuppressWarnings("ALL") public PlayerManager<? extends PlotPlayer<Player>, ? extends Player> getPlayerManager() {
return (PlayerManager<BukkitPlayer, Player>) getInjector().getInstance(PlayerManager.class);
}

View File

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

View File

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

View File

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

View File

@ -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<BlockVector2> chunkConsumer,
@Assisted @Nonnull final World world,
@Assisted @Nonnull final Collection<BlockVector2> requestedChunks,
@Assisted @Nonnull final Runnable whenDone,
@Assisted @Nonnull final Consumer<Throwable> throwableConsumer,
@Assisted final boolean unloadAfter) {
@Assisted final int initialBatchSize,
@Assisted @Nonnull final Consumer<BlockVector2> chunkConsumer,
@Assisted @Nonnull final World world,
@Assisted @Nonnull final Collection<BlockVector2> requestedChunks,
@Assisted @Nonnull final Runnable whenDone,
@Assisted @Nonnull final Consumer<Throwable> 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);
}

View File

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

View File

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

View File

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

View File

@ -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<BlockType> 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<Chunk> chunkConsumer) {
private static void ensureLoaded(@Nonnull final String world, final int x, final int z, @Nonnull final Consumer<Chunk> 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<Chunk> chunkConsumer) {
PaperLib.getChunkAtAsync(adapt(location), true)
.thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk));
private static void ensureLoaded(@Nonnull final Location location, @Nonnull final Consumer<Chunk> chunkConsumer) {
PaperLib.getChunkAtAsync(adapt(location), true).thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk));
}
private static <T> void ensureMainThread(@Nonnull final Consumer<T> consumer,
@Nonnull final T value) {
private static <T> void ensureMainThread(@Nonnull final Consumer<T> 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<BiomeType> 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<BiomeType> 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<BlockState>.ComparisonResult getClosestBlock(@Nonnull String name) {
@Override @Nonnull public StringComparison<BlockState>.ComparisonResult getClosestBlock(@Nonnull String name) {
BlockState state = BlockUtil.get(name);
return new StringComparison<BlockState>().new ComparisonResult(1, state);
}
@Override
public void setBiomes(@Nonnull final String worldName, @Nonnull final 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<BlockState> result) {
@Override public void getBlock(@Nonnull final Location location, @Nonnull final Consumer<BlockState> 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<com.sk89q.worldedit.world.entity.EntityType> getTypesInCategory(
@Nonnull final String category) {
@Override @Nonnull public Set<com.sk89q.worldedit.world.entity.EntityType> getTypesInCategory(@Nonnull final String category) {
final Collection<Class<?>> 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();