io.papermc.lib.PaperLib Java Examples

The following examples show how to use io.papermc.lib.PaperLib. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TeleportLogic.java    From uSkyBlock with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Teleport the given {@link Player} to the given {@link Location}, loading the {@link org.bukkit.Chunk} before
 * teleporting and with the configured teleport delay if applicable.
 * @param player Player to teleport.
 * @param targetLocation Location to teleport the player to.
 * @param force True to override teleport delay, false otherwise.
 */
public void safeTeleport(@NotNull Player player, @NotNull Location targetLocation, boolean force) {
    Validate.notNull(player, "Player cannot be null");
    Validate.notNull(targetLocation, "TargetLocation cannot be null");

    log.log(Level.FINER, "safeTeleport " + player + " to " + targetLocation + (force ? " with force" : ""));
    final Location targetLoc = LocationUtil.centerOnBlock(targetLocation.clone());
    if (player.hasPermission("usb.mod.bypassteleport") || (teleportDelay == 0) || force) {
        PaperLib.teleportAsync(player, targetLoc);
    } else {
        player.sendMessage(tr("\u00a7aYou will be teleported in {0} seconds.", teleportDelay));
        BukkitTask tpTask = plugin.sync(() -> {
            pendingTeleports.remove(player.getUniqueId());
            PaperLib.teleportAsync(player, targetLoc);
        }, TimeUtil.secondsAsMillis(teleportDelay));
        pendingTeleports.put(player.getUniqueId(), new PendingTeleport(player.getLocation(), tpTask));
    }
}
 
Example #2
Source File: TeleportLogic.java    From uSkyBlock with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Teleport the given {@link Player} to the spawn in the island world, loading the {@link org.bukkit.Chunk} before
 * teleporting and with the configured teleport delay if applicable.
 * @param player Player to teleport.
 * @param force True to override teleport delay, false otherwise.
 */
public void spawnTeleport(@NotNull Player player, boolean force) {
    Validate.notNull(player, "Player cannot be null");

    Location spawnLocation = LocationUtil.centerOnBlock(plugin.getWorldManager().getWorld().getSpawnLocation());
    if (player.hasPermission("usb.mod.bypassteleport") || (teleportDelay == 0) || force) {
        if (Settings.extras_sendToSpawn) {
            plugin.execCommand(player, "op:spawn", false);
        } else {
            PaperLib.teleportAsync(player, spawnLocation);
        }
    } else {
        player.sendMessage(tr("\u00a7aYou will be teleported in {0} seconds.", teleportDelay));
        BukkitTask tpTask = plugin.sync(() -> {
            pendingTeleports.remove(player.getUniqueId());
            if (Settings.extras_sendToSpawn) {
                plugin.execCommand(player, "op:spawn", false);
            } else {
                PaperLib.teleportAsync(player, spawnLocation);
            }
        }, TimeUtil.secondsAsMillis(teleportDelay));
        pendingTeleports.put(player.getUniqueId(), new PendingTeleport(player.getLocation(), tpTask));
    }
}
 
Example #3
Source File: BedSpawnLocationPaper.java    From PaperLib with MIT License 5 votes vote down vote up
@Override
public CompletableFuture<Location> getBedSpawnLocationAsync(Player player, boolean isUrgent) {
    Location bedLocation = player.getPotentialBedLocation();
    if (bedLocation == null) {
        return CompletableFuture.completedFuture(null);
    }
    return PaperLib.getChunkAtAsync(bedLocation.getWorld(), bedLocation.getBlockX() >> 4, bedLocation.getBlockZ() >> 4, false, isUrgent).thenCompose(chunk -> CompletableFuture.completedFuture(player.getBedSpawnLocation()));
}
 
Example #4
Source File: AsyncChunksSync.java    From PaperLib with MIT License 5 votes vote down vote up
@Override
public CompletableFuture<Chunk> getChunkAtAsync(World world, int x, int z, boolean gen, boolean isUrgent) {
    if (!gen && !PaperLib.isChunkGenerated(world, x, z)) {
        return CompletableFuture.completedFuture(null);
    } else {
        return CompletableFuture.completedFuture(world.getChunkAt(x, z));
    }
}
 
Example #5
Source File: AsyncChunksPaper_9_12.java    From PaperLib with MIT License 5 votes vote down vote up
@Override
public CompletableFuture<Chunk> getChunkAtAsync(World world, int x, int z, boolean gen, boolean isUrgent) {
    CompletableFuture<Chunk> future = new CompletableFuture<>();
    if (!gen && PaperLib.getMinecraftVersion() >= 12 && !world.isChunkGenerated(x, z)) {
        future.complete(null);
    } else {
        World.ChunkLoadCallback chunkLoadCallback = future::complete;
        world.getChunkAtAsync(x, z, chunkLoadCallback);
    }
    return future;
}
 
Example #6
Source File: PlantsListener.java    From ExoticGarden with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onGrow(StructureGrowEvent e) {
    if (PaperLib.isPaper()) {
        if (PaperLib.isChunkGenerated(e.getLocation())) {
            growStructure(e);
        } else {
            PaperLib.getChunkAtAsync(e.getLocation()).thenRun(() -> growStructure(e));
        }
    } else {
        if (!e.getLocation().getChunk().isLoaded()) {
            e.getLocation().getChunk().load();
        }
        growStructure(e);
    }
}
 
Example #7
Source File: TeleportTarget.java    From WildernessTp with MIT License 5 votes vote down vote up
private void teleportPlayer(Location loc, Player p) {
    String location = loc.getBlockX() + " " + loc.getY() + " " + loc.getBlockZ();
    String teleport = wild.getConfig().getString("Teleport").replace("<loc>", location);
    TeleportTarget teleportTarget = new TeleportTarget(wild);
    if (!PlayMoveEvent.moved.contains(p.getUniqueId()) && !PlayMoveEvent.dontTele.contains(p.getUniqueId())) {
        cmdUsed.remove(p.getUniqueId());
        Wild.applyPotions(p);
        PaperLib.teleportAsync(p, loc).thenAccept(res -> {
            if(res){
                p.sendMessage(ChatColor.translateAlternateColorCodes('&', teleport));
            } else {
                p.teleport(loc);
            }
        });
        if (wild.getConfig().getBoolean("Play"))
            p.playSound(loc, Sounds.getSound(), 3, 10);
        if(wild.getConfig().getBoolean("DoParticle")){
            String[] tmp = Bukkit.getVersion().split("MC: ");
            String version = tmp[tmp.length - 1].substring(0, 3);
            loc.setY(loc.getY()-1);
            if (version.equals("1.9") || version.equals("1.1"))
                loc.getWorld().spawnParticle(Particle.valueOf(wild.getConfig().getString("Particle").toUpperCase()),loc,30,2,2,2);
            else {
                Effect effect = Effect.valueOf(wild.getConfig().getString("Particle").toUpperCase());
                loc.getWorld().playEffect(loc,effect,effect.getData(),2);
            }
        }
        teleportTarget.doCommands(p);
    }
    PlayMoveEvent.moved.remove(p.getUniqueId());
    wild.biome.remove(p.getUniqueId());
    wild.portalUsed.remove(p.getUniqueId());
    PlayMoveEvent.dontTele.remove(p.getUniqueId());
    wild.village.remove(p.getUniqueId());
}
 
Example #8
Source File: uSkyBlock.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onEnable() {
    WorldManager.skyBlockWorld = null; // Force a re-import or what-ever...
    WorldManager.skyBlockNetherWorld = null;
    missingRequirements = null;
    instance = this;
    CommandManager.registerRequirements(this);
    FileUtil.setDataFolder(getDataFolder());
    FileUtil.setAllwaysOverwrite("levelConfig.yml");
    I18nUtil.setDataFolder(getDataFolder());

    reloadConfigs();

    getServer().getScheduler().runTaskLater(getInstance(), new Runnable() {
        @Override
        public void run() {
            ServerUtil.init(uSkyBlock.this);
            if (!isRequirementsMet(Bukkit.getConsoleSender(), null)) {
                return;
            }
            uSkyBlock.this.getHookManager().setupEconomyHook();
            uSkyBlock.this.getHookManager().setupPermissionsHook();
            AsyncWorldEditHandler.onEnable(uSkyBlock.this);
            WorldGuardHandler.setupGlobal(getWorldManager().getWorld());
            if (getWorldManager().getNetherWorld() != null) {
                WorldGuardHandler.setupGlobal(getWorldManager().getNetherWorld());
            }
            registerEventsAndCommands();
            if (!getConfig().getBoolean("importer.name2uuid.imported", false)) {
                Bukkit.getConsoleSender().sendMessage(tr("Converting data to UUID, this make take a while!"));
                getImporter().importUSB(Bukkit.getConsoleSender(), "name2uuid");
            }
            log(Level.INFO, getVersionInfo(false));
        }
    }, getConfig().getLong("init.initDelay", 50L));

    metricsManager = new MetricsManager(this);
    PaperLib.suggestPaper(this);
}
 
Example #9
Source File: MinecraftHook.java    From RandomTeleport with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean canBuild(Player player, Location location) {
    BlockStateSnapshotResult state = PaperLib.getBlockState(location.getBlock(), false);
    if (state.getState() instanceof Lockable) {
        return ((Lockable) state.getState()).getLock() == null;
    }
    return true;
}
 
Example #10
Source File: AsyncTeleportPaper.java    From PaperLib with MIT License 4 votes vote down vote up
@Override
public CompletableFuture<Boolean> teleportAsync(Entity entity, Location location, TeleportCause cause) {
    int x = location.getBlockX() >> 4;
    int z = location.getBlockZ() >> 4;
    return PaperLib.getChunkAtAsyncUrgently(entity.getWorld(), x, z, true).thenApply(chunk -> entity.teleport(location, cause));
}
 
Example #11
Source File: Wild.java    From WildernessTp with MIT License 4 votes vote down vote up
public void onEnable() {
    Console.send("&7-----------------------------------------------");
    String[] tmp = Bukkit.getVersion().split("MC: ");
    String version = tmp[tmp.length - 1].substring(0, 4);
    int ver = parseMcVer(version);

    thirteen = ver>=13;
    instance = this;
    this.getCommand("wildtp").setExecutor(new CmdWildTp(this));
    this.getCommand("wild").setExecutor(new CmdWild(this));
    this.getCommand("wild").setTabCompleter(new WildTab());
    this.getCommand("wildtp").setTabCompleter(new WildTpTab());
    this.getConfig().options().copyDefaults(true);
    this.saveConfig();
    this.saveResource("PotionsEffects.txt", true);
    this.saveResource("Biomes.txt", true);
    this.saveResource("Sounds.txt", true);
    this.saveResource("Particles.txt", true);
    Bukkit.getPluginManager().registerEvents(new InvClick(this), this);
    Bukkit.getPluginManager().registerEvents(new SetVal(this), this);
    Bukkit.getPluginManager().registerEvents(new SignChange(this), this);
    Bukkit.getPluginManager().registerEvents(new SignBreak(this), this);
    Bukkit.getPluginManager().registerEvents(new SignClick(this), this);
    Bukkit.getPluginManager().registerEvents(new HookClick(), this);
    Bukkit.getPluginManager().registerEvents(new PlayMoveEvent(this), this);
    Bukkit.getPluginManager().registerEvents(new CommandUseEvent(this), this);
    Bukkit.getPluginManager().registerEvents(new BlockClickEvent(this), this);
    Bukkit.getPluginManager().registerEvents(new PortalEvent(this),this);
    LoadDependencies.loadAll();
    Initializer initialize = new Initializer(this);
    initialize.initializeAll();
    SavePortals save = new SavePortals(this);
    save.createFile();
    LocationsFile locationsFile = new LocationsFile(this);
    locationsFile.createFile();
    cooldownTime = new HashMap<>();
    Sounds.init();
    CheckConfig check = new CheckConfig();
    usageMode = UsageMode.valueOf(this.getConfig().getString("UsageMode"));
    if (this.getConfig().getBoolean("Metrics"))
        new Metrics(this);
    if (!check.isCorrectPots()) {
        Console.send(prefix + "Config for potions is misconfigured please check the documentation on the plugin page to make sure you have configured correctly");
        Console.send(prefix +"&cPlugin will now disable");
        Bukkit.getPluginManager().disablePlugin(this);
    }
    if(!check.checkParticle()){
        Console.send(prefix +"Particle type is invalid disabling particles to stop errors");
        this.getConfig().set("DoParticles",false);
    }
    if (this.getConfig().getInt("Cost") > 0) {
        if (!setupEconomy()) {
            this.getLogger().severe("[%s] - Disabled due to no Vault dependency found!");
            Bukkit.getServer().getPluginManager().disablePlugin(this);
            return;
        }
    }
    if(PaperLib.isPaper()){
        Console.send(prefix + "&bPaper was found ! Async Teleport &aenabled&b.");
    }
    OldFormatConverter.convert();
    checkUpdate();
    getUpdates();
    Console.send("&7-----------------------------------------------");
}
 
Example #12
Source File: RandomSearcher.java    From RandomTeleport with GNU General Public License v3.0 4 votes vote down vote up
private void checkRandom(CompletableFuture<Location> future) {
    if (checks >= maxTries) {
        future.completeExceptionally(new NotFoundException("location"));
        return;
    }
    if (future.isCancelled() || future.isDone() || future.isCompletedExceptionally()) {
        return;
    }
    lastCheck = center.getWorld().getTime();
    Location randomLoc = center.clone();
    randomLoc.setY(0);
    int minChunk = minRadius >> 4;
    int maxChunk = maxRadius >> 4;
    int randChunkX;
    int randChunkZ;
    Chunk[] loadedChunks = new Chunk[0];
    if (loadedOnly) {
        loadedChunks = randomLoc.getWorld().getLoadedChunks();
        if (loadedChunks.length == 0) {
            future.completeExceptionally(new NotFoundException("loaded chunk"));
            return;
        }
    }

    do {
        checks++;
        if (checks >= maxTries) {
            future.completeExceptionally(new NotFoundException("location"));
            return;
        }
        if (loadedOnly) {
            Chunk chunk = loadedChunks[random.nextInt(loadedChunks.length)];
            randChunkX = chunk.getX();
            randChunkZ = chunk.getZ();
        } else {
            randChunkX = (random.nextBoolean() ? 1 : -1) * random.nextInt(maxChunk + 1);
            randChunkZ = (random.nextBoolean() ? 1 : -1) * random.nextInt(maxChunk + 1);
        }
    } while (!checked.put(randChunkX, randChunkZ) || !inRadius(Math.abs(randChunkX), Math.abs(randChunkZ), minChunk, maxChunk));

    randomLoc.setX(((center.getBlockX() >> 4) + randChunkX) * 16);
    randomLoc.setZ(((center.getBlockZ() >> 4) + randChunkZ) * 16);
    PaperLib.getChunkAtAsync(randomLoc, generatedOnly).thenApply(c -> {
        checks++;
        if (c == null) {
            // Chunk not generated, test another one
            checkRandom(future);
            return false;
        }
        int indexOffset = random.nextInt(RANDOM_LIST.size());
        Location foundLoc = null;
        for (int i = 0; i < RANDOM_LIST.size(); i++) {
            int index = (i + indexOffset) % RANDOM_LIST.size();
            boolean validated = true;
            Location loc = randomLoc.clone().add(RANDOM_LIST.get(index)[0], 0, RANDOM_LIST.get(index)[1]);

            if (!inRadius(loc)) {
                continue;
            }

            for (LocationValidator validator : getValidators().getAll()) {
                if (!validator.validate(this, loc)) {
                    validated = false;
                    break;
                }
            }
            if (validated) {
                foundLoc = loc;
                break;
            }
        }

        if (foundLoc != null) {
            // all checks are for the top block, put we want a location above that so add 1 to y
            future.complete(foundLoc.add(0, 1, 0));
            return true;
        }
        long diff = center.getWorld().getTime() - lastCheck;
        if (diff < checkDelay) {
            plugin.getServer().getScheduler().runTaskLater(plugin, () -> checkRandom(future), checkDelay - diff);
        } else {
            checkRandom(future);
        }
        return false;
    }).exceptionally(future::completeExceptionally);
}