feat(progression): unlock stealth from potion invisibility
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/** Marshals unlock presentation onto the server thread. */
|
||||
public final class BukkitUnlockNotifier implements Consumer<UUID> {
|
||||
private final Function<UUID, Player> playerLookup;
|
||||
private final Consumer<Runnable> mainThread;
|
||||
private final String chatMessage;
|
||||
|
||||
public BukkitUnlockNotifier(
|
||||
Function<UUID, Player> playerLookup,
|
||||
Consumer<Runnable> mainThread,
|
||||
String chatMessage) {
|
||||
this.playerLookup = Objects.requireNonNull(playerLookup, "playerLookup");
|
||||
this.mainThread = Objects.requireNonNull(mainThread, "mainThread");
|
||||
this.chatMessage = Objects.requireNonNull(chatMessage, "chatMessage");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(UUID playerId) {
|
||||
mainThread.accept(() -> {
|
||||
Player player = playerLookup.apply(playerId);
|
||||
if (player == null || !player.isOnline()) {
|
||||
return;
|
||||
}
|
||||
player.sendTitle("Stealth Unlocked", "Your identity can now be concealed", 10, 100, 20);
|
||||
player.sendMessage(chatMessage);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.EntityPotionEffectEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
/** Attributes invisibility changes to directly consumed potions and closes intervals safely. */
|
||||
public final class InvisibilityEffectListener implements Listener {
|
||||
private final QualifyingInvisibilityService progression;
|
||||
private final Clock clock;
|
||||
|
||||
public InvisibilityEffectListener(QualifyingInvisibilityService progression, Clock clock) {
|
||||
this.progression = Objects.requireNonNull(progression, "progression");
|
||||
this.clock = Objects.requireNonNull(clock, "clock");
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onPotionEffect(EntityPotionEffectEvent event) {
|
||||
if (!(event.getEntity() instanceof Player player)) {
|
||||
return;
|
||||
}
|
||||
handlePotionEffect(
|
||||
player,
|
||||
PotionEffectType.INVISIBILITY.equals(event.getModifiedType()),
|
||||
event.getCause(),
|
||||
event.getAction());
|
||||
}
|
||||
|
||||
void handlePotionEffect(
|
||||
Player player,
|
||||
boolean invisibility,
|
||||
EntityPotionEffectEvent.Cause cause,
|
||||
EntityPotionEffectEvent.Action action) {
|
||||
if (!invisibility) {
|
||||
return;
|
||||
}
|
||||
boolean addedOrChanged = action == EntityPotionEffectEvent.Action.ADDED
|
||||
|| action == EntityPotionEffectEvent.Action.CHANGED;
|
||||
if (cause == EntityPotionEffectEvent.Cause.POTION_DRINK && addedOrChanged) {
|
||||
progression.begin(player.getUniqueId(), player.getName(), Instant.now(clock));
|
||||
} else {
|
||||
progression.stop(player.getUniqueId());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
progression.stop(event.getPlayer().getUniqueId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
/** Accumulates qualifying potion invisibility using monotonic elapsed time. */
|
||||
public final class QualifyingInvisibilityService {
|
||||
private final StealthStateManager stateManager;
|
||||
private final long unlockThresholdMillis;
|
||||
private final LongSupplier nanoTime;
|
||||
private final Consumer<UUID> unlockNotifier;
|
||||
private final Map<UUID, ActiveInterval> activeIntervals = new HashMap<>();
|
||||
|
||||
public QualifyingInvisibilityService(
|
||||
StealthStateManager stateManager,
|
||||
Duration unlockThreshold,
|
||||
LongSupplier nanoTime,
|
||||
Consumer<UUID> unlockNotifier) {
|
||||
this.stateManager = Objects.requireNonNull(stateManager, "stateManager");
|
||||
this.unlockThresholdMillis = Objects.requireNonNull(unlockThreshold, "unlockThreshold").toMillis();
|
||||
this.nanoTime = Objects.requireNonNull(nanoTime, "nanoTime");
|
||||
this.unlockNotifier = Objects.requireNonNull(unlockNotifier, "unlockNotifier");
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> begin(UUID playerId, String playerName, Instant startedAt) {
|
||||
Objects.requireNonNull(playerId, "playerId");
|
||||
Objects.requireNonNull(startedAt, "startedAt");
|
||||
long nowNanos = nanoTime.getAsLong();
|
||||
ActiveInterval previous = activeIntervals.put(playerId, new ActiveInterval(nowNanos, startedAt, playerName));
|
||||
return record(playerId, playerName, elapsedMillis(previous, nowNanos), startedAt, true);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> checkpoint(UUID playerId) {
|
||||
long nowNanos = nanoTime.getAsLong();
|
||||
ActiveInterval previous = activeIntervals.get(playerId);
|
||||
if (previous == null) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
long elapsedMillis = elapsedMillis(previous, nowNanos);
|
||||
Instant continuedAt = previous.startedAt().plusMillis(elapsedMillis);
|
||||
activeIntervals.put(playerId, new ActiveInterval(nowNanos, continuedAt, previous.playerName()));
|
||||
return record(playerId, previous.playerName(), elapsedMillis, continuedAt, true);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> stop(UUID playerId) {
|
||||
long nowNanos = nanoTime.getAsLong();
|
||||
ActiveInterval previous = activeIntervals.remove(playerId);
|
||||
if (previous == null) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
return record(playerId, previous.playerName(), elapsedMillis(previous, nowNanos), null, false);
|
||||
}
|
||||
|
||||
public boolean isQualifying(UUID playerId) {
|
||||
return activeIntervals.containsKey(playerId);
|
||||
}
|
||||
|
||||
public Set<UUID> activePlayerIds() {
|
||||
return Set.copyOf(activeIntervals.keySet());
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> stopAll() {
|
||||
CompletableFuture<?>[] stops = activePlayerIds().stream()
|
||||
.map(this::stop)
|
||||
.toArray(CompletableFuture[]::new);
|
||||
return CompletableFuture.allOf(stops);
|
||||
}
|
||||
|
||||
public long currentAccumulatedMillis(UUID playerId) {
|
||||
long persisted = stateManager.snapshot().player(playerId).accumulatedMillis();
|
||||
return Math.addExact(persisted, elapsedMillis(activeIntervals.get(playerId), nanoTime.getAsLong()));
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> record(
|
||||
UUID playerId,
|
||||
String playerName,
|
||||
long elapsedMillis,
|
||||
Instant qualifyingSince,
|
||||
boolean active) {
|
||||
AtomicBoolean unlockedNow = new AtomicBoolean();
|
||||
CompletableFuture<Void> saved = stateManager.update(state -> {
|
||||
PlayerStealthState player = state.player(playerId);
|
||||
long accumulated = Math.addExact(player.accumulatedMillis(), elapsedMillis);
|
||||
boolean unlocked = player.unlocked() || accumulated >= unlockThresholdMillis;
|
||||
unlockedNow.set(unlocked && !player.unlocked());
|
||||
PlayerStealthState updated = new PlayerStealthState(
|
||||
playerId,
|
||||
playerName,
|
||||
accumulated,
|
||||
unlocked,
|
||||
player.preparedLogin(),
|
||||
player.concealed(),
|
||||
active ? qualifyingSince : null,
|
||||
player.unknownFields());
|
||||
return state.withPlayer(updated);
|
||||
});
|
||||
return saved.thenRun(() -> {
|
||||
if (unlockedNow.get()) {
|
||||
unlockNotifier.accept(playerId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static long elapsedMillis(ActiveInterval interval, long nowNanos) {
|
||||
if (interval == null) {
|
||||
return 0L;
|
||||
}
|
||||
long elapsedNanos = Math.max(0L, nowNanos - interval.startedNanos());
|
||||
return Duration.ofNanos(elapsedNanos).toMillis();
|
||||
}
|
||||
|
||||
private record ActiveInterval(long startedNanos, Instant startedAt, String playerName) { }
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
@@ -9,6 +10,7 @@ import org.bukkit.plugin.java.JavaPlugin;
|
||||
public final class SpigotStealthPlugin extends JavaPlugin {
|
||||
private CompletableFuture<StealthStateManager> stateManagerFuture;
|
||||
private StealthSettings settings;
|
||||
private QualifyingInvisibilityService progression;
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
@@ -35,6 +37,9 @@ public final class SpigotStealthPlugin extends JavaPlugin {
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (progression != null) {
|
||||
progression.stopAll().join();
|
||||
}
|
||||
if (stateManagerFuture != null && stateManagerFuture.isDone() && !stateManagerFuture.isCompletedExceptionally()) {
|
||||
stateManagerFuture.join().close();
|
||||
}
|
||||
@@ -45,11 +50,28 @@ public final class SpigotStealthPlugin extends JavaPlugin {
|
||||
}
|
||||
|
||||
private void finishInitialization(StealthStateManager manager) {
|
||||
getServer().getScheduler().runTaskTimer(this, ignored -> manager.save().exceptionally(failure -> {
|
||||
BukkitUnlockNotifier notifier = new BukkitUnlockNotifier(
|
||||
getServer()::getPlayer,
|
||||
runnable -> getServer().getScheduler().runTask(this, runnable),
|
||||
settings.unlockedMessage());
|
||||
progression = new QualifyingInvisibilityService(
|
||||
manager, settings.unlockThreshold(), System::nanoTime, notifier);
|
||||
getServer().getPluginManager().registerEvents(
|
||||
new InvisibilityEffectListener(progression, Clock.systemUTC()), this);
|
||||
getServer().getScheduler().runTaskTimer(this, ignored -> {
|
||||
for (java.util.UUID playerId : progression.activePlayerIds()) {
|
||||
logSaveFailure(progression.checkpoint(playerId));
|
||||
}
|
||||
}, 20L, 20L);
|
||||
getServer().getScheduler().runTaskTimer(this, ignored -> logSaveFailure(manager.save()), 6000L, 6000L);
|
||||
getLogger().info("Spigot Stealth enabled");
|
||||
}
|
||||
|
||||
private void logSaveFailure(CompletableFuture<Void> save) {
|
||||
save.exceptionally(failure -> {
|
||||
getLogger().severe("Unable to save Spigot Stealth state: " + rootMessage(failure));
|
||||
return null;
|
||||
}), 6000L, 6000L);
|
||||
getLogger().info("Spigot Stealth enabled");
|
||||
});
|
||||
}
|
||||
|
||||
private static String rootMessage(Throwable throwable) {
|
||||
|
||||
Reference in New Issue
Block a user