Use internal yaml resource for unsafe blocks by key, remove caching, fixes

This commit is contained in:
William committed 2022-11-23 21:51:23 +00:00
1 parent c4b16db9a9
commit a3ea62a85c
11 files changed
+215 -269

No files matched your search

@@ -358,7 +358,15 @@ public interface HuskHomes {
*
* @return a {@link CompletableFuture} that will be completed when the plugin reload is complete and if it was successful
*/
CompletableFuture<Boolean> reload();
boolean reload();
/**
* Returns if the block, by provided identifier, is unsafe
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
*/
boolean isBlockUnsafe(@NotNull String blockId);
/**
* Registers the plugin with bStats metrics
@@ -86,13 +86,11 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable,
.ifPresent(onlineUser::sendMessage);
return;
}
plugin.reload().thenAccept(reloaded -> {
if (!reloaded) {
onlineUser.sendMessage(new MineDown("[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)"));
return;
}
onlineUser.sendMessage(new MineDown("[HuskHomes](#00fb9a bold) &#00fb9a&| Reloaded config & message files."));
});
if (!plugin.reload()) {
onlineUser.sendMessage(new MineDown("[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)"));
return;
}
onlineUser.sendMessage(new MineDown("[HuskHomes](#00fb9a bold) &#00fb9a&| Reloaded config & message files."));
}
case "update" -> {
if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_UPDATE.node)) {
@@ -135,13 +133,13 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable,
(command.command.length() < 16 ? " ".repeat(16 - command.command.length()) : "")
+ " - " + command.getDescription()));
}
case "reload" -> plugin.reload().thenAccept(reloaded -> {
if (!reloaded) {
case "reload" -> {
if (!plugin.reload()) {
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to reload the plugin.");
return;
}
plugin.getLoggingAdapter().log(Level.INFO, "Reloaded config & message files.");
});
}
case "update" -> plugin.getLatestVersionIfOutdated().thenAccept(newestVersion ->
newestVersion.ifPresentOrElse(newVersion -> plugin.getLoggingAdapter().log(Level.WARNING,
"An update is available for HuskHomes, v" + newVersion
@@ -62,9 +62,9 @@ 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)))
Long.toString(currentTime.until(userData.get().rtpCooldown(), ChronoUnit.MINUTES) + 1))
.ifPresent(onlineUser::sendMessage);
return;
}
@@ -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)));
@@ -203,9 +203,6 @@ public class Settings {
@YamlKey("rtp.distribution_deviation")
public float rtpDistributionStandardDeviation = 2f;
@YamlKey("rtp.location_cache_size")
public int rtpLocationCacheSize = 10;
@YamlKey("rtp.restricted_worlds")
public List<String> rtpRestrictedWorlds = List.of("world_nether", "world_the_end");
@@ -3,11 +3,11 @@ 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.*;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
/**
@@ -19,11 +19,6 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
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");
@@ -31,16 +26,6 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
this.spawnRadius = implementor.getSettings().rtpSpawnRadius;
this.mean = implementor.getSettings().rtpDistributionMean;
this.standardDeviation = implementor.getSettings().rtpDistributionStandardDeviation;
this.cacheSize = implementor.getSettings().rtpLocationCacheSize;
this.cache = new HashMap<>();
// Prepare cache
for (final World world : implementor.getWorlds()) {
if (implementor.getSettings().rtpRestrictedWorlds.contains(world.name)) {
continue;
}
cache.put(world.uuid, new LinkedList<>());
}
}
/**
@@ -52,7 +37,7 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
*/
@NotNull
protected static Location generateLocation(@NotNull Location origin, float mean, float standardDeviation,
float spawnRadius, float maxRadius) {
float spawnRadius, float maxRadius) {
// Generate random values
final float radius = generateNormallyDistributedRadius(mean, standardDeviation, spawnRadius, maxRadius);
final float angle = generateRandomAngle();
@@ -100,34 +85,18 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
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());
});
public CompletableFuture<Optional<Position>> getRandomPosition(@NotNull World world, @NotNull String[] args) {
Optional<Location> location = generateSafeLocation(world).join();
int attempts = 0;
while (location.isEmpty()) {
location = generateSafeLocation(world).join();
if (attempts > randomTimeout) {
return CompletableFuture.completedFuture(null);
}
}
CompletableFuture.runAsync(() -> populateCache(world));
return position;
return CompletableFuture.completedFuture(location.map(resolved ->
new Position(resolved, plugin.getPluginServer())));
}
}
@@ -7,7 +7,6 @@ import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public abstract class RandomTeleportEngine {
@@ -18,7 +17,7 @@ public abstract class RandomTeleportEngine {
public final String name;
/**
* How long before {@link #getRandomPosition} future calls time out
* How many attempts to allow {@link #getRandomPosition} lookups before timing out
*/
public long randomTimeout = 8;
@@ -44,15 +43,6 @@ public abstract class RandomTeleportEngine {
world, plugin.getPluginServer()));
}
/**
* Finds a random position in the {@link World}
*
* @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 abstract CompletableFuture<Position> findRandomPosition(@NotNull World world, @NotNull String[] args);
/**
* 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
@@ -62,11 +52,6 @@ public abstract class RandomTeleportEngine {
* @return A {@link CompletableFuture} containing the random position, if one was found before the
* {@link #randomTimeout operation timed out}
*/
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);
}
public abstract CompletableFuture<Optional<Position>> getRandomPosition(@NotNull World world, @NotNull String[] args);
}
@@ -0,0 +1,36 @@
package net.william278.huskhomes.util;
import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Unsafe /rtp Blocks ┃
┃ Developed by William278 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""")
public class UnsafeBlocks {
@YamlKey("unsafe_blocks")
public List<String> unsafeBlocks;
/**
* Returns if the block, by provided identifier, is unsafe
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
*/
public boolean isUnsafe(@NotNull String blockId) {
if (!blockId.startsWith("minecraft:")) {
blockId = "minecraft:" + blockId;
}
return unsafeBlocks.contains(blockId);
}
@SuppressWarnings("unused")
public UnsafeBlocks() {
}
}