Files
AstraCauldron/src/main/java/online/astradev/cauldron/LiquidPots.java
T

436 lines
18 KiB
Java
Raw Normal View History

package online.astradev.cauldron;
import com.google.gson.*;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
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.*;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
/**
* 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);
}
public String source() {
if (potion == null) return "dyed_water";
return potion.contents()
.potion()
.flatMap(holder -> holder.unwrapKey())
.map(key -> key.identifier().toString())
.orElse("astracauldron:custom_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;
}
public boolean applyRecipe(ServerLevel level, BlockPos blockPos, int remaining, Integer color) {
var pos = Position.at(level, blockPos);
var previous = liquids.get(pos);
if (remaining < 0 || remaining > 3)
throw new IllegalArgumentException("Invalid remaining liquid");
Liquid next = null;
if (remaining > 0) {
int rgb = color == null ? Objects.requireNonNull(previous).rgb : color;
next = new Liquid(remaining, rgb, previous == null ? null : previous.potion);
}
if (!change(pos, next)) return false;
level.setBlock(blockPos, Blocks.CAULDRON.defaultBlockState(), 3);
if (next != null) setVisual(level, pos, next);
return true;
}
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 (AstraCauldron.config().dyeWater
&& 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 (AstraCauldron.config().storePotions
&& 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 (AstraCauldron.config().dyeWater && 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 blocks = api.dyeBlocks(held, liquid.rgb, liquid.levels);
if (AstraCauldron.config().dyeBlocks && blocks.isPresent()) {
var batch = blocks.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;
}
var armor = api.dyeArmor(held, liquid.rgb);
if (AstraCauldron.config().dyeArmor && 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 (!AstraCauldron.config().storePotions) return true;
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 (AstraCauldron.config().tipArrows && 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) {
var config = AstraCauldron.config();
if (config.sounds)
level.playSound(
null, pos, SoundEvents.BOTTLE_FILL, SoundSource.BLOCKS, config.soundVolume, 1);
}
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 error(ServerPlayer player) {
say(player, "Не удалось сохранить котёл. Действие отменено.");
}
}