mirror of
https://github.com/darksaid98/HuskHomes.git
synced 2026-12-02 06:28:49 +00:00
Refactor and simplify RandomTeleportEngine API and logic
This commit is contained in:
1 parent
c8a0f00290
commit
6b55327e52
6 files changed
+109
-178
No files matched your search
@@ -155,7 +155,7 @@ public interface HuskHomes {
|
||||
RandomTeleportEngine getRandomTeleportEngine();
|
||||
|
||||
/**
|
||||
* Set the {@link RandomTeleportEngine} to use and initialize it, calling {@link RandomTeleportEngine#initialize()}
|
||||
* Sets the {@link RandomTeleportEngine} to be used for processing random teleports
|
||||
*
|
||||
* @param randomTeleportEngine the {@link RandomTeleportEngine} to use
|
||||
*/
|
||||
@@ -291,7 +291,7 @@ public interface HuskHomes {
|
||||
* @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);
|
||||
CompletableFuture<Optional<Location>> resolveSafeGroundLocation(@NotNull Location location);
|
||||
|
||||
/**
|
||||
* Returns the {@link Server} the plugin is on
|
||||
|
||||
@@ -389,7 +389,7 @@ public abstract class BaseHuskHomesAPI {
|
||||
final boolean timedTeleport,
|
||||
@NotNull String... rtpArgs) {
|
||||
return CompletableFuture.supplyAsync(() -> plugin.getRandomTeleportEngine()
|
||||
.getRandomPosition(user, rtpArgs)
|
||||
.getRandomPosition(user.getPosition().world, rtpArgs)
|
||||
.thenApply(position -> {
|
||||
if (position.isPresent()) {
|
||||
final TeleportBuilder builder = Teleport.builder(plugin, user)
|
||||
|
||||
@@ -62,7 +62,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
|
||||
}
|
||||
final Instant currentTime = Instant.now();
|
||||
if (isExecutorTeleporting && !currentTime.isAfter(userData.get().rtpCooldown())
|
||||
&& !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) {
|
||||
&& !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) {
|
||||
plugin.getLocales().getLocale("error_rtp_cooldown",
|
||||
Long.toString(currentTime.until(userData.get().rtpCooldown(), ChronoUnit.MINUTES)))
|
||||
.ifPresent(onlineUser::sendMessage);
|
||||
@@ -70,7 +70,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
|
||||
}
|
||||
|
||||
// Get a random position and teleport
|
||||
plugin.getRandomTeleportEngine().getRandomPosition(onlineUser, rtpArguments).thenAccept(position -> {
|
||||
plugin.getRandomTeleportEngine().getRandomPosition(onlineUser.getPosition().world, rtpArguments).thenAccept(position -> {
|
||||
if (position.isEmpty()) {
|
||||
plugin.getLocales().getLocale("error_rtp_randomization_timeout")
|
||||
.ifPresent(onlineUser::sendMessage);
|
||||
@@ -86,7 +86,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
|
||||
teleportFuture.thenAccept(teleport -> teleport.execute()
|
||||
.thenAccept(result -> {
|
||||
if (isExecutorTeleporting &&
|
||||
result.successful() && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) {
|
||||
result.successful() && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) {
|
||||
plugin.getDatabase().updateUserData(new UserData(onlineUser,
|
||||
userData.get().homeSlots(), userData.get().ignoringTeleports(),
|
||||
Instant.now().plus(plugin.getSettings().rtpCooldownLength, ChronoUnit.MINUTES)));
|
||||
@@ -109,7 +109,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
|
||||
}
|
||||
|
||||
plugin.getLoggingAdapter().log(Level.INFO, "Finding a random position for " + foundUser.get().username + "...");
|
||||
plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get(), ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> {
|
||||
plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get().getPosition().world, ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> {
|
||||
if (position.isEmpty()) {
|
||||
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + foundUser.get().username + " to a random position; randomization timed out!");
|
||||
return;
|
||||
|
||||
+64
-12
@@ -2,10 +2,12 @@ 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.Server;
|
||||
import net.william278.huskhomes.position.World;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
@@ -13,11 +15,15 @@ import java.util.concurrent.CompletableFuture;
|
||||
*/
|
||||
public class NormalDistributionEngine extends RandomTeleportEngine {
|
||||
|
||||
private final HuskHomes plugin;
|
||||
protected final int radius;
|
||||
protected final int spawnRadius;
|
||||
private final float mean;
|
||||
private final float standardDeviation;
|
||||
private final int cacheSize;
|
||||
|
||||
// Cache of random positions
|
||||
@NotNull
|
||||
private final Map<UUID, LinkedList<Position>> cache;
|
||||
|
||||
public NormalDistributionEngine(@NotNull HuskHomes implementor) {
|
||||
super(implementor, "Normal Distribution");
|
||||
@@ -25,24 +31,28 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
|
||||
this.spawnRadius = implementor.getSettings().rtpSpawnRadius;
|
||||
this.mean = implementor.getSettings().rtpDistributionMean;
|
||||
this.standardDeviation = implementor.getSettings().rtpDistributionStandardDeviation;
|
||||
this.plugin = implementor;
|
||||
}
|
||||
this.cacheSize = implementor.getSettings().rtpLocationCacheSize;
|
||||
this.cache = new HashMap<>();
|
||||
|
||||
@Override
|
||||
protected @NotNull CompletableFuture<Optional<Location>> generateRandomLocation(@NotNull Location origin,
|
||||
@NotNull String... args) {
|
||||
return plugin.getSafeGroundLocation(generateLocation(origin, mean, standardDeviation, spawnRadius, radius));
|
||||
// Prepare cache
|
||||
for (final World world : implementor.getWorlds()) {
|
||||
if (implementor.getSettings().rtpRestrictedWorlds.contains(world.name)) {
|
||||
continue;
|
||||
}
|
||||
cache.put(world.uuid, new LinkedList<>());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a location through a randomized normally-distributed radius and random angle using the mean and
|
||||
* Generate a {@link 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) {
|
||||
@NotNull
|
||||
private 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();
|
||||
@@ -55,6 +65,17 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
|
||||
origin.yaw, origin.pitch, origin.world);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a safe ground-level {@link Location} through a randomized normally-distributed radius and random angle
|
||||
*
|
||||
* @param world The world to generate the location in
|
||||
* @return A generated location
|
||||
*/
|
||||
private CompletableFuture<Optional<Location>> generateSafeLocation(@NotNull World world) {
|
||||
return plugin.resolveSafeGroundLocation(generateLocation(
|
||||
getOrigin(world), mean, standardDeviation, spawnRadius, radius));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a normally distributed radius between the spawnRadius and the maximum radius value,
|
||||
* using the provided standard deviation and mean.
|
||||
@@ -78,4 +99,35 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
|
||||
private static float generateRandomAngle() {
|
||||
return (float) (Math.random() * 360);
|
||||
}
|
||||
|
||||
/**
|
||||
* Populate the cache with a set of random locations
|
||||
*/
|
||||
private void populateCache(@NotNull World world) {
|
||||
final Server server = plugin.getPluginServer();
|
||||
while (cache.size() < cacheSize) {
|
||||
generateSafeLocation(world).thenAccept(location -> location
|
||||
.ifPresent(value -> cache.getOrDefault(world.uuid, new LinkedList<>())
|
||||
.addLast(new Position(value, server))));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Position> findRandomPosition(@NotNull World world, @NotNull String[] args) {
|
||||
CompletableFuture<Position> position;
|
||||
if (!cache.getOrDefault(world.uuid, new LinkedList<>()).isEmpty()) {
|
||||
position = CompletableFuture.completedFuture(cache.get(world.uuid).removeFirst());
|
||||
} else {
|
||||
position = CompletableFuture.supplyAsync(() -> {
|
||||
Optional<Location> resolved = Optional.empty();
|
||||
while (resolved.isEmpty()) {
|
||||
resolved = generateSafeLocation(world).join();
|
||||
}
|
||||
return new Position(resolved.get(), plugin.getPluginServer());
|
||||
});
|
||||
}
|
||||
|
||||
CompletableFuture.runAsync(() -> populateCache(world));
|
||||
return position;
|
||||
}
|
||||
}
|
||||
@@ -1,192 +1,72 @@
|
||||
package net.william278.huskhomes.random;
|
||||
|
||||
import net.william278.huskhomes.HuskHomes;
|
||||
import net.william278.huskhomes.player.OnlineUser;
|
||||
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.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* An engine for random teleportation, that generates and caches random locations and serves them as requested
|
||||
* <p>
|
||||
* See {@link #generateRandomLocation(Location, String...)} for details on how to generate positions
|
||||
*
|
||||
* @since 3.0
|
||||
*/
|
||||
public abstract class RandomTeleportEngine {
|
||||
|
||||
/**
|
||||
* Name of the engine
|
||||
*/
|
||||
@NotNull
|
||||
protected final String name;
|
||||
/**
|
||||
* Number of random positions to cache on each world
|
||||
*/
|
||||
protected final int cacheSize;
|
||||
/**
|
||||
* {@link World}s to serve random positions in
|
||||
*/
|
||||
protected final HuskHomes plugin;
|
||||
|
||||
@NotNull
|
||||
private final List<World> worlds;
|
||||
/**
|
||||
* A cache of random {@link Location}s for each random teleport world
|
||||
*/
|
||||
@NotNull
|
||||
private final Map<World, Queue<Location>> cachedPositions;
|
||||
public final String name;
|
||||
|
||||
/**
|
||||
* <b>(Internal use only)</b> Create a new random teleport engine, using HuskHomes config settings
|
||||
*
|
||||
* @param implementor The HuskHomes instance
|
||||
* @param name The name of the engine
|
||||
* How long before {@link #getRandomPosition} future calls time out
|
||||
*/
|
||||
protected RandomTeleportEngine(@NotNull HuskHomes implementor, @NotNull String name) {
|
||||
public long randomTimeout = 8;
|
||||
|
||||
protected RandomTeleportEngine(@NotNull HuskHomes plugin, @NotNull String name) {
|
||||
this.plugin = plugin;
|
||||
this.name = name;
|
||||
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.cachedPositions = new HashMap<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new random teleport engine
|
||||
* Get the origin position (spawn) of this server
|
||||
*
|
||||
* @param name The name of the engine
|
||||
* @param worlds The worlds to serve random locations for. Random locations will be generated using
|
||||
* {@link #generateRandomLocation(Location, String...)} for each world in this list when
|
||||
* {@link #initialize()} is called.
|
||||
* @since 3.0
|
||||
* @return The origin position
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
protected RandomTeleportEngine(@NotNull String name, @NotNull List<World> worlds) {
|
||||
this.name = name;
|
||||
this.cacheSize = 10;
|
||||
this.worlds = worlds;
|
||||
this.cachedPositions = new HashMap<>();
|
||||
protected final Position getOrigin(@NotNull World world) {
|
||||
return plugin.getLocalCachedSpawn()
|
||||
.flatMap(spawn -> {
|
||||
if (!spawn.worldUuid.equals(world.uuid.toString())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return spawn.getPosition(plugin.getPluginServer());
|
||||
})
|
||||
.orElse(new Position(0d, 128d, 0d, 0f, 0f,
|
||||
world, plugin.getPluginServer()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the RTP engine, populating the cache with random positons for each world.
|
||||
* This is called after the engine is registered.
|
||||
* Finds a random position in the {@link World}
|
||||
*
|
||||
* @since 3.0
|
||||
* @param world The world to find a random position in
|
||||
* @param args The arguments to pass to the random teleport engine
|
||||
* @return A {@link CompletableFuture} containing the random position
|
||||
*/
|
||||
public void initialize() {
|
||||
CompletableFuture.runAsync(() -> {
|
||||
for (final World world : worlds) {
|
||||
cachedPositions.put(world, new LinkedList<>());
|
||||
populateCache(world, cacheSize);
|
||||
}
|
||||
});
|
||||
}
|
||||
public abstract CompletableFuture<Position> findRandomPosition(@NotNull World world, @NotNull String[] args);
|
||||
|
||||
/**
|
||||
* Attempts to populate the cache with new random locations, by calling
|
||||
* {@link #generateRandomLocation(Location, String...)}
|
||||
* Gets a random position in the {@link World}, supplying a future to be completed with the optional position
|
||||
* is found, or empty if the operation times out
|
||||
*
|
||||
* @param world The world to populate the cache for
|
||||
* @param cacheSize The size of the cache
|
||||
* @since 3.0
|
||||
* @param world The world to find a random position in
|
||||
* @param args The arguments to pass to the random teleport engine
|
||||
* @return A {@link CompletableFuture} containing the random position, if one was found before the
|
||||
* {@link #randomTimeout operation timed out}
|
||||
*/
|
||||
private void populateCache(@NotNull World world, final int cacheSize) {
|
||||
if (cacheSize <= 0) {
|
||||
return;
|
||||
}
|
||||
CompletableFuture.runAsync(() -> {
|
||||
final int amountToPopulate = cacheSize - cachedPositions.get(world).size();
|
||||
final Location originLocation = new Location(0, 0, 0, world);
|
||||
for (int i = 0; i < amountToPopulate; i++) {
|
||||
generateRandomLocation(originLocation)
|
||||
.thenAcceptAsync(location -> location
|
||||
.ifPresent(generated -> cachedPositions.get(world).add(generated)))
|
||||
.orTimeout(10, TimeUnit.SECONDS)
|
||||
.exceptionally(throwable -> null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a new random {@link Location} on this server within the radius of the origin position.
|
||||
* <p>
|
||||
* The default implementation of a {@link RandomTeleportEngine} will only invoke this message in three occasions:
|
||||
* <ul>
|
||||
* <li>If the cache is empty (the arguments specified by the permission request command will be passed).</li>
|
||||
* <li>When a position has been requested from the cache ({@link #getRandomLocation(World, String...)}, this will
|
||||
* be called as many times as needed to replenish the cache. (no arguments will be passed).</li>
|
||||
* <li>When {@link #initialize()} is called while the plugin is enabling (no arguments will be passed).</li>
|
||||
* </ul>
|
||||
* Locations returned by this method should be safe for players to teleport to. This means that the location has
|
||||
* solid ground to stand on and that the player will not die by standing still at the location.
|
||||
* Implementations of HuskHomes validate location safety using {@link HuskHomes#getSafeGroundLocation(Location)}.
|
||||
* <p>
|
||||
* RandomTeleportEngines that wish to return cross-server random {@link Position}s can use this method to cache
|
||||
* locations on this server, and override {@link #getRandomPosition(OnlineUser, String...)} to return a random position
|
||||
* from the caches of the engine on other servers.
|
||||
* <p>
|
||||
* If you'd prefer not to use caching for whatever reason, you can simply override {@link #getRandomLocation(World, String...)}
|
||||
* to call this method directly, though this will affect the speed at which positions can be served to users.
|
||||
*
|
||||
* @param origin The origin {@link Location} to generate a random position around, such as the server spawn, or
|
||||
* ({@code x: 0, z: 0})
|
||||
* @param args Arguments specified by the random location request. These may be used to alter which locations are
|
||||
* generated by the randomizer.
|
||||
* @return a generated {@link Location} if one was found; an {@link Optional#empty()} otherwise
|
||||
* @since 3.0
|
||||
*/
|
||||
@NotNull
|
||||
protected abstract CompletableFuture<Optional<Location>> generateRandomLocation(@NotNull Location origin,
|
||||
@NotNull String... args);
|
||||
|
||||
/**
|
||||
* Returns a random {@link Position} from the cache, generating if the cache is empty
|
||||
*
|
||||
* @param onlineUser The {@link OnlineUser} requesting the random position
|
||||
* @param args Arguments specified by the random location request. These may be used to alter which locations are
|
||||
* generated by the randomizer.
|
||||
* @return a generated {@link Location} if one was found; an {@link Optional#empty()} otherwise
|
||||
* @since 3.0
|
||||
*/
|
||||
public CompletableFuture<Optional<Position>> getRandomPosition(@NotNull OnlineUser onlineUser,
|
||||
@NotNull String... args) {
|
||||
return getRandomLocation(onlineUser.getPosition().world, args).thenApply(location ->
|
||||
location.map(position -> new Position(position, onlineUser.getPosition().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}. Note that ({@code x: 0, z: 0}) will be
|
||||
* passed as the origin position in the world
|
||||
* @param args Arguments specified by the random location request. These may be used to alter which locations are
|
||||
* generated by the randomizer.
|
||||
* @return a generated {@link Location} if one was found; an {@link Optional#empty()} otherwise
|
||||
* @since 3.0
|
||||
*/
|
||||
private CompletableFuture<Optional<Location>> getRandomLocation(@NotNull World world, @NotNull String... args) {
|
||||
final Optional<World> keyedWorld = cachedPositions.keySet().stream()
|
||||
.filter(cachedWorld -> cachedWorld.uuid.equals(world.uuid))
|
||||
.findFirst();
|
||||
if (keyedWorld.isPresent()) {
|
||||
final Queue<Location> cachedWorldLocations = cachedPositions.get(keyedWorld.get());
|
||||
if (!cachedWorldLocations.isEmpty()) {
|
||||
populateCache(keyedWorld.get(), cacheSize);
|
||||
return CompletableFuture.completedFuture(Optional.of(cachedWorldLocations.remove()));
|
||||
} else {
|
||||
populateCache(keyedWorld.get(), cacheSize);
|
||||
}
|
||||
}
|
||||
return generateRandomLocation(new Location(0, 0, 0, world), args)
|
||||
.orTimeout(5, TimeUnit.SECONDS)
|
||||
.exceptionally(throwable -> Optional.empty());
|
||||
public final CompletableFuture<Optional<Position>> getRandomPosition(@NotNull World world, @NotNull String[] args) {
|
||||
return findRandomPosition(world, args)
|
||||
.orTimeout(Math.max(1, randomTimeout), TimeUnit.SECONDS)
|
||||
.exceptionally(e -> null)
|
||||
.thenApplyAsync(Optional::ofNullable);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user