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,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),
/**