Migrate AstraSoups to NeoForge as AstraCauldron
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.mojang.brigadier.arguments.*;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.util.TriState;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.bus.api.EventPriority;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.fml.loading.FMLPaths;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
||||
import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.neoforged.neoforge.event.level.*;
|
||||
import net.neoforged.neoforge.event.server.*;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
import org.slf4j.*;
|
||||
|
||||
@Mod(value = "astracauldron", dist = Dist.DEDICATED_SERVER)
|
||||
public final class AstraCauldron {
|
||||
static final Logger LOG = LoggerFactory.getLogger("AstraCauldron");
|
||||
private static SoupPots pots;
|
||||
private static LiquidPots liquids;
|
||||
public AstraCauldron() {
|
||||
NeoForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::resources);
|
||||
NeoForge.EVENT_BUS.addListener(this::start);
|
||||
NeoForge.EVENT_BUS.addListener(this::stop);
|
||||
NeoForge.EVENT_BUS.addListener(this::tick);
|
||||
NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::interact);
|
||||
NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::breakBlock);
|
||||
NeoForge.EVENT_BUS.addListener(this::explosion);
|
||||
NeoForge.EVENT_BUS.addListener(this::piston);
|
||||
NeoForge.EVENT_BUS.addListener(this::unload);
|
||||
NeoForge.EVENT_BUS.addListener(this::join);
|
||||
NeoForge.EVENT_BUS.addListener(this::commands);
|
||||
}
|
||||
private void resources(ServerAboutToStartEvent event) {
|
||||
try { SoupResources.install(FMLPaths.GAMEDIR.get()); }
|
||||
catch (Exception e) { throw new IllegalStateException("Cannot export AstraCauldron resources", e); }
|
||||
}
|
||||
private void start(ServerStartedEvent event) {
|
||||
try {
|
||||
online.astradev.plus.api.AstraPlusApi.current().orElseThrow(() -> new IllegalStateException("AstraPlus API unavailable"));
|
||||
pots = new SoupPots(event.getServer(), FMLPaths.CONFIGDIR.get().resolve("astracauldron.json"));
|
||||
liquids = new LiquidPots(event.getServer());
|
||||
LOG.info("AstraCauldron ready: NeoForge 26.2, AstraPlus API");
|
||||
} catch (Exception e) { throw new IllegalStateException("Cannot initialize AstraCauldron; existing data preserved", e); }
|
||||
}
|
||||
private void stop(ServerStoppingEvent event) { if (pots != null) pots.close(); if (liquids != null) liquids.close(); pots = null; liquids = null; }
|
||||
private void tick(ServerTickEvent.Post event) { if (pots != null) pots.tick(); if (liquids != null) liquids.tick(); }
|
||||
public static SoupPots pots() { return pots; }
|
||||
public static LiquidPots liquids() { return liquids; }
|
||||
public static boolean occupied(Level level, BlockPos pos) {
|
||||
return level instanceof ServerLevel serverLevel && ((pots != null && pots.contains(serverLevel, pos))
|
||||
|| (liquids != null && liquids.contains(serverLevel,pos)));
|
||||
}
|
||||
private void interact(PlayerInteractEvent.RightClickBlock event) {
|
||||
if (pots == null || event.isCanceled() || event.getUseBlock() == TriState.FALSE || event.getUseItem() == TriState.FALSE) return;
|
||||
if (event.getEntity() instanceof ServerPlayer player && ((!pots.contains(player.level(),event.getPos()) && liquids != null
|
||||
&& liquids.interact(player,event.getPos(),event.getHand())) || pots.interact(player, event.getPos(), event.getHand()))) {
|
||||
event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
}
|
||||
}
|
||||
private void breakBlock(net.neoforged.neoforge.event.level.block.BreakBlockEvent event) {
|
||||
if (!event.isCanceled() && pots != null && event.getLevel() instanceof ServerLevel level
|
||||
&& (!pots.breakPot(level, event.getPos()) || (liquids != null && !liquids.breakPot(level,event.getPos())))) { event.setCanceled(true); event.setNotifyClient(true); }
|
||||
}
|
||||
private void explosion(ExplosionEvent.Detonate event) {
|
||||
if (pots != null && event.getLevel() instanceof ServerLevel level)
|
||||
event.getAffectedBlocks().removeIf(pos -> occupied(level, pos));
|
||||
}
|
||||
private void piston(PistonEvent.Pre event) {
|
||||
if (pots == null || event.isCanceled() || !(event.getLevel() instanceof ServerLevel level)) return;
|
||||
var resolver = event.getStructureHelper();
|
||||
if (resolver != null && resolver.resolve() && (resolver.getToPush().stream().anyMatch(p -> occupied(level, p))
|
||||
|| resolver.getToDestroy().stream().anyMatch(p -> occupied(level, p)))) event.setCanceled(true);
|
||||
}
|
||||
private void unload(ChunkEvent.Unload event) {
|
||||
if (pots != null && event.getLevel() instanceof ServerLevel level)
|
||||
pots.unload(level, event.getChunk().getPos().x(), event.getChunk().getPos().z());
|
||||
}
|
||||
private void join(EntityJoinLevelEvent event) {
|
||||
if (event.loadedFromDisk() && event.getEntity().entityTags().contains(SoupDisplay.TAG)) event.setCanceled(true);
|
||||
else if (event.getEntity() instanceof ItemEntity item) Ingredients.normalize(item.getItem());
|
||||
}
|
||||
private void commands(RegisterCommandsEvent event) {
|
||||
var command = Commands.literal("cauldron").executes(c -> {
|
||||
c.getSource().sendSuccess(() -> Component.literal("Краситель + вода: окрашивание брони. Зелье + пустой котёл: хранение и стрелы с эффектом. Еда/зелья + полный котёл воды: 4 ингредиента супа, Shift+ПКМ — варка, миска — порция."), false); return 1;
|
||||
});
|
||||
command.then(Commands.literal("reload").requires(Commands.hasPermission(Commands.LEVEL_ADMINS)).executes(c -> {
|
||||
try { requirePots().reload(); c.getSource().sendSuccess(() -> Component.literal("AstraCauldron: настройки применены."), true); return 1; }
|
||||
catch (Exception e) { c.getSource().sendFailure(Component.literal("Ошибка: " + e.getMessage() + ". Прежние настройки сохранены.")); return 0; }
|
||||
}));
|
||||
command.then(Commands.literal("register").requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
||||
.then(Commands.argument("id", StringArgumentType.word()).then(Commands.argument("nutrition", IntegerArgumentType.integer(0))
|
||||
.then(Commands.argument("saturation", FloatArgumentType.floatArg(0)).executes(c -> {
|
||||
try {
|
||||
requirePots().register(StringArgumentType.getString(c, "id"), c.getSource().getPlayerOrException(),
|
||||
IntegerArgumentType.getInteger(c, "nutrition"), FloatArgumentType.getFloat(c, "saturation"));
|
||||
c.getSource().sendSuccess(() -> Component.literal("Ингредиент зарегистрирован."), true); return 1;
|
||||
} catch (Exception e) { c.getSource().sendFailure(Component.literal("Ошибка регистрации: " + e.getMessage())); return 0; }
|
||||
})))));
|
||||
var root = event.getDispatcher().register(command);
|
||||
event.getDispatcher().register(Commands.literal("soups").redirect(root).executes(root.getCommand()));
|
||||
}
|
||||
private static SoupPots requirePots() { if (pots == null) throw new IllegalStateException("AstraCauldron ещё не запущен"); return pots; }
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package online.astradev.soups;
|
||||
package online.astradev.cauldron;
|
||||
|
||||
/** ItemDisplay centers relative to the cauldron, without native dropped-item physics or bobbing. */
|
||||
public final class CauldronAnimation {
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package online.astradev.soups;
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
@@ -0,0 +1,41 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
|
||||
|
||||
|
||||
final class IngredientColors {
|
||||
private IngredientColors() {}
|
||||
|
||||
static int food(String material, int fallback) {
|
||||
int rgb =
|
||||
switch (material) {
|
||||
case "spider_eye", "fermented_spider_eye" -> 0xB52B38;
|
||||
case "golden_apple", "enchanted_golden_apple", "golden_carrot" -> 0xF2C94C;
|
||||
case "apple", "sweet_berries" -> 0xC73735;
|
||||
case "beetroot", "beetroot_soup" -> 0xA52B4B;
|
||||
case "carrot", "pumpkin_pie", "glow_berries" -> 0xE99032;
|
||||
case "dried_kelp" -> 0x47733B;
|
||||
case "poisonous_potato" -> 0x91A340;
|
||||
case "melon_slice" -> 0xD94E58;
|
||||
case "chorus_fruit" -> 0x9C6C9D;
|
||||
case "beef", "mutton", "porkchop", "rabbit" -> 0xC76B70;
|
||||
case "chicken" -> 0xE2A6A0;
|
||||
case "cooked_beef", "cooked_mutton" -> 0x815033;
|
||||
case "cooked_porkchop", "cooked_rabbit", "cooked_chicken" -> 0xBA8551;
|
||||
case "salmon", "cooked_salmon", "tropical_fish" -> 0xD98262;
|
||||
case "cod" -> 0xB0A07B;
|
||||
case "cooked_cod" -> 0xC4B486;
|
||||
case "pufferfish" -> 0xD3B54D;
|
||||
case "bread", "cookie", "baked_potato" -> 0xBA873F;
|
||||
case "potato" -> 0xC7A76B;
|
||||
case "rotten_flesh" -> 0x8F6540;
|
||||
case "honey_bottle" -> 0xE9AC32;
|
||||
case "cake" -> 0xE8CCBA;
|
||||
case "mushroom_stew" -> 0xA37A53;
|
||||
case "rabbit_stew" -> 0xAC8854;
|
||||
case "suspicious_stew" -> 0x867743;
|
||||
default -> fallback;
|
||||
};
|
||||
return rgb;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import java.util.*;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.world.effect.MobEffectInstance;
|
||||
import net.minecraft.world.food.FoodProperties;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.component.*;
|
||||
import net.minecraft.world.item.consume_effects.*;
|
||||
import online.astradev.plus.api.AstraPlusApi;
|
||||
|
||||
public final class Ingredients {
|
||||
public record Ingredient(int nutrition, float saturation, List<ConsumeEffect> effects, Set<String> tags, int color) {}
|
||||
private record Custom(String id, ItemStack sample, SoupConfig.Custom definition, List<MobEffectInstance> effects) {}
|
||||
private final SoupConfig config;
|
||||
private final HolderLookup.Provider registries;
|
||||
private final List<Custom> custom = new ArrayList<>();
|
||||
public Ingredients(SoupConfig config, HolderLookup.Provider registries) {
|
||||
config.validate();
|
||||
this.config = config;
|
||||
this.registries = registries;
|
||||
for (var entry : config.customIngredients.entrySet()) {
|
||||
var c = entry.getValue();
|
||||
ItemStack sample = c.item == null ? ItemStack.EMPTY : SoupFiles.decode(c.item, registries);
|
||||
if (c.item != null && (sample.isEmpty() || sample.getCount() != 1))
|
||||
throw new IllegalArgumentException("Некорректный образец " + entry.getKey());
|
||||
normalize(sample);
|
||||
List<MobEffectInstance> effects = new ArrayList<>();
|
||||
for (var e : c.effects) {
|
||||
var type = BuiltInRegistries.MOB_EFFECT.get(Identifier.parse(e.type)).orElseThrow();
|
||||
effects.add(new MobEffectInstance(type, e.duration, e.amplifier));
|
||||
}
|
||||
custom.add(new Custom(entry.getKey(), sample, c, List.copyOf(effects)));
|
||||
}
|
||||
}
|
||||
public Ingredient read(ItemStack stack) {
|
||||
if (stack.isEmpty()) return null;
|
||||
var plus = AstraPlusApi.current().flatMap(api -> api.find(stack));
|
||||
Custom match = custom.stream().filter(c -> c.definition.astraPlusId != null
|
||||
? plus.map(p -> p.id().toString().equals(c.definition.astraPlusId)).orElse(false)
|
||||
: ItemStack.isSameItemSameComponents(c.sample, normalizedCopy(stack))).findFirst().orElse(null);
|
||||
var food = stack.get(DataComponents.FOOD);
|
||||
boolean potion = stack.is(Items.POTION) || stack.is(Items.SPLASH_POTION) || stack.is(Items.LINGERING_POTION);
|
||||
boolean cake = stack.is(Items.CAKE);
|
||||
if (food == null && !potion && !cake && match == null) return null;
|
||||
int nutrition = food == null ? (cake ? 14 : 0) : food.nutrition();
|
||||
float saturation = food == null ? (cake ? 2.8f : 0) : food.saturation();
|
||||
var effects = new ArrayList<ConsumeEffect>();
|
||||
var consumable = stack.get(DataComponents.CONSUMABLE);
|
||||
if (consumable != null) effects.addAll(consumable.onConsumeEffects());
|
||||
String material = BuiltInRegistries.ITEM.getKey(stack.getItem()).getPath();
|
||||
int color = IngredientColors.food(material, SoupConfig.rgb(config.defaultColor));
|
||||
if (isCombined(stack)) color = color(stack);
|
||||
var contents = stack.get(DataComponents.POTION_CONTENTS);
|
||||
if (potion && contents != null) {
|
||||
List<MobEffectInstance> potionEffects = new ArrayList<>();
|
||||
contents.forEachEffect(potionEffects::add, stack.transmuteCopy(Items.POTION, 1).getOrDefault(DataComponents.POTION_DURATION_SCALE, 1f));
|
||||
if (!potionEffects.isEmpty()) effects.add(new ApplyStatusEffectsConsumeEffect(potionEffects));
|
||||
color = contents.getColor() & 0xFFFFFF;
|
||||
}
|
||||
var stew = stack.get(DataComponents.SUSPICIOUS_STEW_EFFECTS);
|
||||
if (stew != null && !stew.effects().isEmpty())
|
||||
effects.add(new ApplyStatusEffectsConsumeEffect(stew.effects().stream().map(SuspiciousStewEffects.Entry::createEffectInstance).toList()));
|
||||
Set<String> tags = new HashSet<>();
|
||||
tags.add("material:" + material);
|
||||
if (isCombined(stack)) tags.add("soup:combined");
|
||||
plus.ifPresent(p -> tags.add("astraplus:" + p.id()));
|
||||
if (match != null) {
|
||||
nutrition = match.definition.nutrition;
|
||||
saturation = match.definition.saturation;
|
||||
if (match.definition.color != null) color = SoupConfig.rgb(match.definition.color);
|
||||
if (!match.effects.isEmpty()) effects.add(new ApplyStatusEffectsConsumeEffect(match.effects));
|
||||
tags.add("custom:" + match.id);
|
||||
}
|
||||
for (var effect : effects) if (effect instanceof ApplyStatusEffectsConsumeEffect apply)
|
||||
for (var e : apply.effects()) tags.add("effect:" + BuiltInRegistries.MOB_EFFECT.getKey(e.getEffect().value()));
|
||||
return new Ingredient(nutrition, saturation, List.copyOf(effects), Set.copyOf(tags), color);
|
||||
}
|
||||
public String rejection(List<ItemStack> items) {
|
||||
var data = items.stream().map(this::read).toList();
|
||||
if (data.contains(null)) return "Предмет больше не зарегистрирован как ингредиент.";
|
||||
String error = CombinationRules.rejection(data.stream().map(Ingredient::tags).toList(), config.blockedIngredients, config.incompatible);
|
||||
if (error != null) return error;
|
||||
long nutrition = data.stream().mapToLong(Ingredient::nutrition).sum();
|
||||
double saturation = data.stream().mapToDouble(Ingredient::saturation).sum();
|
||||
if (nutrition < 0 || nutrition > config.maxNutrition || !Double.isFinite(saturation)
|
||||
|| saturation < 0 || saturation > config.maxSaturation) 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);
|
||||
var data = items.stream().map(Ingredients::normalizedCopy)
|
||||
.sorted(Comparator.comparing(s -> SoupFiles.encode(s, registries).toString())).map(this::read).toList();
|
||||
int nutrition = data.stream().mapToInt(Ingredient::nutrition).sum();
|
||||
float saturation = (float) data.stream().mapToDouble(Ingredient::saturation).sum();
|
||||
var effects = data.stream().flatMap(i -> i.effects.stream()).toList();
|
||||
int rgb = averageColor(data.stream().mapToInt(Ingredient::color).toArray());
|
||||
var soup = new ItemStack(Items.MUSHROOM_STEW);
|
||||
CustomData.update(DataComponents.CUSTOM_DATA, soup, tag -> {
|
||||
tag.putBoolean("astracauldron:combined_soup", true);
|
||||
tag.putInt("astracauldron:soup_color", rgb);
|
||||
});
|
||||
soup.set(DataComponents.CUSTOM_NAME, Component.literal(config.soupName).withStyle(s -> s.withColor(rgb).withItalic(false)));
|
||||
soup.set(DataComponents.FOOD, new FoodProperties(nutrition, saturation, true));
|
||||
var base = Objects.requireNonNull(soup.get(DataComponents.CONSUMABLE));
|
||||
soup.set(DataComponents.CONSUMABLE, new Consumable(base.consumeSeconds(), base.animation(), base.sound(), base.hasConsumeParticles(), effects));
|
||||
soup.set(DataComponents.USE_REMAINDER, new UseRemainder(ItemStackTemplate.fromNonEmptyStack(new ItemStack(Items.BOWL))));
|
||||
normalize(soup);
|
||||
return soup;
|
||||
}
|
||||
static int averageColor(int[] colors) {
|
||||
int r = 0, g = 0, b = 0;
|
||||
for (int c : colors) { r += (c >> 16) & 255; g += (c >> 8) & 255; b += c & 255; }
|
||||
return ((r / colors.length) << 16) | ((g / colors.length) << 8) | (b / colors.length);
|
||||
}
|
||||
public static boolean isCombined(ItemStack stack) {
|
||||
return stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag().getBooleanOr("astracauldron:combined_soup", false);
|
||||
}
|
||||
public static int color(ItemStack stack) {
|
||||
return stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag().getIntOr("astracauldron:soup_color", 0xB77A36) & 0xFFFFFF;
|
||||
}
|
||||
static ItemStack normalizedCopy(ItemStack stack) {
|
||||
var copy = stack.copyWithCount(1); normalize(copy); return copy;
|
||||
}
|
||||
public static void normalize(ItemStack stack) {
|
||||
if (!(stack.is(Items.MUSHROOM_STEW) || stack.is(Items.RABBIT_STEW) || stack.is(Items.BEETROOT_SOUP) || stack.is(Items.SUSPICIOUS_STEW))) return;
|
||||
stack.set(DataComponents.MAX_STACK_SIZE, 16);
|
||||
if (!isCombined(stack)) return;
|
||||
stack.set(DataComponents.ITEM_MODEL, Identifier.parse("astradev_soups:combined_soup"));
|
||||
var data = stack.getOrDefault(DataComponents.CUSTOM_MODEL_DATA, CustomModelData.EMPTY);
|
||||
var colors = new ArrayList<>(data.colors());
|
||||
if (colors.isEmpty()) colors.add(color(stack)); else colors.set(0, color(stack));
|
||||
stack.set(DataComponents.CUSTOM_MODEL_DATA, new CustomModelData(data.floats(), data.flags(), data.strings(), colors));
|
||||
var food = stack.get(DataComponents.FOOD);
|
||||
var consumable = stack.get(DataComponents.CONSUMABLE);
|
||||
if (food != null && consumable != null) stack.set(DataComponents.LORE, new ItemLore(lore(food, consumable.onConsumeEffects())));
|
||||
}
|
||||
private static List<Component> lore(FoodProperties food, List<ConsumeEffect> effects) {
|
||||
var lines = new ArrayList<Component>();
|
||||
lines.add(line("Голод: +" + food.nutrition(), ChatFormatting.YELLOW));
|
||||
lines.add(line(String.format(Locale.ROOT, "Насыщение: +%.1f", food.saturation()), ChatFormatting.GOLD));
|
||||
for (var effect : effects) {
|
||||
if (effect instanceof ApplyStatusEffectsConsumeEffect apply) for (var e : apply.effects()) {
|
||||
String duration = e.isInfiniteDuration() ? "∞" : String.format(Locale.ROOT, "%d:%02d", e.getDuration() / 1200, (e.getDuration() / 20) % 60);
|
||||
lines.add(Component.translatable(e.getDescriptionId()).append(" " + SoupText.roman(e.getAmplifier() + 1) + " (" + duration + ")"
|
||||
+ (apply.probability() < 1 ? " " + Math.round(apply.probability() * 100) + "%" : ""))
|
||||
.withStyle(s -> s.withColor(ChatFormatting.AQUA).withItalic(false)));
|
||||
} else lines.add(line(effect instanceof TeleportRandomlyConsumeEffect ? "Случайная телепортация"
|
||||
: effect instanceof ClearAllStatusEffectsConsumeEffect ? "Снятие всех эффектов"
|
||||
: effect instanceof RemoveStatusEffectsConsumeEffect ? "Снятие эффектов" : "Звук при употреблении", ChatFormatting.GRAY));
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
private static Component line(String text, ChatFormatting color) {
|
||||
return Component.literal(text).withStyle(s -> s.withColor(color).withItalic(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.*;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.*;
|
||||
import net.minecraft.sounds.*;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.alchemy.Potions;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
import online.astradev.plus.api.*;
|
||||
|
||||
/** Persistent dyed water and potion storage; all item transformations and rendering use AstraPlus API. */
|
||||
public final class LiquidPots implements AutoCloseable {
|
||||
private record Position(String dimension, BlockPos pos) {
|
||||
static Position at(ServerLevel level, BlockPos pos) { return new Position(level.dimension().identifier().toString(), pos.immutable()); }
|
||||
}
|
||||
public record Liquid(int levels, int rgb, CauldronApi.Potion potion) {
|
||||
public Liquid {
|
||||
if (levels < 1 || levels > 3 || rgb < 0 || rgb > 0xFFFFFF) throw new IllegalArgumentException("Invalid liquid");
|
||||
}
|
||||
Liquid withLevels(int value) { return new Liquid(value, rgb, potion); }
|
||||
}
|
||||
private static final Identifier OWNER = Identifier.parse("astracauldron:liquids");
|
||||
private final MinecraftServer server;
|
||||
private final CauldronApi api;
|
||||
private final Path file;
|
||||
private final Map<Position, Liquid> liquids = new LinkedHashMap<>();
|
||||
public LiquidPots(MinecraftServer server) throws IOException {
|
||||
this.server = server;
|
||||
api = AstraPlusApi.current().flatMap(AstraPlusApi::cauldrons).orElseThrow();
|
||||
file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/liquids.json");
|
||||
if (Files.exists(file)) {
|
||||
var json = JsonParser.parseString(Files.readString(file)).getAsJsonObject();
|
||||
if (json.get("version").getAsInt() != 1) throw new IllegalArgumentException("Unknown liquid data version");
|
||||
for (var entry : json.getAsJsonArray("cauldrons")) {
|
||||
var c = entry.getAsJsonObject();
|
||||
var pos = new Position(Identifier.parse(c.get("dimension").getAsString()).toString(), new BlockPos(c.get("x").getAsInt(), c.get("y").getAsInt(), c.get("z").getAsInt()));
|
||||
CauldronApi.Potion potion = c.has("potion") ? api.potion(SoupFiles.decode(c.get("potion"), server.registryAccess())).orElseThrow() : null;
|
||||
var liquid = new Liquid(c.get("levels").getAsInt(), c.get("rgb").getAsInt(), potion);
|
||||
if (liquids.putIfAbsent(pos, liquid) != null) throw new IllegalArgumentException("Duplicate liquid cauldron");
|
||||
}
|
||||
}
|
||||
}
|
||||
public Liquid get(ServerLevel level, BlockPos pos) { return liquids.get(Position.at(level, pos)); }
|
||||
public boolean contains(ServerLevel level, BlockPos pos) { return get(level, pos) != null; }
|
||||
private boolean change(Position pos, Liquid next) {
|
||||
var old = liquids.get(pos);
|
||||
if (next == null) liquids.remove(pos); else liquids.put(pos, next);
|
||||
try {
|
||||
var root = new JsonObject(); root.addProperty("version", 1); var array = new JsonArray(); root.add("cauldrons", array);
|
||||
for (var entry : liquids.entrySet()) {
|
||||
var p = entry.getKey(); var liquid = entry.getValue(); var c = new JsonObject();
|
||||
c.addProperty("dimension", p.dimension); c.addProperty("x", p.pos.getX()); c.addProperty("y", p.pos.getY()); c.addProperty("z", p.pos.getZ());
|
||||
c.addProperty("levels", liquid.levels); c.addProperty("rgb", liquid.rgb);
|
||||
if (liquid.potion != null) c.add("potion", SoupFiles.encode(api.bottle(liquid.potion), server.registryAccess()));
|
||||
array.add(c);
|
||||
}
|
||||
SoupFiles.write(file, root);
|
||||
if (next == null) removeSurface(pos);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
if (old == null) liquids.remove(pos); else liquids.put(pos, old);
|
||||
AstraCauldron.LOG.error("Не удалось сохранить жидкость; действие отменено", e); return false;
|
||||
}
|
||||
}
|
||||
public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) {
|
||||
if (player.isSpectator()) return false;
|
||||
var level = player.level(); var pos = Position.at(level, blockPos); var liquid = liquids.get(pos);
|
||||
if (hand != InteractionHand.MAIN_HAND) return liquid != null;
|
||||
var state = level.getBlockState(blockPos); var held = player.getMainHandItem();
|
||||
if (!state.is(Blocks.CAULDRON) && !state.is(Blocks.WATER_CAULDRON)) return false;
|
||||
var potion = api.potion(held);
|
||||
if (liquid == null) {
|
||||
if (potion.isPresent() && plainWater(potion.get())) {
|
||||
int current = state.is(Blocks.WATER_CAULDRON) ? state.getValue(LayeredCauldronBlock.LEVEL) : 0;
|
||||
if (current < 3) {
|
||||
level.setBlock(blockPos,Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL,current+1),3);
|
||||
consumeAndGive(player,1,new ItemStack(Items.GLASS_BOTTLE));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
var dye = api.mixDye(OptionalInt.empty(), held);
|
||||
if (state.is(Blocks.WATER_CAULDRON) && dye.isPresent()) {
|
||||
var next = new Liquid(state.getValue(LayeredCauldronBlock.LEVEL), dye.getAsInt(), null);
|
||||
if (!change(pos, next)) { error(player); return true; }
|
||||
held.consume(1, player); setVisual(level, pos, next);
|
||||
say(player, "Вода окрашена. Добавьте краситель для смешивания или окуните кожаную броню."); return true;
|
||||
}
|
||||
if (state.is(Blocks.CAULDRON) && potion.isPresent()) {
|
||||
var next = new Liquid(1, potion.get().contents().getColor() & 0xFFFFFF, potion.get());
|
||||
if (!change(pos, next)) { error(player); return true; }
|
||||
consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE)); setVisual(level, pos, next);
|
||||
say(player, "Зелье налито: 1/3. Бутылочка — забрать, стрелы — обработать."); return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (liquid.potion == null) {
|
||||
var dye = api.mixDye(OptionalInt.of(liquid.rgb), held);
|
||||
if (dye.isPresent()) {
|
||||
var next = new Liquid(liquid.levels, dye.getAsInt(), null);
|
||||
if (!change(pos, next)) { error(player); return true; }
|
||||
held.consume(1, player); setVisual(level,pos,next); return true;
|
||||
}
|
||||
var armor = api.dyeArmor(held, liquid.rgb);
|
||||
if (armor.isPresent()) {
|
||||
if (!decrease(level,pos,liquid,1)) { error(player); return true; }
|
||||
// Transform the equipped item, including Creative, preserving enchantments/damage/name.
|
||||
if (held.getCount() == 1) player.setItemInHand(hand, armor.get()); else consumeAndGive(player,1,armor.get());
|
||||
sound(level,blockPos); say(player,"Броня окрашена. Израсходован один уровень воды."); return true;
|
||||
}
|
||||
if (held.is(Items.WATER_BUCKET)) {
|
||||
if (!change(pos,null)) { error(player); return true; }
|
||||
level.setBlock(blockPos, Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL,3),3);
|
||||
consumeAndGive(player,1,new ItemStack(Items.BUCKET)); return true;
|
||||
}
|
||||
if (held.is(Items.BUCKET) && liquid.levels == 3) {
|
||||
if (!decrease(level,pos,liquid,3)) { error(player); return true; }
|
||||
consumeAndGive(player,1,new ItemStack(Items.WATER_BUCKET)); return true;
|
||||
}
|
||||
if (held.is(Items.GLASS_BOTTLE)) {
|
||||
if (!decrease(level,pos,liquid,1)) { error(player); return true; }
|
||||
consumeAndGive(player,1,api.bottle(new CauldronApi.Potion(new net.minecraft.world.item.alchemy.PotionContents(Potions.WATER),1))); return true;
|
||||
}
|
||||
say(player,"Цветная вода: " + liquid.levels + "/3. Для варки супа нужна чистая вода."); return true;
|
||||
}
|
||||
if (potion.isPresent()) {
|
||||
if (!potion.get().equals(liquid.potion)) { say(player,"В котле другое зелье. Сначала заберите его бутылочками."); return true; }
|
||||
if (liquid.levels == 3) { say(player,"Котёл уже полон."); return true; }
|
||||
var next = liquid.withLevels(liquid.levels + 1);
|
||||
if (!change(pos,next)) { error(player); return true; }
|
||||
consumeAndGive(player,1,new ItemStack(Items.GLASS_BOTTLE)); setVisual(level,pos,next); return true;
|
||||
}
|
||||
if (held.is(Items.GLASS_BOTTLE)) {
|
||||
var bottle = api.bottle(liquid.potion);
|
||||
if (!decrease(level,pos,liquid,1)) { error(player); return true; }
|
||||
consumeAndGive(player,1,bottle); sound(level,blockPos); return true;
|
||||
}
|
||||
var arrows = api.tipArrows(held,liquid.potion,liquid.levels);
|
||||
if (arrows.isPresent()) {
|
||||
var batch = arrows.get(); var result = batch.result();
|
||||
if (!decrease(level,pos,liquid,batch.levelsUsed())) { error(player); return true; }
|
||||
int count = result.getCount();
|
||||
consumeAndGive(player,count,result); sound(level,blockPos);
|
||||
say(player,"Обработано стрел: " + count + "."); return true;
|
||||
}
|
||||
say(player,"Зелье: " + liquid.levels + "/3. Окуните обычные стрелы или наберите бутылочку."); return true;
|
||||
}
|
||||
private boolean decrease(ServerLevel level, Position pos, Liquid old, int used) {
|
||||
int remaining = old.levels - used; var next = remaining == 0 ? null : old.withLevels(remaining);
|
||||
if (!change(pos,next)) return false;
|
||||
level.setBlock(pos.pos,Blocks.CAULDRON.defaultBlockState(),3);
|
||||
if (next != null) setVisual(level,pos,next); return true;
|
||||
}
|
||||
private static boolean plainWater(CauldronApi.Potion potion) {
|
||||
var contents = potion.contents();
|
||||
return contents.is(Potions.WATER) && contents.customColor().isEmpty() && contents.customName().isEmpty() && potion.durationScale()==1f;
|
||||
}
|
||||
public boolean breakPot(ServerLevel level,BlockPos pos) { var position = Position.at(level,pos); return !liquids.containsKey(position) || change(position,null); }
|
||||
public void tick() {
|
||||
for (var entry : new ArrayList<>(liquids.entrySet())) {
|
||||
var pos=entry.getKey(); var level=level(pos);
|
||||
if (level==null || !level.hasChunkAt(pos.pos)) continue;
|
||||
if (!level.getBlockState(pos.pos).is(Blocks.CAULDRON)) { change(pos,null); continue; }
|
||||
surface(level,pos,entry.getValue());
|
||||
}
|
||||
}
|
||||
private void setVisual(ServerLevel level,Position pos,Liquid liquid) {
|
||||
level.setBlock(pos.pos,Blocks.CAULDRON.defaultBlockState(),3); surface(level,pos,liquid);
|
||||
}
|
||||
private void surface(ServerLevel level,Position pos,Liquid liquid) {
|
||||
api.water().show(level,pos.pos,new ColoredWaterApi.Surface(OWNER,liquid.rgb,.375f+.1875f*liquid.levels));
|
||||
}
|
||||
private ServerLevel level(Position pos) { return server.getLevel(ResourceKey.create(Registries.DIMENSION,Identifier.parse(pos.dimension))); }
|
||||
private void removeSurface(Position pos) { var level=level(pos); if(level!=null) api.water().remove(level,pos.pos,OWNER); }
|
||||
@Override public void close() { api.water().removeAll(OWNER); }
|
||||
private static void consumeAndGive(ServerPlayer player,int count,ItemStack result) {
|
||||
player.getMainHandItem().consume(count,player);
|
||||
player.getInventory().add(result); if(!result.isEmpty()) player.drop(result,false);
|
||||
player.containerMenu.broadcastChanges();
|
||||
}
|
||||
private static void sound(ServerLevel level,BlockPos pos) { level.playSound(null,pos,SoundEvents.BOTTLE_FILL,SoundSource.BLOCKS,.8f,1); }
|
||||
private static void say(ServerPlayer player,String text) { player.sendSystemMessage(Component.literal(text).withStyle(ChatFormatting.GOLD),true); }
|
||||
private static void error(ServerPlayer player) { say(player,"Не удалось сохранить котёл. Действие отменено."); }
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
public final class SoupConfig {
|
||||
public int servingsPerBrew = 4;
|
||||
public boolean requireFullWater = true;
|
||||
public double brewSeconds = 4;
|
||||
public String soupName = "Комбинированный суп";
|
||||
public String defaultColor = "#B77A36";
|
||||
public int maxNutrition = 1000;
|
||||
public float maxSaturation = 1000;
|
||||
public List<String> blockedIngredients = new ArrayList<>();
|
||||
public List<List<String>> incompatible = new ArrayList<>();
|
||||
public Map<String, Custom> customIngredients = new LinkedHashMap<>();
|
||||
public static final class Custom {
|
||||
public JsonElement item;
|
||||
public String astraPlusId;
|
||||
public int nutrition;
|
||||
public float saturation;
|
||||
public String color;
|
||||
public List<Effect> effects = new ArrayList<>();
|
||||
}
|
||||
public static final class Effect {
|
||||
public String type;
|
||||
public int duration;
|
||||
public int amplifier;
|
||||
}
|
||||
public static SoupConfig load(Path file) throws IOException {
|
||||
SoupConfig config = Files.exists(file)
|
||||
? SoupFiles.JSON.fromJson(Files.readString(file), SoupConfig.class) : new SoupConfig();
|
||||
if (config == null) throw new IllegalArgumentException("Пустая конфигурация");
|
||||
config.validate();
|
||||
if (!Files.exists(file)) SoupFiles.write(file, SoupFiles.JSON.toJsonTree(config));
|
||||
return config;
|
||||
}
|
||||
public void validate() {
|
||||
if (servingsPerBrew < 1 || servingsPerBrew > 16 || !Double.isFinite(brewSeconds)
|
||||
|| brewSeconds < .5 || brewSeconds > 60 || maxNutrition < 0
|
||||
|| !Float.isFinite(maxSaturation) || maxSaturation < 0 || soupName == null || soupName.isBlank())
|
||||
throw new IllegalArgumentException("Некорректные настройки варки/питания");
|
||||
rgb(defaultColor);
|
||||
if (blockedIngredients == null || incompatible == null || customIngredients == null)
|
||||
throw new IllegalArgumentException("Списки настроек не могут быть null");
|
||||
blockedIngredients.forEach(SoupConfig::selector);
|
||||
for (var pair : incompatible) {
|
||||
if (pair == null || pair.size() != 2) throw new IllegalArgumentException("В incompatible нужны пары");
|
||||
pair.forEach(SoupConfig::selector);
|
||||
}
|
||||
for (var entry : customIngredients.entrySet()) {
|
||||
var c = entry.getValue();
|
||||
if (!entry.getKey().matches("[a-z0-9_-]+") || c == null || (c.item == null) == (c.astraPlusId == null)
|
||||
|| c.nutrition < 0 || c.nutrition > maxNutrition || !Float.isFinite(c.saturation)
|
||||
|| c.saturation < 0 || c.saturation > maxSaturation || c.effects == null)
|
||||
throw new IllegalArgumentException("Некорректный ингредиент " + entry.getKey());
|
||||
if (c.astraPlusId != null && !c.astraPlusId.matches("[a-z0-9_.-]+:[a-z0-9/._-]+"))
|
||||
throw new IllegalArgumentException("Некорректный AstraPlus ID");
|
||||
if (c.color != null) rgb(c.color);
|
||||
for (var e : c.effects) if (e == null || e.type == null || e.duration < -1 || e.duration == 0
|
||||
|| e.amplifier < 0 || e.amplifier > 255) throw new IllegalArgumentException("Некорректный эффект");
|
||||
}
|
||||
}
|
||||
private static void selector(String s) {
|
||||
if (s == null || !s.toLowerCase(Locale.ROOT).matches("\\*|(?:material|effect|custom|astraplus|soup):[a-z0-9_:./-]+"))
|
||||
throw new IllegalArgumentException("Неизвестный селектор: " + s);
|
||||
}
|
||||
static int rgb(String s) {
|
||||
if (s == null || !s.matches("#[0-9a-fA-F]{6}")) throw new IllegalArgumentException("Цвет: #RRGGBB");
|
||||
return Integer.parseInt(s.substring(1), 16);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.mojang.math.Transformation;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
|
||||
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.Display;
|
||||
import net.minecraft.world.entity.EntityTypes;
|
||||
import net.minecraft.world.item.*;
|
||||
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
final class SoupDisplay extends Display.ItemDisplay {
|
||||
static final String TAG = "astracauldron:cauldron_visual";
|
||||
SoupDisplay(ServerLevel level, BlockPos pos, ItemStack stack) {
|
||||
super(EntityTypes.ITEM_DISPLAY, level);
|
||||
setPos(pos.getX() + .5, pos.getY() + .5, pos.getZ() + .5);
|
||||
getSlot(0).set(stack.copy());
|
||||
setItemTransform(ItemDisplayContext.FIXED);
|
||||
setNoGravity(true);
|
||||
setInvulnerable(true);
|
||||
setSilent(true);
|
||||
addTag(TAG);
|
||||
setTransformationInterpolationDuration(2);
|
||||
}
|
||||
void ingredient(int slot, int water, int ticks, int elapsed, int duration) {
|
||||
var frame = CauldronAnimation.frame(slot, water, ticks, elapsed, duration);
|
||||
setTransformationInterpolationDelay(0);
|
||||
setTransformation(new Transformation(new Vector3f((float)frame.x() - .5f, (float)frame.y() - .5f, (float)frame.z() - .5f),
|
||||
new Quaternionf(), new Vector3f(.3f), new Quaternionf().rotationY(ticks * .035f + slot)));
|
||||
}
|
||||
@Override public boolean shouldBeSaved() { return false; }
|
||||
@Override public boolean saveAsPassenger(ValueOutput output) { return false; }
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
|
||||
final class SoupFiles {
|
||||
static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||
private SoupFiles() {}
|
||||
static void write(Path path, JsonElement json) throws IOException {
|
||||
Files.createDirectories(path.getParent());
|
||||
Path temp = Files.createTempFile(path.getParent(), "soups-", ".tmp");
|
||||
try {
|
||||
Files.writeString(temp, JSON.toJson(json));
|
||||
try { Files.move(temp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||
catch (AtomicMoveNotSupportedException e) { Files.move(temp, path, StandardCopyOption.REPLACE_EXISTING); }
|
||||
} finally { Files.deleteIfExists(temp); }
|
||||
}
|
||||
static JsonElement encode(ItemStack stack, HolderLookup.Provider registries) {
|
||||
return ItemStack.CODEC.encodeStart(RegistryOps.create(JsonOps.INSTANCE, registries), stack).getOrThrow();
|
||||
}
|
||||
static ItemStack decode(JsonElement json, HolderLookup.Provider registries) {
|
||||
return ItemStack.CODEC.parse(RegistryOps.create(JsonOps.INSTANCE, registries), json).getOrThrow();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.particles.ParticleTypes;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.*;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.*;
|
||||
import net.minecraft.sounds.*;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
|
||||
public final class SoupPots implements AutoCloseable {
|
||||
record Position(String dimension, BlockPos pos) {
|
||||
static Position at(ServerLevel level, BlockPos pos) { return new Position(level.dimension().identifier().toString(), pos.immutable()); }
|
||||
}
|
||||
public record Pot(List<ItemStack> items, ItemStack soup, int brewTicks, int servings, int capacity) {
|
||||
public Pot { items = List.copyOf(items); }
|
||||
boolean brewing() { return brewTicks > 0; }
|
||||
boolean ready() { return !soup.isEmpty() && !brewing(); }
|
||||
static Pot raw(List<ItemStack> items) { return new Pot(items, ItemStack.EMPTY, 0, 0, 0); }
|
||||
}
|
||||
private final MinecraftServer server;
|
||||
private static final Identifier WATER_OWNER = Identifier.parse("astracauldron:cauldrons");
|
||||
private final online.astradev.plus.api.ColoredWaterApi water;
|
||||
private final Path file;
|
||||
private final Path configFile;
|
||||
private SoupConfig config;
|
||||
private Ingredients ingredients;
|
||||
private final Map<Position, Pot> pots = new LinkedHashMap<>();
|
||||
private final Map<Position, List<SoupDisplay>> visuals = new HashMap<>();
|
||||
private final Map<Position, Integer> elapsed = new HashMap<>();
|
||||
private int ticks;
|
||||
public SoupPots(MinecraftServer server, Path configFile) throws IOException {
|
||||
this.server = server;
|
||||
this.water = online.astradev.plus.api.AstraPlusApi.current().flatMap(api -> api.coloredWater()).orElseThrow();
|
||||
this.file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/cauldrons.json");
|
||||
this.configFile = configFile;
|
||||
reload();
|
||||
load();
|
||||
}
|
||||
public Ingredients ingredients() { return ingredients; }
|
||||
public boolean contains(ServerLevel level, BlockPos pos) { return pots.containsKey(Position.at(level, pos)); }
|
||||
public Pot get(ServerLevel level, BlockPos pos) { return pots.get(Position.at(level, pos)); }
|
||||
public void reload() throws IOException {
|
||||
var next = SoupConfig.load(configFile);
|
||||
var nextIngredients = new Ingredients(next, server.registryAccess());
|
||||
config = next;
|
||||
ingredients = nextIngredients;
|
||||
}
|
||||
public void register(String id, ServerPlayer player, int nutrition, float saturation) throws IOException {
|
||||
if (!id.matches("[a-z0-9_-]+") || player.getMainHandItem().isEmpty()) throw new IllegalArgumentException("Нужны ID и предмет в руке");
|
||||
var next = SoupFiles.JSON.fromJson(SoupFiles.JSON.toJson(config), SoupConfig.class);
|
||||
var custom = new SoupConfig.Custom();
|
||||
// Resolve by stable AstraPlus identity; definitions can evolve without invalidating the registration.
|
||||
var plus = online.astradev.plus.api.AstraPlusApi.current().flatMap(api -> api.find(player.getMainHandItem()));
|
||||
if (plus.isPresent()) custom.astraPlusId = plus.get().id().toString();
|
||||
else custom.item = SoupFiles.encode(Ingredients.normalizedCopy(player.getMainHandItem()), server.registryAccess());
|
||||
custom.nutrition = nutrition;
|
||||
custom.saturation = saturation;
|
||||
next.customIngredients.put(id, custom);
|
||||
var validated = new Ingredients(next, server.registryAccess());
|
||||
SoupFiles.write(configFile, SoupFiles.JSON.toJsonTree(next));
|
||||
config = next;
|
||||
ingredients = validated;
|
||||
}
|
||||
private void load() throws IOException {
|
||||
if (!Files.exists(file)) return;
|
||||
var root = JsonParser.parseString(Files.readString(file)).getAsJsonObject();
|
||||
if (root.get("version").getAsInt() != 1) throw new IllegalArgumentException("Unknown cauldron data version");
|
||||
for (var value : root.getAsJsonArray("cauldrons")) {
|
||||
var c = value.getAsJsonObject();
|
||||
String dimension = Identifier.parse(c.get("dimension").getAsString()).toString();
|
||||
var pos = new Position(dimension, new BlockPos(c.get("x").getAsInt(), c.get("y").getAsInt(), c.get("z").getAsInt()));
|
||||
var items = new ArrayList<ItemStack>();
|
||||
for (var i : c.getAsJsonArray("items")) items.add(SoupFiles.decode(i, server.registryAccess()));
|
||||
var soup = c.has("soup") ? SoupFiles.decode(c.get("soup"), server.registryAccess()) : ItemStack.EMPTY;
|
||||
var pot = new Pot(items, soup, c.get("brewTicks").getAsInt(), c.get("servings").getAsInt(), c.get("capacity").getAsInt());
|
||||
validate(pot);
|
||||
if (pots.putIfAbsent(pos, pot) != null) throw new IllegalArgumentException("Duplicate cauldron " + pos);
|
||||
}
|
||||
}
|
||||
private static void validate(Pot p) {
|
||||
if (p.items.size() > 4 || p.items.stream().anyMatch(i -> i.isEmpty() || i.getCount() != 1)
|
||||
|| p.brewTicks < 0 || p.brewTicks > 1200
|
||||
|| (p.soup.isEmpty() ? p.servings != 0 || p.capacity != 0 || p.brewing() || p.items.isEmpty()
|
||||
: p.soup.getCount() != 1 || !Ingredients.isCombined(p.soup) || p.servings < 1 || p.capacity < p.servings || p.capacity > 16
|
||||
|| (p.brewing() ? p.items.size() != 4 : !p.items.isEmpty())))
|
||||
throw new IllegalArgumentException("Invalid cauldron contents");
|
||||
}
|
||||
private boolean change(Position pos, Pot next) {
|
||||
Pot old = pots.get(pos);
|
||||
if (next == null) pots.remove(pos); else { validate(next); pots.put(pos, next); }
|
||||
try {
|
||||
var root = new JsonObject(); root.addProperty("version", 1);
|
||||
var array = new JsonArray(); root.add("cauldrons", array);
|
||||
for (var e : pots.entrySet()) {
|
||||
var c = new JsonObject(); var p = e.getKey(); var pot = e.getValue();
|
||||
c.addProperty("dimension", p.dimension); c.addProperty("x", p.pos.getX()); c.addProperty("y", p.pos.getY()); c.addProperty("z", p.pos.getZ());
|
||||
var items = new JsonArray(); pot.items.forEach(i -> items.add(SoupFiles.encode(i, server.registryAccess()))); c.add("items", items);
|
||||
if (!pot.soup.isEmpty()) c.add("soup", SoupFiles.encode(pot.soup, server.registryAccess()));
|
||||
c.addProperty("brewTicks", pot.brewTicks); c.addProperty("servings", pot.servings); c.addProperty("capacity", pot.capacity);
|
||||
array.add(c);
|
||||
}
|
||||
SoupFiles.write(file, root);
|
||||
if (old == null || next == null || old.ready() != next.ready() || old.items.size() != next.items.size()) removeVisuals(pos);
|
||||
elapsed.remove(pos);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
if (old == null) pots.remove(pos); else pots.put(pos, old);
|
||||
AstraCauldron.LOG.error("Не удалось сохранить котёл; действие отменено", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/** Returns whether vanilla interaction should be consumed. Saves before taking/giving items. */
|
||||
public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) {
|
||||
var level = player.level(); var pos = Position.at(level, blockPos); var pot = pots.get(pos);
|
||||
if (player.isSpectator()) return false;
|
||||
if (hand != InteractionHand.MAIN_HAND) return pot != null;
|
||||
var state = level.getBlockState(blockPos);
|
||||
if (!valid(state, pot)) return false;
|
||||
var held = player.getMainHandItem();
|
||||
if (pot == null && ingredients.read(held) == null) return false;
|
||||
if (pot == null) {
|
||||
if (config.requireFullWater && state.getValue(LayeredCauldronBlock.LEVEL) != 3) {
|
||||
say(player, "Сначала наполните котёл водой доверху."); return true;
|
||||
}
|
||||
pot = Pot.raw(List.of());
|
||||
}
|
||||
if (pot.brewing()) { say(player, "Суп варится… Осталось: " + Math.max(1, (pot.brewTicks - elapsed.getOrDefault(pos, 0) + 19) / 20) + " с."); return true; }
|
||||
if (pot.ready()) {
|
||||
if (!held.is(Items.BOWL)) { say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ."); return true; }
|
||||
int left = pot.servings - 1; var result = pot.soup.copy();
|
||||
if (!change(pos, left == 0 ? null : new Pot(List.of(), pot.soup, 0, left, pot.capacity))) { saveError(player); return true; }
|
||||
held.consume(1, player); give(player, result);
|
||||
level.setBlock(blockPos, Blocks.CAULDRON.defaultBlockState(), 3);
|
||||
if (left > 0) show(level, pos, pots.get(pos));
|
||||
sound(level, blockPos, SoundEvents.BOTTLE_FILL);
|
||||
say(player, left == 0 ? "Последняя порция собрана. Котёл пуст." : "Осталось порций: " + left + "."); return true;
|
||||
}
|
||||
if (pot.items.size() == 4 && (player.isShiftKeyDown() || !held.isEmpty())) {
|
||||
String rejection = ingredients.rejection(pot.items);
|
||||
if (rejection != null) { say(player, rejection + " ПКМ пустой рукой возвращает последний ингредиент."); return true; }
|
||||
var next = new Pot(pot.items, ingredients.brew(pot.items), (int)Math.round(config.brewSeconds * 20), config.servingsPerBrew, config.servingsPerBrew);
|
||||
if (!change(pos, next)) { saveError(player); return true; }
|
||||
sound(level, blockPos, SoundEvents.BREWING_STAND_BREW); say(player, "Варка началась! Дождитесь окончания водоворота."); return true;
|
||||
}
|
||||
if (held.isEmpty()) {
|
||||
if (pot.items.isEmpty()) return true;
|
||||
var remaining = new ArrayList<>(pot.items); var last = remaining.removeLast();
|
||||
if (!change(pos, remaining.isEmpty() ? null : Pot.raw(remaining))) { saveError(player); return true; }
|
||||
give(player, last.copy()); say(player, "Возвращён последний ингредиент. В котле: " + remaining.size() + "/4."); return true;
|
||||
}
|
||||
if (ingredients.read(held) == null) { say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/4."); return true; }
|
||||
var items = new ArrayList<>(pot.items); items.add(held.copyWithCount(1));
|
||||
if (!change(pos, Pot.raw(items))) { saveError(player); return true; }
|
||||
held.consume(1, player); show(level, pos, pots.get(pos)); sound(level, blockPos, SoundEvents.GENERIC_SPLASH);
|
||||
say(player, "Ингредиенты: " + items.size() + "/4." + (items.size() == 4 ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." : ""));
|
||||
return true;
|
||||
}
|
||||
public boolean breakPot(ServerLevel level, BlockPos blockPos) {
|
||||
var pos = Position.at(level, blockPos); var old = pots.get(pos);
|
||||
if (old == null) return true;
|
||||
if (!change(pos, null)) return false;
|
||||
old.items.forEach(i -> Block.popResource(level, blockPos, i.copy()));
|
||||
return true;
|
||||
}
|
||||
private static boolean valid(BlockState state, Pot pot) {
|
||||
return state.is(Blocks.WATER_CAULDRON) || (state.is(Blocks.CAULDRON) && pot != null && pot.ready());
|
||||
}
|
||||
public void tick() {
|
||||
ticks++;
|
||||
for (var entry : new ArrayList<>(pots.entrySet())) {
|
||||
var pos = entry.getKey(); var pot = entry.getValue();
|
||||
var level = server.getLevel(ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension)));
|
||||
if (level == null || !level.hasChunkAt(pos.pos)) { removeVisuals(pos); continue; }
|
||||
if (!valid(level.getBlockState(pos.pos), pot)) { breakPot(level, pos.pos); continue; }
|
||||
if (pot.brewing()) {
|
||||
int time = elapsed.merge(pos, 1, Integer::sum);
|
||||
if (time >= pot.brewTicks && (time - pot.brewTicks) % 20 == 0
|
||||
&& change(pos, new Pot(List.of(), pot.soup, 0, pot.servings, pot.capacity))) {
|
||||
pot = pots.get(pos);
|
||||
level.setBlock(pos.pos, Blocks.CAULDRON.defaultBlockState(), 3);
|
||||
sound(level, pos.pos, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP);
|
||||
level.sendParticles(ParticleTypes.CLOUD, pos.pos.getX() + .5, pos.pos.getY() + 1.05, pos.pos.getZ() + .5, 12, .2, .12, .2, .01);
|
||||
}
|
||||
}
|
||||
show(level, pos, pot);
|
||||
if (ticks % 2 == 0 && !pot.ready()) {
|
||||
var displays = visuals.get(pos);
|
||||
int water = level.getBlockState(pos.pos).getValue(LayeredCauldronBlock.LEVEL);
|
||||
for (int i = 0; i < displays.size(); i++) displays.get(i).ingredient(i, water, ticks + 2, elapsed.getOrDefault(pos, 0) + 2, pot.brewTicks);
|
||||
if (pot.brewing() && ticks % 10 == 0)
|
||||
level.sendParticles(ParticleTypes.SPLASH, pos.pos.getX() + .5, pos.pos.getY() + .95, pos.pos.getZ() + .5, 2, .2, 0, .2, 0);
|
||||
}
|
||||
}
|
||||
if (ticks % 20 == 0) for (var player : server.getPlayerList().getPlayers()) {
|
||||
for (var slot : player.containerMenu.slots) Ingredients.normalize(slot.getItem());
|
||||
for (int i = 0; i < player.getInventory().getContainerSize(); i++) Ingredients.normalize(player.getInventory().getItem(i));
|
||||
Ingredients.normalize(player.containerMenu.getCarried());
|
||||
player.containerMenu.broadcastChanges();
|
||||
}
|
||||
}
|
||||
private void show(ServerLevel level, Position pos, Pot pot) {
|
||||
if (pot.ready()) {
|
||||
water.show(level, pos.pos, new online.astradev.plus.api.ColoredWaterApi.Surface(WATER_OWNER,
|
||||
Ingredients.color(pot.soup), (float)CauldronAnimation.liquidHeight(pot.servings, pot.capacity)));
|
||||
return;
|
||||
}
|
||||
var existing = visuals.get(pos);
|
||||
if (existing != null && existing.stream().anyMatch(d -> d.isRemoved())) { removeVisuals(pos); existing = null; }
|
||||
if (existing != null) return;
|
||||
var displays = new ArrayList<SoupDisplay>();
|
||||
for (int i = 0; i < pot.items.size(); i++) {
|
||||
var display = new SoupDisplay(level, pos.pos, pot.items.get(i));
|
||||
display.ingredient(i, level.getBlockState(pos.pos).getValue(LayeredCauldronBlock.LEVEL), ticks, elapsed.getOrDefault(pos, 0), pot.brewTicks);
|
||||
displays.add(display);
|
||||
}
|
||||
displays.forEach(level::addFreshEntity); visuals.put(pos, displays);
|
||||
}
|
||||
public void unload(ServerLevel level, int chunkX, int chunkZ) {
|
||||
for (var pos : new ArrayList<>(visuals.keySet())) if (pos.dimension.equals(level.dimension().identifier().toString())
|
||||
&& (pos.pos.getX() >> 4) == chunkX && (pos.pos.getZ() >> 4) == chunkZ) removeVisuals(pos);
|
||||
}
|
||||
private void removeVisuals(Position pos) {
|
||||
var list = visuals.remove(pos); if (list != null) list.forEach(SoupDisplay::discard);
|
||||
var level = server.getLevel(ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension)));
|
||||
if (level != null) water.remove(level, pos.pos, WATER_OWNER);
|
||||
}
|
||||
@Override public void close() {
|
||||
for (var pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos);
|
||||
water.removeAll(WATER_OWNER);
|
||||
}
|
||||
private static void sound(ServerLevel level, BlockPos pos, SoundEvent sound) { level.playSound(null, pos, sound, SoundSource.BLOCKS, .8f, 1f); }
|
||||
private static void give(ServerPlayer player, ItemStack item) { Ingredients.normalize(item); player.getInventory().add(item); if (!item.isEmpty()) player.drop(item, false); player.containerMenu.broadcastChanges(); }
|
||||
private static void say(ServerPlayer player, String text) { player.sendSystemMessage(Component.literal(text).withStyle(ChatFormatting.GOLD), true); }
|
||||
private static void saveError(ServerPlayer player) { say(player, "Не удалось сохранить котёл. Обратитесь к администратору."); }
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.List;
|
||||
|
||||
/** Export before AstraPlus's startup pack build; never overwrite administrator resources. */
|
||||
final class SoupResources {
|
||||
private SoupResources() {}
|
||||
static void install(Path root) throws IOException {
|
||||
for (String name : List.of("items/combined_soup.json",
|
||||
"models/item/soup_liquid.json")) {
|
||||
String relative = "assets/astradev_soups/" + name;
|
||||
Path target = root.resolve("astraplus/resources").resolve(relative);
|
||||
Files.createDirectories(target.getParent());
|
||||
if (Files.exists(target)) continue;
|
||||
try (var input = SoupResources.class.getResourceAsStream("/astra-resources/" + relative)) {
|
||||
if (input == null) throw new IOException("Missing resource " + relative);
|
||||
Files.copy(input, target);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package online.astradev.soups;
|
||||
package online.astradev.cauldron;
|
||||
|
||||
final class SoupText {
|
||||
private SoupText() {}
|
||||
@@ -0,0 +1,25 @@
|
||||
package online.astradev.cauldron.mixin;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.Fluid;
|
||||
import online.astradev.cauldron.AstraCauldron;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
/** NeoForge has no cancellable event for these vanilla cauldron mutations. */
|
||||
@Mixin({CauldronBlock.class, LayeredCauldronBlock.class})
|
||||
abstract class CauldronWeatherMixin {
|
||||
@Inject(method = "handlePrecipitation", at = @At("HEAD"), cancellable = true)
|
||||
private void soups$rain(BlockState state, Level level, BlockPos pos, Biome.Precipitation precipitation, CallbackInfo ci) {
|
||||
if (AstraCauldron.occupied(level, pos)) ci.cancel();
|
||||
}
|
||||
@Inject(method = "receiveStalactiteDrip", at = @At("HEAD"), cancellable = true)
|
||||
private void soups$drip(BlockState state, Level level, BlockPos pos, Fluid fluid, CallbackInfo ci) {
|
||||
if (AstraCauldron.occupied(level, pos)) ci.cancel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package online.astradev.cauldron.mixin;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.LayeredCauldronBlock;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import online.astradev.cauldron.AstraCauldron;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(LayeredCauldronBlock.class)
|
||||
abstract class LayeredCauldronMixin {
|
||||
@Inject(method = "lowerFillLevel", at = @At("HEAD"), cancellable = true)
|
||||
private static void soups$lower(BlockState state, Level level, BlockPos pos, CallbackInfo ci) {
|
||||
if (AstraCauldron.occupied(level, pos)) ci.cancel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package online.astradev.cauldron.mixin;
|
||||
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.component.*;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
/** Per-stack patch is sent to vanilla clients; no change to their assumed item defaults. */
|
||||
@Mixin(ItemStack.class)
|
||||
abstract class SoupStackMixin {
|
||||
@Inject(method = "<init>(Lnet/minecraft/core/Holder;ILnet/minecraft/core/component/PatchedDataComponentMap;)V", at = @At("RETURN"))
|
||||
private void soups$stackSize(Holder<Item> item, int count, PatchedDataComponentMap components, CallbackInfo ci) {
|
||||
var key = item.unwrapKey().orElse(null);
|
||||
if (key == null || !key.identifier().getNamespace().equals("minecraft")) return;
|
||||
switch (key.identifier().getPath()) {
|
||||
case "mushroom_stew", "rabbit_stew", "beetroot_soup", "suspicious_stew" -> components.set(DataComponents.MAX_STACK_SIZE, 16);
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,824 +0,0 @@
|
||||
package online.astradev.soups;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
|
||||
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.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
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 final Map<Position, Integer> brewElapsed = 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, int brewTicks, int servings, int capacity) {
|
||||
Pot {
|
||||
items = List.copyOf(items);
|
||||
}
|
||||
|
||||
Pot(List<ItemStack> items, ItemStack soup) {
|
||||
this(items, soup, 0, soup == null ? 0 : 1, soup == null ? 0 : 1);
|
||||
}
|
||||
|
||||
boolean brewing() {
|
||||
return brewTicks > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
pots.clear();
|
||||
brewElapsed.clear();
|
||||
ticks = 0;
|
||||
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, 1);
|
||||
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");
|
||||
int brewTicks = c.getInt("brew-ticks", 0);
|
||||
int servings = c.getInt("servings", soup == null ? 0 : 1);
|
||||
int capacity =
|
||||
c.getInt(
|
||||
"capacity",
|
||||
soup == null
|
||||
? 0
|
||||
: Math.max(
|
||||
servings, getConfig().getInt("servings-per-brew", 4)));
|
||||
if (items.size() > 4
|
||||
|| brewTicks < 0
|
||||
|| brewTicks > 1200
|
||||
|| (soup == null ? capacity != 0 : capacity < servings || capacity > 16)
|
||||
|| (soup == null ? servings != 0 : servings < 1 || servings > 16)
|
||||
|| (soup != null && (soup.getAmount() != 1 || !ingredients.isCombined(soup)))
|
||||
|| (brewTicks > 0
|
||||
? items.size() != 4 || soup == null
|
||||
: (soup != null ? !items.isEmpty() : items.isEmpty()))) {
|
||||
throw new IllegalArgumentException("Invalid cauldron at " + id);
|
||||
}
|
||||
pots.put(Position.parse(id), new Pot(items, soup, brewTicks, servings, capacity));
|
||||
}
|
||||
}
|
||||
|
||||
/** 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);
|
||||
if (entry.getValue().brewing())
|
||||
data.set(prefix + ".brew-ticks", entry.getValue().brewTicks);
|
||||
if (entry.getValue().soup != null)
|
||||
data.set(prefix + ".servings", entry.getValue().servings);
|
||||
if (entry.getValue().soup != null)
|
||||
data.set(prefix + ".capacity", entry.getValue().capacity);
|
||||
}
|
||||
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);
|
||||
}
|
||||
// Keep the same visuals when starting a brew or taking a portion: no respawn flash.
|
||||
if (old == null || next == null || !old.items.equals(next.items)) removeVisuals(pos);
|
||||
brewElapsed.remove(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 (!validBlock(block, pot)) 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.brewing()) {
|
||||
int remaining =
|
||||
Math.max(1, (pot.brewTicks - brewElapsed.getOrDefault(pos, 0) + 19) / 20);
|
||||
say(player, "Суп варится… Осталось: " + remaining + " с.");
|
||||
return;
|
||||
}
|
||||
if (pot.soup != null) {
|
||||
if (!bowl) {
|
||||
say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ.");
|
||||
return;
|
||||
}
|
||||
ItemStack result = pot.soup.clone();
|
||||
int remaining = pot.servings - 1;
|
||||
if (!change(
|
||||
pos,
|
||||
remaining == 0
|
||||
? null
|
||||
: new Pot(List.of(), pot.soup, 0, remaining, pot.capacity))) {
|
||||
saveError(player);
|
||||
return;
|
||||
}
|
||||
takeOne(player);
|
||||
give(player, result);
|
||||
if (remaining == 0) block.setType(Material.CAULDRON);
|
||||
else {
|
||||
syncWater(block, pots.get(pos));
|
||||
show(pos, pots.get(pos), block);
|
||||
}
|
||||
block.getWorld().playSound(block.getLocation(), Sound.ITEM_BOTTLE_FILL, 0.8f, 0.7f);
|
||||
say(
|
||||
player,
|
||||
remaining == 0
|
||||
? "Последняя порция собрана. Котёл пуст."
|
||||
: "Осталось порций: " + remaining + ".");
|
||||
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);
|
||||
int duration = (int) Math.round(getConfig().getDouble("brew-seconds", 4.0) * 20);
|
||||
int capacity = getConfig().getInt("servings-per-brew", 4);
|
||||
if (!change(pos, new Pot(pot.items, soup, duration, capacity, capacity))) {
|
||||
saveError(player);
|
||||
return;
|
||||
}
|
||||
show(pos, pots.get(pos), block);
|
||||
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BREWING_STAND_BREW, 1, 1);
|
||||
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++;
|
||||
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 (!validBlock(block, entry.getValue())) {
|
||||
// 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;
|
||||
}
|
||||
Pot pot = entry.getValue();
|
||||
if (pot.brewing()) {
|
||||
int elapsed = brewElapsed.merge(pos, 1, Integer::sum);
|
||||
// On a save failure keep ingredients locked and retry once per second.
|
||||
if (elapsed >= pot.brewTicks
|
||||
&& (elapsed - pot.brewTicks) % 20 == 0
|
||||
&& change(
|
||||
pos, new Pot(List.of(), pot.soup, 0, pot.servings, pot.capacity))) {
|
||||
syncWater(block, pots.get(pos));
|
||||
show(pos, pots.get(pos), block);
|
||||
block.getWorld()
|
||||
.playSound(
|
||||
block.getLocation(),
|
||||
Sound.BLOCK_BUBBLE_COLUMN_BUBBLE_POP,
|
||||
.8f,
|
||||
1.2f);
|
||||
block.getWorld()
|
||||
.spawnParticle(
|
||||
Particle.CLOUD,
|
||||
block.getLocation().add(.5, 1.05, .5),
|
||||
12,
|
||||
.2,
|
||||
.12,
|
||||
.2,
|
||||
.01);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (pot.soup != null && !pot.brewing()) syncWater(block, pot);
|
||||
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 ItemDisplay item && ticks % 2 == 0) {
|
||||
// Client interpolates the local transform; the entity itself never
|
||||
// teleports.
|
||||
item.setInterpolationDelay(0);
|
||||
item.setTransformation(itemTransform(block, i, pot, 2));
|
||||
if (pot.brewing() && ticks % 5 == 0) {
|
||||
Vector3f offset = item.getTransformation().getTranslation();
|
||||
double height =
|
||||
.375 + .1875 * ((Levelled) block.getBlockData()).getLevel();
|
||||
block.getWorld()
|
||||
.spawnParticle(
|
||||
Particle.SPLASH,
|
||||
block.getLocation()
|
||||
.add(
|
||||
.5 + offset.x,
|
||||
height + .01,
|
||||
.5 + offset.z),
|
||||
1,
|
||||
.015,
|
||||
0,
|
||||
.015,
|
||||
0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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 boolean validBlock(Block block, Pot pot) {
|
||||
return block.getType() == Material.WATER_CAULDRON
|
||||
|| (block.getType() == Material.CAULDRON
|
||||
&& pot != null
|
||||
&& pot.soup != null
|
||||
&& !pot.brewing());
|
||||
}
|
||||
|
||||
private void syncWater(Block block, Pot pot) {
|
||||
int level = CauldronAnimation.waterLevel(pot.servings, pot.capacity);
|
||||
if (level == 0) {
|
||||
if (block.getType() != Material.CAULDRON) block.setType(Material.CAULDRON);
|
||||
} else {
|
||||
if (block.getType() != Material.WATER_CAULDRON) block.setType(Material.WATER_CAULDRON);
|
||||
Levelled water = (Levelled) block.getBlockData();
|
||||
if (water.getLevel() != level) {
|
||||
water.setLevel(level);
|
||||
block.setBlockData(water);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Transformation itemTransform(Block block, int i, Pot pot, int ahead) {
|
||||
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
|
||||
CauldronAnimation.Offset frame =
|
||||
CauldronAnimation.frame(
|
||||
i,
|
||||
waterLevel,
|
||||
ticks + ahead,
|
||||
brewElapsed.getOrDefault(Position.at(block), 0) + ahead,
|
||||
pot.brewTicks);
|
||||
return new Transformation(
|
||||
new Vector3f(
|
||||
(float) frame.x() - .5f, (float) frame.y() - .5f, (float) frame.z() - .5f),
|
||||
new Quaternionf(),
|
||||
new Vector3f(.3f),
|
||||
new Quaternionf().rotationY((ticks + ahead) * .035f + i));
|
||||
}
|
||||
|
||||
private Transformation liquidTransform(Pot pot) {
|
||||
return new Transformation(
|
||||
new Vector3f(
|
||||
-.075f,
|
||||
(float) CauldronAnimation.liquidHeight(pot.servings, pot.capacity)
|
||||
+ .005f
|
||||
- .5f,
|
||||
.375f),
|
||||
new Quaternionf().rotationX((float) (-Math.PI / 2)),
|
||||
new Vector3f(6, 3, 1),
|
||||
new Quaternionf());
|
||||
}
|
||||
|
||||
private void show(Position pos, Pot pot, Block block) {
|
||||
if (visuals.containsKey(pos)) {
|
||||
if (pot.soup != null && !pot.brewing())
|
||||
for (Entity entity : visuals.get(pos))
|
||||
if (entity instanceof TextDisplay display) {
|
||||
display.setInterpolationDelay(0);
|
||||
display.setTransformation(liquidTransform(pot));
|
||||
}
|
||||
return;
|
||||
}
|
||||
List<Entity> entities = new ArrayList<>();
|
||||
visuals.put(pos, entities);
|
||||
if (pot.soup != null && !pot.brewing()) {
|
||||
int rgb =
|
||||
pot.soup
|
||||
.getItemMeta()
|
||||
.getPersistentDataContainer()
|
||||
.getOrDefault(colorKey, PersistentDataType.INTEGER, 0xB77A36);
|
||||
TextDisplay display =
|
||||
block.getWorld()
|
||||
.spawn(
|
||||
block.getLocation().add(.5, .5, .5),
|
||||
TextDisplay.class,
|
||||
d -> {
|
||||
markVisual(d);
|
||||
// One default-font space: native background spans 5x10
|
||||
// pixels at 0.025 blocks/pixel.
|
||||
// Center the rectangle, scale to 0.75x0.75 and face upwards
|
||||
// inside the cauldron.
|
||||
d.text(
|
||||
Component.text(" ")
|
||||
.font(
|
||||
net.kyori.adventure.key.Key.key(
|
||||
"minecraft:default")));
|
||||
d.setDefaultBackground(false);
|
||||
d.setBackgroundColor(Color.fromARGB(0xFF000000 | rgb));
|
||||
d.setShadowed(false);
|
||||
d.setSeeThrough(false);
|
||||
d.setTransformation(liquidTransform(pot));
|
||||
d.setInterpolationDuration(5);
|
||||
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();
|
||||
int slot = i;
|
||||
ItemDisplay item =
|
||||
block.getWorld()
|
||||
.spawn(
|
||||
block.getLocation().add(.5, .5, .5),
|
||||
ItemDisplay.class,
|
||||
e -> {
|
||||
markVisual(e);
|
||||
e.setItemStack(stack);
|
||||
e.setItemDisplayTransform(
|
||||
ItemDisplay.ItemDisplayTransform.FIXED);
|
||||
e.setTransformation(itemTransform(block, slot, pot, 0));
|
||||
e.setInterpolationDuration(2);
|
||||
e.setViewRange(.5f);
|
||||
});
|
||||
entities.add(item);
|
||||
}
|
||||
}
|
||||
|
||||
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 && !pot.brewing())
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package online.astradev.soups;
|
||||
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Material;
|
||||
|
||||
final class IngredientColors {
|
||||
private IngredientColors() {}
|
||||
|
||||
static Color food(Material material, Color fallback) {
|
||||
int rgb =
|
||||
switch (material) {
|
||||
case SPIDER_EYE, FERMENTED_SPIDER_EYE -> 0xB52B38;
|
||||
case GOLDEN_APPLE, ENCHANTED_GOLDEN_APPLE, GOLDEN_CARROT -> 0xF2C94C;
|
||||
case APPLE, SWEET_BERRIES -> 0xC73735;
|
||||
case BEETROOT, BEETROOT_SOUP -> 0xA52B4B;
|
||||
case CARROT, PUMPKIN_PIE, GLOW_BERRIES -> 0xE99032;
|
||||
case DRIED_KELP -> 0x47733B;
|
||||
case POISONOUS_POTATO -> 0x91A340;
|
||||
case MELON_SLICE -> 0xD94E58;
|
||||
case CHORUS_FRUIT -> 0x9C6C9D;
|
||||
case BEEF, MUTTON, PORKCHOP, RABBIT -> 0xC76B70;
|
||||
case CHICKEN -> 0xE2A6A0;
|
||||
case COOKED_BEEF, COOKED_MUTTON -> 0x815033;
|
||||
case COOKED_PORKCHOP, COOKED_RABBIT, COOKED_CHICKEN -> 0xBA8551;
|
||||
case SALMON, COOKED_SALMON, TROPICAL_FISH -> 0xD98262;
|
||||
case COD -> 0xB0A07B;
|
||||
case COOKED_COD -> 0xC4B486;
|
||||
case PUFFERFISH -> 0xD3B54D;
|
||||
case BREAD, COOKIE, BAKED_POTATO -> 0xBA873F;
|
||||
case POTATO -> 0xC7A76B;
|
||||
case ROTTEN_FLESH -> 0x8F6540;
|
||||
case HONEY_BOTTLE -> 0xE9AC32;
|
||||
case CAKE -> 0xE8CCBA;
|
||||
case MUSHROOM_STEW -> 0xA37A53;
|
||||
case RABBIT_STEW -> 0xAC8854;
|
||||
case SUSPICIOUS_STEW -> 0x867743;
|
||||
default -> fallback.asRGB();
|
||||
};
|
||||
return Color.fromRGB(rgb);
|
||||
}
|
||||
}
|
||||
@@ -1,393 +0,0 @@
|
||||
package online.astradev.soups;
|
||||
|
||||
import io.papermc.paper.datacomponent.DataComponentTypes;
|
||||
import io.papermc.paper.datacomponent.item.Consumable;
|
||||
import io.papermc.paper.datacomponent.item.CustomModelData;
|
||||
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.key.Key;
|
||||
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,
|
||||
Color color) {}
|
||||
|
||||
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;
|
||||
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");
|
||||
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);
|
||||
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));
|
||||
}
|
||||
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 = IngredientColors.food(item.getType(), defaultColor);
|
||||
if (isCombined(item))
|
||||
color =
|
||||
Color.fromRGB(
|
||||
meta.getPersistentDataContainer()
|
||||
.getOrDefault(
|
||||
plugin.colorKey,
|
||||
PersistentDataType.INTEGER,
|
||||
defaultColor.asRGB()));
|
||||
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 (match.color != null) color = match.color;
|
||||
}
|
||||
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", "Комбинированный суп"),
|
||||
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) {
|
||||
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(
|
||||
" "
|
||||
+ SoupText.roman(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));
|
||||
}
|
||||
return lore;
|
||||
}
|
||||
|
||||
private static 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;
|
||||
}) return false;
|
||||
boolean changed = false;
|
||||
if (!Objects.equals(item.getData(DataComponentTypes.MAX_STACK_SIZE), 16)) {
|
||||
item.setData(DataComponentTypes.MAX_STACK_SIZE, 16);
|
||||
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;
|
||||
}
|
||||
int rgb = meta.getPersistentDataContainer().getOrDefault(
|
||||
new NamespacedKey("astrasoups", "soup_color"),
|
||||
PersistentDataType.INTEGER, 0xB77A36);
|
||||
Key model = Key.key("astradev_soups", "combined_soup");
|
||||
if (!Objects.equals(item.getData(DataComponentTypes.ITEM_MODEL), model)) {
|
||||
item.setData(DataComponentTypes.ITEM_MODEL, model);
|
||||
changed = true;
|
||||
}
|
||||
CustomModelData data = item.getData(DataComponentTypes.CUSTOM_MODEL_DATA);
|
||||
Color tint = Color.fromRGB(rgb & 0xFFFFFF);
|
||||
if (data == null || data.colors().isEmpty() || !data.colors().getFirst().equals(tint)) {
|
||||
var builder = CustomModelData.customModelData().addColor(tint);
|
||||
if (data != null) {
|
||||
builder.addFloats(data.floats()).addFlags(data.flags()).addStrings(data.strings());
|
||||
builder.addColors(data.colors().stream().skip(1).toList());
|
||||
}
|
||||
item.setData(DataComponentTypes.CUSTOM_MODEL_DATA, builder.build());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
public net.minecraft.world.entity.Display setTransformation(Lcom/mojang/math/Transformation;)V
|
||||
public net.minecraft.world.entity.Display setTransformationInterpolationDuration(I)V
|
||||
public net.minecraft.world.entity.Display setTransformationInterpolationDelay(I)V
|
||||
public net.minecraft.world.entity.Display setPosRotInterpolationDuration(I)V
|
||||
public net.minecraft.world.entity.Display$ItemDisplay setItemTransform(Lnet/minecraft/world/item/ItemDisplayContext;)V
|
||||
@@ -0,0 +1,26 @@
|
||||
modLoader="javafml"
|
||||
loaderVersion="[11,)"
|
||||
license="All Rights Reserved"
|
||||
[[mods]]
|
||||
modId="astracauldron"
|
||||
version="${version}"
|
||||
displayName="AstraCauldron"
|
||||
description='''Server-side cauldron soups with AstraPlus ingredients and resources.'''
|
||||
[[mixins]]
|
||||
config="astracauldron.mixins.json"
|
||||
[[dependencies.astracauldron]]
|
||||
modId="neoforge"
|
||||
type="required"
|
||||
versionRange="[26.2.0.79,26.3)"
|
||||
side="SERVER"
|
||||
[[dependencies.astracauldron]]
|
||||
modId="minecraft"
|
||||
type="required"
|
||||
versionRange="[26.2,26.3)"
|
||||
side="SERVER"
|
||||
[[dependencies.astracauldron]]
|
||||
modId="astraplus"
|
||||
type="required"
|
||||
versionRange="[0.5.1,0.6)"
|
||||
ordering="AFTER"
|
||||
side="SERVER"
|
||||
@@ -1,3 +0,0 @@
|
||||
schema=1
|
||||
plugin=AstraSoups
|
||||
folder=astradev_soups
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"required": true,
|
||||
"package": "online.astradev.cauldron.mixin",
|
||||
"compatibilityLevel": "JAVA_25",
|
||||
"server": ["CauldronWeatherMixin", "LayeredCauldronMixin", "SoupStackMixin"],
|
||||
"injectors": {"defaultRequire": 1}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
# Ровно четыре предмета, по одной единице каждого. Повторы разрешены.
|
||||
# Одна варка даёт четыре порции; каждая получает питание и эффекты всего состава.
|
||||
servings-per-brew: 4
|
||||
require-full-water: true
|
||||
# Время варки в секундах (0.5–60).
|
||||
brew-seconds: 4.0
|
||||
soup-name: 'Комбинированный суп'
|
||||
# Цвет ингредиентов, для которых не задан собственный RGB.
|
||||
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. Эффекты добавляются к исходным.
|
||||
# Необязательный color: '#D45B37' задаёт цвет уникальной еды для смешивания.
|
||||
custom-ingredients: {}
|
||||
@@ -1,16 +0,0 @@
|
||||
name: AstraSoups
|
||||
version: '${version}'
|
||||
main: online.astradev.soups.AstraSoupsPlugin
|
||||
api-version: '26.2'
|
||||
description: Four-ingredient cauldron soups with food and potion properties
|
||||
author: AstraDev
|
||||
depend: [AstraPacks, ItemsAdder]
|
||||
commands:
|
||||
soups:
|
||||
description: Комбинированные супы
|
||||
usage: /soups [reload|register <id> <голод> <насыщение>]
|
||||
permissions:
|
||||
astrasoups.use:
|
||||
default: true
|
||||
astrasoups.admin:
|
||||
default: op
|
||||
Reference in New Issue
Block a user