This commit is contained in:
1 parent
e16570cb35
commit
1dcc7cfae8
34 files changed
+1091
-25
No files matched your search
@@ -39,6 +39,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private games.dmg.fantasystick.party.CharacterPartyDirectory characterParties;
|
||||
private games.dmg.fantasystick.party.PartyRegistrarDirectory partyRegistrars;
|
||||
private games.dmg.fantasystick.party.PartyRegistrarController partyRegistrarController;
|
||||
private games.dmg.fantasystick.training.TrainingDummyDirectory trainingDummies;
|
||||
private games.dmg.fantasystick.training.TrainingDummyController trainingDummyController;
|
||||
private games.dmg.fantasystick.party.PartyManagement partyManagement;
|
||||
private games.dmg.fantasystick.party.PartyRegistrarMenus partyRegistrarMenus;
|
||||
private games.dmg.fantasystick.party.PartyEvents partyEvents;
|
||||
@@ -284,9 +286,11 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
new games.dmg.fantasystick.persistence.YamlPartyRepository(getDataFolder().toPath()), partySettings::maximum);
|
||||
partyRegistrars = new games.dmg.fantasystick.party.PartyRegistrarDirectory(
|
||||
new games.dmg.fantasystick.persistence.YamlPartyRegistrarRepository(getDataFolder().toPath()));
|
||||
trainingDummies = new games.dmg.fantasystick.training.TrainingDummyDirectory(
|
||||
new games.dmg.fantasystick.persistence.YamlTrainingDummyRepository(getDataFolder().toPath()));
|
||||
armorers=new games.dmg.fantasystick.shop.FantasyArmorerDirectory(new games.dmg.fantasystick.persistence.YamlFantasyArmorerRepository(getDataFolder().toPath()));
|
||||
} catch (java.io.IOException invalidPartyState) {
|
||||
throw new java.io.UncheckedIOException("Persistent party state could not be loaded", invalidPartyState);
|
||||
} catch (java.io.IOException invalidManagedState) {
|
||||
throw new java.io.UncheckedIOException("Persistent party, shop or training state could not be loaded", invalidManagedState);
|
||||
}
|
||||
characterParties.suspend();
|
||||
sheetResourcePack = new games.dmg.fantasystick.presentation.SheetResourcePack(sheetResourcePackSettings,
|
||||
@@ -296,6 +300,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
sessions.attachSwitchDelay(switchDelaySettings::delay);
|
||||
sessions.attachRoleplayDisabled(roleplaySettings::disabled);
|
||||
combatFeedback = new games.dmg.fantasystick.presentation.CombatFeedback(feedbackPreferences, sessions);
|
||||
trainingDummyController = new games.dmg.fantasystick.training.TrainingDummyController(this, trainingDummies);
|
||||
parties = new games.dmg.fantasystick.party.PartyRoster(characterParties, sessions, partySettings::maximum);
|
||||
characterParties.attachEnded(former -> nextTick.accept(() -> {
|
||||
String message = "Party ended: " + former.displayName();
|
||||
@@ -470,7 +475,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
abilityScheduler::later, (size, title) -> getServer().createInventory(null, size, title),
|
||||
problem -> getLogger().log(Level.WARNING, "Admin revival failed", problem));
|
||||
abilityEngine = new games.dmg.fantasystick.ability.AbilityEngine(abilityRegistry, characters, sessions, parties,
|
||||
Clock.systemUTC(), nextTick, abilityScheduler, report -> { }, combatFeedback,
|
||||
Clock.systemUTC(), nextTick, abilityScheduler, report -> { }, combatFeedback, trainingDummyController,
|
||||
problem -> getLogger().log(Level.WARNING, "Ability engine failed for character " + problem.character()
|
||||
+ "; ability " + problem.ability(), problem.cause()));
|
||||
abilityEngine.install(this);
|
||||
@@ -481,7 +486,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
var player = getServer().getPlayer(id);
|
||||
return net.kyori.adventure.text.Component.text(name != null ? name : player == null ? id.toString() : player.getName());
|
||||
}, abilityRegistry, abilityEngine, passiveRegistry, passiveEngine);
|
||||
var localBasicAttack = new games.dmg.fantasystick.combat.BasicAttack(sessions, Clock.systemUTC(), combatFeedback);
|
||||
var localBasicAttack = new games.dmg.fantasystick.combat.BasicAttack(
|
||||
sessions, Clock.systemUTC(), combatFeedback, trainingDummyController);
|
||||
basicAttack = localBasicAttack;
|
||||
sessionEvents = new EquipmentSessionEvents(sessions, nextTick, diagnostics, input -> {
|
||||
books.accept(input);
|
||||
@@ -533,6 +539,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
admin.attachPartySettings(partySettings);
|
||||
admin.attachPartyEconomySettings(partyEconomySettings);
|
||||
admin.attachPartyRegistrars(partyRegistrars, partyRegistrarController);
|
||||
admin.attachTrainingDummies(trainingDummies, trainingDummyController);
|
||||
admin.attachGearSettings(gearSettings);
|
||||
admin.attachArmorers(armorers,armorerController);
|
||||
admin.attachArmorMarket(armorMarket);
|
||||
@@ -561,10 +568,12 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
getServer().getPluginManager().registerEvents(partyEvents, this);
|
||||
getServer().getPluginManager().registerEvents(partyCombat, this);
|
||||
getServer().getPluginManager().registerEvents(partyRegistrarController, this);
|
||||
getServer().getPluginManager().registerEvents(trainingDummyController, this);
|
||||
getServer().getPluginManager().registerEvents(partyRegistrarMenus, this);
|
||||
getServer().getPluginManager().registerEvents(armorerController,this);
|
||||
getServer().getPluginManager().registerEvents(armorShopMenus,this);
|
||||
partyRegistrarController.install();
|
||||
trainingDummyController.install();
|
||||
armorerController.install();
|
||||
var localArmorMarket=armorMarket;
|
||||
armorMarketPulse=getServer().getScheduler().runTaskTimer(this,()->{if(lifetime!=generation)return;
|
||||
@@ -639,6 +648,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
var closingCharacterParties = characterParties; characterParties = null;
|
||||
var closingPartyRegistrars = partyRegistrars; partyRegistrars = null;
|
||||
var closingPartyRegistrarController = partyRegistrarController; partyRegistrarController = null;
|
||||
var closingTrainingDummies = trainingDummies; trainingDummies = null;
|
||||
var closingTrainingDummyController = trainingDummyController; trainingDummyController = null;
|
||||
var closingPartyRegistrarMenus = partyRegistrarMenus; partyRegistrarMenus = null;
|
||||
var closingPartyManagement = partyManagement; partyManagement = null;
|
||||
var closingArmorers=armorers;armorers=null;var closingArmorerController=armorerController;armorerController=null;
|
||||
@@ -775,6 +786,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
: closingCharacterParties.drained().toCompletableFuture(),
|
||||
closingPartyRegistrars == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
|
||||
: closingPartyRegistrars.drained().toCompletableFuture(),
|
||||
closingTrainingDummies == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
|
||||
: closingTrainingDummies.drained().toCompletableFuture(),
|
||||
closingPartyManagement == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
|
||||
: closingPartyManagement.drained().toCompletableFuture(),
|
||||
closingArmorers==null?java.util.concurrent.CompletableFuture.completedFuture(null):closingArmorers.drained().toCompletableFuture(),
|
||||
@@ -867,6 +880,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
if (closingPartyManagement != null) cleanup("party management", closingPartyManagement::close);
|
||||
if (closingPartyRegistrarController != null) cleanup("party registrar entities", closingPartyRegistrarController::close);
|
||||
if (closingPartyRegistrars != null) cleanup("party registrars", closingPartyRegistrars::close);
|
||||
if (closingTrainingDummyController != null) cleanup("training dummy entities", closingTrainingDummyController::close);
|
||||
if (closingTrainingDummies != null) cleanup("training dummies", closingTrainingDummies::close);
|
||||
if(closingArmorMarketPulse!=null)cleanup("armor market schedule",closingArmorMarketPulse::cancel);
|
||||
if(closingArmorMenuPulse!=null)cleanup("armor menu schedule",closingArmorMenuPulse::cancel);
|
||||
if(closingArmorShopMenus!=null)cleanup("armor shop menus",closingArmorShopMenus::close);
|
||||
@@ -883,6 +898,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
unregister(closingPartyEvents);
|
||||
unregister(closingPartyCombat);
|
||||
unregister(closingPartyRegistrarController);
|
||||
unregister(closingTrainingDummyController);
|
||||
unregister(closingPartyRegistrarMenus);
|
||||
unregister(closingArmorerController);unregister(closingArmorShopMenus);
|
||||
unregister(closingCombatExperience);
|
||||
|
||||
@@ -40,6 +40,7 @@ public final class AbilityEngine implements Consumer<ControlInput>, AutoCloseabl
|
||||
private final AbilityScheduler scheduler;
|
||||
private final Consumer<AbilityReport> reports;
|
||||
private final AbilityFeedback feedback;
|
||||
private final games.dmg.fantasystick.training.TrainingDamage trainingDamage;
|
||||
private final Consumer<Failure> failures;
|
||||
private final Map<Key, Object> pending = new HashMap<>();
|
||||
private final Map<Key, Long> generations = new HashMap<>();
|
||||
@@ -51,17 +52,27 @@ public final class AbilityEngine implements Consumer<ControlInput>, AutoCloseabl
|
||||
PartyRoster parties, Clock clock, Consumer<Runnable> nextTick, AbilityScheduler scheduler,
|
||||
Consumer<AbilityReport> reports, Consumer<Failure> failures) {
|
||||
this(registry, characters, sessions, parties, clock, nextTick, scheduler, reports,
|
||||
(definition, input, type, target, amount) -> { }, failures);
|
||||
(definition, input, type, target, amount) -> { },
|
||||
games.dmg.fantasystick.training.TrainingDamage.passthrough(), failures);
|
||||
}
|
||||
|
||||
public AbilityEngine(AbilityRegistry registry, CharacterStorage characters, EquipmentSessions sessions,
|
||||
PartyRoster parties, Clock clock, Consumer<Runnable> nextTick, AbilityScheduler scheduler,
|
||||
Consumer<AbilityReport> reports, AbilityFeedback feedback, Consumer<Failure> failures) {
|
||||
this(registry, characters, sessions, parties, clock, nextTick, scheduler, reports, feedback,
|
||||
games.dmg.fantasystick.training.TrainingDamage.passthrough(), failures);
|
||||
}
|
||||
|
||||
public AbilityEngine(AbilityRegistry registry, CharacterStorage characters, EquipmentSessions sessions,
|
||||
PartyRoster parties, Clock clock, Consumer<Runnable> nextTick, AbilityScheduler scheduler,
|
||||
Consumer<AbilityReport> reports, AbilityFeedback feedback,
|
||||
games.dmg.fantasystick.training.TrainingDamage trainingDamage, Consumer<Failure> failures) {
|
||||
this.registry = Objects.requireNonNull(registry); this.characters = Objects.requireNonNull(characters);
|
||||
this.sessions = Objects.requireNonNull(sessions); this.parties = Objects.requireNonNull(parties);
|
||||
this.clock = Objects.requireNonNull(clock); this.nextTick = Objects.requireNonNull(nextTick);
|
||||
this.scheduler = Objects.requireNonNull(scheduler); this.reports = Objects.requireNonNull(reports);
|
||||
this.feedback = Objects.requireNonNull(feedback); this.failures = Objects.requireNonNull(failures);
|
||||
this.feedback = Objects.requireNonNull(feedback); this.trainingDamage = Objects.requireNonNull(trainingDamage);
|
||||
this.failures = Objects.requireNonNull(failures);
|
||||
}
|
||||
|
||||
public void install(org.bukkit.plugin.Plugin plugin) {
|
||||
@@ -334,6 +345,13 @@ public final class AbilityEngine implements Consumer<ControlInput>, AutoCloseabl
|
||||
}
|
||||
owned.add(resource);
|
||||
}
|
||||
@Override public boolean trainingDummy(Entity target) { return trainingDamage.target(Objects.requireNonNull(target)); }
|
||||
@Override public void damage(org.bukkit.entity.LivingEntity target, double amount,
|
||||
org.bukkit.damage.DamageSource source) {
|
||||
Objects.requireNonNull(target); Objects.requireNonNull(source);
|
||||
var measured = trainingDamage.apply(input.player(), target, () -> target.damage(amount, source));
|
||||
measured.ifPresent(value -> report(AbilityReport.Type.DAMAGE, target, value));
|
||||
}
|
||||
@Override public void report(AbilityReport.Type type, Entity target, java.math.BigDecimal amount) {
|
||||
if (!stillCurrent() || definition.targetPolicy() == AbilityDefinition.TargetPolicy.EXCEPTIONAL_NONCOMBAT
|
||||
|| definition.targetPolicy() == AbilityDefinition.TargetPolicy.EXCEPTIONAL_NONCOMBAT_SELECTION
|
||||
|
||||
@@ -5,7 +5,9 @@ import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.bukkit.damage.DamageSource;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
|
||||
/** Bounded owned runtime supplied by the shared engine after durable cast authorization. */
|
||||
public interface AbilityExecution extends AutoCloseable {
|
||||
@@ -16,6 +18,8 @@ public interface AbilityExecution extends AutoCloseable {
|
||||
List<Entity> eligible(Collection<? extends Entity> candidates, int maximum);
|
||||
AbilityScheduler.Task later(Duration delay, Runnable action);
|
||||
void own(AutoCloseable resource);
|
||||
boolean trainingDummy(Entity target);
|
||||
void damage(LivingEntity target, double amount, DamageSource source);
|
||||
void report(AbilityReport.Type type, Entity target, BigDecimal amount);
|
||||
void finish();
|
||||
@Override void close();
|
||||
|
||||
@@ -117,7 +117,7 @@ public final class ChainLightning implements AbilityEffect, Listener, AutoClosea
|
||||
var source = DamageSource.builder(DamageType.LIGHTNING_BOLT).withCausingEntity(caster)
|
||||
.withDirectEntity(caster).withDamageLocation(origin).build();
|
||||
var attempt = new Attempt(execution, target); damaging = attempt;
|
||||
try { target.damage(amount, source); }
|
||||
try { execution.damage(target, amount, source); }
|
||||
finally { if (damaging == attempt) damaging = null; }
|
||||
}
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ public final class Fireball implements AbilityEffect, Listener, AutoCloseable {
|
||||
.withDirectEntity(state.projectile).withDamageLocation(state.projectile.getLocation()).build();
|
||||
state.target = target;
|
||||
damaging = state;
|
||||
try { target.damage(nativeDamage, source); }
|
||||
try { state.execution.damage(target, nativeDamage, source); }
|
||||
finally { if (damaging == state) damaging = null; }
|
||||
} finally {
|
||||
state.execution.finish();
|
||||
|
||||
@@ -135,7 +135,7 @@ public final class FrostNova implements AbilityEffect, Listener, AutoCloseable {
|
||||
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); }
|
||||
try { execution.damage(target, amount, sourceDamage); }
|
||||
finally { if (damaging == attempt) damaging = null; }
|
||||
affected++;
|
||||
if (!attempt.accepted || !execution.stillCurrent() || !eligible(execution, target, origin, captured.radius())) continue;
|
||||
|
||||
@@ -175,7 +175,7 @@ public final class FrostShard implements AbilityEffect, Listener, AutoCloseable
|
||||
var source = DamageSource.builder(DamageType.FREEZE).withCausingEntity(state.execution.input().player())
|
||||
.withDirectEntity(state.projectile).withDamageLocation(state.projectile.getLocation()).build();
|
||||
state.target = target; damaging = state;
|
||||
try { target.damage(nativeDamage, source); }
|
||||
try { state.execution.damage(target, nativeDamage, source); }
|
||||
finally { if (damaging == state) damaging = null; }
|
||||
if (state.accepted && state.execution.stillCurrent()) {
|
||||
int ticks = Math.toIntExact(Math.max(1,
|
||||
|
||||
@@ -93,7 +93,7 @@ public final class GreatSword implements AbilityEffect, Listener, AutoCloseable
|
||||
.withDirectEntity(player).build();
|
||||
var attempt = new Attempt(execution, target);
|
||||
damaging = attempt;
|
||||
try { target.damage(nativeDamage, source); }
|
||||
try { execution.damage(target, nativeDamage, source); }
|
||||
finally { if (damaging == attempt) damaging = null; }
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ public final class Hex implements AbilityEffect,AutoCloseable{
|
||||
AbilityDefinition.TargetPolicy.HOSTILE,this);}
|
||||
@Override public boolean accepts(ControlInput input){return !closed&&input.target() instanceof LivingEntity target&&inRange(input,target,settings.range());}
|
||||
@Override public void activate(AbilityExecution execution){if(closed||!execution.stillCurrent()||!(execution.input().target() instanceof LivingEntity target))return;
|
||||
var current=from(execution.definition());if(!inRange(execution.input(),target,current.range())){execution.finish();return;}
|
||||
var current=from(execution.definition());if(!inRange(execution.input(),target,current.range())||execution.trainingDummy(target)){execution.finish();return;}
|
||||
var state=new State(execution,target,mitigation.grant(execution,target,current.reductionPercent()));var previous=hexes.put(target.getUniqueId(),state);
|
||||
if(previous!=null)previous.execution.finish();execution.own(state);execution.later(current.duration(),execution::finish);}
|
||||
private static boolean inRange(ControlInput input,LivingEntity target,double range){try{Location source=input.player().getLocation(),destination=target.getLocation();
|
||||
|
||||
@@ -171,7 +171,7 @@ public final class Longbow implements AbilityEffect, Listener, AutoCloseable {
|
||||
var source = DamageSource.builder(DamageType.ARROW).withCausingEntity(state.execution.input().player())
|
||||
.withDirectEntity(state.arrow).withDamageLocation(state.arrow.getLocation()).build();
|
||||
state.target = target; damaging = state;
|
||||
try { target.damage(nativeDamage, source); }
|
||||
try { state.execution.damage(target, nativeDamage, source); }
|
||||
finally { if (damaging == state) damaging = null; }
|
||||
} finally {
|
||||
state.close(); state.execution.finish();
|
||||
|
||||
@@ -46,7 +46,7 @@ public final class Meteor implements AbilityEffect, Listener, AutoCloseable {
|
||||
Warning(AbilityExecution execution,Ground ground,Settings captured){this.execution=execution;source=execution.input().player();this.ground=ground;this.captured=captured;intelligence=execution.character().stats().get(Stat.INT);maximumTicks=(int)Math.max(1,(captured.warning().toNanos()+49_999_999L)/50_000_000L);}
|
||||
void start(){warnings.put(execution,this);execution.own(this);warningVisual();execution.later(Duration.ofMillis(50),this::step);}
|
||||
void step(){if(closed||impacted)return;if(!execution.stillCurrent()){execution.finish();return;}elapsed++;if(elapsed>=maximumTicks){impact();execution.finish();return;}warningVisual();execution.later(Duration.ofMillis(50),this::step);}
|
||||
void impact(){if(closed||impacted)return;impacted=true;if(!groundCurrent()||!execution.stillCurrent())return;impactVisual();double amount=finite(damage(captured.baseDamage(),intelligence));int affected=0;for(var target:candidates(ground.origin(),captured.radius(),captured.verticalRange())){if(affected==64||!execution.stillCurrent())break;if(!eligible(execution,target,ground.origin(),captured.radius(),captured.verticalRange()))continue;var sourceDamage=DamageSource.builder(DamageType.MAGIC).withCausingEntity(source).withDirectEntity(source).withDamageLocation(ground.origin()).build();var attempt=new Attempt(execution,target);damaging=attempt;try{target.damage(amount,sourceDamage);}finally{if(damaging==attempt)damaging=null;}affected++;}}
|
||||
void impact(){if(closed||impacted)return;impacted=true;if(!groundCurrent()||!execution.stillCurrent())return;impactVisual();double amount=finite(damage(captured.baseDamage(),intelligence));int affected=0;for(var target:candidates(ground.origin(),captured.radius(),captured.verticalRange())){if(affected==64||!execution.stillCurrent())break;if(!eligible(execution,target,ground.origin(),captured.radius(),captured.verticalRange()))continue;var sourceDamage=DamageSource.builder(DamageType.MAGIC).withCausingEntity(source).withDirectEntity(source).withDamageLocation(ground.origin()).build();var attempt=new Attempt(execution,target);damaging=attempt;try{execution.damage(target,amount,sourceDamage);}finally{if(damaging==attempt)damaging=null;}affected++;}}
|
||||
boolean groundCurrent(){try{return ground.origin().getWorld()!=null&&ground.block().getWorld()==ground.origin().getWorld()&&ground.block().getType().isSolid();}catch(RuntimeException invalid){return false;}}
|
||||
void warningVisual(){try{var dust=new Particle.DustOptions(Color.fromRGB(255,90,20),1.6f);ground.origin().getWorld().spawnParticle(Particle.DUST,ground.origin().clone().add(0,.15,0),24,captured.radius()/2,.05,captured.radius()/2,0,dust);}catch(RuntimeException ignored){}}
|
||||
void impactVisual(){try{var world=ground.origin().getWorld();world.spawnParticle(Particle.EXPLOSION_EMITTER,ground.origin(),2,0,0,0,0);world.spawnParticle(Particle.FLAME,ground.origin(),48,captured.radius()/2,1,captured.radius()/2,.04);world.playSound(ground.origin(),Sound.ENTITY_GENERIC_EXPLODE,1f,.7f);}catch(RuntimeException ignored){}}
|
||||
|
||||
@@ -91,7 +91,7 @@ public final class ShieldBash implements AbilityEffect, Listener, AutoCloseable
|
||||
if (!Double.isFinite(amount) || amount <= 0) { execution.finish(); return; }
|
||||
var source = DamageSource.builder(DamageType.PLAYER_ATTACK).withCausingEntity(player).withDirectEntity(player).build();
|
||||
var attempt = new Attempt(execution, target, current); damaging = attempt;
|
||||
try { target.damage(amount, source); }
|
||||
try { execution.damage(target, amount, source); }
|
||||
finally { if (damaging == attempt) damaging = null; execution.finish(); }
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ public final class BasicAttack implements Consumer<ControlInput>, Listener, Auto
|
||||
private final EquipmentSessions sessions;
|
||||
private final Clock clock;
|
||||
private final CombatFeedback feedback;
|
||||
private final games.dmg.fantasystick.training.TrainingDamage trainingDamage;
|
||||
private final Map<UUID, Instant> readyAt = new HashMap<>();
|
||||
private Pending pending;
|
||||
private boolean closed;
|
||||
@@ -49,9 +50,15 @@ public final class BasicAttack implements Consumer<ControlInput>, Listener, Auto
|
||||
}
|
||||
|
||||
public BasicAttack(EquipmentSessions sessions, Clock clock, CombatFeedback feedback) {
|
||||
this(sessions, clock, feedback, games.dmg.fantasystick.training.TrainingDamage.passthrough());
|
||||
}
|
||||
|
||||
public BasicAttack(EquipmentSessions sessions, Clock clock, CombatFeedback feedback,
|
||||
games.dmg.fantasystick.training.TrainingDamage trainingDamage) {
|
||||
this.sessions = Objects.requireNonNull(sessions);
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.feedback = feedback;
|
||||
this.trainingDamage = Objects.requireNonNull(trainingDamage);
|
||||
}
|
||||
|
||||
@Override public void accept(ControlInput input) {
|
||||
@@ -68,7 +75,11 @@ public final class BasicAttack implements Consumer<ControlInput>, Listener, Auto
|
||||
var attempt = new Pending(input, target, now);
|
||||
pending = attempt;
|
||||
try {
|
||||
target.damage(nativeDamage, input.player());
|
||||
var measured = trainingDamage.apply(input.player(), target, () -> target.damage(nativeDamage, input.player()));
|
||||
measured.ifPresent(amount -> {
|
||||
attempt.accepted = true;
|
||||
if (feedback != null) feedback.report("Basic Attack", input.player(), AbilityReport.Type.DAMAGE, target, amount);
|
||||
});
|
||||
} finally {
|
||||
if (pending == attempt) pending = null;
|
||||
if (attempt.accepted) readyAt.put(input.session().character(), attempt.attackedAt.plus(CADENCE));
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import games.dmg.fantasystick.training.TrainingDummy;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||
|
||||
/** Atomic desired-state adapter for administrator-managed training dummies. */
|
||||
public final class YamlTrainingDummyRepository {
|
||||
private final Path file;
|
||||
|
||||
public YamlTrainingDummyRepository(Path data) {
|
||||
file = data.toAbsolutePath().resolve("training-dummies.yml");
|
||||
}
|
||||
|
||||
public List<TrainingDummy> load() throws IOException {
|
||||
if (Files.notExists(file)) return List.of();
|
||||
try {
|
||||
Object decoded = yaml().load(Files.readString(file, StandardCharsets.UTF_8));
|
||||
if (!(decoded instanceof Map<?, ?> root) || number(root.get("schema-version")) != 1) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
var result = new ArrayList<TrainingDummy>();
|
||||
for (Object value : list(root.get("dummies"))) {
|
||||
var row = map(value);
|
||||
result.add(new TrainingDummy(UUID.fromString(text(row.get("dummy-id"))), text(row.get("name")),
|
||||
UUID.fromString(text(row.get("world"))), decimal(row.get("x")), decimal(row.get("y")),
|
||||
decimal(row.get("z")), (float) decimal(row.get("yaw")), (float) decimal(row.get("pitch"))));
|
||||
}
|
||||
validate(result); return List.copyOf(result);
|
||||
} catch (RuntimeException invalid) {
|
||||
throw new IOException("Invalid training dummy file", invalid);
|
||||
}
|
||||
}
|
||||
|
||||
public void save(List<TrainingDummy> dummies) throws IOException {
|
||||
validate(dummies);
|
||||
Map<String, Object> root = new LinkedHashMap<>(); root.put("schema-version", 1);
|
||||
root.put("dummies", dummies.stream().sorted(Comparator.comparing(TrainingDummy::id)).map(value -> {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("dummy-id", value.id().toString()); row.put("name", value.name());
|
||||
row.put("world", value.world().toString()); row.put("x", Double.toString(value.x()));
|
||||
row.put("y", Double.toString(value.y())); row.put("z", Double.toString(value.z()));
|
||||
row.put("yaw", Float.toString(value.yaw())); row.put("pitch", Float.toString(value.pitch())); return row;
|
||||
}).toList());
|
||||
Files.createDirectories(file.getParent());
|
||||
Path temporary = Files.createTempFile(file.getParent(), "training-dummies-", ".tmp");
|
||||
try {
|
||||
byte[] bytes = yaml().dump(root).getBytes(StandardCharsets.UTF_8);
|
||||
try (var output = java.nio.channels.FileChannel.open(temporary, StandardOpenOption.WRITE)) {
|
||||
var buffer = java.nio.ByteBuffer.wrap(bytes); while (buffer.hasRemaining()) output.write(buffer); output.force(true);
|
||||
}
|
||||
try { Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||
catch (AtomicMoveNotSupportedException unsupported) {
|
||||
throw new IOException("Atomic training dummy persistence is unavailable", unsupported);
|
||||
}
|
||||
DurableFiles.forceDirectory(file.getParent());
|
||||
} finally { Files.deleteIfExists(temporary); }
|
||||
}
|
||||
|
||||
private static void validate(List<TrainingDummy> values) {
|
||||
var ids = new HashSet<UUID>();
|
||||
if (values.stream().anyMatch(value -> !ids.add(value.id()))) {
|
||||
throw new IllegalArgumentException("Duplicate training dummy identity");
|
||||
}
|
||||
}
|
||||
private static Yaml yaml() { var options = new LoaderOptions(); options.setAllowDuplicateKeys(false);
|
||||
options.setMaxAliasesForCollections(0); options.setCodePointLimit(1_048_576);
|
||||
return new Yaml(new SafeConstructor(options)); }
|
||||
private static Map<?, ?> map(Object value) { if (value instanceof Map<?, ?> result) return result; throw new IllegalArgumentException(); }
|
||||
private static List<?> list(Object value) { if (value instanceof List<?> result) return result; throw new IllegalArgumentException(); }
|
||||
private static String text(Object value) { if (value instanceof String result) return result; throw new IllegalArgumentException(); }
|
||||
private static int number(Object value) { return Integer.parseInt(value.toString()); }
|
||||
private static double decimal(Object value) { return Double.parseDouble(text(value)); }
|
||||
}
|
||||
@@ -80,6 +80,8 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
private games.dmg.fantasystick.passive.PassiveRegistry passiveRegistry;
|
||||
private games.dmg.fantasystick.party.PartyRegistrarDirectory partyRegistrars;
|
||||
private games.dmg.fantasystick.party.PartyRegistrarController partyRegistrarController;
|
||||
private games.dmg.fantasystick.training.TrainingDummyDirectory trainingDummies;
|
||||
private games.dmg.fantasystick.training.TrainingDummyController trainingDummyController;
|
||||
private games.dmg.fantasystick.shop.FantasyArmorerDirectory armorers;
|
||||
private games.dmg.fantasystick.shop.FantasyArmorerController armorerController;
|
||||
private games.dmg.fantasystick.shop.ArmorMarket armorMarket;
|
||||
@@ -365,6 +367,12 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
partyRegistrars=Objects.requireNonNull(directory); partyRegistrarController=Objects.requireNonNull(controller);
|
||||
}
|
||||
|
||||
public void attachTrainingDummies(games.dmg.fantasystick.training.TrainingDummyDirectory directory,
|
||||
games.dmg.fantasystick.training.TrainingDummyController controller) {
|
||||
if (closed || trainingDummies != null) throw new IllegalStateException("Training dummies already attached or command closed");
|
||||
trainingDummies = Objects.requireNonNull(directory); trainingDummyController = Objects.requireNonNull(controller);
|
||||
}
|
||||
|
||||
public void attachArmorers(games.dmg.fantasystick.shop.FantasyArmorerDirectory directory,games.dmg.fantasystick.shop.FantasyArmorerController controller){if(closed||armorers!=null)throw new IllegalStateException("Armorers already attached or command closed");armorers=Objects.requireNonNull(directory);armorerController=Objects.requireNonNull(controller);}
|
||||
public void attachArmorMarket(games.dmg.fantasystick.shop.ArmorMarket market){if(closed||armorMarket!=null)throw new IllegalStateException("Armor market already attached or command closed");armorMarket=Objects.requireNonNull(market);}
|
||||
|
||||
@@ -375,6 +383,9 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
return true;
|
||||
}
|
||||
if(args.length>0&&args[0].equals("shop")){shop(sender,args);return true;}
|
||||
if (args.length > 0 && args[0].equals("training-dummy")) {
|
||||
trainingDummy(sender, args); return true;
|
||||
}
|
||||
if (args.length > 0 && args[0].equals("party-registrar")) {
|
||||
partyRegistrar(sender,args); return true;
|
||||
}
|
||||
@@ -519,6 +530,116 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
private void placeShopResponse(org.bukkit.entity.Player player,org.bukkit.Location location,games.dmg.fantasystick.shop.FantasyArmorer saved,Throwable failure){if(failure!=null)report(player.getUniqueId(),"shop-place",failure);if(closed)return;nextTick.accept(()->{if(closed)return;if(failure!=null){if(player.isOnline())player.sendMessage("Fantasy Armorer placement failed; no registration or entity changed.");return;}try{int x=location.getBlockX()>>4,z=location.getBlockZ()>>4;if(location.getWorld().isChunkLoaded(x,z))armorerController.reconcile(location.getWorld().getChunkAt(x,z));if(player.isOnline())player.sendMessage("Placed Fantasy Armorer "+saved.id()+".");}catch(RuntimeException entityFailure){report(player.getUniqueId(),"shop-entity",entityFailure);armorers.remove(saved.id()).whenComplete((ignored,rollback)->nextTick.accept(()->{armorerController.removeLoaded(saved.id());if(player.isOnline())player.sendMessage("Fantasy Armorer placement failed; no registration or entity changed.");}));}});}
|
||||
private void removeShopResponse(CommandSender sender,UUID id,java.util.Optional<games.dmg.fantasystick.shop.FantasyArmorer> removed,Throwable failure){if(failure!=null)report(null,"shop-remove",failure);if(closed)return;nextTick.accept(()->{if(failure!=null)sender.sendMessage("Fantasy Armorer removal failed; registration and entity are unchanged.");else if(removed.isEmpty())sender.sendMessage("Fantasy Armorer not found.");else try{armorerController.removeLoaded(id);sender.sendMessage("Removed Fantasy Armorer "+id+".");}catch(RuntimeException entityFailure){var value=removed.orElseThrow();report(null,"shop-entity-remove",entityFailure);armorers.restore(value).whenComplete((restored,rollback)->{if(rollback!=null)report(null,"shop-remove-rollback",rollback);if(closed)return;nextTick.accept(()->{if(rollback==null){var world=server.getWorld(value.world());if(world!=null&&world.isChunkLoaded(((int)Math.floor(value.x()))>>4,((int)Math.floor(value.z()))>>4))armorerController.reconcile(world.getChunkAt(((int)Math.floor(value.x()))>>4,((int)Math.floor(value.z()))>>4));sender.sendMessage("Fantasy Armorer removal failed; registration and entity are unchanged.");}else sender.sendMessage("Fantasy Armorer removal rollback failed; inspect diagnostics.");});});}});}
|
||||
|
||||
private void trainingDummy(CommandSender sender, String[] args) {
|
||||
if (trainingDummies == null || trainingDummyController == null || args.length < 2) {
|
||||
trainingDummyUsage(sender); return;
|
||||
}
|
||||
if (args[1].equals("list") && args.length == 2) {
|
||||
var values = trainingDummies.all();
|
||||
if (values.isEmpty()) sender.sendMessage("No training dummies are registered.");
|
||||
else for (var value : values) sender.sendMessage(value.id() + " " + value.displayName() + " @ "
|
||||
+ value.world() + " " + value.x() + " " + value.y() + " " + value.z());
|
||||
return;
|
||||
}
|
||||
if (args[1].equals("place") && sender instanceof org.bukkit.entity.Player player) {
|
||||
String name = args.length < 3 ? "" : String.join(" ", java.util.Arrays.copyOfRange(args, 2, args.length));
|
||||
var location = player.getLocation().clone();
|
||||
try {
|
||||
trainingDummies.place(name, location.getWorld().getUID(), location.getX(), location.getY(),
|
||||
location.getZ(), location.getYaw(), location.getPitch())
|
||||
.whenComplete((saved, failure) -> placeDummyResponse(player, location, saved, failure));
|
||||
} catch (IllegalArgumentException invalid) { sender.sendMessage("Training dummy name is invalid."); }
|
||||
return;
|
||||
}
|
||||
if (args[1].equals("remove") && args.length == 3) {
|
||||
UUID id;
|
||||
try { id = UUID.fromString(args[2]); }
|
||||
catch (IllegalArgumentException invalid) { sender.sendMessage("Training dummy UUID is invalid."); return; }
|
||||
trainingDummies.remove(id).whenComplete((removed, failure) -> removeDummyResponse(sender, id, removed, failure));
|
||||
return;
|
||||
}
|
||||
trainingDummyUsage(sender);
|
||||
}
|
||||
|
||||
private static void trainingDummyUsage(CommandSender sender) {
|
||||
sender.sendMessage("Usage: /fantasystick training-dummy <place [name...]|remove <dummy-uuid>|list>");
|
||||
}
|
||||
|
||||
private void placeDummyResponse(org.bukkit.entity.Player player, org.bukkit.Location location,
|
||||
games.dmg.fantasystick.training.TrainingDummy saved, Throwable failure) {
|
||||
if (failure != null) report(player.getUniqueId(), "training-dummy-place", failure);
|
||||
if (closed) return;
|
||||
try { nextTick.accept(() -> {
|
||||
if (closed) return;
|
||||
if (failure != null) {
|
||||
if (player.isOnline()) player.sendMessage("Training dummy placement failed; no record or entity changed.");
|
||||
return;
|
||||
}
|
||||
if (!player.isOnline() || !player.hasPermission(PERMISSION)) {
|
||||
trainingDummies.remove(saved.id()).whenComplete((ignored, rollbackFailure) -> {
|
||||
if (rollbackFailure != null) report(player.getUniqueId(), "training-dummy-permission-rollback", rollbackFailure);
|
||||
if (!closed) nextTick.accept(() -> {
|
||||
trainingDummyController.removeLoaded(saved.id());
|
||||
if (player.isOnline()) player.sendMessage("Training dummy placement was cancelled because permission changed.");
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
int chunkX = location.getBlockX() >> 4, chunkZ = location.getBlockZ() >> 4;
|
||||
if (location.getWorld().isChunkLoaded(chunkX, chunkZ)) {
|
||||
trainingDummyController.reconcile(location.getWorld().getChunkAt(chunkX, chunkZ));
|
||||
}
|
||||
player.sendMessage("Placed training dummy " + saved.id() + ".");
|
||||
} catch (RuntimeException entityFailure) {
|
||||
report(player.getUniqueId(), "training-dummy-entity", entityFailure);
|
||||
trainingDummies.remove(saved.id()).whenComplete((ignored, rollbackFailure) -> {
|
||||
if (rollbackFailure != null) report(player.getUniqueId(), "training-dummy-rollback", rollbackFailure);
|
||||
if (!closed) nextTick.accept(() -> {
|
||||
trainingDummyController.removeLoaded(saved.id());
|
||||
if (player.isOnline()) player.sendMessage("Training dummy placement failed; no record or entity changed.");
|
||||
});
|
||||
});
|
||||
}
|
||||
}); } catch (RuntimeException rejected) { report(player.getUniqueId(), "training-dummy-response", rejected); }
|
||||
}
|
||||
|
||||
private void removeDummyResponse(CommandSender sender, UUID id,
|
||||
java.util.Optional<games.dmg.fantasystick.training.TrainingDummy> removed, Throwable failure) {
|
||||
if (failure != null) report(null, "training-dummy-remove", failure);
|
||||
if (closed) return;
|
||||
try { nextTick.accept(() -> {
|
||||
if (closed) return;
|
||||
if (failure != null) { sender.sendMessage("Training dummy removal failed; record and entity are unchanged."); return; }
|
||||
if (removed.isEmpty()) { sender.sendMessage("Training dummy not found."); return; }
|
||||
if (!sender.hasPermission(PERMISSION)
|
||||
|| sender instanceof org.bukkit.entity.Player player && !player.isOnline()) {
|
||||
restoreDummy(sender, removed.orElseThrow(), "Training dummy removal was cancelled because permission changed.");
|
||||
return;
|
||||
}
|
||||
try { trainingDummyController.removeLoaded(id); sender.sendMessage("Removed training dummy " + id + "."); }
|
||||
catch (RuntimeException entityFailure) {
|
||||
report(null, "training-dummy-entity", entityFailure);
|
||||
restoreDummy(sender, removed.orElseThrow(), "Training dummy removal failed; record and entity are unchanged.");
|
||||
}
|
||||
}); } catch (RuntimeException rejected) { report(null, "training-dummy-response", rejected); }
|
||||
}
|
||||
|
||||
private void restoreDummy(CommandSender sender, games.dmg.fantasystick.training.TrainingDummy removed, String message) {
|
||||
trainingDummies.restore(removed).whenComplete((restored, rollbackFailure) -> {
|
||||
if (rollbackFailure != null) report(null, "training-dummy-rollback", rollbackFailure);
|
||||
if (closed) return;
|
||||
nextTick.accept(() -> {
|
||||
if (rollbackFailure == null) {
|
||||
var world = server.getWorld(restored.world());
|
||||
int chunkX = ((int) Math.floor(restored.x())) >> 4, chunkZ = ((int) Math.floor(restored.z())) >> 4;
|
||||
if (world != null && world.isChunkLoaded(chunkX, chunkZ)) trainingDummyController.reconcile(world.getChunkAt(chunkX, chunkZ));
|
||||
}
|
||||
sender.sendMessage(message);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private void placeRegistrarResponse(org.bukkit.entity.Player player,org.bukkit.Location location,games.dmg.fantasystick.party.PartyRegistrar saved,Throwable failure){if(failure!=null)report(player.getUniqueId(),"party-registrar-place",failure);if(closed)return;try{nextTick.accept(()->{if(closed)return;if(failure!=null){if(player.isOnline())player.sendMessage("Party Registrar placement failed; no registration or entity changed.");return;}try{int chunkX=location.getBlockX()>>4,chunkZ=location.getBlockZ()>>4;if(location.getWorld().isChunkLoaded(chunkX,chunkZ))partyRegistrarController.reconcile(location.getWorld().getChunkAt(chunkX,chunkZ));if(player.isOnline())player.sendMessage("Placed Party Registrar "+saved.id()+".");}catch(RuntimeException entityFailure){report(player.getUniqueId(),"party-registrar-entity",entityFailure);partyRegistrars.remove(saved.id()).whenComplete((ignored,rollbackFailure)->{if(rollbackFailure!=null)report(player.getUniqueId(),"party-registrar-rollback",rollbackFailure);if(closed)return;nextTick.accept(()->{partyRegistrarController.removeLoaded(saved.id());if(player.isOnline())player.sendMessage("Party Registrar placement failed; no registration or entity changed.");});});}});}catch(RuntimeException rejected){report(player.getUniqueId(),"party-registrar-response",rejected);}}
|
||||
private void removeRegistrarResponse(CommandSender sender,UUID id,java.util.Optional<games.dmg.fantasystick.party.PartyRegistrar> removed,Throwable failure){if(failure!=null)report(null,"party-registrar-remove",failure);if(closed)return;try{nextTick.accept(()->{if(closed)return;if(failure!=null)sender.sendMessage("Party Registrar removal failed; registration and entity are unchanged.");else if(removed.isEmpty())sender.sendMessage("Party Registrar not found.");else try{partyRegistrarController.removeLoaded(id);sender.sendMessage("Removed Party Registrar "+id+".");}catch(RuntimeException entityFailure){report(null,"party-registrar-entity",entityFailure);partyRegistrars.restore(removed.orElseThrow()).whenComplete((restored,rollbackFailure)->{if(rollbackFailure!=null)report(null,"party-registrar-rollback",rollbackFailure);if(closed)return;nextTick.accept(()->{if(rollbackFailure==null){var world=server.getWorld(restored.world());int chunkX=((int)Math.floor(restored.x()))>>4,chunkZ=((int)Math.floor(restored.z()))>>4;if(world!=null&&world.isChunkLoaded(chunkX,chunkZ))partyRegistrarController.reconcile(world.getChunkAt(chunkX,chunkZ));}sender.sendMessage("Party Registrar removal failed; registration and entity are unchanged.");});});}});}catch(RuntimeException rejected){report(null,"party-registrar-response",rejected);}}
|
||||
private void partyRegistrar(CommandSender sender,String[] args){
|
||||
@@ -1204,9 +1325,14 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
|
||||
if (closed || !sender.hasPermission(PERMISSION)) return List.of();
|
||||
if (args.length == 1) return matching(sender instanceof org.bukkit.entity.Player
|
||||
? List.of("config", "experience", "give", "inspect", "party-registrar", "recover", "revive","shop") : List.of("config", "experience", "give", "inspect", "party-registrar", "recover","shop"), args[0]);
|
||||
? List.of("config", "experience", "give", "inspect", "party-registrar", "recover", "revive", "shop", "training-dummy")
|
||||
: List.of("config", "experience", "give", "inspect", "party-registrar", "recover", "shop", "training-dummy"), args[0]);
|
||||
if(args.length==2&&args[0].equals("shop"))return matching(sender instanceof org.bukkit.entity.Player?List.of("list","place","remove","restock"):List.of("list","remove","restock"),args[1]);
|
||||
if(args.length==3&&args[0].equals("shop")&&args[1].equals("remove")&&armorers!=null)return matching(armorers.all().stream().map(value->value.id().toString()).toList(),args[2]);
|
||||
if (args.length == 2 && args[0].equals("training-dummy")) return matching(
|
||||
sender instanceof org.bukkit.entity.Player ? List.of("list", "place", "remove") : List.of("list", "remove"), args[1]);
|
||||
if (args.length == 3 && args[0].equals("training-dummy") && args[1].equals("remove") && trainingDummies != null)
|
||||
return matching(trainingDummies.all().stream().map(value -> value.id().toString()).toList(), args[2]);
|
||||
if (args.length == 2 && args[0].equals("party-registrar")) return matching(
|
||||
sender instanceof org.bukkit.entity.Player ? List.of("list","place","remove") : List.of("list","remove"),args[1]);
|
||||
if (args.length == 3 && args[0].equals("party-registrar") && args[1].equals("remove") && partyRegistrars!=null)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package games.dmg.fantasystick.training;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Optional;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/** Applies native damage while allowing a managed dummy to return its intercepted final amount. */
|
||||
@FunctionalInterface
|
||||
public interface TrainingDamage {
|
||||
Optional<BigDecimal> apply(Player source, LivingEntity target, Runnable nativeDamage);
|
||||
|
||||
default boolean target(org.bukkit.entity.Entity entity) { return false; }
|
||||
|
||||
static TrainingDamage passthrough() {
|
||||
return (source, target, nativeDamage) -> { nativeDamage.run(); return Optional.empty(); };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package games.dmg.fantasystick.training;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Durable desired location for one administrator-managed training dummy. */
|
||||
public record TrainingDummy(UUID id, String name, UUID world, double x, double y, double z, float yaw, float pitch) {
|
||||
public TrainingDummy {
|
||||
Objects.requireNonNull(id); Objects.requireNonNull(name); Objects.requireNonNull(world);
|
||||
name = name.strip();
|
||||
if (name.codePointCount(0, name.length()) > 64 || name.codePoints().anyMatch(codePoint -> {
|
||||
int type = Character.getType(codePoint);
|
||||
return type == Character.CONTROL || type == Character.FORMAT || type == Character.SURROGATE;
|
||||
}) || !Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z)
|
||||
|| !Float.isFinite(yaw) || !Float.isFinite(pitch)) {
|
||||
throw new IllegalArgumentException("Invalid training dummy");
|
||||
}
|
||||
}
|
||||
|
||||
public String displayName() { return name.isBlank() ? "Training Dummy" : name; }
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package games.dmg.fantasystick.training;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.entity.Zombie;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.EntityDamageEvent;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
/** Loaded-chunk reconciliation, containment and final-damage interception for training dummies. */
|
||||
public final class TrainingDummyController implements Listener, TrainingDamage, AutoCloseable {
|
||||
private static final String TYPE = "training_dummy";
|
||||
private final Plugin plugin;
|
||||
private final TrainingDummyDirectory directory;
|
||||
private final NamespacedKey idKey;
|
||||
private final NamespacedKey typeKey;
|
||||
private final java.util.Set<Entity> relocating = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
|
||||
private Attempt pending;
|
||||
private boolean closed;
|
||||
|
||||
private static final class Attempt {
|
||||
final LivingEntity target; BigDecimal amount;
|
||||
Attempt(LivingEntity target) { this.target = target; }
|
||||
}
|
||||
|
||||
public TrainingDummyController(Plugin plugin, TrainingDummyDirectory directory) {
|
||||
this.plugin = Objects.requireNonNull(plugin); this.directory = Objects.requireNonNull(directory);
|
||||
idKey = new NamespacedKey(plugin, "training_dummy_id");
|
||||
typeKey = new NamespacedKey(plugin, "managed_npc_type");
|
||||
}
|
||||
|
||||
public void install() {
|
||||
for (var world : plugin.getServer().getWorlds()) {
|
||||
var chunks = world.getLoadedChunks(); if (chunks != null) for (var chunk : chunks) reconcile(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean tagged(Entity entity) {
|
||||
var data = entity.getPersistentDataContainer();
|
||||
return data != null && TYPE.equals(data.get(typeKey, PersistentDataType.STRING));
|
||||
}
|
||||
|
||||
public void reconcile(Chunk chunk) {
|
||||
if (closed) return;
|
||||
var desired = new HashMap<UUID, TrainingDummy>();
|
||||
for (var value : directory.all()) {
|
||||
if (value.world().equals(chunk.getWorld().getUID()) && chunk(value.x()) == chunk.getX()
|
||||
&& chunk(value.z()) == chunk.getZ()) desired.put(value.id(), value);
|
||||
}
|
||||
var retained = new HashSet<UUID>();
|
||||
for (var entity : chunk.getEntities()) {
|
||||
if (!tagged(entity)) continue;
|
||||
UUID id = id(entity); var target = id == null ? null : desired.get(id);
|
||||
if (!(entity instanceof Zombie zombie) || target == null || !retained.add(id)) { entity.remove(); continue; }
|
||||
configure(zombie, target);
|
||||
var current = zombie.getLocation(); var expected = location(target);
|
||||
if (current.distanceSquared(expected) > 0.000001 || Math.abs(current.getYaw() - expected.getYaw()) > 0.001
|
||||
|| Math.abs(current.getPitch() - expected.getPitch()) > 0.001) {
|
||||
relocating.add(zombie); boolean moved;
|
||||
try { moved = zombie.teleport(expected); } finally { relocating.remove(zombie); }
|
||||
if (!moved) { zombie.remove(); spawn(target); }
|
||||
}
|
||||
}
|
||||
for (var value : desired.values()) if (!retained.contains(value.id())) spawn(value);
|
||||
}
|
||||
|
||||
public void removeLoaded(UUID id) {
|
||||
for (var world : plugin.getServer().getWorlds()) {
|
||||
var entities = world.getEntities(); if (entities != null) for (var entity : entities) {
|
||||
if (tagged(entity) && id.equals(id(entity))) entity.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override public Optional<BigDecimal> apply(Player source, LivingEntity target, Runnable nativeDamage) {
|
||||
Objects.requireNonNull(source); Objects.requireNonNull(target); Objects.requireNonNull(nativeDamage);
|
||||
if (closed || !managed(target)) { nativeDamage.run(); return Optional.empty(); }
|
||||
if (pending != null) throw new IllegalStateException("Nested training damage is unavailable");
|
||||
var attempt = new Attempt(target); pending = attempt;
|
||||
try { nativeDamage.run(); }
|
||||
finally { if (pending == attempt) pending = null; }
|
||||
return Optional.ofNullable(attempt.amount);
|
||||
}
|
||||
|
||||
@Override public boolean target(Entity entity) { return managed(entity); }
|
||||
|
||||
private boolean managed(Entity entity) {
|
||||
if (!(entity instanceof Zombie) || !tagged(entity)) return false;
|
||||
UUID id = id(entity); return id != null && directory.find(id).isPresent();
|
||||
}
|
||||
|
||||
private void spawn(TrainingDummy value) {
|
||||
var world = plugin.getServer().getWorld(value.world()); if (world == null) return;
|
||||
int x = chunk(value.x()), z = chunk(value.z()); if (!world.isChunkLoaded(x, z)) return;
|
||||
world.spawn(location(value), Zombie.class, zombie -> configure(zombie, value));
|
||||
}
|
||||
|
||||
private void configure(Zombie zombie, TrainingDummy value) {
|
||||
zombie.getPersistentDataContainer().set(typeKey, PersistentDataType.STRING, TYPE);
|
||||
zombie.getPersistentDataContainer().set(idKey, PersistentDataType.STRING, value.id().toString());
|
||||
zombie.setAI(false); zombie.setAware(false); zombie.setGravity(false); zombie.setSilent(true);
|
||||
zombie.setInvulnerable(false); zombie.setCollidable(false); zombie.setCanPickupItems(false);
|
||||
zombie.setLeashHolder(null); zombie.setRemoveWhenFarAway(false); zombie.setPersistent(true);
|
||||
zombie.setShouldBurnInDay(false); zombie.setBaby(false); zombie.setCanBreakDoors(false);
|
||||
zombie.setFireTicks(0); zombie.setFreezeTicks(0); zombie.setVelocity(new org.bukkit.util.Vector());
|
||||
for (var effect : java.util.List.copyOf(zombie.getActivePotionEffects())) zombie.removePotionEffect(effect.getType());
|
||||
zombie.customName(net.kyori.adventure.text.Component.text(value.displayName()));
|
||||
zombie.setCustomNameVisible(true);
|
||||
}
|
||||
|
||||
private Location location(TrainingDummy value) {
|
||||
return new Location(plugin.getServer().getWorld(value.world()), value.x(), value.y(), value.z(), value.yaw(), value.pitch());
|
||||
}
|
||||
private UUID id(Entity entity) {
|
||||
String value = entity.getPersistentDataContainer().get(idKey, PersistentDataType.STRING);
|
||||
try { return value == null ? null : UUID.fromString(value); }
|
||||
catch (IllegalArgumentException invalid) { return null; }
|
||||
}
|
||||
private static int chunk(double coordinate) { return ((int) Math.floor(coordinate)) >> 4; }
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void damage(EntityDamageEvent event) {
|
||||
if (!tagged(event.getEntity())) return;
|
||||
var attempt = pending;
|
||||
if (attempt != null && attempt.target == event.getEntity() && managed(event.getEntity())
|
||||
&& Double.isFinite(event.getFinalDamage()) && event.getFinalDamage() > 0) {
|
||||
attempt.amount = BigDecimal.valueOf(event.getFinalDamage()).stripTrailingZeros();
|
||||
}
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void combust(org.bukkit.event.entity.EntityCombustEvent event) {
|
||||
if (tagged(event.getEntity())) event.setCancelled(true);
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void transform(org.bukkit.event.entity.EntityTransformEvent event) {
|
||||
if (tagged(event.getEntity())) event.setCancelled(true);
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void breed(org.bukkit.event.entity.EntityBreedEvent event) {
|
||||
if (tagged(event.getMother()) || tagged(event.getFather())) event.setCancelled(true);
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void vehicle(org.bukkit.event.vehicle.VehicleEnterEvent event) {
|
||||
if (tagged(event.getEntered())) event.setCancelled(true);
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void leash(org.bukkit.event.entity.PlayerLeashEntityEvent event) {
|
||||
if (tagged(event.getEntity())) event.setCancelled(true);
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void teleport(org.bukkit.event.entity.EntityTeleportEvent event) {
|
||||
if (tagged(event.getEntity()) && !relocating.contains(event.getEntity())) event.setCancelled(true);
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void potion(org.bukkit.event.entity.EntityPotionEffectEvent event) {
|
||||
if (tagged(event.getEntity())) event.setCancelled(true);
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void splash(org.bukkit.event.entity.PotionSplashEvent event) {
|
||||
for (var entity : java.util.List.copyOf(event.getAffectedEntities())) if (tagged(entity)) event.setIntensity(entity, 0);
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void cloud(org.bukkit.event.entity.AreaEffectCloudApplyEvent event) {
|
||||
event.getAffectedEntities().removeIf(this::tagged);
|
||||
}
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void chunk(org.bukkit.event.world.ChunkLoadEvent event) { reconcile(event.getChunk()); }
|
||||
|
||||
@Override public void close() {
|
||||
closed = true; pending = null;
|
||||
for (var world : plugin.getServer().getWorlds()) {
|
||||
var entities = world.getEntities(); if (entities != null) for (var entity : entities) if (tagged(entity)) entity.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package games.dmg.fantasystick.training;
|
||||
|
||||
import games.dmg.fantasystick.persistence.YamlTrainingDummyRepository;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/** Serialized durable desired state for training dummy entities. */
|
||||
public final class TrainingDummyDirectory implements AutoCloseable {
|
||||
private final YamlTrainingDummyRepository repository;
|
||||
private final java.util.concurrent.ExecutorService worker = Executors.newSingleThreadExecutor(
|
||||
task -> new Thread(task, "fantasy-training-dummy-persistence"));
|
||||
private volatile List<TrainingDummy> snapshot;
|
||||
private volatile boolean closed;
|
||||
private int pending;
|
||||
private final CompletableFuture<Void> drained = new CompletableFuture<>();
|
||||
|
||||
public TrainingDummyDirectory(YamlTrainingDummyRepository repository) throws IOException {
|
||||
this.repository = Objects.requireNonNull(repository); snapshot = repository.load();
|
||||
}
|
||||
public List<TrainingDummy> all() { return snapshot; }
|
||||
public Optional<TrainingDummy> find(UUID id) {
|
||||
return snapshot.stream().filter(value -> value.id().equals(id)).findFirst();
|
||||
}
|
||||
public CompletableFuture<TrainingDummy> place(String name, UUID world, double x, double y, double z,
|
||||
float yaw, float pitch) {
|
||||
var value = new TrainingDummy(UUID.randomUUID(), name, world, x, y, z, yaw, pitch);
|
||||
return submit(() -> {
|
||||
var next = new ArrayList<>(snapshot); next.add(value); repository.save(next);
|
||||
snapshot = List.copyOf(next); return value;
|
||||
});
|
||||
}
|
||||
public CompletableFuture<Optional<TrainingDummy>> remove(UUID id) {
|
||||
return submit(() -> {
|
||||
var found = find(id); if (found.isEmpty()) return Optional.empty();
|
||||
var next = snapshot.stream().filter(value -> !value.id().equals(id)).toList();
|
||||
repository.save(next); snapshot = next; return found;
|
||||
});
|
||||
}
|
||||
public CompletableFuture<TrainingDummy> restore(TrainingDummy dummy) {
|
||||
return submit(() -> {
|
||||
var found = find(dummy.id());
|
||||
if (found.isPresent()) {
|
||||
if (found.orElseThrow().equals(dummy)) return dummy;
|
||||
throw new IOException("Training dummy identity collision");
|
||||
}
|
||||
var next = new ArrayList<>(snapshot); next.add(dummy);
|
||||
next.sort(Comparator.comparing(value -> value.id().toString()));
|
||||
repository.save(next); snapshot = List.copyOf(next); return dummy;
|
||||
});
|
||||
}
|
||||
private <T> CompletableFuture<T> submit(Callable<T> operation) {
|
||||
var future = new CompletableFuture<T>();
|
||||
synchronized (this) {
|
||||
if (closed) { future.completeExceptionally(new IOException("Training dummy directory closed")); return future; }
|
||||
pending++;
|
||||
}
|
||||
worker.execute(() -> { try { future.complete(operation.call()); }
|
||||
catch (Throwable failure) { future.completeExceptionally(failure); }
|
||||
finally { finished(); } });
|
||||
return future;
|
||||
}
|
||||
private synchronized void finished() { pending--; if (closed && pending == 0) drained.complete(null); }
|
||||
public java.util.concurrent.CompletionStage<Void> drained() { return drained.minimalCompletionStage(); }
|
||||
@Override public synchronized void close() { closed = true; worker.shutdown(); if (pending == 0) drained.complete(null); }
|
||||
}
|
||||
Reference in new issue
Block a user