Add /rtp with normal distribution, economy hook, home limits, new tests, locales

This commit is contained in:
William committed 2022-08-19 19:44:07 +01:00
1 parent 0bb33c6f1e
commit 08e6569027
39 files changed
+1128 -188

No files matched your search

+1
View File
@@ -11,6 +11,7 @@ dependencies {
compileOnly 'de.themoep:minedown:1.7.1-SNAPSHOT'
compileOnly 'org.jetbrains:annotations:23.0.0'
compileOnly 'net.william278:Annotaml:1.0.1'
compileOnly "com.github.MilkBowl:VaultAPI:1.7.1"
testImplementation 'com.github.seeseemelk:MockBukkit-v1.19:2.117.0'
testImplementation 'de.themoep:minedown:1.7.1-SNAPSHOT'
@@ -1,5 +1,6 @@
package net.william278.huskhomes;
import io.papermc.lib.PaperLib;
import net.william278.annotaml.Annotaml;
import net.william278.annotaml.AnnotamlException;
import net.william278.huskhomes.command.BukkitCommand;
@@ -9,6 +10,8 @@ import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.database.MySqlDatabase;
import net.william278.huskhomes.database.SqLiteDatabase;
import net.william278.huskhomes.hook.PluginHook;
import net.william278.huskhomes.hook.VaultEconomyHook;
import net.william278.huskhomes.listener.BukkitEventListener;
import net.william278.huskhomes.listener.EventListener;
import net.william278.huskhomes.messenger.NetworkMessenger;
@@ -16,16 +19,14 @@ import net.william278.huskhomes.messenger.PluginMessenger;
import net.william278.huskhomes.messenger.RedisMessenger;
import net.william278.huskhomes.player.BukkitPlayer;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.SavedPositionManager;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.random.NormalDistributionEngine;
import net.william278.huskhomes.random.RtpEngine;
import net.william278.huskhomes.request.RequestManager;
import net.william278.huskhomes.teleport.TeleportManager;
import net.william278.huskhomes.util.*;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.PluginCommand;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.PluginDescriptionFile;
@@ -35,13 +36,11 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
@@ -59,6 +58,8 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
private RequestManager requestManager;
private SavedPositionManager savedPositionManager;
private EventListener eventListener;
private RtpEngine rtpEngine;
private Set<PluginHook> pluginHooks;
@Nullable
private NetworkMessenger networkMessenger;
@@ -66,28 +67,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
@Nullable
private Server server;
/**
* Returns the {@link Server} the plugin is on
*
* @param onlineUser {@link OnlineUser} to request the server
* @return The {@link Server} object
*/
@Override
public CompletableFuture<Server> getServer(@NotNull OnlineUser onlineUser) {
if (server != null) {
return CompletableFuture.supplyAsync(() -> server);
}
if (!getSettings().crossServer) {
server = new Server("server");
return CompletableFuture.supplyAsync(() -> server);
}
assert networkMessenger != null;
return networkMessenger.getServerName(onlineUser).thenApplyAsync(server -> {
this.server = new Server(server);
return this.server;
});
}
// Instance of the plugin
private static BukkitHuskHomes instance;
@@ -159,6 +138,23 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
// Prepare the home and warp position manager
this.savedPositionManager = new SavedPositionManager(database, cache);
// Initialize the RTP engine with the default normal distribution engine
this.rtpEngine = new NormalDistributionEngine(this);
rtpEngine.initialize();
// Register plugin hooks
this.pluginHooks = new HashSet<>();
if (Bukkit.getPluginManager().getPlugin("Vault") != null && settings.economy) {
final PluginHook vaultHook = new VaultEconomyHook(this);
vaultHook.initialize();
pluginHooks.add(vaultHook);
} else {
settings.economy = false;
}
getLoggingAdapter().log(Level.INFO, "Registered " + pluginHooks.size() + " plugin hooks: " +
pluginHooks.stream().map(PluginHook::getHookName)
.collect(Collectors.joining(", ")));
// Register events
getLoggingAdapter().log(Level.INFO, "Registering events...");
this.eventListener = new BukkitEventListener(this);
@@ -284,12 +280,36 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
}
@Override
public boolean isValidPositionOnServer(Position position) {
final Optional<Location> adaptedLocation = BukkitAdapter.adaptLocation(position);
public @NotNull RtpEngine getRtpEngine() {
return rtpEngine;
}
@Override
public @NotNull Set<PluginHook> getPluginHooks() {
return pluginHooks;
}
@Override
public CompletableFuture<Optional<Location>> getSafeGroundLocation(@NotNull Location location) {
final CompletableFuture<Optional<Location>> future = new CompletableFuture<>();
Bukkit.getScheduler().runTask(getInstance(), () -> BukkitAdapter.adaptLocation(location).ifPresentOrElse(
bukkitLocation -> PaperLib.getChunkAtAsync(bukkitLocation).thenAccept(chunk ->
future.complete(BukkitSafetyUtil.findSafeLocation(location.world, bukkitLocation,
chunk.getChunkSnapshot()))).exceptionally(throwable -> {
throwable.printStackTrace();
return null;
}),
() -> future.complete(Optional.empty())));
return future;
}
@Override
public boolean isValidPositionOnServer(@NotNull Position position) {
final Optional<org.bukkit.Location> adaptedLocation = BukkitAdapter.adaptLocation(position);
if (adaptedLocation.isEmpty()) {
return false;
}
final Location location = adaptedLocation.get();
final org.bukkit.Location location = adaptedLocation.get();
assert location.getWorld() != null;
return location.getWorld().getWorldBorder().isInside(location);
}
@@ -309,6 +329,34 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
return getServer().getName();
}
/**
* Returns the {@link Server} the plugin is on
*
* @param onlineUser {@link OnlineUser} to request the server
* @return The {@link Server} object
*/
@Override
public CompletableFuture<Server> getServer(@NotNull OnlineUser onlineUser) {
if (server != null) {
return CompletableFuture.supplyAsync(() -> server);
}
if (!getSettings().crossServer) {
server = new Server("server");
return CompletableFuture.supplyAsync(() -> server);
}
assert networkMessenger != null;
return networkMessenger.getServerName(onlineUser).thenApplyAsync(server -> {
this.server = new Server(server);
return this.server;
});
}
@Override
public @NotNull List<World> getWorlds() {
return getServer().getWorlds().stream().filter(world -> BukkitAdapter.adaptWorld(world).isPresent())
.map(world -> BukkitAdapter.adaptWorld(world).orElse(null)).collect(Collectors.toList());
}
@Override
public CompletableFuture<Boolean> reload() {
return CompletableFuture.supplyAsync(() -> {
@@ -331,40 +379,14 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
}
// Default constructor
public BukkitHuskHomes()
{
public BukkitHuskHomes() {
super();
}
// Super constructor for unit testing
protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description,
@NotNull File dataFolder, @NotNull File file)
{
@NotNull File dataFolder, @NotNull File file) {
super(loader, description, dataFolder, file);
}
public static final class BukkitAdapter {
public static Optional<Location> adaptLocation(net.william278.huskhomes.position.Location location) {
World world = Bukkit.getWorld(location.world.name);
if (world == null) {
world = Bukkit.getWorld(location.world.uuid);
}
if (world == null) {
return Optional.empty();
}
return Optional.of(new Location(world, location.x, location.y, location.z,
location.yaw, location.pitch));
}
@Nullable
public static net.william278.huskhomes.position.Location adaptLocation(@NotNull Location location) {
if (location.getWorld() == null) return null;
return new net.william278.huskhomes.position.Location(location.getX(), location.getY(), location.getZ(),
location.getYaw(), location.getPitch(),
new net.william278.huskhomes.position.World(location.getWorld().getName(), location.getWorld().getUID()));
}
}
}
@@ -26,6 +26,7 @@ public enum BukkitCommandType {
TPA_HERE_COMMAND(new TpaHereCommand(BukkitHuskHomes.getInstance())),
TPACCEPT_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), true)),
TPDECLINE_COMMAND(new TpRespondCommand(BukkitHuskHomes.getInstance(), false)),
RTP_COMMAND(new RtpCommand(BukkitHuskHomes.getInstance())),
BACK_COMMAND(new BackCommand(BukkitHuskHomes.getInstance()));
public final CommandBase commandBase;
@@ -0,0 +1,58 @@
package net.william278.huskhomes.hook;
import net.milkbowl.vault.economy.Economy;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.HuskHomesInitializationException;
import net.william278.huskhomes.player.BukkitPlayer;
import net.william278.huskhomes.player.OnlineUser;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.jetbrains.annotations.NotNull;
/**
* A hook that hooks into the Vault API to provide economy features
*/
public class VaultEconomyHook extends EconomyHook {
private Economy economy;
public VaultEconomyHook(@NotNull HuskHomes implementor) {
super(implementor, "Vault (Economy)");
}
@Override
public boolean initialize() throws HuskHomesInitializationException {
final RegisteredServiceProvider<Economy> economyProvider = ((BukkitHuskHomes) plugin).getServer()
.getServicesManager().getRegistration(Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
return true;
}
return false;
}
@Override
public double getPlayerBalance(@NotNull OnlineUser player) {
return economy.getBalance(((BukkitPlayer) player).getPlayer());
}
@Override
public void changePlayerBalance(@NotNull OnlineUser player, double amount) {
if (amount != 0d) {
final Player bukkitPlayer = ((BukkitPlayer) player).getPlayer();
final double currentBalance = getPlayerBalance(player);
final double amountToChange = Math.abs(currentBalance - Math.max(0d, currentBalance + amount));
if (amount < 0d) {
economy.withdrawPlayer(bukkitPlayer, amountToChange);
} else {
economy.depositPlayer(bukkitPlayer, amountToChange);
}
}
}
@Override
public String formatCurrency(double amount) {
return economy.format(amount);
}
}
@@ -8,16 +8,17 @@ import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.TeleportResult;
import net.william278.huskhomes.EconomyUnsupportedException;
import net.william278.huskhomes.util.BukkitAdapter;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.UUID;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
/**
* Bukkit implementation of an {@link OnlineUser}
@@ -33,6 +34,7 @@ public class BukkitPlayer extends OnlineUser {
/**
* Adapt a {@link Player} to a {@link OnlineUser}
*
* @param player the online {@link Player} to adapt
* @return the adapted {@link OnlineUser}
*/
@@ -43,6 +45,7 @@ public class BukkitPlayer extends OnlineUser {
/**
* Get an online {@link BukkitPlayer} by their UUID
*
* @param uuid the UUID of the player to find
* @return an {@link Optional} containing the {@link BukkitPlayer} if found; {@link Optional#empty()} otherwise
*/
@@ -56,6 +59,7 @@ public class BukkitPlayer extends OnlineUser {
/**
* Get an online {@link BukkitPlayer} by their exact username
*
* @param username the UUID of the player to find
* @return an {@link Optional} containing the {@link BukkitPlayer} if found; {@link Optional#empty()} otherwise
*/
@@ -77,7 +81,7 @@ public class BukkitPlayer extends OnlineUser {
@Override
public Location getLocation() {
return BukkitHuskHomes.BukkitAdapter.adaptLocation(player.getLocation());
return BukkitAdapter.adaptLocation(player.getLocation()).orElse(null);
}
@Override
@@ -90,6 +94,13 @@ public class BukkitPlayer extends OnlineUser {
return player.hasPermission(node);
}
@Override
public @NotNull Map<String, Boolean> getPermissions() {
return player.getEffectivePermissions().stream().collect(
Collectors.toMap(PermissionAttachmentInfo::getPermission,
PermissionAttachmentInfo::getValue, (a, b) -> b));
}
@Override
public void sendActionBar(@NotNull MineDown mineDown) {
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, mineDown.replace().toComponent());
@@ -107,7 +118,7 @@ public class BukkitPlayer extends OnlineUser {
@Override
public CompletableFuture<TeleportResult> teleport(Location location) {
return CompletableFuture.supplyAsync(() -> {
final Optional<org.bukkit.Location> bukkitLocation = BukkitHuskHomes.BukkitAdapter.adaptLocation(location);
final Optional<org.bukkit.Location> bukkitLocation = BukkitAdapter.adaptLocation(location);
if (bukkitLocation.isEmpty()) {
return TeleportResult.FAILED_INVALID_WORLD;
}
@@ -129,30 +140,19 @@ public class BukkitPlayer extends OnlineUser {
});
}
@Override
public CompletableFuture<Integer> getMaxHomes() {
return null; //todo
}
@Override
public CompletableFuture<Integer> getFreeHomes() {
return null; //todo
}
@Override
public double getEconomyBalance() throws EconomyUnsupportedException {
return 0; //todo
}
@Override
public void deductEconomyBalance() throws EconomyUnsupportedException {
//todo
}
/**
* Send a Bukkit plugin message
*/
public void sendPluginMessage(@NotNull Plugin source, @NotNull String channel, final byte[] message) {
player.sendPluginMessage(source, channel, message);
}
/**
* Return the {@link Player} wrapped by this {@link BukkitPlayer}
*
* @return the {@link Player} wrapped by this {@link BukkitPlayer}
*/
public Player getPlayer() {
return player;
}
}
@@ -0,0 +1,59 @@
package net.william278.huskhomes.util;
import net.william278.huskhomes.position.Location;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
/**
* Static class providing utility methods for adapting Bukkit objects to HuskHomes and vice versa
*/
public final class BukkitAdapter {
/**
* Adapt a Bukkit {@link org.bukkit.Location} to a HuskHomes {@link Location}
*
* @param location the Bukkit {@link org.bukkit.Location} to adapt
* @return the adapted {@link Location}
*/
public static Optional<org.bukkit.Location> adaptLocation(@NotNull Location location) {
org.bukkit.World world = Bukkit.getWorld(location.world.name);
if (world == null) {
world = Bukkit.getWorld(location.world.uuid);
}
if (world == null) {
return Optional.empty();
}
return Optional.of(new org.bukkit.Location(world, location.x, location.y, location.z,
location.yaw, location.pitch));
}
/**
* Adapt a HuskHomes {@link org.bukkit.Location} to a Bukkit {@link org.bukkit.Location}
*
* @param location the HuskHomes {@link org.bukkit.Location} to adapt
* @return the adapted {@link org.bukkit.Location}
*/
public static Optional<Location> adaptLocation(@NotNull org.bukkit.Location location) {
if (location.getWorld() == null) return Optional.empty();
return Optional.of(new Location(location.getX(), location.getY(), location.getZ(),
location.getYaw(), location.getPitch(),
adaptWorld(location.getWorld()).orElse(new net.william278.huskhomes.position.World())));
}
public static Optional<net.william278.huskhomes.position.World> adaptWorld(@Nullable org.bukkit.World world) {
if (world == null) {
return Optional.empty();
}
return Optional.of(new net.william278.huskhomes.position.World(world.getName(), world.getUID(),
switch (world.getEnvironment()) {
case NORMAL -> net.william278.huskhomes.position.World.Environment.OVERWORLD;
case NETHER -> net.william278.huskhomes.position.World.Environment.NETHER;
case THE_END -> net.william278.huskhomes.position.World.Environment.THE_END;
case CUSTOM -> net.william278.huskhomes.position.World.Environment.CUSTOM;
}, adaptLocation(world.getSpawnLocation()).orElse(null)));
}
}
@@ -0,0 +1,62 @@
package net.william278.huskhomes.util;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.World;
import org.bukkit.ChunkSnapshot;
import org.bukkit.Material;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
public class BukkitSafetyUtil {
/**
* Finds a safe location to teleport to about a point.
*
* @param world The world to search in
* @param bukkitLocation The location to search around
* @param chunkSnapshot The chunk snapshot to search in
* @return The safe location, if found
*/
public static Optional<Location> findSafeLocation(@NotNull World world, @NotNull org.bukkit.Location bukkitLocation,
@NotNull ChunkSnapshot chunkSnapshot) {
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int chunkX = Math.abs(bukkitLocation.getBlockX() % 16) + i;
int chunkZ = Math.abs(bukkitLocation.getBlockZ() % 16) + j;
if (chunkX < 0 || chunkX > 15 || chunkZ < 0 || chunkZ > 15) {
continue;
}
int chunkY = chunkSnapshot.getHighestBlockYAt(chunkX, chunkZ);
if (isSafePosition(chunkSnapshot, chunkX, chunkY, chunkZ)) {
return Optional.of(new Location(bukkitLocation.getBlockX() + i,
chunkY + 1.5d, bukkitLocation.getBlockZ() + j,
90, 0, world));
}
}
}
return Optional.empty();
}
/**
* Searches a chunk and returns if a block is safe to teleport to.
*
* @param chunkSnapshot The chunk snapshot to search in
* @param chunkX The chunk x coordinate to search at
* @param chunkY The chunk y coordinate to search at
* @param chunkZ The chunk z coordinate to search at
* @return True if the block is safe, false otherwise
*/
public static boolean isSafePosition(@NotNull ChunkSnapshot chunkSnapshot, final int chunkX, final int chunkY, final int chunkZ) {
final Material blockType = chunkSnapshot.getBlockType(chunkX, chunkY, chunkZ);
return switch (blockType) {
// Special case handling for safe, un-solid blocks
case TALL_GRASS, TALL_SEAGRASS, FERN, LARGE_FERN, DANDELION, POPPY, BLUE_ORCHID, ALLIUM, AZURE_BLUET,
RED_TULIP, ORANGE_TULIP, WHITE_TULIP, PINK_TULIP, OXEYE_DAISY, CORNFLOWER, LILY_OF_THE_VALLEY,
ROSE_BUSH, WHEAT_SEEDS, BEETROOT_SEEDS, MELON_SEEDS, PUMPKIN_SEEDS, GRASS_PATH, FARMLAND,
OAK_LEAVES, BIRCH_LEAVES, DEAD_BUSH, SUGAR_CANE, SNOW, ICE, BLUE_ICE, FROSTED_ICE -> true;
default -> blockType.isSolid() || blockType.isOccluding();
};
}
}
+2
View File
@@ -55,5 +55,7 @@ commands:
tpdecline:
usage: /tpdecline
aliases: [tpdeny, tpno]
rtp:
usage: /rtp
back:
usage: /back
+2
View File
@@ -14,6 +14,8 @@ dependencies {
compileOnly 'org.xerial:sqlite-jdbc:' + sqlite_driver_version
compileOnly 'mysql:mysql-connector-java:' + mysql_driver_version
compileOnly 'org.jetbrains:annotations:23.0.0'
testImplementation 'com.github.yuriy-g:simple-java-plot:5c502c2e98'
}
shadowJar {
@@ -1,12 +0,0 @@
package net.william278.huskhomes;
/**
* Indicates that economy features of the plugin have tried to be accessed when they are not enabled.
*/
public class EconomyUnsupportedException extends HuskHomesException {
public EconomyUnsupportedException(String message) {
super(message);
}
}
@@ -3,14 +3,16 @@ package net.william278.huskhomes;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.hook.PluginHook;
import net.william278.huskhomes.messenger.NetworkMessenger;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.position.SavedPositionManager;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.random.RtpEngine;
import net.william278.huskhomes.request.RequestManager;
import net.william278.huskhomes.teleport.TeleportManager;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.Version;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -42,7 +44,7 @@ public interface HuskHomes {
List<OnlineUser> getOnlinePlayers();
/**
* Finds a {@link OnlineUser} by their name. Auto-completes partially typed names for a closest match
* Finds a {@link OnlineUser} by their name. Auto-completes partially typed names for the closest match
*
* @param playerName the name of the player to find
* @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found
@@ -119,6 +121,74 @@ public interface HuskHomes {
@Nullable
NetworkMessenger getNetworkMessenger();
/**
* The {@link RtpEngine} that manages random teleports
*
* @return the {@link RtpEngine} implementation
*/
@NotNull
RtpEngine getRtpEngine();
/**
* Set of active {@link PluginHook}s running on the server
*
* @return the {@link Set} of active {@link PluginHook}s
*/
@NotNull
Set<PluginHook> getPluginHooks();
/**
* Perform an economy check on the {@link OnlineUser}; returning {@code true} if it passes the check
*
* @param player the player to perform the check on
* @param action the action to perform
* @return {@code true} if the action passes the check, {@code false} if the user has insufficient funds
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
default boolean validateEconomyCheck(@NotNull OnlineUser player, @NotNull Settings.EconomyAction action) {
final Optional<Double> cost = getSettings().getEconomyCost(action).map(Math::abs);
if (cost.isPresent() && !player.hasPermission(Permission.BYPASS_ECONOMY_CHECKS.node)) {
final Optional<EconomyHook> hook = getPluginHooks().stream().filter(pluginHook ->
pluginHook instanceof EconomyHook).findFirst().map(pluginHook -> (EconomyHook) pluginHook);
if (hook.isPresent()) {
if (cost.get() > hook.get().getPlayerBalance(player)) {
getLocales().getLocale("error_insufficient_funds", hook.get().formatCurrency(cost.get()))
.ifPresent(player::sendMessage);
return false;
}
}
}
return true;
}
/**
* Execute an economy transaction if needed, updating the player's balance
*
* @param player the player to deduct the cost from if needed
* @param action the action to deduct the cost from if needed
*/
default void performEconomyTransaction(@NotNull OnlineUser player, @NotNull Settings.EconomyAction action) {
final Optional<Double> cost = getSettings().getEconomyCost(action).map(Math::abs);
if (cost.isPresent() && !player.hasPermission(Permission.BYPASS_ECONOMY_CHECKS.node)) {
final Optional<EconomyHook> hook = getPluginHooks().stream().filter(pluginHook ->
pluginHook instanceof EconomyHook).findFirst().map(pluginHook -> (EconomyHook) pluginHook);
if (hook.isPresent()) {
hook.get().changePlayerBalance(player, -cost.get());
getLocales().getLocale(action.confirmationLocaleId, hook.get().formatCurrency(cost.get()))
.ifPresent(player::sendMessage);
}
}
}
/**
* Returns a safe ground location for the specified {@link Location} if possible
*
* @param location the {@link Location} to find a safe ground location for
* @return a {@link CompletableFuture} that will complete with an optional of the safe ground position, if it is
* possible to find one
*/
CompletableFuture<Optional<Location>> getSafeGroundLocation(@NotNull Location location);
/**
* Get the {@link Server} this server is on
*
@@ -126,6 +196,14 @@ public interface HuskHomes {
*/
CompletableFuture<Server> getServer(@NotNull OnlineUser requester);
/**
* Returns a list of worlds on the server
*
* @return a list of worlds on the server
*/
@NotNull
List<World> getWorlds();
/**
* Returns true if the position is a valid location on the server
*
@@ -1,21 +1,31 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
public class BackCommand extends CommandBase {
public BackCommand(@NotNull HuskHomes implementor) {
protected BackCommand(@NotNull HuskHomes implementor) {
super("back", Permission.COMMAND_BACK, implementor);
}
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
plugin.getDatabase().getLastPosition(onlineUser).thenAccept(lastPosition ->
lastPosition.ifPresentOrElse(position -> plugin.getTeleportManager().timedTeleport(onlineUser, position)
.thenAccept(result -> plugin.getTeleportManager().finishTeleport(onlineUser, result)),
lastPosition.ifPresentOrElse(position -> {
// Validate the /back command economy action and that the user has sufficient funds if needed
if (!plugin.validateEconomyCheck(onlineUser, Settings.EconomyAction.BACK_COMMAND)) {
return;
}
plugin.performEconomyTransaction(onlineUser, Settings.EconomyAction.BACK_COMMAND);
// Teleport the player
plugin.getTeleportManager().timedTeleport(onlineUser, position)
.thenAccept(result -> plugin.getTeleportManager().finishTeleport(onlineUser, result));
},
() -> plugin.getLocales().getLocale("error_no_last_position").ifPresent(onlineUser::sendMessage)));
}
@@ -13,7 +13,7 @@ import java.util.stream.Collectors;
public class DelHomeCommand extends CommandBase implements TabCompletable, ConsoleExecutable {
public DelHomeCommand(@NotNull HuskHomes implementor) {
protected DelHomeCommand(@NotNull HuskHomes implementor) {
super("delhome", Permission.COMMAND_DELETE_HOME, implementor);
}
@@ -11,7 +11,7 @@ import java.util.stream.Collectors;
public class DelWarpCommand extends CommandBase implements TabCompletable, ConsoleExecutable {
public DelWarpCommand(@NotNull HuskHomes implementor) {
protected DelWarpCommand(@NotNull HuskHomes implementor) {
super("delwarp", Permission.COMMAND_DELETE_WARP, implementor);
}
@@ -2,6 +2,7 @@ package net.william278.huskhomes.command;
import de.themoep.minedown.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.PositionMeta;
@@ -204,26 +205,46 @@ public class EditHomeCommand extends CommandBase implements TabCompletable, Cons
return;
}
//todo economy check here
plugin.getSavedPositionManager().updateHomePrivacy(home, newIsPublic).thenRun(() -> {
if (home.owner.uuid.equals(editor.uuid)) {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success",
home.meta.name).orElse(new MineDown("")));
} else {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success_other",
home.owner.username, home.meta.name).orElse(new MineDown("")));
// Perform checks if making the home public
if (newIsPublic && !otherOwner) {
// Check against maximum public homes
final List<Home> existingPublicHomes = plugin.getDatabase().getHomes(editor).join().stream()
.filter(existingHome -> existingHome.isPublic).toList();
final int maxPublicHomes = editor.getMaxPublicHomes(plugin.getSettings().maxPublicHomes,
plugin.getSettings().stackPermissionLimits);
if (existingPublicHomes.size() >= maxPublicHomes) {
plugin.getLocales().getLocale("error_edit_home_maximum_public_homes")
.ifPresent(editor::sendMessage);
return;
}
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
getHomeEditorWindow(home, false, otherOwner,
!otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node))
.forEach(editor::sendMessage);
// Check against economy
if (!plugin.validateEconomyCheck(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC)) {
return;
}
});
}
// Execute the update
plugin.getSavedPositionManager().updateHomePrivacy(home, newIsPublic).join();
if (home.owner.uuid.equals(editor.uuid)) {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success",
home.meta.name).orElse(new MineDown("")));
} else {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success_other",
home.owner.username, home.meta.name).orElse(new MineDown("")));
}
// Perform necessary economy transaction
plugin.performEconomyTransaction(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC);
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
getHomeEditorWindow(home, false, otherOwner,
!otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node))
.forEach(editor::sendMessage);
}
}
default -> plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome <name> [" + String.join("|", EDIT_HOME_COMPLETIONS) + "] [args]")
@@ -20,7 +20,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable, Cons
private final String[] EDIT_WARP_COMPLETIONS = {"rename", "description", "relocate"};
public EditWarpCommand(@NotNull HuskHomes implementor) {
protected EditWarpCommand(@NotNull HuskHomes implementor) {
super("editwarp", Permission.COMMAND_EDIT_WARP, implementor);
}
@@ -12,7 +12,7 @@ import java.util.stream.Collectors;
public class HomeCommand extends CommandBase implements TabCompletable, ConsoleExecutable {
public HomeCommand(@NotNull HuskHomes implementor) {
protected HomeCommand(@NotNull HuskHomes implementor) {
super("home", Permission.COMMAND_HOME, implementor);
}
@@ -7,7 +7,7 @@ import org.jetbrains.annotations.NotNull;
public class HomeListCommand extends CommandBase implements ConsoleExecutable {
public HomeListCommand(@NotNull HuskHomes implementor) {
protected HomeListCommand(@NotNull HuskHomes implementor) {
super("homelist", Permission.COMMAND_HOME, implementor, "homes");
}
@@ -15,7 +15,7 @@ import java.util.stream.Collectors;
public class PublicHomeCommand extends CommandBase implements TabCompletable, ConsoleExecutable {
public PublicHomeCommand(@NotNull HuskHomes implementor) {
protected PublicHomeCommand(@NotNull HuskHomes implementor) {
super("publichome", Permission.COMMAND_PUBLIC_HOME, implementor, "phome");
}
@@ -7,7 +7,7 @@ import org.jetbrains.annotations.NotNull;
public class PublicHomeListCommand extends CommandBase implements ConsoleExecutable {
public PublicHomeListCommand(@NotNull HuskHomes implementor) {
protected PublicHomeListCommand(@NotNull HuskHomes implementor) {
super("publichomelist", Permission.COMMAND_HOME, implementor, "phomelist", "phomes");
}
@@ -0,0 +1,54 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
public class RtpCommand extends CommandBase implements ConsoleExecutable {
protected RtpCommand(@NotNull HuskHomes implementor) {
super("rtp", Permission.COMMAND_RTP, implementor);
}
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length != 0) {
plugin.getLocales().getLocale("error_invalid_syntax", "/rtp")
.ifPresent(onlineUser::sendMessage);
return;
}
final Position userPosition = onlineUser.getPosition().join();
if (plugin.getSettings().rtpRestrictedWorlds.stream()
.anyMatch(worldName -> worldName.equals(userPosition.world.name))) {
plugin.getLocales().getLocale("error_rtp_restricted_world")
.ifPresent(onlineUser::sendMessage);
return;
}
if (!plugin.validateEconomyCheck(onlineUser, Settings.EconomyAction.RANDOM_TELEPORT)) {
return;
}
plugin.getRtpEngine().getRandomPosition(userPosition)
.thenAccept(position -> {
if (position.isEmpty()) {
plugin.getLocales().getLocale("error_rtp_randomization_timeout")
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.getTeleportManager().timedTeleport(onlineUser, position.get())
.thenAccept(result -> {
plugin.getTeleportManager().finishTeleport(onlineUser, result);
plugin.performEconomyTransaction(onlineUser, Settings.EconomyAction.RANDOM_TELEPORT);
});
});
}
@Override
public void onConsoleExecute(@NotNull String[] args) {
//todo
}
}
@@ -2,51 +2,109 @@ package net.william278.huskhomes.command;
import de.themoep.minedown.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.SavedPositionManager;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
public class SetHomeCommand extends CommandBase {
public SetHomeCommand(@NotNull HuskHomes implementor) {
protected SetHomeCommand(@NotNull HuskHomes implementor) {
super("sethome", Permission.COMMAND_SET_HOME, implementor);
}
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
switch (args.length) {
case 0 -> plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> {
if (homes.isEmpty()) {
setHome(onlineUser, onlineUser, "home");
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/sethome <name>")
.ifPresent(onlineUser::sendMessage);
plugin.getDatabase().getHomes(onlineUser).thenAccept(homes -> {
switch (args.length) {
case 0 -> {
if (homes.isEmpty()) {
setHome(onlineUser, "home", homes);
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/sethome <name>")
.ifPresent(onlineUser::sendMessage);
}
}
});
case 1 -> setHome(onlineUser, onlineUser, args[0]);
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/sethome <name>")
.ifPresent(onlineUser::sendMessage);
}
case 1 -> setHome(onlineUser, args[0], homes);
default -> plugin.getLocales().getLocale("error_invalid_syntax", "/sethome <name>")
.ifPresent(onlineUser::sendMessage);
}
});
}
private void setHome(@NotNull OnlineUser onlineUser, @NotNull User user, @NotNull String homeName) {
onlineUser.getPosition().thenAccept(position -> plugin.getSavedPositionManager().setHome(new PositionMeta(homeName,
plugin.getLocales().getRawLocale("home_default_description", user.username).orElse("")),
user, position).thenAccept(setResult ->
(switch (setResult.resultType()) {
case SUCCESS -> {
assert setResult.savedPosition().isPresent();
yield plugin.getLocales().getLocale("set_home_success", setResult.savedPosition().get().meta.name);
}
case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_home_name_taken");
case FAILED_NAME_LENGTH -> plugin.getLocales().getLocale("error_home_name_length");
case FAILED_NAME_CHARACTERS -> plugin.getLocales().getLocale("error_home_name_characters");
default -> Optional.of(new MineDown(""));
}).ifPresent(onlineUser::sendMessage)));
/**
* Attempts to set a home by given name for the {@link OnlineUser}.
* <p>
* A number of validation checks will take place before the home is set. If these checks fail, the home won't be set.
* <ul>
* <li>The user's currentHomes must not exceed the permissive maximum home limit</li>
* <li>If economy features are on and the user does not have enough home slots, they must have sufficient funds to buy another</li>
* <li>The home name must not already exist</li>
* <li>The home name must meet the length and character criteria</li>
* </ul>
*
* @param onlineUser The {@link OnlineUser} to set the home for
* @param homeName The name of the home to set
* @param currentHomes The current homes of the {@link OnlineUser}
*/
private void setHome(@NotNull OnlineUser onlineUser, @NotNull String homeName, @NotNull List<Home> currentHomes) {
// Check against maximum homes
final int maxHomes = onlineUser.getMaxHomes(plugin.getSettings().maxHomes, plugin.getSettings().stackPermissionLimits);
if (currentHomes.size() >= maxHomes) {
plugin.getLocales().getLocale("error_set_home_maximum_homes", Integer.toString(maxHomes))
.ifPresent(onlineUser::sendMessage);
return;
}
// Check against economy if needed
boolean newSlotNeeded = false;
UserData userDataToUpdate = null;
if (plugin.getSettings().economy) {
final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().freeHomeSlots, plugin.getSettings().stackPermissionLimits);
final Optional<UserData> fetchedData = plugin.getDatabase().getUserData(onlineUser.uuid).join();
if (fetchedData.isPresent()) {
newSlotNeeded = (currentHomes.size() + 1) > (freeHomes + fetchedData.get().homeSlots());
}
// If a new slot is needed, validate the user has enough funds to purchase one
if (newSlotNeeded) {
if (!plugin.validateEconomyCheck(onlineUser, Settings.EconomyAction.ADDITIONAL_HOME_SLOT)) {
return;
}
userDataToUpdate = new UserData(onlineUser, (currentHomes.size() + 1) - freeHomes,
fetchedData.get().ignoringTeleports(), fetchedData.get().rtpCooldown());
}
}
// Set the home in the saved position manager
final SavedPositionManager.SaveResult setResult = plugin.getSavedPositionManager()
.setHome(new PositionMeta(homeName, plugin.getLocales().getRawLocale("home_default_description",
onlineUser.username).orElse("")), onlineUser, onlineUser.getPosition().join()).join();
// Display feedback of the result of the set operation
(switch (setResult.resultType()) {
case SUCCESS -> {
assert setResult.savedPosition().isPresent();
// If the user needed to buy a new slot, perform the transaction and update their data
if (newSlotNeeded) {
plugin.performEconomyTransaction(onlineUser, Settings.EconomyAction.ADDITIONAL_HOME_SLOT);
plugin.getDatabase().updateUserData(userDataToUpdate).join();
}
yield plugin.getLocales().getLocale("set_home_success", setResult.savedPosition().get().meta.name);
}
case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_home_name_taken");
case FAILED_NAME_LENGTH -> plugin.getLocales().getLocale("error_home_name_length");
case FAILED_NAME_CHARACTERS -> plugin.getLocales().getLocale("error_home_name_characters");
default -> Optional.of(new MineDown(""));
}).ifPresent(onlineUser::sendMessage);
}
}
@@ -11,7 +11,7 @@ import java.util.Optional;
public class SetWarpCommand extends CommandBase {
public SetWarpCommand(@NotNull HuskHomes implementor) {
protected SetWarpCommand(@NotNull HuskHomes implementor) {
super("setwarp", Permission.COMMAND_SET_WARP, implementor);
}
@@ -32,7 +32,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
return;
}
// If the first argument is a player
// If the first argument is a player target
if (args.length == 1) {
targetPosition = new TeleportCommandTarget(args[0]);
} else {
@@ -10,7 +10,7 @@ import java.util.stream.Collectors;
public class WarpCommand extends CommandBase implements TabCompletable, ConsoleExecutable {
public WarpCommand(@NotNull HuskHomes implementor) {
protected WarpCommand(@NotNull HuskHomes implementor) {
super("warp", Permission.COMMAND_WARP, implementor);
}
@@ -7,7 +7,7 @@ import org.jetbrains.annotations.NotNull;
public class WarpListCommand extends CommandBase implements ConsoleExecutable {
public WarpListCommand(@NotNull HuskHomes implementor) {
protected WarpListCommand(@NotNull HuskHomes implementor) {
super("warplist", Permission.COMMAND_WARP, implementor, "warps");
}
@@ -5,6 +5,7 @@ import net.william278.annotaml.KeyPath;
import net.william278.annotaml.YamlFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -81,6 +82,9 @@ public class Settings {
@KeyPath("general.max_public_homes")
public int maxPublicHomes = 10;
@KeyPath("general.stack_permission_limits")
public boolean stackPermissionLimits = true;
@KeyPath("general.teleport_warmup_time")
public int teleportWarmupTime = 5;
@@ -102,9 +106,6 @@ public class Settings {
@KeyPath("general.allow_unicode_descriptions")
public boolean allowUnicodeDescriptions = true;
@KeyPath("general.handle_vanished_players")
public boolean handleVanishedPlayers = true;
@KeyPath("general.use_paper_lib")
public boolean usePaperLib = true;
@@ -146,6 +147,52 @@ public class Settings {
public boolean redisUseSsl = false;
// Rtp command settings
@KeyPath("rtp.radius")
public int rtpRadius = 5000;
@KeyPath("rtp.spawn_radius")
public int rtpSpawnRadius = 500;
@KeyPath("rtp.distribution_mean")
public float rtpDistributionMean = 0.75f;
@KeyPath("rtp.distribution_deviation")
public float rtpDistributionStandardDeviation = 2f;
@KeyPath("rtp.location_cache_size")
public int rtpLocationCacheSize = 10;
@KeyPath("rtp.restricted_worlds")
public List<String> rtpRestrictedWorlds = List.of("world_nether", "world_the_end");
// Economy settings
@KeyPath("economy.enabled")
public boolean economy = false;
@KeyPath("economy.free_home_slots")
public int freeHomeSlots = 5;
@KeyPath("economy.costs")
public Map<String, Double> economyCosts = Map.of(
EconomyAction.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyAction.ADDITIONAL_HOME_SLOT.defaultCost,
EconomyAction.MAKE_HOME_PUBLIC.name(), EconomyAction.MAKE_HOME_PUBLIC.defaultCost,
EconomyAction.RANDOM_TELEPORT.name().toLowerCase(), EconomyAction.RANDOM_TELEPORT.defaultCost,
EconomyAction.BACK_COMMAND.name(), EconomyAction.BACK_COMMAND.defaultCost
);
public Optional<Double> getEconomyCost(@NotNull EconomyAction action) {
if (!economy) {
return Optional.empty();
}
final Double cost = economyCosts.get(action.name().toLowerCase());
if (cost != null && cost > 0d) {
return Optional.of(cost);
}
return Optional.empty();
}
@SuppressWarnings("unused")
public Settings() {
}
@@ -209,6 +256,25 @@ public class Settings {
}
}
/**
* Identifies actions that incur an economic cost if economy is enabled
*/
public enum EconomyAction {
ADDITIONAL_HOME_SLOT(100.00, "economy_action_additional_home_slot"),
MAKE_HOME_PUBLIC(50.00, "economy_action_make_home_public"),
RANDOM_TELEPORT(25.00, "economy_action_random_teleport"),
BACK_COMMAND(0.00, "economy_action_back_command");
private final double defaultCost;
@NotNull
public final String confirmationLocaleId;
EconomyAction(final double defaultCost, @NotNull String confirmationLocaleId) {
this.defaultCost = defaultCost;
this.confirmationLocaleId = confirmationLocaleId;
}
}
/**
* Identifies types of databases
*/
@@ -0,0 +1,40 @@
package net.william278.huskhomes.hook;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import org.jetbrains.annotations.NotNull;
/**
* A hook that provides economy features
*/
public abstract class EconomyHook extends PluginHook {
protected EconomyHook(@NotNull HuskHomes implementor, @NotNull String hookName) {
super(implementor, hookName);
}
/**
* Get the balance of a player
*
* @param player the player to get the balance of
* @return the balance of the player
*/
public abstract double getPlayerBalance(@NotNull OnlineUser player);
/**
* Set the balance of a player
*
* @param player the player to set the balance of
* @param amount the amount to set the balance to
*/
public abstract void changePlayerBalance(@NotNull OnlineUser player, final double amount);
/**
* Format a balance to a string
*
* @param amount the amount to format
* @return the formatted string
*/
public abstract String formatCurrency(final double amount);
}
@@ -0,0 +1,46 @@
package net.william278.huskhomes.hook;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.HuskHomesInitializationException;
import org.jetbrains.annotations.NotNull;
/**
* A plugin hook, where HuskHomes hooks into another plugin
*/
public abstract class PluginHook {
/**
* The plugin that this hook is for
*/
protected final HuskHomes plugin;
/**
* The name of the hook
*/
protected final String hookName;
/**
* Construct a new {@link PluginHook}
*
* @param implementor the {@link HuskHomes} instance
*/
protected PluginHook(@NotNull HuskHomes implementor, @NotNull String hookName) {
this.plugin = implementor;
this.hookName = hookName;
}
/**
* Initialize the hook and return {@code true} if it could be enabled
*
* @return {@code true} if the hook could be enabled
* @throws HuskHomesInitializationException if an exception occurred enabling the hook
*/
public abstract boolean initialize() throws HuskHomesInitializationException;
@NotNull
public String getHookName() {
return hookName;
}
}
@@ -4,9 +4,10 @@ import de.themoep.minedown.MineDown;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.TeleportResult;
import net.william278.huskhomes.EconomyUnsupportedException;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -49,6 +50,14 @@ public abstract class OnlineUser extends User {
*/
public abstract boolean hasPermission(@NotNull String node);
/**
* Returns a {@link Map} of a player's permission nodes
*
* @return a {@link Map} of all permissions this player has to their set values
*/
@NotNull
public abstract Map<String, Boolean> getPermissions();
/**
* Dispatch a MineDown-formatted action bar message to this player
*
@@ -72,33 +81,84 @@ public abstract class OnlineUser extends User {
public abstract CompletableFuture<TeleportResult> teleport(Location location);
/**
* Returns the maximum number of homes this player can set
* Get the maximum number of homes this user may set
*
* @return a {@link CompletableFuture} providing the max number of homes this player can set
* @param defaultMaxHomes the default maximum number of homes if the user has not set a custom value
* @param stack whether to stack numerical permissions that grant the user extra max homes
* @return the maximum number of homes this user may set
*/
public abstract CompletableFuture<Integer> getMaxHomes();
public final int getMaxHomes(final int defaultMaxHomes, final boolean stack) {
final List<Integer> homes = getNumericalPermissions("huskhomes.max_homes.");
if (homes.isEmpty()) {
return defaultMaxHomes;
}
if (stack) {
return defaultMaxHomes + homes.stream().reduce(0, Integer::sum);
} else {
return homes.get(0);
}
}
/**
* Returns the number of homes this player can set for free
* Get the number of homes this user may make public
*
* @return a {@link CompletableFuture} providing the max number of homes this player can set
* @param defaultPublicHomes the default number of homes this user may make public
* @param stack whether to stack numerical permissions that grant the user extra public homes
* @return the number of public home slots this user may set
*/
public abstract CompletableFuture<Integer> getFreeHomes();
public int getMaxPublicHomes(final int defaultPublicHomes, final boolean stack) {
final List<Integer> homes = getNumericalPermissions("huskhomes.max_public_homes.");
if (homes.isEmpty()) {
return defaultPublicHomes;
}
if (stack) {
return defaultPublicHomes + homes.stream().reduce(0, Integer::sum);
} else {
return homes.get(0);
}
}
/**
* Get this player's economy balance
* Get the number of free home slots this user may set
*
* @return the player's economy balance
* @throws EconomyUnsupportedException if the economy integration is not enabled
* @param defaultFreeHomes the default number of free home slots to give this user
* @param stack whether to stack numerical permissions that grant the user extra free homes
* @return the number of free home slots this user may set
*/
public abstract double getEconomyBalance() throws EconomyUnsupportedException;
public int getFreeHomes(final int defaultFreeHomes, final boolean stack) {
final List<Integer> homes = getNumericalPermissions("huskhomes.free_homes.");
if (homes.isEmpty()) {
return defaultFreeHomes;
}
if (stack) {
return defaultFreeHomes + homes.stream().reduce(0, Integer::sum);
} else {
return homes.get(0);
}
}
/**
* Deduct money from this player's economy balance
* Gets a list of numbers from the prefixed permission nodes
*
* @throws EconomyUnsupportedException if the economy integration is not enabled
* @param nodePrefix the prefix of the permission nodes to get
* @return a list of numbers from the prefixed permission nodes, sorted by size
*/
public abstract void deductEconomyBalance() throws EconomyUnsupportedException;
private List<Integer> getNumericalPermissions(@NotNull String nodePrefix) {
return getPermissions().entrySet().stream()
.filter(Map.Entry::getValue)
.filter(permission -> permission.getKey().startsWith(nodePrefix))
.filter(permission -> {
try {
// Remove node prefix from the permission and parse as an integer
Integer.parseInt(permission.getKey().substring(nodePrefix.length()));
} catch (final NumberFormatException e) {
return false;
}
return true;
})
.map(permission -> Integer.parseInt(permission.getKey().substring(nodePrefix.length())))
.sorted().toList();
}
}
@@ -37,6 +37,15 @@ public class Location {
*/
public World world;
public Location(double x, double y, double z, @NotNull World world) {
this.x = x;
this.y = y;
this.z = z;
this.yaw = 0;
this.pitch = 0;
this.world = world;
}
public Location(double x, double y, double z, float yaw, float pitch,
@NotNull World world) {
this.x = x;
@@ -1,6 +1,7 @@
package net.william278.huskhomes.position;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
@@ -19,12 +20,42 @@ public class World {
*/
public UUID uuid;
/**
* Environment of the world ({@link Environment#OVERWORLD}, {@link Environment#NETHER}, {@link Environment#THE_END},
* or {@link Environment#CUSTOM})
*/
@Nullable
public Environment environment;
/**
* Spawn location of the world
*/
@Nullable
public Location spawn;
public World(@NotNull String name, @NotNull UUID uuid) {
this.name = name;
this.uuid = uuid;
}
public World(@NotNull String name, @NotNull UUID uuid, @Nullable Environment environment, @Nullable Location spawn) {
this.name = name;
this.uuid = uuid;
this.environment = environment;
this.spawn = spawn;
}
public World() {
}
/**
* Identifies the environment of the world
*/
public enum Environment {
OVERWORLD,
NETHER,
THE_END,
CUSTOM
}
}
@@ -0,0 +1,77 @@
package net.william278.huskhomes.random;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Location;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class NormalDistributionEngine extends RtpEngine {
private final HuskHomes plugin;
private final float mean;
private final float standardDeviation;
public NormalDistributionEngine(@NotNull HuskHomes implementor) {
super(implementor, "Normal Distribution");
this.mean = implementor.getSettings().rtpDistributionMean;
this.standardDeviation = implementor.getSettings().rtpDistributionStandardDeviation;
this.plugin = implementor;
}
@Override
protected @NotNull CompletableFuture<Optional<Location>> generateRandomPosition(@NotNull Location origin) {
return CompletableFuture.supplyAsync(() -> plugin.getSafeGroundLocation(generateLocation(origin, mean,
standardDeviation, spawnRadius, radius)).join())
.orTimeout(5, TimeUnit.SECONDS)
.exceptionally(throwable -> Optional.empty());
}
/**
* Generate a location through a randomized normally-distributed radius and random angle using the mean and
* standard deviation, about the origin position.
*
* @param origin The origin position
* @return A generated location
*/
protected static Location generateLocation(@NotNull Location origin, float mean, float standardDeviation,
float spawnRadius, float maxRadius) {
// Generate random values
final float radius = generateNormallyDistributedRadius(mean, standardDeviation, spawnRadius, maxRadius);
final float angle = generateRandomAngle();
// Calculate corresponding x and z
final float z = (float) (radius * Math.cos(angle));
final float x = (float) (radius * Math.sin(angle));
return new Location(origin.x + x, 128, origin.z + z,
origin.yaw, origin.pitch, origin.world);
}
/**
* Generates a normally distributed radius between the spawnRadius and the maximum radius value,
* using the provided standard deviation and mean.
*
* @return the generated radius
*/
private static float generateNormallyDistributedRadius(float mean, float standardDeviation,
float spawnRadius, float maxRadius) {
double value = new Random().nextGaussian(mean, standardDeviation) * maxRadius;
if (value < spawnRadius || value > maxRadius) {
return generateNormallyDistributedRadius(mean, standardDeviation, spawnRadius, maxRadius);
}
return (float) value;
}
/**
* Generates a random angle in the range [0, 360]
*
* @return a random angle in the range [0, 360]
*/
private static float generateRandomAngle() {
return (float) (Math.random() * 360);
}
}
@@ -0,0 +1,128 @@
package net.william278.huskhomes.random;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* An engine for random teleportation, that generates and caches random points
*/
public abstract class RtpEngine {
@NotNull
protected final String name;
protected final int radius;
protected final int spawnRadius;
protected final int cacheSize;
@NotNull
private final List<World> worlds;
@NotNull
private final Map<World, Queue<Location>> cachedRandomLocations;
protected RtpEngine(@NotNull HuskHomes implementor, @NotNull String name) {
this.name = name;
this.radius = implementor.getSettings().rtpRadius;
this.spawnRadius = implementor.getSettings().rtpSpawnRadius;
this.cacheSize = implementor.getSettings().rtpLocationCacheSize;
this.worlds = implementor.getWorlds().stream()
.filter(world -> world.environment != World.Environment.NETHER)
.filter(world -> !implementor.getSettings().rtpRestrictedWorlds.contains(world.name))
.collect(Collectors.toList());
this.cachedRandomLocations = new HashMap<>();
}
//todo better API for this?
protected RtpEngine(@NotNull String name, int radius, int spawnRadius, int cacheSize, @NotNull List<World> worlds) {
this.name = name;
this.radius = radius;
this.spawnRadius = spawnRadius;
this.cacheSize = cacheSize;
this.worlds = worlds;
this.cachedRandomLocations = new HashMap<>();
}
/**
* Initializes the RTP engine, populating the cache. This is to be called after the engine has been created.
*/
public void initialize() {
CompletableFuture.runAsync(() -> {
for (final World world : worlds) {
cachedRandomLocations.put(world, new LinkedList<>());
populateCache(world, cacheSize);
}
});
}
/**
* Populates the cache with new random locations
*
* @param world The world to populate the cache for
* @param cacheSize The size of the cache
*/
private void populateCache(@NotNull World world, final int cacheSize) {
final int amountToPopulate = Math.max(1, cacheSize) - cachedRandomLocations.get(world).size();
for (final AtomicInteger i = new AtomicInteger(); i.get() < amountToPopulate; i.getAndIncrement()) {
generateRandomPosition(new Location(0, 0, 0, 0f, 0f, world)).join()
.ifPresentOrElse(location -> cachedRandomLocations.get(world).add(location), i::getAndDecrement);
}
}
/**
* Generates a new random position within the radius of the origin position.
*
* @param origin The origin position
* @return A generated location
*/
@NotNull
protected abstract CompletableFuture<Optional<Location>> generateRandomPosition(@NotNull Location origin);
/**
* Returns a random {@link Position} from the cache, generating only if needed
*
* @param userPosition The user's position
* @return A random {@link Position}
*/
public CompletableFuture<Optional<Position>> getRandomPosition(@NotNull Position userPosition) {
return getRandomLocation(userPosition.world).thenApply(location -> {
if (location.isEmpty()) {
return Optional.empty();
}
return Optional.of(new Position(location.get().x, location.get().y, location.get().z, location.get().yaw,
location.get().pitch, location.get().world, userPosition.server));
});
}
/**
* Returns a random {@link Location} on this server from the cache, only generating if necessary
*
* @param world the {@link World} to search for a random {@link Location}
* @return a {@link CompletableFuture} containing an {@link Optional} containing a {@link Location} if one was found;
* an {@link Optional#empty()} otherwise
*/
private CompletableFuture<Optional<Location>> getRandomLocation(@NotNull World world) {
return CompletableFuture.supplyAsync(() -> {
final Optional<World> keyedWorld = cachedRandomLocations.keySet().stream()
.filter(cachedWorld -> cachedWorld.uuid.equals(world.uuid)).findFirst();
if (keyedWorld.isPresent()) {
final Queue<Location> cachedWorldLocations = cachedRandomLocations.get(keyedWorld.get());
if (!cachedWorldLocations.isEmpty()) {
populateCache(keyedWorld.get(), cacheSize);
return Optional.of(cachedWorldLocations.remove());
} else {
populateCache(keyedWorld.get(), cacheSize);
}
}
return generateRandomPosition(world.spawn != null ? world.spawn : new Location(0, 0, 0, world))
.join();
}).orTimeout(5, TimeUnit.SECONDS).exceptionally(throwable -> Optional.empty());
}
}
@@ -83,7 +83,7 @@ public class TeleportManager {
*/
public void teleportToWarpByName(@NotNull OnlineUser onlineUser, @NotNull String warpName) {
plugin.getDatabase().getWarp(warpName).thenAccept(optionalWarp ->
optionalWarp.ifPresentOrElse(warp -> //todo permission restricted warps
optionalWarp.ifPresentOrElse(warp ->
teleportToWarp(onlineUser, warp), () ->
plugin.getLocales().getLocale("error_warp_invalid", warpName)
.ifPresent(onlineUser::sendMessage)));
@@ -96,6 +96,7 @@ public class TeleportManager {
* @param warp the {@link Warp} to teleport to
*/
public void teleportToWarp(@NotNull OnlineUser onlineUser, @NotNull Warp warp) {
//todo permission restricted warps
timedTeleport(onlineUser, warp).thenAccept(result -> finishTeleport(onlineUser, result));
}
@@ -19,6 +19,10 @@ public enum Permission {
* Lets the user bypass the cooldown on the {@code /rtp} command
*/
BYPASS_RTP_COOLDOWN("huskhomes.bypass.rtp_cooldown", DefaultAccess.NOBODY),
/**
* Lets the user bypass economy costs when teleporting
*/
BYPASS_ECONOMY_CHECKS("huskhomes.bypass.economy", DefaultAccess.NOBODY),
/*
* Command permission nodes
@@ -81,7 +85,7 @@ public enum Permission {
*/
COMMAND_TP("huskhomes.command.tp", DefaultAccess.OPERATORS),
/**
* Lets the user instantly tp to a set of coordinates ({@code /tp [x] [y] [z] [yaw] [pitch] [world] [server]})
* Lets the user instantly tp to a set of coordinates ({@code /tp [x] [y] [z] [world] [server]})
*/
COMMAND_TP_TO_COORDINATES("huskhomes.command.tp.coordinates", DefaultAccess.OPERATORS),
/**
+10 -7
View File
@@ -80,16 +80,14 @@ teleport_request_declined_confirmation: '[You declined %1%''s teleport request.]
teleport_request_accepted: '[%1% has accepted your teleport request!](#00fb9a)'
teleport_request_declined: '[%1% has declined your teleport request.](#ff7e5e)'
set_home_spent_money: '[Successfully spent %1% to set an additional home!](gray)'
set_home_used_free_slots: '[You''ve used all of your free set home slots (%1%); setting additional homes will cost %2% each.](gray)'
set_home_success: '[Successfully set a new home called](#00fb9a) [%1%](#00fb9a bold)'
set_warp_success: '[Successfully set a new warp called](#00fb9a) [%1%](#00fb9a bold)'
set_spawn_success: '[Updated spawn position for this server to your current location.](#00fb9a)'
return_by_death: '[Return to where you died?](gray) [/back](#00fb9a show_text=&#00fb9a&Click to return to where you died run_command=/back)'
rtp_spent_money: '[Spent %1% to randomly teleport.](gray)'
back_spent_money: '[Spent %1% to return to your last position.](gray)'
home_default_description: '%1%''s home'
warp_default_description: 'A publicly accessible warp'
home_default_description: '%1%''s home.'
warp_default_description: 'A publicly accessible warp.'
delete_all_homes_confirm: '[Warning:](#ff3300) [Are you sure you want to delete all of your homes?](#ff7e5e)\n[Once you confirm, it will not be possible to recover them.](gray)\n[→](gray) [[Confirm]](#ff3300 show_text=&#ff3300&Click to confirm deletion. This cannot be undone. run_command=/delhome all confirm)'
delete_all_warps_confirm: '[Warning:](#ff3300) [Are you sure you want to delete every warp?](#ff7e5e)\n[Once you confirm, it will not be possible to recover them.](gray)\n[→](gray) [[Confirm]](#ff3300 show_text=&#ff3300&Click to confirm deletion. This cannot be undone. run_command=/delwarp all confirm)'
delete_all_homes_success: '[Successfully deleted your](#00fb9a) [%1%](#00fb9a bold) [home(s).](#00fb9a)'
@@ -101,6 +99,11 @@ tpignore_toggle_off: '[You are now](#00fb9a) [listening](#00fb9a bold) [to any i
tpignore_on_reminder: '[You are currently ignoring incoming teleport requests!](gray) [(Click to toggle)](gray show_text=&7Click to listen for incoming teleport requests run_command=/huskhomes:tpignore)'
teleporting_all_players: '[Teleporting all players to your position…](#00fb9a)'
economy_action_additional_home_slot: '[ℹ Spent %1% to set an additional home.](gray)'
economy_action_make_home_public: '[ℹ Spent %1% to make your home public.](gray)'
economy_action_random_teleport: '[ℹ Spent %1% to randomly teleport.](gray)'
economy_action_back_command: '[ℹ Spent %1% to return to your last position.](gray)'
error_home_name_taken: '[Error:](#ff3300) [You already have a home set with that name.](#ff7e5e)'
error_home_name_length: '[Error:](#ff3300) [Home names can only contain up to 16 characters!](#ff7e5e)'
error_home_name_characters: '[Error:](#ff3300) [Home names must be alphanumeric (A-Z, 0-9, -_)](#ff7e5e)'
@@ -121,6 +124,7 @@ error_invalid_server: '[Error:](#ff3300) [Failed to finish teleportation as the
error_home_invalid: '[Error:](#ff3300) [You do not have a home named "%1%"](#ff7e5e)'
error_warp_invalid: '[Error:](#ff3300) [There is no warp set named "%1%"](#ff7e5e)'
error_invalid_syntax: '[Error:](#ff3300) [Incorrect syntax. Usage: %1%](#ff7e5e)'
error_insufficient_funds: '[Error:](#ff3300) [You do not have enough money. (Cost: %1%)](#ff7e5e)'
error_edit_home_privacy_already_public: '[Error:](#ff3300) [This home is already set as public.](#ff7e5e)'
error_edit_home_privacy_already_private: '[Error:](#ff3300) [This home is already set as private.](#ff7e5e)'
error_edit_home_privacy_no_permission: '[Error:](#ff3300) [You do not have permission to make homes public.](#ff7e5e)'
@@ -129,7 +133,6 @@ error_no_public_homes_set: '[Error:](#ff3300) [There are no public homes set!](#
error_no_warps_set: '[Error:](#ff3300) [There are no warps set!](#ff7e5e)'
error_public_home_invalid: '[Error:](#ff3300) [Could not find a public home owned by %1% called %2%.](#ff7e5e)'
error_set_home_maximum_homes: '[Error:](#ff3300) [You can only set a maximum of %1% homes!](#ff7e5e)'
error_insufficient_funds: '[Error:](#ff3300) [You do not have enough money! (Cost: %1%)](#ff7e5e)'
error_spawn_undefined: '[Error:](#ff3300) [There is no spawn position defined on this server.](#ff7e5e)'
error_no_teleport_requests: '[Error:](#ff3300) [You do not have a pending teleport request.](#ff7e5e)'
error_teleport_request_expired: '[Error:](#ff3300) [Your pending teleport request has expired.](#ff7e5e)'
@@ -138,7 +141,7 @@ error_ignoring_teleport_requests: '[Error:](#ff3300) [You are currently ignoring
error_invalid_teleport_request: '[Error:](#ff3300) [You do not have a pending request from %1%.](#ff7e5e)'
error_player_not_found: '[Error:](#ff3300) [Could not find the player %1%.](#ff7e5e)'
error_tp_self: '[Error:](#ff3300) [You cannot teleport to yourself!](#ff7e5e)'
error_rtp_invalid_dimension: '[Error:](#ff3300) [You can only randomly teleport in the overworld!](#ff7e5e)'
error_rtp_restricted_world: '[Error:](#ff3300) [You cannot randomly teleport in this world.](#ff7e5e)'
error_rtp_cooldown: '[Error:](#ff3300) [You must wait %1% minutes before randomly teleporting again.](#ff7e5e)'
error_command_disabled: '[Error:](#ff3300) [That command is disabled!](#ff7e5e)'
error_console_only: '[Error:](#ff3300) [That command can only be run from the server console.](#ff7e5e)'
@@ -0,0 +1,59 @@
package net.william278.huskhomes.random;
import com.github.plot.Plot;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.World;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class NormalDistributionTests {
@Test
public void testNormalDistributionRandomizer() {
Assertions.assertEquals(1000, generateLocations(1000).size());
}
// Plots location distribution
public static void generateRtpLocationDistributionImage() {
final List<Location> locations = generateLocations(2000);
final double[] xValues = new double[locations.size()];
final double[] zValues = new double[locations.size()];
for (int i = 0; i < locations.size(); i++) {
xValues[i] = locations.get(i).x;
zValues[i] = locations.get(i).z;
}
final Plot plot = Plot.plot(Plot.plotOpts()
.title("RTP Normal Distribution demo")
.legend(Plot.LegendFormat.BOTTOM))
.xAxis("x", Plot.axisOpts().range(-3250, 3250))
.yAxis("z", Plot.axisOpts().range(-3250, 3250))
.series("Data", Plot.data()
.xy(xValues, zValues),
Plot.seriesOpts()
.marker(Plot.Marker.CIRCLE)
.markerColor(new Color(0, 60, 255, 180))
.color(new Color(0, 0, 0, 0)));
try {
plot.save("images/rtp-location-distribution", "png");
} catch (IOException e) {
e.printStackTrace();
}
}
private static List<Location> generateLocations(int amount) {
final List<Location> locations = new ArrayList<>();
for (int i = 0; i < amount; i++) {
locations.add(NormalDistributionEngine.generateLocation(
new Location(0, 0, 0, 0, 0, new World("TestWorld", UUID.randomUUID())),
0.75f, 2f, 500f, 3000f));
}
return locations;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB