Simplify ingredient handling and remove generated verification files

This commit is contained in:
2026-09-13 21:55:44 +03:00
parent fcd84c7024
commit ce5a37e139
31 changed files with 1596 additions and 914 deletions
@@ -95,9 +95,9 @@ public final class AstraCauldron {
}
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)));
if (!(level instanceof ServerLevel serverLevel)) return false;
if (pots != null && pots.contains(serverLevel, pos)) return true;
return liquids != null && liquids.contains(serverLevel, pos);
}
private void interact(PlayerInteractEvent.RightClickBlock event) {
@@ -105,31 +105,26 @@ public final class AstraCauldron {
|| event.isCanceled()
|| event.getUseBlock() == TriState.FALSE
|| event.getUseItem() == TriState.FALSE) return;
if (event.getEntity() instanceof ServerPlayer player
&& RegisteredRecipes.interact(player, event.getPos(), event.getHand())) {
event.setCanceled(true);
event.setCancellationResult(InteractionResult.SUCCESS);
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);
}
if (!(event.getEntity() instanceof ServerPlayer player)) return;
var pos = event.getPos();
var hand = event.getHand();
boolean handled = RegisteredRecipes.interact(player, pos, hand);
if (!handled && !pots.contains(player.level(), pos) && liquids != null)
handled = liquids.interact(player, pos, hand);
if (!handled) handled = pots.interact(player, pos, hand);
if (!handled) return;
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);
}
if (event.isCanceled() || pots == null) return;
if (!(event.getLevel() instanceof ServerLevel level)) return;
boolean removed = pots.breakPot(level, event.getPos());
if (removed && liquids != null) removed = liquids.breakPot(level, event.getPos());
if (removed) return;
event.setCanceled(true);
event.setNotifyClient(true);
}
private void explosion(ExplosionEvent.Detonate event) {
@@ -141,11 +136,11 @@ public final class AstraCauldron {
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);
if (resolver == null || !resolver.resolve()) return;
boolean movesCauldron = resolver.getToPush().stream().anyMatch(pos -> occupied(level, pos));
boolean breaksCauldron =
resolver.getToDestroy().stream().anyMatch(pos -> occupied(level, pos));
if (movesCauldron || breaksCauldron) event.setCanceled(true);
}
private void unload(ChunkEvent.Unload event) {
@@ -193,7 +188,7 @@ public final class AstraCauldron {
() ->
Component.literal(
"AstraCauldron: настройки"
+ " применены."),
+ " применены."),
true);
return 1;
} catch (Exception e) {
@@ -11,25 +11,49 @@ import net.minecraft.world.level.block.LayeredCauldronBlock;
/** Uses the existing campfire ticker; no scanning worlds or spawning persistent effects. */
public final class CauldronHeat {
private CauldronHeat() {}
public static boolean heated(LevelReader level, BlockPos cauldron) {
var below = cauldron.below();
if (!level.hasChunkAt(below)) return false;
var state = level.getBlockState(below);
return state.getBlock() instanceof CampfireBlock && state.getValue(CampfireBlock.LIT);
}
public static void tick(ServerLevel level, BlockPos campfire) {
if (!AstraCauldron.config().particles) return;
var pos = campfire.above();
if ((level.getGameTime() + pos.asLong()) % 10 != 0 || !heated(level, pos)) return;
var state = level.getBlockState(pos);
double surface;
if (state.is(Blocks.WATER_CAULDRON)) surface = .375 + .1875 * state.getValue(LayeredCauldronBlock.LEVEL);
if (state.is(Blocks.WATER_CAULDRON))
surface = .375 + .1875 * state.getValue(LayeredCauldronBlock.LEVEL);
else {
var pot = AstraCauldron.pots() == null ? null : AstraCauldron.pots().get(level, pos);
if (!state.is(Blocks.CAULDRON) || pot == null || pot.soup().isEmpty() || pot.brewTicks() > 0) return;
if (!state.is(Blocks.CAULDRON)
|| pot == null
|| pot.soup().isEmpty()
|| pot.brewTicks() > 0) return;
surface = CauldronAnimation.liquidHeight(pot.servings(), pot.capacity());
}
level.sendParticles(ParticleTypes.BUBBLE_POP, pos.getX() + .5, pos.getY() + surface + .01, pos.getZ() + .5, 4, .18, .015, .18, 0);
level.sendParticles(ParticleTypes.SPLASH, pos.getX() + .5, pos.getY() + surface + .02, pos.getZ() + .5, 2, .16, 0, .16, 0);
level.sendParticles(
ParticleTypes.BUBBLE_POP,
pos.getX() + .5,
pos.getY() + surface + .01,
pos.getZ() + .5,
4,
.18,
.015,
.18,
0);
level.sendParticles(
ParticleTypes.SPLASH,
pos.getX() + .5,
pos.getY() + surface + .02,
pos.getZ() + .5,
2,
.16,
0,
.16,
0);
}
}
@@ -14,7 +14,12 @@ public final class CombinationRules {
List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs) {
return rejection(ingredients, blocked, pairs, 4);
}
public static String rejection(List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs, int count) {
public static String rejection(
List<Set<String>> ingredients,
List<String> blocked,
List<List<String>> pairs,
int count) {
if (ingredients.size() != count) return "Нужно ровно " + count + " ингредиента.";
for (Set<String> tags : ingredients) {
for (String selector : blocked) {
@@ -1,8 +1,5 @@
package online.astradev.cauldron;
final class IngredientColors {
private IngredientColors() {}
@@ -1,6 +1,5 @@
package online.astradev.cauldron;
import java.util.*;
import net.minecraft.ChatFormatting;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.component.DataComponents;
@@ -12,21 +11,37 @@ 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;
import java.util.*;
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) {}
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);
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);
@@ -38,18 +53,28 @@ public final class Ingredients {
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);
String plusId = plus.map(value -> value.id().toString()).orElse(null);
Custom match = findCustom(stack, plusId);
var food = stack.get(DataComponents.FOOD);
boolean potion = stack.is(Items.POTION) || stack.is(Items.SPLASH_POTION) || stack.is(Items.LINGERING_POTION);
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();
int nutrition = 0;
float saturation = 0;
if (food != null) {
nutrition = food.nutrition();
saturation = food.saturation();
} else if (cake) {
nutrition = 14;
saturation = 2.8f;
}
var effects = new ArrayList<ConsumeEffect>();
var consumable = stack.get(DataComponents.CONSUMABLE);
if (consumable != null) effects.addAll(consumable.onConsumeEffects());
@@ -59,13 +84,21 @@ public final class Ingredients {
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));
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()));
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");
@@ -74,91 +107,199 @@ public final class Ingredients {
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));
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()));
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);
}
private Custom findCustom(ItemStack stack, String plusId) {
ItemStack normalized = null;
for (var ingredient : custom) {
String expected = ingredient.definition.astraPlusId;
if (expected != null) {
if (expected.equals(plusId)) return ingredient;
continue;
}
if (normalized == null) normalized = normalizedCopy(stack);
if (ItemStack.isSameItemSameComponents(ingredient.sample, normalized))
return ingredient;
}
return null;
}
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, config.ingredientCount);
String error =
CombinationRules.rejection(
data.stream().map(Ingredient::tags).toList(),
config.blockedIngredients,
config.incompatible,
config.ingredientCount);
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 "В супе слишком много эффектов.";
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();
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();
List<ConsumeEffect> effects = config.inheritEffects ? data.stream().flatMap(i -> i.effects.stream()).toList() : List.of();
List<ConsumeEffect> effects =
config.inheritEffects
? data.stream().flatMap(i -> i.effects.stream()).toList()
: List.of();
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, config.alwaysEdible));
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, config.alwaysEdible));
var base = Objects.requireNonNull(soup.get(DataComponents.CONSUMABLE));
soup.set(DataComponents.CONSUMABLE, new Consumable(config.consumeSeconds, base.animation(), base.sound(), config.particles && base.hasConsumeParticles(), effects));
if (config.returnBowl) soup.set(DataComponents.USE_REMAINDER, new UseRemainder(ItemStackTemplate.fromNonEmptyStack(new ItemStack(Items.BOWL))));
soup.set(
DataComponents.CONSUMABLE,
new Consumable(
config.consumeSeconds,
base.animation(),
base.sound(),
config.particles && base.hasConsumeParticles(),
effects));
if (config.returnBowl)
soup.set(
DataComponents.USE_REMAINDER,
new UseRemainder(
ItemStackTemplate.fromNonEmptyStack(new ItemStack(Items.BOWL))));
else soup.remove(DataComponents.USE_REMAINDER);
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; }
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);
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;
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;
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;
if (isCombined(stack) || AstraCauldron.config().normalizeVanillaSoups) stack.set(DataComponents.MAX_STACK_SIZE, AstraCauldron.config().soupStackSize);
if (!(stack.is(Items.MUSHROOM_STEW)
|| stack.is(Items.RABBIT_STEW)
|| stack.is(Items.BEETROOT_SOUP)
|| stack.is(Items.SUSPICIOUS_STEW))) return;
if (isCombined(stack) || AstraCauldron.config().normalizeVanillaSoups)
stack.set(DataComponents.MAX_STACK_SIZE, AstraCauldron.config().soupStackSize);
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));
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())));
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));
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));
if (effect instanceof ApplyStatusEffectsConsumeEffect apply) {
for (var instance : apply.effects())
lines.add(effectLine(instance, apply.probability()));
continue;
}
String description =
switch (effect) {
case TeleportRandomlyConsumeEffect ignored -> "Случайная телепортация";
case ClearAllStatusEffectsConsumeEffect ignored -> "Снятие всех эффектов";
case RemoveStatusEffectsConsumeEffect ignored -> "Снятие эффектов";
default -> "Звук при употреблении";
};
lines.add(line(description, ChatFormatting.GRAY));
}
return lines;
}
private static Component effectLine(MobEffectInstance effect, float probability) {
String duration = "∞";
if (!effect.isInfiniteDuration())
duration =
String.format(
Locale.ROOT,
"%d:%02d",
effect.getDuration() / 1200,
effect.getDuration() / 20 % 60);
String details = " " + SoupText.roman(effect.getAmplifier() + 1) + " (" + duration + ")";
if (probability < 1) details += " " + Math.round(probability * 100) + "%";
return Component.translatable(effect.getDescriptionId())
.append(details)
.withStyle(style -> style.withColor(ChatFormatting.AQUA).withItalic(false));
}
private static Component line(String text, ChatFormatting color) {
return Component.literal(text).withStyle(s -> s.withColor(color).withItalic(false));
}
@@ -194,7 +194,7 @@ public final class LiquidPots implements AutoCloseable {
say(
player,
"Вода окрашена. Окуните кожаную броню, шерсть или ковры; красители можно"
+ " смешивать.");
+ " смешивать.");
return true;
}
if (AstraCauldron.config().storePotions
@@ -1,6 +1,7 @@
package online.astradev.cauldron;
import com.google.gson.*;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
@@ -36,6 +37,7 @@ public final class SoupConfig {
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;
@@ -44,55 +46,95 @@ public final class SoupConfig {
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();
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 (ingredientCount < 1 || ingredientCount > 4 || soupStackSize < 1 || soupStackSize > 64 || !Float.isFinite(consumeSeconds) || consumeSeconds < .05 || consumeSeconds > 60)
if (ingredientCount < 1
|| ingredientCount > 4
|| soupStackSize < 1
|| soupStackSize > 64
|| !Float.isFinite(consumeSeconds)
|| consumeSeconds < .05
|| consumeSeconds > 60)
throw new IllegalArgumentException("Invalid ingredients/consumption settings");
if (!Float.isFinite(soundVolume) || soundVolume < 0 || soundVolume > 4 || messageOverrides == null
|| messageOverrides.containsValue(null)) throw new IllegalArgumentException("Invalid sound/messages");
if (servingsPerBrew < 1 || servingsPerBrew > 16 || !Double.isFinite(brewSeconds)
|| brewSeconds < .5 || brewSeconds > 60 || maxNutrition < 0
|| !Float.isFinite(maxSaturation) || maxSaturation < 0 || soupName == null || soupName.isBlank())
if (!Float.isFinite(soundVolume)
|| soundVolume < 0
|| soundVolume > 4
|| messageOverrides == null
|| messageOverrides.containsValue(null))
throw new IllegalArgumentException("Invalid sound/messages");
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 нужны пары");
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)
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("Некорректный эффект");
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_:./-]+"))
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");
if (s == null || !s.matches("#[0-9a-fA-F]{6}"))
throw new IllegalArgumentException("Цвет: #RRGGBB");
return Integer.parseInt(s.substring(1), 16);
}
}
@@ -3,19 +3,18 @@ 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);
@@ -27,12 +26,28 @@ final class SoupDisplay extends Display.ItemDisplay {
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)));
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;
}
@Override public boolean shouldBeSaved() { return false; }
@Override public boolean saveAsPassenger(ValueOutput output) { return false; }
}
@@ -2,28 +2,47 @@ 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;
import java.io.IOException;
import java.nio.file.*;
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); }
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();
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();
return ItemStack.CODEC
.parse(RegistryOps.create(JsonOps.INSTANCE, registries), json)
.getOrThrow();
}
}
@@ -1,9 +1,7 @@
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;
@@ -15,21 +13,40 @@ 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;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
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()); }
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); }
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;
@@ -41,32 +58,59 @@ public final class SoupPots implements AutoCloseable {
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.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 SoupConfig config() { return config; }
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 Ingredients ingredients() {
return ingredients;
}
public SoupConfig config() {
return config;
}
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 и предмет в руке");
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()));
// 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());
else
custom.item =
SoupFiles.encode(
Ingredients.normalizedCopy(player.getMainHandItem()),
server.registryAccess());
custom.nutrition = nutrition;
custom.saturation = saturation;
next.customIngredients.put(id, custom);
@@ -75,57 +119,108 @@ public final class SoupPots implements AutoCloseable {
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");
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 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());
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);
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.isEmpty() : !p.items.isEmpty())))
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.isEmpty() : !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); }
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);
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);
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);
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);
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);
var level = player.level();
var pos = Position.at(level, blockPos);
var pot = pots.get(pos);
if (player.isSpectator()) return false;
if (!config.soupsEnabled && pot == null) return false;
if (hand != InteractionHand.MAIN_HAND) return pot != null;
@@ -135,117 +230,282 @@ public final class SoupPots implements AutoCloseable {
if (pot == null && ingredients.read(held) == null) return false;
if (pot == null) {
if (config.requireFullWater && state.getValue(LayeredCauldronBlock.LEVEL) != 3) {
say(player, "Сначала наполните котёл водой доверху."); return true;
say(player, "Сначала наполните котёл водой доверху.");
return true;
}
pot = Pot.raw(List.of());
}
if (pot.brewing()) { say(player, (!config.requireHeat || CauldronHeat.heated(level, blockPos)) ? "Суп варится… Осталось: " + Math.max(1, (pot.brewTicks - elapsed.getOrDefault(pos, 0) + 19) / 20) + " с." : "Варка приостановлена. Зажгите костёр под котлом."); return true; }
if (pot.brewing()) {
say(
player,
(!config.requireHeat || CauldronHeat.heated(level, blockPos))
? "Суп варится… Осталось: "
+ 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);
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;
say(
player,
left == 0
? "Последняя порция собрана. Котёл пуст."
: "Осталось порций: " + left + ".");
return true;
}
if (pot.items.size() >= config.ingredientCount && (player.isShiftKeyDown() || !held.isEmpty())) {
if (config.requireHeat && !CauldronHeat.heated(level, blockPos)) { say(player, "Для варки нужен горящий костёр прямо под котлом."); return true; }
if (pot.items.size() >= config.ingredientCount
&& (player.isShiftKeyDown() || !held.isEmpty())) {
if (config.requireHeat && !CauldronHeat.heated(level, blockPos)) {
say(player, "Для варки нужен горящий костёр прямо под котлом.");
return true;
}
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 (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() + "/" + config.ingredientCount + "."); 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()
+ "/"
+ config.ingredientCount
+ ".");
return true;
}
if (ingredients.read(held) == null) { say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/" + config.ingredientCount + "."); 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() + "/" + config.ingredientCount + "." + (items.size() == config.ingredientCount ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." : ""));
if (ingredients.read(held) == null) {
say(
player,
"Добавьте еду или зелье. В котле: "
+ pot.items.size()
+ "/"
+ config.ingredientCount
+ ".");
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()
+ "/"
+ config.ingredientCount
+ "."
+ (items.size() == config.ingredientCount
? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний."
: ""));
return true;
}
public boolean breakPot(ServerLevel level, BlockPos blockPos) {
var pos = Position.at(level, blockPos); var old = pots.get(pos);
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());
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; }
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;
}
boolean heated = !config.requireHeat || CauldronHeat.heated(level, pos.pos);
if (pot.brewing() && heated) {
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))) {
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);
if (config.particles) level.sendParticles(ParticleTypes.CLOUD, pos.pos.getX() + .5, pos.pos.getY() + 1.05, pos.pos.getZ() + .5, 12, .2, .12, .2, .01);
if (config.particles)
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 (config.ingredientDisplays && 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) + (heated ? 2 : 0), pot.brewTicks);
for (int i = 0; i < displays.size(); i++)
displays.get(i)
.ingredient(
i,
water,
ticks + 2,
elapsed.getOrDefault(pos, 0) + (heated ? 2 : 0),
pot.brewTicks);
}
}
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();
}
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)));
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;
}
if (!config.ingredientDisplays) {
removeVisuals(pos);
return;
}
if (!config.ingredientDisplays) { removeVisuals(pos); return; }
var existing = visuals.get(pos);
if (existing != null && existing.stream().anyMatch(d -> d.isRemoved())) { removeVisuals(pos); existing = null; }
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);
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);
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);
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)));
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() {
@Override
public void close() {
for (var pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos);
water.removeAll(WATER_OWNER);
}
private void sound(ServerLevel level, BlockPos pos, SoundEvent sound) { if (config.sounds) level.playSound(null, pos, sound, SoundSource.BLOCKS, config.soundVolume, 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) { var config = AstraCauldron.config(); if (config.messages) player.sendSystemMessage(Component.literal(config.messageOverrides.getOrDefault(text, text)).withStyle(ChatFormatting.GOLD), true); }
private static void saveError(ServerPlayer player) { say(player, "Не удалось сохранить котёл. Обратитесь к администратору."); }
private void sound(ServerLevel level, BlockPos pos, SoundEvent sound) {
if (config.sounds)
level.playSound(null, pos, sound, SoundSource.BLOCKS, config.soundVolume, 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) {
var config = AstraCauldron.config();
if (config.messages)
player.sendSystemMessage(
Component.literal(config.messageOverrides.getOrDefault(text, text))
.withStyle(ChatFormatting.GOLD),
true);
}
private static void saveError(ServerPlayer player) {
say(player, "Не удалось сохранить котёл. Обратитесь к администратору.");
}
}
@@ -1,46 +1,61 @@
package online.astradev.cauldron;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.nio.file.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.List;
import static java.nio.charset.StandardCharsets.UTF_8;
/** Export before AstraPlus's startup pack build; upgrade only known, unmodified defaults. */
final class SoupResources {
// Bundled flat-colour model in 0.2.0–0.2.3, with normalized newlines and outer whitespace.
private static final String FLAT_MODEL_SHA256 =
"51b5c2b0561ec815e5ddaff5654ce04fffa0995fc3e5972323f385d58842cd2c";
private SoupResources() {}
static void install(Path root) throws IOException {
for (String name : List.of("items/combined_soup.json",
"models/item/soup_liquid.json")) {
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());
boolean exists = Files.exists(target, LinkOption.NOFOLLOW_LINKS);
if (exists && !(name.equals("models/item/soup_liquid.json") && isFlatDefault(target))) continue;
try (var input = SoupResources.class.getResourceAsStream("/astra-resources/" + relative)) {
if (exists && !(name.equals("models/item/soup_liquid.json") && isFlatDefault(target)))
continue;
try (var input =
SoupResources.class.getResourceAsStream("/astra-resources/" + relative)) {
if (input == null) throw new IOException("Missing resource " + relative);
if (!exists) Files.copy(input, target);
else {
Path temp = Files.createTempFile(target.getParent(), "soup-model-", ".tmp");
try {
Files.copy(input, temp, StandardCopyOption.REPLACE_EXISTING);
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} finally { Files.deleteIfExists(temp); }
Files.move(
temp,
target,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(temp);
}
}
}
}
}
private static boolean isFlatDefault(Path path) throws IOException {
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.size(path) > 8192) return false;
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.size(path) > 8192)
return false;
String model = Files.readString(path, UTF_8).replace("\r\n", "\n").trim();
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
.digest(model.getBytes(UTF_8))).equals(FLAT_MODEL_SHA256);
} catch (NoSuchAlgorithmException impossible) { throw new AssertionError(impossible); }
return HexFormat.of()
.formatHex(MessageDigest.getInstance("SHA-256").digest(model.getBytes(UTF_8)))
.equals(FLAT_MODEL_SHA256);
} catch (NoSuchAlgorithmException impossible) {
throw new AssertionError(impossible);
}
}
}
@@ -5,6 +5,7 @@ import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.crafting.*;
import net.minecraft.world.level.block.entity.CampfireBlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
@@ -13,8 +14,13 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(CampfireBlockEntity.class)
public abstract class CampfireHeatMixin {
@Inject(method = "cookTick", at = @At("TAIL"))
private static void astracauldron$heat(ServerLevel level, BlockPos pos, BlockState state, CampfireBlockEntity entity,
RecipeManager.CachedCheck<SingleRecipeInput, CampfireCookingRecipe> recipes, CallbackInfo ci) {
private static void astracauldron$heat(
ServerLevel level,
BlockPos pos,
BlockState state,
CampfireBlockEntity entity,
RecipeManager.CachedCheck<SingleRecipeInput, CampfireCookingRecipe> recipes,
CallbackInfo ci) {
online.astradev.cauldron.CauldronHeat.tick(level, pos);
}
}
@@ -6,7 +6,9 @@ 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;
@@ -15,11 +17,18 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@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) {
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) {
private void soups$drip(
BlockState state, Level level, BlockPos pos, Fluid fluid, CallbackInfo ci) {
if (AstraCauldron.occupied(level, pos)) ci.cancel();
}
}
@@ -4,7 +4,9 @@ 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;
@@ -4,6 +4,7 @@ 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;
@@ -11,16 +12,21 @@ 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) {
@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" -> {
var config = online.astradev.cauldron.AstraCauldron.config();
if (config.normalizeVanillaSoups) components.set(DataComponents.MAX_STACK_SIZE, config.soupStackSize);
if (config.normalizeVanillaSoups)
components.set(DataComponents.MAX_STACK_SIZE, config.soupStackSize);
}
default -> { }
default -> {}
}
}
}