Apply registered cauldron recipes with heat liquid source and persistent color
This commit is contained in:
@@ -10,10 +10,13 @@ Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+, без Paper и ItemsAdder.
|
|||||||
`old-mods/YYYYMMDD-HHMMSS/` с сохранением имени. Не оставлять две версии в `mods`.
|
`old-mods/YYYYMMDD-HHMMSS/` с сохранением имени. Не оставлять две версии в `mods`.
|
||||||
- Сравнивать SHA-256 установленного файла и сборки. При блокировке файла сообщить,
|
- Сравнивать SHA-256 установленного файла и сборки. При блокировке файла сообщить,
|
||||||
не использовать отложенные установки. Конфигурации, данные и миры не заменять.
|
не использовать отложенные установки. Конфигурации, данные и миры не заменять.
|
||||||
- AstraPlus 0.5.1+ — обязательная зависимость. Публичные интерфейсы `CauldronApi` и
|
- AstraPlus 0.7.x — обязательная зависимость. Публичные интерфейсы `CauldronApi` и
|
||||||
`ColoredWaterApi` принадлежат AstraPlus; мод котлов использует их для преобразования
|
`ColoredWaterApi` принадлежат AstraPlus; мод котлов использует их для преобразования
|
||||||
предметов и отображения жидкости. Не дублировать здесь модель/рендер цветной воды.
|
предметов и отображения жидкости. Не дублировать здесь модель/рендер цветной воды.
|
||||||
- В AstraCauldron живут игровые взаимодействия, расход предметов, варка и сохранение котлов.
|
- В AstraCauldron живут игровые взаимодействия, расход предметов, варка и сохранение котлов.
|
||||||
|
RegisteredRecipes обслуживает Java/файловые рецепты AstraPlus: источник жидкости,
|
||||||
|
точный уровень, зажжённый обычный/душевный костёр снизу, расход и цвет остатка воды.
|
||||||
|
Сохранение жидкости должно завершаться до расхода ингредиента и выдачи результата.
|
||||||
- Клиенту достаточно ванильного Minecraft и серверного ресурспака. Не регистрировать
|
- Клиенту достаточно ванильного Minecraft и серверного ресурспака. Не регистрировать
|
||||||
клиентские предметы/блоки и обязательные сетевые каналы.
|
клиентские предметы/блоки и обязательные сетевые каналы.
|
||||||
- Проверки с игровым миром запускать только в отдельном каталоге `build` и с флагом
|
- Проверки с игровым миром запускать только в отдельном каталоге `build` и с флагом
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# AstraCauldron
|
# AstraCauldron
|
||||||
|
|
||||||
Серверный мод котлов для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**.
|
Серверный мод котлов для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**.
|
||||||
Переименован и перенесён из AstraSoups. Требуется **AstraPlus 0.5.58+**.
|
Переименован и перенесён из AstraSoups. Требуется **AstraPlus 0.7.x**.
|
||||||
Игроку достаточно ванильного клиента и актуального ресурспака AstraPlus/AstraPacks.
|
Игроку достаточно ванильного клиента и актуального ресурспака AstraPlus/AstraPacks.
|
||||||
|
|
||||||
## Режимы котла
|
## Режимы котла
|
||||||
@@ -12,9 +12,19 @@
|
|||||||
Готовые порции можно забирать без огня. При перезапуске незаконченная варка, как и раньше,
|
Готовые порции можно забирать без огня. При перезапуске незаконченная варка, как и раньше,
|
||||||
начинает отсчёт заново и ждёт горящего костра.
|
начинает отсчёт заново и ждёт горящего костра.
|
||||||
|
|
||||||
В версии 0.2.2 обычные котлы выполняют рецепты из вкладки «Рецепты» AstraPlusEditor:
|
В версии 0.3.0 котлы выполняют также Java-рецепты через `ContentRegistry.recipe` AstraPlus.
|
||||||
предмет и его количество, тип жидкости, точный уровень, расход и результат. Определения принадлежат AstraPlus,
|
Задаются предмет и количество, источник жидкости, точный уровень, расход, результат,
|
||||||
а расход и выдача — AstraCauldron. Супы, цветная вода и сохранённые зелья сохраняют свои правила.
|
условие нагрева и цвет оставшейся воды. Проверяется зажжённый обычный костёр, костёр душ,
|
||||||
|
любой из них либо отсутствие нагрева. Источником может быть чистая/цветная вода,
|
||||||
|
лава, рыхлый снег, пустой котёл или ID сохранённого зелья.
|
||||||
|
|
||||||
|
Рецепт выполняется мгновенно по ПКМ. Цвет относится к оставшейся воде; он и её объём
|
||||||
|
сохраняются до расхода ингредиента. Зарегистрированный рецепт имеет приоритет перед
|
||||||
|
обычными действиями с жидкостями. Если он не подходит, действуют правила ниже.
|
||||||
|
Котёл с супом остаётся под управлением механики супов. Время варки супа не меняется.
|
||||||
|
|
||||||
|
Пример Java-регистрации и контракт находятся в соседнем AstraPlus:
|
||||||
|
`examples/WorkshopContent.java`, `docs/content-api.md`.
|
||||||
|
|
||||||
| Действие | Результат |
|
| Действие | Результат |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
|
|||||||
+2
-2
@@ -3,10 +3,10 @@ plugins {
|
|||||||
id("net.neoforged.moddev") version "2.0.146"
|
id("net.neoforged.moddev") version "2.0.146"
|
||||||
}
|
}
|
||||||
group = "online.astradev"
|
group = "online.astradev"
|
||||||
version = "0.2.5"
|
version = "0.3.0"
|
||||||
repositories { mavenCentral() }
|
repositories { mavenCentral() }
|
||||||
val astraPlusApi = providers.gradleProperty("astraPlusApi")
|
val astraPlusApi = providers.gradleProperty("astraPlusApi")
|
||||||
.orElse("../AstraPlus/build/libs/AstraPlus-0.5.58-api.jar")
|
.orElse("../AstraPlus/build/libs/AstraPlus-0.7.0.jar")
|
||||||
dependencies {
|
dependencies {
|
||||||
compileOnly(files(astraPlusApi))
|
compileOnly(files(astraPlusApi))
|
||||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package online.astradev.cauldron;
|
package online.astradev.cauldron;
|
||||||
|
|
||||||
import com.mojang.brigadier.arguments.*;
|
import com.mojang.brigadier.arguments.*;
|
||||||
|
|
||||||
import net.minecraft.commands.Commands;
|
import net.minecraft.commands.Commands;
|
||||||
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.network.chat.Component;
|
import net.minecraft.network.chat.Component;
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.server.level.ServerPlayer;
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
@@ -9,7 +11,6 @@ import net.minecraft.util.TriState;
|
|||||||
import net.minecraft.world.InteractionResult;
|
import net.minecraft.world.InteractionResult;
|
||||||
import net.minecraft.world.entity.item.ItemEntity;
|
import net.minecraft.world.entity.item.ItemEntity;
|
||||||
import net.minecraft.world.level.Level;
|
import net.minecraft.world.level.Level;
|
||||||
import net.minecraft.core.BlockPos;
|
|
||||||
import net.neoforged.api.distmarker.Dist;
|
import net.neoforged.api.distmarker.Dist;
|
||||||
import net.neoforged.bus.api.EventPriority;
|
import net.neoforged.bus.api.EventPriority;
|
||||||
import net.neoforged.fml.common.Mod;
|
import net.neoforged.fml.common.Mod;
|
||||||
@@ -21,6 +22,7 @@ import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
|||||||
import net.neoforged.neoforge.event.level.*;
|
import net.neoforged.neoforge.event.level.*;
|
||||||
import net.neoforged.neoforge.event.server.*;
|
import net.neoforged.neoforge.event.server.*;
|
||||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||||
|
|
||||||
import org.slf4j.*;
|
import org.slf4j.*;
|
||||||
|
|
||||||
@Mod(value = "astracauldron", dist = Dist.DEDICATED_SERVER)
|
@Mod(value = "astracauldron", dist = Dist.DEDICATED_SERVER)
|
||||||
@@ -29,6 +31,7 @@ public final class AstraCauldron {
|
|||||||
private static SoupPots pots;
|
private static SoupPots pots;
|
||||||
private static final SoupConfig DEFAULT_CONFIG = new SoupConfig();
|
private static final SoupConfig DEFAULT_CONFIG = new SoupConfig();
|
||||||
private static LiquidPots liquids;
|
private static LiquidPots liquids;
|
||||||
|
|
||||||
public AstraCauldron() {
|
public AstraCauldron() {
|
||||||
NeoForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::resources);
|
NeoForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::resources);
|
||||||
NeoForge.EVENT_BUS.addListener(this::start);
|
NeoForge.EVENT_BUS.addListener(this::start);
|
||||||
@@ -42,78 +45,233 @@ public final class AstraCauldron {
|
|||||||
NeoForge.EVENT_BUS.addListener(this::join);
|
NeoForge.EVENT_BUS.addListener(this::join);
|
||||||
NeoForge.EVENT_BUS.addListener(this::commands);
|
NeoForge.EVENT_BUS.addListener(this::commands);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void resources(ServerAboutToStartEvent event) {
|
private void resources(ServerAboutToStartEvent event) {
|
||||||
try { SoupResources.install(FMLPaths.GAMEDIR.get()); }
|
try {
|
||||||
catch (Exception e) { throw new IllegalStateException("Cannot export AstraCauldron resources", e); }
|
SoupResources.install(FMLPaths.GAMEDIR.get());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException("Cannot export AstraCauldron resources", e);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void start(ServerStartedEvent event) {
|
private void start(ServerStartedEvent event) {
|
||||||
try {
|
try {
|
||||||
online.astradev.plus.api.AstraPlusApi.current().orElseThrow(() -> new IllegalStateException("AstraPlus API unavailable"));
|
online.astradev.plus.api.AstraPlusApi.current()
|
||||||
pots = new SoupPots(event.getServer(), FMLPaths.CONFIGDIR.get().resolve("astracauldron.json"));
|
.orElseThrow(() -> new IllegalStateException("AstraPlus API unavailable"));
|
||||||
|
pots =
|
||||||
|
new SoupPots(
|
||||||
|
event.getServer(),
|
||||||
|
FMLPaths.CONFIGDIR.get().resolve("astracauldron.json"));
|
||||||
liquids = new LiquidPots(event.getServer());
|
liquids = new LiquidPots(event.getServer());
|
||||||
LOG.info("AstraCauldron ready: NeoForge 26.2, AstraPlus API");
|
LOG.info("AstraCauldron ready: NeoForge 26.2, AstraPlus API");
|
||||||
} catch (Exception e) { throw new IllegalStateException("Cannot initialize AstraCauldron; existing data preserved", e); }
|
} 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; }
|
private void stop(ServerStoppingEvent event) {
|
||||||
public static SoupConfig config() { return pots == null ? DEFAULT_CONFIG : pots.config(); }
|
if (pots != null) pots.close();
|
||||||
public static LiquidPots liquids() { return liquids; }
|
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 SoupConfig config() {
|
||||||
|
return pots == null ? DEFAULT_CONFIG : pots.config();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LiquidPots liquids() {
|
||||||
|
return liquids;
|
||||||
|
}
|
||||||
|
|
||||||
public static boolean occupied(Level level, BlockPos pos) {
|
public static boolean occupied(Level level, BlockPos pos) {
|
||||||
return level instanceof ServerLevel serverLevel && ((pots != null && pots.contains(serverLevel, pos))
|
return level instanceof ServerLevel serverLevel
|
||||||
|| (liquids != null && liquids.contains(serverLevel,pos)));
|
&& ((pots != null && pots.contains(serverLevel, pos))
|
||||||
|
|| (liquids != null && liquids.contains(serverLevel, pos)));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void interact(PlayerInteractEvent.RightClickBlock event) {
|
private void interact(PlayerInteractEvent.RightClickBlock event) {
|
||||||
if (pots == null || event.isCanceled() || event.getUseBlock() == TriState.FALSE || event.getUseItem() == TriState.FALSE) return;
|
if (pots == null
|
||||||
if (event.getEntity() instanceof ServerPlayer player && EditorCauldronRecipes.interact(player, event.getPos(), event.getHand())) {
|
|| event.isCanceled()
|
||||||
event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS); return;
|
|| 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
|
if (event.getEntity() instanceof ServerPlayer player
|
||||||
&& liquids.interact(player,event.getPos(),event.getHand())) || pots.interact(player, event.getPos(), event.getHand()))) {
|
&& ((!pots.contains(player.level(), event.getPos())
|
||||||
event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS);
|
&& 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) {
|
private void breakBlock(net.neoforged.neoforge.event.level.block.BreakBlockEvent event) {
|
||||||
if (!event.isCanceled() && pots != null && event.getLevel() instanceof ServerLevel level
|
if (!event.isCanceled()
|
||||||
&& (!pots.breakPot(level, event.getPos()) || (liquids != null && !liquids.breakPot(level,event.getPos())))) { event.setCanceled(true); event.setNotifyClient(true); }
|
&& 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) {
|
private void explosion(ExplosionEvent.Detonate event) {
|
||||||
if (pots != null && event.getLevel() instanceof ServerLevel level)
|
if (pots != null && event.getLevel() instanceof ServerLevel level)
|
||||||
event.getAffectedBlocks().removeIf(pos -> occupied(level, pos));
|
event.getAffectedBlocks().removeIf(pos -> occupied(level, pos));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void piston(PistonEvent.Pre event) {
|
private void piston(PistonEvent.Pre event) {
|
||||||
if (pots == null || event.isCanceled() || !(event.getLevel() instanceof ServerLevel level)) return;
|
if (pots == null || event.isCanceled() || !(event.getLevel() instanceof ServerLevel level))
|
||||||
|
return;
|
||||||
var resolver = event.getStructureHelper();
|
var resolver = event.getStructureHelper();
|
||||||
if (resolver != null && resolver.resolve() && (resolver.getToPush().stream().anyMatch(p -> occupied(level, p))
|
if (resolver != null
|
||||||
|| resolver.getToDestroy().stream().anyMatch(p -> occupied(level, p)))) event.setCanceled(true);
|
&& 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) {
|
private void unload(ChunkEvent.Unload event) {
|
||||||
if (pots != null && event.getLevel() instanceof ServerLevel level)
|
if (pots != null && event.getLevel() instanceof ServerLevel level)
|
||||||
pots.unload(level, event.getChunk().getPos().x(), event.getChunk().getPos().z());
|
pots.unload(level, event.getChunk().getPos().x(), event.getChunk().getPos().z());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void join(EntityJoinLevelEvent event) {
|
private void join(EntityJoinLevelEvent event) {
|
||||||
if (event.loadedFromDisk() && event.getEntity().entityTags().contains(SoupDisplay.TAG)) event.setCanceled(true);
|
if (event.loadedFromDisk() && event.getEntity().entityTags().contains(SoupDisplay.TAG))
|
||||||
else if (event.getEntity() instanceof ItemEntity item) Ingredients.normalize(item.getItem());
|
event.setCanceled(true);
|
||||||
|
else if (event.getEntity() instanceof ItemEntity item)
|
||||||
|
Ingredients.normalize(item.getItem());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void commands(RegisterCommandsEvent event) {
|
private void commands(RegisterCommandsEvent event) {
|
||||||
var command = Commands.literal("cauldron").executes(c -> {
|
var command =
|
||||||
c.getSource().sendSuccess(() -> Component.literal("Краситель + вода: окрашивание брони. Зелье + пустой котёл: хранение и стрелы с эффектом. Еда/зелья + полный котёл воды: 4 ингредиента супа, Shift+ПКМ — варка, миска — порция."), false); return 1;
|
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 -> {
|
command.then(
|
||||||
try { requirePots().reload(); c.getSource().sendSuccess(() -> Component.literal("AstraCauldron: настройки применены."), true); return 1; }
|
Commands.literal("reload")
|
||||||
catch (Exception e) { c.getSource().sendFailure(Component.literal("Ошибка: " + e.getMessage() + ". Прежние настройки сохранены.")); return 0; }
|
.requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
||||||
}));
|
.executes(
|
||||||
command.then(Commands.literal("register").requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
c -> {
|
||||||
.then(Commands.argument("id", StringArgumentType.word()).then(Commands.argument("nutrition", IntegerArgumentType.integer(0))
|
|
||||||
.then(Commands.argument("saturation", FloatArgumentType.floatArg(0)).executes(c -> {
|
|
||||||
try {
|
try {
|
||||||
requirePots().register(StringArgumentType.getString(c, "id"), c.getSource().getPlayerOrException(),
|
requirePots().reload();
|
||||||
IntegerArgumentType.getInteger(c, "nutrition"), FloatArgumentType.getFloat(c, "saturation"));
|
c.getSource()
|
||||||
c.getSource().sendSuccess(() -> Component.literal("Ингредиент зарегистрирован."), true); return 1;
|
.sendSuccess(
|
||||||
} catch (Exception e) { c.getSource().sendFailure(Component.literal("Ошибка регистрации: " + e.getMessage())); return 0; }
|
() ->
|
||||||
|
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);
|
var root = event.getDispatcher().register(command);
|
||||||
event.getDispatcher().register(Commands.literal("soups").redirect(root).executes(root.getCommand()));
|
event.getDispatcher()
|
||||||
|
.register(Commands.literal("soups").redirect(root).executes(root.getCommand()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SoupPots requirePots() {
|
||||||
|
if (pots == null) throw new IllegalStateException("AstraCauldron ещё не запущен");
|
||||||
|
return pots;
|
||||||
}
|
}
|
||||||
private static SoupPots requirePots() { if (pots == null) throw new IllegalStateException("AstraCauldron ещё не запущен"); return pots; }
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,39 +0,0 @@
|
|||||||
package online.astradev.cauldron;
|
|
||||||
|
|
||||||
import net.minecraft.core.BlockPos;
|
|
||||||
import net.minecraft.server.level.ServerPlayer;
|
|
||||||
import net.minecraft.world.InteractionHand;
|
|
||||||
import net.minecraft.world.item.ItemStack;
|
|
||||||
import net.minecraft.world.level.block.Blocks;
|
|
||||||
import net.minecraft.world.level.block.LayeredCauldronBlock;
|
|
||||||
import net.neoforged.neoforge.common.NeoForge;
|
|
||||||
import online.astradev.plus.api.CauldronRecipeEvent;
|
|
||||||
|
|
||||||
/** Applies editor recipes only to ordinary cauldrons; saved soups and special liquids retain ownership. */
|
|
||||||
public final class EditorCauldronRecipes {
|
|
||||||
private EditorCauldronRecipes() {}
|
|
||||||
public static boolean interact(ServerPlayer player, BlockPos pos, InteractionHand hand) {
|
|
||||||
var level = player.level();
|
|
||||||
if (AstraCauldron.occupied(level, pos) || player.isSpectator() || !player.mayInteract(level, pos)) return false;
|
|
||||||
var state = level.getBlockState(pos);
|
|
||||||
String liquid = state.is(Blocks.CAULDRON) ? "empty" : state.is(Blocks.WATER_CAULDRON) ? "water"
|
|
||||||
: state.is(Blocks.LAVA_CAULDRON) ? "lava" : state.is(Blocks.POWDER_SNOW_CAULDRON) ? "powder_snow" : "";
|
|
||||||
if (liquid.isEmpty()) return false;
|
|
||||||
int fill = state.hasProperty(LayeredCauldronBlock.LEVEL) ? state.getValue(LayeredCauldronBlock.LEVEL) : liquid.equals("empty") ? 0 : 3;
|
|
||||||
var request = NeoForge.EVENT_BUS.post(new CauldronRecipeEvent(player.getItemInHand(hand), liquid, fill));
|
|
||||||
ItemStack output = request.output();
|
|
||||||
if (output.isEmpty()) return false;
|
|
||||||
int remaining = fill - request.liquidCost();
|
|
||||||
if (request.liquidCost() > 0) {
|
|
||||||
var next = remaining == 0 ? Blocks.CAULDRON.defaultBlockState() : state.setValue(LayeredCauldronBlock.LEVEL, remaining);
|
|
||||||
if (!level.setBlock(pos, next, 3)) return true;
|
|
||||||
}
|
|
||||||
ItemStack held = player.getItemInHand(hand);
|
|
||||||
held.consume(request.inputCount(), player);
|
|
||||||
if (held.isEmpty()) player.setItemInHand(hand, output);
|
|
||||||
else { player.getInventory().add(output); if (!output.isEmpty()) player.drop(output, false); }
|
|
||||||
level.playSound(null, pos, net.minecraft.sounds.SoundEvents.BUCKET_EMPTY, net.minecraft.sounds.SoundSource.BLOCKS, 0.5F, 1);
|
|
||||||
player.containerMenu.broadcastChanges();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +1,9 @@
|
|||||||
package online.astradev.cauldron;
|
package online.astradev.cauldron;
|
||||||
|
|
||||||
import com.google.gson.*;
|
import com.google.gson.*;
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.*;
|
|
||||||
import java.util.*;
|
|
||||||
import net.minecraft.ChatFormatting;
|
import net.minecraft.ChatFormatting;
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.core.component.DataComponents;
|
|
||||||
import net.minecraft.core.registries.Registries;
|
import net.minecraft.core.registries.Registries;
|
||||||
import net.minecraft.network.chat.Component;
|
import net.minecraft.network.chat.Component;
|
||||||
import net.minecraft.resources.*;
|
import net.minecraft.resources.*;
|
||||||
@@ -18,90 +15,201 @@ import net.minecraft.world.item.*;
|
|||||||
import net.minecraft.world.item.alchemy.Potions;
|
import net.minecraft.world.item.alchemy.Potions;
|
||||||
import net.minecraft.world.level.block.*;
|
import net.minecraft.world.level.block.*;
|
||||||
import net.minecraft.world.level.storage.LevelResource;
|
import net.minecraft.world.level.storage.LevelResource;
|
||||||
|
|
||||||
import online.astradev.plus.api.*;
|
import online.astradev.plus.api.*;
|
||||||
|
|
||||||
/** Persistent dyed water and potion storage; all item transformations and rendering use AstraPlus 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 {
|
public final class LiquidPots implements AutoCloseable {
|
||||||
private record Position(String dimension, BlockPos pos) {
|
private 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 Liquid(int levels, int rgb, CauldronApi.Potion potion) {
|
public record Liquid(int levels, int rgb, CauldronApi.Potion potion) {
|
||||||
public Liquid {
|
public Liquid {
|
||||||
if (levels < 1 || levels > 3 || rgb < 0 || rgb > 0xFFFFFF) throw new IllegalArgumentException("Invalid 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); }
|
|
||||||
|
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 static final Identifier OWNER = Identifier.parse("astracauldron:liquids");
|
||||||
private final MinecraftServer server;
|
private final MinecraftServer server;
|
||||||
private final CauldronApi api;
|
private final CauldronApi api;
|
||||||
private final Path file;
|
private final Path file;
|
||||||
private final Map<Position, Liquid> liquids = new LinkedHashMap<>();
|
private final Map<Position, Liquid> liquids = new LinkedHashMap<>();
|
||||||
|
|
||||||
public LiquidPots(MinecraftServer server) throws IOException {
|
public LiquidPots(MinecraftServer server) throws IOException {
|
||||||
this.server = server;
|
this.server = server;
|
||||||
api = AstraPlusApi.current().flatMap(AstraPlusApi::cauldrons).orElseThrow();
|
api = AstraPlusApi.current().flatMap(AstraPlusApi::cauldrons).orElseThrow();
|
||||||
file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/liquids.json");
|
file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/liquids.json");
|
||||||
if (Files.exists(file)) {
|
if (Files.exists(file)) {
|
||||||
var json = JsonParser.parseString(Files.readString(file)).getAsJsonObject();
|
var json = JsonParser.parseString(Files.readString(file)).getAsJsonObject();
|
||||||
if (json.get("version").getAsInt() != 1) throw new IllegalArgumentException("Unknown liquid data version");
|
if (json.get("version").getAsInt() != 1)
|
||||||
|
throw new IllegalArgumentException("Unknown liquid data version");
|
||||||
for (var entry : json.getAsJsonArray("cauldrons")) {
|
for (var entry : json.getAsJsonArray("cauldrons")) {
|
||||||
var c = entry.getAsJsonObject();
|
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()));
|
var pos =
|
||||||
CauldronApi.Potion potion = c.has("potion") ? api.potion(SoupFiles.decode(c.get("potion"), server.registryAccess())).orElseThrow() : null;
|
new Position(
|
||||||
var liquid = new Liquid(c.get("levels").getAsInt(), c.get("rgb").getAsInt(), potion);
|
Identifier.parse(c.get("dimension").getAsString()).toString(),
|
||||||
if (liquids.putIfAbsent(pos, liquid) != null) throw new IllegalArgumentException("Duplicate liquid cauldron");
|
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 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) {
|
private boolean change(Position pos, Liquid next) {
|
||||||
var old = liquids.get(pos);
|
var old = liquids.get(pos);
|
||||||
if (next == null) liquids.remove(pos); else liquids.put(pos, next);
|
if (next == null) liquids.remove(pos);
|
||||||
|
else liquids.put(pos, next);
|
||||||
try {
|
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 entry : liquids.entrySet()) {
|
for (var entry : liquids.entrySet()) {
|
||||||
var p = entry.getKey(); var liquid = entry.getValue(); var c = new JsonObject();
|
var p = entry.getKey();
|
||||||
c.addProperty("dimension", p.dimension); c.addProperty("x", p.pos.getX()); c.addProperty("y", p.pos.getY()); c.addProperty("z", p.pos.getZ());
|
var liquid = entry.getValue();
|
||||||
c.addProperty("levels", liquid.levels); c.addProperty("rgb", liquid.rgb);
|
var c = new JsonObject();
|
||||||
if (liquid.potion != null) c.add("potion", SoupFiles.encode(api.bottle(liquid.potion), server.registryAccess()));
|
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);
|
array.add(c);
|
||||||
}
|
}
|
||||||
SoupFiles.write(file, root);
|
SoupFiles.write(file, root);
|
||||||
if (next == null) removeSurface(pos);
|
if (next == null) removeSurface(pos);
|
||||||
return true;
|
return true;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if (old == null) liquids.remove(pos); else liquids.put(pos, old);
|
if (old == null) liquids.remove(pos);
|
||||||
AstraCauldron.LOG.error("Не удалось сохранить жидкость; действие отменено", e); return false;
|
else liquids.put(pos, old);
|
||||||
|
AstraCauldron.LOG.error("Не удалось сохранить жидкость; действие отменено", e);
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) {
|
public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) {
|
||||||
if (player.isSpectator()) return false;
|
if (player.isSpectator()) return false;
|
||||||
var level = player.level(); var pos = Position.at(level, blockPos); var liquid = liquids.get(pos);
|
var level = player.level();
|
||||||
|
var pos = Position.at(level, blockPos);
|
||||||
|
var liquid = liquids.get(pos);
|
||||||
if (hand != InteractionHand.MAIN_HAND) return liquid != null;
|
if (hand != InteractionHand.MAIN_HAND) return liquid != null;
|
||||||
var state = level.getBlockState(blockPos); var held = player.getMainHandItem();
|
var state = level.getBlockState(blockPos);
|
||||||
|
var held = player.getMainHandItem();
|
||||||
if (!state.is(Blocks.CAULDRON) && !state.is(Blocks.WATER_CAULDRON)) return false;
|
if (!state.is(Blocks.CAULDRON) && !state.is(Blocks.WATER_CAULDRON)) return false;
|
||||||
var potion = api.potion(held);
|
var potion = api.potion(held);
|
||||||
if (liquid == null) {
|
if (liquid == null) {
|
||||||
if (potion.isPresent() && plainWater(potion.get())) {
|
if (potion.isPresent() && plainWater(potion.get())) {
|
||||||
int current = state.is(Blocks.WATER_CAULDRON) ? state.getValue(LayeredCauldronBlock.LEVEL) : 0;
|
int current =
|
||||||
|
state.is(Blocks.WATER_CAULDRON)
|
||||||
|
? state.getValue(LayeredCauldronBlock.LEVEL)
|
||||||
|
: 0;
|
||||||
if (current < 3) {
|
if (current < 3) {
|
||||||
level.setBlock(blockPos,Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL,current+1),3);
|
level.setBlock(
|
||||||
consumeAndGive(player,1,new ItemStack(Items.GLASS_BOTTLE));
|
blockPos,
|
||||||
|
Blocks.WATER_CAULDRON
|
||||||
|
.defaultBlockState()
|
||||||
|
.setValue(LayeredCauldronBlock.LEVEL, current + 1),
|
||||||
|
3);
|
||||||
|
consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE));
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
var dye = api.mixDye(OptionalInt.empty(), held);
|
var dye = api.mixDye(OptionalInt.empty(), held);
|
||||||
if (AstraCauldron.config().dyeWater && state.is(Blocks.WATER_CAULDRON) && dye.isPresent()) {
|
if (AstraCauldron.config().dyeWater
|
||||||
var next = new Liquid(state.getValue(LayeredCauldronBlock.LEVEL), dye.getAsInt(), null);
|
&& state.is(Blocks.WATER_CAULDRON)
|
||||||
if (!change(pos, next)) { error(player); return true; }
|
&& dye.isPresent()) {
|
||||||
held.consume(1, player); setVisual(level, pos, next);
|
var next =
|
||||||
say(player, "Вода окрашена. Окуните кожаную броню, шерсть или ковры; красители можно смешивать."); return true;
|
new Liquid(
|
||||||
|
state.getValue(LayeredCauldronBlock.LEVEL), dye.getAsInt(), null);
|
||||||
|
if (!change(pos, next)) {
|
||||||
|
error(player);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
if (AstraCauldron.config().storePotions && state.is(Blocks.CAULDRON) && potion.isPresent()) {
|
held.consume(1, player);
|
||||||
var next = new Liquid(1, potion.get().contents().getColor() & 0xFFFFFF, potion.get());
|
setVisual(level, pos, next);
|
||||||
if (!change(pos, next)) { error(player); return true; }
|
say(
|
||||||
consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE)); setVisual(level, pos, next);
|
player,
|
||||||
say(player, "Зелье налито: 1/3. Бутылочка — забрать, стрелы — обработать."); return true;
|
"Вода окрашена. Окуните кожаную броню, шерсть или ковры; красители можно"
|
||||||
|
+ " смешивать.");
|
||||||
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -109,96 +217,219 @@ public final class LiquidPots implements AutoCloseable {
|
|||||||
var dye = api.mixDye(OptionalInt.of(liquid.rgb), held);
|
var dye = api.mixDye(OptionalInt.of(liquid.rgb), held);
|
||||||
if (AstraCauldron.config().dyeWater && dye.isPresent()) {
|
if (AstraCauldron.config().dyeWater && dye.isPresent()) {
|
||||||
var next = new Liquid(liquid.levels, dye.getAsInt(), null);
|
var next = new Liquid(liquid.levels, dye.getAsInt(), null);
|
||||||
if (!change(pos, next)) { error(player); return true; }
|
if (!change(pos, next)) {
|
||||||
held.consume(1, player); setVisual(level,pos,next); return true;
|
error(player);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
held.consume(1, player);
|
||||||
|
setVisual(level, pos, next);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
var blocks = api.dyeBlocks(held, liquid.rgb, liquid.levels);
|
var blocks = api.dyeBlocks(held, liquid.rgb, liquid.levels);
|
||||||
if (AstraCauldron.config().dyeBlocks && blocks.isPresent()) {
|
if (AstraCauldron.config().dyeBlocks && blocks.isPresent()) {
|
||||||
var batch = blocks.get(); var result = batch.result();
|
var batch = blocks.get();
|
||||||
if (!decrease(level,pos,liquid,batch.levelsUsed())) { error(player); return true; }
|
var result = batch.result();
|
||||||
|
if (!decrease(level, pos, liquid, batch.levelsUsed())) {
|
||||||
|
error(player);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
int count = result.getCount();
|
int count = result.getCount();
|
||||||
consumeAndGive(player,count,result); sound(level,blockPos);
|
consumeAndGive(player, count, result);
|
||||||
say(player,"Окрашено предметов: " + count + "."); return true;
|
sound(level, blockPos);
|
||||||
|
say(player, "Окрашено предметов: " + count + ".");
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
var armor = api.dyeArmor(held, liquid.rgb);
|
var armor = api.dyeArmor(held, liquid.rgb);
|
||||||
if (AstraCauldron.config().dyeArmor && armor.isPresent()) {
|
if (AstraCauldron.config().dyeArmor && armor.isPresent()) {
|
||||||
if (!decrease(level,pos,liquid,1)) { error(player); return true; }
|
if (!decrease(level, pos, liquid, 1)) {
|
||||||
// Transform the equipped item, including Creative, preserving enchantments/damage/name.
|
error(player);
|
||||||
if (held.getCount() == 1) player.setItemInHand(hand, armor.get()); else consumeAndGive(player,1,armor.get());
|
return true;
|
||||||
sound(level,blockPos); say(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 (held.is(Items.WATER_BUCKET)) {
|
||||||
if (!change(pos,null)) { error(player); return true; }
|
if (!change(pos, null)) {
|
||||||
level.setBlock(blockPos, Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL,3),3);
|
error(player);
|
||||||
consumeAndGive(player,1,new ItemStack(Items.BUCKET)); return true;
|
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 (held.is(Items.BUCKET) && liquid.levels == 3) {
|
||||||
if (!decrease(level,pos,liquid,3)) { error(player); return true; }
|
if (!decrease(level, pos, liquid, 3)) {
|
||||||
consumeAndGive(player,1,new ItemStack(Items.WATER_BUCKET)); return true;
|
error(player);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
consumeAndGive(player, 1, new ItemStack(Items.WATER_BUCKET));
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
if (held.is(Items.GLASS_BOTTLE)) {
|
if (held.is(Items.GLASS_BOTTLE)) {
|
||||||
if (!decrease(level,pos,liquid,1)) { error(player); return true; }
|
if (!decrease(level, pos, liquid, 1)) {
|
||||||
consumeAndGive(player,1,api.bottle(new CauldronApi.Potion(new net.minecraft.world.item.alchemy.PotionContents(Potions.WATER),1))); return true;
|
error(player);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
say(player,"Цветная вода: " + liquid.levels + "/3. Для варки супа нужна чистая вода."); 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.isPresent()) {
|
||||||
if (!AstraCauldron.config().storePotions) return true;
|
if (!AstraCauldron.config().storePotions) return true;
|
||||||
if (!potion.get().equals(liquid.potion)) { say(player,"В котле другое зелье. Сначала заберите его бутылочками."); return true; }
|
if (!potion.get().equals(liquid.potion)) {
|
||||||
if (liquid.levels == 3) { say(player,"Котёл уже полон."); return true; }
|
say(player, "В котле другое зелье. Сначала заберите его бутылочками.");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (liquid.levels == 3) {
|
||||||
|
say(player, "Котёл уже полон.");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
var next = liquid.withLevels(liquid.levels + 1);
|
var next = liquid.withLevels(liquid.levels + 1);
|
||||||
if (!change(pos,next)) { error(player); return true; }
|
if (!change(pos, next)) {
|
||||||
consumeAndGive(player,1,new ItemStack(Items.GLASS_BOTTLE)); setVisual(level,pos,next); return true;
|
error(player);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE));
|
||||||
|
setVisual(level, pos, next);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
if (held.is(Items.GLASS_BOTTLE)) {
|
if (held.is(Items.GLASS_BOTTLE)) {
|
||||||
var bottle = api.bottle(liquid.potion);
|
var bottle = api.bottle(liquid.potion);
|
||||||
if (!decrease(level,pos,liquid,1)) { error(player); return true; }
|
if (!decrease(level, pos, liquid, 1)) {
|
||||||
consumeAndGive(player,1,bottle); sound(level,blockPos); return true;
|
error(player);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
var arrows = api.tipArrows(held,liquid.potion,liquid.levels);
|
consumeAndGive(player, 1, bottle);
|
||||||
|
sound(level, blockPos);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
var arrows = api.tipArrows(held, liquid.potion, liquid.levels);
|
||||||
if (AstraCauldron.config().tipArrows && arrows.isPresent()) {
|
if (AstraCauldron.config().tipArrows && arrows.isPresent()) {
|
||||||
var batch = arrows.get(); var result = batch.result();
|
var batch = arrows.get();
|
||||||
if (!decrease(level,pos,liquid,batch.levelsUsed())) { error(player); return true; }
|
var result = batch.result();
|
||||||
|
if (!decrease(level, pos, liquid, batch.levelsUsed())) {
|
||||||
|
error(player);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
int count = result.getCount();
|
int count = result.getCount();
|
||||||
consumeAndGive(player,count,result); sound(level,blockPos);
|
consumeAndGive(player, count, result);
|
||||||
say(player,"Обработано стрел: " + count + "."); return true;
|
sound(level, blockPos);
|
||||||
|
say(player, "Обработано стрел: " + count + ".");
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
say(player,"Зелье: " + liquid.levels + "/3. Окуните обычные стрелы или наберите бутылочку."); return true;
|
say(
|
||||||
|
player,
|
||||||
|
"Зелье: " + liquid.levels + "/3. Окуните обычные стрелы или наберите бутылочку.");
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean decrease(ServerLevel level, Position pos, Liquid old, int used) {
|
private boolean decrease(ServerLevel level, Position pos, Liquid old, int used) {
|
||||||
int remaining = old.levels - used; var next = remaining == 0 ? null : old.withLevels(remaining);
|
int remaining = old.levels - used;
|
||||||
if (!change(pos,next)) return false;
|
var next = remaining == 0 ? null : old.withLevels(remaining);
|
||||||
level.setBlock(pos.pos,Blocks.CAULDRON.defaultBlockState(),3);
|
if (!change(pos, next)) return false;
|
||||||
if (next != null) setVisual(level,pos,next); return true;
|
level.setBlock(pos.pos, Blocks.CAULDRON.defaultBlockState(), 3);
|
||||||
|
if (next != null) setVisual(level, pos, next);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean plainWater(CauldronApi.Potion potion) {
|
private static boolean plainWater(CauldronApi.Potion potion) {
|
||||||
var contents = potion.contents();
|
var contents = potion.contents();
|
||||||
return contents.is(Potions.WATER) && contents.customColor().isEmpty() && contents.customName().isEmpty() && potion.durationScale()==1f;
|
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 boolean breakPot(ServerLevel level, BlockPos pos) {
|
||||||
|
var position = Position.at(level, pos);
|
||||||
|
return !liquids.containsKey(position) || change(position, null);
|
||||||
|
}
|
||||||
|
|
||||||
public void tick() {
|
public void tick() {
|
||||||
for (var entry : new ArrayList<>(liquids.entrySet())) {
|
for (var entry : new ArrayList<>(liquids.entrySet())) {
|
||||||
var pos=entry.getKey(); var level=level(pos);
|
var pos = entry.getKey();
|
||||||
if (level==null || !level.hasChunkAt(pos.pos)) continue;
|
var level = level(pos);
|
||||||
if (!level.getBlockState(pos.pos).is(Blocks.CAULDRON)) { change(pos,null); continue; }
|
if (level == null || !level.hasChunkAt(pos.pos)) continue;
|
||||||
surface(level,pos,entry.getValue());
|
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 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 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); }
|
private ServerLevel level(Position pos) {
|
||||||
@Override public void close() { api.water().removeAll(OWNER); }
|
return server.getLevel(
|
||||||
private static void consumeAndGive(ServerPlayer player,int count,ItemStack result) {
|
ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension)));
|
||||||
player.getMainHandItem().consume(count,player);
|
}
|
||||||
player.getInventory().add(result); if(!result.isEmpty()) player.drop(result,false);
|
|
||||||
|
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();
|
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 sound(ServerLevel level, BlockPos pos) {
|
||||||
private static void error(ServerPlayer player) { say(player,"Не удалось сохранить котёл. Действие отменено."); }
|
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, "Не удалось сохранить котёл. Действие отменено.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package online.astradev.cauldron;
|
||||||
|
|
||||||
|
import net.minecraft.core.BlockPos;
|
||||||
|
import net.minecraft.server.level.ServerLevel;
|
||||||
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
|
import net.minecraft.world.InteractionHand;
|
||||||
|
import net.minecraft.world.item.ItemStack;
|
||||||
|
import net.minecraft.world.level.block.Blocks;
|
||||||
|
import net.minecraft.world.level.block.CampfireBlock;
|
||||||
|
import net.minecraft.world.level.block.LayeredCauldronBlock;
|
||||||
|
import net.neoforged.neoforge.common.NeoForge;
|
||||||
|
|
||||||
|
import online.astradev.plus.api.CauldronRecipeEvent;
|
||||||
|
|
||||||
|
/** Java and editor recipes use the same matching and transactional liquid consumption. */
|
||||||
|
public final class RegisteredRecipes {
|
||||||
|
private RegisteredRecipes() {}
|
||||||
|
|
||||||
|
public static String heat(ServerLevel level, BlockPos pos) {
|
||||||
|
var below = level.getBlockState(pos.below());
|
||||||
|
if (!below.hasProperty(CampfireBlock.LIT) || !below.getValue(CampfireBlock.LIT))
|
||||||
|
return "none";
|
||||||
|
if (below.is(Blocks.SOUL_CAMPFIRE)) return "soul_campfire";
|
||||||
|
if (below.is(Blocks.CAMPFIRE)) return "campfire";
|
||||||
|
return "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean interact(ServerPlayer player, BlockPos pos, InteractionHand hand) {
|
||||||
|
var level = player.level();
|
||||||
|
if (AstraCauldron.pots().contains(level, pos)
|
||||||
|
|| player.isSpectator()
|
||||||
|
|| !player.mayInteract(level, pos)) return false;
|
||||||
|
var state = level.getBlockState(pos);
|
||||||
|
var saved = AstraCauldron.liquids().get(level, pos);
|
||||||
|
if (saved != null && !state.is(Blocks.CAULDRON)) return false;
|
||||||
|
String source;
|
||||||
|
int fill;
|
||||||
|
if (saved != null) {
|
||||||
|
source = saved.source();
|
||||||
|
fill = saved.levels();
|
||||||
|
} else {
|
||||||
|
if (state.is(Blocks.CAULDRON)) source = "empty";
|
||||||
|
else if (state.is(Blocks.WATER_CAULDRON)) source = "water";
|
||||||
|
else if (state.is(Blocks.LAVA_CAULDRON)) source = "lava";
|
||||||
|
else if (state.is(Blocks.POWDER_SNOW_CAULDRON)) source = "powder_snow";
|
||||||
|
else return false;
|
||||||
|
fill = source.equals("empty") ? 0 : 3;
|
||||||
|
if (state.hasProperty(LayeredCauldronBlock.LEVEL))
|
||||||
|
fill = state.getValue(LayeredCauldronBlock.LEVEL);
|
||||||
|
}
|
||||||
|
var request =
|
||||||
|
NeoForge.EVENT_BUS.post(
|
||||||
|
new CauldronRecipeEvent(
|
||||||
|
player.getItemInHand(hand), source, fill, heat(level, pos)));
|
||||||
|
ItemStack output = request.output();
|
||||||
|
if (output.isEmpty()) return false;
|
||||||
|
int remaining = fill - request.liquidCost();
|
||||||
|
if (saved != null || request.color() != null) {
|
||||||
|
if (!AstraCauldron.liquids().applyRecipe(level, pos, remaining, request.color()))
|
||||||
|
return true;
|
||||||
|
} else if (request.liquidCost() > 0) {
|
||||||
|
var next =
|
||||||
|
remaining == 0
|
||||||
|
? Blocks.CAULDRON.defaultBlockState()
|
||||||
|
: state.setValue(LayeredCauldronBlock.LEVEL, remaining);
|
||||||
|
if (!level.setBlock(pos, next, 3)) return true;
|
||||||
|
}
|
||||||
|
ItemStack held = player.getItemInHand(hand);
|
||||||
|
held.consume(request.inputCount(), player);
|
||||||
|
if (held.isEmpty()) player.setItemInHand(hand, output);
|
||||||
|
else {
|
||||||
|
player.getInventory().add(output);
|
||||||
|
if (!output.isEmpty()) player.drop(output, false);
|
||||||
|
}
|
||||||
|
level.playSound(
|
||||||
|
null,
|
||||||
|
pos,
|
||||||
|
net.minecraft.sounds.SoundEvents.BUCKET_EMPTY,
|
||||||
|
net.minecraft.sounds.SoundSource.BLOCKS,
|
||||||
|
0.5F,
|
||||||
|
1);
|
||||||
|
player.containerMenu.broadcastChanges();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,6 @@ side="SERVER"
|
|||||||
[[dependencies.astracauldron]]
|
[[dependencies.astracauldron]]
|
||||||
modId="astraplus"
|
modId="astraplus"
|
||||||
type="required"
|
type="required"
|
||||||
versionRange="[0.5.58,0.6)"
|
versionRange="[0.7,0.8)"
|
||||||
ordering="AFTER"
|
ordering="AFTER"
|
||||||
side="SERVER"
|
side="SERVER"
|
||||||
|
|||||||
Reference in New Issue
Block a user