Compare commits

...
Author SHA1 Message Date
Ruling-0 dd4bd60c3e Merge branch 'master' into versioned-transformers 2026-11-21 15:21:32 -06:00
UltraProdigy bdd8977182 ci: run build and test on release branches 2026-11-09 02:38:08 -05:00
Martin Robertz b4c46e95be Merge branch 'master' into versioned-transformers 2026-11-01 12:37:59 +01:00
DarkShadow44 e590bbfb61 Add API to get transformed block (#28) 2026-11-01 12:35:57 +01:00
Ruling-0 e5eefc8f8b Merge remote-tracking branch 'origin/master' into versioned-transformers
# Conflicts:
#	src/main/java/com/gtnewhorizons/postea/mixins/early/MixinAnvilChunkLoader.java
2026-09-30 12:57:54 -05:00
danyadev 82349735e4 better compat with other mixins for AnvilChunkLoader.readChunkFromNBT (#27) 2026-09-27 22:03:47 +03:00
Ruling-0 987ceffb0d Doc cleanup 2026-09-20 15:26:27 -05:00
Ruling-0 b03184a934 Gate custom data calls on a running server instead of the effective side 2026-09-15 08:47:41 -05:00
Ruling-0 49ef265f85 Treat a world without a saved id map as already mapped 2026-09-15 08:37:52 -05:00
Ruling-0 649fa9b5b9 Add custom world data transform API 2026-09-14 23:44:05 -05:00
Ruling-0 2e73e94ed1 Documentation cleanup 2026-08-29 19:23:11 -05:00
Ruling-0 d14955b5ba Update the README for retired-only id capture and the height map rebuild 2026-08-27 22:44:05 -05:00
Ruling-0 1df9b851ee Announce version spans once per world and rebuild the height map after block id changes 2026-08-27 22:44:05 -05:00
Ruling-0 de78b11610 Carry player version stamps across respawns 2026-08-27 22:44:04 -05:00
Ruling-0 dbcfcbff48 Attach absent tile entity and entity lists to the chunk tag 2026-08-27 22:44:03 -05:00
Ruling-0 71d49fc7d9 Record only retired names in the world id table and strip FML's item discriminator 2026-08-27 22:44:02 -05:00
Ruling-0 ef4230fa86 Document versioned transformers and the retired id table 2026-08-27 20:01:46 -05:00
Ruling-0 ccdd37c38f Persist retired block and item ids per world and resolve transformers through them 2026-08-27 20:00:19 -05:00
Ruling-0 4f8e73f915 Run versioned transformers on player data read and write 2026-08-27 19:51:20 -05:00
Ruling-0 2e0b571550 Run versioned transformers at chunk read and stamp chunks on save 2026-08-27 19:49:25 -05:00
Ruling-0 99907e564c Add recursive item stack NBT walker 2026-08-27 19:45:59 -05:00
Ruling-0 490eefc6b7 Add logger, JUnit setup, and the versioned transformer API 2026-08-27 19:45:02 -05:00
Ruling-0 42b5e4d38c Extend block transformer metadata to int (#25) 2026-08-16 12:26:35 -05:00
41 changed files with 1760 additions and 214 deletions

No files matched your search

+2 -2
View File
@@ -3,9 +3,9 @@ name: Build and test
on:
pull_request:
branches: [ master, main ]
branches: [ master, main, release/** ]
push:
branches: [ master, main ]
branches: [ master, main, release/** ]
jobs:
build-and-test:
+93 -4
View File
@@ -1,4 +1,4 @@
# TileEntityReplacementManager API
# Postea
This library provides a suite of tools for transforming any existing tile entities, blocks and items the world at
runtime. Allowing developers to replace, migrate or modify game elements based on specific conditions.
@@ -11,6 +11,9 @@ runtime. Allowing developers to replace, migrate or modify game elements based o
4. **Simple Replacement API**: Efficiently replace or remap large amounts of blocks and items at scale without incurring any noticeable performance impact.
5. **Missing Mapping Replacement API**: A set of API endpoints to register actions to be taken when FML detects a missing mapping for a given ID.
6. **Numeric ID Identification for Removed Content**: A way to identify the ID of any content that has ceased to exist.
7. **Versioned Chunk and Player Transformers**: transform a chunk or a player's data exactly once per version of your content, however many sessions it was saved across.
8. **Retired Id Table**: names of removed content keep resolving in every later session.
9. **Custom World Data Transformers**: versioned transformation of a mod's own world storage, offered by the mod that owns it.
## Examples
@@ -30,9 +33,9 @@ transformed.
> [!TIP]
>
> Tile entity and block transformers are only ran once per chunk until a player's mod list changes. This behaviour is
> disabled if you are in a dev environment; Allowing you to test your transformers simply by leaving and rejoining your
> test world.
> Tile entity, block, and item transformers run once per chunk until the mod list changes (disabled in a dev
> environment). For transformations that must run exactly once per version of your own content, use a versioned
> transformer (§9).
> [!CAUTION]
>
@@ -514,3 +517,89 @@ public abstract class FMLIgnoreMissingMappingExample {
}
}
```
### 9. Versioned Transformers
Postea provides some API endpoints to allow mods to have versioned changes. The mod declares that it
expects some version, and if Postea detects that a chunk or player was saved on a previous version, runs a transformer
to bring them up-to-date. Register an `IVersionedTransformer` through `VersionedReplacementManager.register`.
Some mods keep item stacks stored outside chunks or player data. Postea provides an API, `CustomDataReplacementManager`,
for those mods to allow that data to be transformed by an `IVersionedTransformer`.
> [!IMPORTANT]
>
> Versioned transformers run before every other Postea pass, in registration order, and are never disabled in a dev
> environment. Data saved before a transformer existed reads as `UNSTAMPED`; the transformer decides what that means.
> [!CAUTION]
>
> Chunk transformers may run on a chunk I/O thread, several concurrently for different chunks. They must not touch
> world state beyond the context, and their own state must be safe to read concurrently. As with the other chunk-read
> passes, `ChunkTransformContext.world()` cannot be used for block access.
>
> When a transformer changes a block id, Postea recomputes the chunk's height map and flags it for a relight once
> every transformer has run; nothing is recomputed for metadata-only changes.
>
> An exception thrown by a transformer crashes the game, with the key, both versions, and the chunk or player named in
> the crash report. This is deliberate: a half-transformed chunk stamped at the current version could never be
> recovered.
Code example:
```java
public final class VersionedExample implements IVersionedTransformer {
public static void postLoad() {
VersionedReplacementManager.register(new VersionedExample());
}
@Override
public String key() {
return "examplemod:gemIndex";
}
// The version the running mod writes gems under; bump it whenever the index assignment changes.
@Override
public int currentVersion() {
return 2;
}
@Override
public void transformChunk(ChunkTransformContext ctx) {
// Data saved before this transformer existed carries no stamp.
if (ctx.storedVersion() == ChunkTransformContext.UNSTAMPED || ctx.storedVersion() == 1) {
int gemBlockId = Block.getIdFromBlock(ExampleMod.gemBlock);
ctx.forEachBlock((x, y, z, id, meta) -> {
if (id == gemBlockId) ctx.setBlock(x, y, z, id, meta + 1);
});
ctx.forEachItemStackTag(stack -> {
if (IDExtenderCompat.getItemStackID(stack) == Item.getIdFromItem(ExampleMod.gemItem)) {
stack.setShort("Damage", (short) (stack.getShort("Damage") + 1));
}
});
}
}
@Override
public void transformPlayer(PlayerDataTransformContext ctx) {
if (ctx.storedVersion() == PlayerDataTransformContext.UNSTAMPED || ctx.storedVersion() == 1) {
ctx.forEachItemStackTag(stack -> {
if (IDExtenderCompat.getItemStackID(stack) == Item.getIdFromItem(ExampleMod.gemItem)) {
stack.setShort("Damage", (short) (stack.getShort("Damage") + 1));
}
});
}
}
}
```
### 10. Retired Ids
Whenever a world loads, every block or item name in its saved id map that no longer exists is recorded, with the id it
held, in `<world>/postea/known-ids.json`. This way, retired objects can still be referenced by transformers.
When a name resolves only through retired ids, Postea logs it once per world load:
```
Block ExtraUtilities:cobblestone_compressed is no longer registered; its transformers target retired id(s) [3402]
```
+4
View File
@@ -3,3 +3,7 @@
plugins {
id 'com.gtnewhorizons.gtnhconvention'
}
test {
useJUnitPlatform()
}
+6 -1
View File
@@ -2,7 +2,12 @@
dependencies {
api("com.github.GTNewHorizons:GTNHLib:0.9.39:dev")
compileOnly('com.github.GTNewHorizons:NotEnoughIds:2.1.10:dev')
compileOnly('com.falsepattern:chunkapi-mc1.7.10:0.8.2:dev')
compileOnly('com.falsepattern:endlessids-mc1.7.10:1.7.1:dev')
compileOnly("com.github.GTNewHorizons:NotEnoughItems:2.8.75-GTNH:dev") { transitive = false }
testImplementation(platform('org.junit:junit-bom:5.11.4'))
testImplementation('org.junit.jupiter:junit-jupiter')
testRuntimeOnly('org.junit.platform:junit-platform-launcher')
// fastutil is only on the compile/runtime classpath via the patched Minecraft jar, not the plain test JVM.
testRuntimeOnly('it.unimi.dsi:fastutil:8.5.18')
}
@@ -14,9 +14,13 @@ import net.minecraftforge.oredict.OreDictionary;
import com.gtnewhorizons.postea.api.BlockAccessCompat;
import com.gtnewhorizons.postea.api.BlockReplacementManager;
import com.gtnewhorizons.postea.api.ChunkTransformContext;
import com.gtnewhorizons.postea.api.IDExtenderCompat;
import com.gtnewhorizons.postea.api.IVersionedTransformer;
import com.gtnewhorizons.postea.api.ItemStackReplacementManager;
import com.gtnewhorizons.postea.api.PlayerDataTransformContext;
import com.gtnewhorizons.postea.api.TileEntityReplacementManager;
import com.gtnewhorizons.postea.api.VersionedReplacementManager;
import com.gtnewhorizons.postea.utility.BlockConversionInfo;
import com.gtnewhorizons.postea.utility.BlockInfo;
@@ -32,6 +36,7 @@ abstract class ExampleMigrators {
ComplexBlockTransformer.postLoad();
ComplexItemTransformer.postLoad();
FMLReMappingExample.postLoad();
VersionedExample.postLoad();
}
public static abstract class TEToBlockExample {
@@ -347,4 +352,47 @@ abstract class ExampleMigrators {
BlockReplacementManager.ignoreMissingMapping("IC2:blockCrop");
}
}
public static final class VersionedExample implements IVersionedTransformer {
public static void postLoad() {
VersionedReplacementManager.register(new VersionedExample());
}
@Override
public String key() {
return "examplemod:gemIndex";
}
// The version the running mod writes gems under; bump it whenever the index assignment changes.
@Override
public int currentVersion() {
return 2;
}
@Override
public void transformChunk(ChunkTransformContext ctx) {
// Data saved before this transformer existed carries no stamp.
if (ctx.storedVersion() == ChunkTransformContext.UNSTAMPED || ctx.storedVersion() == 1) {
int gemBlockId = Block.getIdFromBlock(Blocks.wool);
ctx.forEachBlock((x, y, z, id, meta) -> { if (id == gemBlockId) ctx.setBlock(x, y, z, id, meta + 1); });
ctx.forEachItemStackTag(stack -> {
if (IDExtenderCompat.getItemStackID(stack) == Item.getIdFromItem(Items.dye)) {
stack.setShort("Damage", (short) (stack.getShort("Damage") + 1));
}
});
}
}
@Override
public void transformPlayer(PlayerDataTransformContext ctx) {
if (ctx.storedVersion() == PlayerDataTransformContext.UNSTAMPED || ctx.storedVersion() == 1) {
ctx.forEachItemStackTag(stack -> {
if (IDExtenderCompat.getItemStackID(stack) == Item.getIdFromItem(Items.dye)) {
stack.setShort("Damage", (short) (stack.getShort("Damage") + 1));
}
});
}
}
}
}
@@ -1,20 +1,29 @@
package com.gtnewhorizons.postea;
import java.io.File;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.gtnewhorizons.postea.utility.ChunkFixerUtility;
import com.gtnewhorizons.postea.utility.IDRegistry;
import com.gtnewhorizons.postea.utility.MissingMappingHandler;
import com.gtnewhorizons.postea.utility.SimpleTransformationRegistry;
import com.gtnewhorizons.postea.utility.TransformerRegistry;
import com.gtnewhorizons.postea.utility.VersionedTransformerLog;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLMissingMappingsEvent;
import cpw.mods.fml.common.event.FMLModIdMappingEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerAboutToStartEvent;
import cpw.mods.fml.common.event.FMLServerStoppedEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@Mod(
@@ -29,6 +38,8 @@ public class Postea {
public static final String MODID = "postea";
public static final String MODNAME = "Postea";
public static final Logger LOG = LogManager.getLogger(MODNAME);
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
MinecraftForge.EVENT_BUS.register(this);
@@ -44,6 +55,22 @@ public class Postea {
ChunkFixerUtility.onChunkLoaded(event.getChunk());
}
@Mod.EventHandler
public void serverAboutToStart(FMLServerAboutToStartEvent event) {
IDRegistry.beginWorld(
new File(
FMLCommonHandler.instance()
.getSavesDirectory(),
event.getServer()
.getFolderName()));
}
@Mod.EventHandler
public void serverStopped(FMLServerStoppedEvent event) {
IDRegistry.endWorld();
VersionedTransformerLog.clear();
}
@Mod.EventHandler
public void onIdMappingsChanged(FMLModIdMappingEvent event) {
SimpleTransformationRegistry.onIdMappingsChanged();
@@ -0,0 +1,22 @@
package com.gtnewhorizons.postea.api;
/**
* A block referenced by its namespaced id, together with a meta value. Returned by
* {@link BlockReplacementManager#transformBlock(String, int)}.
*/
public final class BlockNameAndMeta {
/**
* The namespaced id of the block.
*/
public final String name;
/**
* The meta value of the block.
*/
public final int metadata;
public BlockNameAndMeta(String name, int metadata) {
this.name = name;
this.metadata = metadata;
}
}
@@ -3,6 +3,7 @@ package com.gtnewhorizons.postea.api;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraftforge.oredict.OreDictionary;
@@ -54,6 +55,32 @@ public abstract class BlockReplacementManager {
// endregion custom transformer registration
// region lookup
/**
* Runs the block transformers registered for the given id on a block that isn't placed in the world, and returns
* what it would be transformed into.<br>
* <br>
* This is meant for mods that store blocks by their namespaced id inside their own NBT (e.g.: blocks that are
* made out of other blocks), which Postea can't reach while converting chunks. Calling this when such a block is
* loaded applies every migration registered to Postea to it.
*
* @apiNote Only call this while a world is loaded, transformers rely on the numeric ids resolved for that world.
* The transformers are given a {@link com.gtnewhorizons.postea.utility.BlockConversionInfo} without a
* world, and with all coordinates set to 0. Tile entity transformers are not run.
*
* @param name The namespaced id of the block.
* @param metadata The meta value of the block.
* @return The namespaced id and meta value of the block to use instead, or null if no transformer applies.
*/
@SuppressWarnings("unused")
public static @Nullable BlockNameAndMeta transformBlock(@Nonnull String name, int metadata) {
if (name == null) throw new NullPointerException("name cannot be null");
return TransformerRegistry.transformBlock(name, metadata);
}
// endregion lookup
// region id resolving
// spotless:off
@@ -0,0 +1,166 @@
package com.gtnewhorizons.postea.api;
import java.util.function.Consumer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import com.gtnewhorizons.postea.compat.Compat;
import com.gtnewhorizons.postea.compat.SubChunkAccess;
import com.gtnewhorizons.postea.utility.NbtItemStacks;
import com.gtnewhorizons.postea.utility.NbtLists;
import com.gtnewhorizons.postea.utility.VersionStamps;
/**
* A chunk as handed to {@link IVersionedTransformer#transformChunk}: its block storage and the raw {@code Level}
* tag as read from disk, before tile entities and entities are parsed. Coordinates are chunk-local
* ({@code 0..15}, {@code y 0..255}); block ids and metadata are the world's numeric values at full EndlessIDs
* width. The world is not loaded yet: block access through {@link #world()} is not possible. When a transformer
* changed a block id, Postea recomputes the height map and flags the chunk for a relight once all transformers ran.
*/
public final class ChunkTransformContext {
public static final int UNSTAMPED = VersionStamps.UNSTAMPED;
private final Chunk chunk;
private final World world;
private final NBTTagCompound levelTag;
private final int storedVersion;
private final int currentVersion;
private final SubChunkAccess[] sections = new SubChunkAccess[16];
private boolean blockIdsChanged;
public ChunkTransformContext(Chunk chunk, World world, NBTTagCompound levelTag, int storedVersion,
int currentVersion) {
this.chunk = chunk;
this.world = world;
this.levelTag = levelTag;
this.storedVersion = storedVersion;
this.currentVersion = currentVersion;
}
public Chunk chunk() {
return chunk;
}
public World world() {
return world;
}
public int chunkX() {
return chunk.xPosition;
}
public int chunkZ() {
return chunk.zPosition;
}
/**
* The chunk's {@code Level} tag. Changes to its {@code TileEntities} and {@code Entities} lists are loaded by
* the game.
*/
public NBTTagCompound levelTag() {
return levelTag;
}
public NBTTagList tileEntityTags() {
return NbtLists.compoundList(levelTag, "TileEntities");
}
public NBTTagList entityTags() {
return NbtLists.compoundList(levelTag, "Entities");
}
/**
* The version this transformer's key was stamped with when the chunk was saved, or {@link #UNSTAMPED}.
*/
public int storedVersion() {
return storedVersion;
}
public int currentVersion() {
return currentVersion;
}
/**
* The block id at a chunk-local position; 0 for a missing section.
*/
public int getBlockId(int x, int y, int z) {
SubChunkAccess access = section(y >> 4, false);
return access == null ? 0 : access.getBlockId(x, y & 15, z);
}
public int getMetadata(int x, int y, int z) {
SubChunkAccess access = section(y >> 4, false);
return access == null ? 0 : access.getMeta(x, y & 15, z);
}
/**
* Sets the block at a chunk-local position, creating the section when a non-air block goes into a missing one.
*/
public void setBlock(int x, int y, int z, int blockId, int metadata) {
SubChunkAccess access = section(y >> 4, blockId != 0);
if (access == null) return;
if (access.getBlockId(x, y & 15, z) != blockId) blockIdsChanged = true;
access.setBlockId(x, y & 15, z, blockId);
access.setMeta(x, y & 15, z, metadata);
}
/**
* Visits every non-air block of every present section.
*/
public void forEachBlock(BlockVisitor visitor) {
ExtendedBlockStorage[] storage = chunk.getBlockStorageArray();
for (int index = 0; index < storage.length; index++) {
if (storage[index] == null) continue;
SubChunkAccess access = section(index, false);
int base = index << 4;
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
int id = access.getBlockId(x, y, z);
if (id != 0) visitor.visit(x, base + y, z, id, access.getMeta(x, y, z));
}
}
}
}
}
/**
* Visits every serialized item stack held by the chunk's tile entities and entities; see
* {@link NbtItemStacks#forEach}.
*/
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(tileEntityTags(), visitor);
NbtItemStacks.forEach(entityTags(), visitor);
}
/**
* Whether a block id (not only metadata) was rewritten.
*/
public boolean blockIdsChanged() {
return blockIdsChanged;
}
private SubChunkAccess section(int index, boolean create) {
if (index < 0 || index >= sections.length) return null;
if (sections[index] == null) {
ExtendedBlockStorage[] storage = chunk.getBlockStorageArray();
if (storage[index] == null) {
if (!create) return null;
storage[index] = new ExtendedBlockStorage(index << 4, !world.provider.hasNoSky);
}
sections[index] = Compat.getSubChunkAccess(storage[index]);
}
return sections[index];
}
@FunctionalInterface
public interface BlockVisitor {
void visit(int x, int y, int z, int blockId, int metadata);
}
}
@@ -0,0 +1,64 @@
package com.gtnewhorizons.postea.api;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ReportedException;
import com.gtnewhorizons.postea.Postea;
import com.gtnewhorizons.postea.utility.ChunkFixerUtility;
import com.gtnewhorizons.postea.utility.IDRegistry;
import com.gtnewhorizons.postea.utility.VersionStamps;
import com.gtnewhorizons.postea.utility.VersionedTransformerLog;
import cpw.mods.fml.common.FMLCommonHandler;
/**
* Manages applying an {@link IVersionedTransformer} to mods' custom storage files.
* <ul>
* <li>Call {@link #transform} once on the root read from disk, before consuming it, and persist that root (stamps
* included) when writing the storage back.</li>
* <li>A save path that rebuilds its NBT from scratch calls {@link #stamp} on the fresh root instead.</li>
* </ul>
*/
public abstract class CustomDataReplacementManager {
/**
* Transforms {@code root} in place through every registered transformer whose stamp differs from its current
* version, then writes the updated stamps onto {@code root}. Does nothing without a running server. Throws
* {@link IllegalStateException} when called before the world's saved id mappings were applied.
*/
public static void transform(String storageId, NBTTagCompound root) {
// Not the effective side: mods save their storage from worker threads, which 1.7.10 reports as client.
if (FMLCommonHandler.instance()
.getMinecraftServerInstance() == null) return;
if (!IDRegistry.isMappingApplied()) {
throw new IllegalStateException(
"Custom data " + storageId
+ " was offered for transformation before the world's id mappings were applied");
}
NBTTagCompound stamps = VersionStamps.read(root);
for (IVersionedTransformer transformer : VersionedReplacementManager.transformers()) {
int current = transformer.currentVersion();
int stored = VersionStamps.stored(stamps, transformer.key());
if (stored == current) continue;
VersionedTransformerLog.announce(transformer, stored, current);
Postea.LOG.debug("{}: custom data {} from version {} to {}", transformer.key(), storageId, stored, current);
try {
transformer.transformCustomData(new CustomDataTransformContext(storageId, root, stored, current));
} catch (Throwable t) {
throw new ReportedException(
ChunkFixerUtility.describe(t, transformer, stored, current, "Custom data", storageId));
}
}
VersionStamps.write(root, stamps, VersionedReplacementManager.transformers());
}
/**
* Stamps a freshly built root about to be written to disk with every registered transformer's current version.
* Does nothing without a running server.
*/
public static void stamp(NBTTagCompound root) {
if (FMLCommonHandler.instance()
.getMinecraftServerInstance() == null) return;
VersionStamps.write(root, VersionStamps.read(root), VersionedReplacementManager.transformers());
}
}
@@ -0,0 +1,59 @@
package com.gtnewhorizons.postea.api;
import java.util.function.Consumer;
import net.minecraft.nbt.NBTTagCompound;
import com.gtnewhorizons.postea.utility.NbtItemStacks;
import com.gtnewhorizons.postea.utility.VersionStamps;
/**
* Context for a mod's custom world storage, used by {@link IVersionedTransformer#transformCustomData}. Stacks here
* may have string {@code id}s instead of numeric ones; {@link #forEachItemStackTag} visits both.
*/
public final class CustomDataTransformContext {
public static final int UNSTAMPED = VersionStamps.UNSTAMPED;
private final String storageId;
private final NBTTagCompound root;
private final int storedVersion;
private final int currentVersion;
public CustomDataTransformContext(String storageId, NBTTagCompound root, int storedVersion, int currentVersion) {
this.storageId = storageId;
this.root = root;
this.storedVersion = storedVersion;
this.currentVersion = currentVersion;
}
/**
* The storage's identity as its owner registered it, e.g. {@code "betterquesting:questDatabase"}.
*/
public String storageId() {
return storageId;
}
public NBTTagCompound root() {
return root;
}
/**
* The version this transformer's key was stamped with when the storage was written, or {@link #UNSTAMPED}.
*/
public int storedVersion() {
return storedVersion;
}
public int currentVersion() {
return currentVersion;
}
/**
* Visits every serialized item stack in the storage, including stacks whose {@code id} is a string name; see
* {@link NbtItemStacks#forEach}.
*/
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(root, visitor, true);
}
}
@@ -0,0 +1,49 @@
package com.gtnewhorizons.postea.api;
/**
* A transformer that brings saved data written under an older version of its owner's content up to the current
* version. Postea stamps every chunk and every player it saves with {@link #currentVersion()} under {@link #key()}
* and, when reading, invokes the transformer only for data whose stamp differs, so each chunk and player is seen
* exactly once per version change no matter how many sessions passed in between. Data saved before the transformer
* existed reads as {@link ChunkTransformContext#UNSTAMPED}; the transformer decides what that means.
* <p>
* Register through {@link VersionedReplacementManager#register(IVersionedTransformer)} during mod loading, postInit
* at the latest. Transformers run in registration order and before every other Postea pass, so a transformer whose
* output depends on another mod's versioned data (for example one that writes that mod's indices) must register
* after that mod; FML's dependency ordering guarantees this when both register in the same lifecycle phase.
* <p>
* Chunk transformers may run on a chunk I/O thread, several concurrently for different chunks. They must not touch
* world state beyond the context and their own state must be safe to read concurrently.
* <p>
* Mods that keep item stacks in their own world storage offer it through {@link CustomDataReplacementManager};
* such storage is stamped the same way and reaches the transformer through {@link #transformCustomData}.
*/
public interface IVersionedTransformer {
/**
* The stamp key, unique across all registered transformers, e.g. {@code "examplemod:idList"}.
*/
String key();
/**
* The version the transformer's output is written under. Sampled at every read and every save.
*/
int currentVersion();
/**
* Brings a chunk stamped at {@link ChunkTransformContext#storedVersion()} to {@link #currentVersion()}.
*/
default void transformChunk(ChunkTransformContext ctx) {}
/**
* Brings a player's saved data stamped at {@link PlayerDataTransformContext#storedVersion()} to
* {@link #currentVersion()}.
*/
default void transformPlayer(PlayerDataTransformContext ctx) {}
/**
* Brings a mod's custom world storage stamped at {@link CustomDataTransformContext#storedVersion()} to
* {@link #currentVersion()}. Stacks in such storage may carry a string {@code id} instead of a numeric one.
*/
default void transformCustomData(CustomDataTransformContext ctx) {}
}
@@ -0,0 +1,55 @@
package com.gtnewhorizons.postea.api;
import java.util.function.Consumer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import com.gtnewhorizons.postea.utility.NbtItemStacks;
import com.gtnewhorizons.postea.utility.VersionStamps;
/**
* A player's saved data as handed to {@link IVersionedTransformer#transformPlayer}: the root tag about to be
* loaded into the player, which holds the inventory, ender chest, {@code ForgeData}, and every extended-properties
* compound. The player object is constructed but not yet loaded from the tag.
*/
public final class PlayerDataTransformContext {
public static final int UNSTAMPED = VersionStamps.UNSTAMPED;
private final EntityPlayerMP player;
private final NBTTagCompound playerTag;
private final int storedVersion;
private final int currentVersion;
public PlayerDataTransformContext(EntityPlayerMP player, NBTTagCompound playerTag, int storedVersion,
int currentVersion) {
this.player = player;
this.playerTag = playerTag;
this.storedVersion = storedVersion;
this.currentVersion = currentVersion;
}
public EntityPlayerMP player() {
return player;
}
public NBTTagCompound playerTag() {
return playerTag;
}
public int storedVersion() {
return storedVersion;
}
public int currentVersion() {
return currentVersion;
}
/**
* Visits every serialized item stack anywhere in the player's data; see {@link NbtItemStacks#forEach}.
*/
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(playerTag, visitor);
}
}
@@ -0,0 +1,36 @@
package com.gtnewhorizons.postea.api;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Registration of {@link IVersionedTransformer}s. See that interface for the execution contract.
*/
public abstract class VersionedReplacementManager {
private static final List<IVersionedTransformer> TRANSFORMERS = new CopyOnWriteArrayList<>();
/**
* Registers a transformer. Throws {@link IllegalArgumentException} when its key is empty or already registered.
*/
public static void register(IVersionedTransformer transformer) {
String key = Objects.requireNonNull(transformer.key(), "key must not be null");
if (key.isEmpty()) throw new IllegalArgumentException("Versioned transformer key must not be empty");
for (IVersionedTransformer existing : TRANSFORMERS) {
if (existing.key()
.equals(key)) {
throw new IllegalArgumentException("A versioned transformer is already registered for " + key);
}
}
TRANSFORMERS.add(transformer);
}
/**
* The registered transformers in registration order.
*/
public static List<IVersionedTransformer> transformers() {
return Collections.unmodifiableList(TRANSFORMERS);
}
}
@@ -14,23 +14,10 @@ import codechicken.nei.api.API;
public class Compat {
private static Boolean chunkapi = null;
private static Boolean endlessids = null;
private static Boolean neid = null;
private static Boolean nei = null;
public static boolean chunkapiPresent() {
if (chunkapi == null) {
boolean present = false;
try {
present = Launch.classLoader.getClassBytes("com.falsepattern.chunk.internal.core.CoreLoadingPlugin")
!= null;
} catch (Throwable ignored) {}
chunkapi = present;
}
return chunkapi;
}
public static boolean endlessidsPresent() {
if (endlessids == null) {
boolean present = false;
@@ -1,26 +0,0 @@
package com.gtnewhorizons.postea.mixins;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.gtnewhorizon.gtnhmixins.ILateMixinLoader;
import com.gtnewhorizon.gtnhmixins.LateMixin;
@LateMixin
public final class PosteaLateLoadingPlugin implements ILateMixinLoader {
@Override
public String getMixinConfig() {
return "mixins.postea.late.json";
}
@Override
public List<String> getMixins(Set<String> loadedMods) {
final List<String> mixins = new ArrayList<>();
if (loadedMods.contains("chunkapi")) {
mixins.add("MixinDataRegistryImpl");
}
return mixins;
}
}
@@ -45,6 +45,8 @@ public final class PosteaLoadingPlugin implements IEarlyMixinLoader, IFMLLoading
final List<String> mixins = new ArrayList<>();
mixins.add("MixinItemStack");
mixins.add("MixinChunk");
mixins.add("MixinEntity");
mixins.add("MixinEntityPlayer");
mixins.add("MixinAnvilChunkLoader");
mixins.add("MixinNBTTagList");
return mixins;
@@ -12,16 +12,18 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import com.gtnewhorizons.postea.utility.ChunkFixerUtility;
import com.llamalad7.mixinextras.sugar.Local;
@Mixin(value = AnvilChunkLoader.class, priority = 1100)
public abstract class MixinAnvilChunkLoader {
// This hook is compatible with Vanilla/NEID/EIDs
@Inject(method = "readChunkFromNBT", at = @At("RETURN"), require = 1)
private void postea$chunkHook(CallbackInfoReturnable<Chunk> cir, @Local Chunk chunk,
@Local(argsOnly = true) World world, @Local(ordinal = 0, argsOnly = true) NBTTagCompound tag) {
ChunkFixerUtility.onChunkRead(chunk, world, tag);
// Forge-added funnel for sync and async loads; runs after relocation fix-ups and after ChunkAPI's own
// readChunkFromNBT replacement, so covers vanilla, NEID, EndlessIDs, and ChunkAPI.
@Inject(method = "checkedReadChunkFromNBT__Async", at = @At("RETURN"), remap = false, require = 1)
private void postea$chunkHook(CallbackInfoReturnable<Object[]> cir) {
Object[] data = cir.getReturnValue();
if (data == null) return;
Chunk chunk = (Chunk) data[0];
ChunkFixerUtility.onChunkRead(chunk, chunk.worldObj, ((NBTTagCompound) data[1]).getCompoundTag("Level"));
}
@Inject(method = "loadChunk", at = @At("RETURN"))
@@ -1,5 +1,6 @@
package com.gtnewhorizons.postea.mixins.early;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Mixin;
@@ -15,6 +16,13 @@ public class MixinChunk implements IChunkMixin {
@Unique
private long postea_GTNH$posteaID;
// The stamps the chunk was read with; null for a chunk generated this session.
@Unique
private NBTTagCompound postea$versionStamps;
@Unique
private boolean postea$versionedDirty;
@Unique
public long Postea$getPosteaCode() {
return postea_GTNH$posteaID;
@@ -24,4 +32,24 @@ public class MixinChunk implements IChunkMixin {
public void Postea$setPosteaCode(long POSTEA_ID) {
this.postea_GTNH$posteaID = POSTEA_ID;
}
@Unique
public NBTTagCompound Postea$getVersionStamps() {
return postea$versionStamps;
}
@Unique
public void Postea$setVersionStamps(NBTTagCompound stamps) {
this.postea$versionStamps = stamps;
}
@Unique
public boolean Postea$isVersionedDirty() {
return postea$versionedDirty;
}
@Unique
public void Postea$setVersionedDirty(boolean dirty) {
this.postea$versionedDirty = dirty;
}
}
@@ -0,0 +1,46 @@
package com.gtnewhorizons.postea.mixins.early;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.gtnewhorizons.postea.mixins.interfaces.IPlayerStampsMixin;
import com.gtnewhorizons.postea.utility.PlayerDataFixerUtility;
@Mixin(Entity.class)
public abstract class MixinEntity implements IPlayerStampsMixin {
// The stamps a server player's data was read with; carried across respawns by MixinEntityPlayer.
@Unique
private NBTTagCompound postea$versionStamps;
@Unique
public NBTTagCompound Postea$getVersionStamps() {
return postea$versionStamps;
}
@Unique
public void Postea$setVersionStamps(NBTTagCompound stamps) {
this.postea$versionStamps = stamps;
}
@Inject(method = "readFromNBT", at = @At("HEAD"), require = 1)
private void postea$transformPlayerData(NBTTagCompound tag, CallbackInfo ci) {
if ((Object) this instanceof EntityPlayerMP player) {
postea$versionStamps = PlayerDataFixerUtility.onPlayerRead(player, tag);
}
}
@Inject(method = "writeToNBT", at = @At("RETURN"), require = 1)
private void postea$stampPlayerData(NBTTagCompound tag, CallbackInfo ci) {
if ((Object) this instanceof EntityPlayerMP) {
PlayerDataFixerUtility.onPlayerWrite(tag, postea$versionStamps);
}
}
}
@@ -0,0 +1,20 @@
package com.gtnewhorizons.postea.mixins.early;
import net.minecraft.entity.player.EntityPlayer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.gtnewhorizons.postea.mixins.interfaces.IPlayerStampsMixin;
@Mixin(EntityPlayer.class)
public abstract class MixinEntityPlayer {
// A respawned player is a fresh entity built from the old one without going through NBT.
@Inject(method = "clonePlayer", at = @At("RETURN"), require = 1)
private void postea$carryVersionStamps(EntityPlayer oldPlayer, boolean respawn, CallbackInfo ci) {
((IPlayerStampsMixin) this).Postea$setVersionStamps(((IPlayerStampsMixin) oldPlayer).Postea$getVersionStamps());
}
}
@@ -1,8 +1,18 @@
package com.gtnewhorizons.postea.mixins.interfaces;
import net.minecraft.nbt.NBTTagCompound;
public interface IChunkMixin {
long Postea$getPosteaCode();
void Postea$setPosteaCode(long posteaID);
NBTTagCompound Postea$getVersionStamps();
void Postea$setVersionStamps(NBTTagCompound stamps);
boolean Postea$isVersionedDirty();
void Postea$setVersionedDirty(boolean dirty);
}
@@ -0,0 +1,10 @@
package com.gtnewhorizons.postea.mixins.interfaces;
import net.minecraft.nbt.NBTTagCompound;
public interface IPlayerStampsMixin {
NBTTagCompound Postea$getVersionStamps();
void Postea$setVersionStamps(NBTTagCompound stamps);
}
@@ -1,24 +0,0 @@
package com.gtnewhorizons.postea.mixins.late;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.falsepattern.chunk.internal.DataRegistryImpl;
import com.gtnewhorizons.postea.utility.ChunkFixerUtility;
@Mixin(value = DataRegistryImpl.class, remap = false)
public abstract class MixinDataRegistryImpl {
@Inject(
method = "readChunkFromNBT(Lnet/minecraft/world/chunk/Chunk;Lnet/minecraft/nbt/NBTTagCompound;)V",
at = @At("RETURN"),
require = 1)
private static void Postea$chunkReadHook(Chunk chunk, NBTTagCompound chunkNBT, CallbackInfo ci) {
ChunkFixerUtility.onChunkRead(chunk, chunk.worldObj, chunkNBT);
}
}
@@ -6,13 +6,19 @@ import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.ReportedException;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import com.gtnewhorizons.postea.api.ChunkTransformContext;
import com.gtnewhorizons.postea.api.IVersionedTransformer;
import com.gtnewhorizons.postea.api.TriFunction;
import com.gtnewhorizons.postea.api.VersionedReplacementManager;
import com.gtnewhorizons.postea.compat.Compat;
import com.gtnewhorizons.postea.compat.SubChunkAccess;
import com.gtnewhorizons.postea.mixins.interfaces.IChunkMixin;
@@ -33,10 +39,8 @@ public class ChunkFixerUtility {
public static void onChunkRead(Chunk chunk, World world, NBTTagCompound tag) {
IChunkMixin chunkMixin = (IChunkMixin) chunk;
chunkMixin.Postea$setPosteaCode(-1);
if (tag.hasKey("POSTEA", 4)) {
chunkMixin.Postea$setPosteaCode(tag.getLong("POSTEA"));
}
runVersionedTransformers(chunk, world, tag);
chunkMixin.Postea$setPosteaCode(tag.hasKey("POSTEA", 4) ? tag.getLong("POSTEA") : -1);
// This checks if the chunk has been run with the current POSTEA_UPDATE_CODE and skips it if so.
if (hasChunkBeenUpdated(chunkMixin.Postea$getPosteaCode())) return;
List<ConversionInfo> conversionInfoList = adjustTileEntities(tag.getTagList("TileEntities", 10), world, chunk);
@@ -62,18 +66,86 @@ public class ChunkFixerUtility {
chunkMixin.Postea$setPosteaCode(ChunkFixerUtility.POSTEA_UPDATE_CODE);
}
private static void runVersionedTransformers(Chunk chunk, World world, NBTTagCompound tag) {
IChunkMixin chunkMixin = (IChunkMixin) chunk;
NBTTagCompound stamps = VersionStamps.read(tag);
chunkMixin.Postea$setVersionStamps(stamps == null ? null : (NBTTagCompound) stamps.copy());
boolean blockIdsChanged = false;
for (IVersionedTransformer transformer : VersionedReplacementManager.transformers()) {
int current = transformer.currentVersion();
int stored = VersionStamps.stored(stamps, transformer.key());
if (stored == current) continue;
ChunkTransformContext ctx = new ChunkTransformContext(chunk, world, tag, stored, current);
VersionedTransformerLog.announce(transformer, stored, current);
try {
transformer.transformChunk(ctx);
} catch (Throwable t) {
throw new ReportedException(
describe(
t,
transformer,
stored,
current,
"Chunk",
chunk.xPosition + "," + chunk.zPosition + " in dimension " + world.provider.dimensionId));
}
chunkMixin.Postea$setVersionedDirty(true);
blockIdsChanged |= ctx.blockIdsChanged();
}
if (!blockIdsChanged) return;
// A section's block count is what decides whether it is saved at all, and writing through SubChunkAccess
// bypasses the bookkeeping ExtendedBlockStorage does in its own setters.
for (ExtendedBlockStorage section : chunk.getBlockStorageArray()) {
if (section != null) section.removeInvalidBlocks();
}
regenerateHeightMap(chunk);
chunk.isLightPopulated = false;
}
// Chunk.generateHeightMap is client-only and generateSkylightMap reaches into the world, so the height map is
// rebuilt here from the chunk's own storage, which is safe on the chunk I/O thread.
private static void regenerateHeightMap(Chunk chunk) {
int top = chunk.getTopFilledSegment() + 16 - 1;
chunk.heightMapMinimum = Integer.MAX_VALUE;
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
chunk.precipitationHeightMap[x + (z << 4)] = -999;
int y = top;
while (y > 0 && chunk.func_150808_b(x, y - 1, z) == 0) {
y--;
}
if (y > 0) {
chunk.heightMap[z << 4 | x] = y;
chunk.heightMapMinimum = Math.min(chunk.heightMapMinimum, y);
}
}
}
}
public static CrashReport describe(Throwable cause, IVersionedTransformer transformer, int stored, int current,
String subjectName, String subject) {
CrashReport report = CrashReport.makeCrashReport(cause, "Running versioned transformer " + transformer.key());
CrashReportCategory category = report.makeCategory("Postea versioned transformer");
category.addCrashSection("Key", transformer.key());
category.addCrashSection("Stored version", stored);
category.addCrashSection("Current version", current);
category.addCrashSection(subjectName, subject);
return report;
}
public static void onChunkLoaded(Chunk chunk) {
if (chunk instanceof IChunkMixin iChunkMixin) {
if (!hasChunkBeenUpdated(iChunkMixin.Postea$getPosteaCode())) {
iChunkMixin.Postea$setPosteaCode(ChunkFixerUtility.POSTEA_UPDATE_CODE);
chunk.setChunkModified();
}
boolean stale = !hasChunkBeenUpdated(iChunkMixin.Postea$getPosteaCode());
if (stale) iChunkMixin.Postea$setPosteaCode(ChunkFixerUtility.POSTEA_UPDATE_CODE);
if (stale || iChunkMixin.Postea$isVersionedDirty()) chunk.setChunkModified();
}
}
public static void onChunkWrite(Chunk chunk, NBTTagCompound tag) {
if (chunk instanceof IChunkMixin iChunkMixin) {
tag.setLong("POSTEA", iChunkMixin.Postea$getPosteaCode());
VersionStamps.write(tag, iChunkMixin.Postea$getVersionStamps(), VersionedReplacementManager.transformers());
iChunkMixin.Postea$setVersionedDirty(false);
}
}
@@ -97,7 +169,7 @@ public class ChunkFixerUtility {
BlockConversionInfo output = getBlockReplacement(
blockId,
(byte) metadata,
metadata,
world,
x + chunkXPos + 1,
y + sectionY,
@@ -1,17 +1,29 @@
package com.gtnewhorizons.postea.utility;
import java.io.File;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;
import com.google.common.collect.LinkedHashMultimap;
import com.gtnewhorizons.postea.Postea;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderState;
import cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry;
import cpw.mods.fml.common.registry.GameData;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
/**
* A simple utility to resolve the IDs of any namepsaced ID that has ever been registered to an active world's id list.
* Resolves a namespaced id to the numeric ids it holds or held in the active world: the live registry id, the id
* the world's own saved map assigns it, and the ids recorded in the world's {@link WorldIdTable} for content that
* has since been removed. A retired id counts only while FML still blocks it and no live content occupies it.
*/
public abstract class IDRegistry {
@@ -24,6 +36,39 @@ public abstract class IDRegistry {
private static final LinkedHashMultimap<String, Consumer<Integer>> BLOCK_ID_RESOLVERS = LinkedHashMultimap.create();
private static final LinkedHashMultimap<String, Consumer<Integer>> ITEM_ID_RESOLVERS = LinkedHashMultimap.create();
private static File tableFile;
private static WorldIdTable table = new WorldIdTable();
private static IntSet blockedIds;
private static volatile boolean mappingApplied;
/**
* Opens the retired id table of the world about to load. Until {@link #endWorld()} the saved id map is captured
* and its missing names merged into it.
*/
public static void beginWorld(File worldDirectory) {
tableFile = new File(new File(worldDirectory, Postea.MODID), WorldIdTable.FILE_NAME);
table = WorldIdTable.load(tableFile);
// A world without a level.dat has no saved id map: the live registries already are its mapping, and
// FML fires no remap event on its first session.
mappingApplied = !new File(worldDirectory, "level.dat").exists();
}
public static void endWorld() {
tableFile = null;
table = new WorldIdTable();
blockedIds = null;
mappingApplied = false;
BLOCK_NAME_TO_ID.clear();
ITEM_NAME_TO_ID.clear();
}
/**
* Whether FML has applied the loading world's saved id map in this session.
*/
public static boolean isMappingApplied() {
return mappingApplied;
}
/**
* Triggers all the callbacks registered by other mods that wish to identify a block that may no longer exist.
* These callbacks effectively remove the need for dummies, and should help improve performance at runtime.
@@ -33,58 +78,140 @@ public abstract class IDRegistry {
// some space memory we can just ignore adding stuff safely.
if (!Loader.instance()
.isInState(LoaderState.SERVER_ABOUT_TO_START)) return;
// we should be fine to execute those in parallel I think?
BLOCK_ID_RESOLVERS.asMap()
.entrySet()
.parallelStream()
.forEach(kv -> {
int id = getItemId(kv.getKey());
for (Consumer<Integer> resolver : kv.getValue()) {
resolver.accept(id);
}
});
ITEM_ID_RESOLVERS.asMap()
.entrySet()
.parallelStream()
.forEach(kv -> {
int id = getItemId(kv.getKey());
for (Consumer<Integer> resolver : kv.getValue()) {
resolver.accept(id);
}
});
}
/**
* Called by {@link com.gtnewhorizons.postea.mixins.preinit.MixinGameData}, this function is used to register all
* the previously registered namespaced to numeric id mappings that have ever been seen into a world.<br>
* <br>
* This function executes before the game starts remapping it's own internal IDs, so we can be sure that any
* existing will remain while the world is loaded.
*/
public static void registerWorldSpecificIDs(Map<String, Integer> map) {
BLOCK_NAME_TO_ID.clear();
ITEM_NAME_TO_ID.clear();
for (Map.Entry<String, Integer> kv : map.entrySet()) {
String name = kv.getKey()
.substring(1);
int id = kv.getValue();
if (kv.getKey()
.charAt(0) == '\u0001') {
BLOCK_NAME_TO_ID.put(name, id);
} else {
ITEM_NAME_TO_ID.put(name, id);
mappingApplied = true;
for (Map.Entry<String, Collection<Consumer<Integer>>> kv : BLOCK_ID_RESOLVERS.asMap()
.entrySet()) {
int id = getBlockId(kv.getKey());
for (Consumer<Integer> resolver : kv.getValue()) {
resolver.accept(id);
}
}
for (Map.Entry<String, Collection<Consumer<Integer>>> kv : ITEM_ID_RESOLVERS.asMap()
.entrySet()) {
int id = getItemId(kv.getKey());
for (Consumer<Integer> resolver : kv.getValue()) {
resolver.accept(id);
}
}
}
/**
* Fetches the block numeric ID associated with the namespaced ID.
*
* @param name the namespaced id of the block.
* @return The ID of the block, or -1 if the namespaced ID has never been registered while the current world was
* loaded.
* Called by {@link com.gtnewhorizons.postea.mixins.preinit.MixinGameData}, this function captures the world's
* saved name-to-id map before FML remaps the live registries onto it, and records the names no registered
* content answers to in the world's retired id table. Ignored outside a server world and off the server thread,
* since the client side of the FML handshake also injects a map.
*/
public static void registerWorldSpecificIDs(Map<String, Integer> map) {
if (tableFile == null || !FMLCommonHandler.instance()
.getEffectiveSide()
.isServer()) return;
BLOCK_NAME_TO_ID.clear();
ITEM_NAME_TO_ID.clear();
blockedIds = null;
Map<String, Integer> missing = new LinkedHashMap<>();
for (Map.Entry<String, Integer> kv : map.entrySet()) {
String name = kv.getKey()
.substring(1);
boolean block = kv.getKey()
.charAt(0) == WorldIdTable.BLOCK_PREFIX;
if (block) {
BLOCK_NAME_TO_ID.put(name, (int) kv.getValue());
} else {
ITEM_NAME_TO_ID.put(name, (int) kv.getValue());
}
FMLControlledNamespacedRegistry<?> registry = block ? GameData.getBlockRegistry()
: GameData.getItemRegistry();
if (registry.getId(name) < 0) missing.put(kv.getKey(), kv.getValue());
}
if (table.merge(missing)) table.save(tableFile);
}
/**
* The block id {@code name} currently holds in this world: the live registry id, or the id it held before its
* content was removed, or -1 when the world never mapped it.
*/
public static int getBlockId(String name) {
int id = liveBlockId(name);
if (id >= 0) return id;
IntList retired = retiredBlockIds(name, id);
return retired.isEmpty() ? -1 : retired.getInt(retired.size() - 1);
}
/**
* The item id {@code name} currently holds in this world: the live registry id, or the id it held before its
* content was removed, or -1 when the world never mapped it.
*/
public static int getItemId(String name) {
int id = liveItemId(name);
if (id >= 0) return id;
IntList retired = retiredItemIds(name, id);
return retired.isEmpty() ? -1 : retired.getInt(retired.size() - 1);
}
/**
* Every block id {@code name} holds or held in this world, live id first. Empty when the world never mapped
* the name.
*/
public static IntList getBlockIds(String name) {
int live = liveBlockId(name);
IntList ids = retiredBlockIds(name, live);
if (live >= 0) {
ids.add(0, live);
} else if (!ids.isEmpty()) {
Postea.LOG.info("Block {} is no longer registered; its transformers target retired id(s) {}", name, ids);
}
return ids;
}
/**
* Every item id {@code name} holds or held in this world, live id first. Empty when the world never mapped
* the name.
*/
public static IntList getItemIds(String name) {
int live = liveItemId(name);
IntList ids = retiredItemIds(name, live);
if (live >= 0) {
ids.add(0, live);
} else if (!ids.isEmpty()) {
Postea.LOG.info("Item {} is no longer registered; its transformers target retired id(s) {}", name, ids);
}
return ids;
}
private static IntList retiredBlockIds(String name, int live) {
IntList ids = new IntArrayList();
for (int id : table.blockIds(name)) {
if (id != live && blockedIds().contains(id)
&& GameData.getBlockRegistry()
.getRaw(id) == null) {
ids.add(id);
}
}
return ids;
}
private static IntList retiredItemIds(String name, int live) {
IntList ids = new IntArrayList();
for (int id : table.itemIds(name)) {
if (id != live && blockedIds().contains(id)
&& GameData.getItemRegistry()
.getRaw(id) == null) {
ids.add(id);
}
}
return ids;
}
private static IntSet blockedIds() {
IntSet ids = blockedIds;
if (ids == null) {
ids = new IntOpenHashSet(GameData.getBlockedIds());
blockedIds = ids;
}
return ids;
}
private static int liveBlockId(String name) {
int id = BLOCK_NAME_TO_ID.getOrDefault(name, -1);
if (id < 0) {
id = GameData.getBlockRegistry()
@@ -94,14 +221,7 @@ public abstract class IDRegistry {
return id;
}
/**
* Fetches the item numeric ID associated with the namespaced ID.
*
* @param name the namespaced id of the block.
* @return The ID of the block, or -1 if the namespaced ID has never been registered while the current world was
* loaded.
*/
public static int getItemId(String name) {
private static int liveItemId(String name) {
int id = ITEM_NAME_TO_ID.getOrDefault(name, -1);
if (id < 0) {
id = GameData.getItemRegistry()
@@ -0,0 +1,55 @@
package com.gtnewhorizons.postea.utility;
import static net.minecraftforge.common.util.Constants.NBT.TAG_ANY_NUMERIC;
import static net.minecraftforge.common.util.Constants.NBT.TAG_COMPOUND;
import static net.minecraftforge.common.util.Constants.NBT.TAG_INT;
import static net.minecraftforge.common.util.Constants.NBT.TAG_SHORT;
import static net.minecraftforge.common.util.Constants.NBT.TAG_STRING;
import java.util.function.Consumer;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
/**
* Visits every serialized item stack in an NBT tree. A compound is a stack when it has a numeric {@code id} or an
* EndlessIDs {@code idExt} together with a {@code Count}; in string-id mode a string {@code id} (a registry name,
* as quest databases store) also qualifies. String-id mode must not be used on chunk or player trees, where tile
* entity compounds carry a string {@code id} of their own. The walk is pre-order and descends into every compound
* and every list of compounds, so stacks nested inside another stack's {@code tag} (backpacks, storage cells) are
* visited too. Lists of lists are not descended. A visitor may change or remove keys of the stack it is given; it
* must not touch other parts of the tree.
*/
public final class NbtItemStacks {
private NbtItemStacks() {}
public static void forEach(NBTBase root, Consumer<NBTTagCompound> visitor) {
forEach(root, visitor, false);
}
public static void forEach(NBTBase root, Consumer<NBTTagCompound> visitor, boolean stringIds) {
if (root instanceof NBTTagCompound compound) {
if (isStack(compound, stringIds)) visitor.accept(compound);
for (Object key : compound.func_150296_c()) {
forEach(compound.getTag((String) key), visitor, stringIds);
}
} else if (root instanceof NBTTagList list && list.func_150303_d() == TAG_COMPOUND) {
for (int i = 0; i < list.tagCount(); i++) {
forEach(list.getCompoundTagAt(i), visitor, stringIds);
}
}
}
public static boolean isStack(NBTTagCompound compound) {
return isStack(compound, false);
}
public static boolean isStack(NBTTagCompound compound, boolean stringIds) {
return compound.hasKey("Count", TAG_ANY_NUMERIC)
&& (compound.hasKey("id", TAG_SHORT) || compound.hasKey("id", TAG_INT)
|| compound.hasKey("idExt", TAG_INT)
|| (stringIds && compound.hasKey("id", TAG_STRING)));
}
}
@@ -0,0 +1,21 @@
package com.gtnewhorizons.postea.utility;
import static net.minecraftforge.common.util.Constants.NBT.TAG_COMPOUND;
import static net.minecraftforge.common.util.Constants.NBT.TAG_LIST;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
public final class NbtLists {
private NbtLists() {}
/**
* The list of compounds stored under {@code key}, attached to {@code parent} first when absent so that tags
* appended to it are part of {@code parent}.
*/
public static NBTTagList compoundList(NBTTagCompound parent, String key) {
if (!parent.hasKey(key, TAG_LIST)) parent.setTag(key, new NBTTagList());
return parent.getTagList(key, TAG_COMPOUND);
}
}
@@ -0,0 +1,49 @@
package com.gtnewhorizons.postea.utility;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ReportedException;
import com.gtnewhorizons.postea.api.IVersionedTransformer;
import com.gtnewhorizons.postea.api.PlayerDataTransformContext;
import com.gtnewhorizons.postea.api.VersionedReplacementManager;
/**
* Runs versioned transformers over a server player's NBT as it is read, and stamps it as it is written. Hooked on
* {@code Entity.readFromNBT}/{@code writeToNBT} so both the {@code playerdata/<uuid>.dat} files and the
* single-player host's copy inside {@code level.dat} are covered.
*/
public final class PlayerDataFixerUtility {
private PlayerDataFixerUtility() {}
/**
* Transforms {@code tag} in place and returns a copy of the stamps it carried (null when unstamped).
*/
public static NBTTagCompound onPlayerRead(EntityPlayerMP player, NBTTagCompound tag) {
NBTTagCompound stamps = VersionStamps.read(tag);
for (IVersionedTransformer transformer : VersionedReplacementManager.transformers()) {
int current = transformer.currentVersion();
int stored = VersionStamps.stored(stamps, transformer.key());
if (stored == current) continue;
VersionedTransformerLog.announce(transformer, stored, current);
try {
transformer.transformPlayer(new PlayerDataTransformContext(player, tag, stored, current));
} catch (Throwable t) {
throw new ReportedException(
ChunkFixerUtility.describe(
t,
transformer,
stored,
current,
"Player",
player.getCommandSenderName() + " (" + player.getUniqueID() + ")"));
}
}
return stamps == null ? null : (NBTTagCompound) stamps.copy();
}
public static void onPlayerWrite(NBTTagCompound tag, NBTTagCompound carried) {
VersionStamps.write(tag, carried, VersionedReplacementManager.transformers());
}
}
@@ -49,13 +49,13 @@ class SimpleTransformationMap<T> {
* The target meta/damage value for the transformation.
* If the value is {@link OreDictionary#WILDCARD_VALUE}, It maintains the old meta/damage value.
*/
public final short targetMeta;
public final int targetMeta;
/**
* The numeric id of the target block, updated during the FMLMappingUpdate event
*/
public int targetRuntimeId;
public Value(T target, short targetMeta) {
public Value(T target, int targetMeta) {
this.target = target;
this.targetMeta = targetMeta;
this.targetRuntimeId = -1;
@@ -73,7 +73,7 @@ class SimpleTransformationMap<T> {
* When querying, the value will be replaced, which will
* be used when ever no other specific meta match is found.
*/
public void put(String originalId, int originalMeta, T target, short targetMeta) {
public void put(String originalId, int originalMeta, T target, int targetMeta) {
if (originalMeta == -1) originalMeta = OreDictionary.WILDCARD_VALUE;
this.registry.computeIfAbsent(originalId, k -> new Int2ObjectOpenHashMap<>())
.put(originalMeta, new Value<>(target, targetMeta));
@@ -100,11 +100,11 @@ public class SimpleTransformationRegistry {
public static void addSimpleTransformer(String originalId, int originalMeta, Block newBlock, int newMeta,
boolean skipStackRemap) {
if (newMeta == -1) newMeta = OreDictionary.WILDCARD_VALUE;
SIMPLE_BLOCK_TRANSFORMATION_MAP.put(originalId, originalMeta, newBlock, (short) newMeta);
SIMPLE_BLOCK_TRANSFORMATION_MAP.put(originalId, originalMeta, newBlock, newMeta);
if (!skipStackRemap) {
Item item = Item.getItemFromBlock(newBlock);
if (item != null) {
SIMPLE_ITEM_TRANSFORMATION_MAP.put(originalId, originalMeta, item, (short) newMeta);
SIMPLE_ITEM_TRANSFORMATION_MAP.put(originalId, originalMeta, item, newMeta);
}
}
}
@@ -166,9 +166,9 @@ public class SimpleTransformationRegistry {
boolean skipBlockRemap) {
if (newMeta == -1) newMeta = OreDictionary.WILDCARD_VALUE;
if (!skipBlockRemap && newItem instanceof ItemBlock ib) {
SIMPLE_BLOCK_TRANSFORMATION_MAP.put(originalId, originalMeta, ib.field_150939_a, (short) newMeta);
SIMPLE_BLOCK_TRANSFORMATION_MAP.put(originalId, originalMeta, ib.field_150939_a, newMeta);
}
SIMPLE_ITEM_TRANSFORMATION_MAP.put(originalId, originalMeta, newItem, (short) newMeta);
SIMPLE_ITEM_TRANSFORMATION_MAP.put(originalId, originalMeta, newItem, newMeta);
}
/**
@@ -191,7 +191,8 @@ public class SimpleTransformationRegistry {
if (mapping == null || mapping.targetRuntimeId <= -1) return false;
IDExtenderCompat.setItemStackID(tag, mapping.targetRuntimeId);
if (mapping.targetMeta != OreDictionary.WILDCARD_VALUE) {
tag.setShort("Damage", mapping.targetMeta);
// Damage is a vanilla short NBT field, unrelated to EndlessIDs block metadata width.
tag.setShort("Damage", (short) mapping.targetMeta);
}
return true;
}
@@ -1,11 +1,13 @@
package com.gtnewhorizons.postea.utility;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
@@ -13,6 +15,8 @@ import net.minecraft.world.chunk.Chunk;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.LinkedListMultimap;
import com.gtnewhorizons.postea.Postea;
import com.gtnewhorizons.postea.api.BlockNameAndMeta;
import com.gtnewhorizons.postea.api.IBlockTransformationHandler;
import com.gtnewhorizons.postea.api.IDExtenderCompat;
import com.gtnewhorizons.postea.api.IItemStackTransformationHandler;
@@ -20,7 +24,9 @@ import com.gtnewhorizons.postea.api.TriFunction;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderState;
import cpw.mods.fml.common.registry.GameData;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntList;
/**
* A registry for all transformer functions
@@ -36,15 +42,17 @@ public class TransformerRegistry {
/**
* Map of itemID -> originalName+transformationHandler.
* Pivoting on the id is faster than pivoting on the strings so this should help with perf a bit.
* Generated during the mapping update event whilst entering/loading a world.
* Generated during the mapping update event whilst entering/loading a world. An id carries several names when
* content that once held it has been removed.
*/
private static final Int2ObjectOpenHashMap<Pair<String, List<IItemStackTransformationHandler>>> RUNTIME_ITEM_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
private static final Int2ObjectOpenHashMap<List<Pair<String, List<IItemStackTransformationHandler>>>> RUNTIME_ITEM_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
/**
* Map of blockIO -> originalName+transformationHandler.
* Map of blockID -> originalName+transformationHandler.
* Pivoting on the id is faster than pivoting on the strings so this should help with perf a bit.
* Generated during the mapping update event whilst entering/loading a world.
* Generated during the mapping update event whilst entering/loading a world. An id carries several names when
* content that once held it has been removed.
*/
private static final Int2ObjectOpenHashMap<Pair<String, List<IBlockTransformationHandler>>> RUNTIME_BLOCK_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
private static final Int2ObjectOpenHashMap<List<Pair<String, List<IBlockTransformationHandler>>>> RUNTIME_BLOCK_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
// region FML Life Cycle handlers
/**
@@ -64,17 +72,27 @@ public class TransformerRegistry {
if (!Loader.instance()
.isInState(LoaderState.SERVER_ABOUT_TO_START)) return;
// create a lookup for source block ids.
for (String key : BLOCK_REPLACEMENT_MAP.keys()) {
int id = IDRegistry.getBlockId(key);
if (id >= 0) {
RUNTIME_BLOCK_REPLACEMENT_MAP.put(id, Pair.of(key, BLOCK_REPLACEMENT_MAP.get(key)));
for (String key : BLOCK_REPLACEMENT_MAP.keySet()) {
IntList ids = IDRegistry.getBlockIds(key);
if (ids.isEmpty()) {
Postea.LOG.debug("Block {} has no id in this world; its transformers stay inactive", key);
continue;
}
for (int id : ids) {
RUNTIME_BLOCK_REPLACEMENT_MAP.computeIfAbsent(id, unused -> new ArrayList<>())
.add(Pair.of(key, BLOCK_REPLACEMENT_MAP.get(key)));
}
}
// create a lookup for source block ids.
for (String key : ITEM_REPLACEMENT_MAP.keys()) {
int id = IDRegistry.getItemId(key);
if (id >= 0) {
RUNTIME_ITEM_REPLACEMENT_MAP.put(id, Pair.of(key, ITEM_REPLACEMENT_MAP.get(key)));
// create a lookup for source item ids.
for (String key : ITEM_REPLACEMENT_MAP.keySet()) {
IntList ids = IDRegistry.getItemIds(key);
if (ids.isEmpty()) {
Postea.LOG.debug("Item {} has no id in this world; its transformers stay inactive", key);
continue;
}
for (int id : ids) {
RUNTIME_ITEM_REPLACEMENT_MAP.computeIfAbsent(id, unused -> new ArrayList<>())
.add(Pair.of(key, ITEM_REPLACEMENT_MAP.get(key)));
}
}
}
@@ -83,12 +101,8 @@ public class TransformerRegistry {
/**
* Registers a block transformation handler function for the given id.
*
* @implNote It doesn't matter if the id doesn't belong to an existing block, a dummy block will be created when
* Postea detects that the id isn't associated to a block during the FMLLoadCompleted event. Dependent
* mods don't need to worry about this as the block name in the BlockConversionInfo is automatically
* updated to the original id when attempting to transform a dummy block. When Postea runs a
* transformation on a dummy block and no handler return true, Postea will automatically convert it to
* air.
* @implNote The id may name content that no longer exists: Postea resolves it through the world's saved id map
* and its retired-id table, so the handler runs on every numeric id the content held in this world.
*
* @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the block.
@@ -101,15 +115,11 @@ public class TransformerRegistry {
/**
* Registers an item transformation handler function for the given id.
*
* @implNote It doesn't matter if the id doesn't belong to an existing item, a dummy item will be created when
* Postea detects that the id isn't associated to an item during the FMLLoadCompleted event. Dependent
* mods don't need to worry about this as transformation handlers are given the original id associated
* with the nbt they are provided when the handler is executed. When Postea runs a transformation on a
* dummy item and no handler returns true, Postea will automatically invalidate the stack by removing
* its id and idExt fields.
* @implNote The id may name content that no longer exists: Postea resolves it through the world's saved id map
* and its retired-id table, so the handler runs on every numeric id the content held in this world.
*
* @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the block.
* @param originalId The namespaced id of the item to transform.
* @param transformer The transformation handler that will execute a transformation on the stack.
*/
public static void addStackTransformer(@Nonnull String originalId,
@Nonnull IItemStackTransformationHandler transformer) {
@@ -117,17 +127,13 @@ public class TransformerRegistry {
}
/**
* Registers an item transformation handler function for the given id.
* Registers a tile entity transformation handler function for the given id.
*
* @implNote It doesn't matter if the id doesn't belong to an existing item, a dummy item will be created when
* Postea detects that the id isn't associated to an item during the FMLLoadCompleted event. Dependent
* mods don't need to worry about this as transformation handlers are given the original id associated
* with the nbt they are provided when the handler is executed. When Postea runs a transformation on a
* dummy item and no handler returns true, Postea will automatically invalidate the stack by removing
* its id and idExt fields.
* @implNote Keyed by the tile entity's saved {@code id}; handlers run in registration order until one returns a
* non-null {@link BlockInfo}.
*
* @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the block.
* @param originalId The saved id of the tile entity to transform.
* @param transformer The transformation handler that will execute a transformation on the tile entity.
*/
public static void addTileEntityTransformer(@Nonnull String originalId,
@Nonnull TriFunction<NBTTagCompound, World, Chunk, BlockInfo> transformer) {
@@ -135,22 +141,40 @@ public class TransformerRegistry {
}
// region transformation handlers
public static @Nullable BlockConversionInfo getBlockReplacement(int blockId, byte metadata, World world, int x,
public static @Nullable BlockConversionInfo getBlockReplacement(int blockId, int metadata, World world, int x,
int y, int z) {
Pair<String, List<IBlockTransformationHandler>> data = RUNTIME_BLOCK_REPLACEMENT_MAP.get(blockId);
if (data == null) return null;
List<Pair<String, List<IBlockTransformationHandler>>> candidates = RUNTIME_BLOCK_REPLACEMENT_MAP.get(blockId);
if (candidates == null) return null;
for (Pair<String, List<IBlockTransformationHandler>> data : candidates) {
BlockConversionInfo info = new BlockConversionInfo(data.getKey(), blockId, metadata, x, y, z, world);
for (IBlockTransformationHandler transformer : data.getValue()) {
if (transformer.apply(info)) return info;
}
}
return null;
}
public static @Nullable BlockNameAndMeta transformBlock(@Nonnull String name, int metadata) {
List<IBlockTransformationHandler> handlers = BLOCK_REPLACEMENT_MAP.get(name);
if (handlers.isEmpty()) return null;
// there is no position nor world, the block isn't placed anywhere
BlockConversionInfo blockConversionInfo = new BlockConversionInfo(
// transparently maps the id to the original id if it's a dummy id
data.getKey(),
blockId,
name,
IDRegistry.getBlockId(name),
metadata,
x,
y,
z,
world);
for (IBlockTransformationHandler transformer : data.getValue()) {
0,
0,
0,
null);
for (IBlockTransformationHandler transformer : handlers) {
if (transformer.apply(blockConversionInfo)) {
return blockConversionInfo;
Block block = GameData.getBlockRegistry()
.getRaw(blockConversionInfo.blockID);
if (block == null) return null;
return new BlockNameAndMeta(
GameData.getBlockRegistry()
.getNameForObject(block),
blockConversionInfo.metadata);
}
}
return null;
@@ -159,17 +183,12 @@ public class TransformerRegistry {
public static void transformItem(NBTTagCompound tag) {
// abort early if tag is bad.
if (tag.hasNoTags() || !tag.hasKey("id")) return;
// get handler
int id = IDExtenderCompat.getItemStackID(tag);
Pair<String, List<IItemStackTransformationHandler>> data = RUNTIME_ITEM_REPLACEMENT_MAP.get(id);
// abort early if handler not found
if (data != null && !data.getValue()
.isEmpty()) {
// apply handlers
List<Pair<String, List<IItemStackTransformationHandler>>> candidates = RUNTIME_ITEM_REPLACEMENT_MAP
.get(IDExtenderCompat.getItemStackID(tag));
if (candidates == null) return;
for (Pair<String, List<IItemStackTransformationHandler>> data : candidates) {
for (IItemStackTransformationHandler transformer : data.getValue()) {
if (transformer.apply(data.getKey(), tag)) {
return;
}
if (transformer.apply(data.getKey(), tag)) return;
}
}
}
@@ -0,0 +1,48 @@
package com.gtnewhorizons.postea.utility;
import static net.minecraftforge.common.util.Constants.NBT.TAG_COMPOUND;
import static net.minecraftforge.common.util.Constants.NBT.TAG_INT;
import net.minecraft.nbt.NBTTagCompound;
import com.gtnewhorizons.postea.api.IVersionedTransformer;
/**
* The {@code POSTEA_VERSIONS} compound Postea keeps on data handled by {@link IVersionedTransformer}s, one
* int per registered transformer key. Keys of transformers that are not registered in the running session are
* carried through unchanged so a mod that is temporarily absent does not lose its stamps.
*/
public final class VersionStamps {
public static final String KEY = "POSTEA_VERSIONS";
public static final int UNSTAMPED = -1;
private VersionStamps() {}
/**
* The stamps stored on {@code container}, or null when it carries none.
*/
public static NBTTagCompound read(NBTTagCompound container) {
return container.hasKey(KEY, TAG_COMPOUND) ? container.getCompoundTag(KEY) : null;
}
/**
* The version stored for {@code key} in {@code stamps} (which may be null), or {@link #UNSTAMPED}.
*/
public static int stored(NBTTagCompound stamps, String key) {
return stamps != null && stamps.hasKey(key, TAG_INT) ? stamps.getInteger(key) : UNSTAMPED;
}
/**
* Writes the stamps onto {@code container}: {@code carried} (the stamps the data was read with, or null) with
* every registered transformer's key set to its current version.
*/
public static void write(NBTTagCompound container, NBTTagCompound carried,
Iterable<IVersionedTransformer> transformers) {
NBTTagCompound stamps = carried == null ? new NBTTagCompound() : (NBTTagCompound) carried.copy();
for (IVersionedTransformer transformer : transformers) {
stamps.setInteger(transformer.key(), transformer.currentVersion());
}
container.setTag(KEY, stamps);
}
}
@@ -0,0 +1,31 @@
package com.gtnewhorizons.postea.utility;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.gtnewhorizons.postea.Postea;
import com.gtnewhorizons.postea.api.IVersionedTransformer;
/**
* Announces each version span a transformer is bringing data across once per world, instead of once per chunk.
*/
public final class VersionedTransformerLog {
private static final Set<String> ANNOUNCED = ConcurrentHashMap.newKeySet();
private VersionedTransformerLog() {}
public static void announce(IVersionedTransformer transformer, int stored, int current) {
if (ANNOUNCED.add(transformer.key() + ' ' + stored + ' ' + current)) {
Postea.LOG.info(
"{} is bringing saved data from version {} to {}",
transformer.key(),
stored == VersionStamps.UNSTAMPED ? "unstamped" : String.valueOf(stored),
current);
}
}
public static void clear() {
ANNOUNCED.clear();
}
}
@@ -0,0 +1,137 @@
package com.gtnewhorizons.postea.utility;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import java.util.TreeMap;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.ints.IntLists;
/**
* Every namespaced block and item name whose content was missing when a world loaded, with every id it held,
* oldest first. FML drops a missing name from {@code level.dat} on the first save after its content disappears;
* this table keeps the name so transformers keyed on it keep resolving in later sessions. Persisted as
* {@code <world>/postea/known-ids.json}, format version 1:
*
* <pre>
* { "version": 1, "blocks": { "mod:block": [300, 301] }, "items": { "mod:item": [4200] } }
* </pre>
*/
public final class WorldIdTable {
static final String FILE_NAME = "known-ids.json";
/** FML prefixes block names with this character in a saved id map; items get U+0002. */
static final char BLOCK_PREFIX = 1;
private static final int FORMAT_VERSION = 1;
private final Map<String, IntList> blocks = new TreeMap<>();
private final Map<String, IntList> items = new TreeMap<>();
/**
* Loads {@code file}; an absent file yields an empty table. Throws {@link IllegalStateException} on a file that
* cannot be read or parsed.
*/
public static WorldIdTable load(File file) {
WorldIdTable table = new WorldIdTable();
if (!file.exists()) return table;
try {
JsonObject root = new JsonParser()
.parse(new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8))
.getAsJsonObject();
if (root.get("version")
.getAsInt() != FORMAT_VERSION) {
throw new IllegalStateException(file + " has an unsupported format version");
}
read(root.getAsJsonObject("blocks"), table.blocks);
read(root.getAsJsonObject("items"), table.items);
} catch (IOException | RuntimeException e) {
throw new IllegalStateException("Cannot read the retired id table " + file, e);
}
return table;
}
private static void read(JsonObject object, Map<String, IntList> into) {
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
IntList ids = new IntArrayList();
for (JsonElement id : entry.getValue()
.getAsJsonArray()) {
ids.add(id.getAsInt());
}
into.put(entry.getKey(), ids);
}
}
/**
* Writes the table through a temporary file so a crash mid-write never truncates it.
*/
public void save(File file) {
JsonObject root = new JsonObject();
root.addProperty("version", FORMAT_VERSION);
root.add("blocks", write(blocks));
root.add("items", write(items));
File temp = new File(file.getPath() + ".tmp");
try {
Files.createDirectories(
file.toPath()
.getParent());
Files.write(
temp.toPath(),
new GsonBuilder().create()
.toJson(root)
.getBytes(StandardCharsets.UTF_8));
Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new IllegalStateException("Cannot write the retired id table " + file, e);
}
}
private static JsonObject write(Map<String, IntList> from) {
JsonObject object = new JsonObject();
for (Map.Entry<String, IntList> entry : from.entrySet()) {
JsonArray ids = new JsonArray();
for (int id : entry.getValue()) {
ids.add(new JsonPrimitive(id));
}
object.add(entry.getKey(), ids);
}
return object;
}
/**
* Records entries of a world's saved name-to-id map, whose names FML prefixes with U+0001 for a block and
* U+0002 for an item. Returns whether any pair was new.
*/
public boolean merge(Map<String, Integer> dataList) {
boolean changed = false;
for (Map.Entry<String, Integer> entry : dataList.entrySet()) {
String prefixed = entry.getKey();
Map<String, IntList> into = prefixed.charAt(0) == BLOCK_PREFIX ? blocks : items;
IntList ids = into.computeIfAbsent(prefixed.substring(1), name -> new IntArrayList());
if (!ids.contains((int) entry.getValue())) {
ids.add((int) entry.getValue());
changed = true;
}
}
return changed;
}
public IntList blockIds(String name) {
return blocks.getOrDefault(name, IntLists.EMPTY_LIST);
}
public IntList itemIds(String name) {
return items.getOrDefault(name, IntLists.EMPTY_LIST);
}
}
@@ -8,6 +8,8 @@
"mixins": [
"MixinAnvilChunkLoader",
"MixinChunk",
"MixinEntity",
"MixinEntityPlayer",
"MixinItemStack",
"MixinNBTTagList"
],
@@ -1,8 +0,0 @@
{
"required": true,
"minVersion": "0.8.5-GTNH",
"package": "com.gtnewhorizons.postea.mixins.late",
"refmap": "mixins.postea.refmap.json",
"target": "@env(DEFAULT)",
"compatibilityLevel": "JAVA_8"
}
@@ -0,0 +1,116 @@
package com.gtnewhorizons.postea.utility;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import org.junit.jupiter.api.Test;
class NbtItemStacksTest {
private static NBTTagCompound stack(int id, int damage) {
NBTTagCompound stack = new NBTTagCompound();
stack.setShort("id", (short) id);
stack.setByte("Count", (byte) 1);
stack.setShort("Damage", (short) damage);
return stack;
}
private static List<NBTTagCompound> visited(NBTTagCompound root) {
List<NBTTagCompound> stacks = new ArrayList<>();
NbtItemStacks.forEach(root, stacks::add);
return stacks;
}
@Test
void visitsStacksInInventoryListsAndStacksNestedInsideAStacksTag() {
NBTTagCompound nested = stack(2, 0);
NBTTagCompound backpack = stack(1, 0);
NBTTagCompound backpackTag = new NBTTagCompound();
NBTTagList contents = new NBTTagList();
contents.appendTag(nested);
backpackTag.setTag("Items", contents);
backpack.setTag("tag", backpackTag);
NBTTagList items = new NBTTagList();
items.appendTag(backpack);
NBTTagCompound tileEntity = new NBTTagCompound();
tileEntity.setString("id", "Chest");
tileEntity.setTag("Items", items);
NBTTagList tileEntities = new NBTTagList();
tileEntities.appendTag(tileEntity);
NBTTagCompound level = new NBTTagCompound();
level.setTag("TileEntities", tileEntities);
assertEquals(Arrays.asList(backpack, nested), visited(level));
}
@Test
void ignoresCompoundsThatAreNotStacks() {
NBTTagCompound enchantment = new NBTTagCompound();
enchantment.setShort("id", (short) 3);
enchantment.setShort("lvl", (short) 1);
NBTTagCompound tileEntity = new NBTTagCompound();
tileEntity.setString("id", "Chest");
tileEntity.setInteger("Count", 1);
NBTTagCompound root = new NBTTagCompound();
root.setTag("ench", enchantment);
root.setTag("te", tileEntity);
assertEquals(Collections.emptyList(), visited(root));
}
@Test
void recognisesExtendedIdStacksWithoutADamageKey() {
NBTTagCompound extended = new NBTTagCompound();
extended.setShort("id", (short) 0);
extended.setInteger("idExt", 40000);
extended.setByte("Count", (byte) 3);
NBTTagCompound root = new NBTTagCompound();
root.setTag("Item", extended);
assertEquals(Collections.singletonList(extended), visited(root));
}
// Pins the split that keeps chunk and player walks safe: a string id with a Count is a stack only in
// string-id mode, which custom data uses and tile entity trees never do.
@Test
void stringIdStacksAreVisitedOnlyInStringIdMode() {
NBTTagCompound quest = new NBTTagCompound();
quest.setString("id", "examplemod:gem");
quest.setInteger("Count", 3);
quest.setShort("Damage", (short) 7);
NBTTagCompound root = new NBTTagCompound();
root.setTag("requiredItems", quest);
List<NBTTagCompound> wide = new ArrayList<>();
NbtItemStacks.forEach(root, wide::add, true);
assertEquals(Collections.emptyList(), visited(root));
assertEquals(Collections.singletonList(quest), wide);
}
@Test
void aVisitorMayInvalidateTheStackItIsGiven() {
NBTTagCompound first = stack(5, 1);
NBTTagCompound second = stack(5, 2);
NBTTagList items = new NBTTagList();
items.appendTag(first);
items.appendTag(second);
NBTTagCompound root = new NBTTagCompound();
root.setTag("Items", items);
List<NBTTagCompound> seen = new ArrayList<>();
NbtItemStacks.forEach(root, tag -> {
seen.add(tag);
tag.removeTag("id");
});
assertEquals(Arrays.asList(first, second), seen);
}
}
@@ -0,0 +1,35 @@
package com.gtnewhorizons.postea.utility;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import org.junit.jupiter.api.Test;
class NbtListsTest {
@Test
void anAbsentListIsCreatedAndAttachedSoAppendedTagsAreKept() {
NBTTagCompound level = new NBTTagCompound();
NbtLists.compoundList(level, "TileEntities")
.appendTag(new NBTTagCompound());
assertEquals(
1,
level.getTagList("TileEntities", 10)
.tagCount());
}
@Test
void anExistingListIsReturnedAsIs() {
NBTTagCompound level = new NBTTagCompound();
NBTTagList existing = new NBTTagList();
existing.appendTag(new NBTTagCompound());
level.setTag("Entities", existing);
assertSame(existing, NbtLists.compoundList(level, "Entities"));
}
}
@@ -0,0 +1,63 @@
package com.gtnewhorizons.postea.utility;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.Collections;
import net.minecraft.nbt.NBTTagCompound;
import org.junit.jupiter.api.Test;
import com.gtnewhorizons.postea.api.IVersionedTransformer;
class VersionStampsTest {
private static IVersionedTransformer transformer(String key, int version) {
return new IVersionedTransformer() {
@Override
public String key() {
return key;
}
@Override
public int currentVersion() {
return version;
}
};
}
@Test
void anUnstampedContainerReadsAsUnstamped() {
NBTTagCompound container = new NBTTagCompound();
assertNull(VersionStamps.read(container));
assertEquals(VersionStamps.UNSTAMPED, VersionStamps.stored(null, "mod:key"));
}
@Test
void writeStampsRegisteredKeysAtTheirCurrentVersionAndCarriesUnknownKeys() {
NBTTagCompound carried = new NBTTagCompound();
carried.setInteger("absentmod:key", 7);
carried.setInteger("mod:key", 2);
NBTTagCompound container = new NBTTagCompound();
VersionStamps.write(container, carried, Collections.singletonList(transformer("mod:key", 3)));
NBTTagCompound stamps = VersionStamps.read(container);
assertEquals(3, VersionStamps.stored(stamps, "mod:key"));
assertEquals(7, VersionStamps.stored(stamps, "absentmod:key"));
assertEquals(2, carried.getInteger("mod:key"));
}
@Test
void writeWithoutCarriedStampsWritesOnlyRegisteredKeys() {
NBTTagCompound container = new NBTTagCompound();
VersionStamps.write(container, null, Collections.singletonList(transformer("mod:key", 1)));
assertEquals(1, VersionStamps.stored(VersionStamps.read(container), "mod:key"));
assertEquals(VersionStamps.UNSTAMPED, VersionStamps.stored(VersionStamps.read(container), "other:key"));
}
}
@@ -0,0 +1,79 @@
package com.gtnewhorizons.postea.utility;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
class WorldIdTableTest {
@TempDir
File dir;
private File file() {
return new File(dir, "known-ids.json");
}
private static IntList ids(int... ids) {
return IntArrayList.wrap(ids);
}
private static Map<String, Integer> savedIds(Object... namesAndIds) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < namesAndIds.length; i += 2) {
map.put((String) namesAndIds[i], (Integer) namesAndIds[i + 1]);
}
return map;
}
@Test
void mergeRecordsEveryIdANameHeldInObservationOrderAndReportsChanges() {
WorldIdTable table = new WorldIdTable();
assertTrue(table.merge(savedIds("\u0001mod:block", 300, "\u0002mod:item", 4200)));
assertFalse(table.merge(savedIds("\u0001mod:block", 300, "\u0002mod:item", 4200)));
assertTrue(table.merge(savedIds("\u0001mod:block", 301)));
assertEquals(ids(300, 301), table.blockIds("mod:block"));
assertEquals(ids(4200), table.itemIds("mod:item"));
assertEquals(ids(), table.blockIds("mod:item"));
}
@Test
void saveAndLoadRoundTrip() {
WorldIdTable table = new WorldIdTable();
table.merge(savedIds("\u0001mod:block", 300, "\u0002mod:item", 4200));
table.merge(savedIds("\u0001mod:block", 301));
table.save(file());
WorldIdTable loaded = WorldIdTable.load(file());
assertEquals(ids(300, 301), loaded.blockIds("mod:block"));
assertEquals(ids(4200), loaded.itemIds("mod:item"));
}
@Test
void anAbsentFileLoadsEmptyAndAMalformedFileFailsLoudly() throws IOException {
assertEquals(
ids(),
WorldIdTable.load(file())
.blockIds("mod:block"));
Files.write(file().toPath(), "{\"version\":1,\"blocks\":5}".getBytes(StandardCharsets.UTF_8));
assertThrows(IllegalStateException.class, () -> WorldIdTable.load(file()));
}
}