Files
purpur-inventory-helper/src/main/java/games/dmg/spigotinventoryhelper/DispenserRecipeRegistrar.java
T
dmg 534cab061c
Release / release (push) Successful in 4m12s
CI / build (push) Successful in 3m23s
feat(crafting): add stackable dispenser recipe
2026-09-22 21:20:47 -04:00

87 lines
2.7 KiB
Java

package games.dmg.spigotinventoryhelper;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ShapelessRecipe;
import org.bukkit.inventory.recipe.CraftingBookCategory;
public final class DispenserRecipeRegistrar implements RecipeRegistrar {
private final NamespacedKey recipeKey;
private final Supplier<ItemStack> resultFactory;
private final RecipeFactory recipeFactory;
private Server registeredServer;
private boolean owned;
public DispenserRecipeRegistrar(NamespacedKey recipeKey) {
this(recipeKey, () -> new ItemStack(Material.DISPENSER), ShapelessRecipe::new);
}
DispenserRecipeRegistrar(
NamespacedKey recipeKey,
Supplier<ItemStack> resultFactory,
RecipeFactory recipeFactory
) {
this.recipeKey = Objects.requireNonNull(recipeKey, "recipeKey");
this.resultFactory = Objects.requireNonNull(resultFactory, "resultFactory");
this.recipeFactory = Objects.requireNonNull(recipeFactory, "recipeFactory");
}
public boolean register(Server server) {
Objects.requireNonNull(server, "server");
if (owned) {
return true;
}
registeredServer = server;
if (server.getRecipe(recipeKey) != null) {
return false;
}
ItemStack result = resultFactory.get();
ShapelessRecipe recipe = recipeFactory.create(recipeKey, result);
recipe.addIngredient(Material.DROPPER);
recipe.addIngredient(Material.TRIPWIRE_HOOK);
recipe.setCategory(CraftingBookCategory.REDSTONE);
try {
owned = server.addRecipe(recipe);
return owned;
} catch (RuntimeException exception) {
try {
owned = server.getRecipe(recipeKey) != null;
unregister();
} catch (RuntimeException cleanupFailure) {
exception.addSuppressed(cleanupFailure);
}
throw exception;
}
}
@Override
public List<NamespacedKey> recipeKeys() {
return List.of(recipeKey);
}
public void unregister() {
if (!owned || registeredServer == null) {
return;
}
if (!registeredServer.removeRecipe(recipeKey)) {
throw new IllegalStateException("Could not remove owned recipe " + recipeKey);
}
owned = false;
}
@Override
public String description() {
return "alternative Dispenser recipe";
}
@FunctionalInterface
interface RecipeFactory {
ShapelessRecipe create(NamespacedKey key, ItemStack result);
}
}