Own cauldron gameplay lifecycle and persistence outside AstraPlus
This commit is contained in:
@@ -0,0 +1,254 @@
|
||||
package online.astradev.cauldron.mixing;
|
||||
|
||||
import com.mojang.brigadier.arguments.*;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.util.TriState;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.neoforged.bus.api.EventPriority;
|
||||
import net.neoforged.bus.api.IEventBus;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import com.google.gson.JsonObject;
|
||||
import java.nio.file.Path;
|
||||
import java.io.IOException;
|
||||
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
||||
import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.neoforged.neoforge.event.level.*;
|
||||
import net.neoforged.neoforge.event.level.block.BreakBlockEvent;
|
||||
import net.neoforged.neoforge.event.server.*;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
|
||||
import online.astradev.plus.api.AstraPlusApi;
|
||||
import online.astradev.plus.api.editor.EditorDefinitionProvider;
|
||||
import online.astradev.plus.api.editor.EditorDefinitions;
|
||||
|
||||
import org.slf4j.*;
|
||||
|
||||
public final class MixingCapabilities {
|
||||
static final Logger LOG = LoggerFactory.getLogger("MixingCapabilities");
|
||||
private static MixingPots pots;
|
||||
private static MixingProfile profile;
|
||||
private static MixingConfig initialConfig;
|
||||
private static LiquidMixingPots liquids;
|
||||
private static EditorDefinitionProvider editorDefinition;
|
||||
private static boolean registered;
|
||||
|
||||
private MixingCapabilities() {}
|
||||
|
||||
/** Register immutable command names before Minecraft constructs its dispatcher. */
|
||||
public static void declareCompatibility(JsonObject compatibility) {
|
||||
if (pots != null) throw new IllegalStateException("Mixing capability already started");
|
||||
profile = MixingProfile.parse(compatibility);
|
||||
}
|
||||
|
||||
public static void register(IEventBus bus) {
|
||||
if (registered) return;
|
||||
registered = true;
|
||||
var hooks = new MixingCapabilities();
|
||||
bus.addListener(hooks::tick);
|
||||
bus.addListener(EventPriority.LOWEST, hooks::interact);
|
||||
bus.addListener(EventPriority.LOWEST, hooks::breakBlock);
|
||||
bus.addListener(hooks::explosion);
|
||||
bus.addListener(hooks::piston);
|
||||
bus.addListener(hooks::unload);
|
||||
bus.addListener(hooks::join);
|
||||
bus.addListener(hooks::commands);
|
||||
}
|
||||
|
||||
public static void start(MinecraftServer server, Path file, String id, String name,
|
||||
String defaultsJson, String schemaJson, JsonObject compatibility) throws IOException {
|
||||
close();
|
||||
profile = MixingProfile.parse(compatibility);
|
||||
initialConfig = MixingConfig.parse(defaultsJson, defaultsJson, schemaJson);
|
||||
try {
|
||||
AstraPlusApi.current()
|
||||
.orElseThrow(() -> new IllegalStateException("AstraPlus API unavailable"));
|
||||
pots =
|
||||
new MixingPots(server, file, id, name, defaultsJson, schemaJson);
|
||||
liquids = new LiquidMixingPots(server);
|
||||
editorDefinition = pots.editorDefinition();
|
||||
EditorDefinitions.register(editorDefinition);
|
||||
new MixingCapabilities().registerCommands(server.getCommands().getDispatcher());
|
||||
LOG.info("MixingCapabilities ready: NeoForge 26.2, AstraPlus API");
|
||||
} catch (RuntimeException | IOException e) {
|
||||
close();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public static void close() {
|
||||
if (editorDefinition != null) EditorDefinitions.unregister(editorDefinition);
|
||||
editorDefinition = null;
|
||||
if (pots != null) pots.close();
|
||||
if (liquids != null) liquids.close();
|
||||
pots = null;
|
||||
liquids = null;
|
||||
initialConfig = null;
|
||||
// Keep immutable command names across consecutive server lifecycles. Listeners
|
||||
// are registered once per mod load and remain inert when no runtime is active.
|
||||
}
|
||||
|
||||
private void tick(ServerTickEvent.Post event) {
|
||||
if (pots != null) pots.tick();
|
||||
if (liquids != null) liquids.tick();
|
||||
}
|
||||
|
||||
public static MixingPots pots() {
|
||||
return pots;
|
||||
}
|
||||
|
||||
public static MixingConfig config() {
|
||||
return pots == null ? initialConfig : pots.config();
|
||||
}
|
||||
|
||||
public static boolean active() { return config() != null && profile != null; }
|
||||
public static MixingProfile profile() { return profile; }
|
||||
public static MixingRuntime runtime() { return config().runtime(); }
|
||||
|
||||
public static LiquidMixingPots liquids() {
|
||||
return liquids;
|
||||
}
|
||||
|
||||
public static boolean occupied(Level level, BlockPos 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) {
|
||||
if (pots == null
|
||||
|| event.isCanceled()
|
||||
|| event.getUseBlock() == TriState.FALSE
|
||||
|| event.getUseItem() == TriState.FALSE) return;
|
||||
if (!(event.getEntity() instanceof ServerPlayer player)) return;
|
||||
var pos = event.getPos();
|
||||
var hand = event.getHand();
|
||||
boolean handled = MixingRecipes.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(BreakBlockEvent event) {
|
||||
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) {
|
||||
if (pots != null && event.getLevel() instanceof ServerLevel level)
|
||||
event.getAffectedBlocks().removeIf(pos -> occupied(level, pos));
|
||||
}
|
||||
|
||||
private void piston(PistonEvent.Pre event) {
|
||||
if (pots == null || event.isCanceled() || !(event.getLevel() instanceof ServerLevel level))
|
||||
return;
|
||||
var resolver = event.getStructureHelper();
|
||||
if (resolver == null || !resolver.resolve()) 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) {
|
||||
if (pots != null && event.getLevel() instanceof ServerLevel level)
|
||||
pots.unload(level, event.getChunk().getPos().x(), event.getChunk().getPos().z());
|
||||
}
|
||||
|
||||
private void join(EntityJoinLevelEvent event) {
|
||||
if (!active()) return;
|
||||
if (event.loadedFromDisk() && event.getEntity().entityTags().contains(profile.visualTag()))
|
||||
event.setCanceled(true);
|
||||
else if (event.getEntity() instanceof ItemEntity item)
|
||||
MixingIngredients.normalize(item.getItem());
|
||||
}
|
||||
|
||||
private void commands(RegisterCommandsEvent event) {
|
||||
registerCommands(event.getDispatcher());
|
||||
}
|
||||
|
||||
private void registerCommands(com.mojang.brigadier.CommandDispatcher<CommandSourceStack> dispatcher) {
|
||||
if (profile == null) return;
|
||||
var command = Commands.literal(profile.commands().getFirst()).executes(this::help);
|
||||
command.then(
|
||||
Commands.literal("reload")
|
||||
.requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
||||
.executes(this::reload));
|
||||
var saturation =
|
||||
Commands.argument("saturation", FloatArgumentType.floatArg(0))
|
||||
.executes(this::registerIngredient);
|
||||
var nutrition =
|
||||
Commands.argument("nutrition", IntegerArgumentType.integer(0)).then(saturation);
|
||||
var id = Commands.argument("id", StringArgumentType.word()).then(nutrition);
|
||||
command.then(
|
||||
Commands.literal("register")
|
||||
.requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
||||
.then(id));
|
||||
var root = dispatcher.register(command);
|
||||
for (String alias : profile.commands().subList(1, profile.commands().size()))
|
||||
dispatcher.register(Commands.literal(alias).redirect(root).executes(root.getCommand()));
|
||||
}
|
||||
|
||||
private int help(CommandContext<CommandSourceStack> context) {
|
||||
var message =
|
||||
Component.literal(
|
||||
"Краситель + вода: окрашивание брони. Зелье + пустой котёл: хранение и"
|
||||
+ " стрелы с эффектом. Еда/зелья + полный котёл воды: " + config().ingredientCount + " ингредиента"
|
||||
+ " супа, Shift+ПКМ — варка, миска — порция.");
|
||||
context.getSource().sendSuccess(() -> message, false);
|
||||
return 1;
|
||||
}
|
||||
|
||||
private int reload(CommandContext<CommandSourceStack> context) {
|
||||
try {
|
||||
requirePots().reload();
|
||||
context.getSource()
|
||||
.sendSuccess(
|
||||
() -> Component.literal("MixingCapabilities: настройки применены."), true);
|
||||
return 1;
|
||||
} catch (Exception error) {
|
||||
String message = "Ошибка: " + error.getMessage() + ". Прежние настройки сохранены.";
|
||||
context.getSource().sendFailure(Component.literal(message));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private int registerIngredient(CommandContext<CommandSourceStack> context) {
|
||||
try {
|
||||
String id = StringArgumentType.getString(context, "id");
|
||||
var player = context.getSource().getPlayerOrException();
|
||||
int nutrition = IntegerArgumentType.getInteger(context, "nutrition");
|
||||
float saturation = FloatArgumentType.getFloat(context, "saturation");
|
||||
requirePots().register(id, player, nutrition, saturation);
|
||||
context.getSource()
|
||||
.sendSuccess(() -> Component.literal("Ингредиент зарегистрирован."), true);
|
||||
return 1;
|
||||
} catch (Exception error) {
|
||||
context.getSource()
|
||||
.sendFailure(Component.literal("Ошибка регистрации: " + error.getMessage()));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static MixingPots requirePots() {
|
||||
if (pots == null) throw new IllegalStateException("MixingCapabilities ещё не запущен");
|
||||
return pots;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user