keys = new IdentityHashMap<>();
+ for (ChecklistEntry entry : entries) {
+ String first = null;
+ for (UUID finder : entry.finders()) {
+ if (!resolved.containsKey(finder)) resolved.put(finder, names.apply(finder));
+ String name = resolved.get(finder);
+ if (name != null && (first == null || String.CASE_INSENSITIVE_ORDER.compare(name, first) < 0)) first = name;
+ }
+ keys.put(entry, first);
+ }
+ return keys;
}
}
diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java
index 8777a8c1..d6e36e19 100644
--- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java
+++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java
@@ -18,6 +18,8 @@
import org.bukkit.WorldBorder;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
+import org.bukkit.damage.DamageSource;
+import org.bukkit.damage.DamageType;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@@ -28,29 +30,34 @@
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
+import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
+import java.util.Set;
import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
/**
- * The one world border every challenge shares.
+ * The one world border of a challenge round, the one /worldborder sets and every border challenge changes.
*
* Challenges never touch {@link World#getWorldBorder()}: a challenge whose border starts small and
* grows with the game state sets how far it has {@link #setGrowth(AbstractChallenge, double, boolean)
* grown} it, one that only makes it bigger or smaller {@link #changeSize(double) changes} it, and all of
- * them add up. Going through the world border instead would mean the last writer wins, so enabling a
- * second border challenge would silently turn the first one into a no-op.
+ * them add up on top of the size /worldborder {@link #setSize(double, long) set}. Going through the world
+ * border instead would mean the last writer wins, so enabling a second border challenge would silently
+ * turn the first one into a no-op.
*
- * What the players see is a border of this manager's own, sent per player, so the world keeps the
- * border it was created with and a reset needs nothing but forgetting the numbers here.
+ * What the players see is a border of this manager's own, sent per player. The world keeps its vanilla
+ * border, because the server spawns no mobs in chunks outside the world's border.
*/
public final class BorderManager implements GamestateSaveable, Listener {
- private static final double MIN_SIZE = 1;
+ public static final double MIN_SIZE = 1;
+ public static final double MAX_SIZE = 59_999_968;
private static final double START_SIZE = 1;
private final Map apiBorders = new ConcurrentHashMap<>();
@@ -58,6 +65,7 @@ public final class BorderManager implements GamestateSaveable, Listener {
// Players a challenge has given a border of their own. The shared border leaves them alone until it
// is handed back, so a challenge that traps somebody is not undone by one that shrinks the border.
+ private final Set teleporting = ConcurrentHashMap.newKeySet();
private final Map overrides = new ConcurrentHashMap<>();
// How far each challenge whose border starts small has grown it, by unique challenge name. Not saved:
@@ -65,6 +73,22 @@ public final class BorderManager implements GamestateSaveable, Listener {
private final Map growth = new ConcurrentHashMap<>();
private volatile double offset;
+ // The size the border is sliding from and to, so players are held to the line they see moving
+ // rather than to where it ends up. NaN while there is no border.
+ private volatile double drawnTarget = Double.NaN;
+ private volatile double slideFrom;
+ private volatile long slideStart;
+ private volatile long slideEnd;
+
+ // The size /worldborder set, null while nobody did
+ private volatile Double size;
+
+ // Unlike vanilla's 5 blocks, no buffer: a border that shrinks by a block has to hurt whoever it passes
+ private static final double DAMAGE_PER_BLOCK = 0.2;
+ private volatile double damageBuffer = 0;
+ private volatile double damagePerBlock = DAMAGE_PER_BLOCK;
+ private volatile Containment containment = Containment.DAMAGE;
+
// One bar for every challenge that drives the border, so two of them never stack two bars
private final ChallengeBossBar bossbar = new ChallengeBossBar();
@@ -76,52 +100,143 @@ public void enable() {
}
/**
- * Whether any challenge is currently driving the border. While nothing is, players keep the border
- * their world came with.
+ * Whether there is a border at all: one set with /worldborder or one a challenge grows. While there is
+ * none, players keep the border their world came with.
*/
public boolean isActive() {
- return !growth.isEmpty() || offset != 0;
+ return isGrowing() || size != null;
+ }
+
+ private boolean isGrowing() {
+ return !growth.isEmpty();
}
/**
* Shrinks the border down to a single block while any challenge has set a growth, and grows it by the
- * sum of all of them. Passing the same growth twice is free.
+ * sum of all of them. A border /worldborder set is grown from its own size instead.
+ * Passing the same growth twice is free.
*/
public void setGrowth(@NotNull AbstractChallenge challenge, double blocks, boolean animate) {
Double previous = growth.put(challenge.getUniqueName(), blocks);
if (previous != null && previous == blocks) return;
- update(animate);
+ update(animate ? 1 : 0);
}
public void clearGrowth(@NotNull AbstractChallenge challenge) {
if (growth.remove(challenge.getUniqueName()) == null) return;
- update(false);
+ update(0);
}
/**
* Grows or shrinks the border by {@code delta}, on top of whatever size it has otherwise.
* The border slides to the new size rather than jumping to it, the way it does when the level border
- * follows a level.
+ * follows a level. Without a border there is nothing to see, but the change is kept for when there is.
*/
public void changeSize(double delta) {
offset += delta;
- update(true);
+ update(1);
+ }
+
+ /**
+ * Makes the border {@code target} blocks wide over {@code seconds}, the way /worldborder set does.
+ * Challenges that change the border go on from there.
+ */
+ public void setSize(double target, long seconds) {
+ double clamped = Math.clamp(target, MIN_SIZE, MAX_SIZE);
+ size = clamped - (isGrowing() ? grown() : 0) - offset;
+ update(seconds);
+ }
+
+ /**
+ * Takes back what /worldborder set, so without a challenge that grows one there is no border any more.
+ */
+ public void reset() {
+ size = null;
+ centers.clear();
+ update(0);
+ }
+
+ public void setCenter(@NotNull World world, @NotNull Location center) {
+ centers.put(world, center.clone());
+ if (isActive()) updateBorder(world);
+ }
+
+ public void setDamage(double buffer, double perBlock) {
+ damageBuffer = Math.max(0, buffer);
+ damagePerBlock = Math.max(0, perBlock);
+ }
+
+ public void setContainment(@NotNull Containment containment) {
+ this.containment = containment;
+ }
+
+ @NotNull
+ public Containment getContainment() {
+ return containment;
+ }
+
+ public double getDamageBuffer() {
+ return damageBuffer;
+ }
+
+ public double getDamagePerBlock() {
+ return damagePerBlock;
}
/**
- * The size players are actually held to in this world.
+ * The size the border has in this world once it stops sliding.
*/
public double getSize(@NotNull World world) {
- double base = growth.isEmpty()
- ? world.getWorldBorder().getSize()
- : START_SIZE + growth.values().stream().mapToDouble(Double::doubleValue).sum();
- return Math.max(MIN_SIZE, base + offset);
+ if (!isActive()) return world.getWorldBorder().getSize();
+ return targetSize();
+ }
+
+ private double targetSize() {
+ double base = size != null ? size : START_SIZE;
+ return Math.clamp(base + (isGrowing() ? grown() : 0) + offset, MIN_SIZE, MAX_SIZE);
+ }
+
+ /**
+ * The size the border is drawn at right now, somewhere between where a slide started and
+ * {@link #getSize(World)}.
+ */
+ public double getDrawnSize(@NotNull World world) {
+ if (!isActive()) return getSize(world);
+ return drawnSize(System.currentTimeMillis());
+ }
+
+ private double drawnSize(long now) {
+ if (now >= slideEnd) return drawnTarget;
+ double progress = (now - slideStart) / (double) (slideEnd - slideStart);
+ return slideFrom + (drawnTarget - slideFrom) * progress;
+ }
+
+ private void startSlide(long seconds) {
+ long now = System.currentTimeMillis();
+ double from = Double.isNaN(drawnTarget) ? Double.NaN : drawnSize(now);
+ double target = isActive() ? targetSize() : Double.NaN;
+ if (seconds > 0 && !Double.isNaN(from) && !Double.isNaN(target)) {
+ slideFrom = from;
+ slideStart = now;
+ slideEnd = now + seconds * 1000;
+ } else {
+ slideEnd = 0;
+ }
+ drawnTarget = target;
+ }
+
+ private double grown() {
+ return growth.values().stream().mapToDouble(Double::doubleValue).sum();
}
@NotNull
public Location getCenter(@NotNull World world) {
+ if (!isActive()) return world.getWorldBorder().getCenter();
+
Location center = centers.get(world);
if (center != null) return center.clone();
+ // a border that starts small opens where players spawn, one /worldborder set where vanilla's would be
+ if (!isGrowing()) return new Location(world, 0, 0, 0);
Location spawn = world.getSpawnLocation();
spawn.setX(spawn.getBlockX() + 0.5);
@@ -129,11 +244,6 @@ public Location getCenter(@NotNull World world) {
return spawn;
}
- public void setCenter(@NotNull World world, @NotNull Location center) {
- centers.put(world, center.clone());
- if (isActive()) updateBorder(world, false);
- }
-
/**
* Remembers a center only if the world does not have one yet, for challenges that follow the player
* into a world rather than deciding where its border belongs.
@@ -155,7 +265,7 @@ public boolean isOutside(@NotNull Location location) {
if (world == null || !isActive()) return false;
Location center = getCenter(world);
- double radius = getSize(world) / 2;
+ double radius = getDrawnSize(world) / 2;
return isOutside(location.getBlockX(), center.getX(), radius)
|| isOutside(location.getBlockZ(), center.getZ(), radius);
}
@@ -164,20 +274,61 @@ private static boolean isOutside(int block, double center, double radius) {
return block < Math.floor(center - radius) || block >= Math.ceil(center + radius);
}
+ /**
+ * How far this location lies past the area the client lets a player walk in, 0 inside it. Measured
+ * from the same whole-block bounds as {@link #isOutside(Location)}, so standing where the border let
+ * a player walk never hurts.
+ */
+ public double distanceOutside(@NotNull Location location) {
+ World world = location.getWorld();
+ if (world == null || !isActive()) return 0;
+
+ Location center = getCenter(world);
+ double radius = getDrawnSize(world) / 2;
+ return Math.max(0, Math.max(
+ distanceOutside(location.getX(), center.getX(), radius),
+ distanceOutside(location.getZ(), center.getZ(), radius)));
+ }
+
+ private static double distanceOutside(double position, double center, double radius) {
+ return Math.max(Math.floor(center - radius) - position, position - Math.ceil(center + radius));
+ }
+
/**
* Moves a player to the spot inside the drawn border closest to where they are.
*/
public void teleportInside(@NotNull Player player) {
Location location = player.getLocation();
Location center = getCenter(player.getWorld());
- double radius = getSize(player.getWorld()) / 2;
+ double radius = getDrawnSize(player.getWorld()) / 2;
double margin = Math.min(player.getWidth() / 2, radius);
location.setX(Math.clamp(location.getX(), center.getX() - radius + margin, center.getX() + radius - margin));
location.setZ(Math.clamp(location.getZ(), center.getZ() - radius + margin, center.getZ() + radius - margin));
- Location spot = standingSpot(location);
+ if (!teleporting.add(player.getUniqueId())) return;
player.setFallDistance(0);
- player.teleportAsync(spot != null ? spot : surface(center, player.getWorld()));
+
+ // The ground at the target belongs to another region than the player's, so it is read there.
+ Plugin plugin = Challenges.getInstance();
+ Regions.at(plugin, location, () -> {
+ try {
+ Location spot = standingSpot(location);
+ if (spot != null) {
+ teleportTo(player, spot);
+ } else {
+ Regions.at(plugin, center, () -> teleportTo(player, surface(center, player.getWorld())));
+ }
+ } catch (RuntimeException e) {
+ teleporting.remove(player.getUniqueId());
+ throw e;
+ }
+ });
+ }
+
+ // One teleport per player at a time, so a player who stays outside until it lands does not queue another every tick.
+ private void teleportTo(@NotNull Player player, @NotNull Location spot) {
+ CompletableFuture teleport = player.teleportAsync(spot);
+ teleport.whenComplete((done, error) -> teleporting.remove(player.getUniqueId()));
}
@NotNull
@@ -207,12 +358,12 @@ private static Location standingSpot(@NotNull Location location) {
}
/**
- * Gives a player the border of the world they are in, or the world's own border while no challenge is
- * driving one or the player left the game worlds behind.
+ * Gives a player the border of the world they are in, or the world's own border while there is none
+ * or the player left the game worlds behind.
*
* Sending must not rewrite a border somebody else is already watching, or a join would cut short an
* animated resize for the whole world. It only writes one it has never written before: a world can
- * join the game worlds long after the border went active - {@code /world void} creates one on demand -
+ * join the game worlds long after the border went active - a world generator challenge swaps them -
* and would otherwise hand out the untouched 59,999,968 block default.
*/
public void sendTo(@NotNull Player player) {
@@ -227,7 +378,7 @@ public void sendTo(@NotNull Player player) {
return;
}
- if (!hasBorder(world)) applyTo(world, false);
+ if (!hasBorder(world)) applyTo(world);
bind(player);
}
@@ -239,11 +390,9 @@ public void sendTo(@NotNull Player player) {
public void override(@NotNull Player player, @NotNull Location center, double size) {
WorldBorder border = Bukkit.createWorldBorder();
// The world of the center, not of the player: a teleport hands this its destination while the
- // player still stands in the world they came from. The client places a nether border at an eighth
- // of the coordinates it is given.
+ // player still stands in the world they came from.
World world = center.getWorld() == null ? player.getWorld() : center.getWorld();
- double factor = world.getEnvironment() == World.Environment.NETHER ? 8 : 1;
- border.setCenter(center.getX() * factor, center.getZ() * factor);
+ setCenter(border, world, center);
border.setSize(size);
border.setWarningDistance(0);
border.setWarningTime(0);
@@ -257,15 +406,19 @@ public void clearOverride(@NotNull Player player) {
if (player.isOnline()) sendTo(player);
}
- public void update(boolean animate) {
+ /**
+ * Writes the border onto every game world over {@code seconds}, 0 for at once.
+ */
+ public void update(long seconds) {
+ startSlide(seconds);
for (World world : ChallengeAPI.getGameWorlds()) {
- updateBorder(world, animate);
+ updateBorder(world);
}
updateBossBar();
}
private void updateBossBar() {
- if (growth.isEmpty()) {
+ if (!isGrowing()) {
if (bossbar.isShown()) bossbar.hide();
} else if (bossbar.isShown()) {
bossbar.update();
@@ -307,7 +460,7 @@ public void onRespawn(@NotNull PlayerRespawnedEvent event) {
// not around that world's spawn.
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPortal(@NotNull PlayerTeleportEvent event) {
- if (!isActive() || !ChallengeAPI.isStarted() || ChallengeAPI.isWorldInUse() || event.getTo() == null) return;
+ if (!isGrowing() || !ChallengeAPI.isStarted() || ChallengeAPI.isWorldInUse() || event.getTo() == null) return;
if (event.getCause() != PlayerTeleportEvent.TeleportCause.NETHER_PORTAL
&& event.getCause() != PlayerTeleportEvent.TeleportCause.END_PORTAL) return;
if (AbstractChallenge.ignorePlayer(event.getPlayer())) return;
@@ -325,20 +478,45 @@ public void onDamageAcrossBorder(@NotNull EntityDamageByEntityEvent event) {
}
}
- // Before the start too: a new player spawns scattered around the world spawn, outside a small border
- @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS)
+ /**
+ * Puts every player who stands outside the border inside it, for a border that appears around players
+ * who never crossed it.
+ */
public void containPlayers() {
Challenges.getInstance().getPlayerManager().forEachAudience(this::contain);
}
+ // Before the start, a new player spawns scattered around the world spawn, outside a small border, and
+ // is put inside whatever the containment says.
+ @ScheduledTask(ticks = 10, async = false, timerPolicy = TimerPolicy.ALWAYS)
+ public void holdPlayers() {
+ if (!ChallengeAPI.isStarted() || containment == Containment.PUSH) {
+ containPlayers();
+ return;
+ }
+ Challenges.getInstance().getPlayerManager().forEachAudience(this::hurtOutside);
+ }
+
private void contain(@NotNull Player player) {
- if (!isActive() || ChallengeAPI.isWorldInUse()) return;
- if (overrides.containsKey(player.getUniqueId())) return;
- if (player.isDead() || AbstractChallenge.ignorePlayer(player)) return;
+ if (!isHeld(player)) return;
if (isOutside(player.getLocation())) teleportInside(player);
}
- private void updateBorder(@NotNull World world, boolean animate) {
+ private void hurtOutside(@NotNull Player player) {
+ if (!isHeld(player) || damagePerBlock <= 0) return;
+ double beyond = distanceOutside(player.getLocation()) - damageBuffer;
+ if (beyond <= 0) return;
+ // vanilla's own formula, at least half a heart per hit
+ player.damage(Math.max(1, Math.floor(beyond * damagePerBlock)), DamageSource.builder(DamageType.OUTSIDE_BORDER).build());
+ }
+
+ private boolean isHeld(@NotNull Player player) {
+ if (!isActive() || ChallengeAPI.isWorldInUse()) return false;
+ if (overrides.containsKey(player.getUniqueId())) return false;
+ return !player.isDead() && !AbstractChallenge.ignorePlayer(player);
+ }
+
+ private void updateBorder(@NotNull World world) {
if (!isActive()) {
forEachPlayerIn(world, this::resetFor);
return;
@@ -346,7 +524,7 @@ private void updateBorder(@NotNull World world, boolean animate) {
// apply once for the whole world: re-applying per player would overwrite the animated transition
// with an instant resize before anyone is told about it
- applyTo(world, animate);
+ applyTo(world);
forEachPlayerIn(world, this::bind);
}
@@ -373,20 +551,25 @@ private void bind(@NotNull Player player) {
/**
* Writes the current size and center onto the world's border object, without sending it anywhere.
*/
- private void applyTo(@NotNull World world, boolean animate) {
- Location center = getCenter(world);
- double size = getSize(world);
-
+ private void applyTo(@NotNull World world) {
WorldBorder border = apiBorder(world);
- // the client places a nether border at an eighth of the coordinates it is given
- double factor = world.getEnvironment() == World.Environment.NETHER ? 8 : 1;
- border.setCenter(center.getX() * factor, center.getZ() * factor);
- if (animate) border.setSize(size, 1);
- else border.setSize(size);
+ setCenter(border, world, getCenter(world));
+ // Written from where the slide is now, never from what the border object held before: a border
+ // that is new or was last used before a reset holds a size nobody is shown any more.
+ long now = System.currentTimeMillis();
+ long remaining = slideEnd - now;
+ border.setSize(drawnSize(now));
+ if (remaining > 0) border.changeSize(getSize(world), Math.max(1, remaining / 50));
border.setWarningDistance(0);
border.setWarningTime(0);
}
+ // the client places a nether border at an eighth of the coordinates it is given
+ private static void setCenter(@NotNull WorldBorder border, @NotNull World world, @NotNull Location center) {
+ double factor = world.getEnvironment() == World.Environment.NETHER ? 8 : 1;
+ border.setCenter(center.getX() * factor, center.getZ() * factor);
+ }
+
private void resetFor(@NotNull Player player) {
if (overrides.containsKey(player.getUniqueId())) return;
@@ -402,6 +585,14 @@ private WorldBorder apiBorder(@NotNull World world) {
return apiBorders.computeIfAbsent(world, _ -> Bukkit.createWorldBorder());
}
+ /**
+ * What happens to a player the border moves over: vanilla border damage, or being put back inside.
+ */
+ public enum Containment {
+ DAMAGE,
+ PUSH
+ }
+
@Override
public String getUniqueGamestateName() {
return "world-border";
@@ -410,6 +601,10 @@ public String getUniqueGamestateName() {
@Override
public void writeGameState(@NotNull Document document) {
document.set("offset", offset);
+ if (size != null) document.set("size", size);
+ document.set("damage-buffer", damageBuffer);
+ document.set("damage-per-block", damagePerBlock);
+ document.set("containment", containment.name());
GsonDocument worlds = new GsonDocument();
centers.forEach((world, center) -> worlds.set(world.getName(), center));
@@ -419,6 +614,13 @@ public void writeGameState(@NotNull Document document) {
@Override
public void loadGameState(@NotNull Document document) {
offset = document.getDouble("offset");
+ damageBuffer = 0;
+ damagePerBlock = DAMAGE_PER_BLOCK;
+ containment = Containment.DAMAGE;
+ size = document.contains("size") ? document.getDouble("size") : null;
+ if (document.contains("damage-buffer")) damageBuffer = document.getDouble("damage-buffer");
+ if (document.contains("damage-per-block")) damagePerBlock = document.getDouble("damage-per-block");
+ if (document.contains("containment")) containment = Containment.valueOf(document.getString("containment"));
centers.clear();
Document worlds = document.getDocument("centers");
@@ -428,7 +630,7 @@ public void loadGameState(@NotNull Document document) {
centers.put(world, worlds.getInstance(worldName, Location.class));
}
- update(false);
+ update(0);
}
}
diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/TerrainPrefetcher.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/TerrainPrefetcher.java
new file mode 100644
index 00000000..5b4d8819
--- /dev/null
+++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/TerrainPrefetcher.java
@@ -0,0 +1,18 @@
+package net.cyperia.challenges.plugin.management.server;
+
+import org.bukkit.Location;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.concurrent.CompletableFuture;
+
+@FunctionalInterface
+public interface TerrainPrefetcher {
+
+ /**
+ * Makes the terrain around {@code at} available before its first chunk load. Implementations must
+ * not touch world state; the returned future may complete on any thread.
+ */
+ @NotNull
+ CompletableFuture prefetch(@NotNull Location at);
+
+}
diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java
index 639cb926..53259071 100644
--- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java
+++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java
@@ -1,5 +1,6 @@
package net.cyperia.challenges.plugin.management.server;
+import com.google.common.base.Preconditions;
import lombok.Getter;
import lombok.Setter;
import net.cyperia.challenges.plugin.ChallengeAPI;
@@ -25,7 +26,10 @@
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
public final class WorldManager {
@@ -41,6 +45,8 @@ public final class WorldManager {
private boolean shutdownBecauseOfReset = false;
private WorldSettings settings = new WorldSettings();
private World flatWorld;
+ private final AtomicBoolean prefetchFailureLogged = new AtomicBoolean();
+ private TerrainPrefetcher terrainPrefetcher = at -> CompletableFuture.completedFuture(null);
@Getter
private boolean worldInUse;
@@ -61,6 +67,66 @@ public WorldManager() {
};
}
+ public void setTerrainPrefetcher(@NotNull TerrainPrefetcher terrainPrefetcher) {
+ Preconditions.checkNotNull(terrainPrefetcher, "Cannot set TerrainPrefetcher to null");
+ this.terrainPrefetcher = terrainPrefetcher;
+ }
+
+ /**
+ * Completes once the terrain at {@code at} is ready to be loaded, possibly on another thread. A
+ * prefetcher that fails only costs the head start, so the returned future never completes exceptionally.
+ */
+ @NotNull
+ public CompletableFuture prefetchTerrain(@NotNull Location at) {
+ CompletableFuture prefetch;
+ try {
+ prefetch = terrainPrefetcher.prefetch(at);
+ } catch (Exception | LinkageError ex) {
+ logPrefetchFailure(ex);
+ return CompletableFuture.completedFuture(null);
+ }
+ if (prefetch == null) return CompletableFuture.completedFuture(null);
+ return prefetch.exceptionally(ex -> {
+ logPrefetchFailure(ex);
+ return null;
+ });
+ }
+
+ /**
+ * Loads the chunk at {@code at} after its terrain was prefetched and passes it to {@code action} on
+ * the region owning the location. The future completes after {@code action} ran, or exceptionally if
+ * a step failed.
+ */
+ @NotNull
+ public CompletableFuture loadChunkAfterPrefetch(@NotNull Location at, @NotNull Consumer action) {
+ Challenges plugin = Challenges.getInstance();
+ World world = at.getWorld();
+ CompletableFuture done = new CompletableFuture<>();
+ // the prefetch completes off the region thread and has to precede the first chunk load at the target
+ prefetchTerrain(at).thenRun(() -> Regions.at(plugin, at, () ->
+ world.getChunkAtAsync(at).thenAccept(chunk -> Regions.at(plugin, at, () -> {
+ try {
+ action.accept(chunk);
+ done.complete(null);
+ } catch (Throwable ex) {
+ done.completeExceptionally(ex);
+ }
+ })).exceptionally(ex -> {
+ done.completeExceptionally(ex);
+ return null;
+ }))).exceptionally(ex -> {
+ done.completeExceptionally(ex);
+ return null;
+ });
+ return done;
+ }
+
+ private void logPrefetchFailure(@NotNull Throwable ex) {
+ if (prefetchFailureLogged.compareAndSet(false, true)) {
+ Logger.warn("Terrain prefetch failed, loading chunks without it", ex);
+ }
+ }
+
public void load() {
executeWorldResetIfNecessary();
}
@@ -167,9 +233,13 @@ private void executeWorldResetIfNecessary() {
public void executeWorldReset() {
Logger.info("Deleting worlds..");
+ File levelFolder = new File(Bukkit.getWorldContainer(), levelName);
+ List playerFolders = listPlayerFolders(levelFolder);
for (String world : worlds) {
deleteWorld(world);
}
+ // Paper creates these before plugins load and never again, so without them every player save fails until the next restart
+ playerFolders.forEach(File::mkdirs);
long newSeed = getCustomSeedOrRandom();
String newSeedString = String.valueOf(newSeed);
@@ -297,6 +367,12 @@ private void injectSeedInto(Object obj, String oldSeed, String newSeed, int dept
}
}
+ @NotNull
+ static List listPlayerFolders(@NotNull File levelFolder) {
+ File[] folders = new File(levelFolder, "players").listFiles(File::isDirectory);
+ return folders == null ? List.of() : List.of(folders);
+ }
+
private void deleteWorld(@NotNull String name) {
File folder = new File(Bukkit.getWorldContainer(), name);
FileUtils.deleteWorldFolder(folder);
diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java b/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java
index f2b53bfa..c6c66eb9 100644
--- a/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java
+++ b/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java
@@ -59,6 +59,7 @@ public final class ChallengesPermissions {
public static final String COMMAND_TIME = COMMAND + "time";
public static final String COMMAND_WEATHER = COMMAND + "weather";
+ public static final String COMMAND_WORLDBORDER = COMMAND + "worldborder";
public static final String COMMAND_DIFFICULTY = COMMAND + "difficulty";
public static final String COMMAND_INVSEE = COMMAND + "invsee";
public static final String COMMAND_VILLAGE = COMMAND + "village";
diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommand.java
index 98508c89..875bb674 100644
--- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommand.java
+++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommand.java
@@ -11,10 +11,17 @@
import net.cyperia.challenges.plugin.management.files.ConfigManager;
import net.cyperia.challenges.plugin.permission.ChallengesPermissions;
import net.cyperia.commons.bukkit.utils.animation.SoundSample;
+import net.cyperia.commons.bukkit.utils.logging.Logger;
+import net.cyperia.commons.bukkit.utils.misc.Regions;
+import net.cyperia.commons.common.config.Document;
+import net.cyperia.commons.common.config.document.GsonDocument;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Executor;
+import java.util.function.Consumer;
public class DatabaseCommand implements ChallengeCommand {
@@ -30,51 +37,69 @@ public DatabaseCommand() {
@Override
public void save(Player player) throws Exception {
if (checkFeatureDisabled(savePlayerConfigs, player)) return;
- Challenges.getInstance().getChallengeManager().saveSettings(player);
- MessageKey.of("command.database.config-saved").send(player, Prefix.CHALLENGES);
+ ChallengeManager manager = Challenges.getInstance().getChallengeManager();
+ Document settings = new GsonDocument();
+ manager.saveSettingsInto(settings);
+ offThread(player, () -> {
+ manager.saveSettings(player.getUniqueId(), settings);
+ return null;
+ }, none -> MessageKey.of("command.database.config-saved").send(player, Prefix.CHALLENGES));
}
@Override
public void load(Player player) throws Exception {
if (checkFeatureDisabled(savePlayerConfigs, player)) return;
ChallengeManager manager = Challenges.getInstance().getChallengeManager();
- manager.loadSettings(manager.getSavedSettings(player.getUniqueId()));
- MessageKey.of("command.database.config-loaded").send(player, Prefix.CHALLENGES);
+ offThread(player, () -> manager.getSavedSettings(player.getUniqueId()), settings -> {
+ manager.loadSettings(settings);
+ MessageKey.of("command.database.config-loaded").send(player, Prefix.CHALLENGES);
+ });
}
@Override
public void reset(Player player) throws Exception {
if (checkFeatureDisabled(savePlayerConfigs, player)) return;
- Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges")
- .where("uuid", player.getUniqueId())
- .set("config", null)
- .execute();
- MessageKey.of("command.database.config-reset").send(player, Prefix.CHALLENGES);
+ offThread(player, () -> {
+ Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges")
+ .where("uuid", player.getUniqueId())
+ .set("config", null)
+ .execute();
+ return null;
+ }, none -> MessageKey.of("command.database.config-reset").send(player, Prefix.CHALLENGES));
}
}, "customs", new DatabaseCommandExecutor() {
@Override
public void save(Player player) throws Exception {
if (checkFeatureDisabled(savePlayerChallenges, player)) return;
- Challenges.getInstance().getChallengeManager().saveCustomChallenges(player);
- MessageKey.of("command.database.customs-saved").send(player, Prefix.CHALLENGES);
+ ChallengeManager manager = Challenges.getInstance().getChallengeManager();
+ Document customChallenges = new GsonDocument();
+ manager.saveCustomChallengesInto(customChallenges);
+ offThread(player, () -> {
+ manager.saveCustomChallenges(player.getUniqueId(), customChallenges);
+ return null;
+ }, none -> MessageKey.of("command.database.customs-saved").send(player, Prefix.CHALLENGES));
}
@Override
public void load(Player player) throws Exception {
if (checkFeatureDisabled(savePlayerChallenges, player)) return;
ChallengeManager manager = Challenges.getInstance().getChallengeManager();
- manager.loadCustomChallenges(manager.getSavedCustomChallenges(player.getUniqueId()));
- MessageKey.of("command.database.customs-loaded").send(player, Prefix.CHALLENGES);
+ offThread(player, () -> manager.getSavedCustomChallenges(player.getUniqueId()), customChallenges -> {
+ manager.loadCustomChallenges(customChallenges);
+ MessageKey.of("command.database.customs-loaded").send(player, Prefix.CHALLENGES);
+ });
}
@Override
public void reset(Player player) throws Exception {
if (checkFeatureDisabled(savePlayerChallenges, player)) return;
- Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges")
- .where("uuid", player.getUniqueId())
- .set("custom_challenges", null)
- .execute();
- MessageKey.of("command.database.customs-reset").send(player, Prefix.CHALLENGES);
+ offThread(player, () -> {
+ Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges")
+ .where("uuid", player.getUniqueId())
+ .set("custom_challenges", null)
+ .execute();
+ return null;
+ }, none -> MessageKey.of("command.database.customs-reset").send(player, Prefix.CHALLENGES));
}
});
}
@@ -103,6 +128,28 @@ private LiteralArgumentBuilder action(@NotNull CommandNodes nodes, @No
return node;
}
+ private static void offThread(@NotNull Player player, @NotNull Callable database, @NotNull Consumer onGlobalThread) {
+ offThread(Challenges.getInstance().getExecutor(), task -> Regions.global(Challenges.getInstance(), task), database, onGlobalThread,
+ ex -> {
+ player.sendMessage(Prefix.FALLBACK + "§cSomething went wrong while executing the command");
+ Logger.error("Something went wrong while accessing the database for {}", player.getName(), ex);
+ });
+ }
+
+ static void offThread(@NotNull Executor async, @NotNull Executor global, @NotNull Callable database,
+ @NotNull Consumer onGlobalThread, @NotNull Consumer onError) {
+ async.execute(() -> {
+ T result;
+ try {
+ result = database.call();
+ } catch (Exception ex) {
+ onError.accept(ex);
+ return;
+ }
+ global.execute(() -> onGlobalThread.accept(result));
+ });
+ }
+
/**
* Checks for disabled features and sends a proper messages to indicate that
*/
diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java
index 2a81828c..b2353ff5 100644
--- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java
+++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java
@@ -16,8 +16,14 @@
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
+import java.util.function.Consumer;
+import java.util.function.IntFunction;
+
public class VillageCommand implements ChallengeCommand {
+ // Chunks; the first ring is what vanilla /locate searches. Each ring runs on its own tick.
+ private static final int[] SEARCH_RADII = {100, 250, 500};
+
@NotNull
@Override
public CommandInfo info() {
@@ -32,22 +38,36 @@ public void define(@NotNull LiteralArgumentBuilder root, @NotNull Command
private static void teleportToVillage(@NotNull Player player) {
player.setNoDamageTicks(10);
MessageKey.of("command.village.searching").send(player, Prefix.CHALLENGES);
- Regions.nextTick(Challenges.getInstance(), player, () -> {
- World world = player.getWorld();
- Location village = world.locateNearestStructure(player.getLocation(), StructureType.VILLAGE, 5000, true);
- if (village == null) {
- MessageKey.of("command.village.none").send(player, Prefix.CHALLENGES);
- return;
- }
+ searchRings(SEARCH_RADII, 0,
+ radius -> player.getWorld().locateNearestStructure(player.getLocation(), StructureType.VILLAGE, radius, true),
+ task -> Regions.nextTick(Challenges.getInstance(), player, task),
+ village -> teleportTo(player, village),
+ () -> MessageKey.of("command.village.none").send(player, Prefix.CHALLENGES));
+ }
- world.getChunkAtAsync(village).thenAccept(chunk -> Regions.at(Challenges.getInstance(), village, () -> {
- Location target = world.getHighestBlockAt(village).getLocation().add(0.5, 1, 0.5);
- Regions.later(Challenges.getInstance(), player, () -> player.teleportAsync(target).thenAccept(success -> {
- SoundSample.TELEPORT.play(player);
- MessageKey.of("command.village.done").send(player, Prefix.CHALLENGES);
- }), 20 /* run after 1 second to give the chunks/world time to load/generate */);
- }));
+ static void searchRings(int[] radii, int ring, @NotNull IntFunction locate, @NotNull Consumer nextTick,
+ @NotNull Consumer onFound, @NotNull Runnable onNone) {
+ nextTick.accept(() -> {
+ Location village = locate.apply(radii[ring]);
+ if (village != null) {
+ onFound.accept(village);
+ } else if (ring + 1 < radii.length) {
+ searchRings(radii, ring + 1, locate, nextTick, onFound, onNone);
+ } else {
+ onNone.run();
+ }
});
}
+ private static void teleportTo(@NotNull Player player, @NotNull Location village) {
+ World world = village.getWorld();
+ world.getChunkAtAsync(village).thenAccept(chunk -> Regions.at(Challenges.getInstance(), village, () -> {
+ Location target = world.getHighestBlockAt(village).getLocation().add(0.5, 1, 0.5);
+ Regions.later(Challenges.getInstance(), player, () -> player.teleportAsync(target).thenAccept(success -> {
+ SoundSample.TELEPORT.play(player);
+ MessageKey.of("command.village.done").send(player, Prefix.CHALLENGES);
+ }), 20 /* run after 1 second to give the chunks/world time to load/generate */);
+ }));
+ }
+
}
diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WorldborderCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WorldborderCommand.java
new file mode 100644
index 00000000..50c43110
--- /dev/null
+++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WorldborderCommand.java
@@ -0,0 +1,131 @@
+package net.cyperia.challenges.plugin.spigot.command;
+
+import com.mojang.brigadier.arguments.DoubleArgumentType;
+import com.mojang.brigadier.arguments.LongArgumentType;
+import com.mojang.brigadier.builder.LiteralArgumentBuilder;
+import net.cyperia.challenges.plugin.ChallengeAPI;
+import net.cyperia.challenges.plugin.Challenges;
+import net.cyperia.challenges.plugin.content.i18n.MessageKey;
+import net.cyperia.challenges.plugin.content.i18n.Prefix;
+import net.cyperia.challenges.plugin.management.command.ChallengeCommand;
+import net.cyperia.challenges.plugin.management.command.CommandInfo;
+import net.cyperia.challenges.plugin.management.command.CommandNodes;
+import net.cyperia.challenges.plugin.management.server.BorderManager;
+import net.cyperia.challenges.plugin.management.server.BorderManager.Containment;
+import net.cyperia.challenges.plugin.permission.ChallengesPermissions;
+import net.cyperia.commons.bukkit.utils.misc.Regions;
+import org.bukkit.Location;
+import org.bukkit.World;
+import org.bukkit.World.Environment;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.Locale;
+
+// Replaces the vanilla command: the border players see is the one BorderManager draws, so a vanilla
+// border set next to it would be a second one nobody can see
+public class WorldborderCommand implements ChallengeCommand {
+
+ // keeps the slide, counted in milliseconds and ticks, far from overflowing
+ private static final long MAX_SECONDS = Integer.MAX_VALUE / 20;
+
+ @NotNull
+ @Override
+ public CommandInfo info() {
+ return CommandInfo.command("worldborder", ChallengesPermissions.COMMAND_WORLDBORDER);
+ }
+
+ @Override
+ public void define(@NotNull LiteralArgumentBuilder root, @NotNull CommandNodes nodes) {
+ root.then(nodes.literal("set").then(nodes.argument("size", DoubleArgumentType.doubleArg(BorderManager.MIN_SIZE, BorderManager.MAX_SIZE))
+ .executes(nodes.run((sender, context) -> set(sender, DoubleArgumentType.getDouble(context, "size"), 0)))
+ .then(nodes.argument("seconds", LongArgumentType.longArg(0, MAX_SECONDS))
+ .executes(nodes.run((sender, context) -> set(sender, DoubleArgumentType.getDouble(context, "size"), LongArgumentType.getLong(context, "seconds")))))));
+ root.then(nodes.literal("add").then(nodes.argument("size", DoubleArgumentType.doubleArg(-BorderManager.MAX_SIZE, BorderManager.MAX_SIZE))
+ .executes(nodes.run((sender, context) -> add(sender, DoubleArgumentType.getDouble(context, "size"), 0)))
+ .then(nodes.argument("seconds", LongArgumentType.longArg(0, MAX_SECONDS))
+ .executes(nodes.run((sender, context) -> add(sender, DoubleArgumentType.getDouble(context, "size"), LongArgumentType.getLong(context, "seconds")))))));
+ root.then(nodes.literal("center")
+ .executes(nodes.runAsPlayer((player, context) -> center(player, player.getLocation())))
+ .then(nodes.argument("x", DoubleArgumentType.doubleArg()).then(nodes.argument("z", DoubleArgumentType.doubleArg())
+ .executes(nodes.run((sender, context) -> center(sender,
+ new Location(world(sender), DoubleArgumentType.getDouble(context, "x"), 0, DoubleArgumentType.getDouble(context, "z"))))))));
+ root.then(nodes.literal("get").executes(nodes.run((sender, context) -> get(sender))));
+ root.then(nodes.literal("damage")
+ .then(nodes.literal("buffer").then(nodes.argument("blocks", DoubleArgumentType.doubleArg(0))
+ .executes(nodes.run((sender, context) -> {
+ double buffer = DoubleArgumentType.getDouble(context, "blocks");
+ border().setDamage(buffer, border().getDamagePerBlock());
+ MessageKey.of("command.worldborder.damage-buffer").send(sender, Prefix.CHALLENGES, format(buffer));
+ }))))
+ .then(nodes.literal("amount").then(nodes.argument("damage", DoubleArgumentType.doubleArg(0))
+ .executes(nodes.run((sender, context) -> {
+ double amount = DoubleArgumentType.getDouble(context, "damage");
+ border().setDamage(border().getDamageBuffer(), amount);
+ MessageKey.of("command.worldborder.damage-amount").send(sender, Prefix.CHALLENGES, format(amount));
+ })))));
+ LiteralArgumentBuilder mode = nodes.literal("mode");
+ for (Containment containment : Containment.values()) {
+ String name = containment.name().toLowerCase(Locale.ROOT);
+ mode.then(nodes.literal(name).executes(nodes.run((sender, context) -> {
+ border().setContainment(containment);
+ MessageKey.of("command.worldborder.mode." + name).send(sender, Prefix.CHALLENGES);
+ })));
+ }
+ root.then(mode);
+ root.then(nodes.literal("reset").executes(nodes.run((sender, context) -> {
+ Regions.global(Challenges.getInstance(), () -> border().reset());
+ MessageKey.of("command.worldborder.reset").send(sender, Prefix.CHALLENGES);
+ })));
+ }
+
+ private static void set(@NotNull CommandSender sender, double size, long seconds) {
+ Regions.global(Challenges.getInstance(), () -> border().setSize(size, seconds));
+ sendSize(sender, size, seconds);
+ }
+
+ private static void add(@NotNull CommandSender sender, double delta, long seconds) {
+ double size = Math.clamp(border().getSize(world(sender)) + delta, BorderManager.MIN_SIZE, BorderManager.MAX_SIZE);
+ set(sender, size, seconds);
+ }
+
+ private static void sendSize(@NotNull CommandSender sender, double size, long seconds) {
+ if (seconds > 0) {
+ MessageKey.of("command.worldborder.set-over").send(sender, Prefix.CHALLENGES, format(size), seconds);
+ } else {
+ MessageKey.of("command.worldborder.set").send(sender, Prefix.CHALLENGES, format(size));
+ }
+ }
+
+ private static void center(@NotNull CommandSender sender, @NotNull Location center) {
+ Regions.global(Challenges.getInstance(), () -> border().setCenter(center.getWorld(), center));
+ MessageKey.of("command.worldborder.center").send(sender, Prefix.CHALLENGES, format(center.getX()), format(center.getZ()));
+ }
+
+ private static void get(@NotNull CommandSender sender) {
+ World world = world(sender);
+ Location center = border().getCenter(world);
+ MessageKey.of("command.worldborder.get").send(sender, Prefix.CHALLENGES,
+ format(border().getSize(world)), format(center.getX()), format(center.getZ()));
+ }
+
+ // The console has no world of its own, so it means the overworld of the game
+ @NotNull
+ private static World world(@NotNull CommandSender sender) {
+ if (sender instanceof Player player) return player.getWorld();
+ return ChallengeAPI.getGameWorld(Environment.NORMAL);
+ }
+
+ @NotNull
+ private static BorderManager border() {
+ return Challenges.getInstance().getBorderManager();
+ }
+
+ @NotNull
+ static String format(double value) {
+ if (value == Math.rint(value)) return String.valueOf((long) value);
+ return String.format(Locale.ROOT, "%.1f", value);
+ }
+
+}
diff --git a/plugin/src/main/java/net/cyperia/commons/bukkit/utils/misc/Regions.java b/plugin/src/main/java/net/cyperia/commons/bukkit/utils/misc/Regions.java
index c468cd65..f7b4b5b2 100644
--- a/plugin/src/main/java/net/cyperia/commons/bukkit/utils/misc/Regions.java
+++ b/plugin/src/main/java/net/cyperia/commons/bukkit/utils/misc/Regions.java
@@ -17,6 +17,7 @@
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.stream.Collectors;
+import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
/**
@@ -31,6 +32,9 @@ public final class Regions {
// Only Folia based servers have a regionised server
private static final boolean REGIONIZED = isClassPresent("io.papermc.paper.threadedregions.RegionizedServer");
+ // Tests replace this to simulate a regionised server.
+ static BooleanSupplier regionized = () -> REGIONIZED;
+
private Regions() {
}
@@ -60,6 +64,20 @@ else if (!plugin.isEnabled() || !entity.getScheduler().execute(plugin, task, ret
}
}
+ /**
+ * Removes the entity on its owning thread. While a regionised server stops, region data is gone
+ * and {@code remove} throws, so the entity is only marked non-persistent and is not saved.
+ */
+ public static void remove(@NotNull Plugin plugin, @NotNull Entity entity) {
+ if (regionized.getAsBoolean() && Bukkit.isStopping()) {
+ entity.setPersistent(false);
+ return;
+ }
+ entity(plugin, entity, () -> {
+ if (entity.isValid()) entity.remove();
+ });
+ }
+
public static void at(@NotNull Plugin plugin, @NotNull Location location, @NotNull Runnable task) {
if (Bukkit.isOwnedByCurrentRegion(location)) task.run();
else if (plugin.isEnabled()) Bukkit.getRegionScheduler().execute(plugin, location, task);
@@ -83,7 +101,7 @@ public static CompletableFuture forEachRegion(@NotNull Plugin plugin, @Not
List players = Bukkit.getOnlinePlayers().stream().filter(player -> player.getWorld() == world).collect(Collectors.toList());
if (players.isEmpty()) {
- if (!REGIONIZED) runScan(plugin, world, scan);
+ if (!regionized.getAsBoolean()) runScan(plugin, world, scan);
done.complete(null);
return;
}
diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/custom/CustomChallengeTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/custom/CustomChallengeTest.java
new file mode 100644
index 00000000..04f38066
--- /dev/null
+++ b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/custom/CustomChallengeTest.java
@@ -0,0 +1,20 @@
+package net.cyperia.challenges.plugin.challenges.custom;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.CALLS_REAL_METHODS;
+import static org.mockito.Mockito.mock;
+
+class CustomChallengeTest {
+
+ @Test
+ void hasNoFallbackNamesWithoutACatalogEntry() {
+ CustomChallenge challenge = mock(CustomChallenge.class, CALLS_REAL_METHODS);
+
+ assertEquals(List.of(), challenge.getFallbackNames());
+ }
+
+}
diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallengeTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallengeTest.java
new file mode 100644
index 00000000..76ef6009
--- /dev/null
+++ b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallengeTest.java
@@ -0,0 +1,75 @@
+package net.cyperia.challenges.plugin.challenges.implementation.challenge;
+
+import net.cyperia.challenges.plugin.Challenges;
+import org.bukkit.Location;
+import org.bukkit.World;
+import org.bukkit.entity.Player;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+class DamageTeleportChallengeTest {
+
+ @Test
+ void aSecondHitWhileATeleportIsPendingStartsNothing() {
+ try (MockedStatic challenges = mockStatic(Challenges.class, RETURNS_DEEP_STUBS)) {
+ AtomicInteger started = new AtomicInteger();
+ CompletableFuture pending = new CompletableFuture<>();
+ challenges.when(() -> Challenges.getInstance().getWorldManager().loadChunkAfterPrefetch(any(), any())).thenAnswer(i -> {
+ started.incrementAndGet();
+ return pending;
+ });
+ challenges.when(() -> Challenges.getInstance().getBorderManager().getSize(any())).thenReturn(100d);
+ challenges.when(() -> Challenges.getInstance().getBorderManager().getCenter(any())).thenAnswer(i -> new Location(null, 0, 0, 0));
+ DamageTeleportChallenge challenge = mock(DamageTeleportChallenge.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS));
+ Player player = mock(Player.class);
+ when(player.getUniqueId()).thenReturn(UUID.randomUUID());
+ when(player.getWorld()).thenReturn(mock(World.class));
+
+ challenge.handleDamage(player);
+ challenge.handleDamage(player);
+
+ assertEquals(1, started.get());
+ pending.complete(null);
+ challenge.handleDamage(player);
+ assertEquals(2, started.get());
+ }
+ }
+
+ @Test
+ void aWorldWithoutABorderStillTeleportsNearby() {
+ try (MockedStatic challenges = mockStatic(Challenges.class, RETURNS_DEEP_STUBS)) {
+ challenges.when(() -> Challenges.getInstance().getBorderManager().getSize(any())).thenReturn(59_999_968d);
+ challenges.when(() -> Challenges.getInstance().getBorderManager().getCenter(any())).thenAnswer(i -> new Location(null, 0, 0, 0));
+ DamageTeleportChallenge challenge = mock(DamageTeleportChallenge.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS));
+
+ for (int i = 0; i < 100; i++) {
+ Location target = challenge.getRandomLocation(mock(World.class));
+ assertTrue(Math.abs(target.getX()) <= 2000 && Math.abs(target.getZ()) <= 2000, target.toString());
+ }
+ }
+ }
+
+ @Test
+ void aSmallBorderStaysTheLimit() {
+ try (MockedStatic challenges = mockStatic(Challenges.class, RETURNS_DEEP_STUBS)) {
+ challenges.when(() -> Challenges.getInstance().getBorderManager().getSize(any())).thenReturn(100d);
+ challenges.when(() -> Challenges.getInstance().getBorderManager().getCenter(any())).thenAnswer(i -> new Location(null, 0, 0, 0));
+ DamageTeleportChallenge challenge = mock(DamageTeleportChallenge.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS));
+
+ for (int i = 0; i < 100; i++) {
+ Location target = challenge.getRandomLocation(mock(World.class));
+ assertTrue(Math.abs(target.getX()) < 50 && Math.abs(target.getZ()) < 50, target.toString());
+ }
+ }
+ }
+
+}
diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistViewTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistViewTest.java
index 0fa0068d..83bb41e5 100644
--- a/plugin/src/test/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistViewTest.java
+++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistViewTest.java
@@ -1,10 +1,14 @@
package net.cyperia.challenges.plugin.management.menu.generator.impl.goal;
+import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal.ChecklistCategory;
import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal.ChecklistEntry;
+import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage;
import org.bukkit.inventory.ItemStack;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
+import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -28,7 +32,7 @@ private static ChecklistEntry entry(String name, boolean done, List finder
}
private static List apply(GoalChecklistView.Filter filter, GoalChecklistView.Sort sort, boolean descending) {
- return new GoalChecklistView(filter, sort, descending).apply(ENTRIES, NAMES::get);
+ return new GoalChecklistView(filter, sort, descending, GoalChecklistView.ALL_CATEGORIES).apply(ENTRIES, NAMES::get);
}
@Test
@@ -59,4 +63,74 @@ void sortsByFinderNameIgnoringCase() {
apply(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.FINDER, false));
}
+ @Test
+ void sortsByFinderDescendingWithEntriesWithoutFinderLast() {
+ assertEquals(List.of(EARLY_BY_BEN, LATE_BY_ANNA, MISSING, SKIPPED),
+ apply(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.FINDER, true));
+ }
+
+ @Test
+ void usesTheAlphabeticallyFirstOfSeveralFinders() {
+ ChecklistEntry shared = entry("shared", true, List.of(BEN, ANNA), 5L);
+ ChecklistEntry onlyBen = entry("onlyBen", true, List.of(BEN), 6L);
+
+ assertEquals(List.of(shared, onlyBen),
+ new GoalChecklistView(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.FINDER, false, GoalChecklistView.ALL_CATEGORIES)
+ .apply(List.of(onlyBen, shared), NAMES::get));
+ }
+
+ @Test
+ void resolvesEachFinderNameAtMostOnce() {
+ Map calls = new HashMap<>();
+ List many = new ArrayList<>();
+ for (int i = 0; i < 50; i++) many.add(entry("e" + i, true, List.of(i % 2 == 0 ? ANNA : BEN), (long) i));
+ many.add(MISSING);
+
+ new GoalChecklistView(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.FINDER, false, GoalChecklistView.ALL_CATEGORIES)
+ .apply(many, uuid -> {
+ calls.merge(uuid, 1, Integer::sum);
+ return NAMES.get(uuid);
+ });
+
+ assertEquals(Map.of(ANNA, 1, BEN, 1), calls);
+ }
+
+ @Test
+ void doesNotResolveNamesOfFilteredOutEntries() {
+ List asked = new ArrayList<>();
+
+ new GoalChecklistView(GoalChecklistView.Filter.MISSING, GoalChecklistView.Sort.FINDER, false, GoalChecklistView.ALL_CATEGORIES)
+ .apply(ENTRIES, uuid -> {
+ asked.add(uuid);
+ return NAMES.get(uuid);
+ });
+
+ assertEquals(List.of(), asked);
+ }
+
+ private static final List CATEGORIES = List.of(
+ new ChecklistCategory(Mockito.mock(LocalizableMessage.class), Mockito.mock(ItemStack.class), List.of(MISSING)),
+ new ChecklistCategory(Mockito.mock(LocalizableMessage.class), Mockito.mock(ItemStack.class), List.of(EARLY_BY_BEN, SKIPPED)));
+
+ @Test
+ void aCategoryShowsOnlyItsEntries() {
+ GoalChecklistView view = GoalChecklistView.DEFAULT.toggleCategory(1);
+
+ assertEquals(List.of(EARLY_BY_BEN, SKIPPED), view.select(ENTRIES, CATEGORIES));
+ }
+
+ @Test
+ void choosingTheShownCategoryAgainShowsEverything() {
+ GoalChecklistView view = GoalChecklistView.DEFAULT.toggleCategory(1).toggleCategory(1);
+
+ assertEquals(ENTRIES, view.select(ENTRIES, CATEGORIES));
+ }
+
+ @Test
+ void aCategoryTheGoalDoesNotHaveShowsEverything() {
+ GoalChecklistView view = GoalChecklistView.DEFAULT.toggleCategory(1);
+
+ assertEquals(ENTRIES, view.select(ENTRIES, List.of()));
+ }
+
}
diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java
index f0954194..afe60462 100644
--- a/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java
+++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java
@@ -2,18 +2,29 @@
import net.cyperia.challenges.plugin.Challenges;
import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge;
+import net.cyperia.challenges.plugin.management.server.BorderManager.Containment;
+import net.cyperia.commons.common.config.Document;
+import net.cyperia.commons.common.config.document.GsonDocument;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
+import org.bukkit.WorldBorder;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
+import java.util.ArrayList;
+import java.util.List;
+
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -21,19 +32,34 @@
class BorderManagerTest {
+ private static final double VANILLA = 59_999_968d;
+
private MockedStatic challenges;
private MockedStatic bukkit;
private BorderManager border;
private final World world = mock(World.class, RETURNS_DEEP_STUBS);
+ private final FakeBorder real = new FakeBorder(world);
+ private final List drawn = new ArrayList<>();
+ private final AbstractChallenge level = challenge("level-border");
@BeforeEach
void setUp() {
- // update() walks the game worlds; deep stubs hand it an empty list
challenges = mockStatic(Challenges.class, RETURNS_DEEP_STUBS);
bukkit = mockStatic(Bukkit.class);
bukkit.when(Bukkit::getMinecraftVersion).thenReturn("1.21.4");
+ bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(any(Location.class))).thenReturn(true);
+ bukkit.when(() -> Bukkit.getWorld("world")).thenReturn(world);
+ bukkit.when(Bukkit::createWorldBorder).thenAnswer(_ -> {
+ FakeBorder border = new FakeBorder(null);
+ drawn.add(border);
+ return border;
+ });
+ when(Challenges.getInstance().getGameWorldStorage().getGameWorlds()).thenReturn(List.of(world));
+ when(world.getWorldBorder()).thenReturn(real);
+ when(world.getName()).thenReturn("world");
+ when(world.getEnvironment()).thenReturn(World.Environment.NORMAL);
+ when(world.getSpawnLocation()).thenAnswer(_ -> new Location(world, 12, 64, 7));
border = new BorderManager();
- when(world.getWorldBorder().getSize()).thenReturn(59_999_968d);
}
@AfterEach
@@ -43,18 +69,27 @@ void tearDown() {
}
@Test
- void withoutGrowthTheWorldKeepsItsOwnBorder() {
+ void withNothingSetPlayersKeepTheWorldsOwnBorder() {
+ border.update(0);
+
assertFalse(border.isActive());
- assertEquals(59_999_968d, border.getSize(world));
+ assertTrue(drawn.isEmpty());
+ assertEquals(VANILLA, border.getSize(world));
}
@Test
- void growthsAddUpOnABorderThatStartsAtOneBlock() {
- AbstractChallenge level = challenge("level-border");
- AbstractChallenge damage = challenge("damage-border");
+ void aGrowingBorderStartsAtOneBlockAroundTheSpawn() {
+ border.setGrowth(level, 4, false);
- border.setGrowth(level, 0, false);
- assertEquals(1, border.getSize(world));
+ assertEquals(5, drawn().size);
+ assertEquals(12.5, drawn().centerX);
+ assertEquals(7.5, drawn().centerZ);
+ assertEquals(0, drawn().warningDistance);
+ }
+
+ @Test
+ void growthsAddUp() {
+ AbstractChallenge damage = challenge("damage-border");
border.setGrowth(level, 4, false);
border.setGrowth(damage, 3, false);
@@ -67,9 +102,207 @@ void growthsAddUpOnABorderThatStartsAtOneBlock() {
assertEquals(6, border.getSize(world));
}
+ @Test
+ void aBorderSetWithTheCommandIsWhereAGrowingBorderStarts() {
+ border.setCenter(world, new Location(world, 300.5, 0, 300.5));
+ border.setSize(10, 0);
+
+ border.setGrowth(level, 4, false);
+
+ assertEquals(14, drawn().size);
+ assertEquals(300.5, drawn().centerX);
+ assertEquals(300.5, drawn().centerZ);
+ }
+
+ @Test
+ void sizeChangesGoOnTopOfTheCommandsBorder() {
+ border.setCenter(world, new Location(world, 300.5, 0, 300.5));
+ border.setSize(10, 0);
+
+ border.changeSize(1);
+ assertEquals(11, drawn().size);
+ assertEquals(20, drawn().lastTicks, 1);
+
+ border.changeSize(1);
+ assertEquals(12, drawn().size);
+ assertEquals(300.5, drawn().centerX);
+ }
+
+ @Test
+ void sizeChangesWithoutABorderWaitForOne() {
+ border.changeSize(2);
+ assertFalse(border.isActive());
+ assertTrue(drawn.isEmpty());
+
+ border.setSize(10, 0);
+ assertEquals(10, drawn().size);
+ border.changeSize(1);
+ assertEquals(11, drawn().size);
+ }
+
+ @Test
+ void aSizeSetWhileAChallengeGrowsTheBorderIsWhereItGrowsOnFrom() {
+ border.setGrowth(level, 4, false);
+ border.changeSize(2);
+ assertEquals(7, border.getSize(world));
+
+ border.setSize(10, 0);
+ assertEquals(10, drawn().size);
+
+ border.setGrowth(level, 6, false);
+ assertEquals(12, drawn().size);
+ }
+
+ @Test
+ void sizeChangesStopAtOneBlock() {
+ border.setSize(3, 0);
+ border.changeSize(-10);
+ assertEquals(1, drawn().size);
+ }
+
+ @Test
+ void aNewBorderAppearsAtItsSizeInsteadOfSlidingInFromTheHorizon() {
+ border.setSize(10, 5);
+ assertEquals(10, drawn().size);
+ assertEquals(0, drawn().lastTicks);
+
+ border.setSize(20, 5);
+ assertEquals(20, drawn().size);
+ assertEquals(100, drawn().lastTicks, 1);
+ }
+
+ @Test
+ void theWorldsOwnBorderIsNeverWritten() {
+ border.setCenter(world, new Location(world, 300.5, 0, 300.5));
+ border.setSize(10, 0);
+ border.setGrowth(level, 4, false);
+ border.changeSize(3);
+ border.reset();
+
+ assertEquals(0, real.writes);
+ }
+
+ @Test
+ void aResetLeavesOnlyWhatChallengesGrow() {
+ border.setSize(10, 0);
+ border.reset();
+ assertFalse(border.isActive());
+
+ border.setSize(10, 0);
+ border.setGrowth(level, 4, false);
+ border.reset();
+ assertTrue(border.isActive());
+ assertEquals(5, border.getSize(world));
+ }
+
+ @Test
+ void theBorderOutlivesARestart() {
+ border.setCenter(world, new Location(world, 300.5, 0, -20.5));
+ border.setSize(10, 0);
+ border.changeSize(2);
+ border.setDamage(2, 0.5);
+ border.setContainment(Containment.PUSH);
+ Document save = new GsonDocument();
+ border.writeGameState(save);
+
+ BorderManager restarted = new BorderManager();
+ restarted.loadGameState(save);
+
+ assertEquals(12, restarted.getSize(world));
+ assertEquals(300.5, restarted.getCenter(world).getX());
+ assertEquals(-20.5, restarted.getCenter(world).getZ());
+ assertEquals(2, restarted.getDamageBuffer());
+ assertEquals(0.5, restarted.getDamagePerBlock());
+ assertEquals(Containment.PUSH, restarted.getContainment());
+ }
+
+ @Test
+ void aSaveWithoutASizeHasNoBorder() {
+ border.changeSize(2);
+ Document save = new GsonDocument();
+ border.writeGameState(save);
+
+ BorderManager restarted = new BorderManager();
+ restarted.loadGameState(save);
+
+ assertFalse(restarted.isActive());
+ assertEquals(Containment.DAMAGE, restarted.getContainment());
+ }
+
+ @Test
+ void aNetherBorderIsCenteredAtEightTimesItsCoordinates() {
+ World nether = mock(World.class, RETURNS_DEEP_STUBS);
+ when(nether.getEnvironment()).thenReturn(World.Environment.NETHER);
+ when(Challenges.getInstance().getGameWorldStorage().getGameWorlds()).thenReturn(List.of(nether));
+
+ border.setCenter(nether, new Location(nether, 10, 70, -3));
+ border.setSize(10, 0);
+
+ assertEquals(80, drawn().centerX);
+ assertEquals(-24, drawn().centerZ);
+ }
+
+ @Test
+ void theDistanceOutsideIsMeasuredFromWhereTheClientStopsWalking() {
+ border.setCenter(world, new Location(world, 0.5, 0, 0.5));
+ border.setSize(9, 0);
+
+ // drawn from -4 to 5, walkable from -4 to 5; at 10 it is drawn from -4.5 to 5.5 and walkable from -5 to 6
+ assertEquals(0, border.distanceOutside(new Location(world, 4.7, 64, 0)));
+ assertEquals(4, border.distanceOutside(new Location(world, 9, 64, 0)), 1e-9);
+ assertEquals(7, border.distanceOutside(new Location(world, 2, 64, -11)), 1e-9);
+
+ border.setSize(10, 0);
+ assertEquals(0, border.distanceOutside(new Location(world, 5.7, 64, 0)));
+ assertEquals(0, border.distanceOutside(new Location(world, -4.7, 64, 0)));
+ assertEquals(0.5, border.distanceOutside(new Location(world, 6.5, 64, 0)), 1e-9);
+ }
+
+ @Test
+ void aSlidingBorderHoldsPlayersToWhereItIsDrawnNow() {
+ border.setCenter(world, new Location(world, 0.5, 0, 0.5));
+ border.setSize(20, 0);
+ border.setSize(4, 60);
+
+ assertEquals(4, border.getSize(world));
+ assertEquals(20, border.getDrawnSize(world), 0.1);
+ assertFalse(border.isOutside(new Location(world, 8.5, 64, 0.5)));
+ assertEquals(0, border.distanceOutside(new Location(world, 8.5, 64, 0.5)));
+ }
+
+ @Test
+ void aBorderUsedBeforeAResetStartsAtItsNewSize() {
+ border.setSize(5000, 0);
+ border.reset();
+ border.setSize(100, 10);
+
+ assertEquals(100, drawn().size);
+ assertEquals(0, drawn().lastTicks);
+ assertEquals(100, border.getDrawnSize(world));
+ }
+
+ @Test
+ void aCenterMovedDuringASlideKeepsItSliding() {
+ border.setSize(20, 0);
+ border.setSize(4, 60);
+ border.setCenter(world, new Location(world, 50, 0, 50));
+
+ assertEquals(4, drawn().size);
+ assertEquals(1200, drawn().lastTicks, 2);
+ assertEquals(50, drawn().centerX);
+ }
+
+ @Test
+ void aBorderWithoutASlideIsDrawnAtItsSize() {
+ border.setSize(20, 0);
+ border.setSize(4, 0);
+
+ assertEquals(4, border.getDrawnSize(world));
+ }
+
@Test
void aFractionalSizeHoldsPlayersToTheWholeBlocksTheClientCollidesWith() {
- border.setCenter(world, new Location(world, 0.5, 64, 0.5));
+ border.setCenter(world, new Location(world, 0.5, 0, 0.5));
border.setGrowth(challenge("damage-border"), 4.1, false);
// drawn from -2.05 to 3.05, walkable from -3 to 4
@@ -81,7 +314,7 @@ void aFractionalSizeHoldsPlayersToTheWholeBlocksTheClientCollidesWith() {
@Test
void aPlayerOutsideIsPutJustInsideWhereTheyCrossed() {
- border.setCenter(world, new Location(world, 0.5, 64, 0.5));
+ border.setCenter(world, new Location(world, 0.5, 0, 0.5));
border.setGrowth(challenge("damage-border"), 9, false);
Block feet = mock(Block.class);
@@ -92,11 +325,7 @@ void aPlayerOutsideIsPutJustInsideWhereTheyCrossed() {
when(feet.getRelative(BlockFace.DOWN)).thenReturn(ground);
when(world.getBlockAt(any(Location.class))).thenReturn(feet);
- Player player = mock(Player.class);
- when(player.getWorld()).thenReturn(world);
- when(player.getWidth()).thenReturn(0.6);
- when(player.getLocation()).thenReturn(new Location(world, 40, 64, 2));
-
+ Player player = player();
border.teleportInside(player);
ArgumentCaptor target = ArgumentCaptor.forClass(Location.class);
@@ -107,9 +336,30 @@ void aPlayerOutsideIsPutJustInsideWhereTheyCrossed() {
assertEquals(64, target.getValue().getY(), 1e-9);
}
+ @Test
+ void aPlayerWhoseTeleportIsStillOnItsWayIsNotSentAgain() {
+ border.setCenter(world, new Location(world, 0.5, 0, 0.5));
+ border.setGrowth(challenge("damage-border"), 9, false);
+ Block feet = mock(Block.class);
+ when(feet.isPassable()).thenReturn(true);
+ when(feet.getRelative(any(BlockFace.class))).thenReturn(feet);
+ when(world.getBlockAt(any(Location.class))).thenReturn(feet);
+
+ Player player = player();
+ CompletableFuture pending = new CompletableFuture<>();
+ when(player.teleportAsync(any(Location.class))).thenReturn(pending);
+ border.teleportInside(player);
+ border.teleportInside(player);
+ verify(player, times(1)).teleportAsync(any(Location.class));
+
+ pending.complete(true);
+ border.teleportInside(player);
+ verify(player, times(2)).teleportAsync(any(Location.class));
+ }
+
@Test
void overTheVoidAPlayerIsPutOnTheCenterInstead() {
- border.setCenter(world, new Location(world, 0.5, 64, 0.5));
+ border.setCenter(world, new Location(world, 0.5, 0, 0.5));
border.setGrowth(challenge("damage-border"), 9, false);
Block air = mock(Block.class);
@@ -119,11 +369,7 @@ void overTheVoidAPlayerIsPutOnTheCenterInstead() {
when(world.getBlockAt(any(Location.class))).thenReturn(air);
when(world.getMinHeight()).thenReturn(0);
- Player player = mock(Player.class);
- when(player.getWorld()).thenReturn(world);
- when(player.getWidth()).thenReturn(0.6);
- when(player.getLocation()).thenReturn(new Location(world, 40, 64, 2));
-
+ Player player = player();
border.teleportInside(player);
ArgumentCaptor target = ArgumentCaptor.forClass(Location.class);
@@ -132,10 +378,141 @@ void overTheVoidAPlayerIsPutOnTheCenterInstead() {
assertEquals(0.5, target.getValue().getZ(), 1e-9);
}
+ private FakeBorder drawn() {
+ assertEquals(1, drawn.size(), "one border per world");
+ return drawn.getFirst();
+ }
+
+ private Player player() {
+ Player player = mock(Player.class);
+ when(player.getWorld()).thenReturn(world);
+ when(player.getWidth()).thenReturn(0.6);
+ when(player.getLocation()).thenReturn(new Location(world, 40, 64, 2));
+ when(player.getUniqueId()).thenReturn(UUID.randomUUID());
+ when(player.teleportAsync(any(Location.class))).thenReturn(CompletableFuture.completedFuture(true));
+ return player;
+ }
+
private static AbstractChallenge challenge(String name) {
AbstractChallenge challenge = mock(AbstractChallenge.class);
when(challenge.getUniqueName()).thenReturn(name);
return challenge;
}
+ private static final class FakeBorder implements WorldBorder {
+
+ private final World world;
+ private double size = VANILLA;
+ private double centerX;
+ private double centerZ;
+ private int warningDistance = 5;
+ private int warningTicks = 300;
+ private long lastTicks;
+ private int writes;
+
+ FakeBorder(@Nullable World world) {
+ this.world = world;
+ }
+
+ @Override
+ public @Nullable World getWorld() {
+ return world;
+ }
+
+ @Override
+ public void reset() {
+ size = VANILLA;
+ centerX = 0;
+ centerZ = 0;
+ }
+
+ @Override
+ public double getSize() {
+ return size;
+ }
+
+ @Override
+ public void setSize(double newSize) {
+ changeSize(newSize, 0);
+ }
+
+ @Override
+ public void changeSize(double newSize, long ticks) {
+ writes++;
+ size = newSize;
+ lastTicks = ticks;
+ }
+
+ @Override
+ public @NotNull Location getCenter() {
+ return new Location(world, centerX, 0, centerZ);
+ }
+
+ @Override
+ public void setCenter(double x, double z) {
+ writes++;
+ centerX = x;
+ centerZ = z;
+ }
+
+ @Override
+ public void setCenter(@NotNull Location location) {
+ setCenter(location.getX(), location.getZ());
+ }
+
+ @Override
+ public double getDamageBuffer() {
+ return 5;
+ }
+
+ @Override
+ public void setDamageBuffer(double blocks) {
+ }
+
+ @Override
+ public double getDamageAmount() {
+ return 0.2;
+ }
+
+ @Override
+ public void setDamageAmount(double damage) {
+ }
+
+ @Override
+ public int getWarningTimeTicks() {
+ return warningTicks;
+ }
+
+ @Override
+ public void setWarningTimeTicks(int ticks) {
+ warningTicks = ticks;
+ }
+
+ @Override
+ public int getWarningDistance() {
+ return warningDistance;
+ }
+
+ @Override
+ public void setWarningDistance(int distance) {
+ warningDistance = distance;
+ }
+
+ @Override
+ public boolean isInside(@NotNull Location location) {
+ return true;
+ }
+
+ @Override
+ public double getMaxSize() {
+ return VANILLA;
+ }
+
+ @Override
+ public double getMaxCenterCoordinate() {
+ return 29_999_984d;
+ }
+
+ }
+
}
diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/PlayerFoldersTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/PlayerFoldersTest.java
new file mode 100644
index 00000000..bdfdf352
--- /dev/null
+++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/PlayerFoldersTest.java
@@ -0,0 +1,38 @@
+package net.cyperia.challenges.plugin.management.server;
+
+import net.cyperia.commons.common.misc.FileUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class PlayerFoldersTest {
+
+ @Test
+ void playerFoldersSurviveTheWorldDeletionEmpty(@TempDir File container) throws IOException {
+ File level = new File(container, "world");
+ File data = new File(level, "players/data");
+ File stats = new File(level, "players/stats");
+ assertTrue(data.mkdirs() && stats.mkdirs());
+ Files.writeString(new File(data, "player.dat").toPath(), "inventory");
+
+ List folders = WorldManager.listPlayerFolders(level);
+ FileUtils.deleteWorldFolder(level);
+ folders.forEach(File::mkdirs);
+
+ assertTrue(data.isDirectory());
+ assertTrue(stats.isDirectory());
+ assertArrayEquals(new String[0], data.list());
+ }
+
+ @Test
+ void aLevelWithoutPlayerFoldersHasNoneToKeep(@TempDir File container) {
+ assertEquals(List.of(), WorldManager.listPlayerFolders(new File(container, "world")));
+ }
+
+}
diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/WorldManagerTerrainPrefetchTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/WorldManagerTerrainPrefetchTest.java
new file mode 100644
index 00000000..83820900
--- /dev/null
+++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/WorldManagerTerrainPrefetchTest.java
@@ -0,0 +1,134 @@
+package net.cyperia.challenges.plugin.management.server;
+
+import net.cyperia.challenges.plugin.Challenges;
+import net.cyperia.commons.bukkit.utils.logging.Logger;
+import net.cyperia.commons.common.config.document.GsonDocument;
+import org.bukkit.Bukkit;
+import org.bukkit.Chunk;
+import org.bukkit.Location;
+import org.bukkit.World;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.*;
+
+class WorldManagerTerrainPrefetchTest {
+
+ private MockedStatic challenges;
+ private MockedStatic logger;
+ private WorldManager manager;
+ private final Location at = mock(Location.class);
+
+ @BeforeEach
+ void setUp() {
+ challenges = mockStatic(Challenges.class, RETURNS_DEEP_STUBS);
+ challenges.when(() -> Challenges.getInstance().getConfigDocument()).thenReturn(new GsonDocument());
+ logger = mockStatic(Logger.class);
+ manager = new WorldManager();
+ }
+
+ @AfterEach
+ void tearDown() {
+ logger.close();
+ challenges.close();
+ }
+
+ @Test
+ void completesImmediatelyWithoutAPrefetcher() {
+ assertTrue(manager.prefetchTerrain(at).isDone());
+ }
+
+ @Test
+ void delegatesToTheInstalledPrefetcher() {
+ CompletableFuture pending = new CompletableFuture<>();
+ manager.setTerrainPrefetcher(location -> {
+ assertSame(at, location);
+ return pending;
+ });
+
+ CompletableFuture result = manager.prefetchTerrain(at);
+
+ assertFalse(result.isDone());
+ pending.complete(null);
+ assertTrue(result.isDone());
+ }
+
+ @Test
+ void rejectsNull() {
+ assertThrows(NullPointerException.class, () -> manager.setTerrainPrefetcher(null));
+ }
+
+ @Test
+ void anExceptionalFutureStillCompletes() {
+ manager.setTerrainPrefetcher(location -> CompletableFuture.failedFuture(new IllegalStateException("boom")));
+
+ CompletableFuture result = manager.prefetchTerrain(at);
+
+ assertTrue(result.isDone());
+ assertFalse(result.isCompletedExceptionally());
+ }
+
+ @Test
+ void aThrowingPrefetcherStillCompletes() {
+ manager.setTerrainPrefetcher(location -> {
+ throw new NoSuchMethodError("prefetch");
+ });
+
+ CompletableFuture result = manager.prefetchTerrain(at);
+
+ assertTrue(result.isDone());
+ assertFalse(result.isCompletedExceptionally());
+ }
+
+ @Test
+ void aNullFutureStillCompletes() {
+ manager.setTerrainPrefetcher(location -> null);
+
+ assertTrue(manager.prefetchTerrain(at).isDone());
+ }
+
+ @Test
+ void loadsTheChunkOnlyAfterThePrefetchCompleted() {
+ World world = mock(World.class);
+ Chunk chunk = mock(Chunk.class);
+ when(at.getWorld()).thenReturn(world);
+ when(world.getChunkAtAsync(at)).thenReturn(CompletableFuture.completedFuture(chunk));
+ try (MockedStatic bukkit = mockStatic(Bukkit.class)) {
+ bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(at)).thenReturn(true);
+ CompletableFuture pending = new CompletableFuture<>();
+ manager.setTerrainPrefetcher(location -> pending);
+ AtomicReference received = new AtomicReference<>();
+
+ CompletableFuture done = manager.loadChunkAfterPrefetch(at, received::set);
+
+ verify(world, never()).getChunkAtAsync(any(Location.class));
+ assertFalse(done.isDone());
+ pending.complete(null);
+ verify(world).getChunkAtAsync(at);
+ assertSame(chunk, received.get());
+ assertTrue(done.isDone());
+ }
+ }
+
+ @Test
+ void aFailedChunkLoadFailsTheFuture() {
+ World world = mock(World.class);
+ when(at.getWorld()).thenReturn(world);
+ when(world.getChunkAtAsync(at)).thenReturn(CompletableFuture.failedFuture(new IllegalStateException("boom")));
+ try (MockedStatic bukkit = mockStatic(Bukkit.class)) {
+ bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(at)).thenReturn(true);
+
+ assertTrue(manager.loadChunkAfterPrefetch(at, chunk -> { }).isCompletedExceptionally());
+ }
+ }
+
+}
diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java
index 01f5ecae..6f03213e 100644
--- a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java
+++ b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java
@@ -109,6 +109,26 @@ void timeTakesNamedTimesAndTicks() {
assertFalse(runs("time set dusk", sender));
}
+ @Test
+ void worldborderTakesTheVanillaSubcommandsAndAMode() {
+ register(new WorldborderCommand());
+ CommandSender sender = senderWith(ChallengesPermissions.COMMAND_WORLDBORDER);
+
+ assertTrue(runs("worldborder set 10", sender));
+ assertTrue(runs("worldborder set 10.5 30", sender));
+ assertTrue(runs("worldborder add -4 5", sender));
+ assertTrue(runs("worldborder center 300.5 -20", sender));
+ assertTrue(runs("worldborder damage buffer 0", sender));
+ assertTrue(runs("worldborder damage amount 0.2", sender));
+ assertTrue(runs("worldborder mode push", sender));
+ assertTrue(runs("worldborder mode damage", sender));
+ assertTrue(runs("worldborder get", sender));
+ assertTrue(runs("worldborder reset", sender));
+ assertFalse(runs("worldborder set 0", sender));
+ assertFalse(runs("worldborder mode bounce", sender));
+ assertFalse(runs("worldborder set 10", senderWith()));
+ }
+
@Test
void genericCommandsAreTheOnesANetworkToolboxProvides() {
assertTrue(new HealCommand().info().isGeneric());
@@ -117,6 +137,7 @@ void genericCommandsAreTheOnesANetworkToolboxProvides() {
assertTrue(HelpCommand.INFO.isGeneric());
assertFalse(new TimerCommand().info().isGeneric());
assertFalse(new BackCommand().info().isGeneric());
+ assertFalse(new WorldborderCommand().info().isGeneric());
}
@Test
diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommandTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommandTest.java
new file mode 100644
index 00000000..553e9e4e
--- /dev/null
+++ b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommandTest.java
@@ -0,0 +1,58 @@
+package net.cyperia.challenges.plugin.spigot.command;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.Executor;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class DatabaseCommandTest {
+
+ private final Queue async = new ArrayDeque<>();
+ private final Queue global = new ArrayDeque<>();
+ private final List events = new ArrayList<>();
+
+ private final Executor asyncExecutor = async::add;
+ private final Executor globalExecutor = global::add;
+
+ @Test
+ void runsTheDatabaseCallOnlyOnTheAsyncExecutor() {
+ DatabaseCommand.offThread(asyncExecutor, globalExecutor, () -> {
+ events.add("db");
+ return "doc";
+ }, doc -> events.add("apply " + doc), ex -> events.add("error"));
+
+ assertTrue(events.isEmpty());
+ async.poll().run();
+ assertEquals(List.of("db"), events);
+ }
+
+ @Test
+ void appliesTheResultOnTheGlobalExecutor() {
+ DatabaseCommand.offThread(asyncExecutor, globalExecutor, () -> "doc",
+ doc -> events.add("apply " + doc), ex -> events.add("error"));
+
+ async.poll().run();
+ assertTrue(events.isEmpty());
+ global.poll().run();
+ assertEquals(List.of("apply doc"), events);
+ }
+
+ @Test
+ void reportsAFailureWithoutApplying() {
+ DatabaseCommand.offThread(asyncExecutor, globalExecutor, () -> {
+ throw new IOException("down");
+ }, doc -> events.add("apply"), ex -> events.add("error " + ex.getMessage()));
+
+ async.poll().run();
+ assertEquals(List.of("error down"), events);
+ assertTrue(global.isEmpty());
+ }
+
+}
diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/VillageCommandTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/VillageCommandTest.java
new file mode 100644
index 00000000..0b365d96
--- /dev/null
+++ b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/VillageCommandTest.java
@@ -0,0 +1,67 @@
+package net.cyperia.challenges.plugin.spigot.command;
+
+import org.bukkit.Location;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class VillageCommandTest {
+
+ private static final int[] RADII = {100, 250, 500};
+
+ private final Queue ticks = new ArrayDeque<>();
+
+ private void runAllTicks() {
+ while (!ticks.isEmpty()) ticks.poll().run();
+ }
+
+ @Test
+ void searchesNothingBeforeTheFirstTick() {
+ List searched = new ArrayList<>();
+ VillageCommand.searchRings(RADII, 0, radius -> {
+ searched.add(radius);
+ return null;
+ }, ticks::add, village -> { }, () -> { });
+ assertTrue(searched.isEmpty());
+ }
+
+ @Test
+ void widensOneRingPerTickUntilFound() {
+ List searched = new ArrayList<>();
+ Location found = new Location(null, 1, 2, 3);
+ List result = new ArrayList<>();
+ VillageCommand.searchRings(RADII, 0, radius -> {
+ searched.add(radius);
+ return radius == 250 ? found : null;
+ }, ticks::add, result::add, () -> result.add(null));
+
+ ticks.poll().run();
+ assertEquals(List.of(100), searched);
+ ticks.poll().run();
+ assertEquals(List.of(100, 250), searched);
+ assertTrue(ticks.isEmpty());
+ assertEquals(List.of(found), result);
+ }
+
+ @Test
+ void reportsNoneAfterTheLastRing() {
+ List searched = new ArrayList<>();
+ AtomicInteger none = new AtomicInteger();
+ VillageCommand.searchRings(RADII, 0, radius -> {
+ searched.add(radius);
+ return null;
+ }, ticks::add, village -> { throw new AssertionError(); }, none::incrementAndGet);
+
+ runAllTicks();
+ assertEquals(List.of(100, 250, 500), searched);
+ assertEquals(1, none.get());
+ }
+
+}
diff --git a/plugin/src/test/java/net/cyperia/commons/bukkit/utils/misc/RegionsTest.java b/plugin/src/test/java/net/cyperia/commons/bukkit/utils/misc/RegionsTest.java
index d2f855d6..ad5b6430 100644
--- a/plugin/src/test/java/net/cyperia/commons/bukkit/utils/misc/RegionsTest.java
+++ b/plugin/src/test/java/net/cyperia/commons/bukkit/utils/misc/RegionsTest.java
@@ -58,6 +58,7 @@ void mockServer() {
@AfterEach
void closeServer() {
bukkit.close();
+ Regions.regionized = () -> false;
}
@Test
@@ -281,4 +282,49 @@ void forEachRegion_scansInlineWhenThePluginIsDisabledOnShutdown() {
assertTrue(done.isDone());
}
+
+ @Test
+ void remove_onlyMarksNonPersistentWhileARegionisedServerStops() {
+ Regions.regionized = () -> true;
+ bukkit.when(Bukkit::isStopping).thenReturn(true);
+ bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(true);
+
+ Regions.remove(plugin, entity);
+
+ verify(entity).setPersistent(false);
+ verify(entity, never()).remove();
+ }
+
+ @Test
+ void remove_removesInlineWhileANonRegionisedServerStops() {
+ bukkit.when(Bukkit::isStopping).thenReturn(true);
+ bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(true);
+ when(entity.isValid()).thenReturn(true);
+
+ Regions.remove(plugin, entity);
+
+ verify(entity).remove();
+ }
+
+ @Test
+ void remove_skipsAnEntityThatIsAlreadyGone() {
+ bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(true);
+ when(entity.isValid()).thenReturn(false);
+
+ Regions.remove(plugin, entity);
+
+ verify(entity, never()).remove();
+ }
+
+ @Test
+ void remove_isScheduledOnTheEntityFromAnotherThread() {
+ Regions.regionized = () -> true;
+ bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(false);
+ when(entityScheduler.execute(any(), any(), any(), anyLong())).thenReturn(true);
+
+ Regions.remove(plugin, entity);
+
+ verify(entityScheduler).execute(eq(plugin), any(), eq(null), eq(1L));
+ verify(entity, never()).remove();
+ }
}