feat(anvil): combine items beyond enchantment limits
This commit is contained in:
1 parent
24a220ae4a
commit
de045fb458
29 files changed
+4519
-9
No files matched your search
@@ -0,0 +1,125 @@
|
||||
package games.dmg.spigotinventoryhelper;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.ClickType;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
/** Main-thread destination reservation: no overflow drops, no overwrite of unrelated items. */
|
||||
final class AdvancedAnvilDelivery {
|
||||
private final Player player;
|
||||
private final ItemStack cursorBefore;
|
||||
private final ItemStack cursorAfter;
|
||||
private final ItemStack[] storageBefore;
|
||||
private final ItemStack[] storageAfter;
|
||||
private final ItemStack offhandBefore;
|
||||
private final ItemStack offhandAfter;
|
||||
private final boolean cursorDelivery;
|
||||
private final boolean offhandDelivery;
|
||||
|
||||
private AdvancedAnvilDelivery(Player player, ItemStack cursorBefore, ItemStack cursorAfter,
|
||||
ItemStack[] storageBefore, ItemStack[] storageAfter, ItemStack offhandBefore,
|
||||
ItemStack offhandAfter, boolean cursorDelivery, boolean offhandDelivery) {
|
||||
this.player = player;
|
||||
this.cursorBefore = cursorBefore;
|
||||
this.cursorAfter = cursorAfter;
|
||||
this.storageBefore = storageBefore;
|
||||
this.storageAfter = storageAfter;
|
||||
this.offhandBefore = offhandBefore;
|
||||
this.offhandAfter = offhandAfter;
|
||||
this.cursorDelivery = cursorDelivery;
|
||||
this.offhandDelivery = offhandDelivery;
|
||||
}
|
||||
|
||||
static AdvancedAnvilDelivery reserve(InventoryClickEvent event, ItemStack output) {
|
||||
if (!(event.getWhoClicked() instanceof Player player) || event.getRawSlot() != 2) return null;
|
||||
ItemStack cursor = copy(player.getItemOnCursor());
|
||||
switch (event.getAction()) {
|
||||
case PICKUP_ALL, PICKUP_HALF, PICKUP_ONE, PICKUP_SOME -> {
|
||||
if (event.getClick() != ClickType.LEFT && event.getClick() != ClickType.RIGHT) return null;
|
||||
ItemStack next = copy(output);
|
||||
if (cursor != null) {
|
||||
if (!cursor.isSimilar(output) || cursor.getAmount() >= cursor.getMaxStackSize()) return null;
|
||||
next = cursor.clone();
|
||||
next.setAmount(next.getAmount() + 1);
|
||||
}
|
||||
return new AdvancedAnvilDelivery(player, cursor, next, null, null, null, null, true, false);
|
||||
}
|
||||
case MOVE_TO_OTHER_INVENTORY -> {
|
||||
ItemStack[] before = copies(player.getInventory().getStorageContents());
|
||||
ItemStack[] after = copies(before);
|
||||
if (!allocate(after, output)) return null;
|
||||
return new AdvancedAnvilDelivery(player, cursor, null, before, after, null, null, false, false);
|
||||
}
|
||||
case HOTBAR_SWAP, HOTBAR_MOVE_AND_READD -> {
|
||||
int target = event.getClick() == ClickType.SWAP_OFFHAND ? 40 : event.getHotbarButton();
|
||||
if ((target < 0 || target > 8) && target != 40) return null;
|
||||
ItemStack[] before = copies(player.getInventory().getStorageContents());
|
||||
ItemStack[] after = copies(before);
|
||||
boolean offhand = target == 40;
|
||||
ItemStack old = offhand ? copy(player.getInventory().getItemInOffHand()) : copy(before[target]);
|
||||
if (!offhand) after[target] = output.clone();
|
||||
if (old != null && !allocate(after, old)) return null;
|
||||
return new AdvancedAnvilDelivery(player, cursor, null, before, after,
|
||||
offhand ? old : null, offhand ? output.clone() : null, false, offhand);
|
||||
}
|
||||
default -> { return null; }
|
||||
}
|
||||
}
|
||||
|
||||
boolean stillValid() {
|
||||
return Objects.equals(cursorBefore, copy(player.getItemOnCursor()))
|
||||
&& (storageBefore == null || Arrays.equals(storageBefore,
|
||||
copies(player.getInventory().getStorageContents())))
|
||||
&& (!offhandDelivery || Objects.equals(offhandBefore,
|
||||
copy(player.getInventory().getItemInOffHand())));
|
||||
}
|
||||
|
||||
void deliver() {
|
||||
if (cursorDelivery) player.setItemOnCursor(copy(cursorAfter));
|
||||
if (storageAfter != null) {
|
||||
for (int slot = 0; slot < storageAfter.length; slot++) {
|
||||
if (!Objects.equals(storageBefore[slot], storageAfter[slot])) {
|
||||
player.getInventory().setItem(slot, copy(storageAfter[slot]));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (offhandDelivery) player.getInventory().setItemInOffHand(copy(offhandAfter));
|
||||
}
|
||||
|
||||
/** Native anvil quick-move searches hotbar8..0 then storage35..9, merge pass before empty pass. */
|
||||
private static boolean allocate(ItemStack[] storage, ItemStack source) {
|
||||
ItemStack remaining = source.clone();
|
||||
int[] order = new int[36];
|
||||
for (int i = 0; i < 9; i++) order[i] = 8 - i;
|
||||
for (int i = 9; i < 36; i++) order[i] = 44 - i;
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
for (int slot : order) {
|
||||
ItemStack present = storage[slot];
|
||||
if (pass == 0 && present != null && present.isSimilar(remaining)) {
|
||||
int moved = Math.min(remaining.getAmount(), present.getMaxStackSize() - present.getAmount());
|
||||
if (moved > 0) {
|
||||
present.setAmount(present.getAmount() + moved);
|
||||
remaining.setAmount(remaining.getAmount() - moved);
|
||||
}
|
||||
} else if (pass == 1 && present == null) {
|
||||
int moved = Math.min(remaining.getAmount(), remaining.getMaxStackSize());
|
||||
storage[slot] = remaining.asQuantity(moved);
|
||||
remaining.setAmount(remaining.getAmount() - moved);
|
||||
}
|
||||
if (remaining.getAmount() == 0) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static ItemStack copy(ItemStack item) {
|
||||
return item == null || item.isEmpty() ? null : item.clone();
|
||||
}
|
||||
|
||||
private static ItemStack[] copies(ItemStack[] items) {
|
||||
return Arrays.stream(items).map(AdvancedAnvilDelivery::copy).toArray(ItemStack[]::new);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package games.dmg.spigotinventoryhelper;
|
||||
|
||||
import com.destroystokyo.paper.event.block.AnvilDamagedEvent;
|
||||
import java.util.function.DoubleSupplier;
|
||||
import org.bukkit.Effect;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.bukkit.block.data.Directional;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.view.AnvilView;
|
||||
|
||||
/** Native protection-aware side effects, invoked only after a committed inventory transaction. */
|
||||
final class AdvancedAnvilEffects {
|
||||
private AdvancedAnvilEffects() {}
|
||||
|
||||
static void explode(Player player, Location origin) {
|
||||
// Purpur's final flag is essential: the combining player must remain damage-eligible.
|
||||
origin.getWorld().createExplosion(player, origin.clone().add(.5, .5, .5),
|
||||
6F, false, true, false);
|
||||
}
|
||||
|
||||
static void use(AnvilView view, Player player, Location origin, DoubleSupplier wear) {
|
||||
var block = origin.getBlock();
|
||||
Material type = block.getType();
|
||||
if (player.getGameMode() != GameMode.CREATIVE && isAnvil(type) && wear.getAsDouble() < .12) {
|
||||
Material next = switch (type) {
|
||||
case ANVIL -> Material.CHIPPED_ANVIL;
|
||||
case CHIPPED_ANVIL -> Material.DAMAGED_ANVIL;
|
||||
default -> null;
|
||||
};
|
||||
BlockData proposal = next == null ? null : next.createBlockData();
|
||||
var event = new AnvilDamagedEvent(view, proposal);
|
||||
if (!event.callEvent()) return; // Native cancellation also suppresses the use effect.
|
||||
if (event.getDamageState() == AnvilDamagedEvent.DamageState.BROKEN) {
|
||||
block.setType(Material.AIR, false);
|
||||
origin.getWorld().playEffect(origin, Effect.ANVIL_BREAK, 0);
|
||||
return;
|
||||
}
|
||||
BlockData chosen = event.getDamageState().getMaterial().createBlockData();
|
||||
if (chosen instanceof Directional facing && block.getBlockData() instanceof Directional old) {
|
||||
facing.setFacing(old.getFacing());
|
||||
}
|
||||
block.setBlockData(chosen, false);
|
||||
}
|
||||
origin.getWorld().playEffect(origin, Effect.ANVIL_USE, 0);
|
||||
}
|
||||
|
||||
static boolean isAnvil(Material material) {
|
||||
return material == Material.ANVIL || material == Material.CHIPPED_ANVIL
|
||||
|| material == Material.DAMAGED_ANVIL;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package games.dmg.spigotinventoryhelper;
|
||||
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.InventoryCloseEvent;
|
||||
import org.bukkit.event.inventory.PrepareAnvilEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.view.AnvilView;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
/** Owns native preview and deferred, final-cancellation-aware one-item transactions. */
|
||||
final class AdvancedAnvilListener implements Listener, AutoCloseable {
|
||||
private static final Component WARNING = Component.text(
|
||||
"Taking this result commits the attempt. Failure destroys both items and causes an explosion.");
|
||||
private final Plugin plugin;
|
||||
private final Supplier<AdvancedAnvilPolicy> policy;
|
||||
private final java.util.function.IntSupplier risk;
|
||||
private final java.util.function.DoubleSupplier wear;
|
||||
private final Map<AnvilView, Preview> previews = new IdentityHashMap<>();
|
||||
private final Map<AnvilView, Attempt> pending = new IdentityHashMap<>();
|
||||
private final Map<org.bukkit.event.inventory.InventoryClickEvent, Boolean> seen = new java.util.WeakHashMap<>();
|
||||
|
||||
private static final class Attempt {
|
||||
final Preview preview;
|
||||
final org.bukkit.event.inventory.InventoryClickEvent event;
|
||||
final AdvancedAnvilDelivery delivery;
|
||||
final AdvancedAnvilProtocolGuard.Admission admission;
|
||||
boolean invalid;
|
||||
Attempt(Preview preview, org.bukkit.event.inventory.InventoryClickEvent event,
|
||||
AdvancedAnvilDelivery delivery, AdvancedAnvilProtocolGuard.Admission admission, boolean invalid) {
|
||||
this.preview = preview;
|
||||
this.event = event;
|
||||
this.delivery = delivery;
|
||||
this.admission = admission;
|
||||
this.invalid = invalid;
|
||||
}
|
||||
}
|
||||
private final AdvancedAnvilProtocolGuard protocol;
|
||||
private final BukkitTask refresh;
|
||||
private boolean closed;
|
||||
|
||||
// Main-thread-only, exact snapshots for preparation/invalidation, not transaction authority.
|
||||
private record Preview(ItemStack left, ItemStack right, AdvancedAnvilPolicy policy,
|
||||
AdvancedAnvilMerge.Proposal proposal, boolean originalBypass, Component message) {}
|
||||
|
||||
AdvancedAnvilListener(Plugin plugin, Supplier<AdvancedAnvilPolicy> policy,
|
||||
java.util.function.IntSupplier risk, java.util.function.DoubleSupplier wear,
|
||||
com.comphenix.protocol.ProtocolManager manager, String version) {
|
||||
this.plugin = Objects.requireNonNull(plugin);
|
||||
this.policy = Objects.requireNonNull(policy);
|
||||
this.risk = Objects.requireNonNull(risk);
|
||||
this.wear = Objects.requireNonNull(wear);
|
||||
protocol = new AdvancedAnvilProtocolGuard(plugin, manager, version, this);
|
||||
try {
|
||||
refresh = Objects.requireNonNull(plugin.getServer().getScheduler().runTaskTimer(
|
||||
plugin, this::refreshActionBars, 40L, 40L));
|
||||
} catch (RuntimeException | LinkageError unavailable) {
|
||||
protocol.close();
|
||||
throw unavailable;
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void prepare(PrepareAnvilEvent event) {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
AnvilView view = event.getView();
|
||||
Attempt attempt = pending.get(view);
|
||||
if (attempt != null) {
|
||||
// Any intervening preparation invalidates the captured generation, even an ABA edit.
|
||||
attempt.invalid = true;
|
||||
protocol.invalidate(view);
|
||||
event.setResult(null);
|
||||
return;
|
||||
}
|
||||
Preview previous = previews.get(view);
|
||||
ItemStack left = view.getTopInventory().getItem(0);
|
||||
ItemStack right = view.getTopInventory().getItem(1);
|
||||
AdvancedAnvilPolicy effective = policy.get();
|
||||
AdvancedAnvilMerge.Proposal proposal = AdvancedAnvilMerge.prepare(left, right, effective);
|
||||
if (proposal == null) {
|
||||
if (previous != null) {
|
||||
release(view);
|
||||
// Prior bypass can alter vanilla createResult's Too Expensive decision before this
|
||||
// event runs. Recompute once with restored flags instead of leaking an exemption.
|
||||
recompute(view);
|
||||
event.setResult(view.getTopInventory().getItem(2));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!protocol.watch(view)) {
|
||||
release(view);
|
||||
event.setResult(null); // Withhold enhanced output BEFORE any unsafe bypass/install.
|
||||
return;
|
||||
}
|
||||
boolean originalBypass = previous == null ? view.canBypassCost() : previous.originalBypass();
|
||||
Component message = message(proposal);
|
||||
boolean generationChanged = previous == null || !matches(view, previous) || changed(previous, proposal);
|
||||
if (generationChanged) {
|
||||
NativeAnvilGeneration.menu(view).incrementStateId();
|
||||
NativeAnvilGeneration.requireResultFrame(view, proposal.output() == null);
|
||||
}
|
||||
previews.put(view, generationChanged ? new Preview(left.clone(), right.clone(), effective, proposal,
|
||||
originalBypass, message) : previous);
|
||||
if (view.getPlayer() instanceof Player player) {
|
||||
player.sendActionBar(message);
|
||||
if (changed(previous, proposal)) {
|
||||
player.sendMessage(proposal.output() == null ? message : WARNING);
|
||||
}
|
||||
}
|
||||
// Exact private risk is published before CraftEventFactory installs/broadcasts the output.
|
||||
event.setResult(proposal.output());
|
||||
if (proposal.output() != null) {
|
||||
view.setRepairCost(0);
|
||||
view.setBypassCost(true);
|
||||
} else view.setBypassCost(originalBypass);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void intercept(org.bukkit.event.inventory.InventoryClickEvent event) {
|
||||
if (closed || !(event.getView() instanceof AnvilView view)) return;
|
||||
Preview preview = previews.get(view);
|
||||
boolean collection = event.getAction() == org.bukkit.event.inventory.InventoryAction.COLLECT_TO_CURSOR;
|
||||
if (event.getRawSlot() != 2 && !collection) return;
|
||||
if (pending.containsKey(view)) {
|
||||
if (pending.get(view).event != event) event.setCancelled(true);
|
||||
view.getTopInventory().setItem(2, null);
|
||||
return;
|
||||
}
|
||||
if (preview == null && !protocol.watched(view)) return; // Never-owned vanilla stays native.
|
||||
boolean duplicate = seen.put(event, Boolean.TRUE) != null;
|
||||
var admission = protocol.consume(view, preview, event);
|
||||
if (duplicate || admission == null) {
|
||||
event.setCancelled(true);
|
||||
if (preview != null) rerender(view);
|
||||
return;
|
||||
}
|
||||
if (preview == null) return; // Fresh normal book/repair after enhanced context stays native.
|
||||
boolean stale = !matches(view, preview)
|
||||
|| !Objects.equals(preview.proposal().output(), view.getTopInventory().getItem(2));
|
||||
AdvancedAnvilDelivery delivery = preview.proposal().output() == null ? null
|
||||
: AdvancedAnvilDelivery.reserve(event, preview.proposal().output());
|
||||
Attempt attempt = new Attempt(preview, event, delivery, admission,
|
||||
stale || event.isCancelled() || delivery == null);
|
||||
pending.put(view, attempt);
|
||||
// Do not self-cancel accepted intents: continuation can observe the final native denial.
|
||||
// Empty output prevents native onTake, bulk loops and collection from producing/payment.
|
||||
view.getTopInventory().setItem(2, null);
|
||||
try {
|
||||
plugin.getServer().getScheduler().runTask(plugin, () -> finish(view, attempt));
|
||||
} catch (RuntimeException unavailable) {
|
||||
pending.remove(view);
|
||||
event.setCancelled(true);
|
||||
rerender(view);
|
||||
}
|
||||
}
|
||||
|
||||
private void finish(AnvilView view, Attempt attempt) {
|
||||
if (closed || pending.get(view) != attempt) return;
|
||||
pending.remove(view);
|
||||
if (attempt.invalid || attempt.event.isCancelled() || !attempt.admission.valid()
|
||||
|| previews.get(view) != attempt.preview
|
||||
|| !current(view) || !matches(view, attempt.preview)
|
||||
|| !attempt.delivery.stillValid()) {
|
||||
rerender(view);
|
||||
return;
|
||||
}
|
||||
org.bukkit.Location origin = view.getTopInventory().getLocation();
|
||||
if (origin == null || !isAnvil(origin.getBlock().getType())) {
|
||||
rerender(view);
|
||||
return;
|
||||
}
|
||||
int roll = risk.getAsInt();
|
||||
if (roll < 0 || roll >= 100) throw new IllegalStateException("Invalid anvil risk roll");
|
||||
boolean failed = roll < attempt.preview.proposal().failurePercent();
|
||||
ItemStack left = view.getTopInventory().getItem(0);
|
||||
ItemStack right = view.getTopInventory().getItem(1);
|
||||
// Craft anvil getItem returns live native mirrors. Change both counts without invoking
|
||||
// slotsChanged between debits, so close/death/prepare callbacks cannot return a paid item.
|
||||
left.setAmount(left.getAmount() - 1);
|
||||
right.setAmount(right.getAmount() - 1);
|
||||
view.setBypassCost(attempt.preview.originalBypass());
|
||||
try {
|
||||
if (!failed) attempt.delivery.deliver();
|
||||
try {
|
||||
AdvancedAnvilEffects.use(view, (Player) view.getPlayer(), origin, wear);
|
||||
} finally {
|
||||
if (failed) AdvancedAnvilEffects.explode((Player) view.getPlayer(), origin);
|
||||
}
|
||||
} finally {
|
||||
rerender(view);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean matches(AnvilView view, Preview preview) {
|
||||
return Objects.equals(preview.left(), view.getTopInventory().getItem(0))
|
||||
&& Objects.equals(preview.right(), view.getTopInventory().getItem(1))
|
||||
&& preview.policy().equals(policy.get());
|
||||
}
|
||||
|
||||
private void rerender(AnvilView view) {
|
||||
org.bukkit.Location origin = view.getTopInventory().getLocation();
|
||||
if (current(view) && origin != null && isAnvil(origin.getBlock().getType())) {
|
||||
recompute(view);
|
||||
} else release(view);
|
||||
}
|
||||
|
||||
private static boolean isAnvil(org.bukkit.Material material) {
|
||||
return AdvancedAnvilEffects.isAnvil(material);
|
||||
}
|
||||
|
||||
/** Durable settings acknowledgment invalidates snapshots through real input preparation. */
|
||||
void policyChanged() {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
for (AnvilView view : List.copyOf(previews.keySet())) {
|
||||
if (current(view)) {
|
||||
recompute(view);
|
||||
} else {
|
||||
release(view);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void closeView(InventoryCloseEvent event) {
|
||||
if (event.getView() instanceof AnvilView view) {
|
||||
pending.remove(view);
|
||||
release(view);
|
||||
protocol.forget(view);
|
||||
}
|
||||
}
|
||||
|
||||
private void refreshActionBars() {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
protocol.prune();
|
||||
for (AnvilView view : List.copyOf(previews.keySet())) {
|
||||
if (!current(view)) {
|
||||
release(view);
|
||||
continue;
|
||||
}
|
||||
Preview preview = previews.get(view);
|
||||
// A changed input/policy cannot keep displaying a stale risk between preparations.
|
||||
if (!Objects.equals(preview.left(), view.getTopInventory().getItem(0))
|
||||
|| !Objects.equals(preview.right(), view.getTopInventory().getItem(1))
|
||||
|| !preview.policy().equals(policy.get())) {
|
||||
recompute(view);
|
||||
} else if (view.getPlayer() instanceof Player player) {
|
||||
player.sendActionBar(preview.message());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Object protocolPreview(AnvilView view) { return previews.get(view); }
|
||||
|
||||
boolean protocolReady(AnvilView view) {
|
||||
Preview preview = previews.get(view);
|
||||
return !closed && current(view) && !pending.containsKey(view)
|
||||
&& (preview == null || (matches(view, preview)
|
||||
&& Objects.equals(preview.proposal().output(), view.getTopInventory().getItem(2))));
|
||||
}
|
||||
|
||||
private static boolean current(AnvilView view) {
|
||||
return view.getPlayer().getOpenInventory() == view
|
||||
&& (!(view.getPlayer() instanceof Player player) || (player.isOnline() && !player.isDead()));
|
||||
}
|
||||
|
||||
private static void recompute(AnvilView view) {
|
||||
ItemStack left = view.getTopInventory().getItem(0);
|
||||
view.getTopInventory().setItem(0, left == null ? null : left.clone());
|
||||
// Preparation has now returned through CraftEventFactory's final result installation.
|
||||
// Identical-output policy changes still need a real header/frame, not merely a counter.
|
||||
NativeAnvilGeneration.publish(view);
|
||||
}
|
||||
|
||||
private void release(AnvilView view) {
|
||||
protocol.invalidate(view);
|
||||
Preview preview = previews.remove(view);
|
||||
if (preview != null) {
|
||||
view.setBypassCost(preview.originalBypass());
|
||||
if (view.getPlayer() instanceof Player player) {
|
||||
player.sendActionBar(Component.empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean changed(Preview previous, AdvancedAnvilMerge.Proposal next) {
|
||||
return previous == null || !Objects.equals(previous.proposal().output(), next.output())
|
||||
|| previous.proposal().failurePercent() != next.failurePercent()
|
||||
|| !Objects.equals(previous.proposal().refusal(), next.refusal());
|
||||
}
|
||||
|
||||
private static Component message(AdvancedAnvilMerge.Proposal proposal) {
|
||||
if (proposal.output() == null) {
|
||||
return Component.text("Advanced Anvil: " + proposal.refusal());
|
||||
}
|
||||
ItemStack output = proposal.output();
|
||||
Component result = Component.text(title(output.getType().name()));
|
||||
Component customName = output.getItemMeta().customName();
|
||||
if (customName != null) {
|
||||
result = result.append(Component.text(" (" )).append(customName).append(Component.text(")"));
|
||||
}
|
||||
String enchantments = output.getEnchantments().entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey(java.util.Comparator.comparing(
|
||||
enchantment -> enchantment.getKey().toString())))
|
||||
.map(entry -> title(entry.getKey().getKey().getKey()) + " " + roman(entry.getValue()))
|
||||
.collect(Collectors.joining(" · "));
|
||||
return result.append(Component.text(" · " + enchantments + " · Success "
|
||||
+ (100 - proposal.failurePercent()) + "% · Failure " + proposal.failurePercent()
|
||||
+ "% — explosion"));
|
||||
}
|
||||
|
||||
private static String title(String identifier) {
|
||||
return java.util.Arrays.stream(identifier.toLowerCase(Locale.ROOT).split("_"))
|
||||
.map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
|
||||
.collect(Collectors.joining(" "));
|
||||
}
|
||||
|
||||
private static String roman(int level) {
|
||||
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
|
||||
String[] digits = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int index = 0; index < values.length; index++) {
|
||||
while (level >= values[index]) {
|
||||
result.append(digits[index]);
|
||||
level -= values[index];
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
pending.clear();
|
||||
seen.clear();
|
||||
refresh.cancel();
|
||||
HandlerList.unregisterAll(this);
|
||||
for (AnvilView view : List.copyOf(previews.keySet())) {
|
||||
release(view);
|
||||
if (current(view)) {
|
||||
recompute(view);
|
||||
}
|
||||
}
|
||||
protocol.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package games.dmg.spigotinventoryhelper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.Damageable;
|
||||
|
||||
/** Native item proposal, independent of payment and risk rolling. Never mutates either input. */
|
||||
final class AdvancedAnvilMerge {
|
||||
private AdvancedAnvilMerge() {}
|
||||
|
||||
/** Null prepare = unrelated vanilla operation; null output = explained enhanced refusal. */
|
||||
record Proposal(ItemStack output, int failurePercent, String refusal) {}
|
||||
|
||||
static Proposal prepare(ItemStack left, ItemStack right, AdvancedAnvilPolicy policy) {
|
||||
Objects.requireNonNull(policy);
|
||||
if (left == null || right == null || left.isEmpty() || right.isEmpty()
|
||||
|| left.getType() != right.getType() || book(left.getType())) {
|
||||
return null;
|
||||
}
|
||||
Map<Enchantment, Integer> levels = new LinkedHashMap<>(left.getEnchantments());
|
||||
Map<Enchantment, Integer> rightLevels = right.getEnchantments();
|
||||
if (levels.isEmpty() && rightLevels.isEmpty()) {
|
||||
return null; // Repair/rename-only belongs exclusively to native handling.
|
||||
}
|
||||
try {
|
||||
for (var entry : rightLevels.entrySet()) {
|
||||
levels.merge(entry.getKey(), entry.getValue(), (first, second) ->
|
||||
first.equals(second) ? Math.addExact(first, 1) : Math.max(first, second));
|
||||
}
|
||||
} catch (ArithmeticException overflow) {
|
||||
return refused("Enchantment level cannot be represented by this server.");
|
||||
}
|
||||
ItemStack output = left.clone();
|
||||
output.setAmount(1);
|
||||
var enchantments = new ArrayList<>(levels.keySet());
|
||||
for (int index = 0; index < enchantments.size(); index++) {
|
||||
Enchantment enchantment = enchantments.get(index);
|
||||
if (levels.get(enchantment) <= 0 || !enchantment.canEnchantItem(output)) {
|
||||
return refused("An enchantment is not applicable to this item.");
|
||||
}
|
||||
for (int other = index + 1; other < enchantments.size(); other++) {
|
||||
Enchantment candidate = enchantments.get(other);
|
||||
if (enchantment.conflictsWith(candidate) || candidate.conflictsWith(enchantment)) {
|
||||
return refused("The resulting enchantments conflict.");
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
output.addUnsafeEnchantments(levels);
|
||||
repair(output, right);
|
||||
// Unsafe API setters may clamp silently; persistence can independently reject a result.
|
||||
// Inspect the actual native representation instead of imposing a lower gameplay cap.
|
||||
if (!output.getEnchantments().equals(levels)) {
|
||||
return refused("Enchantment level cannot be represented by this server.");
|
||||
}
|
||||
ItemStack restored = ItemStack.deserializeBytes(output.serializeAsBytes());
|
||||
if (!restored.equals(output) || !restored.getEnchantments().equals(levels)) {
|
||||
return refused("Result cannot be represented exactly by this server.");
|
||||
}
|
||||
} catch (RuntimeException unsupported) {
|
||||
return refused("Result cannot be represented exactly by this server.");
|
||||
}
|
||||
int excess = levels.entrySet().stream()
|
||||
.mapToInt(entry -> Math.max(0, entry.getValue() - entry.getKey().getMaxLevel()))
|
||||
.max().orElse(0);
|
||||
return new Proposal(output, policy.failurePercent(excess), null);
|
||||
}
|
||||
|
||||
private static Proposal refused(String reason) {
|
||||
return new Proposal(null, 0, reason);
|
||||
}
|
||||
|
||||
private static boolean book(Material material) {
|
||||
return switch (material) {
|
||||
case BOOK, ENCHANTED_BOOK, WRITABLE_BOOK, WRITTEN_BOOK, KNOWLEDGE_BOOK -> true;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private static void repair(ItemStack output, ItemStack right) {
|
||||
if (!(output.getItemMeta() instanceof Damageable first) || first.isUnbreakable()) {
|
||||
return;
|
||||
}
|
||||
int maximum = maxDamage(output, first);
|
||||
if (maximum <= 0 || !first.hasDamageValue()) {
|
||||
return;
|
||||
}
|
||||
if (!(right.getItemMeta() instanceof Damageable second)) {
|
||||
return;
|
||||
}
|
||||
// Native same-item formula uses each input's effective MAX_DAMAGE component, not material
|
||||
// durability for both. Use long intermediates so custom component values cannot overflow.
|
||||
long remaining = (long) maximum - first.getDamage()
|
||||
+ maxDamage(right, second) - second.getDamage() + (long) maximum * 12 / 100;
|
||||
long damage = Math.max(0, maximum - remaining);
|
||||
if (damage < first.getDamage()) {
|
||||
first.setDamage((int) damage);
|
||||
output.setItemMeta(first);
|
||||
}
|
||||
}
|
||||
|
||||
private static int maxDamage(ItemStack item, Damageable meta) {
|
||||
Integer maximum = item.getData(io.papermc.paper.datacomponent.DataComponentTypes.MAX_DAMAGE);
|
||||
return maximum == null ? 0 : maximum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package games.dmg.spigotinventoryhelper;
|
||||
|
||||
/** Immutable balance captured by an attempt; excess is not an enchantment-level cap. */
|
||||
record AdvancedAnvilPolicy(int basePercent, int stepPercent, int maxFailurePercent) {
|
||||
AdvancedAnvilPolicy {
|
||||
validate(basePercent);
|
||||
validate(stepPercent);
|
||||
validate(maxFailurePercent);
|
||||
}
|
||||
|
||||
static AdvancedAnvilPolicy defaults() {
|
||||
return new AdvancedAnvilPolicy(20, 5, 99);
|
||||
}
|
||||
|
||||
int failurePercent(int greatestExcess) {
|
||||
if (greatestExcess < 0) {
|
||||
throw new IllegalArgumentException("Excess must be nonnegative");
|
||||
}
|
||||
if (greatestExcess == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (basePercent >= maxFailurePercent) {
|
||||
return maxFailurePercent;
|
||||
}
|
||||
if (stepPercent == 0) {
|
||||
return basePercent;
|
||||
}
|
||||
// int-sized excess has a representable long triangular number. Compare before
|
||||
// multiplying by step: that multiplication could overflow even a long.
|
||||
long triangular = (long) greatestExcess * (greatestExcess - 1) / 2;
|
||||
if (triangular > (maxFailurePercent - basePercent) / stepPercent) {
|
||||
return maxFailurePercent;
|
||||
}
|
||||
return basePercent + (int) triangular * stepPercent;
|
||||
}
|
||||
|
||||
private static void validate(int percent) {
|
||||
if (percent < 0 || percent > 100) {
|
||||
throw new IllegalArgumentException("Percent must be an integer from 0 through 100");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package games.dmg.spigotinventoryhelper;
|
||||
|
||||
import com.comphenix.protocol.PacketType;
|
||||
import com.comphenix.protocol.ProtocolManager;
|
||||
import com.comphenix.protocol.events.ListenerPriority;
|
||||
import com.comphenix.protocol.events.PacketAdapter;
|
||||
import com.comphenix.protocol.events.PacketEvent;
|
||||
import com.comphenix.protocol.events.PacketContainer;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import net.minecraft.network.protocol.game.ServerboundContainerClickPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundContainerSetContentPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.view.AnvilView;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
/** Main-thread, one-use protocol-to-Bukkit admission for exact watched native anvil views. */
|
||||
final class AdvancedAnvilProtocolGuard implements AutoCloseable {
|
||||
static final class Admission {
|
||||
final PacketEvent event;
|
||||
final ServerboundContainerClickPacket packet;
|
||||
final Object preview;
|
||||
final java.util.function.BooleanSupplier available;
|
||||
BukkitTask expiry;
|
||||
boolean sealed;
|
||||
Admission(PacketEvent event, ServerboundContainerClickPacket packet, Object preview,
|
||||
java.util.function.BooleanSupplier available) {
|
||||
this.event = event;
|
||||
this.packet = packet;
|
||||
this.preview = preview;
|
||||
this.available = available;
|
||||
}
|
||||
boolean valid() {
|
||||
// Consumption removes the map ticket, but bridge loss must still revoke deferred payment.
|
||||
return available.getAsBoolean() && sealed && !event.isCancelled() && event.getPacket().getHandle() == packet;
|
||||
}
|
||||
}
|
||||
|
||||
private final Plugin plugin;
|
||||
private final ProtocolManager manager;
|
||||
private final AdvancedAnvilListener owner;
|
||||
private final Set<AnvilView> watched = java.util.Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
// Only this immutable actor membership is read on an unexpectedly off-thread library callback.
|
||||
private final Set<Player> actors = java.util.concurrent.ConcurrentHashMap.newKeySet();
|
||||
private final Map<AnvilView, Admission> admissions = new IdentityHashMap<>();
|
||||
private final Map<PacketEvent, Boolean> seen = new java.util.WeakHashMap<>();
|
||||
private record Frame(PacketEvent event, Object packet, int version, int nativeState, Object preview) {
|
||||
boolean valid() { return !event.isCancelled() && event.getPacket().getHandle() == packet; }
|
||||
}
|
||||
private final Map<AnvilView, Frame> frames = new IdentityHashMap<>();
|
||||
// Guard-wide, not reset on forget: even a reused window ID cannot reuse a displayed version.
|
||||
private final AnvilFrameVersions versions = new AnvilFrameVersions();
|
||||
private final PacketAdapter outbound;
|
||||
private final PacketAdapter gate;
|
||||
private final PacketAdapter seal;
|
||||
private volatile boolean closed;
|
||||
|
||||
AdvancedAnvilProtocolGuard(Plugin plugin, ProtocolManager manager, String version, AdvancedAnvilListener owner) {
|
||||
this.plugin = Objects.requireNonNull(plugin);
|
||||
this.manager = Objects.requireNonNull(manager);
|
||||
this.owner = Objects.requireNonNull(owner);
|
||||
if (version == null || !version.contains("Purpur") || !version.contains("26.2.build.2618-stable")
|
||||
|| manager.isClosed()) throw new IllegalStateException("Unsupported Advanced Anvil generation bridge");
|
||||
gate = new PacketAdapter(PacketAdapter.params(plugin, PacketType.Play.Client.WINDOW_CLICK)
|
||||
.listenerPriority(ListenerPriority.LOWEST).optionSync()) {
|
||||
@Override public void onPacketReceiving(PacketEvent event) { receive(event); }
|
||||
};
|
||||
seal = new PacketAdapter(PacketAdapter.params(plugin, PacketType.Play.Client.WINDOW_CLICK)
|
||||
.listenerPriority(ListenerPriority.MONITOR).optionSync()) {
|
||||
@Override public void onPacketReceiving(PacketEvent event) { seal(event); }
|
||||
};
|
||||
outbound = new PacketAdapter(PacketAdapter.params(plugin,
|
||||
PacketType.Play.Server.WINDOW_ITEMS, PacketType.Play.Server.SET_SLOT)
|
||||
.listenerPriority(ListenerPriority.HIGHEST).optionSync()) {
|
||||
@Override public void onPacketSending(PacketEvent event) { send(event); }
|
||||
};
|
||||
try {
|
||||
manager.addPacketListener(outbound);
|
||||
manager.addPacketListener(gate);
|
||||
manager.addPacketListener(seal);
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
manager.removePacketListener(outbound);
|
||||
manager.removePacketListener(gate);
|
||||
manager.removePacketListener(seal);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
boolean watch(AnvilView view) {
|
||||
if (closed || manager.isClosed() || versions.exhausted() || !plugin.getServer().isPrimaryThread()) return false;
|
||||
try {
|
||||
NativeAnvilGeneration.menu(view);
|
||||
if (!(view.getPlayer() instanceof Player player)) return false;
|
||||
watched.add(view);
|
||||
actors.add(player);
|
||||
invalidate(view);
|
||||
return true;
|
||||
} catch (RuntimeException | LinkageError unavailable) { return false; }
|
||||
}
|
||||
|
||||
boolean watched(AnvilView view) { return watched.contains(view); }
|
||||
|
||||
void invalidate(AnvilView view) {
|
||||
Admission admission = admissions.remove(view);
|
||||
if (admission != null && admission.expiry != null) admission.expiry.cancel();
|
||||
}
|
||||
|
||||
private void send(PacketEvent event) {
|
||||
if (closed) return;
|
||||
if (!plugin.getServer().isPrimaryThread()) {
|
||||
if (actors.contains(event.getPlayer())) event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
if (!(event.getPlayer().getOpenInventory() instanceof AnvilView view) || !watched.contains(view)) return;
|
||||
try {
|
||||
Object raw = event.getPacket().getHandle();
|
||||
int containerId;
|
||||
int nativeState;
|
||||
if (raw instanceof ClientboundContainerSetContentPacket content) {
|
||||
containerId = content.containerId();
|
||||
nativeState = content.stateId();
|
||||
} else if (raw instanceof ClientboundContainerSetSlotPacket slot) {
|
||||
containerId = slot.getContainerId();
|
||||
nativeState = slot.getStateId();
|
||||
} else throw new IllegalStateException("Unsupported native anvil frame");
|
||||
if (containerId != NativeAnvilGeneration.menu(view).containerId) return;
|
||||
frames.remove(view);
|
||||
if (event.isCancelled()) return;
|
||||
int version = versions.next();
|
||||
if (version < 0 || manager.isClosed()) {
|
||||
event.setCancelled(true);
|
||||
invalidate(view);
|
||||
return;
|
||||
}
|
||||
Object translated = raw instanceof ClientboundContainerSetContentPacket content
|
||||
? new ClientboundContainerSetContentPacket(containerId, version, content.items(), content.carriedItem())
|
||||
: new ClientboundContainerSetSlotPacket(containerId, version,
|
||||
((ClientboundContainerSetSlotPacket) raw).getSlot(),
|
||||
((ClientboundContainerSetSlotPacket) raw).getItem());
|
||||
event.setPacket(new PacketContainer(event.getPacketType(), translated));
|
||||
frames.put(view, new Frame(event, translated, version, nativeState, owner.protocolPreview(view)));
|
||||
} catch (RuntimeException | LinkageError unavailable) {
|
||||
frames.remove(view);
|
||||
invalidate(view);
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void receive(PacketEvent event) {
|
||||
if (closed) return;
|
||||
if (!plugin.getServer().isPrimaryThread()) {
|
||||
if (actors.contains(event.getPlayer())) event.setCancelled(true);
|
||||
return; // Never inspect or mutate a Bukkit view off the tick thread.
|
||||
}
|
||||
if (!(event.getPlayer().getOpenInventory() instanceof AnvilView view) || !watched.contains(view)) return;
|
||||
invalidate(view); // A new raw intent can never reuse an earlier ticket.
|
||||
try {
|
||||
Object raw = event.getPacket().getHandle();
|
||||
if (seen.put(event, Boolean.TRUE) != null || event.isCancelled()
|
||||
|| !(raw instanceof ServerboundContainerClickPacket packet)
|
||||
|| packet.containerInput() == null || !currentFrame(view, packet)
|
||||
|| (NativeAnvilGeneration.take(packet) && !NativeAnvilGeneration.supportedTake(packet))
|
||||
|| !owner.protocolReady(view)) {
|
||||
refuse(event, view);
|
||||
return;
|
||||
}
|
||||
// Typed reconstruction changes ONLY stateId. Native classification and predictions
|
||||
// receive every original action/input/hash field, with the menu's untouched state.
|
||||
var translated = new ServerboundContainerClickPacket(packet.containerId(), frames.get(view).nativeState(),
|
||||
packet.slotNum(), packet.buttonNum(), packet.containerInput(), packet.changedSlots(), packet.carriedItem());
|
||||
event.setPacket(new PacketContainer(event.getPacketType(), translated));
|
||||
if (!NativeAnvilGeneration.take(translated)) return;
|
||||
Admission admission = new Admission(event, translated, owner.protocolPreview(view),
|
||||
() -> !closed && !manager.isClosed() && !versions.exhausted());
|
||||
admissions.put(view, admission);
|
||||
admission.expiry = plugin.getServer().getScheduler().runTask(plugin, () -> {
|
||||
if (admissions.get(view) == admission) admissions.remove(view);
|
||||
});
|
||||
} catch (RuntimeException | LinkageError unavailable) { refuse(event, view); }
|
||||
}
|
||||
|
||||
private boolean currentFrame(AnvilView view, ServerboundContainerClickPacket packet) {
|
||||
Frame frame = frames.get(view);
|
||||
var menu = NativeAnvilGeneration.menu(view);
|
||||
return !manager.isClosed() && !versions.exhausted() && frame != null && frame.valid()
|
||||
&& packet.containerId() == menu.containerId && packet.stateId() == frame.version()
|
||||
&& frame.nativeState() == menu.getStateId() && frame.preview() == owner.protocolPreview(view);
|
||||
}
|
||||
|
||||
private void seal(PacketEvent event) {
|
||||
if (closed || !plugin.getServer().isPrimaryThread()) return;
|
||||
if (!(event.getPlayer().getOpenInventory() instanceof AnvilView view)) return;
|
||||
Admission admission = admissions.get(view);
|
||||
if (admission == null || admission.event != event) return;
|
||||
// MONITOR is observational. Retain the actual event for final cancellation checks both
|
||||
// at Bukkit dispatch and deferred commit, including later MONITOR listeners.
|
||||
admission.sealed = !event.isCancelled() && event.getPacket().getHandle() == admission.packet;
|
||||
if (!admission.sealed) invalidate(view);
|
||||
}
|
||||
|
||||
Admission consume(AnvilView view, Object preview, InventoryClickEvent event) {
|
||||
Admission admission = admissions.get(view);
|
||||
invalidate(view);
|
||||
if (closed || admission == null || !admission.valid() || admission.preview != preview
|
||||
|| !NativeAnvilGeneration.current(view, admission.packet)
|
||||
|| !NativeAnvilGeneration.matches(admission.packet, event) || !owner.protocolReady(view)) return null;
|
||||
return admission;
|
||||
}
|
||||
|
||||
private static void refuse(PacketEvent event, AnvilView view) {
|
||||
event.setCancelled(true);
|
||||
if (view.getPlayer() instanceof Player player) player.updateInventory();
|
||||
}
|
||||
|
||||
void forget(AnvilView view) {
|
||||
invalidate(view);
|
||||
watched.remove(view);
|
||||
frames.remove(view);
|
||||
if (view.getPlayer() instanceof Player player
|
||||
&& watched.stream().noneMatch(other -> other.getPlayer() == player)) actors.remove(player);
|
||||
}
|
||||
|
||||
void prune() {
|
||||
for (AnvilView view : List.copyOf(watched)) {
|
||||
if (view.getPlayer().getOpenInventory() != view) forget(view);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
for (AnvilView view : List.copyOf(watched)) {
|
||||
forget(view);
|
||||
// Retiring the exact owned window prevents an old enhanced packet becoming an
|
||||
// unrelated vanilla XP take after the protocol listeners have been removed.
|
||||
if (view.getPlayer().getOpenInventory() == view) view.getPlayer().closeInventory();
|
||||
}
|
||||
actors.clear();
|
||||
seen.clear();
|
||||
manager.removePacketListener(outbound);
|
||||
manager.removePacketListener(gate);
|
||||
manager.removePacketListener(seal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package games.dmg.spigotinventoryhelper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.yaml.snakeyaml.DumperOptions;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||
import org.yaml.snakeyaml.error.YAMLException;
|
||||
|
||||
/** Owns startup loading and durable admin updates, not plugin registration or gameplay. */
|
||||
final class AdvancedAnvilSettings implements AutoCloseable {
|
||||
private static final String PERMISSION = "spigotinventoryhelper.admin";
|
||||
private static final List<String> KEYS = List.of(
|
||||
"advanced-anvil-base-failure-percent",
|
||||
"advanced-anvil-risk-step-percent",
|
||||
"advanced-anvil-max-failure-percent");
|
||||
private final Plugin plugin;
|
||||
private final Path file;
|
||||
private final Consumer<AdvancedAnvilPolicy> onChange;
|
||||
private final ThreadPoolExecutor writer;
|
||||
private final Object lifecycle = new Object();
|
||||
private volatile AdvancedAnvilPolicy effective;
|
||||
private volatile boolean closed;
|
||||
// Writer-only state, independent of delayed scheduler acknowledgments.
|
||||
private AdvancedAnvilPolicy persisted;
|
||||
private long savedRevision;
|
||||
// Accessed only under lifecycle, including main-thread acknowledgments.
|
||||
private long publishedRevision;
|
||||
|
||||
static AdvancedAnvilSettings open(
|
||||
Plugin plugin, Consumer<AdvancedAnvilPolicy> onAcknowledgedChange) throws IOException {
|
||||
Objects.requireNonNull(plugin);
|
||||
Objects.requireNonNull(onAcknowledgedChange);
|
||||
Path file = plugin.getDataFolder().toPath().resolve("config.yml");
|
||||
AdvancedAnvilPolicy initial = parsePolicy(read(file));
|
||||
return new AdvancedAnvilSettings(plugin, file, onAcknowledgedChange, initial);
|
||||
}
|
||||
|
||||
private AdvancedAnvilSettings(Plugin plugin, Path file,
|
||||
Consumer<AdvancedAnvilPolicy> onChange, AdvancedAnvilPolicy initial) {
|
||||
this.plugin = plugin;
|
||||
this.file = file;
|
||||
this.onChange = onChange;
|
||||
effective = initial;
|
||||
persisted = initial;
|
||||
writer = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,
|
||||
new ArrayBlockingQueue<>(128), runnable -> {
|
||||
Thread thread = new Thread(runnable, "inventory-helper-config");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}, new ThreadPoolExecutor.AbortPolicy());
|
||||
}
|
||||
|
||||
AdvancedAnvilPolicy policy() {
|
||||
return effective;
|
||||
}
|
||||
|
||||
/** Call on enable with this plugin's actual inventoryhelperadmin command. */
|
||||
void bind(PluginCommand command) {
|
||||
Objects.requireNonNull(command);
|
||||
if (command.getPlugin() != plugin || !command.getName().equals("inventoryhelperadmin")) {
|
||||
throw new IllegalArgumentException("Expected this plugin's inventoryhelperadmin command");
|
||||
}
|
||||
synchronized (lifecycle) {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("Settings closed");
|
||||
}
|
||||
command.setPermission(PERMISSION);
|
||||
command.permissionMessage(Component.text("Permission denied."));
|
||||
command.setExecutor((sender, ignored, label, args) -> execute(sender, args));
|
||||
command.setTabCompleter((sender, ignored, label, args) -> complete(sender, args));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean execute(CommandSender sender, String[] args) {
|
||||
// Revalidate even if the caller bypasses Command.testPermission.
|
||||
if (!sender.hasPermission(PERMISSION)) {
|
||||
sender.sendMessage("Permission denied.");
|
||||
return true;
|
||||
}
|
||||
if (closed) {
|
||||
sender.sendMessage("Configuration unavailable.");
|
||||
return true;
|
||||
}
|
||||
if (args.length < 2 || args.length > 3 || !args[0].equals("config")
|
||||
|| !KEYS.contains(args[1])) {
|
||||
sender.sendMessage("Usage: /inventoryhelperadmin config <key> [value]");
|
||||
return true;
|
||||
}
|
||||
String key = args[1];
|
||||
if (args.length == 2) {
|
||||
sender.sendMessage(key + " = " + value(effective, key));
|
||||
return true;
|
||||
}
|
||||
int percent;
|
||||
try {
|
||||
// Parse integers rather than restricting users to suggested spellings.
|
||||
// No trimming or floating-point/YAML coercion; range validation remains mandatory.
|
||||
percent = Integer.parseInt(args[2]);
|
||||
if (percent < 0 || percent > 100) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
sender.sendMessage("Value must be an integer from 0 through 100.");
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
writer.execute(() -> save(sender, key, percent));
|
||||
} catch (RejectedExecutionException unavailable) {
|
||||
sender.sendMessage("Configuration unavailable; no update accepted.");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private List<String> complete(CommandSender sender, String[] args) {
|
||||
if (closed || !sender.hasPermission(PERMISSION) || args.length > 3) {
|
||||
return List.of();
|
||||
}
|
||||
if (args.length <= 1) {
|
||||
return prefix(List.of("config"), args.length == 0 ? "" : args[0]);
|
||||
}
|
||||
if (!args[0].equals("config")) {
|
||||
return List.of();
|
||||
}
|
||||
if (args.length == 2) {
|
||||
return prefix(KEYS, args[1]);
|
||||
}
|
||||
if (!KEYS.contains(args[1])) {
|
||||
return List.of();
|
||||
}
|
||||
LinkedHashSet<String> candidates = new LinkedHashSet<>();
|
||||
candidates.add(Integer.toString(value(effective, args[1])));
|
||||
candidates.add(Integer.toString(value(AdvancedAnvilPolicy.defaults(), args[1])));
|
||||
candidates.add("0");
|
||||
candidates.add("100");
|
||||
return prefix(List.copyOf(candidates), args[2]);
|
||||
}
|
||||
|
||||
private static List<String> prefix(List<String> candidates, String prefix) {
|
||||
String lower = prefix.toLowerCase(Locale.ROOT);
|
||||
return candidates.stream().filter(value -> value.startsWith(lower)).toList();
|
||||
}
|
||||
|
||||
private void save(CommandSender sender, String key, int percent) {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Map<Object, Object> document = read(file);
|
||||
parsePolicy(document); // Refuse a malformed intervening file, without clobbering it.
|
||||
AdvancedAnvilPolicy next = replace(persisted, key, percent);
|
||||
for (String setting : KEYS) {
|
||||
document.put(setting, value(next, setting));
|
||||
}
|
||||
writeAtomically(document);
|
||||
persisted = next;
|
||||
long revision = ++savedRevision;
|
||||
schedule(() -> acknowledge(sender, key, next, revision));
|
||||
} catch (IOException | YAMLException failure) {
|
||||
schedule(() -> {
|
||||
synchronized (lifecycle) {
|
||||
if (!closed && sender.hasPermission(PERMISSION)) {
|
||||
sender.sendMessage("Configuration save failed; effective settings unchanged.");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void schedule(Runnable acknowledgment) {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
plugin.getServer().getScheduler().runTask(plugin, acknowledgment);
|
||||
} catch (RuntimeException unavailable) {
|
||||
// A disabled/rejected scheduler cannot safely publish gameplay state off-thread.
|
||||
plugin.getLogger().warning("Configuration acknowledgment unavailable; restart reloads disk settings.");
|
||||
}
|
||||
}
|
||||
|
||||
private void acknowledge(CommandSender sender, String key, AdvancedAnvilPolicy next, long revision) {
|
||||
synchronized (lifecycle) {
|
||||
if (closed || revision <= publishedRevision) {
|
||||
return;
|
||||
}
|
||||
publishedRevision = revision;
|
||||
effective = next;
|
||||
try {
|
||||
onChange.accept(next);
|
||||
} catch (RuntimeException failure) {
|
||||
plugin.getLogger().warning("Configuration saved but policy-change callback failed.");
|
||||
}
|
||||
if (!closed && sender.hasPermission(PERMISSION)) {
|
||||
sender.sendMessage(key + " = " + value(next, key) + " (saved)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void writeAtomically(Map<Object, Object> document) throws IOException {
|
||||
Files.createDirectories(file.getParent());
|
||||
Path temporary = Files.createTempFile(file.getParent(), ".config-", ".tmp");
|
||||
try {
|
||||
DumperOptions options = new DumperOptions();
|
||||
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
||||
byte[] bytes = new Yaml(options).dump(document).getBytes(StandardCharsets.UTF_8);
|
||||
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE,
|
||||
StandardOpenOption.TRUNCATE_EXISTING)) {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) {
|
||||
channel.write(buffer);
|
||||
}
|
||||
channel.force(true);
|
||||
}
|
||||
if (closed) {
|
||||
throw new IOException("Settings closed");
|
||||
}
|
||||
// No non-atomic fallback: an unsupported atomic replacement is a failed save.
|
||||
Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
// Publication itself must be durable, not just the temporary file's contents.
|
||||
try (FileChannel directory = FileChannel.open(file.getParent(), StandardOpenOption.READ)) {
|
||||
directory.force(true);
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
Files.deleteIfExists(temporary);
|
||||
} catch (IOException cleanupFailure) {
|
||||
plugin.getLogger().warning("Could not remove configuration temporary file.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<Object, Object> read(Path file) throws IOException {
|
||||
if (Files.notExists(file)) {
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
LoaderOptions options = new LoaderOptions();
|
||||
options.setAllowDuplicateKeys(false);
|
||||
try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
|
||||
Object loaded = new Yaml(new SafeConstructor(options)).load(reader);
|
||||
if (loaded == null) {
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
if (!(loaded instanceof Map<?, ?> values)) {
|
||||
throw new IOException("Configuration must be a YAML mapping");
|
||||
}
|
||||
return new LinkedHashMap<>(values);
|
||||
} catch (YAMLException invalid) {
|
||||
throw new IOException("Malformed configuration", invalid);
|
||||
}
|
||||
}
|
||||
|
||||
private static AdvancedAnvilPolicy parsePolicy(Map<Object, Object> document) throws IOException {
|
||||
AdvancedAnvilPolicy defaults = AdvancedAnvilPolicy.defaults();
|
||||
int[] values = new int[3];
|
||||
for (int index = 0; index < KEYS.size(); index++) {
|
||||
String key = KEYS.get(index);
|
||||
Object raw = document.get(key);
|
||||
if (!document.containsKey(key)) {
|
||||
values[index] = value(defaults, key);
|
||||
} else if ((raw instanceof Integer || raw instanceof Long)
|
||||
&& ((Number) raw).longValue() >= 0 && ((Number) raw).longValue() <= 100) {
|
||||
values[index] = ((Number) raw).intValue();
|
||||
} else {
|
||||
throw new IOException("Invalid integer percent for " + key);
|
||||
}
|
||||
}
|
||||
return new AdvancedAnvilPolicy(values[0], values[1], values[2]);
|
||||
}
|
||||
|
||||
private static int value(AdvancedAnvilPolicy policy, String key) {
|
||||
return switch (KEYS.indexOf(key)) {
|
||||
case 0 -> policy.basePercent();
|
||||
case 1 -> policy.stepPercent();
|
||||
case 2 -> policy.maxFailurePercent();
|
||||
default -> throw new IllegalArgumentException("Unsupported setting");
|
||||
};
|
||||
}
|
||||
|
||||
private static AdvancedAnvilPolicy replace(AdvancedAnvilPolicy policy, String key, int percent) {
|
||||
return new AdvancedAnvilPolicy(
|
||||
key.equals(KEYS.get(0)) ? percent : policy.basePercent(),
|
||||
key.equals(KEYS.get(1)) ? percent : policy.stepPercent(),
|
||||
key.equals(KEYS.get(2)) ? percent : policy.maxFailurePercent());
|
||||
}
|
||||
|
||||
/** Nonblocking close: drop queued work, interrupt the daemon writer, suppress every late ack. */
|
||||
@Override
|
||||
public void close() {
|
||||
synchronized (lifecycle) {
|
||||
closed = true;
|
||||
writer.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package games.dmg.spigotinventoryhelper;
|
||||
|
||||
/** Positive VarInt frame IDs outside the native 15-bit range; never wrap or recycle. */
|
||||
final class AnvilFrameVersions {
|
||||
private long next = 32768;
|
||||
private boolean exhausted;
|
||||
|
||||
int next() {
|
||||
if (next > Integer.MAX_VALUE) {
|
||||
exhausted = true;
|
||||
return -1;
|
||||
}
|
||||
return (int) next++;
|
||||
}
|
||||
|
||||
boolean exhausted() { return exhausted; }
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package games.dmg.spigotinventoryhelper;
|
||||
|
||||
import net.minecraft.network.protocol.game.ServerboundContainerClickPacket;
|
||||
import net.minecraft.world.inventory.AnvilMenu;
|
||||
import net.minecraft.world.inventory.ContainerInput;
|
||||
import org.bukkit.craftbukkit.inventory.view.CraftAnvilView;
|
||||
import org.bukkit.event.inventory.ClickType;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.view.AnvilView;
|
||||
|
||||
/** Compile-only linkage to the checksum-pinned Purpur 26.2 build 2618 menu/packet API. */
|
||||
final class NativeAnvilGeneration {
|
||||
private NativeAnvilGeneration() {}
|
||||
|
||||
static AnvilMenu menu(AnvilView view) {
|
||||
if (!(view instanceof CraftAnvilView craft)) throw new IllegalStateException("Unsupported native anvil view");
|
||||
if (!(craft.getHandle() instanceof AnvilMenu menu)) throw new IllegalStateException("Unsupported native anvil menu");
|
||||
return menu;
|
||||
}
|
||||
|
||||
/** Ensure CraftEventFactory's post-event broadcast emits the final installed result.
|
||||
* Quantity/risk-only changes may otherwise be skipped by native result diffing.
|
||||
* Invalidate only the owned result's remote prediction, never an actual item or input.
|
||||
*/
|
||||
static void requireResultFrame(AnvilView view, boolean emptyOutput) {
|
||||
var menu = menu(view);
|
||||
menu.setRemoteSlot(2, emptyOutput ? menu.getSlot(0).getItem().copy()
|
||||
: net.minecraft.world.item.ItemStack.EMPTY);
|
||||
}
|
||||
|
||||
/** Publish after native preparation has installed the final result, even when diffing skips it. */
|
||||
static void publish(AnvilView view) {
|
||||
menu(view).sendAllDataToRemote();
|
||||
}
|
||||
|
||||
static boolean current(AnvilView view, ServerboundContainerClickPacket packet) {
|
||||
var menu = menu(view);
|
||||
return packet.containerId() == menu.containerId && packet.stateId() == menu.getStateId();
|
||||
}
|
||||
|
||||
static boolean take(ServerboundContainerClickPacket packet) {
|
||||
return packet.slotNum() == 2 || packet.containerInput() == ContainerInput.PICKUP_ALL;
|
||||
}
|
||||
|
||||
static boolean supportedTake(ServerboundContainerClickPacket packet) {
|
||||
return click(packet) != ClickType.UNKNOWN;
|
||||
}
|
||||
|
||||
private static ClickType click(ServerboundContainerClickPacket packet) {
|
||||
int button = packet.buttonNum();
|
||||
return switch (packet.containerInput()) {
|
||||
case PICKUP -> button == 0 ? ClickType.LEFT : button == 1 ? ClickType.RIGHT : ClickType.UNKNOWN;
|
||||
case QUICK_MOVE -> button == 0 ? ClickType.SHIFT_LEFT : button == 1 ? ClickType.SHIFT_RIGHT : ClickType.UNKNOWN;
|
||||
case SWAP -> button == 40 ? ClickType.SWAP_OFFHAND
|
||||
: button >= 0 && button <= 8 ? ClickType.NUMBER_KEY : ClickType.UNKNOWN;
|
||||
case CLONE -> button == 2 ? ClickType.MIDDLE : ClickType.UNKNOWN;
|
||||
case THROW -> button == 0 ? ClickType.DROP : button == 1 ? ClickType.CONTROL_DROP : ClickType.UNKNOWN;
|
||||
case PICKUP_ALL -> button == 0 ? ClickType.DOUBLE_CLICK : ClickType.UNKNOWN;
|
||||
case QUICK_CRAFT -> ClickType.UNKNOWN;
|
||||
};
|
||||
}
|
||||
|
||||
static boolean matches(ServerboundContainerClickPacket packet, InventoryClickEvent event) {
|
||||
if (packet.slotNum() != event.getRawSlot()) return false;
|
||||
ClickType click = click(packet);
|
||||
return click != ClickType.UNKNOWN && event.getClick() == click
|
||||
&& (click != ClickType.NUMBER_KEY || event.getHotbarButton() == packet.buttonNum());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package games.dmg.spigotinventoryhelper;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.plugin.PluginDescriptionFile;
|
||||
@@ -10,6 +11,15 @@ import org.bukkit.plugin.java.JavaPluginLoader;
|
||||
public final class SpigotInventoryHelperPlugin extends JavaPlugin {
|
||||
private SortingStickItemFactory sortingSticks;
|
||||
private RecipeLifecycleGroup recipeLifecycles;
|
||||
private AdvancedAnvilSettings advancedAnvilSettings;
|
||||
private AdvancedAnvilListener advancedAnvil;
|
||||
private java.util.function.IntSupplier anvilRisk = () -> java.util.concurrent.ThreadLocalRandom.current().nextInt(100);
|
||||
private java.util.function.DoubleSupplier anvilWear = () -> java.util.concurrent.ThreadLocalRandom.current().nextDouble();
|
||||
|
||||
private java.util.function.Supplier<com.comphenix.protocol.ProtocolManager> anvilProtocol =
|
||||
com.comphenix.protocol.ProtocolLibrary::getProtocolManager;
|
||||
private java.util.function.Supplier<String> anvilVersion =
|
||||
() -> getServer().getName() + " " + getServer().getBukkitVersion();
|
||||
|
||||
public SpigotInventoryHelperPlugin() {}
|
||||
|
||||
@@ -20,6 +30,23 @@ public final class SpigotInventoryHelperPlugin extends JavaPlugin {
|
||||
super(loader, description, dataFolder, file);
|
||||
}
|
||||
|
||||
SpigotInventoryHelperPlugin(JavaPluginLoader loader, PluginDescriptionFile description,
|
||||
File dataFolder, File file, java.util.function.IntSupplier risk,
|
||||
java.util.function.DoubleSupplier wear) {
|
||||
this(loader, description, dataFolder, file);
|
||||
anvilRisk = java.util.Objects.requireNonNull(risk);
|
||||
anvilWear = java.util.Objects.requireNonNull(wear);
|
||||
}
|
||||
|
||||
SpigotInventoryHelperPlugin(JavaPluginLoader loader, PluginDescriptionFile description,
|
||||
File dataFolder, File file, java.util.function.IntSupplier risk,
|
||||
java.util.function.DoubleSupplier wear, com.comphenix.protocol.ProtocolManager manager,
|
||||
java.util.function.Supplier<String> version) {
|
||||
this(loader, description, dataFolder, file, risk, wear);
|
||||
anvilProtocol = () -> java.util.Objects.requireNonNull(manager);
|
||||
anvilVersion = java.util.Objects.requireNonNull(version);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
sortingSticks = new SortingStickItemFactory(new NamespacedKey(this, "sorting_stick"));
|
||||
@@ -54,17 +81,45 @@ public final class SpigotInventoryHelperPlugin extends JavaPlugin {
|
||||
new BrokenToolListener(this, new ToolReplacementService()),
|
||||
this
|
||||
);
|
||||
try {
|
||||
advancedAnvilSettings = AdvancedAnvilSettings.open(this, ignored -> {
|
||||
if (advancedAnvil != null) {
|
||||
advancedAnvil.policyChanged();
|
||||
}
|
||||
});
|
||||
advancedAnvilSettings.bind(java.util.Objects.requireNonNull(
|
||||
getCommand("inventoryhelperadmin"), "Missing inventoryhelperadmin command"));
|
||||
advancedAnvil = new AdvancedAnvilListener(this, advancedAnvilSettings::policy, anvilRisk, anvilWear,
|
||||
anvilProtocol.get(), anvilVersion.get());
|
||||
getServer().getPluginManager().registerEvents(advancedAnvil, this);
|
||||
} catch (IOException | RuntimeException | LinkageError failure) {
|
||||
closeAdvancedAnvil();
|
||||
getLogger().log(java.util.logging.Level.SEVERE,
|
||||
"Advanced Anvil unavailable; configuration or initialization failed.", failure);
|
||||
}
|
||||
getLogger().info("Spigot Inventory Helper enabled.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
closeAdvancedAnvil();
|
||||
if (recipeLifecycles != null) {
|
||||
recipeLifecycles.disableAll();
|
||||
recipeLifecycles = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void closeAdvancedAnvil() {
|
||||
if (advancedAnvil != null) {
|
||||
advancedAnvil.close();
|
||||
advancedAnvil = null;
|
||||
}
|
||||
if (advancedAnvilSettings != null) {
|
||||
advancedAnvilSettings.close();
|
||||
advancedAnvilSettings = null;
|
||||
}
|
||||
}
|
||||
|
||||
SortingStickItemFactory sortingSticks() {
|
||||
if (sortingSticks == null) {
|
||||
throw new IllegalStateException("Sorting Stick service is unavailable");
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# Advanced Anvil: integer percentages, inclusive 0–100.
|
||||
# E is the greatest resulting enchantment excess above its native maximum.
|
||||
# E=0: no failure; otherwise min(cap, base + step * E * (E - 1) / 2).
|
||||
advanced-anvil-base-failure-percent: 20
|
||||
advanced-anvil-risk-step-percent: 5
|
||||
advanced-anvil-max-failure-percent: 99
|
||||
@@ -2,5 +2,15 @@ name: SpigotInventoryHelper
|
||||
version: ${version}
|
||||
main: games.dmg.spigotinventoryhelper.SpigotInventoryHelperPlugin
|
||||
api-version: "1.20"
|
||||
depend: [ProtocolLib]
|
||||
description: Inventory sorting and automatic tool replacement utilities.
|
||||
author: dmg.games
|
||||
commands:
|
||||
inventoryhelperadmin:
|
||||
description: Read and durably update Inventory Helper balance settings.
|
||||
usage: /inventoryhelperadmin config <key> [value]
|
||||
permission: spigotinventoryhelper.admin
|
||||
permissions:
|
||||
spigotinventoryhelper.admin:
|
||||
description: Administer Inventory Helper balance settings.
|
||||
default: op
|
||||
Reference in new issue
Block a user