diff --git a/docs/xml-machines.md b/docs/xml-machines.md index 9ef25f51..a4a2e292 100644 --- a/docs/xml-machines.md +++ b/docs/xml-machines.md @@ -3,9 +3,8 @@ An installed mod can declare a machine with optional item, energy and fluid storage in `src/main/resources/mmdlib/machine/.xml`. Its ID is `:`. MMDLib registers the block, item, block-entity type, declared recipe type and -serializer, capabilities, screen and JEI catalyst. All instances use the shared -`DefinedMachineBlock` and `DefinedMachineEntity`; no machine-specific Java class -is needed. +serializer, capabilities, screen and JEI catalyst. By default, the XML block creates a +`DefinedMachineEntity`. A mod can supply a subclass for an individual machine. Definitions load at startup on both sides. Changing a machine's storage, screen, appearance or recipe generator configuration requires a restart. Recipe JSON and @@ -19,6 +18,43 @@ configuration or a slot's role/limit is detected even if the screen looks identi XML attribute order, comments, whitespace and local source paths do not affect the CRC. Different definitions are rejected before constructing the client menu. +## Porting an existing block entity + +Keep the machine XML at the existing block and block-entity registry ID when +those IDs match. Let MMDLib own the registrations. In your mod constructor on +both sides, register the entity constructor under the concrete XML machine ID: + +```java +MachineContent.registerEntityFactory(ResourceLocation.parse("example:boiler"), + BoilerEntity::new); +``` + +Extend `DefinedMachineEntity` and forward its five constructor arguments +(`BlockEntityType`, `BlockPos`, `BlockState`, `MachineDefinition`, and the +primary `MachineRecipeType`, which can be null) to `super`. Both placement and +world loading use this constructor. The XML definition still supplies the +machine's storage, processors, capabilities and screen. + +For legacy save keys, override `migrateMachineData`. It receives the persistent +root tag before storage and processors restore their state. For example, a mod +whose old boiler stored FE in a numeric `BoilerFE` field could use: + +```java +@Override +protected CompoundTag migrateMachineData(CompoundTag tag, HolderLookup.Provider registries) { + if (tag.contains("energy") || !tag.contains("BoilerFE", Tag.TAG_ANY_NUMERIC)) + return tag; + var converted = tag.copy(); + converted.putLong("energy", tag.getLong("BoilerFE")); + converted.remove("BoilerFE"); + return converted; +} +``` + +The next save writes the current format. Client update tags bypass migration. +If an old save uses a different block or block-entity registry ID, the mod must +also arrange for that ID to resolve before Minecraft can load the entity. + ## SimpleCrusher The playable example is diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/LegacyMachineEntityTests.java b/src/companionTest/java/zone/moddev/mc/companion/test/LegacyMachineEntityTests.java new file mode 100644 index 00000000..f92f4039 --- /dev/null +++ b/src/companionTest/java/zone/moddev/mc/companion/test/LegacyMachineEntityTests.java @@ -0,0 +1,94 @@ +package zone.moddev.mc.companion.test; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; +import net.minecraft.gametest.framework.GameTest; +import net.minecraft.gametest.framework.GameTestHelper; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; + +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.fml.event.lifecycle.FMLConstructModEvent; +import net.neoforged.neoforge.gametest.GameTestHolder; +import net.neoforged.neoforge.gametest.PrefixGameTestTemplate; + +import zone.moddev.mc.companion.CompanionMod; +import zone.moddev.mc.lib.machine.definition.MachineDefinition; +import zone.moddev.mc.lib.machine.neoforge.DefinedMachineEntity; +import zone.moddev.mc.lib.machine.neoforge.MachineContent; +import zone.moddev.mc.lib.machine.recipe.MachineRecipeType; + +@EventBusSubscriber(modid = CompanionMod.ID, bus = EventBusSubscriber.Bus.MOD) +@GameTestHolder("mmdlib_porting") +@PrefixGameTestTemplate(false) +public final class LegacyMachineEntityTests { + @SubscribeEvent + public static void register(FMLConstructModEvent event) { + MachineContent.registerEntityFactory( + CompanionMod.id("test/upgraded_fluid_still"), LegacyStill::new); + } + + public static final class LegacyStill extends DefinedMachineEntity { + private int migrations; + + public LegacyStill(BlockEntityType type, BlockPos pos, + BlockState state, MachineDefinition definition, + MachineRecipeType recipes) { + super(type, pos, state, definition, recipes); + } + + @Override + protected CompoundTag migrateMachineData(CompoundTag tag, + HolderLookup.Provider registries) { + if (tag.contains("energy") + || !tag.contains("StillFE", Tag.TAG_ANY_NUMERIC)) + return tag; + migrations++; + var converted = tag.copy(); + converted.putLong("energy", tag.getLong("StillFE")); + converted.remove("StillFE"); + return converted; + } + } + + @GameTest(template = "empty") + public static void legacyEnergySurvivesAnXmlMachineRoundTrip( + GameTestHelper h) { + var placed = PortingHooksTests.place(h, "test/upgraded_fluid_still"); + h.assertTrue(placed instanceof LegacyStill, + "Placement uses the registered subclass"); + var registries = h.getLevel().registryAccess(); + var pos = placed.getBlockPos(); + var state = placed.getBlockState(); + var legacy = new CompoundTag(); + legacy.putString("id", "mmdlib_companion:test/upgraded_fluid_still"); + legacy.putInt("StillFE", 625); + var imported = (LegacyStill) BlockEntity.loadStatic(pos, state, legacy, + registries); + h.assertTrue( + imported != null && imported.migrations == 1 + && imported.energy.stored() == 625, + "World load translates the legacy value before XML storage reads it"); + var saved = imported.saveWithFullMetadata(registries); + h.assertTrue( + saved.getLong("energy") == 625 && !saved.contains("StillFE"), + "Saving writes current XML storage"); + var restored = (LegacyStill) BlockEntity.loadStatic(pos, state, saved, + registries); + h.assertTrue( + restored != null && restored.migrations == 0 + && restored.energy.stored() == 625, + "Current saves retain the imported energy without a second migration"); + var update = restored.getUpdateTag(registries); + update.putInt("StillFE", 999); + restored.loadWithComponents(update, registries); + h.assertTrue( + restored.migrations == 0 && restored.energy.stored() == 625, + "Client updates bypass the persistence hook"); + h.succeed(); + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java index 892bbb50..357b8479 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java @@ -2,10 +2,12 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.Tag; @@ -280,6 +282,16 @@ protected void loadMachineData(CompoundTag tag, HolderLookup.Provider registries) { } + /** + * Translates a persistent root tag before shared storage and features load. + * Return the original for current saves or a converted copy for legacy + * saves. Client synchronization bypasses this hook. + */ + protected CompoundTag migrateMachineData(CompoundTag tag, + HolderLookup.Provider registries) { + return tag; + } + /** * Maps old numeric item/tank indices before storage and processor * restoration. Stable IDs bypass it. @@ -353,6 +365,9 @@ protected final void loadAdditional(CompoundTag tag, loadClientData(tag.getCompound(CLIENT_DATA), registries); return; } + tag = Objects.requireNonNull(migrateMachineData(tag, registries), + () -> "migrateMachineData must return a tag for " + + BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(getType())); super.loadAdditional(tag, registries); var inventory = configuredInventory(); if (inventory != null) diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java index d5bcd149..3ed32d06 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java @@ -27,8 +27,11 @@ import zone.moddev.mc.lib.machine.presentation.VisualVariables; import zone.moddev.mc.lib.machine.recipe.MachineRecipeType; -/** Shared runtime assembled from XML. There is no per-machine Java subclass. */ -public final class DefinedMachineEntity extends BaseMachine +/** + * Shared XML runtime. Mods can supply a subclass through + * {@link MachineContent#registerEntityFactory}. + */ +public class DefinedMachineEntity extends BaseMachine implements zone.moddev.mc.lib.machine.feature.ProcessorMachine, zone.moddev.mc.lib.machine.presentation.VisualizerStyle.Provider { public final MachineDefinition definition; diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java index 0b57420e..d557d062 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java @@ -5,12 +5,14 @@ import java.util.Objects; import java.util.TreeMap; +import net.minecraft.core.BlockPos; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluids; import net.neoforged.bus.api.IEventBus; @@ -52,6 +54,43 @@ public final class MachineContent { private static final Map items = new TreeMap<>(); private static final Map> entities = new TreeMap<>(); + private static final Map entityFactories = new TreeMap<>(); + private static boolean entityFactoriesFrozen; + + @FunctionalInterface + public interface EntityFactory { + /** + * Construct the XML entity with the supplied arguments. Recipes may be + * null. + */ + DefinedMachineEntity create(BlockEntityType type, BlockPos pos, + BlockState state, MachineDefinition definition, + @org.jetbrains.annotations.Nullable MachineRecipeType recipes); + } + + /** + * Selects the block entity constructor for a concrete XML machine. Register + * during mod construction, before machine definitions are loaded. + */ + public static synchronized void registerEntityFactory(ResourceLocation id, + EntityFactory factory) { + if (entityFactoriesFrozen) + throw new IllegalStateException( + "XML machine entity factories are frozen: " + id); + if (entityFactories.putIfAbsent(Objects.requireNonNull(id), + Objects.requireNonNull(factory)) != null) + throw new IllegalArgumentException( + "Duplicate XML machine entity factory: " + id); + } + + private static synchronized void freezeEntityFactories() { + for (var id : entityFactories.keySet()) + if (!definitions.containsKey(id)) + throw new IllegalArgumentException( + "No concrete XML machine for entity factory: " + id); + entityFactoriesFrozen = true; + } + private MachineContent() { } @@ -139,6 +178,7 @@ private static void checkEvent(MachineDefinition machine, String attribute, public static void load(List roots) { definitions = MachineDefinitions.load(roots); + freezeEntityFactories(); var declarations = new TreeMap(); for (var machine : definitions.values()) machine.processingTypes().stream() @@ -220,13 +260,24 @@ private static void registries(RegisterEvent event) { }); event.register(Registries.BLOCK_ENTITY_TYPE, helper -> definitions.forEach((id, definition) -> { - var type = BlockEntityType.Builder.of( - (pos, state) -> new DefinedMachineEntity(entities.get(id), - pos, state, definition, - definition.processingType() - .map(recipe -> recipeType(recipe.id())) - .orElse(null)), - blocks.get(id)).build(null); + var factory = entityFactories.getOrDefault(id, + DefinedMachineEntity::new); + var primary = definition.processingType() + .map(recipe -> recipeType(recipe.id())).orElse(null); + var type = BlockEntityType.Builder + .of((pos, state) -> { + var registered = entityType(id); + var entity = factory.create(registered, pos, state, + definition, primary); + if (entity == null || entity.getType() != registered + || !entity.getBlockPos().equals(pos) + || entity.getBlockState() != state + || entity.definition != definition) + throw new IllegalStateException( + "XML machine factory must use the supplied type, position, state and definition: " + + id); + return entity; + }, blocks.get(id)).build(null); helper.register(id, type); entities.put(id, type); }));