Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
683c4ed312 |
No files matched your search
@@ -77,6 +77,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private games.dmg.fantasystick.ability.OutgoingDamageBonus outgoingDamageBonus;
|
||||
private games.dmg.fantasystick.ability.RallyingCry rallyingCry;
|
||||
private games.dmg.fantasystick.persistence.RallyingCrySettings rallyingCrySettings;
|
||||
private games.dmg.fantasystick.ability.FrostNova frostNova;
|
||||
private games.dmg.fantasystick.persistence.FrostNovaSettings frostNovaSettings;
|
||||
private games.dmg.fantasystick.persistence.HexSettings hexSettings;
|
||||
private games.dmg.fantasystick.persistence.ShieldBashSettings shieldBashSettings;
|
||||
private games.dmg.fantasystick.persistence.StoneSkinSettings stoneSkinSettings;
|
||||
@@ -151,6 +153,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
var guardianBondInitial = games.dmg.fantasystick.persistence.GuardianBondSettings.parse(guardianBondConfiguration);
|
||||
var rallyingCryConfiguration = rallyingCryConfiguration();
|
||||
var rallyingCryInitial = games.dmg.fantasystick.persistence.RallyingCrySettings.parse(rallyingCryConfiguration);
|
||||
var frostNovaConfiguration = frostNovaConfiguration();
|
||||
var frostNovaInitial = games.dmg.fantasystick.persistence.FrostNovaSettings.parse(frostNovaConfiguration);
|
||||
var adminReviveTimeout = games.dmg.fantasystick.persistence.AdminReviveSettings.parse(
|
||||
getConfig().get(games.dmg.fantasystick.persistence.AdminReviveSettings.KEY));
|
||||
var factory = new CharacterFactory();
|
||||
@@ -259,6 +263,9 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
getDataFolder().toPath(), rallyingCryConfiguration);
|
||||
rallyingCry = new games.dmg.fantasystick.ability.RallyingCry(
|
||||
rallyingCryInitial, sessions, parties, outgoingDamageBonus);
|
||||
frostNovaSettings = new games.dmg.fantasystick.persistence.FrostNovaSettings(
|
||||
getDataFolder().toPath(), frostNovaConfiguration);
|
||||
frostNova = new games.dmg.fantasystick.ability.FrostNova(frostNovaInitial, sessions, parties);
|
||||
greatSword = new games.dmg.fantasystick.ability.GreatSword(greatSwordSettings);
|
||||
revivals = new games.dmg.fantasystick.persistence.RevivalStore(getDataFolder().toPath());
|
||||
revive = new games.dmg.fantasystick.ability.Revive(characters, revivals, Clock.systemUTC(), nextTick,
|
||||
@@ -277,6 +284,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
abilityRegistry.register(purify.definition());
|
||||
abilityRegistry.register(guardianBond.definition());
|
||||
abilityRegistry.register(rallyingCry.definition());
|
||||
abilityRegistry.register(frostNova.definition());
|
||||
abilityRegistry.register(greatSword.definition());
|
||||
abilityRegistry.register(revive.definition());
|
||||
sessions.attachAbilityRegistry(abilityRegistry);
|
||||
@@ -323,6 +331,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
admin.attachPurify(purifySettings, purify);
|
||||
admin.attachGuardianBond(guardianBondSettings, guardianBond);
|
||||
admin.attachRallyingCry(rallyingCrySettings, rallyingCry);
|
||||
admin.attachFrostNova(frostNovaSettings, frostNova);
|
||||
admin.attachAdminRevival(adminRevival, adminReviveSettings);
|
||||
admin.attachExperienceGrant(new games.dmg.fantasystick.session.AdminExperienceGrant(
|
||||
characters, rules, sessions, nextTick, getServer()::getPlayer,
|
||||
@@ -351,6 +360,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
combatExperience.install(this);
|
||||
getServer().getPluginManager().registerEvents(fireball, this);
|
||||
getServer().getPluginManager().registerEvents(frostShard, this);
|
||||
getServer().getPluginManager().registerEvents(frostNova, this);
|
||||
getServer().getPluginManager().registerEvents(longbow, this);
|
||||
getServer().getPluginManager().registerEvents(quickstep, this);
|
||||
getServer().getPluginManager().registerEvents(combatMitigation, this);
|
||||
@@ -434,6 +444,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
var closingGuardianBondSettings = guardianBondSettings; guardianBondSettings = null;
|
||||
var closingRallyingCry = rallyingCry; rallyingCry = null;
|
||||
var closingRallyingCrySettings = rallyingCrySettings; rallyingCrySettings = null;
|
||||
var closingFrostNova = frostNova; frostNova = null;
|
||||
var closingFrostNovaSettings = frostNovaSettings; frostNovaSettings = null;
|
||||
var closingOutgoingDamageBonus = outgoingDamageBonus; outgoingDamageBonus = null;
|
||||
var closingAdminRevival = adminRevival; adminRevival = null;
|
||||
var closingAdminReviveSettings = adminReviveSettings; adminReviveSettings = null;
|
||||
@@ -473,6 +485,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
if (closingGuardianBondSettings != null) cleanup("Guardian Bond configuration", closingGuardianBondSettings::close);
|
||||
if (closingRallyingCry != null) cleanup("Rallying Cry", closingRallyingCry::close);
|
||||
if (closingRallyingCrySettings != null) cleanup("Rallying Cry configuration", closingRallyingCrySettings::close);
|
||||
if (closingFrostNova != null) cleanup("Frost Nova", closingFrostNova::close);
|
||||
if (closingFrostNovaSettings != null) cleanup("Frost Nova configuration", closingFrostNovaSettings::close);
|
||||
if (closingOutgoingDamageBonus != null) cleanup("outgoing damage bonuses", closingOutgoingDamageBonus::close);
|
||||
if (closingAdminReviveSettings != null) cleanup("admin revival configuration", closingAdminReviveSettings::close);
|
||||
if (closingSwitchDelaySettings != null) cleanup("switch delay configuration", closingSwitchDelaySettings::close);
|
||||
@@ -507,6 +521,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
: closingGuardianBondSettings.drained().toCompletableFuture(),
|
||||
closingRallyingCrySettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
|
||||
: closingRallyingCrySettings.drained().toCompletableFuture(),
|
||||
closingFrostNovaSettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
|
||||
: closingFrostNovaSettings.drained().toCompletableFuture(),
|
||||
closingAdminReviveSettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
|
||||
: closingAdminReviveSettings.drained().toCompletableFuture(),
|
||||
closingSwitchDelaySettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
|
||||
@@ -747,6 +763,16 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
return java.util.Map.copyOf(values);
|
||||
}
|
||||
|
||||
private java.util.Map<String, String> frostNovaConfiguration() {
|
||||
var values = new java.util.LinkedHashMap<String, String>();
|
||||
for (String key : games.dmg.fantasystick.persistence.FrostNovaSettings.keys()) {
|
||||
values.put(key, getConfig().getString(key,
|
||||
games.dmg.fantasystick.persistence.FrostNovaSettings.defaultValue(key)));
|
||||
}
|
||||
games.dmg.fantasystick.persistence.FrostNovaSettings.parse(values);
|
||||
return java.util.Map.copyOf(values);
|
||||
}
|
||||
|
||||
private games.dmg.fantasystick.ability.GreatSword.Settings greatSwordSettings() {
|
||||
try {
|
||||
var base = new java.math.BigInteger(getConfig().getString("great-sword-base-damage", "7"));
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
package games.dmg.fantasystick.ability;
|
||||
|
||||
import games.dmg.fantasystick.party.PartyRoster;
|
||||
import games.dmg.fantasystick.progression.Stat;
|
||||
import games.dmg.fantasystick.session.ControlInput;
|
||||
import games.dmg.fantasystick.session.EquipmentSessions;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Particle;
|
||||
import org.bukkit.damage.DamageSource;
|
||||
import org.bukkit.damage.DamageType;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
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.EntityDamageEvent;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
/** Bounded instantaneous Frost Nova damage and ownership-aware Slowness. */
|
||||
public final class FrostNova implements AbilityEffect, Listener, AutoCloseable {
|
||||
public record Settings(BigInteger baseDamage, Duration cooldown, double radius,
|
||||
int slownessAmplifier, Duration slownessDuration) {
|
||||
public Settings {
|
||||
Objects.requireNonNull(baseDamage); Objects.requireNonNull(cooldown); Objects.requireNonNull(slownessDuration);
|
||||
if (baseDamage.signum() < 0 || cooldown.isNegative() || cooldown.compareTo(Duration.ofDays(365)) > 0
|
||||
|| !Double.isFinite(radius) || radius <= 0 || radius > 64
|
||||
|| slownessAmplifier < 0 || slownessAmplifier > 255
|
||||
|| slownessDuration.isNegative() || slownessDuration.isZero()
|
||||
|| slownessDuration.compareTo(Duration.ofDays(1)) > 0) {
|
||||
throw new IllegalArgumentException("Invalid Frost Nova settings");
|
||||
}
|
||||
}
|
||||
public static Settings defaults() {
|
||||
return new Settings(BigInteger.valueOf(5), Duration.ofSeconds(12), 5, 1, Duration.ofSeconds(3));
|
||||
}
|
||||
}
|
||||
|
||||
private static final class SlowLease implements AutoCloseable {
|
||||
final LivingEntity target; final PotionEffect previous; final PotionEffect applied;
|
||||
final long started = System.nanoTime(); boolean owned; boolean closed;
|
||||
SlowLease(LivingEntity target, PotionEffect applied) {
|
||||
this.target = target; previous = target.getPotionEffect(PotionEffectType.SLOWNESS); this.applied = applied;
|
||||
}
|
||||
boolean apply() { owned = target.addPotionEffect(applied); return owned; }
|
||||
@Override public void close() {
|
||||
if (closed) return; closed = true; if (!owned) return;
|
||||
var current = target.getPotionEffect(PotionEffectType.SLOWNESS);
|
||||
long elapsed = Math.max(0, (System.nanoTime() - started) / 50_000_000L);
|
||||
int expected = (int) Math.max(0, (long) applied.getDuration() - elapsed);
|
||||
if (current == null || current.getAmplifier() != applied.getAmplifier()
|
||||
|| current.getDuration() > expected + 2) return;
|
||||
target.removePotionEffect(PotionEffectType.SLOWNESS);
|
||||
if (previous != null) {
|
||||
int remaining = (int) Math.max(0, (long) previous.getDuration() - elapsed);
|
||||
if (remaining > 0) target.addPotionEffect(previous.withDuration(remaining));
|
||||
}
|
||||
}
|
||||
}
|
||||
private final class LeaseGroup implements AutoCloseable {
|
||||
final AbilityExecution execution; final List<SlowLease> leases = new ArrayList<>(); boolean closed;
|
||||
LeaseGroup(AbilityExecution execution) { this.execution = execution; }
|
||||
@Override public void close() {
|
||||
if (closed) return; closed = true; active.remove(execution, this);
|
||||
for (var lease : List.copyOf(leases)) lease.close(); leases.clear();
|
||||
}
|
||||
}
|
||||
private static final class Attempt {
|
||||
final AbilityExecution execution; final LivingEntity target; boolean accepted;
|
||||
Attempt(AbilityExecution execution, LivingEntity target) { this.execution = execution; this.target = target; }
|
||||
}
|
||||
|
||||
private volatile Settings settings;
|
||||
private final EquipmentSessions sessions;
|
||||
private final PartyRoster parties;
|
||||
private final Map<AbilityExecution, LeaseGroup> active = new java.util.IdentityHashMap<>();
|
||||
private Attempt damaging;
|
||||
private boolean closed;
|
||||
|
||||
public FrostNova(Settings settings, EquipmentSessions sessions, PartyRoster parties) {
|
||||
this.settings = Objects.requireNonNull(settings); this.sessions = Objects.requireNonNull(sessions);
|
||||
this.parties = Objects.requireNonNull(parties);
|
||||
}
|
||||
public void configure(Settings settings) { this.settings = Objects.requireNonNull(settings); }
|
||||
|
||||
public AbilityDefinition definition() {
|
||||
var current = settings;
|
||||
return new AbilityDefinition("frost_nova", "Frost Nova", Material.SNOWBALL,
|
||||
List.of("Burst in a " + decimal(BigDecimal.valueOf(current.radius())) + "-block sphere for "
|
||||
+ current.baseDamage() + " + INT modifier damage.",
|
||||
"Applies Slowness " + level(current.slownessAmplifier()) + " for " + seconds(current.slownessDuration()) + " seconds."),
|
||||
"Use to affect exposed enemies; caster, party and ordinary players are excluded.",
|
||||
Map.of(Stat.INT, BigInteger.valueOf(16), Stat.DEX, BigInteger.TEN), BigInteger.ONE,
|
||||
AbilityDefinition.Activation.DELAYED, ControlInput.Gesture.USE, current.cooldown(),
|
||||
Map.of("base-damage", new BigDecimal(current.baseDamage()),
|
||||
"radius", BigDecimal.valueOf(current.radius()).stripTrailingZeros(),
|
||||
"slowness-amplifier", BigDecimal.valueOf(current.slownessAmplifier()),
|
||||
"slowness-duration-seconds", BigDecimal.valueOf(current.slownessDuration().toNanos()).movePointLeft(9)),
|
||||
AbilityDefinition.TargetPolicy.AREA, this);
|
||||
}
|
||||
|
||||
public static BigInteger damage(BigInteger intelligence) { return damage(BigInteger.valueOf(5), intelligence); }
|
||||
static BigInteger damage(BigInteger base, BigInteger intelligence) {
|
||||
Objects.requireNonNull(base); Objects.requireNonNull(intelligence);
|
||||
if (base.signum() < 0 || intelligence.signum() < 0) throw new IllegalArgumentException("Invalid Frost Nova damage input");
|
||||
var delta = intelligence.subtract(BigInteger.TEN); var divided = delta.divideAndRemainder(BigInteger.TWO);
|
||||
var modifier = divided[0]; if (delta.signum() < 0 && divided[1].signum() != 0) modifier = modifier.subtract(BigInteger.ONE);
|
||||
return base.add(modifier);
|
||||
}
|
||||
|
||||
@Override public boolean accepts(ControlInput input) { return !closed && input.target() == null; }
|
||||
@Override public void activate(AbilityExecution execution) {
|
||||
if (closed || !execution.stillCurrent()) return;
|
||||
var captured = from(execution.definition()); var source = execution.input().player();
|
||||
Location origin = source.getEyeLocation().clone();
|
||||
var group = new LeaseGroup(execution); active.put(execution, group); execution.own(group);
|
||||
BigInteger exact = damage(captured.baseDamage(), execution.character().stats().get(Stat.INT));
|
||||
double amount = exact.bitLength() > 1023 ? Double.MAX_VALUE : exact.doubleValue();
|
||||
int affected = 0;
|
||||
for (var target : candidates(source, origin, captured.radius())) {
|
||||
if (affected == 64 || !execution.stillCurrent()) break;
|
||||
if (!eligible(execution, target, origin, captured.radius())) continue;
|
||||
var sourceDamage = DamageSource.builder(DamageType.FREEZE).withCausingEntity(source)
|
||||
.withDirectEntity(source).withDamageLocation(origin).build();
|
||||
var attempt = new Attempt(execution, target); damaging = attempt;
|
||||
try { target.damage(amount, sourceDamage); }
|
||||
finally { if (damaging == attempt) damaging = null; }
|
||||
affected++;
|
||||
if (!attempt.accepted || !execution.stillCurrent() || !eligible(execution, target, origin, captured.radius())) continue;
|
||||
int ticks = Math.toIntExact(Math.max(1,
|
||||
(captured.slownessDuration().toNanos() + 49_999_999L) / 50_000_000L));
|
||||
var lease = new SlowLease(target, new PotionEffect(PotionEffectType.SLOWNESS, ticks,
|
||||
captured.slownessAmplifier(), false, true, true));
|
||||
if (lease.apply()) group.leases.add(lease);
|
||||
}
|
||||
try { source.getWorld().spawnParticle(Particle.SNOWFLAKE, origin, 32,
|
||||
captured.radius() / 2, captured.radius() / 2, captured.radius() / 2, 0.01); }
|
||||
catch (RuntimeException ignored) { }
|
||||
if (group.leases.isEmpty()) execution.finish();
|
||||
else execution.later(captured.slownessDuration(), execution::finish);
|
||||
}
|
||||
|
||||
private List<LivingEntity> candidates(Player source, Location origin, double radius) {
|
||||
List<Entity> nearby;
|
||||
try { nearby = source.getNearbyEntities(radius, radius, radius); }
|
||||
catch (RuntimeException unavailable) { return List.of(); }
|
||||
var unique = new LinkedHashMap<UUID, LivingEntity>(); int inspected = 0;
|
||||
for (var entity : nearby) {
|
||||
if (++inspected > 256) break;
|
||||
if (entity instanceof LivingEntity target && target != source) unique.putIfAbsent(target.getUniqueId(), target);
|
||||
}
|
||||
var result = new ArrayList<>(unique.values());
|
||||
result.sort(Comparator.comparingDouble((LivingEntity target) -> distance(origin, target))
|
||||
.thenComparing(LivingEntity::getUniqueId));
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean eligible(AbilityExecution execution, LivingEntity target, Location origin, double radius) {
|
||||
if (target == execution.input().player() || !inside(origin, target, radius)) return false;
|
||||
try {
|
||||
if (!execution.input().player().hasLineOfSight(target) || !unobstructed(origin, target)) return false;
|
||||
} catch (RuntimeException unavailable) { return false; }
|
||||
if (!(target instanceof Player player)) return true;
|
||||
var active = sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);
|
||||
if (active == null) return false;
|
||||
var sourceParty = parties.partyOf(execution.input().player().getUniqueId()).orElse(null);
|
||||
var targetParty = parties.partyOf(player.getUniqueId()).orElse(null);
|
||||
return sourceParty == null || targetParty == null || !sourceParty.id().equals(targetParty.id());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void acceptedDamage(EntityDamageEvent event) {
|
||||
var attempt = damaging;
|
||||
if (attempt == null || attempt.accepted || event.getEntity() != attempt.target
|
||||
|| event.getCause() != EntityDamageEvent.DamageCause.FREEZE
|
||||
|| event.getFinalDamage() <= 0 || !Double.isFinite(event.getFinalDamage())) return;
|
||||
attempt.accepted = true;
|
||||
attempt.execution.report(AbilityReport.Type.DAMAGE, attempt.target, BigDecimal.valueOf(event.getFinalDamage()));
|
||||
}
|
||||
|
||||
private static boolean unobstructed(Location origin, LivingEntity target) {
|
||||
var world = origin.getWorld(); if (world == null) return false;
|
||||
var location = target.getLocation(); if (location.getWorld() != world) return false;
|
||||
var bounds = target.getBoundingBox();
|
||||
var center = bounds == null ? location.toVector().add(new org.bukkit.util.Vector(0, target.getHeight() / 2, 0))
|
||||
: bounds.getCenter();
|
||||
var offset = center.clone().subtract(origin.toVector()); double distance = offset.length();
|
||||
if (!Double.isFinite(distance) || distance == 0) return distance == 0;
|
||||
return world.rayTraceBlocks(origin, offset.multiply(1 / distance), distance,
|
||||
org.bukkit.FluidCollisionMode.NEVER, true) == null;
|
||||
}
|
||||
|
||||
private static boolean inside(Location origin, LivingEntity target, double radius) {
|
||||
try { var location = target.getLocation(); return origin.getWorld() == location.getWorld()
|
||||
&& origin.distanceSquared(location) <= radius * radius; }
|
||||
catch (RuntimeException invalid) { return false; }
|
||||
}
|
||||
private static double distance(Location origin, LivingEntity target) {
|
||||
try { var location = target.getLocation(); return origin.getWorld() == location.getWorld()
|
||||
? origin.distanceSquared(location) : Double.POSITIVE_INFINITY; }
|
||||
catch (RuntimeException invalid) { return Double.POSITIVE_INFINITY; }
|
||||
}
|
||||
private static Settings from(AbilityDefinition definition) {
|
||||
var parameters = definition.parameters();
|
||||
return new Settings(parameters.get("base-damage").toBigIntegerExact(), definition.cooldown(),
|
||||
parameters.get("radius").doubleValue(), parameters.get("slowness-amplifier").intValueExact(),
|
||||
Duration.ofNanos(parameters.get("slowness-duration-seconds").movePointRight(9).longValueExact()));
|
||||
}
|
||||
private static String decimal(BigDecimal value) { return value.stripTrailingZeros().toPlainString(); }
|
||||
private static String seconds(Duration duration) {
|
||||
return decimal(BigDecimal.valueOf(duration.toNanos()).movePointLeft(9));
|
||||
}
|
||||
private static String level(int amplifier) {
|
||||
return switch (amplifier + 1) { case 1 -> "I"; case 2 -> "II"; case 3 -> "III"; case 4 -> "IV"; default -> Integer.toString(amplifier + 1); };
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
if (closed) return; closed = true; damaging = null;
|
||||
for (var group : List.copyOf(active.values())) { group.close(); group.execution.finish(); }
|
||||
active.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import games.dmg.fantasystick.ability.FrostNova;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.OverlappingFileLockException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||
|
||||
/** Serialized durable Frost Nova settings; publication remains a server-thread caller decision. */
|
||||
public final class FrostNovaSettings implements AutoCloseable {
|
||||
private static final int MAX_BYTES = 1_048_576;
|
||||
public static final String BASE = "frost-nova-base-damage";
|
||||
public static final String COOLDOWN = "frost-nova-cooldown-seconds";
|
||||
public static final String RADIUS = "frost-nova-radius-blocks";
|
||||
public static final String SLOWNESS = "frost-nova-slowness-amplifier";
|
||||
public static final String DURATION = "frost-nova-slowness-duration-seconds";
|
||||
private static final List<String> KEYS = List.of(BASE, COOLDOWN, RADIUS, SLOWNESS, DURATION);
|
||||
private static final Map<String, String> DEFAULTS = Map.of(
|
||||
BASE, "5", COOLDOWN, "12", RADIUS, "5", SLOWNESS, "1", DURATION, "3");
|
||||
|
||||
@FunctionalInterface interface Replacement { void move(Path from, Path to) throws IOException; }
|
||||
public record Update(String key, String value, FrostNova.Settings settings, Map<String, String> values, long sequence) {
|
||||
public Update { values = Map.copyOf(values); }
|
||||
}
|
||||
|
||||
private final Path directory;
|
||||
private final Replacement replacement;
|
||||
private final java.util.concurrent.ExecutorService worker = Executors.newSingleThreadExecutor(
|
||||
task -> new Thread(task, "fantasy-frost-nova-configuration"));
|
||||
private volatile Map<String, String> effectiveValues;
|
||||
private Map<String, String> persistedValues;
|
||||
private long persistedSequence;
|
||||
private long publishedSequence;
|
||||
private boolean closed;
|
||||
private int pending;
|
||||
private final CompletableFuture<Void> drained = new CompletableFuture<>();
|
||||
|
||||
public FrostNovaSettings(Path directory, Map<String, String> initial) {
|
||||
this(directory, initial, (from, to) -> Files.move(from, to,
|
||||
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING));
|
||||
}
|
||||
|
||||
FrostNovaSettings(Path directory, Map<String, String> initial, Replacement replacement) {
|
||||
this.directory = Objects.requireNonNull(directory).toAbsolutePath(); this.replacement = Objects.requireNonNull(replacement);
|
||||
var copy = new LinkedHashMap<String, String>();
|
||||
for (String key : KEYS) copy.put(key, Objects.requireNonNull(initial.get(key)));
|
||||
parse(copy); effectiveValues = Map.copyOf(copy); persistedValues = Map.copyOf(copy);
|
||||
}
|
||||
|
||||
public static List<String> keys() { return KEYS; }
|
||||
public static String defaultValue(String key) { return DEFAULTS.get(key); }
|
||||
public String value(String key) { return effectiveValues.get(key); }
|
||||
public FrostNova.Settings settings() { return parse(effectiveValues); }
|
||||
|
||||
public synchronized void publish(Update update) {
|
||||
Objects.requireNonNull(update);
|
||||
if (update.sequence() <= publishedSequence) return;
|
||||
parse(update.values()); effectiveValues = update.values(); publishedSequence = update.sequence();
|
||||
}
|
||||
|
||||
public CompletionStage<Update> set(String key, String value) {
|
||||
Objects.requireNonNull(key); Objects.requireNonNull(value);
|
||||
if (!KEYS.contains(key)) return CompletableFuture.failedStage(new IllegalArgumentException("Unknown setting"));
|
||||
String accepted = canonical(value); var preview = new LinkedHashMap<>(effectiveValues);
|
||||
preview.put(key, accepted); parse(preview);
|
||||
synchronized (this) {
|
||||
if (closed) return CompletableFuture.failedStage(new IOException("Configuration store is closed"));
|
||||
pending++;
|
||||
}
|
||||
try {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
var next = new LinkedHashMap<>(persistedValues); next.put(key, accepted);
|
||||
var parsed = parse(next); save(key, accepted); persistedValues = Map.copyOf(next);
|
||||
return new Update(key, accepted, parsed, persistedValues, ++persistedSequence);
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
throw new java.util.concurrent.CompletionException(failure instanceof IllegalArgumentException
|
||||
? failure : new IOException("Frost Nova configuration save refused or failed; effective settings unchanged"));
|
||||
} finally { finished(); }
|
||||
}, worker).minimalCompletionStage();
|
||||
} catch (RejectedExecutionException rejected) {
|
||||
finished(); return CompletableFuture.failedStage(new IOException("Configuration store is closed"));
|
||||
}
|
||||
}
|
||||
|
||||
private static String canonical(String raw) {
|
||||
try { return new BigDecimal(raw).stripTrailingZeros().toPlainString(); }
|
||||
catch (NumberFormatException invalid) { throw new IllegalArgumentException("Invalid value", invalid); }
|
||||
}
|
||||
|
||||
public static FrostNova.Settings parse(Map<String, String> values) {
|
||||
try { return new FrostNova.Settings(new BigDecimal(values.get(BASE)).toBigIntegerExact(),
|
||||
seconds(values.get(COOLDOWN)), finite(values.get(RADIUS)),
|
||||
new BigDecimal(values.get(SLOWNESS)).intValueExact(), seconds(values.get(DURATION))); }
|
||||
catch (ArithmeticException | NumberFormatException | NullPointerException invalid) {
|
||||
throw new IllegalArgumentException("Frost Nova settings must use supported numeric values", invalid);
|
||||
}
|
||||
}
|
||||
|
||||
private static Duration seconds(String value) {
|
||||
var nanos = new BigDecimal(value).movePointRight(9).toBigIntegerExact().longValueExact();
|
||||
return Duration.ofNanos(nanos);
|
||||
}
|
||||
|
||||
private static double finite(String value) {
|
||||
double result = new BigDecimal(value).doubleValue();
|
||||
if (!Double.isFinite(result)) throw new IllegalArgumentException("Setting is not finite");
|
||||
return result;
|
||||
}
|
||||
|
||||
private void save(String key, String value) throws IOException {
|
||||
Files.createDirectories(directory);
|
||||
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe directory");
|
||||
var file = directory.resolve("config.yml"); var lockFile = directory.resolve(".config.lock");
|
||||
if (Files.exists(lockFile, LinkOption.NOFOLLOW_LINKS) && !Files.isRegularFile(lockFile, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Unsafe lock");
|
||||
}
|
||||
try (var channel = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
|
||||
LinkOption.NOFOLLOW_LINKS); var lock = channel.tryLock()) {
|
||||
if (lock == null) throw new IOException("Configuration busy");
|
||||
var options = new LoaderOptions(); options.setAllowDuplicateKeys(false);
|
||||
options.setMaxAliasesForCollections(20); options.setCodePointLimit(MAX_BYTES);
|
||||
var yaml = new Yaml(new SafeConstructor(options)); Map<String, Object> document = new LinkedHashMap<>();
|
||||
if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
|
||||
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe configuration");
|
||||
byte[] bytes;
|
||||
try (var input = Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS)) { bytes = input.readNBytes(MAX_BYTES + 1); }
|
||||
if (bytes.length > MAX_BYTES) throw new IOException("Configuration too large");
|
||||
Object loaded = yaml.load(StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString());
|
||||
if (loaded != null) {
|
||||
if (!(loaded instanceof Map<?, ?> map)) throw new IOException("Invalid configuration root");
|
||||
for (var entry : map.entrySet()) {
|
||||
if (!(entry.getKey() instanceof String savedKey)) throw new IOException("Invalid configuration key");
|
||||
document.put(savedKey, entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
document.put(key, value); byte[] bytes = yaml.dump(document).getBytes(StandardCharsets.UTF_8);
|
||||
if (bytes.length > MAX_BYTES) throw new IOException("Configuration too large");
|
||||
Path temporary = Files.createTempFile(directory, ".config-", ".tmp");
|
||||
try {
|
||||
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
|
||||
var buffer = ByteBuffer.wrap(bytes); while (buffer.hasRemaining()) output.write(buffer); output.force(true);
|
||||
}
|
||||
replacement.move(temporary, file);
|
||||
} finally { Files.deleteIfExists(temporary); }
|
||||
} catch (OverlappingFileLockException busy) { throw new IOException("Configuration busy"); }
|
||||
}
|
||||
|
||||
private synchronized void finished() { pending--; if (closed && pending == 0) drained.complete(null); }
|
||||
public CompletionStage<Void> drained() { return drained.minimalCompletionStage(); }
|
||||
@Override public synchronized void close() { closed = true; worker.shutdown(); if (pending == 0) drained.complete(null); }
|
||||
}
|
||||
@@ -47,6 +47,8 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
private games.dmg.fantasystick.ability.GuardianBond guardianBond;
|
||||
private games.dmg.fantasystick.persistence.RallyingCrySettings rallyingCrySettings;
|
||||
private games.dmg.fantasystick.ability.RallyingCry rallyingCry;
|
||||
private games.dmg.fantasystick.persistence.FrostNovaSettings frostNovaSettings;
|
||||
private games.dmg.fantasystick.ability.FrostNova frostNova;
|
||||
private AdminCharacterIssuer characterIssuer;
|
||||
private AdminRevival adminRevival;
|
||||
private AdminExperienceGrant experienceGrant;
|
||||
@@ -249,6 +251,12 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
rallyingCrySettings = Objects.requireNonNull(settings); rallyingCry = Objects.requireNonNull(effect);
|
||||
}
|
||||
|
||||
public void attachFrostNova(games.dmg.fantasystick.persistence.FrostNovaSettings settings,
|
||||
games.dmg.fantasystick.ability.FrostNova effect) {
|
||||
if (closed || frostNovaSettings != null) throw new IllegalStateException("Frost Nova already attached or command closed");
|
||||
frostNovaSettings = Objects.requireNonNull(settings); frostNova = Objects.requireNonNull(effect);
|
||||
}
|
||||
|
||||
public void attachSwitchDelay(games.dmg.fantasystick.persistence.SwitchDelaySettings settings){if(closed||switchDelaySettings!=null)throw new IllegalStateException("Switch delay already attached or command closed");switchDelaySettings=Objects.requireNonNull(settings);}
|
||||
public void attachRoleplaySettings(games.dmg.fantasystick.persistence.RoleplaySettings settings){if(closed||roleplaySettings!=null)throw new IllegalStateException("Roleplay settings already attached or command closed");roleplaySettings=Objects.requireNonNull(settings);}
|
||||
public void attachPartySettings(games.dmg.fantasystick.persistence.PartySettings settings){if(closed||partySettings!=null)throw new IllegalStateException("Party settings already attached or command closed");partySettings=Objects.requireNonNull(settings);}
|
||||
@@ -464,6 +472,9 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
if (rallyingCrySettings != null && games.dmg.fantasystick.persistence.RallyingCrySettings.keys().contains(args[1])) {
|
||||
rallyingCryConfiguration(sender, args); return;
|
||||
}
|
||||
if (frostNovaSettings != null && games.dmg.fantasystick.persistence.FrostNovaSettings.keys().contains(args[1])) {
|
||||
frostNovaConfiguration(sender, args); return;
|
||||
}
|
||||
if (frostSettings == null || !games.dmg.fantasystick.persistence.FrostShardSettings.keys().contains(args[1])) {
|
||||
configurationUsage(sender); return;
|
||||
}
|
||||
@@ -672,6 +683,33 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
});
|
||||
}
|
||||
|
||||
private void frostNovaConfiguration(CommandSender sender, String[] args) {
|
||||
String key = args[1];
|
||||
if (args.length == 2) {
|
||||
sender.sendMessage(key + "=" + frostNovaSettings.value(key) + " (applies to future Frost Nova casts only)"); return;
|
||||
}
|
||||
java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.FrostNovaSettings.Update> operation;
|
||||
try { operation = frostNovaSettings.set(key, args[2]); }
|
||||
catch (IllegalArgumentException invalid) {
|
||||
sender.sendMessage("Frost Nova setting is invalid; the effective value is unchanged."); return;
|
||||
}
|
||||
operation.whenComplete((saved, failure) -> {
|
||||
if (failure != null) report(null, "config-" + key, failure);
|
||||
if (closed) return;
|
||||
try { nextTick.accept(() -> {
|
||||
if (closed) return;
|
||||
if (failure == null) {
|
||||
frostNova.configure(saved.settings()); abilities.replace(frostNova.definition()); frostNovaSettings.publish(saved);
|
||||
}
|
||||
if (!sender.hasPermission(PERMISSION)
|
||||
|| sender instanceof org.bukkit.entity.Player player && !player.isOnline()) return;
|
||||
sender.sendMessage(failure == null
|
||||
? "Saved " + key + "=" + saved.value() + " for future Frost Nova casts; active slows and deadlines are unchanged."
|
||||
: "Frost Nova configuration save failed; the effective setting is unchanged.");
|
||||
}); } catch (RuntimeException rejected) { report(null, "config-response", rejected); }
|
||||
});
|
||||
}
|
||||
|
||||
private void hexConfiguration(CommandSender sender, String[] args) {
|
||||
String key=args[1];if(args.length==2){sender.sendMessage(key+"="+hexSettings.value(key)+" (applies to future Hex casts only)");return;}
|
||||
java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.HexSettings.Update> operation;
|
||||
@@ -830,6 +868,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
keys.addAll(games.dmg.fantasystick.persistence.PurifySettings.keys());
|
||||
keys.addAll(games.dmg.fantasystick.persistence.GuardianBondSettings.keys());
|
||||
keys.addAll(games.dmg.fantasystick.persistence.RallyingCrySettings.keys());
|
||||
keys.addAll(games.dmg.fantasystick.persistence.FrostNovaSettings.keys());
|
||||
return matching(keys, args[1]);
|
||||
}
|
||||
if (args.length == 3 && args[0].equals("config")) {
|
||||
@@ -896,6 +935,12 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
String defaults = games.dmg.fantasystick.persistence.RallyingCrySettings.defaultValue(args[1]);
|
||||
return matching(current.equals(defaults) ? List.of(current) : List.of(current, defaults), args[2]);
|
||||
}
|
||||
if (frostNovaSettings != null
|
||||
&& games.dmg.fantasystick.persistence.FrostNovaSettings.keys().contains(args[1])) {
|
||||
String current = frostNovaSettings.value(args[1]);
|
||||
String defaults = games.dmg.fantasystick.persistence.FrostNovaSettings.defaultValue(args[1]);
|
||||
return matching(current.equals(defaults) ? List.of(current) : List.of(current, defaults), args[2]);
|
||||
}
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@@ -115,3 +115,11 @@ rallying-cry-radius-blocks: 8
|
||||
rallying-cry-duration-seconds: 6
|
||||
rallying-cry-speed-amplifier: 0
|
||||
rallying-cry-damage-bonus-percent: 20
|
||||
|
||||
# Frost Nova defaults from the reviewed remaining-development packet.
|
||||
# Admin command: /fantasystick config <key> [value]
|
||||
frost-nova-base-damage: 5
|
||||
frost-nova-cooldown-seconds: 12
|
||||
frost-nova-radius-blocks: 5
|
||||
frost-nova-slowness-amplifier: 1
|
||||
frost-nova-slowness-duration-seconds: 3
|
||||
@@ -1285,7 +1285,7 @@ class EquipmentSessionEventsNativeTest {
|
||||
|
||||
@Test void selectedAbilityUseReachesItsHandlerWithoutVanillaThrowDrinkEquipBlockOrPlacement() throws Exception {
|
||||
try (var f = new Fixture()) {
|
||||
String[] abilities = {"fireball", "purify", "guardian_bond", "shield_bash", "rallying_cry", "war_banner", "revive"};
|
||||
String[] abilities = {"fireball", "purify", "guardian_bond", "shield_bash", "rallying_cry", "frost_nova", "revive"};
|
||||
f.loadout(abilities);
|
||||
var a = f.actor; f.core.activate(a);
|
||||
var target = port(org.bukkit.entity.Player.class); a.targetEntity = target;
|
||||
|
||||
@@ -1721,6 +1721,8 @@ class EquipmentSessionsNativeTest {
|
||||
}
|
||||
case "getOpenInventory" -> view;
|
||||
case "getLocation" -> location.clone();
|
||||
case "getBoundingBox" -> new org.bukkit.util.BoundingBox(location.getX() - 0.3, location.getY(),
|
||||
location.getZ() - 0.3, location.getX() + 0.3, location.getY() + 1.8, location.getZ() + 0.3);
|
||||
case "getGameMode" -> gameMode;
|
||||
case "setGameMode" -> { beforeMode.run(); gameMode = (org.bukkit.GameMode) args[0]; yield null; }
|
||||
case "getHealth" -> health;
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import games.dmg.fantasystick.ability.AbilityExecution;
|
||||
import games.dmg.fantasystick.ability.FrostNova;
|
||||
import games.dmg.fantasystick.party.PartyRoster;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.persistence.YamlCharacterRepository;
|
||||
import games.dmg.fantasystick.progression.Stat;
|
||||
import games.dmg.fantasystick.session.ControlInput;
|
||||
import games.dmg.fantasystick.session.EquipmentSessions;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.minecraft.network.chat.ClickEvent;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||
import org.bukkit.event.entity.EntityDamageEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.inventory.EquipmentSlot;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class FrostNovaNativeTest {
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test void bookAcquisitionEquippedBurstDamagesSlowsEligibleTargetsOnceAndRetainsCooldown() throws Exception {
|
||||
try (var fixture = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
fixture.plugin.setEnabled(true);
|
||||
assertTrue(java.util.Arrays.stream(EntityDamageEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getListener() instanceof FrostNova));
|
||||
var caster = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
var ally = new FantasyStickLifecycleNativeTest.Actor(data); var opponent = new FantasyStickLifecycleNativeTest.Actor(data);
|
||||
prepareCaster(data, caster, false); fixture.players.put(caster.core.id, caster.player);
|
||||
fixture.players.put(ally.core.id, ally.player); fixture.players.put(opponent.core.id, opponent.player);
|
||||
fixture.activate(caster); fixture.activate(ally); fixture.activate(opponent); party(fixture, caster, ally);
|
||||
var enemy = mock(LivingEntity.class); when(enemy.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||
when(enemy.getLocation()).thenReturn(new Location(caster.world, 3, 64, 0)); when(enemy.getType()).thenReturn(org.bukkit.entity.EntityType.ZOMBIE);
|
||||
var vetoed = mock(LivingEntity.class); when(vetoed.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||
when(vetoed.getLocation()).thenReturn(new Location(caster.world, 2.5, 64, 0));
|
||||
doReturn(true).when(caster.player).hasLineOfSight(enemy); doReturn(true).when(caster.player).hasLineOfSight(vetoed);
|
||||
locate(caster, ally.player, 2, true); locate(caster, opponent.player, 4, true);
|
||||
var ordinary = mock(Player.class); when(ordinary.getUniqueId()).thenReturn(UUID.randomUUID()); locate(caster, ordinary, 2, true);
|
||||
doReturn(List.of(enemy, enemy, vetoed, ally.player, ordinary, opponent.player)).when(caster.player)
|
||||
.getNearbyEntities(anyDouble(), anyDouble(), anyDouble());
|
||||
var enemyEffects = effects(enemy); var vetoedEffects = effects(vetoed);
|
||||
var opponentEffects = effects(opponent.player); effects(ally.player); effects(ordinary);
|
||||
var damage = new HashMap<UUID, Double>(); damage(fixture, enemy, damage); damage(fixture, vetoed, damage); damage(fixture, opponent.player, damage);
|
||||
class Veto implements org.bukkit.event.Listener {
|
||||
@org.bukkit.event.EventHandler(priority = org.bukkit.event.EventPriority.LOWEST)
|
||||
public void cancel(EntityDamageEvent event) { if (event.getEntity() == vetoed) event.setCancelled(true); }
|
||||
}
|
||||
fixture.dispatcher.register(new Veto(), fixture.plugin);
|
||||
|
||||
caster.core.inventory.getInventory().setSelectedSlot(0); PartyBookNativeTest.open(fixture, caster);
|
||||
String text = PartyBookNativeTest.text(caster).replaceAll("\\s+", "");
|
||||
assertTrue(text.contains("FrostNova")); assertTrue(text.contains("INT16")); assertTrue(text.contains("DEX10"));
|
||||
assertTrue(text.contains("Cost:1")); assertTrue(text.contains("5")); assertTrue(text.contains("SlownessII"));
|
||||
PartyBookNativeTest.click(fixture, caster, button(caster, "[Learn]", "frost_nova")); drain(fixture, 2);
|
||||
PartyBookNativeTest.click(fixture, caster, button(caster, "[3]", "frost_nova")); drain(fixture, 2);
|
||||
use(fixture, caster); drain(fixture, 2);
|
||||
assertEquals(8, damage.get(enemy.getUniqueId()), 1.0e-9); assertEquals(8, damage.get(opponent.core.id), 1.0e-9);
|
||||
assertEquals(2, damage.size(), "Duplicate, cancelled, party and ordinary targets cannot add accepted hits");
|
||||
assertFalse(vetoedEffects.containsKey(PotionEffectType.SLOWNESS));
|
||||
assertEquals(1, enemyEffects.get(PotionEffectType.SLOWNESS).getAmplifier());
|
||||
assertEquals(1, opponentEffects.get(PotionEffectType.SLOWNESS).getAmplifier());
|
||||
var stored = storage(fixture).find(caster.core.record.id()).get().orElseThrow();
|
||||
assertEquals(BigInteger.valueOf(39), stored.unspentPoints()); assertNotNull(stored.cooldowns().get("frost_nova"));
|
||||
assertEquals(60L, fixture.delayedTicks.getLast()); fixture.delayed.getLast().run();
|
||||
assertFalse(enemyEffects.containsKey(PotionEffectType.SLOWNESS)); assertFalse(opponentEffects.containsKey(PotionEffectType.SLOWNESS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void spherePathOrderingCandidateAndTargetBoundsAreDeterministic() {
|
||||
var sessions = mock(EquipmentSessions.class); var parties = mock(PartyRoster.class); var source = mock(Player.class);
|
||||
var world = mock(org.bukkit.World.class); when(source.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||
when(source.getEyeLocation()).thenReturn(new Location(world, 0, 64, 0)); when(source.getLocation()).thenReturn(new Location(world, 0, 64, 0));
|
||||
var active = new EquipmentSessions.Active(source.getUniqueId(), UUID.randomUUID(), UUID.randomUUID());
|
||||
when(sessions.active(source.getUniqueId())).thenReturn(java.util.Optional.of(active)); when(sessions.current(active)).thenReturn(true);
|
||||
var candidates = new ArrayList<Entity>(); var hitOrder = new ArrayList<UUID>();
|
||||
for (int index = 0; index < 270; index++) {
|
||||
var target = mock(LivingEntity.class); var id = new UUID(0, 300 - index); when(target.getUniqueId()).thenReturn(id);
|
||||
double distance = index < 70 ? 1 + index / 100.0 : 4;
|
||||
when(target.getLocation()).thenReturn(new Location(world, distance, 64, 0)); when(source.hasLineOfSight(target)).thenReturn(index != 1);
|
||||
doAnswer(call -> { hitOrder.add(id); return null; }).when(target).damage(anyDouble(), any(org.bukkit.damage.DamageSource.class));
|
||||
effects(target); candidates.add(target);
|
||||
}
|
||||
when(source.getNearbyEntities(5, 5, 5)).thenReturn(candidates);
|
||||
var execution = execution(source, active); var nova = new FrostNova(FrostNova.Settings.defaults(), sessions, parties);
|
||||
when(execution.definition()).thenReturn(nova.definition()); nova.activate(execution);
|
||||
assertEquals(64, hitOrder.size()); assertFalse(hitOrder.contains(new UUID(0, 299)), "Obstructed target excluded");
|
||||
var sorted = new ArrayList<>(hitOrder); sorted.sort(UUID::compareTo);
|
||||
assertNotEquals(sorted, hitOrder, "Distance precedes UUID while UUID breaks equal-distance ties");
|
||||
verify((LivingEntity) candidates.getLast(), never()).damage(anyDouble(), any(org.bukkit.damage.DamageSource.class));
|
||||
verify(execution, atMost(64)).report(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test void exactSphereBoundaryIsIncludedWhileOutsideAndObstructedTargetsAreExcluded() {
|
||||
var sessions = mock(EquipmentSessions.class); var parties = mock(PartyRoster.class); var source = mock(Player.class);
|
||||
var world = mock(org.bukkit.World.class); when(source.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||
when(source.getEyeLocation()).thenReturn(new Location(world, 0, 64, 0));
|
||||
var active = new EquipmentSessions.Active(source.getUniqueId(), UUID.randomUUID(), UUID.randomUUID());
|
||||
when(sessions.active(source.getUniqueId())).thenReturn(java.util.Optional.of(active)); when(sessions.current(active)).thenReturn(true);
|
||||
var boundary = mock(LivingEntity.class); var outside = mock(LivingEntity.class); var blocked = mock(LivingEntity.class);
|
||||
for (var target : List.of(boundary, outside, blocked)) when(target.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||
when(boundary.getLocation()).thenReturn(new Location(world, 5, 64, 0));
|
||||
when(outside.getLocation()).thenReturn(new Location(world, 5.01, 64, 0));
|
||||
when(blocked.getLocation()).thenReturn(new Location(world, 4, 64, 0));
|
||||
when(source.hasLineOfSight(boundary)).thenReturn(true); when(source.hasLineOfSight(outside)).thenReturn(true);
|
||||
when(source.hasLineOfSight(blocked)).thenReturn(true); when(source.getNearbyEntities(5, 5, 5)).thenReturn(List.of(boundary, outside, blocked));
|
||||
when(world.rayTraceBlocks(any(Location.class), any(org.bukkit.util.Vector.class), eq(4.0),
|
||||
eq(org.bukkit.FluidCollisionMode.NEVER), eq(true))).thenReturn(mock(org.bukkit.util.RayTraceResult.class));
|
||||
effects(boundary); effects(outside); effects(blocked);
|
||||
var execution = execution(source, active); var nova = new FrostNova(FrostNova.Settings.defaults(), sessions, parties);
|
||||
when(execution.definition()).thenReturn(nova.definition()); nova.activate(execution);
|
||||
verify(boundary).damage(anyDouble(), any(org.bukkit.damage.DamageSource.class));
|
||||
verify(outside, never()).damage(anyDouble(), any(org.bukkit.damage.DamageSource.class));
|
||||
verify(blocked, never()).damage(anyDouble(), any(org.bukkit.damage.DamageSource.class));
|
||||
}
|
||||
|
||||
@Test void cancelledDamageAndPartyOrModeRaceApplyNoSlownessOrCredit() throws Exception {
|
||||
var sessions = mock(EquipmentSessions.class); var parties = mock(PartyRoster.class); var source = mock(Player.class);
|
||||
var target = mock(Player.class); var world = mock(org.bukkit.World.class); UUID sourceId = UUID.randomUUID(), targetId = UUID.randomUUID();
|
||||
when(source.getUniqueId()).thenReturn(sourceId); when(target.getUniqueId()).thenReturn(targetId);
|
||||
when(source.getEyeLocation()).thenReturn(new Location(world, 0, 64, 0)); when(source.getLocation()).thenReturn(new Location(world, 0, 64, 0));
|
||||
when(target.getLocation()).thenReturn(new Location(world, 3, 64, 0)); when(source.hasLineOfSight(target)).thenReturn(true);
|
||||
when(source.getNearbyEntities(5, 5, 5)).thenReturn(List.of(target));
|
||||
var sourceActive = new EquipmentSessions.Active(sourceId, UUID.randomUUID(), UUID.randomUUID());
|
||||
var targetActive = new EquipmentSessions.Active(targetId, UUID.randomUUID(), UUID.randomUUID());
|
||||
when(sessions.active(sourceId)).thenReturn(java.util.Optional.of(sourceActive)); when(sessions.current(sourceActive)).thenReturn(true);
|
||||
when(sessions.active(targetId)).thenReturn(java.util.Optional.of(targetActive)); when(sessions.current(targetActive)).thenReturn(true);
|
||||
var targetEffects = effects(target); var execution = execution(source, sourceActive);
|
||||
var nova = new FrostNova(FrostNova.Settings.defaults(), sessions, parties); when(execution.definition()).thenReturn(nova.definition());
|
||||
doAnswer(call -> { when(parties.partyOf(sourceId)).thenReturn(java.util.Optional.of(
|
||||
new PartyRoster.Party(UUID.randomUUID(), sourceId, List.of(sourceId, targetId)))); return null; })
|
||||
.when(target).damage(anyDouble(), any(org.bukkit.damage.DamageSource.class));
|
||||
nova.activate(execution); assertTrue(targetEffects.isEmpty()); verify(execution, never()).report(any(), any(), any());
|
||||
|
||||
when(parties.partyOf(sourceId)).thenReturn(java.util.Optional.empty()); when(sessions.current(targetActive)).thenReturn(false);
|
||||
nova.activate(execution); verify(target, times(1)).damage(anyDouble(), any(org.bukkit.damage.DamageSource.class));
|
||||
}
|
||||
|
||||
@Test void ownedSlownessRestoresWeakerPriorStateButPreservesNewerStrongerState() throws Exception {
|
||||
var sessions = mock(EquipmentSessions.class); var parties = mock(PartyRoster.class); var source = mock(Player.class);
|
||||
var target = mock(LivingEntity.class); var world = mock(org.bukkit.World.class);
|
||||
when(source.getUniqueId()).thenReturn(UUID.randomUUID()); when(target.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||
when(source.getEyeLocation()).thenReturn(new Location(world, 0, 64, 0)); when(target.getLocation()).thenReturn(new Location(world, 2, 64, 0));
|
||||
when(source.hasLineOfSight(target)).thenReturn(true); when(source.getNearbyEntities(5, 5, 5)).thenReturn(List.of(target));
|
||||
var active = new EquipmentSessions.Active(source.getUniqueId(), UUID.randomUUID(), UUID.randomUUID());
|
||||
when(sessions.active(source.getUniqueId())).thenReturn(java.util.Optional.of(active)); when(sessions.current(active)).thenReturn(true);
|
||||
var targetEffects = effects(target); targetEffects.put(PotionEffectType.SLOWNESS,
|
||||
new PotionEffect(PotionEffectType.SLOWNESS, 200, 0));
|
||||
var execution = execution(source, active); var nova = new FrostNova(FrostNova.Settings.defaults(), sessions, parties);
|
||||
when(execution.definition()).thenReturn(nova.definition());
|
||||
doAnswer(call -> { var damageSource = (org.bukkit.damage.DamageSource) call.getArgument(1);
|
||||
var event = new EntityDamageEvent(target, EntityDamageEvent.DamageCause.FREEZE, damageSource, (Double) call.getArgument(0));
|
||||
nova.acceptedDamage(event); return null; }).when(target).damage(anyDouble(), any(org.bukkit.damage.DamageSource.class));
|
||||
nova.activate(execution); assertEquals(1, targetEffects.get(PotionEffectType.SLOWNESS).getAmplifier());
|
||||
var resource = org.mockito.ArgumentCaptor.forClass(AutoCloseable.class); verify(execution).own(resource.capture());
|
||||
resource.getValue().close(); assertEquals(0, targetEffects.get(PotionEffectType.SLOWNESS).getAmplifier());
|
||||
|
||||
var execution2 = execution(source, active); when(execution2.definition()).thenReturn(nova.definition());
|
||||
nova.activate(execution2); targetEffects.put(PotionEffectType.SLOWNESS, new PotionEffect(PotionEffectType.SLOWNESS, 400, 3));
|
||||
var resource2 = org.mockito.ArgumentCaptor.forClass(AutoCloseable.class); verify(execution2).own(resource2.capture());
|
||||
resource2.getValue().close(); assertEquals(3, targetEffects.get(PotionEffectType.SLOWNESS).getAmplifier());
|
||||
}
|
||||
|
||||
@Test void configuredDefinitionAdminRestartAndFutureCastCoverEverySetting() throws Exception {
|
||||
java.nio.file.Files.writeString(data.resolve("config.yml"),
|
||||
"frost-nova-base-damage: 7\nfrost-nova-cooldown-seconds: 2\nfrost-nova-radius-blocks: 8\n"
|
||||
+ "frost-nova-slowness-amplifier: 2\nfrost-nova-slowness-duration-seconds: 5\n");
|
||||
try (var fixture = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
fixture.plugin.setEnabled(true); var registry = (games.dmg.fantasystick.ability.AbilityRegistry)
|
||||
FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin, "abilityRegistry");
|
||||
var definition = registry.find("frost_nova").orElseThrow(); assertEquals(java.time.Duration.ofSeconds(2), definition.cooldown());
|
||||
assertEquals(new BigDecimal("7"), definition.parameters().get("base-damage")); assertEquals(new BigDecimal("8"), definition.parameters().get("radius"));
|
||||
assertEquals(new BigDecimal("2"), definition.parameters().get("slowness-amplifier"));
|
||||
assertEquals(0, new BigDecimal("5").compareTo(definition.parameters().get("slowness-duration-seconds")));
|
||||
var sender = new EquipmentAdminCommandNativeTest.Sender(); sender.allowed = false;
|
||||
assertTrue(fixture.command.tabComplete(sender.port, "fantasystick", new String[]{"config", "frost-nova-"}).isEmpty());
|
||||
fixture.command.execute(sender.port, "fantasystick", new String[]{"config", "frost-nova-radius-blocks", "10"});
|
||||
assertTrue(sender.messages.getLast().contains("Permission denied")); sender.allowed = true;
|
||||
assertEquals(List.of("frost-nova-base-damage", "frost-nova-cooldown-seconds", "frost-nova-radius-blocks",
|
||||
"frost-nova-slowness-amplifier", "frost-nova-slowness-duration-seconds"),
|
||||
fixture.command.tabComplete(sender.port, "fantasystick", new String[]{"config", "frost-nova-"}));
|
||||
assertEquals(List.of("5", "8"), fixture.command.tabComplete(sender.port, "fantasystick",
|
||||
new String[]{"config", "frost-nova-radius-blocks", ""}));
|
||||
fixture.command.execute(sender.port, "fantasystick", new String[]{"config", "frost-nova-radius-blocks"});
|
||||
assertTrue(sender.messages.getLast().contains("=8"));
|
||||
for (String[] update : List.of(new String[]{"frost-nova-base-damage", "9"},
|
||||
new String[]{"frost-nova-cooldown-seconds", "3"}, new String[]{"frost-nova-radius-blocks", "10"},
|
||||
new String[]{"frost-nova-slowness-amplifier", "3"}, new String[]{"frost-nova-slowness-duration-seconds", "6"})) {
|
||||
fixture.command.execute(sender.port, "fantasystick", new String[]{"config", update[0], update[1]});
|
||||
var response = fixture.tasks.poll(5, TimeUnit.SECONDS); assertNotNull(response); response.run();
|
||||
}
|
||||
var configured = registry.find("frost_nova").orElseThrow(); assertEquals(java.time.Duration.ofSeconds(3), configured.cooldown());
|
||||
assertEquals(new BigDecimal("9"), configured.parameters().get("base-damage"));
|
||||
assertEquals(0, new BigDecimal("10").compareTo(configured.parameters().get("radius")));
|
||||
assertEquals(new BigDecimal("3"), configured.parameters().get("slowness-amplifier"));
|
||||
assertEquals(0, new BigDecimal("6").compareTo(configured.parameters().get("slowness-duration-seconds")));
|
||||
|
||||
var caster = new FantasyStickLifecycleNativeTest.Actor(data); prepareCaster(data, caster, true);
|
||||
fixture.players.put(caster.core.id, caster.player); fixture.activate(caster);
|
||||
var enemy = mock(LivingEntity.class); when(enemy.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||
when(enemy.getLocation()).thenReturn(new Location(caster.world, 9, 64, 0)); doReturn(true).when(caster.player).hasLineOfSight(enemy);
|
||||
doReturn(new Location(caster.world, 0, 64, 0)).when(caster.player).getEyeLocation();
|
||||
doReturn(List.of(enemy)).when(caster.player).getNearbyEntities(anyDouble(), anyDouble(), anyDouble());
|
||||
var enemyEffects = effects(enemy); var applied = new HashMap<UUID, Double>(); damage(fixture, enemy, applied);
|
||||
use(fixture, caster); drain(fixture, 2); assertEquals(12, applied.get(enemy.getUniqueId()), 1.0e-9);
|
||||
assertEquals(3, enemyEffects.get(PotionEffectType.SLOWNESS).getAmplifier()); assertEquals(120L, fixture.delayedTicks.getLast());
|
||||
fixture.command.execute(sender.port, "fantasystick", new String[]{"config", "frost-nova-radius-blocks", "0"});
|
||||
assertTrue(sender.messages.getLast().contains("invalid"));
|
||||
fixture.command.execute(sender.port, "fantasystick", new String[]{"config", "frost-nova-radius-blocks", "10", "extra"});
|
||||
assertTrue(sender.messages.getLast().contains("Usage"));
|
||||
fixture.plugin.setEnabled(false); fixture.plugin.setEnabled(true);
|
||||
var saved = ((games.dmg.fantasystick.ability.AbilityRegistry) FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin, "abilityRegistry"))
|
||||
.find("frost_nova").orElseThrow(); assertEquals(new BigDecimal("9"), saved.parameters().get("base-damage"));
|
||||
assertEquals(0, new BigDecimal("10").compareTo(saved.parameters().get("radius")));
|
||||
assertEquals(new BigDecimal("3"), saved.parameters().get("slowness-amplifier"));
|
||||
assertEquals(java.time.Duration.ofSeconds(3), saved.cooldown());
|
||||
assertEquals(0, new BigDecimal("6").compareTo(saved.parameters().get("slowness-duration-seconds")));
|
||||
}
|
||||
for (String invalid : List.of("frost-nova-base-damage: -1\n", "frost-nova-cooldown-seconds: -1\n",
|
||||
"frost-nova-radius-blocks: 0\n", "frost-nova-slowness-amplifier: -1\n", "frost-nova-slowness-duration-seconds: 0\n")) {
|
||||
var directory = data.resolve(Integer.toHexString(invalid.hashCode())); java.nio.file.Files.createDirectories(directory);
|
||||
java.nio.file.Files.writeString(directory.resolve("config.yml"), invalid);
|
||||
try (var fixture = new FantasyStickLifecycleNativeTest.Fixture(directory)) {
|
||||
assertThrows(IllegalArgumentException.class, () -> fixture.plugin.setEnabled(true)); assertTrue(fixture.order.isEmpty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void arbitraryPrecisionFormulaUsesFloorModifier() {
|
||||
assertEquals(BigInteger.valueOf(8), FrostNova.damage(BigInteger.valueOf(16)));
|
||||
assertEquals(BigInteger.valueOf(4), FrostNova.damage(BigInteger.valueOf(9)));
|
||||
var huge = BigInteger.TEN.pow(500); assertEquals(huge.subtract(BigInteger.TEN).divide(BigInteger.TWO).add(BigInteger.valueOf(5)), FrostNova.damage(huge));
|
||||
}
|
||||
|
||||
private static AbilityExecution execution(Player source, EquipmentSessions.Active active) {
|
||||
var execution = mock(AbilityExecution.class); var input = mock(ControlInput.class);
|
||||
when(input.player()).thenReturn(source); when(input.session()).thenReturn(active);
|
||||
when(execution.input()).thenReturn(input); when(execution.stillCurrent()).thenReturn(true);
|
||||
var record = new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());
|
||||
var stats = new EnumMap<>(record.stats()); stats.put(Stat.INT, BigInteger.valueOf(16));
|
||||
when(execution.character()).thenReturn(new CharacterRecord(active.character(), record.name(), record.revision(), stats,
|
||||
record.level(), record.experience(), record.unspentPoints(), record.health(), Set.of("frost_nova"),
|
||||
List.of("frost_nova", "", "", "", "", "", ""), record.cooldowns(), record.restrictedKills(), false, null, null));
|
||||
return execution;
|
||||
}
|
||||
private static Map<org.bukkit.potion.PotionEffectType, PotionEffect> effects(LivingEntity target) {
|
||||
var effects = new HashMap<org.bukkit.potion.PotionEffectType, PotionEffect>();
|
||||
doAnswer(call -> effects.get(call.getArgument(0))).when(target).getPotionEffect(any());
|
||||
doAnswer(call -> { PotionEffect effect = call.getArgument(0); effects.put(effect.getType(), effect); return true; })
|
||||
.when(target).addPotionEffect(any());
|
||||
doAnswer(call -> { effects.remove(call.getArgument(0)); return null; }).when(target).removePotionEffect(any()); return effects;
|
||||
}
|
||||
private static void damage(FantasyStickLifecycleNativeTest.Fixture fixture, LivingEntity target, Map<UUID, Double> damage) {
|
||||
doAnswer(call -> { double amount = call.getArgument(0); org.bukkit.damage.DamageSource source = call.getArgument(1);
|
||||
var event = new EntityDamageByEntityEvent(source.getCausingEntity(), target, EntityDamageEvent.DamageCause.FREEZE, source, amount);
|
||||
fixture.dispatcher.accept(event); if (!event.isCancelled()) damage.merge(target.getUniqueId(), event.getFinalDamage(), Double::sum); return null;
|
||||
}).when(target).damage(anyDouble(), any(org.bukkit.damage.DamageSource.class));
|
||||
}
|
||||
private static void locate(FantasyStickLifecycleNativeTest.Actor caster, Player target, double distance, boolean visible) {
|
||||
doReturn(new Location(caster.world, 0, 64, 0)).when(caster.player).getEyeLocation();
|
||||
doReturn(new Location(caster.world, 0, 64, 0)).when(caster.player).getLocation();
|
||||
doReturn(new Location(caster.world, distance, 64, 0)).when(target).getLocation(); doReturn(visible).when(caster.player).hasLineOfSight(target);
|
||||
}
|
||||
private static void use(FantasyStickLifecycleNativeTest.Fixture fixture, FantasyStickLifecycleNativeTest.Actor actor) {
|
||||
actor.core.inventory.getInventory().setSelectedSlot(2);
|
||||
fixture.dispatcher.accept(new PlayerInteractEvent(actor.player, org.bukkit.event.block.Action.RIGHT_CLICK_AIR,
|
||||
actor.core.inventory.getItem(2), null, org.bukkit.block.BlockFace.SELF, EquipmentSlot.HAND));
|
||||
}
|
||||
private static void party(FantasyStickLifecycleNativeTest.Fixture fixture,
|
||||
FantasyStickLifecycleNativeTest.Actor source, FantasyStickLifecycleNativeTest.Actor target) {
|
||||
var parties = PartyLifecycleNativeTest.parties(fixture); var group = parties.create(source.core.id).orElseThrow();
|
||||
assertTrue(parties.accept(target.core.id, parties.invite(source.core.id, group.id(), target.core.id).orElseThrow().id()));
|
||||
}
|
||||
private static void drain(FantasyStickLifecycleNativeTest.Fixture fixture, int count) throws Exception {
|
||||
for (int index = 0; index < count; index++) PartyBookNativeTest.drain(fixture);
|
||||
}
|
||||
private static CharacterStorage storage(FantasyStickLifecycleNativeTest.Fixture fixture) {
|
||||
return (CharacterStorage) FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin, "characters");
|
||||
}
|
||||
private static ClickEvent.Custom button(FantasyStickLifecycleNativeTest.Actor actor, String label, String ability) {
|
||||
var book = org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(actor.books.getLast())
|
||||
.get(net.minecraft.core.component.DataComponents.WRITTEN_BOOK_CONTENT); assertNotNull(book);
|
||||
for (var page : book.pages()) { var found = button(page.raw(), label, ability); if (found != null) return found; }
|
||||
throw new AssertionError("Missing " + label + " for " + ability);
|
||||
}
|
||||
private static ClickEvent.Custom button(net.minecraft.network.chat.Component component, String label, String ability) {
|
||||
if (component.getString().equals(label) && component.getStyle().getClickEvent() instanceof ClickEvent.Custom custom
|
||||
&& custom.payload().orElse(null) instanceof net.minecraft.nbt.StringTag payload
|
||||
&& payload.value().contains(":" + ability)) return custom;
|
||||
for (var child : component.getSiblings()) { var found = button(child, label, ability); if (found != null) return found; } return null;
|
||||
}
|
||||
private static void prepareCaster(Path directory, FantasyStickLifecycleNativeTest.Actor actor, boolean learned) throws Exception {
|
||||
java.nio.file.Files.createDirectories(directory); var repository = new YamlCharacterRepository(directory);
|
||||
var old = repository.load(actor.core.record.id()).orElseThrow(); var stats = new EnumMap<>(old.stats());
|
||||
stats.put(Stat.INT, BigInteger.valueOf(16)); stats.put(Stat.DEX, BigInteger.TEN);
|
||||
repository.replace(new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), stats,
|
||||
old.level(), old.experience(), BigInteger.valueOf(learned ? 39 : 40), old.health(),
|
||||
learned ? Set.of("frost_nova") : old.learned(), learned ? List.of("frost_nova", "", "", "", "", "", "") : old.loadout(),
|
||||
old.cooldowns(), old.restrictedKills(), false, null, null), old.revision());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class FrostNovaSettingsTest {
|
||||
@TempDir Path data;
|
||||
|
||||
@Test void serializesPreservesUnrelatedKeysAndPublishesAcknowledgedSnapshotsInOrder() throws Exception {
|
||||
Files.writeString(data.resolve("config.yml"), "unrelated: retained\n");
|
||||
try (var settings = new FrostNovaSettings(data, defaults())) {
|
||||
var range = settings.set(FrostNovaSettings.RADIUS, "7").toCompletableFuture();
|
||||
var cooldown = settings.set(FrostNovaSettings.COOLDOWN, "24").toCompletableFuture();
|
||||
var savedRange = range.get(5, TimeUnit.SECONDS); var savedCooldown = cooldown.get(5, TimeUnit.SECONDS);
|
||||
assertEquals(5, settings.settings().radius(), 0);
|
||||
settings.publish(savedCooldown); settings.publish(savedRange);
|
||||
assertEquals(7, settings.settings().radius(), 0);
|
||||
assertEquals(java.time.Duration.ofSeconds(24), settings.settings().cooldown());
|
||||
var yaml = (Map<?, ?>) new org.yaml.snakeyaml.Yaml().load(Files.readString(data.resolve("config.yml")));
|
||||
assertEquals("retained", yaml.get("unrelated"));
|
||||
assertEquals("7", String.valueOf(yaml.get(FrostNovaSettings.RADIUS)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void invalidFailedUnsafeAndClosedWritesRetainEffectiveState() throws Exception {
|
||||
try (var settings = new FrostNovaSettings(data, defaults())) {
|
||||
for (var entry : Map.of(
|
||||
FrostNovaSettings.COOLDOWN, "-1",
|
||||
FrostNovaSettings.RADIUS, "0",
|
||||
FrostNovaSettings.DURATION, "0",
|
||||
FrostNovaSettings.BASE, "-1",
|
||||
FrostNovaSettings.SLOWNESS, "-1").entrySet()) {
|
||||
assertThrows(IllegalArgumentException.class, () -> settings.set(entry.getKey(), entry.getValue()));
|
||||
}
|
||||
assertThrows(IllegalArgumentException.class, () -> settings.set(FrostNovaSettings.COOLDOWN, "0.0000000001"));
|
||||
}
|
||||
var fail = new java.util.concurrent.atomic.AtomicBoolean(true);
|
||||
try (var settings = new FrostNovaSettings(data, defaults(), (from, to) -> {
|
||||
if (fail.getAndSet(false)) throw new java.io.IOException("simulated");
|
||||
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
|
||||
})) {
|
||||
assertThrows(java.util.concurrent.ExecutionException.class,
|
||||
() -> settings.set(FrostNovaSettings.RADIUS, "7").toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
assertEquals("5", settings.value(FrostNovaSettings.RADIUS));
|
||||
}
|
||||
if (!System.getProperty("os.name", "").toLowerCase().contains("win")) {
|
||||
var unsafe = data.resolve("unsafe"); Files.createDirectories(unsafe);
|
||||
var outside = data.resolve("outside.yml"); Files.writeString(outside, "safe\n");
|
||||
Files.createSymbolicLink(unsafe.resolve("config.yml"), outside);
|
||||
try (var settings = new FrostNovaSettings(unsafe, defaults())) {
|
||||
assertThrows(java.util.concurrent.ExecutionException.class,
|
||||
() -> settings.set(FrostNovaSettings.DURATION, "8").toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
assertEquals("safe\n", Files.readString(outside));
|
||||
}
|
||||
}
|
||||
var closed = new FrostNovaSettings(data.resolve("closed"), defaults()); closed.close();
|
||||
assertThrows(java.util.concurrent.ExecutionException.class,
|
||||
() -> closed.set(FrostNovaSettings.BASE, "8").toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
closed.drained().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static Map<String, String> defaults() {
|
||||
var values = new LinkedHashMap<String, String>();
|
||||
for (String key : FrostNovaSettings.keys()) values.put(key, FrostNovaSettings.defaultValue(key));
|
||||
return values;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user