2026-09-05 13:34:00 +03:00
|
|
|
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) {}
|
2026-09-05 15:11:52 +03:00
|
|
|
private record Custom(String id, ItemStack sample, int nutrition, float saturation, List<PotionEffect> effects, Color color) {}
|
2026-09-05 13:34:00 +03:00
|
|
|
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;
|
2026-09-05 15:11:52 +03:00
|
|
|
double seconds = plugin.getConfig().getDouble("brew-seconds", 4.0);
|
|
|
|
|
if (!Double.isFinite(seconds) || seconds < .5 || seconds > 60) {
|
|
|
|
|
throw new IllegalArgumentException("brew-seconds должно быть от 0.5 до 60");
|
|
|
|
|
}
|
|
|
|
|
int servings = plugin.getConfig().getInt("servings-per-brew", 4);
|
|
|
|
|
if (servings < 1 || servings > 16) throw new IllegalArgumentException("servings-per-brew должно быть от 1 до 16");
|
2026-09-05 13:34:00 +03:00
|
|
|
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);
|
2026-09-05 15:11:52 +03:00
|
|
|
Color customColor = c.isString("color") ? Color.fromRGB(Integer.parseInt(c.getString("color").replace("#", ""), 16)) : null;
|
|
|
|
|
custom.add(new Custom(id, sample.asOne(), nutrition, saturation, List.copyOf(effects), customColor));
|
2026-09-05 13:34:00 +03:00
|
|
|
}
|
|
|
|
|
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());
|
2026-09-05 15:11:52 +03:00
|
|
|
Color color = IngredientColors.food(item.getType(), defaultColor);
|
|
|
|
|
if (isCombined(item)) color = Color.fromRGB(meta.getPersistentDataContainer().getOrDefault(plugin.colorKey, PersistentDataType.INTEGER, defaultColor.asRGB()));
|
2026-09-05 13:34:00 +03:00
|
|
|
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));
|
2026-09-05 15:11:52 +03:00
|
|
|
if (match.color != null) color = match.color;
|
2026-09-05 13:34:00 +03:00
|
|
|
}
|
|
|
|
|
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();
|
2026-09-05 15:11:52 +03:00
|
|
|
meta.displayName(Component.text(plugin.getConfig().getString("soup-name", "Комбинированный суп"),
|
|
|
|
|
net.kyori.adventure.text.format.TextColor.color(color(ingredients).asRGB())).decoration(TextDecoration.ITALIC, false));
|
|
|
|
|
meta.lore(soupLore(nutrition, saturation, effects));
|
|
|
|
|
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 static List<Component> soupLore(int nutrition, float saturation, List<ConsumeEffect> effects) {
|
2026-09-05 13:34:00 +03:00
|
|
|
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)
|
2026-09-05 15:11:52 +03:00
|
|
|
.append(Component.text(" " + SoupText.roman(pe.getAmplifier() + 1) + " (" + duration + ")"
|
|
|
|
|
+ (apply.probability() < 1 ? " " + Math.round(apply.probability() * 100) + "%" : "")))
|
2026-09-05 13:34:00 +03:00
|
|
|
.decoration(TextDecoration.ITALIC, false));
|
|
|
|
|
}
|
|
|
|
|
} else lore.add(line(effect instanceof ConsumeEffect.TeleportRandomly ? "Случайная телепортация"
|
|
|
|
|
: effect instanceof ConsumeEffect.ClearAllStatusEffects ? "Снятие всех эффектов"
|
|
|
|
|
: effect instanceof ConsumeEffect.RemoveStatusEffects ? "Снятие эффектов" : "Звук при употреблении", NamedTextColor.GRAY));
|
|
|
|
|
}
|
2026-09-05 15:11:52 +03:00
|
|
|
return lore;
|
2026-09-05 13:34:00 +03:00
|
|
|
}
|
|
|
|
|
|
2026-09-05 15:11:52 +03:00
|
|
|
private static Component line(String s, NamedTextColor color) { return Component.text(s, color).decoration(TextDecoration.ITALIC, false); }
|
2026-09-05 13:34:00 +03:00
|
|
|
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;
|
2026-09-05 15:11:52 +03:00
|
|
|
if (!switch (item.getType()) { case MUSHROOM_STEW, RABBIT_STEW, BEETROOT_SOUP, SUSPICIOUS_STEW -> true; default -> false; }) return false;
|
|
|
|
|
boolean changed = false;
|
|
|
|
|
if (!Objects.equals(item.getData(DataComponentTypes.MAX_STACK_SIZE), 16)) {
|
2026-09-05 13:34:00 +03:00
|
|
|
item.setData(DataComponentTypes.MAX_STACK_SIZE, 16);
|
2026-09-05 15:11:52 +03:00
|
|
|
changed = true;
|
|
|
|
|
}
|
|
|
|
|
ItemMeta meta = item.getItemMeta();
|
|
|
|
|
FoodProperties food = item.getData(DataComponentTypes.FOOD);
|
|
|
|
|
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
|
|
|
|
|
if (meta.getPersistentDataContainer().has(new NamespacedKey("astrasoups", "combined_soup"), PersistentDataType.BYTE)
|
|
|
|
|
&& food != null && consumable != null) {
|
|
|
|
|
List<Component> lore = soupLore(food.nutrition(), food.saturation(), consumable.consumeEffects());
|
|
|
|
|
if (!Objects.equals(meta.lore(), lore)) { meta.lore(lore); item.setItemMeta(meta); changed = true; }
|
2026-09-05 13:34:00 +03:00
|
|
|
}
|
2026-09-05 15:11:52 +03:00
|
|
|
return changed;
|
2026-09-05 13:34:00 +03:00
|
|
|
}
|
|
|
|
|
}
|