Compare commits

..
Author SHA1 Message Date
Ruling-0 bb88ee7ff7 Stamp transformed data with the current versions before it replaces the original 2026-11-25 14:46:00 -06:00
Ruling-0 477713f002 Correct versioned transformer threading, stack id and height map docs 2026-11-25 14:46:00 -06:00
Ruling-0 e3e0bcd685 Name the subject and versions in versioned transformer crash descriptions 2026-11-25 14:46:00 -06:00
Ruling-0 1f9213041b Keep the singleplayer host's saved player when its read fails 2026-11-25 14:45:59 -06:00
Ruling-0 93c77c7e5f Leave custom data untouched when a versioned transformer fails 2026-11-25 14:45:59 -06:00
Ruling-0 c7f139c53a Drop a parenthetical from the mapping gate doc 2026-11-25 14:45:59 -06:00
Ruling-0 fe28214bb6 Tidy readiness gate and player hook docs 2026-11-25 14:45:59 -06:00
Ruling-0 b0c79d9439 Move the player data hooks from Entity onto EntityPlayerMP 2026-11-25 14:45:59 -06:00
Ruling-0 7af0b24e3e Open the custom data mapping gate once the world's info has loaded 2026-11-25 14:45:59 -06:00
Ruling-0 be56859050 Make IVersionedTransformer.UNSTAMPED the only unstamped constant 2026-11-25 14:45:59 -06:00
Ruling-0 2336426e89 Clarify how CustomDataReplacementManager.stamp treats existing stamps 2026-11-25 14:45:59 -06:00
Ruling-0 3a0e7cd008 Pin one stackTransform call per pass in VersionedStackTransformerTest 2026-11-25 14:45:58 -06:00
Ruling-0 557b486055 Add VersionedStackTransformer base for transformers that rewrite every saved stack 2026-11-25 14:45:58 -06:00
Ruling-0 f1b35bb96f Trim the versioned transformer context API 2026-11-25 14:45:58 -06:00
Ruling-0 67c695f79d Fix stale and missing columns in the versioned transformer height map rebuild 2026-11-25 14:45:58 -06:00
Ruling-0 032ecdcb49 Keep version stamps of absent transformers on rebuilt custom data roots 2026-11-25 14:45:58 -06:00
Ruling-0 05a424db34 Documentation cleanup 2026-11-25 14:45:57 -06:00
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
50 changed files with 2085 additions and 219 deletions

No files matched your search

+2 -2
View File
@@ -3,9 +3,9 @@ name: Build and test
on: on:
pull_request: pull_request:
branches: [ master, main ] branches: [ master, main, release/** ]
push: push:
branches: [ master, main ] branches: [ master, main, release/** ]
jobs: jobs:
build-and-test: 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 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. 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. 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. 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. 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 ## Examples
@@ -30,9 +33,9 @@ transformed.
> [!TIP] > [!TIP]
> >
> Tile entity and block transformers are only ran once per chunk until a player's mod list changes. This behaviour is > Tile entity, block, and item transformers run once per chunk until the mod list changes (disabled in a dev
> disabled if you are in a dev environment; Allowing you to test your transformers simply by leaving and rejoining your > environment). For transformations that must run exactly once per version of your own content, use a versioned
> test world. > transformer (§9).
> [!CAUTION] > [!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 { plugins {
id 'com.gtnewhorizons.gtnhconvention' id 'com.gtnewhorizons.gtnhconvention'
} }
test {
useJUnitPlatform()
}
+6 -1
View File
@@ -2,7 +2,12 @@
dependencies { dependencies {
api("com.github.GTNewHorizons:GTNHLib:0.9.39:dev") api("com.github.GTNewHorizons:GTNHLib:0.9.39:dev")
compileOnly('com.github.GTNewHorizons:NotEnoughIds:2.1.10: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.falsepattern:endlessids-mc1.7.10:1.7.1:dev')
compileOnly("com.github.GTNewHorizons:NotEnoughItems:2.8.75-GTNH:dev") { transitive = false } 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')
} }
@@ -1,5 +1,9 @@
package com.gtnewhorizons.postea; package com.gtnewhorizons.postea;
import static net.minecraftforge.common.util.Constants.NBT.TAG_STRING;
import java.util.function.Consumer;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.material.Material; import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
@@ -14,9 +18,12 @@ import net.minecraftforge.oredict.OreDictionary;
import com.gtnewhorizons.postea.api.BlockAccessCompat; import com.gtnewhorizons.postea.api.BlockAccessCompat;
import com.gtnewhorizons.postea.api.BlockReplacementManager; import com.gtnewhorizons.postea.api.BlockReplacementManager;
import com.gtnewhorizons.postea.api.ChunkTransformContext;
import com.gtnewhorizons.postea.api.IDExtenderCompat; import com.gtnewhorizons.postea.api.IDExtenderCompat;
import com.gtnewhorizons.postea.api.ItemStackReplacementManager; import com.gtnewhorizons.postea.api.ItemStackReplacementManager;
import com.gtnewhorizons.postea.api.TileEntityReplacementManager; import com.gtnewhorizons.postea.api.TileEntityReplacementManager;
import com.gtnewhorizons.postea.api.VersionedReplacementManager;
import com.gtnewhorizons.postea.api.VersionedStackTransformer;
import com.gtnewhorizons.postea.utility.BlockConversionInfo; import com.gtnewhorizons.postea.utility.BlockConversionInfo;
import com.gtnewhorizons.postea.utility.BlockInfo; import com.gtnewhorizons.postea.utility.BlockInfo;
@@ -32,6 +39,7 @@ abstract class ExampleMigrators {
ComplexBlockTransformer.postLoad(); ComplexBlockTransformer.postLoad();
ComplexItemTransformer.postLoad(); ComplexItemTransformer.postLoad();
FMLReMappingExample.postLoad(); FMLReMappingExample.postLoad();
VersionedExample.postLoad();
} }
public static abstract class TEToBlockExample { public static abstract class TEToBlockExample {
@@ -347,4 +355,45 @@ abstract class ExampleMigrators {
BlockReplacementManager.ignoreMissingMapping("IC2:blockCrop"); BlockReplacementManager.ignoreMissingMapping("IC2:blockCrop");
} }
} }
public static final class VersionedExample extends VersionedStackTransformer {
public static void postLoad() {
VersionedReplacementManager.register(new VersionedExample());
}
@Override
public String key() {
return "examplemod:gemIndex";
}
@Override
public int currentVersion() {
return 2;
}
@Override
public void transformChunk(ChunkTransformContext ctx) {
if (shiftsGems(ctx.storedVersion())) {
int gemBlockId = Block.getIdFromBlock(Blocks.wool);
ctx.forEachBlock((x, y, z, id, meta) -> { if (id == gemBlockId) ctx.setBlock(x, y, z, id, meta + 1); });
}
super.transformChunk(ctx);
}
@Override
protected Consumer<NBTTagCompound> stackTransform(int storedVersion) {
if (!shiftsGems(storedVersion)) return null;
int dyeId = Item.getIdFromItem(Items.dye);
return stack -> {
boolean dye = stack.hasKey("id", TAG_STRING) ? "minecraft:dye".equals(stack.getString("id"))
: IDExtenderCompat.getItemStackID(stack) == dyeId;
if (dye) stack.setShort("Damage", (short) (stack.getShort("Damage") + 1));
};
}
private static boolean shiftsGems(int storedVersion) {
return storedVersion == UNSTAMPED || storedVersion == 1;
}
}
} }
@@ -1,20 +1,29 @@
package com.gtnewhorizons.postea; package com.gtnewhorizons.postea;
import java.io.File;
import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkEvent; 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.ChunkFixerUtility;
import com.gtnewhorizons.postea.utility.IDRegistry; import com.gtnewhorizons.postea.utility.IDRegistry;
import com.gtnewhorizons.postea.utility.MissingMappingHandler; import com.gtnewhorizons.postea.utility.MissingMappingHandler;
import com.gtnewhorizons.postea.utility.SimpleTransformationRegistry; import com.gtnewhorizons.postea.utility.SimpleTransformationRegistry;
import com.gtnewhorizons.postea.utility.TransformerRegistry; 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.Mod;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent; import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLMissingMappingsEvent; import cpw.mods.fml.common.event.FMLMissingMappingsEvent;
import cpw.mods.fml.common.event.FMLModIdMappingEvent; import cpw.mods.fml.common.event.FMLModIdMappingEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent; 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; import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@Mod( @Mod(
@@ -29,6 +38,8 @@ public class Postea {
public static final String MODID = "postea"; public static final String MODID = "postea";
public static final String MODNAME = "Postea"; public static final String MODNAME = "Postea";
public static final Logger LOG = LogManager.getLogger(MODNAME);
@Mod.EventHandler @Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) { public void preInit(FMLPreInitializationEvent event) {
MinecraftForge.EVENT_BUS.register(this); MinecraftForge.EVENT_BUS.register(this);
@@ -44,6 +55,22 @@ public class Postea {
ChunkFixerUtility.onChunkLoaded(event.getChunk()); 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 @Mod.EventHandler
public void onIdMappingsChanged(FMLModIdMappingEvent event) { public void onIdMappingsChanged(FMLModIdMappingEvent event) {
SimpleTransformationRegistry.onIdMappingsChanged(); SimpleTransformationRegistry.onIdMappingsChanged();
@@ -0,0 +1,15 @@
package com.gtnewhorizons.postea.api;
/// A block's namespaced id and meta value, as returned by [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 java.util.function.Consumer;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreDictionary;
@@ -54,6 +55,27 @@ public abstract class BlockReplacementManager {
// endregion custom transformer registration // endregion custom transformer registration
// region lookup
/// Runs the block transformers registered for `name` on a block that is not placed in the world, and returns what
/// it would be transformed into.
///
/// For mods that store blocks by namespaced id in their own NBT, which Postea cannot reach while converting
/// chunks. Call only while a world is loaded. Transformers
/// get a [com.gtnewhorizons.postea.utility.BlockConversionInfo] without a world and with all coordinates 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 replacement block, 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 // region id resolving
// spotless:off // spotless:off
@@ -0,0 +1,140 @@
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;
/// A chunk's block storage and raw `Level` tag, as handed to [IVersionedTransformer#transformChunk].
///
/// The tag is as read from disk, before tile entities and entities are parsed. Coordinates are chunk-local (`0..15`,
/// `y 0..255`), and block ids and metadata are the world's numeric values at full EndlessIDs width. The world is not
/// loaded, so block access through [#world()] is not possible. When a transformer changes a block id, Postea
/// recomputes the height map and flags the chunk for a relight after all transformers ran.
public final class ChunkTransformContext {
private final Chunk chunk;
private final World world;
private final NBTTagCompound levelTag;
private final int storedVersion;
private final SubChunkAccess[] sections = new SubChunkAccess[16];
private boolean blockIdsChanged;
public ChunkTransformContext(Chunk chunk, World world, NBTTagCompound levelTag, int storedVersion) {
this.chunk = chunk;
this.world = world;
this.levelTag = levelTag;
this.storedVersion = storedVersion;
}
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 `Level` tag. Changes to its `TileEntities` and `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 stamped under the transformer's key when the chunk was saved, or [IVersionedTransformer#UNSTAMPED].
public int storedVersion() {
return storedVersion;
}
/// The block id at a chunk-local position, or 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
/// [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,76 @@
package com.gtnewhorizons.postea.api;
import net.minecraft.nbt.NBTTagCompound;
import com.gtnewhorizons.postea.utility.IDRegistry;
import com.gtnewhorizons.postea.utility.VersionStamps;
import com.gtnewhorizons.postea.utility.VersionedPass;
import cpw.mods.fml.common.FMLCommonHandler;
/// Applies [IVersionedTransformer]s to a mod's custom storage files.
///
/// Call [#transform] once on the root read from disk, before consuming it, and persist that root, stamps included,
/// when writing the storage back. A save path that rebuilds its NBT from scratch keeps [#savedStamps] from the read and
/// passes them to [#stamp(NBTTagCompound, NBTTagCompound)] on the fresh root. The stamps of transformers missing at
/// save time then survive.
///
/// Custom data belongs to a world, so [#transform] and [#stamp] do nothing unless a server runs in this JVM.
public abstract class CustomDataReplacementManager {
/// Transforms `root` in place through every registered transformer whose stamp differs from its current version,
/// then writes the updated stamps onto `root`.
///
/// A failing transformer throws [net.minecraft.util.ReportedException] and leaves `root` as read, without stamps
/// added. A call before the world's info and saved id map have loaded throws [IllegalStateException].
public static void transform(String storageId, NBTTagCompound root) {
if (!serverRunning()) return;
if (!IDRegistry.isMappingApplied()) {
throw new IllegalStateException(
"Custom data " + storageId
+ " was offered for transformation before the world's info and id mappings loaded");
}
transform(storageId, root, VersionedReplacementManager.transformers());
}
/// [#transform(String, NBTTagCompound)] through `transformers`, without the server and id mapping checks.
static void transform(String storageId, NBTTagCompound root, Iterable<IVersionedTransformer> transformers) {
NBTTagCompound stamps = VersionedPass.runAtomically(
root,
transformers,
"Custom data",
storageId,
(transformer, data, stored) -> transformer
.transformCustomData(new CustomDataTransformContext(storageId, data, stored)));
VersionStamps.write(root, stamps, transformers);
}
/// Same as [#stamp(NBTTagCompound, NBTTagCompound)] with a null `carried`.
public static void stamp(NBTTagCompound root) {
stamp(root, null);
}
/// Stamps `root` with every registered transformer's current version, keeping the stamps in `carried` for
/// transformers not registered now. A non-null `carried` replaces any stamps already on `root`. A null `carried`
/// keeps them.
public static void stamp(NBTTagCompound root, NBTTagCompound carried) {
if (!serverRunning()) return;
stamp(root, carried, VersionedReplacementManager.transformers());
}
static void stamp(NBTTagCompound root, NBTTagCompound carried, Iterable<IVersionedTransformer> transformers) {
VersionStamps.write(root, carried == null ? VersionStamps.read(root) : carried, transformers);
}
/// A copy of the stamps on a root read from disk, or null when it carries none. Call after [#transform].
public static NBTTagCompound savedStamps(NBTTagCompound root) {
NBTTagCompound stamps = VersionStamps.read(root);
return stamps == null ? null : (NBTTagCompound) stamps.copy();
}
private static boolean serverRunning() {
// Not getEffectiveSide(): mods save from worker threads, which 1.7.10 reports as client.
return FMLCommonHandler.instance()
.getMinecraftServerInstance() != null;
}
}
@@ -0,0 +1,25 @@
package com.gtnewhorizons.postea.api;
import java.util.function.Consumer;
import net.minecraft.nbt.NBTTagCompound;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.postea.utility.NbtItemStacks;
/// A mod's custom world storage, as handed to [IVersionedTransformer#transformCustomData]. Stacks here may have
/// string `id`s instead of numeric ones, and [#forEachItemStackTag] visits both.
///
/// @param storageId the id the owning mod passed to [CustomDataReplacementManager#transform], e.g.
/// `"betterquesting:questDatabase"`
/// @param storedVersion the version stamped under the transformer's key when the storage was written, or
/// [IVersionedTransformer#UNSTAMPED]
@Desugar
public record CustomDataTransformContext(String storageId, NBTTagCompound root, int storedVersion) {
/// Visits every serialized item stack in the storage, including stacks whose `id` is a string name. See
/// [NbtItemStacks#forEach].
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(root, visitor, true);
}
}
@@ -0,0 +1,41 @@
package com.gtnewhorizons.postea.api;
/// Upgrades saved chunks, players and custom world storage written under another version of a mod's content.
///
/// Postea stamps everything it saves with [#currentVersion()] under [#key()]. On read, the transformer runs for every
/// stored stamp that differs from [#currentVersion()], older or newer. The transformer decides what a newer version
/// means and throws if it cannot handle it. Data saved before the transformer existed reads as [#UNSTAMPED].
///
/// Register with [VersionedReplacementManager#register(IVersionedTransformer)] by postInit. Transformers run in
/// registration order, before every other Postea pass. One whose output depends on another mod's versioned data
/// must register after that mod.
///
/// Transformers may run off the server thread, several at once for different data: chunks on chunk I/O threads, players
/// on the network thread handling their login, and custom data on whichever thread the owning mod reads it. A
/// transformer must touch no world state beyond the context, and its own state must be safe to read concurrently. Each
/// call has the context's data to itself, and runs after the world's saved id map has been applied.
///
/// Custom world storage offered through [CustomDataReplacementManager] is stamped the same way and reaches
/// [#transformCustomData].
public interface IVersionedTransformer {
int UNSTAMPED = -1;
/// The stamp key, unique across all registered transformers, e.g. `"examplemod:idList"`. Must return the same
/// value for the transformer's lifetime.
String key();
/// The version the transformer's output is written under. Read on every load and save, and may differ between
/// reads.
int currentVersion();
/// Brings a chunk stamped at [ChunkTransformContext#storedVersion()] to [#currentVersion()].
default void transformChunk(ChunkTransformContext ctx) {}
/// Brings a player's saved data stamped at [PlayerDataTransformContext#storedVersion()] to [#currentVersion()].
default void transformPlayer(PlayerDataTransformContext ctx) {}
/// Brings custom world storage stamped at [CustomDataTransformContext#storedVersion()] to [#currentVersion()].
/// Stacks in such storage may carry a string `id` instead of a numeric one.
default void transformCustomData(CustomDataTransformContext ctx) {}
}
@@ -0,0 +1,22 @@
package com.gtnewhorizons.postea.api;
import java.util.function.Consumer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.postea.utility.NbtItemStacks;
/// A player's saved data, as handed to [IVersionedTransformer#transformPlayer].
///
/// The root tag holds the inventory, ender chest, `ForgeData` and every extended-properties compound. The player
/// object is constructed but not yet loaded from the tag.
@Desugar
public record PlayerDataTransformContext(EntityPlayerMP player, NBTTagCompound playerTag, int storedVersion) {
/// Visits every serialized item stack anywhere in the player's data. See [NbtItemStacks#forEach].
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(playerTag, visitor);
}
}
@@ -0,0 +1,30 @@
package com.gtnewhorizons.postea.api;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
/// Registry of [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 [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, as an unmodifiable view.
public static List<IVersionedTransformer> transformers() {
return Collections.unmodifiableList(TRANSFORMERS);
}
}
@@ -0,0 +1,35 @@
package com.gtnewhorizons.postea.api;
import java.util.function.Consumer;
import net.minecraft.nbt.NBTTagCompound;
/// A versioned transformer that rewrites every saved item stack, in chunks, player data and custom world storage alike.
/// A subclass that also rewrites blocks overrides [#transformChunk] and calls `super`.
///
/// Each pass calls [#stackTransform] once, before visiting any stack.
public abstract class VersionedStackTransformer implements IVersionedTransformer {
/// The rewrite applied to each stack tag in data stamped at `storedVersion`, or null when that data needs none. In
/// custom world storage the rewrite also receives stacks whose `id` is a string name. A rewrite that matches only
/// numeric ids leaves those stacks unchanged.
protected abstract Consumer<NBTTagCompound> stackTransform(int storedVersion);
@Override
public void transformChunk(ChunkTransformContext ctx) {
Consumer<NBTTagCompound> transform = stackTransform(ctx.storedVersion());
if (transform != null) ctx.forEachItemStackTag(transform);
}
@Override
public void transformPlayer(PlayerDataTransformContext ctx) {
Consumer<NBTTagCompound> transform = stackTransform(ctx.storedVersion());
if (transform != null) ctx.forEachItemStackTag(transform);
}
@Override
public void transformCustomData(CustomDataTransformContext ctx) {
Consumer<NBTTagCompound> transform = stackTransform(ctx.storedVersion());
if (transform != null) ctx.forEachItemStackTag(transform);
}
}
@@ -14,23 +14,10 @@ import codechicken.nei.api.API;
public class Compat { public class Compat {
private static Boolean chunkapi = null;
private static Boolean endlessids = null; private static Boolean endlessids = null;
private static Boolean neid = null; private static Boolean neid = null;
private static Boolean nei = 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() { public static boolean endlessidsPresent() {
if (endlessids == null) { if (endlessids == null) {
boolean present = false; 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;
}
}
@@ -7,6 +7,7 @@ import java.util.Set;
import com.gtnewhorizon.gtnhmixins.IEarlyMixinLoader; import com.gtnewhorizon.gtnhmixins.IEarlyMixinLoader;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
@IFMLLoadingPlugin.MCVersion("1.7.10") @IFMLLoadingPlugin.MCVersion("1.7.10")
@@ -45,8 +46,13 @@ public final class PosteaLoadingPlugin implements IEarlyMixinLoader, IFMLLoading
final List<String> mixins = new ArrayList<>(); final List<String> mixins = new ArrayList<>();
mixins.add("MixinItemStack"); mixins.add("MixinItemStack");
mixins.add("MixinChunk"); mixins.add("MixinChunk");
mixins.add("MixinEntityPlayer");
mixins.add("MixinEntityPlayerMP");
mixins.add("MixinAnvilChunkLoader"); mixins.add("MixinAnvilChunkLoader");
mixins.add("MixinNBTTagList"); mixins.add("MixinNBTTagList");
mixins.add("MixinSaveHandler");
if (FMLLaunchHandler.side()
.isClient()) mixins.add("MixinIntegratedPlayerList");
return mixins; return mixins;
} }
} }
@@ -12,16 +12,17 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import com.gtnewhorizons.postea.utility.ChunkFixerUtility; import com.gtnewhorizons.postea.utility.ChunkFixerUtility;
import com.llamalad7.mixinextras.sugar.Local;
@Mixin(value = AnvilChunkLoader.class, priority = 1100) @Mixin(value = AnvilChunkLoader.class, priority = 1100)
public abstract class MixinAnvilChunkLoader { public abstract class MixinAnvilChunkLoader {
// This hook is compatible with Vanilla/NEID/EIDs /// Hooks the funnel shared by sync and async loads, which runs after ChunkAPI's `readChunkFromNBT` replacement.
@Inject(method = "readChunkFromNBT", at = @At("RETURN"), require = 1) @Inject(method = "checkedReadChunkFromNBT__Async", at = @At("RETURN"), remap = false, require = 1)
private void postea$chunkHook(CallbackInfoReturnable<Chunk> cir, @Local Chunk chunk, private void postea$chunkHook(CallbackInfoReturnable<Object[]> cir) {
@Local(argsOnly = true) World world, @Local(ordinal = 0, argsOnly = true) NBTTagCompound tag) { Object[] data = cir.getReturnValue();
ChunkFixerUtility.onChunkRead(chunk, world, tag); 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")) @Inject(method = "loadChunk", at = @At("RETURN"))
@@ -1,5 +1,6 @@
package com.gtnewhorizons.postea.mixins.early; package com.gtnewhorizons.postea.mixins.early;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
@@ -15,6 +16,13 @@ public class MixinChunk implements IChunkMixin {
@Unique @Unique
private long postea_GTNH$posteaID; private long postea_GTNH$posteaID;
/// The stamps the chunk was read with, or null for a chunk generated this session.
@Unique
private NBTTagCompound postea$versionStamps;
@Unique
private boolean postea$versionedDirty;
@Unique @Unique
public long Postea$getPosteaCode() { public long Postea$getPosteaCode() {
return postea_GTNH$posteaID; return postea_GTNH$posteaID;
@@ -24,4 +32,24 @@ public class MixinChunk implements IChunkMixin {
public void Postea$setPosteaCode(long POSTEA_ID) { public void Postea$setPosteaCode(long POSTEA_ID) {
this.postea_GTNH$posteaID = 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,22 @@
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;
/// Carries a player's version stamps to the entity `clonePlayer` builds on respawn, which is not read from NBT.
@Mixin(EntityPlayer.class)
public abstract class MixinEntityPlayer {
@Inject(method = "clonePlayer", at = @At("RETURN"), require = 1)
private void postea$carryVersionStamps(EntityPlayer oldPlayer, boolean respawn, CallbackInfo ci) {
if ((Object) this instanceof IPlayerStampsMixin player && oldPlayer instanceof IPlayerStampsMixin old) {
player.Postea$setVersionStamps(old.Postea$getVersionStamps());
}
}
}
@@ -0,0 +1,71 @@
package com.gtnewhorizons.postea.mixins.early;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Intrinsic;
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;
import com.mojang.authlib.GameProfile;
/// Transforms a server player's saved data on read and stamps it on write.
///
/// The hooks override `Entity.readFromNBT` and `writeToNBT` so the transform also reaches `ForgeData` and the extended
/// properties, which Forge reads before `readEntityFromNBT`. The class extends [EntityPlayer] so the overrides
/// reobfuscate to `Entity`'s srg names.
@Mixin(EntityPlayerMP.class)
public abstract class MixinEntityPlayerMP extends EntityPlayer implements IPlayerStampsMixin {
/// The stamps the player's data was read with. [MixinEntityPlayer] carries them across respawns.
@Unique
private NBTTagCompound postea$versionStamps;
private MixinEntityPlayerMP(World world, GameProfile profile) {
super(world, profile);
}
@Unique
public NBTTagCompound Postea$getVersionStamps() {
return postea$versionStamps;
}
@Unique
public void Postea$setVersionStamps(NBTTagCompound stamps) {
this.postea$versionStamps = stamps;
}
@Intrinsic
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
}
@Intrinsic
@Override
public void writeToNBT(NBTTagCompound tag) {
super.writeToNBT(tag);
}
@Dynamic("Merged into EntityPlayerMP by readFromNBT above")
@SuppressWarnings("target")
@Inject(method = "readFromNBT(Lnet/minecraft/nbt/NBTTagCompound;)V", at = @At("HEAD"), require = 1)
private void postea$transformPlayerData(NBTTagCompound tag, CallbackInfo ci) {
postea$versionStamps = PlayerDataFixerUtility.onPlayerRead((EntityPlayerMP) (Object) this, tag);
}
@Dynamic("Merged into EntityPlayerMP by writeToNBT above")
@SuppressWarnings("target")
@Inject(method = "writeToNBT(Lnet/minecraft/nbt/NBTTagCompound;)V", at = @At("RETURN"), require = 1)
private void postea$stampPlayerData(NBTTagCompound tag, CallbackInfo ci) {
PlayerDataFixerUtility.onPlayerWrite(tag, postea$versionStamps);
}
}
@@ -0,0 +1,46 @@
package com.gtnewhorizons.postea.mixins.early;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.integrated.IntegratedPlayerList;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
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 org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
/// Keeps the singleplayer host's saved player in `level.dat` when the host's login fails before the player is read.
///
/// A host whose read fails is logged out with a player that was never loaded. `IntegratedPlayerList` records host data
/// before the `playerNetServerHandler` check in `ServerConfigurationManager.writePlayerData`, and `level.dat` is saved
/// without a player while no host data exists.
@Mixin(IntegratedPlayerList.class)
public abstract class MixinIntegratedPlayerList {
/// Skips a player that never finished logging in, as the superclass does.
@Inject(
method = "writePlayerData(Lnet/minecraft/entity/player/EntityPlayerMP;)V",
at = @At("HEAD"),
cancellable = true,
require = 1)
private void postea$skipUnloadedPlayer(EntityPlayerMP player, CallbackInfo ci) {
if (player.playerNetServerHandler == null) ci.cancel();
}
/// Returns the player read from `level.dat` while no host data has been written.
@Inject(
method = "getHostPlayerData()Lnet/minecraft/nbt/NBTTagCompound;",
at = @At("RETURN"),
cancellable = true,
require = 1)
private void postea$keepReadHostPlayer(CallbackInfoReturnable<NBTTagCompound> cir) {
if (cir.getReturnValue() != null) return;
WorldServer overworld = DimensionManager.getWorld(0);
if (overworld != null) cir.setReturnValue(
overworld.getWorldInfo()
.getPlayerNBTTagCompound());
}
}
@@ -0,0 +1,26 @@
package com.gtnewhorizons.postea.mixins.early;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
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.CallbackInfoReturnable;
import com.gtnewhorizons.postea.utility.IDRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
/// Opens [IDRegistry]'s mapping gate when `loadWorldInfo` returns on the server thread, after FML has applied any saved
/// id map.
@Mixin(SaveHandler.class)
public abstract class MixinSaveHandler {
@Inject(method = "loadWorldInfo", at = @At("RETURN"), require = 1)
private void postea$markWorldInfoLoaded(CallbackInfoReturnable<WorldInfo> cir) {
if (FMLCommonHandler.instance()
.getEffectiveSide()
.isServer()) IDRegistry.onWorldInfoLoaded();
}
}
@@ -1,8 +1,18 @@
package com.gtnewhorizons.postea.mixins.interfaces; package com.gtnewhorizons.postea.mixins.interfaces;
import net.minecraft.nbt.NBTTagCompound;
public interface IChunkMixin { public interface IChunkMixin {
long Postea$getPosteaCode(); long Postea$getPosteaCode();
void Postea$setPosteaCode(long posteaID); 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);
}
}
@@ -12,7 +12,10 @@ import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage; 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.TriFunction;
import com.gtnewhorizons.postea.api.VersionedReplacementManager;
import com.gtnewhorizons.postea.compat.Compat; import com.gtnewhorizons.postea.compat.Compat;
import com.gtnewhorizons.postea.compat.SubChunkAccess; import com.gtnewhorizons.postea.compat.SubChunkAccess;
import com.gtnewhorizons.postea.mixins.interfaces.IChunkMixin; import com.gtnewhorizons.postea.mixins.interfaces.IChunkMixin;
@@ -33,10 +36,8 @@ public class ChunkFixerUtility {
public static void onChunkRead(Chunk chunk, World world, NBTTagCompound tag) { public static void onChunkRead(Chunk chunk, World world, NBTTagCompound tag) {
IChunkMixin chunkMixin = (IChunkMixin) chunk; IChunkMixin chunkMixin = (IChunkMixin) chunk;
chunkMixin.Postea$setPosteaCode(-1); runVersionedTransformers(chunk, world, tag);
if (tag.hasKey("POSTEA", 4)) { chunkMixin.Postea$setPosteaCode(tag.hasKey("POSTEA", 4) ? tag.getLong("POSTEA") : -1);
chunkMixin.Postea$setPosteaCode(tag.getLong("POSTEA"));
}
// This checks if the chunk has been run with the current POSTEA_UPDATE_CODE and skips it if so. // 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; if (hasChunkBeenUpdated(chunkMixin.Postea$getPosteaCode())) return;
List<ConversionInfo> conversionInfoList = adjustTileEntities(tag.getTagList("TileEntities", 10), world, chunk); List<ConversionInfo> conversionInfoList = adjustTileEntities(tag.getTagList("TileEntities", 10), world, chunk);
@@ -62,18 +63,54 @@ public class ChunkFixerUtility {
chunkMixin.Postea$setPosteaCode(ChunkFixerUtility.POSTEA_UPDATE_CODE); 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);
VersionedTransformerLog.announce(transformer, stored, current);
try {
transformer.transformChunk(ctx);
} catch (Throwable t) {
throw VersionedPass.failure(
t,
transformer,
stored,
current,
"Chunk",
chunk.xPosition + "," + chunk.zPosition + " in dimension " + world.provider.dimensionId);
}
chunkMixin.Postea$setVersionedDirty(true);
blockIdsChanged |= ctx.blockIdsChanged();
}
if (!blockIdsChanged) return;
// SubChunkAccess writes bypass the block counts that ExtendedBlockStorage's setters maintain and that decide
// whether a section is saved.
for (ExtendedBlockStorage section : chunk.getBlockStorageArray()) {
if (section != null) section.removeInvalidBlocks();
}
HeightMaps.regenerate(chunk);
chunk.isLightPopulated = false;
}
public static void onChunkLoaded(Chunk chunk) { public static void onChunkLoaded(Chunk chunk) {
if (chunk instanceof IChunkMixin iChunkMixin) { if (chunk instanceof IChunkMixin iChunkMixin) {
if (!hasChunkBeenUpdated(iChunkMixin.Postea$getPosteaCode())) { boolean stale = !hasChunkBeenUpdated(iChunkMixin.Postea$getPosteaCode());
iChunkMixin.Postea$setPosteaCode(ChunkFixerUtility.POSTEA_UPDATE_CODE); if (stale) iChunkMixin.Postea$setPosteaCode(ChunkFixerUtility.POSTEA_UPDATE_CODE);
chunk.setChunkModified(); if (stale || iChunkMixin.Postea$isVersionedDirty()) chunk.setChunkModified();
}
} }
} }
public static void onChunkWrite(Chunk chunk, NBTTagCompound tag) { public static void onChunkWrite(Chunk chunk, NBTTagCompound tag) {
if (chunk instanceof IChunkMixin iChunkMixin) { if (chunk instanceof IChunkMixin iChunkMixin) {
tag.setLong("POSTEA", iChunkMixin.Postea$getPosteaCode()); tag.setLong("POSTEA", iChunkMixin.Postea$getPosteaCode());
VersionStamps.write(tag, iChunkMixin.Postea$getVersionStamps(), VersionedReplacementManager.transformers());
iChunkMixin.Postea$setVersionedDirty(false);
} }
} }
@@ -0,0 +1,29 @@
package com.gtnewhorizons.postea.utility;
import net.minecraft.world.chunk.Chunk;
/// Rebuilds a chunk's height map from the chunk's own storage. `Chunk.generateHeightMap` is client-only and
/// `generateSkylightMap` reaches into the world.
///
/// Block opacity comes from the position-aware `Block.getLightOpacity`, so a block that overrides it can read the world
/// from the chunk I/O thread.
final class HeightMaps {
private HeightMaps() {}
static void regenerate(Chunk chunk) {
int top = chunk.getTopFilledSegment() + 16;
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--;
}
chunk.heightMap[z << 4 | x] = y;
chunk.heightMapMinimum = Math.min(chunk.heightMapMinimum, y);
}
}
}
}
@@ -1,18 +1,29 @@
package com.gtnewhorizons.postea.utility; package com.gtnewhorizons.postea.utility;
import java.io.File;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.function.Consumer; import java.util.function.Consumer;
import com.google.common.collect.LinkedHashMultimap; 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.Loader;
import cpw.mods.fml.common.LoaderState; import cpw.mods.fml.common.LoaderState;
import cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry;
import cpw.mods.fml.common.registry.GameData; 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; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
/** /// Resolves a namespaced id to the numeric ids it holds in the active world, or held before its content was removed.
* A simple utility to resolve the IDs of any namepsaced ID that has ever been registered to an active world's id list. ///
*/ /// Ids come from the live registry, the world's saved id map and the world's [WorldIdTable]. A retired id counts
/// only while FML still blocks it and no live content occupies it.
public abstract class IDRegistry { public abstract class IDRegistry {
// Part of a bi-map for lookups between block namespaced ids and numeric ids // Part of a bi-map for lookups between block namespaced ids and numeric ids
@@ -24,6 +35,39 @@ public abstract class IDRegistry {
private static final LinkedHashMultimap<String, Consumer<Integer>> BLOCK_ID_RESOLVERS = LinkedHashMultimap.create(); 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 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;
/// Loads the retired id table of the world about to load. [#registerWorldSpecificIDs] records into it until
/// [#endWorld()]. Resets [#isMappingApplied] to false.
public static void beginWorld(File worldDirectory) {
tableFile = new File(new File(worldDirectory, Postea.MODID), WorldIdTable.FILE_NAME);
table = WorldIdTable.load(tableFile);
mappingApplied = false;
}
public static void endWorld() {
tableFile = null;
table = new WorldIdTable();
blockedIds = null;
mappingApplied = false;
BLOCK_NAME_TO_ID.clear();
ITEM_NAME_TO_ID.clear();
}
/// Whether the loading world's id mappings are in place. [#onWorldInfoLoaded] sets it once the world's info and any
/// saved id map have loaded on the server thread. [#onMappingUpdated] sets it when FML's remap event fires.
public static boolean isMappingApplied() {
return mappingApplied;
}
/// Marks the loading world's info as loaded. Ignored outside a world begun by [#beginWorld].
public static void onWorldInfoLoaded() {
if (tableFile != null) mappingApplied = true;
}
/** /**
* Triggers all the callbacks registered by other mods that wish to identify a block that may no longer exist. * 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. * These callbacks effectively remove the need for dummies, and should help improve performance at runtime.
@@ -33,58 +77,127 @@ public abstract class IDRegistry {
// some space memory we can just ignore adding stuff safely. // some space memory we can just ignore adding stuff safely.
if (!Loader.instance() if (!Loader.instance()
.isInState(LoaderState.SERVER_ABOUT_TO_START)) return; .isInState(LoaderState.SERVER_ABOUT_TO_START)) return;
// we should be fine to execute those in parallel I think? mappingApplied = true;
BLOCK_ID_RESOLVERS.asMap() for (Map.Entry<String, Collection<Consumer<Integer>>> kv : BLOCK_ID_RESOLVERS.asMap()
.entrySet() .entrySet()) {
.parallelStream() int id = getBlockId(kv.getKey());
.forEach(kv -> { 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()); int id = getItemId(kv.getKey());
for (Consumer<Integer> resolver : kv.getValue()) { for (Consumer<Integer> resolver : kv.getValue()) {
resolver.accept(id); 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);
} }
});
} }
/** /// Captures the world's saved name-to-id map before FML remaps the live registries onto it, and records the names
* Called by {@link com.gtnewhorizons.postea.mixins.preinit.MixinGameData}, this function is used to register all /// no registered content answers to in the world's retired id table. Ignored outside a server world and off the
* the previously registered namespaced to numeric id mappings that have ever been seen into a world.<br> /// server thread.
* <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) { public static void registerWorldSpecificIDs(Map<String, Integer> map) {
if (tableFile == null || !FMLCommonHandler.instance()
.getEffectiveSide()
.isServer()) return;
BLOCK_NAME_TO_ID.clear(); BLOCK_NAME_TO_ID.clear();
ITEM_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()) { for (Map.Entry<String, Integer> kv : map.entrySet()) {
String name = kv.getKey() String name = kv.getKey()
.substring(1); .substring(1);
int id = kv.getValue(); boolean block = kv.getKey()
if (kv.getKey() .charAt(0) == WorldIdTable.BLOCK_PREFIX;
.charAt(0) == '\u0001') { if (block) {
BLOCK_NAME_TO_ID.put(name, id); BLOCK_NAME_TO_ID.put(name, (int) kv.getValue());
} else { } else {
ITEM_NAME_TO_ID.put(name, id); 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 `name` holds in this world: the live registry id, else the id it held before its content was
* Fetches the block numeric ID associated with the namespaced ID. /// removed, or -1 if the world never mapped it.
*
* @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 getBlockId(String name) { 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 `name` holds in this world: the live registry id, else the id it held before its content was
/// removed, or -1 if 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 `name` holds or held in this world, live id first. Empty if 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 `name` holds or held in this world, live id first. Empty if 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); int id = BLOCK_NAME_TO_ID.getOrDefault(name, -1);
if (id < 0) { if (id < 0) {
id = GameData.getBlockRegistry() id = GameData.getBlockRegistry()
@@ -94,14 +207,7 @@ public abstract class IDRegistry {
return id; return id;
} }
/** private static int liveItemId(String name) {
* 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) {
int id = ITEM_NAME_TO_ID.getOrDefault(name, -1); int id = ITEM_NAME_TO_ID.getOrDefault(name, -1);
if (id < 0) { if (id < 0) {
id = GameData.getItemRegistry() 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 `Count` and a numeric `id` or an EndlessIDs `idExt`. In string-id mode, a
/// string `id` such as a registry name also qualifies. String-id mode must not be used on chunk or player trees,
/// where tile entity compounds carry a string `id` of their own.
///
/// The walk is pre-order and descends into every compound and every list of compounds, including a stack's own
/// `tag`. Lists of lists are not descended. A visitor may change or remove keys of the stack it is given, and 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,19 @@
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 `key`. Adds an empty list to `parent` unless a list is already stored under
/// `key`, so appending to the result changes `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,31 @@
package com.gtnewhorizons.postea.utility;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
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.
///
/// Runs on every server player NBT read and write, which covers `playerdata` and the host player in `level.dat`.
public final class PlayerDataFixerUtility {
private PlayerDataFixerUtility() {}
/// Transforms `tag` in place and returns a copy of the stamps it carried, or null if unstamped. A failing
/// transformer throws and leaves `tag` as read.
public static NBTTagCompound onPlayerRead(EntityPlayerMP player, NBTTagCompound tag) {
return VersionedPass.runAtomically(
tag,
VersionedReplacementManager.transformers(),
"Player",
player.getCommandSenderName() + " (" + player.getUniqueID() + ")",
(transformer, data, stored) -> transformer
.transformPlayer(new PlayerDataTransformContext(player, data, stored)));
}
public static void onPlayerWrite(NBTTagCompound tag, NBTTagCompound carried) {
VersionStamps.write(tag, carried, VersionedReplacementManager.transformers());
}
}
@@ -1,11 +1,13 @@
package com.gtnewhorizons.postea.utility; package com.gtnewhorizons.postea.utility;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
@@ -13,6 +15,8 @@ import net.minecraft.world.chunk.Chunk;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.LinkedListMultimap; 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.IBlockTransformationHandler;
import com.gtnewhorizons.postea.api.IDExtenderCompat; import com.gtnewhorizons.postea.api.IDExtenderCompat;
import com.gtnewhorizons.postea.api.IItemStackTransformationHandler; 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.Loader;
import cpw.mods.fml.common.LoaderState; 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.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntList;
/** /**
* A registry for all transformer functions * A registry for all transformer functions
@@ -33,18 +39,12 @@ public class TransformerRegistry {
.create(); .create();
private static final LinkedListMultimap<String, TriFunction<NBTTagCompound, World, Chunk, BlockInfo>> TILE_ENTITY_REPLACEMENT_MAP = LinkedListMultimap private static final LinkedListMultimap<String, TriFunction<NBTTagCompound, World, Chunk, BlockInfo>> TILE_ENTITY_REPLACEMENT_MAP = LinkedListMultimap
.create(); .create();
/** /// Maps an item id to the names that hold it and their handlers. Generated during the mapping update event when a
* Map of itemID -> originalName+transformationHandler. /// world loads. An id carries several names when content that once held it was removed.
* Pivoting on the id is faster than pivoting on the strings so this should help with perf a bit. private static final Int2ObjectOpenHashMap<List<Pair<String, List<IItemStackTransformationHandler>>>> RUNTIME_ITEM_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
* Generated during the mapping update event whilst entering/loading a world. /// Maps a block id to the names that hold it and their handlers. Generated during the mapping update event when a
*/ /// world loads. An id carries several names when content that once held it was removed.
private static final Int2ObjectOpenHashMap<Pair<String, List<IItemStackTransformationHandler>>> RUNTIME_ITEM_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>(); private static final Int2ObjectOpenHashMap<List<Pair<String, List<IBlockTransformationHandler>>>> RUNTIME_BLOCK_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
/**
* Map of blockIO -> 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.
*/
private static final Int2ObjectOpenHashMap<Pair<String, List<IBlockTransformationHandler>>> RUNTIME_BLOCK_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
// region FML Life Cycle handlers // region FML Life Cycle handlers
/** /**
@@ -64,71 +64,60 @@ public class TransformerRegistry {
if (!Loader.instance() if (!Loader.instance()
.isInState(LoaderState.SERVER_ABOUT_TO_START)) return; .isInState(LoaderState.SERVER_ABOUT_TO_START)) return;
// create a lookup for source block ids. // create a lookup for source block ids.
for (String key : BLOCK_REPLACEMENT_MAP.keys()) { for (String key : BLOCK_REPLACEMENT_MAP.keySet()) {
int id = IDRegistry.getBlockId(key); IntList ids = IDRegistry.getBlockIds(key);
if (id >= 0) { if (ids.isEmpty()) {
RUNTIME_BLOCK_REPLACEMENT_MAP.put(id, Pair.of(key, BLOCK_REPLACEMENT_MAP.get(key))); 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.keySet()) {
for (String key : ITEM_REPLACEMENT_MAP.keys()) { IntList ids = IDRegistry.getItemIds(key);
int id = IDRegistry.getItemId(key); if (ids.isEmpty()) {
if (id >= 0) { Postea.LOG.debug("Item {} has no id in this world; its transformers stay inactive", key);
RUNTIME_ITEM_REPLACEMENT_MAP.put(id, Pair.of(key, ITEM_REPLACEMENT_MAP.get(key))); continue;
}
for (int id : ids) {
RUNTIME_ITEM_REPLACEMENT_MAP.computeIfAbsent(id, unused -> new ArrayList<>())
.add(Pair.of(key, ITEM_REPLACEMENT_MAP.get(key)));
} }
} }
} }
// endregion FML Life Cycle handlers // endregion FML Life Cycle handlers
/** /// Registers a block transformation handler for the given namespaced id.
* Registers a block transformation handler function for the given id. ///
* /// The id may name content that no longer exists. The handler runs on every numeric id the content held in this
* @implNote It doesn't matter if the id doesn't belong to an existing block, a dummy block will be created when /// world, as resolved through the world's saved id map and retired id table.
* 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 /// @param originalId the namespaced id of the block to transform
* updated to the original id when attempting to transform a dummy block. When Postea runs a /// @param transformer the handler that transforms the block
* transformation on a dummy block and no handler return true, Postea will automatically convert it to
* air.
*
* @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the block.
*/
public static void addBlockTransformer(@Nonnull String originalId, public static void addBlockTransformer(@Nonnull String originalId,
@Nonnull IBlockTransformationHandler transformer) { @Nonnull IBlockTransformationHandler transformer) {
BLOCK_REPLACEMENT_MAP.put(originalId, transformer); BLOCK_REPLACEMENT_MAP.put(originalId, transformer);
} }
/** /// Registers an item transformation handler for the given namespaced id.
* Registers an item transformation handler function for the given id. ///
* /// The id may name content that no longer exists. The handler runs on every numeric id the content held in this
* @implNote It doesn't matter if the id doesn't belong to an existing item, a dummy item will be created when /// world, as resolved through the world's saved id map and retired id table.
* 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 /// @param originalId the namespaced id of the item to transform
* with the nbt they are provided when the handler is executed. When Postea runs a transformation on a /// @param transformer the handler that transforms the stack
* dummy item and no handler returns true, Postea will automatically invalidate the stack by removing
* its id and idExt fields.
*
* @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the block.
*/
public static void addStackTransformer(@Nonnull String originalId, public static void addStackTransformer(@Nonnull String originalId,
@Nonnull IItemStackTransformationHandler transformer) { @Nonnull IItemStackTransformationHandler transformer) {
ITEM_REPLACEMENT_MAP.put(originalId, transformer); ITEM_REPLACEMENT_MAP.put(originalId, transformer);
} }
/** /// Registers a tile entity transformation handler for the given saved tile entity id. Handlers run in
* Registers an item transformation handler function for the given id. /// registration order until one returns a non-null [BlockInfo].
* ///
* @implNote It doesn't matter if the id doesn't belong to an existing item, a dummy item will be created when /// @param originalId the saved id of the tile entity to transform
* Postea detects that the id isn't associated to an item during the FMLLoadCompleted event. Dependent /// @param transformer the handler that transforms the tile entity
* 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.
*
* @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the block.
*/
public static void addTileEntityTransformer(@Nonnull String originalId, public static void addTileEntityTransformer(@Nonnull String originalId,
@Nonnull TriFunction<NBTTagCompound, World, Chunk, BlockInfo> transformer) { @Nonnull TriFunction<NBTTagCompound, World, Chunk, BlockInfo> transformer) {
TILE_ENTITY_REPLACEMENT_MAP.put(originalId, transformer); TILE_ENTITY_REPLACEMENT_MAP.put(originalId, transformer);
@@ -137,20 +126,37 @@ public class TransformerRegistry {
// region transformation handlers // region transformation handlers
public static @Nullable BlockConversionInfo getBlockReplacement(int blockId, int metadata, World world, int x, public static @Nullable BlockConversionInfo getBlockReplacement(int blockId, int metadata, World world, int x,
int y, int z) { int y, int z) {
Pair<String, List<IBlockTransformationHandler>> data = RUNTIME_BLOCK_REPLACEMENT_MAP.get(blockId); List<Pair<String, List<IBlockTransformationHandler>>> candidates = RUNTIME_BLOCK_REPLACEMENT_MAP.get(blockId);
if (data == null) return null; if (candidates == null) return null;
BlockConversionInfo blockConversionInfo = new BlockConversionInfo( for (Pair<String, List<IBlockTransformationHandler>> data : candidates) {
// transparently maps the id to the original id if it's a dummy id BlockConversionInfo info = new BlockConversionInfo(data.getKey(), blockId, metadata, x, y, z, world);
data.getKey(),
blockId,
metadata,
x,
y,
z,
world);
for (IBlockTransformationHandler transformer : data.getValue()) { 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;
BlockConversionInfo blockConversionInfo = new BlockConversionInfo(
name,
IDRegistry.getBlockId(name),
metadata,
0,
0,
0,
null);
for (IBlockTransformationHandler transformer : handlers) {
if (transformer.apply(blockConversionInfo)) { 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; return null;
@@ -159,17 +165,12 @@ public class TransformerRegistry {
public static void transformItem(NBTTagCompound tag) { public static void transformItem(NBTTagCompound tag) {
// abort early if tag is bad. // abort early if tag is bad.
if (tag.hasNoTags() || !tag.hasKey("id")) return; if (tag.hasNoTags() || !tag.hasKey("id")) return;
// get handler List<Pair<String, List<IItemStackTransformationHandler>>> candidates = RUNTIME_ITEM_REPLACEMENT_MAP
int id = IDExtenderCompat.getItemStackID(tag); .get(IDExtenderCompat.getItemStackID(tag));
Pair<String, List<IItemStackTransformationHandler>> data = RUNTIME_ITEM_REPLACEMENT_MAP.get(id); if (candidates == null) return;
// abort early if handler not found for (Pair<String, List<IItemStackTransformationHandler>> data : candidates) {
if (data != null && !data.getValue()
.isEmpty()) {
// apply handlers
for (IItemStackTransformationHandler transformer : data.getValue()) { for (IItemStackTransformationHandler transformer : data.getValue()) {
if (transformer.apply(data.getKey(), tag)) { if (transformer.apply(data.getKey(), tag)) return;
return;
}
} }
} }
} }
@@ -0,0 +1,40 @@
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 `POSTEA_VERSIONS` compound Postea keeps on data handled by [IVersionedTransformer]s, with one int per
/// transformer key.
///
/// Keys of transformers not registered in the running session are carried through unchanged.
public final class VersionStamps {
public static final String KEY = "POSTEA_VERSIONS";
private VersionStamps() {}
/// The stamps stored on `container`, or null if it carries none.
public static NBTTagCompound read(NBTTagCompound container) {
return container.hasKey(KEY, TAG_COMPOUND) ? container.getCompoundTag(KEY) : null;
}
/// The version stored for `key` in `stamps`, or [IVersionedTransformer#UNSTAMPED]. `stamps` may be null.
public static int stored(NBTTagCompound stamps, String key) {
return stamps != null && stamps.hasKey(key, TAG_INT) ? stamps.getInteger(key) : IVersionedTransformer.UNSTAMPED;
}
/// Writes the stamps onto `container`: `carried`, the stamps the data was read with or null, with every
/// 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,81 @@
package com.gtnewhorizons.postea.utility;
import java.util.ArrayList;
import java.util.Locale;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ReportedException;
import com.gtnewhorizons.postea.Postea;
import com.gtnewhorizons.postea.api.IVersionedTransformer;
/// Runs versioned transformers over saved NBT and reports their failures.
public final class VersionedPass {
private VersionedPass() {}
/// One transformer's work on `root`, which holds data stamped at `stored`.
@FunctionalInterface
public interface Step {
void apply(IVersionedTransformer transformer, NBTTagCompound root, int stored);
}
/// Runs `step` for every transformer whose stamp on `root` differs from its current version. The steps work on a
/// copy of `root`, which is stamped with the current versions and replaces the contents of `root` once every step
/// has succeeded. A failing step throws the [#failure] for `subjectName` and `subject`, and leaves `root` as read.
///
/// @return a copy of the stamps `root` was read with, or null if unstamped
public static NBTTagCompound runAtomically(NBTTagCompound root, Iterable<IVersionedTransformer> transformers,
String subjectName, String subject, Step step) {
NBTTagCompound stamps = VersionStamps.read(root);
NBTTagCompound carried = stamps == null ? null : (NBTTagCompound) stamps.copy();
NBTTagCompound working = null;
for (IVersionedTransformer transformer : transformers) {
int current = transformer.currentVersion();
int stored = VersionStamps.stored(carried, transformer.key());
if (stored == current) continue;
VersionedTransformerLog.announce(transformer, stored, current);
Postea.LOG
.debug("{}: {} {} from version {} to {}", transformer.key(), subjectName, subject, stored, current);
if (working == null) working = (NBTTagCompound) root.copy();
try {
step.apply(transformer, working, stored);
} catch (Throwable t) {
throw failure(t, transformer, stored, current, subjectName, subject);
}
}
if (working != null) {
VersionStamps.write(working, carried, transformers);
replaceContents(root, working);
}
return carried;
}
/// The exception a failed transformer run throws. Its crash report description names the transformer, the subject
/// and both versions.
public static ReportedException failure(Throwable cause, IVersionedTransformer transformer, int stored, int current,
String subjectName, String subject) {
String description = String.format(
"Running versioned transformer %s on %s %s from version %s to %d",
transformer.key(),
subjectName.toLowerCase(Locale.ROOT),
subject,
VersionedTransformerLog.versionName(stored),
current);
CrashReport report = CrashReport.makeCrashReport(cause, description);
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 new ReportedException(report);
}
private static void replaceContents(NBTTagCompound target, NBTTagCompound source) {
for (Object key : new ArrayList<Object>(target.func_150296_c())) target.removeTag((String) key);
for (Object key : source.func_150296_c()) target.setTag((String) key, source.getTag((String) key));
}
}
@@ -0,0 +1,33 @@
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;
/// Logs each version span a transformer brings data across once per world, not 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(),
versionName(stored),
current);
}
}
static String versionName(int version) {
return version == IVersionedTransformer.UNSTAMPED ? "unstamped" : String.valueOf(version);
}
public static void clear() {
ANNOUNCED.clear();
}
}
@@ -0,0 +1,130 @@
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 `level.dat` on the first save after its content disappears, so this table keeps
/// the name for transformers keyed on it. Persisted as `<world>/postea/known-ids.json`:
///
/// ```json
/// { "version": 1, "blocks": { "mod:block": [300, 301] }, "items": { "mod:item": [4200] } }
/// ```
public final class WorldIdTable {
static final String FILE_NAME = "known-ids.json";
/// FML prefixes block names with this character in a saved id map, and item names with 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 `file`, or an empty table if it is absent. Throws [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 carry FML's block and item prefixes
/// (see [#BLOCK_PREFIX]). 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);
}
}
+4 -1
View File
@@ -8,8 +8,11 @@
"mixins": [ "mixins": [
"MixinAnvilChunkLoader", "MixinAnvilChunkLoader",
"MixinChunk", "MixinChunk",
"MixinEntityPlayer",
"MixinEntityPlayerMP",
"MixinItemStack", "MixinItemStack",
"MixinNBTTagList" "MixinNBTTagList",
"MixinSaveHandler"
], ],
"client": [], "client": [],
"server": [] "server": []
@@ -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,52 @@
package com.gtnewhorizons.postea.api;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Arrays;
import java.util.Collections;
import net.minecraft.nbt.NBTTagCompound;
import org.junit.jupiter.api.Test;
import com.gtnewhorizons.postea.utility.VersionStamps;
class CustomDataReplacementManagerTest {
@Test
void aRebuiltRootKeepsTheStampOfATransformerThatIsNotRegistered() {
StubTransformer present = new StubTransformer("mod:present", 2);
StubTransformer absent = new StubTransformer("mod:absent", 5);
NBTTagCompound original = new NBTTagCompound();
CustomDataReplacementManager.transform("mod:storage", original, Arrays.asList(present, absent));
NBTTagCompound saved = CustomDataReplacementManager.savedStamps(original);
present.version = 3;
NBTTagCompound rebuilt = new NBTTagCompound();
CustomDataReplacementManager.stamp(rebuilt, saved, Collections.singletonList(present));
NBTTagCompound stamps = VersionStamps.read(rebuilt);
assertEquals(3, VersionStamps.stored(stamps, "mod:present"));
assertEquals(5, VersionStamps.stored(stamps, "mod:absent"));
assertEquals(2, VersionStamps.stored(saved, "mod:present"));
}
@Test
void aThrowingTransformerLeavesTheRootAsRead() {
StubTransformer rewrites = new StubTransformer("mod:rewrites", 2);
rewrites.customData = ctx -> ctx.root()
.setString("data", "new");
StubTransformer fails = new StubTransformer("mod:fails", 2);
fails.customData = ctx -> { throw new IllegalStateException("broken"); };
NBTTagCompound root = new NBTTagCompound();
root.setString("data", "old");
NBTTagCompound asRead = (NBTTagCompound) root.copy();
// The ReportedException's CrashReport initializes FML, which fails outside a launched game.
assertThrows(
Throwable.class,
() -> CustomDataReplacementManager.transform("mod:storage", root, Arrays.asList(rewrites, fails)));
assertEquals(asRead, root);
}
}
@@ -0,0 +1,31 @@
package com.gtnewhorizons.postea.api;
import java.util.function.Consumer;
/// An [IVersionedTransformer] at a version the test sets, running the test's custom data transform.
public final class StubTransformer implements IVersionedTransformer {
private final String key;
public int version;
public Consumer<CustomDataTransformContext> customData = ctx -> {};
public StubTransformer(String key, int version) {
this.key = key;
this.version = version;
}
@Override
public String key() {
return key;
}
@Override
public int currentVersion() {
return version;
}
@Override
public void transformCustomData(CustomDataTransformContext ctx) {
customData.accept(ctx);
}
}
@@ -0,0 +1,33 @@
package com.gtnewhorizons.postea.api;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import net.minecraft.nbt.NBTTagCompound;
import org.junit.jupiter.api.Test;
import com.gtnewhorizons.postea.utility.VersionStamps;
import com.gtnewhorizons.postea.utility.VersionedPass;
class VersionedPassTest {
/// Data saved while a later step of the same load fails must not be transformed a second time on the next load.
@Test
void aTransformedRootCarriesTheCurrentStamps() {
StubTransformer transformer = new StubTransformer("mod:t", 2);
NBTTagCompound root = new NBTTagCompound();
root.setString("data", "old");
VersionedPass.runAtomically(
root,
Collections.singletonList(transformer),
"Player",
"someone",
(t, data, stored) -> data.setString("data", "new"));
assertEquals("new", root.getString("data"));
assertEquals(2, VersionStamps.stored(VersionStamps.read(root), "mod:t"));
}
}
@@ -0,0 +1,96 @@
package com.gtnewhorizons.postea.api;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import org.junit.jupiter.api.Test;
class VersionedStackTransformerTest {
/// Bumps every stack's damage by one, or rewrites nothing when `rewrite` is false.
private static final class DamageBump extends VersionedStackTransformer {
private final boolean rewrite;
final List<Integer> requestedVersions = new ArrayList<>();
DamageBump(boolean rewrite) {
this.rewrite = rewrite;
}
@Override
public String key() {
return "test:damage";
}
@Override
public int currentVersion() {
return 9;
}
@Override
protected Consumer<NBTTagCompound> stackTransform(int storedVersion) {
requestedVersions.add(storedVersion);
return rewrite ? stack -> stack.setShort("Damage", (short) (stack.getShort("Damage") + 1)) : null;
}
}
private static NBTTagCompound holding(String listKey, NBTTagCompound... stacks) {
NBTTagList list = new NBTTagList();
for (NBTTagCompound stack : stacks) list.appendTag(stack);
NBTTagCompound holder = new NBTTagCompound();
holder.setTag(listKey, list);
return holder;
}
private static NBTTagCompound stack() {
NBTTagCompound stack = new NBTTagCompound();
stack.setShort("id", (short) 1);
stack.setByte("Count", (byte) 1);
return stack;
}
/// Runs `transformer` over a chunk holding two stacks and a player and custom-data context holding one each, and
/// returns the stacks' damage values in that order.
private static List<Integer> damageAfter(DamageBump transformer) {
NBTTagCompound chunkStack = stack();
NBTTagCompound otherChunkStack = stack();
NBTTagCompound tileEntity = holding("Items", chunkStack, otherChunkStack);
tileEntity.setString("id", "Chest");
NBTTagCompound levelTag = new NBTTagCompound();
levelTag.setTag("TileEntities", holding("list", tileEntity).getTagList("list", 10));
NBTTagCompound playerStack = stack();
NBTTagCompound customStack = stack();
customStack.setString("id", "minecraft:stone");
transformer.transformChunk(new ChunkTransformContext(null, null, levelTag, 1));
transformer.transformPlayer(new PlayerDataTransformContext(null, holding("Inventory", playerStack), 2));
transformer
.transformCustomData(new CustomDataTransformContext("test:storage", holding("Items", customStack), 3));
return Arrays.asList(
(int) chunkStack.getShort("Damage"),
(int) otherChunkStack.getShort("Damage"),
(int) playerStack.getShort("Damage"),
(int) customStack.getShort("Damage"));
}
@Test
void aStackTransformRewritesStacksInChunksPlayersAndCustomData() {
DamageBump transformer = new DamageBump(true);
assertEquals(Arrays.asList(1, 1, 1, 1), damageAfter(transformer));
assertEquals(Arrays.asList(1, 2, 3), transformer.requestedVersions);
}
@Test
void aNullStackTransformLeavesEveryContextUntouched() {
assertEquals(Arrays.asList(0, 0, 0, 0), damageAfter(new DamageBump(false)));
}
}
@@ -0,0 +1,62 @@
package com.gtnewhorizons.postea.utility;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import org.junit.jupiter.api.Test;
class HeightMapsTest {
/// A chunk with empty sections at `sections`, opaque only at positions set through [#setOpaque], with no block
/// registry behind it.
private static final class OpacityChunk extends Chunk {
private final Set<Long> opaque = new HashSet<>();
OpacityChunk(int... sections) {
super(null, 0, 0);
for (int section : sections) getBlockStorageArray()[section] = new ExtendedBlockStorage(section << 4, true);
}
void setOpaque(int x, int y, int z) {
opaque.add(position(x, y, z));
}
@Override
public int func_150808_b(int x, int y, int z) {
return opaque.contains(position(x, y, z)) ? 255 : 0;
}
private static long position(int x, int y, int z) {
return ((long) y << 8) | (z << 4) | x;
}
}
@Test
void anEmptiedColumnGetsHeightZero() {
OpacityChunk chunk = new OpacityChunk(0);
chunk.setOpaque(0, 10, 0);
chunk.heightMap[5 << 4 | 3] = 64;
HeightMaps.regenerate(chunk);
assertEquals(0, chunk.heightMap[5 << 4 | 3]);
assertEquals(11, chunk.heightMap[0]);
assertEquals(0, chunk.heightMapMinimum);
}
@Test
void aBlockAtTheTopOfTheWorldGetsHeight256() {
OpacityChunk chunk = new OpacityChunk(15);
chunk.setOpaque(7, 255, 9);
HeightMaps.regenerate(chunk);
assertEquals(256, chunk.heightMap[9 << 4 | 7]);
}
}
@@ -0,0 +1,34 @@
package com.gtnewhorizons.postea.utility;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class IDRegistryTest {
@TempDir
File world;
@AfterEach
void endWorld() {
IDRegistry.endWorld();
}
@Test
void theMappingGateOpensOnlyWhenTheBegunWorldsInfoLoads() {
IDRegistry.beginWorld(world);
assertFalse(IDRegistry.isMappingApplied());
IDRegistry.onWorldInfoLoaded();
assertTrue(IDRegistry.isMappingApplied());
IDRegistry.endWorld();
IDRegistry.onWorldInfoLoaded();
assertFalse(IDRegistry.isMappingApplied());
}
}
@@ -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));
}
/// A string id with a `Count` is a stack only in string-id mode, which keeps chunk and player walks off tile
/// entity compounds.
@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,34 @@
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;
import com.gtnewhorizons.postea.api.StubTransformer;
class VersionStampsTest {
@Test
void anUnstampedContainerReadsAsUnstamped() {
NBTTagCompound container = new NBTTagCompound();
assertNull(VersionStamps.read(container));
assertEquals(IVersionedTransformer.UNSTAMPED, VersionStamps.stored(null, "mod:key"));
}
@Test
void writeWithoutCarriedStampsWritesOnlyRegisteredKeys() {
NBTTagCompound container = new NBTTagCompound();
VersionStamps.write(container, null, Collections.singletonList(new StubTransformer("mod:key", 1)));
assertEquals(1, VersionStamps.stored(VersionStamps.read(container), "mod:key"));
assertEquals(IVersionedTransformer.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()));
}
}