feat(longbow): audit native draw and arrow damage
Release / release (push) Successful in 17m13s

This commit is contained in:
dmg committed 2026-09-25 22:10:24 -04:00
1 parent f6d95ca338
commit fc90af3a62
7 files changed
+326 -29

No files matched your search

@@ -742,6 +742,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
feedbackCommand.attachEvents(preferenceEvents);
eventCapture.excludeOwnedDamage(fireball::ownsAcceptedDamage);
eventCapture.excludeOwnedDamage(frostShard::ownsAcceptedDamage);
eventCapture.excludeOwnedDamage(longbow::ownsAcceptedDamage);
eventCapture.excludeOwnedDamage(greatSword::ownsAcceptedDamage);
eventCapture.excludeOwnedDamage(guardianBond::ownsAcceptedRedirect);
eventCapture.excludeOwnedDamage(frostNova::ownsAcceptedDamage);
@@ -759,6 +760,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
abilityEngine.enableCastEventsFor("fireball");
abilityEngine.enableCastEventsFor("great_sword");
abilityEngine.enableCastEventsFor("frost_shard");
abilityEngine.enableCastEventsFor("longbow");
abilityEngine.enableCastEventsFor("mending_light");
abilityEngine.enableCastEventsFor("purify");
abilityEngine.enableCastEventsFor("guardian_bond");
@@ -70,7 +70,8 @@ public final class AbilityEngine implements Consumer<ControlInput>, AutoCloseabl
}
private void refuseCast(ControlInput input, CharacterRecord record, AbilityDefinition definition, String reason) {
if (castEvents == null || record == null || !definition.id().equals("great_sword")
if (castEvents == null || record == null
|| !(definition.id().equals("great_sword") || definition.id().equals("longbow"))
|| !eventOwnedAbilities.contains(definition.id())) return;
resolve(castEvents.begin(input, record, definition), "refused", reason);
}
@@ -58,7 +58,9 @@ public final class Longbow implements AbilityEffect, Listener, AutoCloseable {
final Settings settings;
final BigDecimal damage;
LivingEntity target;
double requested;
boolean accepted;
boolean nativeCancelled;
boolean finished;
State(Arrow arrow, AbilityExecution execution, Location origin, Settings settings, BigDecimal damage) {
this.arrow = arrow; this.execution = execution; this.origin = origin; this.settings = settings; this.damage = damage;
@@ -141,12 +143,15 @@ public final class Longbow implements AbilityEffect, Listener, AutoCloseable {
}
execution.own(state);
long rangeTicks = Math.max(1, (long) Math.ceil(shot.range() / speed));
execution.later(Duration.ofMillis(Math.multiplyExact(rangeTicks, 50)), () -> {
if (arrows.containsKey(arrow.getUniqueId())) execution.finish();
});
execution.later(shot.lifetime(), () -> {
if (arrows.containsKey(arrow.getUniqueId())) execution.finish();
});
Runnable expire = () -> {
if (arrows.containsKey(arrow.getUniqueId())) {
try { execution.resolve("expired", Map.of("arrow_id", arrow.getUniqueId().toString())); }
catch (RuntimeException ignored) { /* Auditing cannot retain expired native arrows. */ }
execution.finish();
}
};
execution.later(Duration.ofMillis(Math.multiplyExact(rangeTicks, 50)), expire);
execution.later(shot.lifetime(), expire);
}
@EventHandler(priority = EventPriority.HIGHEST)
@@ -161,18 +166,32 @@ public final class Longbow implements AbilityEffect, Listener, AutoCloseable {
var state = arrows.remove(event.getEntity().getUniqueId());
if (state == null) return;
try {
if (closed || event.isCancelled() || !state.execution.stillCurrent()
|| !(event.getHitEntity() instanceof LivingEntity target)
boolean currentSession = !closed && state.execution.stillCurrent();
if (!currentSession || event.isCancelled() || !(event.getHitEntity() instanceof LivingEntity target)
|| !inRange(state, event.getEntity().getLocation())
|| state.execution.eligible(List.of(target), 1).isEmpty()) return;
|| state.execution.eligible(List.of(target), 1).isEmpty()) {
try { state.execution.resolve(!currentSession ? "interrupted" : event.isCancelled() ? "cancelled" : "miss",
Map.of("arrow_id", state.arrow.getUniqueId().toString())); }
catch (RuntimeException ignored) { /* Auditing cannot prevent native cleanup. */ }
return;
}
double nativeDamage = state.damage.compareTo(BigDecimal.valueOf(Double.MAX_VALUE)) > 0
? Double.MAX_VALUE : state.damage.doubleValue();
if (!Double.isFinite(nativeDamage) || nativeDamage <= 0) return;
if (!Double.isFinite(nativeDamage) || nativeDamage <= 0) {
try { state.execution.resolve("miss", Map.of("arrow_id", state.arrow.getUniqueId().toString())); }
catch (RuntimeException ignored) { /* Auditing cannot prevent native cleanup. */ }
return;
}
var source = DamageSource.builder(DamageType.ARROW).withCausingEntity(state.execution.input().player())
.withDirectEntity(state.arrow).withDamageLocation(state.arrow.getLocation()).build();
state.target = target; damaging = state;
state.target = target; state.requested = nativeDamage; damaging = state;
try { state.execution.damage(target, nativeDamage, source); }
finally { if (damaging == state) damaging = null; }
try { state.execution.resolve(state.accepted ? "hit" : state.nativeCancelled ? "cancelled" : "miss",
Map.of("arrow_id", state.arrow.getUniqueId().toString(),
"target_entity_id", target.getUniqueId().toString(),
"impact_location", locationData(state.arrow.getLocation()))); }
catch (RuntimeException ignored) { /* Audit capture cannot change native damage. */ }
} finally {
state.close(); state.execution.finish();
}
@@ -184,18 +203,38 @@ public final class Longbow implements AbilityEffect, Listener, AutoCloseable {
&& current.distanceSquared(state.origin) <= state.settings.range() * state.settings.range();
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
@EventHandler(priority = EventPriority.MONITOR)
public void acceptedDamage(EntityDamageEvent event) {
var state = damaging;
if (state == null || state.accepted || event.getEntity() != state.target || event.getFinalDamage() <= 0
|| !Double.isFinite(event.getFinalDamage())) return;
if (state == null || state.accepted || event.getEntity() != state.target) return;
var direct = event.getDamageSource().getDirectEntity();
if (direct != state.arrow && (!(event instanceof EntityDamageByEntityEvent byEntity)
|| byEntity.getDamager() != state.arrow)) return;
if (event.isCancelled()) { state.nativeCancelled = true; return; }
if (event.getFinalDamage() <= 0 || !Double.isFinite(event.getFinalDamage())) return;
state.accepted = true;
try { state.execution.acceptedDamage(state.target, state.requested, event.getFinalDamage(), state.arrow,
Map.of("arrow_id", state.arrow.getUniqueId().toString(),
"impact_location", locationData(state.arrow.getLocation()))); }
catch (RuntimeException ignored) { /* Audit capture cannot change an accepted contribution. */ }
state.execution.report(AbilityReport.Type.DAMAGE, event.getEntity(), BigDecimal.valueOf(event.getFinalDamage()));
}
public boolean ownsAcceptedDamage(EntityDamageEvent event) {
var state = damaging;
if (state == null || event.getEntity() != state.target) return false;
var direct = event.getDamageSource().getDirectEntity();
return direct == state.arrow || event instanceof EntityDamageByEntityEvent by
&& by.getDamager() == state.arrow;
}
private static Map<String, Object> locationData(Location location) {
if (location == null || location.getWorld() == null) return Map.of("status", "unavailable");
return Map.of("world_id", location.getWorld().getUID().toString(),
"world_name", location.getWorld().getName(), "x", location.getX(), "y", location.getY(),
"z", location.getZ(), "captured_at", java.time.Instant.now().toString());
}
private static Settings from(AbilityDefinition definition) {
var p = definition.parameters();
return new Settings(p.get("base-damage").toBigIntegerExact(), definition.cooldown(),
@@ -19,11 +19,16 @@ import org.bukkit.entity.Entity;
public final class AbilityCastEventBridge {
public record Cast(UUID actionId, EventInput.Context context, String abilityId, UUID targetId,
String targetType, Map<String, Object> targetLocation, Instant requestedAt,
float attackCharge, UUID executionId) {
float attackCharge, int heldTicks, UUID executionId) {
public Cast(UUID actionId, EventInput.Context context, String abilityId, UUID targetId,
String targetType, Map<String, Object> targetLocation, Instant requestedAt,
float attackCharge, int heldTicks) {
this(actionId, context, abilityId, targetId, targetType, targetLocation, requestedAt,
attackCharge, heldTicks, UUID.randomUUID());
}
public Cast(UUID actionId, EventInput.Context context, String abilityId, UUID targetId,
String targetType, Map<String, Object> targetLocation, Instant requestedAt, float attackCharge) {
this(actionId, context, abilityId, targetId, targetType, targetLocation, requestedAt,
attackCharge, UUID.randomUUID());
this(actionId, context, abilityId, targetId, targetType, targetLocation, requestedAt, attackCharge, 0);
}
public Cast(UUID actionId, EventInput.Context context, String abilityId, UUID targetId,
String targetType, Map<String, Object> targetLocation, Instant requestedAt) {
@@ -50,7 +55,7 @@ public final class AbilityCastEventBridge {
definition.id(), target == null ? null : target.getUniqueId(),
target == null ? null : target instanceof org.bukkit.entity.Player ? "PLAYER" : target.getType().name(),
targetAtRequest == null ? Map.of() : locationData(targetAtRequest),
clock.instant(), input.attackStrength());
clock.instant(), input.attackStrength(), input.heldTicks());
emit(cast, "action.observed", "observed", Map.of("action_kind", "ability_cast"));
return cast;
} catch (RuntimeException ignored) {
@@ -71,6 +76,11 @@ public final class AbilityCastEventBridge {
data.put("captured_settings", settings);
data.put("settings_scope", "definition_at_request");
if (cast.abilityId().equals("great_sword")) data.put("captured_charge", Float.toString(cast.attackCharge()));
if (cast.abilityId().equals("longbow")) {
data.put("draw_ticks", cast.heldTicks());
data.put("draw_power", games.dmg.fantasystick.ability.Longbow.power(cast.heldTicks(),
definition.parameters().get("full-draw-ticks").intValueExact()).stripTrailingZeros().toPlainString());
}
for (Stat stat : definition.requirements().keySet())
data.put("captured_" + stat.name().toLowerCase(java.util.Locale.ROOT), saved.stats().get(stat).toString());
emit(cast, "ability.cast", "accepted", data);
@@ -260,7 +270,8 @@ public final class AbilityCastEventBridge {
data.put("action_kind", "ability_cast");
data.put("ability_id", cast.abilityId());
data.put("outcome", outcome);
if (cast.abilityId().equals("frost_shard")) data.put("execution_id", cast.executionId().toString());
if (cast.abilityId().equals("frost_shard") || cast.abilityId().equals("longbow"))
data.put("execution_id", cast.executionId().toString());
if (cast.targetId() != null) {
data.put("target_entity_id", cast.targetId().toString());
data.put("target_type", cast.targetType());
@@ -77,11 +77,12 @@ public final class LongbowSettings implements AutoCloseable {
public Longbow.Settings settings() { return parse(effectiveValues); }
/** Publish only after the caller returns the durable acknowledgment to the server thread. */
public synchronized void publish(Update update) {
public synchronized boolean publish(Update update) {
Objects.requireNonNull(update);
if (update.sequence() <= publishedSequence) return;
if (update.sequence() <= publishedSequence) return false;
parse(update.values());
effectiveValues = update.values(); publishedSequence = update.sequence();
return true;
}
public CompletionStage<Update> set(String key, String value) {
@@ -1287,8 +1287,11 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
private void longbowConfiguration(CommandSender sender, String[] args) {
String key = args[1];
var actor = abilityConfigEvents == null ? null : abilityConfigEvents.capture(sender);
String before = longbowSettings.value(key);
if (args.length == 2) {
sender.sendMessage(key + "=" + longbowSettings.value(key) + " (applies to future Longbow shots only)");
if (abilityConfigEvents != null) abilityConfigEvents.read(actor, "longbow", key, before);
sender.sendMessage(key + "=" + before + " (applies to future Longbow shots only)");
return;
}
java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.LongbowSettings.Update> operation;
@@ -1302,16 +1305,18 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
try {
nextTick.accept(() -> {
if (closed) return;
if (failure == null) {
longbow.configure(saved.settings());
boolean applied = failure == null && longbowSettings.publish(saved);
if (applied) {
longbow.configure(longbowSettings.settings());
abilities.replace(longbow.definition());
longbowSettings.publish(saved);
if (abilityConfigEvents != null) abilityConfigEvents.changed(actor, "longbow", key, before, saved.value());
}
if (!sender.hasPermission(PERMISSION)
|| sender instanceof org.bukkit.entity.Player player && !player.isOnline()) return;
sender.sendMessage(failure == null
? "Saved " + key + "=" + saved.value() + " for future Longbow shots; active shots and deadlines are unchanged."
: "Longbow configuration save failed; the effective setting is unchanged.");
sender.sendMessage(failure != null
? "Longbow configuration save failed; the effective setting is unchanged."
: applied ? "Saved " + key + "=" + saved.value() + " for future Longbow shots; active shots and deadlines are unchanged."
: "Saved request was superseded; effective " + key + "=" + longbowSettings.value(key) + ".");
});
} catch (RuntimeException rejected) { report(null, "config-response", rejected); }
});