Add four-ingredient cauldron soups with persistent brewing and stackable food

This commit is contained in:
2026-09-05 13:34:00 +03:00
commit 32471fb026
17 changed files with 1310 additions and 0 deletions
@@ -0,0 +1,434 @@
package online.astracraft.soups;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.data.Levelled;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.*;
import org.bukkit.event.inventory.*;
import org.bukkit.event.player.*;
import org.bukkit.event.world.*;
import org.bukkit.inventory.*;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Transformation;
import org.bukkit.util.Vector;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import java.io.File;
import java.nio.file.*;
import java.util.*;
import java.util.logging.Level;
public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
NamespacedKey soupKey, colorKey, visualKey;
private Ingredients ingredients;
private final Map<Position, Pot> pots = new LinkedHashMap<>();
private final Map<Position, List<Entity>> visuals = new HashMap<>();
private File dataFile;
private int ticks;
record Position(UUID world, int x, int y, int z) {
static Position at(Block b) { return new Position(b.getWorld().getUID(), b.getX(), b.getY(), b.getZ()); }
Block loadedBlock() {
World w = Bukkit.getWorld(world);
return w == null || !w.isChunkLoaded(x >> 4, z >> 4) ? null : w.getBlockAt(x, y, z);
}
String id() { return world + "," + x + "," + y + "," + z; }
static Position parse(String s) {
String[] p = s.split(",");
if (p.length != 4) throw new IllegalArgumentException("Invalid cauldron position " + s);
return new Position(UUID.fromString(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]), Integer.parseInt(p[3]));
}
}
record Pot(List<ItemStack> items, ItemStack soup) { Pot { items = List.copyOf(items); } }
@Override public void onEnable() {
pots.clear();
soupKey = new NamespacedKey(this, "combined_soup");
colorKey = new NamespacedKey(this, "soup_color");
visualKey = new NamespacedKey(this, "cauldron_visual");
saveDefaultConfig();
dataFile = new File(getDataFolder(), "cauldrons.yml");
try {
// Unlike loadConfiguration(), load() reports malformed YAML instead of silently using defaults.
new YamlConfiguration().load(new File(getDataFolder(), "config.yml"));
ingredients = new Ingredients(this);
loadPots();
} catch (Exception e) {
getLogger().log(Level.SEVERE, "Не удалось прочитать конфигурацию/котлы; данные оставлены без изменений", e);
Bukkit.getPluginManager().disablePlugin(this);
return;
}
Bukkit.getPluginManager().registerEvents(this, this);
for (World world : Bukkit.getWorlds()) for (Entity entity : world.getEntities()) {
if (isVisual(entity)) entity.remove();
else if (entity instanceof Item item) normalizeEntity(item);
}
for (Player p : Bukkit.getOnlinePlayers()) normalizeInventory(p.getInventory());
Bukkit.getScheduler().runTaskTimer(this, this::refresh, 1, 10);
getLogger().info("AstraSoups: загружено котлов: " + pots.size());
}
@Override public void onDisable() {
for (Position pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos);
}
public Ingredients ingredients() { return ingredients; }
private void loadPots() throws Exception {
if (!dataFile.exists()) return;
YamlConfiguration data = new YamlConfiguration();
data.load(dataFile);
ConfigurationSection section = data.getConfigurationSection("cauldrons");
if (section == null && !data.getKeys(false).isEmpty()) throw new IllegalArgumentException("Invalid cauldrons.yml");
if (section == null) return;
for (String id : section.getKeys(false)) {
ConfigurationSection c = Objects.requireNonNull(section.getConfigurationSection(id));
List<ItemStack> items = new ArrayList<>();
for (Object value : c.getList("items", List.of())) {
if (!(value instanceof ItemStack item) || item.getAmount() != 1 || item.getType().isAir()) throw new IllegalArgumentException("Invalid ingredient at " + id);
items.add(item);
}
ItemStack soup = c.getItemStack("soup");
if (items.size() > 4 || (soup != null && (!items.isEmpty() || soup.getAmount() != 1 || !ingredients.isCombined(soup)))
|| (items.isEmpty() && soup == null)) throw new IllegalArgumentException("Invalid cauldron at " + id);
pots.put(Position.parse(id), new Pot(items, soup));
}
}
/** Save before transferring real items. A failed save rolls back the in-memory change. */
private boolean change(Position pos, Pot next) {
Pot old = pots.get(pos);
if (next == null) pots.remove(pos); else pots.put(pos, next);
try {
YamlConfiguration data = new YamlConfiguration();
data.createSection("cauldrons");
for (Map.Entry<Position, Pot> entry : pots.entrySet()) {
String prefix = "cauldrons." + entry.getKey().id();
data.set(prefix + ".items", entry.getValue().items);
data.set(prefix + ".soup", entry.getValue().soup);
}
Path temp = dataFile.toPath().resolveSibling("cauldrons.yml.tmp");
Files.writeString(temp, data.saveToString());
try { Files.move(temp, dataFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
catch (AtomicMoveNotSupportedException e) { Files.move(temp, dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING); }
removeVisuals(pos);
return true;
} catch (Exception e) {
if (old == null) pots.remove(pos); else pots.put(pos, old);
getLogger().log(Level.SEVERE, "Ошибка сохранения котла; действие отменено", e);
return false;
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void interact(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getClickedBlock() == null) return;
Block block = event.getClickedBlock();
Position pos = Position.at(block);
Pot pot = pots.get(pos);
if (event.getHand() != EquipmentSlot.HAND) {
if (pot != null) event.setCancelled(true);
return;
}
if (event.useInteractedBlock() == Event.Result.DENY || event.useItemInHand() == Event.Result.DENY) return;
if (block.getType() != Material.WATER_CAULDRON) return;
Player player = event.getPlayer();
if (!player.hasPermission("astrasoups.use") || player.getGameMode() == GameMode.SPECTATOR) return;
ItemStack held = player.getInventory().getItemInMainHand();
boolean empty = held.getType().isAir();
boolean bowl = held.getType() == Material.BOWL;
if (pot == null && ingredients.read(held) == null) return;
event.setCancelled(true);
if (pot == null) {
if (getConfig().getBoolean("require-full-water", true)
&& block.getBlockData() instanceof Levelled level && level.getLevel() != level.getMaximumLevel()) {
say(player, "Сначала наполните котёл водой доверху."); return;
}
pot = new Pot(List.of(), null);
}
if (pot.soup != null) {
if (!bowl) { say(player, "Суп готов. Возьмите его миской — ПКМ."); return; }
ItemStack result = pot.soup.clone();
if (!change(pos, null)) { saveError(player); return; }
takeOne(player);
give(player, result);
block.setType(Material.CAULDRON);
block.getWorld().playSound(block.getLocation(), Sound.ITEM_BOTTLE_FILL, 0.8f, 0.7f);
return;
}
boolean cook = pot.items.size() == 4 && (player.isSneaking() || !empty);
if (cook) {
String error = ingredients.rejection(pot.items);
if (error != null) { say(player, error + " ПКМ пустой рукой возвращает последний ингредиент."); return; }
ItemStack soup = ingredients.brew(pot.items);
if (!change(pos, new Pot(List.of(), soup))) { saveError(player); return; }
show(pos, pots.get(pos), block);
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BREWING_STAND_BREW, 1, 1);
block.getWorld().spawnParticle(Particle.CLOUD, block.getLocation().add(.5, 1.05, .5), 12, .2, .12, .2, .01);
say(player, "Суп готов! Соберите его миской.");
return;
}
if (empty) {
if (pot.items.isEmpty()) return;
List<ItemStack> remaining = new ArrayList<>(pot.items);
ItemStack last = remaining.removeLast();
if (!change(pos, remaining.isEmpty() ? null : new Pot(remaining, null))) { saveError(player); return; }
give(player, last.clone());
say(player, "Возвращён последний ингредиент. В котле: " + remaining.size() + "/4.");
return;
}
if (pot.items.size() == 4) { say(player, "Для варки: Shift+ПКМ или ПКМ с предметом в руке."); return; }
if (ingredients.read(held) == null) { say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/4."); return; }
List<ItemStack> items = new ArrayList<>(pot.items);
items.add(held.asOne());
if (!change(pos, new Pot(items, null))) { saveError(player); return; }
takeOne(player);
show(pos, pots.get(pos), block);
block.getWorld().playSound(block.getLocation(), Sound.ENTITY_GENERIC_SPLASH, .3f, 1.6f);
say(player, "Ингредиенты: " + items.size() + "/4." + (items.size() == 4 ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." : ""));
}
private void takeOne(Player p) {
if (p.getGameMode() == GameMode.CREATIVE) return;
ItemStack held = p.getInventory().getItemInMainHand();
p.getInventory().setItemInMainHand(held.getAmount() == 1 ? null : held.subtract(1));
}
private void give(Player p, ItemStack item) {
Ingredients.normalize(item);
p.getInventory().addItem(item).values().forEach(left -> p.getWorld().dropItemNaturally(p.getLocation(), left));
}
private void say(Player p, String text) { p.sendActionBar(Component.text(text, NamedTextColor.GOLD)); }
private void saveError(Player p) { say(p, "Не удалось сохранить котёл. Обратитесь к администратору."); }
private void refresh() {
ticks += 10;
for (Map.Entry<Position, Pot> entry : new ArrayList<>(pots.entrySet())) {
Position pos = entry.getKey();
Block block = pos.loadedBlock();
if (block == null) { removeVisuals(pos); continue; }
if (block.getType() != Material.WATER_CAULDRON) {
// External block editing: return raw ingredients only once, never resurrect a missing block.
if (change(pos, null)) for (ItemStack item : entry.getValue().items) block.getWorld().dropItemNaturally(block.getLocation().add(.5, .5, .5), item.clone());
continue;
}
List<Entity> entities = visuals.get(pos);
if (entities == null || entities.stream().anyMatch(e -> !e.isValid())) {
removeVisuals(pos); show(pos, entry.getValue(), block);
} else {
for (int i = 0; i < entities.size(); i++) if (entities.get(i) instanceof Item item) {
item.teleport(itemLocation(block, i));
item.setVelocity(new Vector());
}
}
}
if (ticks % 20 == 0) for (Player player : Bukkit.getOnlinePlayers()) {
normalizeInventory(player.getInventory());
normalizeInventory(player.getOpenInventory().getTopInventory());
ItemStack cursor = player.getItemOnCursor();
if (Ingredients.normalize(cursor)) player.setItemOnCursor(cursor);
}
}
private Location itemLocation(Block block, int i) {
double[][] offsets = {{.32, .32}, {.68, .32}, {.32, .68}, {.68, .68}};
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
double height = .375 + .1875 * waterLevel;
return block.getLocation().add(offsets[i][0], height - .11 + Math.sin(ticks * .06 + i) * .025, offsets[i][1]);
}
private void show(Position pos, Pot pot, Block block) {
if (visuals.containsKey(pos)) return;
List<Entity> entities = new ArrayList<>();
visuals.put(pos, entities);
if (pot.soup != null) {
int rgb = pot.soup.getItemMeta().getPersistentDataContainer().getOrDefault(colorKey, PersistentDataType.INTEGER, 0xB77A36);
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
BlockDisplay display = block.getWorld().spawn(block.getLocation().add(.125, .375 + .1875 * waterLevel + .005, .125), BlockDisplay.class, d -> {
markVisual(d);
d.setBlock(surface(rgb).createBlockData());
d.setTransformation(new Transformation(new Vector3f(), new Quaternionf(), new Vector3f(.75f, .012f, .75f), new Quaternionf()));
d.setBrightness(new Display.Brightness(12, 12));
d.setViewRange(.5f);
});
entities.add(display);
} else for (int i = 0; i < pot.items.size(); i++) {
ItemStack stack = pot.items.get(i).clone();
Item item = block.getWorld().spawn(itemLocation(block, i), Item.class, e -> {
markVisual(e);
e.setItemStack(stack);
e.setCanPlayerPickup(false);
e.setCanMobPickup(false);
e.setPickupDelay(Integer.MAX_VALUE);
e.setUnlimitedLifetime(true);
e.setVelocity(new Vector());
});
entities.add(item);
}
}
private Material surface(int rgb) {
Material[] materials = {Material.ORANGE_TERRACOTTA, Material.YELLOW_TERRACOTTA, Material.RED_TERRACOTTA,
Material.BROWN_TERRACOTTA, Material.GREEN_TERRACOTTA, Material.LIME_TERRACOTTA,
Material.BLUE_TERRACOTTA, Material.CYAN_TERRACOTTA, Material.PURPLE_TERRACOTTA,
Material.PINK_TERRACOTTA, Material.WHITE_TERRACOTTA, Material.BLACK_TERRACOTTA};
int[] colors = {0xA15325, 0xBA8523, 0x8E3C2E, 0x4D3323, 0x4C532A, 0x677535,
0x4A3B5B, 0x565B5B, 0x764656, 0xA14E4E, 0xD1B2A1, 0x251610};
Color wanted = Color.fromRGB(rgb);
int best = 0, distance = Integer.MAX_VALUE;
for (int i = 0; i < colors.length; i++) {
Color candidate = Color.fromRGB(colors[i]);
int r = candidate.getRed() - wanted.getRed(), g = candidate.getGreen() - wanted.getGreen(), b = candidate.getBlue() - wanted.getBlue();
int d = r * r + g * g + b * b;
if (d < distance) { best = i; distance = d; }
}
return materials[best];
}
private void markVisual(Entity entity) {
entity.getPersistentDataContainer().set(visualKey, PersistentDataType.BYTE, (byte) 1);
entity.setPersistent(false);
entity.setGravity(false);
entity.setInvulnerable(true);
entity.setSilent(true);
}
private boolean isVisual(Entity entity) { return entity.getPersistentDataContainer().has(visualKey, PersistentDataType.BYTE); }
private void removeVisuals(Position pos) {
List<Entity> entities = visuals.remove(pos);
if (entities != null) entities.forEach(Entity::remove);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void breakBlock(BlockBreakEvent e) {
Position pos = Position.at(e.getBlock()); Pot pot = pots.get(pos);
if (pot == null) return;
if (!change(pos, null)) { e.setCancelled(true); saveError(e.getPlayer()); return; }
for (ItemStack item : pot.items) e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation().add(.5, .5, .5), item.clone());
if (pot.soup != null) say(e.getPlayer(), "Суп вылился из разбитого котла.");
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void cauldronChange(CauldronLevelChangeEvent e) { if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void explode(EntityExplodeEvent e) { e.blockList().removeIf(b -> pots.containsKey(Position.at(b))); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void blockExplode(BlockExplodeEvent e) { e.blockList().removeIf(b -> pots.containsKey(Position.at(b))); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void piston(BlockPistonExtendEvent e) { if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b)))) e.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void pistonRetract(BlockPistonRetractEvent e) { if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b)))) e.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void entityBlock(EntityChangeBlockEvent e) { if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void pickup(EntityPickupItemEvent e) { if (isVisual(e.getItem())) e.setCancelled(true); else normalizeEntity(e.getItem()); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void hopperPickup(InventoryPickupItemEvent e) { if (isVisual(e.getItem())) e.setCancelled(true); else normalizeEntity(e.getItem()); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void merge(ItemMergeEvent e) { if (isVisual(e.getEntity()) || isVisual(e.getTarget())) e.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void damage(EntityDamageEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void portal(EntityPortalEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void despawn(ItemDespawnEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
@EventHandler public void unload(ChunkUnloadEvent e) {
for (Position p : new ArrayList<>(visuals.keySet())) if (p.world.equals(e.getWorld().getUID()) && (p.x >> 4) == e.getChunk().getX() && (p.z >> 4) == e.getChunk().getZ()) removeVisuals(p);
}
@EventHandler public void entitiesLoad(EntitiesLoadEvent e) {
for (Entity entity : e.getEntities()) {
if (isVisual(entity) && visuals.values().stream().noneMatch(list -> list.contains(entity))) entity.remove();
else if (entity instanceof Item item && !isVisual(entity)) normalizeEntity(item);
}
}
private void normalizeEntity(Item item) { ItemStack stack = item.getItemStack(); if (Ingredients.normalize(stack)) item.setItemStack(stack); }
private void normalizeInventory(Inventory inv) {
for (int i = 0; i < inv.getSize(); i++) {
ItemStack item = inv.getItem(i);
if (Ingredients.normalize(item)) inv.setItem(i, item);
}
}
@EventHandler public void join(PlayerJoinEvent e) { normalizeInventory(e.getPlayer().getInventory()); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void open(InventoryOpenEvent e) { normalizeInventory(e.getInventory()); normalizeInventory(e.getPlayer().getInventory()); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void spawn(ItemSpawnEvent e) { normalizeEntity(e.getEntity()); }
@EventHandler(priority = EventPriority.HIGHEST)
public void craft(PrepareItemCraftEvent e) {
ItemStack result = e.getInventory().getResult();
if (Ingredients.normalize(result)) e.getInventory().setResult(result);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void crafted(CraftItemEvent e) {
ItemStack result = e.getCurrentItem();
if (Ingredients.normalize(result)) e.setCurrentItem(result);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void loot(LootGenerateEvent e) { e.getLoot().forEach(Ingredients::normalize); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void transfer(InventoryMoveItemEvent e) { ItemStack item = e.getItem(); if (Ingredients.normalize(item)) e.setItem(item); }
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
sender.sendMessage(Component.text("ПКМ с едой/зельем: добавить (4 предмета). ПКМ пустой рукой: забрать последний. Shift+ПКМ или ПКМ с предметом после заполнения: сварить. ПКМ миской по готовому супу: собрать.", NamedTextColor.GOLD));
return true;
}
if (!sender.hasPermission("astrasoups.admin")) { sender.sendMessage("Недостаточно прав."); return true; }
if (args[0].equalsIgnoreCase("reload") && args.length == 1) {
String previous = getConfig().saveToString();
try {
YamlConfiguration candidate = new YamlConfiguration();
candidate.load(new File(getDataFolder(), "config.yml"));
getConfig().loadFromString(candidate.saveToString());
Ingredients next = new Ingredients(this);
ingredients = next;
sender.sendMessage("AstraSoups: конфигурация перезагружена.");
} catch (Exception ex) {
// Restore prior settings in memory; leave the invalid file for the administrator to fix.
restoreConfig(previous);
sender.sendMessage("Ошибка конфигурации: " + ex.getMessage() + ". Продолжают действовать прежние настройки.");
}
return true;
}
if (args[0].equalsIgnoreCase("register") && args.length == 4 && sender instanceof Player player) {
if (!args[1].matches("[a-z0-9_-]+")) { sender.sendMessage("ID: только a-z, 0-9, _ и -."); return true; }
ItemStack item = player.getInventory().getItemInMainHand().asOne();
if (item.getType().isAir()) { sender.sendMessage("Возьмите уникальную еду в основную руку."); return true; }
String previous = getConfig().saveToString();
try {
int nutrition = Integer.parseInt(args[2]); float saturation = Float.parseFloat(args[3]);
if (nutrition < 0 || nutrition > getConfig().getInt("max-nutrition", 1000) || saturation < 0 || !Float.isFinite(saturation)
|| saturation > getConfig().getDouble("max-saturation", 1000)) throw new IllegalArgumentException();
String path = "custom-ingredients." + args[1];
getConfig().set(path + ".item", item);
getConfig().set(path + ".nutrition", nutrition);
getConfig().set(path + ".saturation", saturation);
Ingredients next = new Ingredients(this);
getConfig().save(new File(getDataFolder(), "config.yml"));
ingredients = next;
sender.sendMessage("Зарегистрирован ингредиент: " + args[1]);
} catch (Exception ex) {
restoreConfig(previous);
sender.sendMessage("Не удалось зарегистрировать: проверьте числа и конфигурацию. " + ex.getMessage());
}
return true;
}
return false;
}
private void restoreConfig(String yaml) {
try { getConfig().loadFromString(yaml); }
catch (org.bukkit.configuration.InvalidConfigurationException ex) { throw new IllegalStateException("Cannot restore validated config", ex); }
}
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if (!sender.hasPermission("astrasoups.admin")) return List.of();
return args.length == 1 ? List.of("reload", "register").stream().filter(s -> s.startsWith(args[0].toLowerCase(Locale.ROOT))).toList() : List.of();
}
}
@@ -0,0 +1,32 @@
package online.astracraft.soups;
import java.util.List;
import java.util.Set;
/** Pure matching logic: incompatible selectors must occur in distinct slots. */
public final class CombinationRules {
private CombinationRules() {}
public static boolean matches(Set<String> tags, String selector) {
return selector.equals("*") || tags.contains(selector.toLowerCase(java.util.Locale.ROOT));
}
public static String rejection(List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs) {
if (ingredients.size() != 4) return "Нужно ровно 4 ингредиента.";
for (Set<String> tags : ingredients) {
for (String selector : blocked) {
if (matches(tags, selector)) return "Запрещён ингредиент: " + selector;
}
}
for (List<String> pair : pairs) {
for (int i = 0; i < ingredients.size(); i++) {
for (int j = 0; j < ingredients.size(); j++) {
if (i != j && matches(ingredients.get(i), pair.get(0)) && matches(ingredients.get(j), pair.get(1))) {
return "Несовместимые ингредиенты: " + String.join(" + ", pair);
}
}
}
}
return null;
}
}
@@ -0,0 +1,199 @@
package online.astracraft.soups;
import io.papermc.paper.datacomponent.DataComponentTypes;
import io.papermc.paper.datacomponent.item.Consumable;
import io.papermc.paper.datacomponent.item.FoodProperties;
import io.papermc.paper.datacomponent.item.UseRemainder;
import io.papermc.paper.datacomponent.item.consumable.ConsumeEffect;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.inventory.meta.SuspiciousStewMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.lang.reflect.Method;
import java.util.*;
public final class Ingredients {
public record Ingredient(int nutrition, float saturation, List<ConsumeEffect> effects, Set<String> tags, Color color) {}
private record Custom(String id, ItemStack sample, int nutrition, float saturation, List<PotionEffect> effects) {}
private final AstraSoupsPlugin plugin;
private final List<Custom> custom = new ArrayList<>();
private List<String> blocked;
private final List<List<String>> pairs = new ArrayList<>();
private Method iaLookup, iaId;
private Color defaultColor;
public Ingredients(AstraSoupsPlugin plugin) {
this.plugin = plugin;
defaultColor = Color.fromRGB(Integer.parseInt(plugin.getConfig().getString("default-color", "#B77A36").replace("#", ""), 16));
blocked = plugin.getConfig().getStringList("blocked-ingredients");
for (Object value : plugin.getConfig().getList("incompatible", List.of())) {
if (!(value instanceof List<?> list) || list.size() != 2 || list.stream().anyMatch(x -> !(x instanceof String))) {
throw new IllegalArgumentException("Каждое правило incompatible должно содержать два селектора");
}
pairs.add(List.of((String) list.get(0), (String) list.get(1)));
}
if (plugin.getConfig().getInt("max-nutrition", 1000) < 0
|| !Float.isFinite((float) plugin.getConfig().getDouble("max-saturation", 1000))
|| plugin.getConfig().getDouble("max-saturation", 1000) < 0) {
throw new IllegalArgumentException("Некорректные ограничения питания");
}
ConfigurationSection section = plugin.getConfig().getConfigurationSection("custom-ingredients");
if (section != null) for (String id : section.getKeys(false)) {
ConfigurationSection c = Objects.requireNonNull(section.getConfigurationSection(id));
ItemStack sample = c.getItemStack("item");
int nutrition = c.getInt("nutrition");
float saturation = (float) c.getDouble("saturation");
if (sample == null || sample.getType().isAir() || nutrition < 0 || saturation < 0 || !Float.isFinite(saturation)) {
throw new IllegalArgumentException("Некорректный custom-ingredients." + id);
}
List<PotionEffect> effects = new ArrayList<>();
for (Map<?, ?> map : c.getMapList("effects")) {
PotionEffectType type = Registry.EFFECT.get(Objects.requireNonNull(NamespacedKey.fromString(String.valueOf(map.get("type")))));
if (type == null) throw new IllegalArgumentException("Неизвестный эффект в " + id);
int duration = Integer.parseInt(String.valueOf(map.get("duration")));
int amplifier = Integer.parseInt(String.valueOf(map.get("amplifier")));
if (duration < -1 || duration == 0 || amplifier < 0 || amplifier > 255) throw new IllegalArgumentException("Некорректный эффект в " + id);
effects.add(new PotionEffect(type, duration, amplifier));
}
normalize(sample);
custom.add(new Custom(id, sample.asOne(), nutrition, saturation, List.copyOf(effects)));
}
if (plugin.getServer().getPluginManager().isPluginEnabled("ItemsAdder")) {
try {
Class<?> cls = Class.forName("dev.lone.itemsadder.api.CustomStack");
iaLookup = cls.getMethod("byItemStack", ItemStack.class);
iaId = cls.getMethod("getNamespacedID");
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Не удалось подключить API ItemsAdder", e);
}
}
}
public Ingredient read(ItemStack item) {
if (item == null || item.getType().isAir()) return null;
FoodProperties food = item.getData(DataComponentTypes.FOOD);
ItemMeta meta = item.getItemMeta();
Custom match = custom.stream().filter(c -> c.sample.isSimilar(item)).findFirst().orElse(null);
boolean potion = switch (item.getType()) { case POTION, SPLASH_POTION, LINGERING_POTION -> true; default -> false; };
// Cake is edible as a placed block and has no FOOD component.
boolean cake = item.getType() == Material.CAKE;
if (food == null && !potion && match == null && !cake) return null;
int nutrition = food == null ? (cake ? 14 : 0) : food.nutrition();
float saturation = food == null ? (cake ? 2.8f : 0) : food.saturation();
List<ConsumeEffect> effects = new ArrayList<>();
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
if (consumable != null) effects.addAll(consumable.consumeEffects());
Color color = defaultColor;
if (potion && meta instanceof PotionMeta pm) {
if (!pm.getAllEffects().isEmpty()) effects.add(ConsumeEffect.applyStatusEffects(pm.getAllEffects(), 1));
color = pm.computeEffectiveColor();
}
if (meta instanceof SuspiciousStewMeta stew && stew.hasCustomEffects()) {
effects.add(ConsumeEffect.applyStatusEffects(stew.getCustomEffects(), 1));
}
Set<String> tags = new HashSet<>();
tags.add("material:" + item.getType().name().toLowerCase(Locale.ROOT));
if (isCombined(item)) tags.add("soup:combined");
if (match != null) {
nutrition = match.nutrition;
saturation = match.saturation;
tags.add("custom:" + match.id.toLowerCase(Locale.ROOT));
if (!match.effects.isEmpty()) effects.add(ConsumeEffect.applyStatusEffects(match.effects, 1));
}
if (iaLookup != null) try {
Object ia = iaLookup.invoke(null, item);
if (ia != null) tags.add("itemsadder:" + iaId.invoke(ia).toString().toLowerCase(Locale.ROOT));
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Ошибка чтения уникальной еды ItemsAdder", e);
}
for (ConsumeEffect effect : effects) if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
for (PotionEffect pe : apply.effects()) tags.add("effect:" + pe.getType().getKey());
}
return new Ingredient(nutrition, saturation, List.copyOf(effects), Set.copyOf(tags), color);
}
public String rejection(List<ItemStack> items) {
List<Ingredient> data = items.stream().map(this::read).toList();
if (data.contains(null)) return "Предмет больше не зарегистрирован как ингредиент.";
String rule = CombinationRules.rejection(data.stream().map(Ingredient::tags).toList(), blocked, pairs);
if (rule != null) return rule;
long nutrition = data.stream().mapToLong(Ingredient::nutrition).sum();
double saturation = data.stream().mapToDouble(Ingredient::saturation).sum();
if (nutrition > plugin.getConfig().getInt("max-nutrition", 1000)
|| saturation > plugin.getConfig().getDouble("max-saturation", 1000)) return "Превышен лимит питания супа.";
if (data.stream().mapToInt(i -> i.effects.size()).sum() > 256) return "В супе слишком много эффектов.";
return null;
}
public ItemStack brew(List<ItemStack> items) {
String error = rejection(items);
if (error != null) throw new IllegalArgumentException(error);
// Stable order makes the same recipe stack regardless of insertion order.
List<Ingredient> ingredients = items.stream().map(ItemStack::asOne)
.peek(Ingredients::normalize)
.sorted(Comparator.comparing(stack -> Base64.getEncoder().encodeToString(stack.serializeAsBytes())))
.map(this::read).toList();
int nutrition = ingredients.stream().mapToInt(Ingredient::nutrition).sum();
float saturation = (float) ingredients.stream().mapToDouble(Ingredient::saturation).sum();
List<ConsumeEffect> effects = ingredients.stream().flatMap(i -> i.effects.stream()).toList();
ItemStack soup = new ItemStack(Material.MUSHROOM_STEW);
ItemMeta meta = soup.getItemMeta();
meta.displayName(Component.text(plugin.getConfig().getString("soup-name", "Комбинированный суп"), NamedTextColor.GOLD).decoration(TextDecoration.ITALIC, false));
List<Component> lore = new ArrayList<>();
lore.add(line("Голод: +" + nutrition, NamedTextColor.YELLOW));
lore.add(line(String.format(Locale.ROOT, "Насыщение: +%.1f", saturation), NamedTextColor.GOLD));
for (ConsumeEffect effect : effects) {
if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
for (PotionEffect pe : apply.effects()) {
String duration = pe.isInfinite() ? "∞" : (pe.getDuration() / 1200) + ":" + String.format(Locale.ROOT, "%02d", (pe.getDuration() / 20) % 60);
lore.add(Component.translatable(pe.getType().translationKey()).color(NamedTextColor.AQUA)
.append(Component.text(" " + (pe.getAmplifier() + 1) + " • " + duration
+ (apply.probability() < 1 ? " • " + Math.round(apply.probability() * 100) + "%" : "")))
.decoration(TextDecoration.ITALIC, false));
}
} else lore.add(line(effect instanceof ConsumeEffect.TeleportRandomly ? "Случайная телепортация"
: effect instanceof ConsumeEffect.ClearAllStatusEffects ? "Снятие всех эффектов"
: effect instanceof ConsumeEffect.RemoveStatusEffects ? "Снятие эффектов" : "Звук при употреблении", NamedTextColor.GRAY));
}
meta.lore(lore);
meta.getPersistentDataContainer().set(plugin.soupKey, PersistentDataType.BYTE, (byte) 1);
meta.getPersistentDataContainer().set(plugin.colorKey, PersistentDataType.INTEGER, color(ingredients).asRGB());
soup.setItemMeta(meta);
soup.setData(DataComponentTypes.FOOD, FoodProperties.food().nutrition(nutrition).saturation(saturation).canAlwaysEat(true).build());
soup.setData(DataComponentTypes.CONSUMABLE, Consumable.consumable().effects(effects).build());
soup.setData(DataComponentTypes.USE_REMAINDER, UseRemainder.useRemainder(new ItemStack(Material.BOWL)));
normalize(soup);
return soup;
}
private Component line(String s, NamedTextColor color) { return Component.text(s, color).decoration(TextDecoration.ITALIC, false); }
private Color color(List<Ingredient> ingredients) {
return Color.fromRGB((int) ingredients.stream().mapToInt(i -> i.color.getRed()).average().orElse(183),
(int) ingredients.stream().mapToInt(i -> i.color.getGreen()).average().orElse(122),
(int) ingredients.stream().mapToInt(i -> i.color.getBlue()).average().orElse(54));
}
public boolean isCombined(ItemStack item) {
return item.hasItemMeta() && item.getItemMeta().getPersistentDataContainer().has(plugin.soupKey, PersistentDataType.BYTE);
}
public static boolean normalize(ItemStack item) {
if (item == null) return false;
if (switch (item.getType()) { case MUSHROOM_STEW, RABBIT_STEW, BEETROOT_SOUP, SUSPICIOUS_STEW -> true; default -> false; }
&& !Objects.equals(item.getData(DataComponentTypes.MAX_STACK_SIZE), 16)) {
item.setData(DataComponentTypes.MAX_STACK_SIZE, 16);
return true;
}
return false;
}
}
+23
View File
@@ -0,0 +1,23 @@
# Ровно четыре предмета, по одной единице каждого. Повторы разрешены.
# Одна варка дает одну миску: питание и эффекты не размножаются.
require-full-water: true
soup-name: 'Комбинированный суп'
# Цвет поверхности — ближайший оттенок терракоты без ресурспака.
default-color: '#B77A36'
# Ограничения предотвращают переполнение при многократной варке супов из супов.
max-nutrition: 1000
max-saturation: 1000.0
# Селекторы: material:BEEF, effect:minecraft:poison, custom:my_food,
# itemsadder:namespace:id, soup:combined, * (любой ингредиент).
blocked-ingredients: []
# Каждое правило запрещает одновременное присутствие двух РАЗНЫХ слотов.
# incompatible:
# - ['effect:minecraft:strength', 'effect:minecraft:weakness']
# - ['material:ROTTEN_FLESH', 'material:GOLDEN_APPLE']
incompatible: []
# Регистрируется командой /soups register <id> <голод> <насыщение>.
# Сохраняется образец предмета; количество не участвует в сравнении.
# nutrition — единицы голода (2 = один значок), saturation — очки насыщения.
# Необязательные effects: [{type: 'minecraft:strength', duration: 3600, amplifier: 1}]
# duration в тиках; amplifier: 0 = I, 1 = II. Эффекты добавляются к исходным.
custom-ingredients: {}
+16
View File
@@ -0,0 +1,16 @@
name: AstraSoups
version: '${version}'
main: online.astracraft.soups.AstraSoupsPlugin
api-version: '26.2'
description: Four-ingredient cauldron soups with food and potion properties
author: AstraCraft
softdepend: [ItemsAdder]
commands:
soups:
description: Комбинированные супы
usage: /soups [reload|register <id> <голод> <насыщение>]
permissions:
astrasoups.use:
default: true
astrasoups.admin:
default: op
@@ -0,0 +1,30 @@
package online.astracraft.soups;
import org.junit.jupiter.api.Test;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class CombinationRulesTest {
private final List<Set<String>> four = List.of(Set.of("material:beef", "effect:minecraft:strength"), Set.of("material:carrot"), Set.of("material:beef"), Set.of("material:potion", "effect:minecraft:weakness"));
@Test void exactlyFour() {
assertNotNull(CombinationRules.rejection(four.subList(0, 3), List.of(), List.of()));
assertNull(CombinationRules.rejection(four, List.of(), List.of()));
}
@Test void blockedSelectorsAreCaseInsensitive() {
assertNotNull(CombinationRules.rejection(four, List.of("material:BEEF"), List.of()));
}
@Test void compatibilityIsSymmetricAcrossSlots() {
assertNotNull(CombinationRules.rejection(four, List.of(), List.of(List.of("effect:minecraft:weakness", "effect:minecraft:strength"))));
}
@Test void oneIngredientDoesNotConflictWithItself() {
assertNull(CombinationRules.rejection(four, List.of(), List.of(List.of("material:potion", "effect:minecraft:weakness"))));
}
@Test void duplicatesCanBeForbiddenExplicitly() {
assertNotNull(CombinationRules.rejection(four, List.of(), List.of(List.of("material:beef", "material:beef"))));
assertNull(CombinationRules.rejection(four, List.of(), List.of(List.of("material:carrot", "material:carrot"))));
}
@Test void wildcardAndUnknownSelector() {
assertNotNull(CombinationRules.rejection(four, List.of("*"), List.of()));
assertNull(CombinationRules.rejection(four, List.of("custom:other"), List.of()));
}
}