Compare commits

..
Author SHA1 Message Date
Guillaume Mercier 74dc712460 remove deprecated endpoints
will publish a pre-tag and create integration PRs shortly
2026-01-30 20:07:39 -05:00
Guillaume Mercier 3f8beb3c68 add disabled example file 2026-01-30 20:06:37 -05:00
Guillaume Mercier d3d42d2ff5 Update README.md 2026-01-28 13:48:51 -05:00
Guillaume Mercier 4ebaff3cf9 readme 2nd pass 2026-01-28 12:40:12 -05:00
Guillaume Mercier 494da5c633 fix typos
also shortened the max line length of comments in readme examples so it doesn't go off screen
when you look at it on github when the readme is fully expanded.
2026-01-28 11:28:55 -05:00
Guillaume Mercier 3b03d62751 copy paste errors are funny. 2026-01-27 21:31:28 -05:00
Guillaume Mercier 99f6158e46 Add proper examples to readme.
and it's done!
2026-01-27 21:30:27 -05:00
Guillaume Mercier 2b56022599 spotless apply 2026-01-27 17:50:27 -05:00
Guillaume Mercier 8fec8f2a8a properly handle the result of TE NBT transformers. 2026-01-27 17:49:46 -05:00
Guillaume Mercier 3868d131a7 any mentions of nuke dummies, add new interfaces that better serve good practices. 2026-01-27 16:46:05 -05:00
Guillaume Mercier 78e3f792b7 replacement -> transformer refactor 2026-01-24 11:17:29 -05:00
Guillaume Mercier ccb579f386 spotless bad 2026-01-23 18:46:40 -05:00
Guillaume Mercier 9672270b1e isolate simple transformations to own file + more doc + cleanup 2026-01-23 17:59:04 -05:00
Guillaume Mercier d20a5fe43f doc cleanup 2026-01-23 16:00:38 -05:00
Guillaume Mercier bc3d26e9b2 transformer optimisations and improve public API clarity. 2026-01-23 15:51:34 -05:00
Guillaume Mercier 0fb3c220fb Speedup simple transformers by caching meta map into lambda capture. 2026-01-23 10:17:35 -05:00
Guillaume Mercier b81f3d5b52 spotless apply 2026-01-21 14:02:36 -05:00
Guillaume Mercier bd30015bbd add stack handlers for item -> item+meta 2026-01-21 13:53:47 -05:00
Guillaume Mercier 1f5a792ceb add helper functions to api to stream development 2026-01-20 18:06:33 -05:00
Guillaume Mercier 5c524c2461 typo fix 2026-01-20 13:29:28 -05:00
Guillaume Mercier 6d58c41dd8 move internal stuff to a non-api endpoint and clean-up added structures 2026-01-20 13:27:50 -05:00
Guillaume Mercier 5d4b657868 Move dummy item creation to the load complete event. 2026-01-20 13:07:23 -05:00
Guillaume Mercier 36de68e5ab add dummy item auto-creation 2026-01-20 11:00:33 -05:00
Guillaume Mercier 4d2c1ba3fc Add support for multiple mods remapping the same item/block/tile entity. 2026-01-19 11:52:40 -05:00
59 changed files with 215 additions and 2207 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, release/** ] branches: [ master, main ]
push: push:
branches: [ master, main, release/** ] branches: [ master, main ]
jobs: jobs:
build-and-test: build-and-test:
+8 -97
View File
@@ -1,4 +1,4 @@
# Postea # TileEntityReplacementManager API
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.
@@ -10,10 +10,7 @@ runtime. Allowing developers to replace, migrate or modify game elements based o
3. **ItemStack Transformers**: Replace or Modify items. 3. **ItemStack Transformers**: Replace or Modify items.
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
@@ -33,9 +30,9 @@ transformed.
> [!TIP] > [!TIP]
> >
> Tile entity, block, and item transformers run once per chunk until the mod list changes (disabled in a dev > Tile entity and block transformers are only ran once per chunk until a player's mod list changes. This behaviour is
> environment). For transformations that must run exactly once per version of your own content, use a versioned > disabled if you are in a dev environment; Allowing you to test your transformers simply by leaving and rejoining your
> transformer (§9). > test world.
> [!CAUTION] > [!CAUTION]
> >
@@ -251,7 +248,7 @@ let you register "Simple Transformations".
When applicable, we recommend using these endpoints as they will generally result in a faster execution time than if you When applicable, we recommend using these endpoints as they will generally result in a faster execution time than if you
were to implement your own handler. Another advantage is that multiple, completely distinct, mods can now target the were to implement your own handler. Another advantage is that multiple, completely distinct, mods can now target the
same item ID for a simple transformation with zero impact to compatibility. same item id for a simple transformation with zero impact to compatibility.
Simple Transformers can be used to perform one of 4 types of transformations: Simple Transformers can be used to perform one of 4 types of transformations:
1. Some block or item with any meta or damage value -> some block or item, preserving the meta or damage value. 1. Some block or item with any meta or damage value -> some block or item, preserving the meta or damage value.
@@ -288,7 +285,7 @@ Simple Transformers can be used to perform one of 4 types of transformations:
> >
> When registering block or item conversions, Postea will automatically detect if the given item or block has a block or > When registering block or item conversions, Postea will automatically detect if the given item or block has a block or
> item counterpart (respectively) and register an appropriate simple transformation. You can disable this behaviour by > item counterpart (respectively) and register an appropriate simple transformation. You can disable this behaviour by
> adding a `true` argument to end of all simple transformation endpoints. > adding a `false` argument to end of all simple transformation endpoints.
> [!NOTE] > [!NOTE]
> >
@@ -479,7 +476,7 @@ public abstract class FMLReMappingExample {
public static void postLoad() { public static void postLoad() {
// this only works when the thing you're replacing with has never been registered to a world's // this only works when the thing you're replacing with has never been registered to a world's
// ID map. If you try to run this with a block that already exists (eg good old dirt), FML // id map. If you try to run this with a block that already exists (eg good old dirt), FML
// error out and you that your world is corrupted beyond repair, and advise you to undo what // error out and you that your world is corrupted beyond repair, and advise you to undo what
// ever you just did. // ever you just did.
// //
@@ -517,89 +514,3 @@ 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,7 +3,3 @@
plugins { plugins {
id 'com.gtnewhorizons.gtnhconvention' id 'com.gtnewhorizons.gtnhconvention'
} }
test {
useJUnitPlatform()
}
+4 -9
View File
@@ -1,13 +1,8 @@
dependencies { dependencies {
api("com.github.GTNewHorizons:GTNHLib:0.9.39:dev") api("com.github.GTNewHorizons:GTNHLib:0.6.38:dev")
compileOnly('com.github.GTNewHorizons:NotEnoughIds:2.1.10:dev') compileOnly('com.github.GTNewHorizons:NotEnoughIds:2.1.10:dev')
compileOnly('com.falsepattern:endlessids-mc1.7.10:1.7.1:dev') compileOnly('com.falsepattern:chunkapi-mc1.7.10:0.6.0:dev')
compileOnly("com.github.GTNewHorizons:NotEnoughItems:2.8.75-GTNH:dev") { transitive = false } compileOnly('com.falsepattern:endlessids-mc1.7.10:1.6.0:dev')
compileOnly("com.github.GTNewHorizons:NotEnoughItems:2.8.48-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')
} }
+4 -39
View File
@@ -39,33 +39,9 @@ remoteMappings = https\://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/co
# `./gradlew runClient --username=AnotherPlayer`, or configuring this command in your IDE. # `./gradlew runClient --username=AnotherPlayer`, or configuring this command in your IDE.
developmentEnvironmentUserName = Developer developmentEnvironmentUserName = Developer
# Enables modern Java syntax support. Valid values: # Enables using modern Java syntax (up to version 17) via Jabel, while still targeting JVM 8.
# - false: No modern syntax, Java 8 only # See https://github.com/bsideup/jabel for details on how this works.
# - jabel: Jabel syntax-only support, compiles to J8 bytecode enableModernJavaSyntax = true
# - jvmDowngrader: Full modern Java via JVM Downgrader (syntax + stdlib APIs)
# - modern: Native modern Java bytecode, no downgrading
enableModernJavaSyntax = jabel
# If set, ignores the above setting and compiles with the given toolchain. This may cause unexpected issues,
# and should *not* be used in most situations. -1 disables this.
# forceToolchainVersion = -1
# Target JVM version for JVM Downgrader bytecode downgrading.
# Only used when enableModernJavaSyntax = jvmDowngrader
# downgradeTargetVersion = 8
# Comma-separated list of Java versions for multi-release jar support (JVM Downgrader only).
# Classes will be available in META-INF/versions/N/ for each version N in this list.
# Default: "21,25" (J25+ gets native classes, J21-24 gets partial downgrade, J8-20 gets full downgrade).
# jvmDowngraderMultiReleaseVersions = 21,25
# Specifies how JVM Downgrader API stubs are provided. Options:
# - shade: Shade minimized stubs into the jar
# - gtnhlib: GTNHLib provides stubs at runtime (adds version constraint)
# - external: Another dependency provides stubs (no constraint, no warning)
# - (empty): Warning reminding you to configure stubs
# Note: 'shade' option requires you to verify license compliance, see: https://github.com/unimined/JvmDowngrader/blob/main/LICENSE.md
# jvmDowngraderStubsProvider =
# Enables injecting missing generics into the decompiled source code for a better coding experience. # Enables injecting missing generics into the decompiled source code for a better coding experience.
# Turns most publicly visible List, Map, etc. into proper List<E>, Map<K, V> types. # Turns most publicly visible List, Map, etc. into proper List<E>, Map<K, V> types.
@@ -120,9 +96,7 @@ usesMixinDebug = true
# Specify the location of your implementation of IMixinConfigPlugin. Leave it empty otherwise. # Specify the location of your implementation of IMixinConfigPlugin. Leave it empty otherwise.
mixinPlugin = mixinPlugin =
# Specify the package that contains all of your Mixins. The package must exist or # Specify the package that contains all of your Mixins. You may only place Mixins in this package or the build will fail!
# the build will fail. If you have a package property defined in your mixins.<modid>.json,
# it must match with this or the build will fail.
mixinsPackage = mixins mixinsPackage = mixins
# Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin! # Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin!
@@ -198,12 +172,6 @@ curseForgeRelations =
# projects. New projects should not use this parameter. # projects. New projects should not use this parameter.
# customArchiveBaseName = # customArchiveBaseName =
# Optional parameter to customize the default working directory used by the runClient* tasks. Relative to the project directory.
# runClientWorkingDirectory = run/client
# Optional parameter to customize the default working directory used by the runServer* tasks. Relative to the project directory.
# runServerWorkingDirectory = run/server
# Optional parameter to have the build automatically fail if an illegal version is used. # Optional parameter to have the build automatically fail if an illegal version is used.
# This can be useful if you e.g. only want to allow versions in the form of '1.1.xxx'. # This can be useful if you e.g. only want to allow versions in the form of '1.1.xxx'.
# The check is ONLY performed if the version is a git tag. # The check is ONLY performed if the version is a git tag.
@@ -233,6 +201,3 @@ curseForgeRelations =
# This is meant to be set in $HOME/.gradle/gradle.properties. # This is meant to be set in $HOME/.gradle/gradle.properties.
# ideaCheckSpotlessOnBuild = true # ideaCheckSpotlessOnBuild = true
# Non-GTNH properties
org.gradle.configuration-cache = true
org.gradle.parallel = true
-12
View File
@@ -1,12 +0,0 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/cd495626d2ee49a75447e3fdc6afb287/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/cd495626d2ee49a75447e3fdc6afb287/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/d4fd992c9557644e637ebe98263e0ae7/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/59a9771cad43219260d9aac9a8ec4d6a/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/cd495626d2ee49a75447e3fdc6afb287/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/a4c09dd2e2d7079373d30e524bbc2829/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/8e1d9ee5d0f13e442218f6884a306da1/redirect
toolchainVersion=25
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
Vendored
+6 -3
View File
@@ -1,7 +1,7 @@
#!/bin/sh #!/bin/sh
# #
# Copyright © 2015 the original authors. # Copyright © 2015-2021 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -57,7 +57,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/b631911858264c0b6e4d6603d677ff5218766cee/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@@ -114,6 +114,7 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;; NONSTOP* ) nonstop=true ;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
@@ -171,6 +172,7 @@ fi
# For Cygwin or MSYS, switch paths to Windows format before running java # For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" ) JAVACMD=$( cygpath --unix "$JAVACMD" )
@@ -210,7 +212,8 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ -classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@" "$@"
# Stop when "xargs" is not available. # Stop when "xargs" is not available.
Vendored
+2 -1
View File
@@ -70,10 +70,11 @@ goto fail
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
+1 -1
View File
@@ -17,7 +17,7 @@ pluginManagement {
} }
plugins { plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '2.0.24' id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.41'
} }
@@ -1,9 +1,5 @@
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;
@@ -18,12 +14,9 @@ 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;
@@ -39,7 +32,6 @@ 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 {
@@ -355,45 +347,4 @@ 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,30 +1,19 @@
package com.gtnewhorizons.postea; package com.gtnewhorizons.postea;
import java.io.File;
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;
@Mod( @Mod(
modid = Postea.MODID, modid = Postea.MODID,
@@ -38,39 +27,19 @@ 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);
}
@Mod.EventHandler @Mod.EventHandler
public void postsLoad(FMLPostInitializationEvent event) { public void postsLoad(FMLPostInitializationEvent event) {
// TestUIEMigrator.postLoad(); // TestUIEMigrator.postLoad();
} }
@SubscribeEvent @Mod.EventHandler
public void chunkLoaded(ChunkEvent.Load event) { public void chunkLoaded(ChunkEvent.Load event) {
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();
@@ -87,4 +56,5 @@ public class Postea {
public void onLoadCompleted(FMLLoadCompleteEvent event) { public void onLoadCompleted(FMLLoadCompleteEvent event) {
SimpleTransformationRegistry.onLoadCompleted(); SimpleTransformationRegistry.onLoadCompleted();
} }
} }
@@ -1,15 +0,0 @@
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;
}
}
@@ -1,13 +1,14 @@
package com.gtnewhorizons.postea.api; package com.gtnewhorizons.postea.api;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function;
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;
import com.gtnewhorizons.postea.utility.BlockConversionInfo;
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;
@@ -47,7 +48,7 @@ public abstract class BlockReplacementManager {
* @param transformer The transformer to apply. * @param transformer The transformer to apply.
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static void addTransformationHandler(String originalId, IBlockTransformationHandler transformer) { public static void addTransformationHandler(String originalId, Function<BlockConversionInfo, Boolean> transformer) {
if (originalId == null) throw new IllegalArgumentException("original id is null"); if (originalId == null) throw new IllegalArgumentException("original id is null");
if (transformer == null) throw new IllegalArgumentException("transformer is null"); if (transformer == null) throw new IllegalArgumentException("transformer is null");
TransformerRegistry.addBlockTransformer(originalId, transformer); TransformerRegistry.addBlockTransformer(originalId, transformer);
@@ -55,27 +56,6 @@ 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
@@ -1,140 +0,0 @@
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);
}
}
@@ -1,76 +0,0 @@
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;
}
}
@@ -1,25 +0,0 @@
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);
}
}
@@ -1,9 +0,0 @@
package com.gtnewhorizons.postea.api;
import com.gtnewhorizons.postea.utility.BlockConversionInfo;
@FunctionalInterface
public interface IBlockTransformationHandler {
boolean apply(BlockConversionInfo info);
}
@@ -1,9 +0,0 @@
package com.gtnewhorizons.postea.api;
import net.minecraft.nbt.NBTTagCompound;
@FunctionalInterface
public interface IItemStackTransformationHandler {
boolean apply(String originalId, NBTTagCompound stack);
}
@@ -1,43 +0,0 @@
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].
///
/// A transformer that rewrites item stacks extends [VersionedStackTransformer], which covers every pass.
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()].
void transformChunk(ChunkTransformContext ctx);
/// Brings a player's saved data stamped at [PlayerDataTransformContext#storedVersion()] to [#currentVersion()].
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.
void transformCustomData(CustomDataTransformContext ctx);
}
@@ -1,5 +1,6 @@
package com.gtnewhorizons.postea.api; package com.gtnewhorizons.postea.api;
import java.util.function.BiFunction;
import java.util.function.Consumer; import java.util.function.Consumer;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
@@ -7,6 +8,7 @@ import javax.annotation.Nonnull;
import net.minecraft.init.Items; import net.minecraft.init.Items;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreDictionary;
import com.gtnewhorizons.postea.utility.IDRegistry; import com.gtnewhorizons.postea.utility.IDRegistry;
@@ -50,7 +52,8 @@ public abstract class ItemStackReplacementManager {
* @param transformer The transformer to apply. * @param transformer The transformer to apply.
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static void addTransformationHandler(String originalId, IItemStackTransformationHandler transformer) { public static void addTransformationHandler(String originalId,
BiFunction<String, NBTTagCompound, Boolean> transformer) {
if (originalId == null) throw new IllegalArgumentException("original id is null"); if (originalId == null) throw new IllegalArgumentException("original id is null");
if (transformer == null) throw new IllegalArgumentException("transformer is null"); if (transformer == null) throw new IllegalArgumentException("transformer is null");
TransformerRegistry.addStackTransformer(originalId, transformer); TransformerRegistry.addStackTransformer(originalId, transformer);
@@ -1,22 +0,0 @@
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);
}
}
@@ -1,30 +0,0 @@
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);
}
}
@@ -1,35 +0,0 @@
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,10 +14,23 @@ 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;
@@ -7,7 +7,6 @@ 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")
@@ -46,13 +45,8 @@ 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,17 +12,16 @@ 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 {
/// Hooks the funnel shared by sync and async loads, which runs after ChunkAPI's `readChunkFromNBT` replacement. // This hook is compatible with Vanilla/NEID/EIDs
@Inject(method = "checkedReadChunkFromNBT__Async", at = @At("RETURN"), remap = false, require = 1) @Inject(method = "readChunkFromNBT", at = @At("RETURN"), require = 1)
private void postea$chunkHook(CallbackInfoReturnable<Object[]> cir) { private void postea$chunkHook(CallbackInfoReturnable<Chunk> cir, @Local Chunk chunk,
Object[] data = cir.getReturnValue(); @Local(argsOnly = true) World world, @Local(ordinal = 0, argsOnly = true) NBTTagCompound tag) {
if (data == null) return; ChunkFixerUtility.onChunkRead(chunk, world, tag);
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"))
@@ -30,7 +29,7 @@ public abstract class MixinAnvilChunkLoader {
ChunkFixerUtility.onChunkLoaded(cir.getReturnValue()); ChunkFixerUtility.onChunkLoaded(cir.getReturnValue());
} }
@Inject(method = "writeChunkToNBT", at = @At("HEAD"), order = 900) @Inject(method = "writeChunkToNBT", at = @At("HEAD"))
private void postea$writePosteaChunkCode(Chunk chunk, World world, NBTTagCompound nbtTagCompound, CallbackInfo ci) { private void postea$writePosteaChunkCode(Chunk chunk, World world, NBTTagCompound nbtTagCompound, CallbackInfo ci) {
ChunkFixerUtility.onChunkWrite(chunk, nbtTagCompound); ChunkFixerUtility.onChunkWrite(chunk, nbtTagCompound);
} }
@@ -1,6 +1,5 @@
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;
@@ -16,13 +15,6 @@ 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;
@@ -32,24 +24,4 @@ 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;
}
} }
@@ -1,22 +0,0 @@
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());
}
}
}
@@ -1,71 +0,0 @@
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);
}
}
@@ -1,46 +0,0 @@
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());
}
}
@@ -1,26 +0,0 @@
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,18 +1,8 @@
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);
} }
@@ -1,10 +0,0 @@
package com.gtnewhorizons.postea.mixins.interfaces;
import net.minecraft.nbt.NBTTagCompound;
public interface IPlayerStampsMixin {
NBTTagCompound Postea$getVersionStamps();
void Postea$setVersionStamps(NBTTagCompound stamps);
}
@@ -12,10 +12,7 @@ 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;
@@ -36,8 +33,10 @@ 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;
runVersionedTransformers(chunk, world, tag); chunkMixin.Postea$setPosteaCode(-1);
chunkMixin.Postea$setPosteaCode(tag.hasKey("POSTEA", 4) ? tag.getLong("POSTEA") : -1); if (tag.hasKey("POSTEA", 4)) {
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);
@@ -63,54 +62,18 @@ 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) {
boolean stale = !hasChunkBeenUpdated(iChunkMixin.Postea$getPosteaCode()); if (!hasChunkBeenUpdated(iChunkMixin.Postea$getPosteaCode())) {
if (stale) iChunkMixin.Postea$setPosteaCode(ChunkFixerUtility.POSTEA_UPDATE_CODE); iChunkMixin.Postea$setPosteaCode(ChunkFixerUtility.POSTEA_UPDATE_CODE);
if (stale || iChunkMixin.Postea$isVersionedDirty()) chunk.setChunkModified(); 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);
} }
} }
@@ -134,7 +97,7 @@ public class ChunkFixerUtility {
BlockConversionInfo output = getBlockReplacement( BlockConversionInfo output = getBlockReplacement(
blockId, blockId,
metadata, (byte) metadata,
world, world,
x + chunkXPos + 1, x + chunkXPos + 1,
y + sectionY, y + sectionY,
@@ -1,29 +0,0 @@
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,29 +1,18 @@
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
@@ -35,39 +24,6 @@ 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.
@@ -77,127 +33,58 @@ 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;
mappingApplied = true; // we should be fine to execute those in parallel I think?
for (Map.Entry<String, Collection<Consumer<Integer>>> kv : BLOCK_ID_RESOLVERS.asMap() BLOCK_ID_RESOLVERS.asMap()
.entrySet()) { .entrySet()
int id = getBlockId(kv.getKey()); .parallelStream()
for (Consumer<Integer> resolver : kv.getValue()) { .forEach(kv -> {
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 /**
/// no registered content answers to in the world's retired id table. Ignored outside a server world and off the * Called by {@link com.gtnewhorizons.postea.mixins.preinit.MixinGameData}, this function is used to register all
/// server thread. * the previously registered namespaced to numeric id mappings that have ever been seen into a world.<br>
* <br>
* This function executes before the game starts remapping it's own internal IDs, so we can be sure that any
* existing will remain while the world is loaded.
*/
public static void registerWorldSpecificIDs(Map<String, Integer> map) { 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);
boolean block = kv.getKey() int id = kv.getValue();
.charAt(0) == WorldIdTable.BLOCK_PREFIX; if (kv.getKey()
if (block) { .charAt(0) == '\u0001') {
BLOCK_NAME_TO_ID.put(name, (int) kv.getValue()); BLOCK_NAME_TO_ID.put(name, id);
} else { } else {
ITEM_NAME_TO_ID.put(name, (int) kv.getValue()); ITEM_NAME_TO_ID.put(name, id);
} }
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 /**
/// removed, or -1 if the world never mapped it. * Fetches the block numeric ID associated with the namespaced ID.
*
* @param name the namespaced id of the block.
* @return The ID of the block, or -1 if the namespaced ID has never been registered while the current world was
* loaded.
*/
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()
@@ -207,7 +94,14 @@ 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()
@@ -1,55 +0,0 @@
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)));
}
}
@@ -1,19 +0,0 @@
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);
}
}
@@ -1,31 +0,0 @@
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());
}
}
@@ -49,13 +49,13 @@ class SimpleTransformationMap<T> {
* The target meta/damage value for the transformation. * The target meta/damage value for the transformation.
* If the value is {@link OreDictionary#WILDCARD_VALUE}, It maintains the old meta/damage value. * If the value is {@link OreDictionary#WILDCARD_VALUE}, It maintains the old meta/damage value.
*/ */
public final int targetMeta; public final short targetMeta;
/** /**
* The numeric id of the target block, updated during the FMLMappingUpdate event * The numeric id of the target block, updated during the FMLMappingUpdate event
*/ */
public int targetRuntimeId; public int targetRuntimeId;
public Value(T target, int targetMeta) { public Value(T target, short targetMeta) {
this.target = target; this.target = target;
this.targetMeta = targetMeta; this.targetMeta = targetMeta;
this.targetRuntimeId = -1; this.targetRuntimeId = -1;
@@ -73,7 +73,7 @@ class SimpleTransformationMap<T> {
* When querying, the value will be replaced, which will * When querying, the value will be replaced, which will
* be used when ever no other specific meta match is found. * be used when ever no other specific meta match is found.
*/ */
public void put(String originalId, int originalMeta, T target, int targetMeta) { public void put(String originalId, int originalMeta, T target, short targetMeta) {
if (originalMeta == -1) originalMeta = OreDictionary.WILDCARD_VALUE; if (originalMeta == -1) originalMeta = OreDictionary.WILDCARD_VALUE;
this.registry.computeIfAbsent(originalId, k -> new Int2ObjectOpenHashMap<>()) this.registry.computeIfAbsent(originalId, k -> new Int2ObjectOpenHashMap<>())
.put(originalMeta, new Value<>(target, targetMeta)); .put(originalMeta, new Value<>(target, targetMeta));
@@ -1,6 +1,8 @@
package com.gtnewhorizons.postea.utility; package com.gtnewhorizons.postea.utility;
import java.util.Map; import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.item.Item; import net.minecraft.item.Item;
@@ -8,9 +10,7 @@ import net.minecraft.item.ItemBlock;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreDictionary;
import com.gtnewhorizons.postea.api.IBlockTransformationHandler;
import com.gtnewhorizons.postea.api.IDExtenderCompat; import com.gtnewhorizons.postea.api.IDExtenderCompat;
import com.gtnewhorizons.postea.api.IItemStackTransformationHandler;
/** /**
* A registry for simple item and block transformations. A common use case is mod removal, replacements or deprecations. * A registry for simple item and block transformations. A common use case is mod removal, replacements or deprecations.
@@ -100,11 +100,11 @@ public class SimpleTransformationRegistry {
public static void addSimpleTransformer(String originalId, int originalMeta, Block newBlock, int newMeta, public static void addSimpleTransformer(String originalId, int originalMeta, Block newBlock, int newMeta,
boolean skipStackRemap) { boolean skipStackRemap) {
if (newMeta == -1) newMeta = OreDictionary.WILDCARD_VALUE; if (newMeta == -1) newMeta = OreDictionary.WILDCARD_VALUE;
SIMPLE_BLOCK_TRANSFORMATION_MAP.put(originalId, originalMeta, newBlock, newMeta); SIMPLE_BLOCK_TRANSFORMATION_MAP.put(originalId, originalMeta, newBlock, (short) newMeta);
if (!skipStackRemap) { if (!skipStackRemap) {
Item item = Item.getItemFromBlock(newBlock); Item item = Item.getItemFromBlock(newBlock);
if (item != null) { if (item != null) {
SIMPLE_ITEM_TRANSFORMATION_MAP.put(originalId, originalMeta, item, newMeta); SIMPLE_ITEM_TRANSFORMATION_MAP.put(originalId, originalMeta, item, (short) newMeta);
} }
} }
} }
@@ -114,7 +114,7 @@ public class SimpleTransformationRegistry {
* *
* @implNote This implementation has constant-time runtime. * @implNote This implementation has constant-time runtime.
*/ */
private static class SimpleBlockTransformationHandler implements IBlockTransformationHandler { private static class SimpleBlockTransformationHandler implements Function<BlockConversionInfo, Boolean> {
private final Map<Integer, SimpleTransformationMap.Value<Block>> metaMap; private final Map<Integer, SimpleTransformationMap.Value<Block>> metaMap;
@@ -123,7 +123,7 @@ public class SimpleTransformationRegistry {
} }
@Override @Override
public boolean apply(BlockConversionInfo info) { public Boolean apply(BlockConversionInfo info) {
SimpleTransformationMap.Value<Block> mapping = SimpleTransformationMap SimpleTransformationMap.Value<Block> mapping = SimpleTransformationMap
.getFromSubMap(metaMap, info.metadata); .getFromSubMap(metaMap, info.metadata);
if (mapping == null || mapping.targetRuntimeId <= -1) return false; if (mapping == null || mapping.targetRuntimeId <= -1) return false;
@@ -166,9 +166,9 @@ public class SimpleTransformationRegistry {
boolean skipBlockRemap) { boolean skipBlockRemap) {
if (newMeta == -1) newMeta = OreDictionary.WILDCARD_VALUE; if (newMeta == -1) newMeta = OreDictionary.WILDCARD_VALUE;
if (!skipBlockRemap && newItem instanceof ItemBlock ib) { if (!skipBlockRemap && newItem instanceof ItemBlock ib) {
SIMPLE_BLOCK_TRANSFORMATION_MAP.put(originalId, originalMeta, ib.field_150939_a, newMeta); SIMPLE_BLOCK_TRANSFORMATION_MAP.put(originalId, originalMeta, ib.field_150939_a, (short) newMeta);
} }
SIMPLE_ITEM_TRANSFORMATION_MAP.put(originalId, originalMeta, newItem, newMeta); SIMPLE_ITEM_TRANSFORMATION_MAP.put(originalId, originalMeta, newItem, (short) newMeta);
} }
/** /**
@@ -176,7 +176,7 @@ public class SimpleTransformationRegistry {
* *
* @implNote This implementation has constant-time runtime. * @implNote This implementation has constant-time runtime.
*/ */
private static class SimpleItemTransformationHandler implements IItemStackTransformationHandler { private static class SimpleItemTransformationHandler implements BiFunction<String, NBTTagCompound, Boolean> {
private final Map<Integer, SimpleTransformationMap.Value<Item>> metaMap; private final Map<Integer, SimpleTransformationMap.Value<Item>> metaMap;
@@ -185,14 +185,13 @@ public class SimpleTransformationRegistry {
} }
@Override @Override
public boolean apply(String originalId, NBTTagCompound tag) { public Boolean apply(String originalId, NBTTagCompound tag) {
short meta = tag.getShort("Damage"); short meta = tag.getShort("Damage");
SimpleTransformationMap.Value<Item> mapping = SimpleTransformationMap.getFromSubMap(metaMap, meta); SimpleTransformationMap.Value<Item> mapping = SimpleTransformationMap.getFromSubMap(metaMap, meta);
if (mapping == null || mapping.targetRuntimeId <= -1) return false; if (mapping == null || mapping.targetRuntimeId <= -1) return false;
IDExtenderCompat.setItemStackID(tag, mapping.targetRuntimeId); IDExtenderCompat.setItemStackID(tag, mapping.targetRuntimeId);
if (mapping.targetMeta != OreDictionary.WILDCARD_VALUE) { if (mapping.targetMeta != OreDictionary.WILDCARD_VALUE) {
// Damage is a vanilla short NBT field, unrelated to EndlessIDs block metadata width. tag.setShort("Damage", mapping.targetMeta);
tag.setShort("Damage", (short) mapping.targetMeta);
} }
return true; return true;
} }
@@ -1,13 +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 java.util.function.BiFunction;
import java.util.function.Function;
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;
@@ -15,36 +15,36 @@ 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.IDExtenderCompat; import com.gtnewhorizons.postea.api.IDExtenderCompat;
import com.gtnewhorizons.postea.api.IItemStackTransformationHandler;
import com.gtnewhorizons.postea.api.TriFunction; 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
*/ */
public class TransformerRegistry { public class TransformerRegistry {
private static final LinkedListMultimap<String, IItemStackTransformationHandler> ITEM_REPLACEMENT_MAP = LinkedListMultimap private static final LinkedListMultimap<String, BiFunction<String, NBTTagCompound, Boolean>> ITEM_REPLACEMENT_MAP = LinkedListMultimap
.create(); .create();
public static final LinkedListMultimap<String, IBlockTransformationHandler> BLOCK_REPLACEMENT_MAP = LinkedListMultimap public static final LinkedListMultimap<String, Function<BlockConversionInfo, Boolean>> BLOCK_REPLACEMENT_MAP = LinkedListMultimap
.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 /**
/// world loads. An id carries several names when content that once held it was removed. * Map of itemID -> originalName+transformationHandler.
private static final Int2ObjectOpenHashMap<List<Pair<String, List<IItemStackTransformationHandler>>>> RUNTIME_ITEM_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>(); * Pivoting on the id is faster than pivoting on the strings so this should help with perf a bit.
/// Maps a block id to the names that hold it and their handlers. Generated during the mapping update event when a * Generated during the mapping update event whilst entering/loading a world.
/// world loads. An id carries several names when content that once held it was removed. */
private static final Int2ObjectOpenHashMap<List<Pair<String, List<IBlockTransformationHandler>>>> RUNTIME_BLOCK_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>(); private static final Int2ObjectOpenHashMap<Pair<String, List<BiFunction<String, NBTTagCompound, Boolean>>>> RUNTIME_ITEM_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<Function<BlockConversionInfo, Boolean>>>> RUNTIME_BLOCK_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
// region FML Life Cycle handlers // region FML Life Cycle handlers
/** /**
@@ -64,99 +64,93 @@ 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.keySet()) { for (String key : BLOCK_REPLACEMENT_MAP.keys()) {
IntList ids = IDRegistry.getBlockIds(key); int id = IDRegistry.getBlockId(key);
if (ids.isEmpty()) { if (id >= 0) {
Postea.LOG.debug("Block {} has no id in this world; its transformers stay inactive", key); RUNTIME_BLOCK_REPLACEMENT_MAP.put(id, Pair.of(key, BLOCK_REPLACEMENT_MAP.get(key)));
continue;
}
for (int id : ids) {
RUNTIME_BLOCK_REPLACEMENT_MAP.computeIfAbsent(id, unused -> new ArrayList<>())
.add(Pair.of(key, BLOCK_REPLACEMENT_MAP.get(key)));
} }
} }
for (String key : ITEM_REPLACEMENT_MAP.keySet()) { // create a lookup for source block ids.
IntList ids = IDRegistry.getItemIds(key); for (String key : ITEM_REPLACEMENT_MAP.keys()) {
if (ids.isEmpty()) { int id = IDRegistry.getItemId(key);
Postea.LOG.debug("Item {} has no id in this world; its transformers stay inactive", key); if (id >= 0) {
continue; RUNTIME_ITEM_REPLACEMENT_MAP.put(id, Pair.of(key, ITEM_REPLACEMENT_MAP.get(key)));
}
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 *
/// world, as resolved through the world's saved id map and retired id table. * @implNote It doesn't matter if the id doesn't belong to an existing block, a dummy block will be created when
/// * Postea detects that the id isn't associated to a block during the FMLLoadCompleted event. Dependent
/// @param originalId the namespaced id of the block to transform * mods don't need to worry about this as the block name in the BlockConversionInfo is automatically
/// @param transformer the handler that transforms the block * updated to the original id when attempting to transform a dummy block. When Postea runs a
* transformation on a dummy block and no handler return true, Postea will automatically convert it to
* air.
*
* @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 Function<BlockConversionInfo, Boolean> 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 *
/// world, as resolved through the world's saved id map and retired id table. * @implNote It doesn't matter if the id doesn't belong to an existing item, a dummy item will be created when
/// * Postea detects that the id isn't associated to an item during the FMLLoadCompleted event. Dependent
/// @param originalId the namespaced id of the item to transform * mods don't need to worry about this as transformation handlers are given the original id associated
/// @param transformer the handler that transforms the stack * 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 addStackTransformer(@Nonnull String originalId, public static void addStackTransformer(@Nonnull String originalId,
@Nonnull IItemStackTransformationHandler transformer) { @Nonnull BiFunction<String, NBTTagCompound, Boolean> 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 /**
/// registration order until one returns a non-null [BlockInfo]. * Registers an item transformation handler function for the given id.
/// *
/// @param originalId the saved id of the tile entity to transform * @implNote It doesn't matter if the id doesn't belong to an existing item, a dummy item will be created when
/// @param transformer the handler that transforms the tile entity * Postea detects that the id isn't associated to an item during the FMLLoadCompleted event. Dependent
* mods don't need to worry about this as transformation handlers are given the original id associated
* with the nbt they are provided when the handler is executed. When Postea runs a transformation on a
* dummy item and no handler returns true, Postea will automatically invalidate the stack by removing
* its id and idExt fields.
*
* @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);
} }
// 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, byte metadata, World world, int x,
int y, int z) { int y, int z) {
List<Pair<String, List<IBlockTransformationHandler>>> candidates = RUNTIME_BLOCK_REPLACEMENT_MAP.get(blockId); Pair<String, List<Function<BlockConversionInfo, Boolean>>> data = RUNTIME_BLOCK_REPLACEMENT_MAP.get(blockId);
if (candidates == null) return null; if (data == null) return null;
for (Pair<String, List<IBlockTransformationHandler>> data : candidates) {
BlockConversionInfo info = new BlockConversionInfo(data.getKey(), blockId, metadata, x, y, z, world);
for (IBlockTransformationHandler transformer : data.getValue()) {
if (transformer.apply(info)) return info;
}
}
return null;
}
public static @Nullable BlockNameAndMeta transformBlock(@Nonnull String name, int metadata) {
List<IBlockTransformationHandler> handlers = BLOCK_REPLACEMENT_MAP.get(name);
if (handlers.isEmpty()) return null;
BlockConversionInfo blockConversionInfo = new BlockConversionInfo( BlockConversionInfo blockConversionInfo = new BlockConversionInfo(
name, // transparently maps the id to the original id if it's a dummy id
IDRegistry.getBlockId(name), data.getKey(),
blockId,
metadata, metadata,
0, x,
0, y,
0, z,
null); world);
for (IBlockTransformationHandler transformer : handlers) { for (Function<BlockConversionInfo, Boolean> transformer : data.getValue()) {
if (transformer.apply(blockConversionInfo)) { if (transformer.apply(blockConversionInfo)) {
Block block = GameData.getBlockRegistry() return blockConversionInfo;
.getRaw(blockConversionInfo.blockID);
if (block == null) return null;
return new BlockNameAndMeta(
GameData.getBlockRegistry()
.getNameForObject(block),
blockConversionInfo.metadata);
} }
} }
return null; return null;
@@ -165,12 +159,17 @@ 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;
List<Pair<String, List<IItemStackTransformationHandler>>> candidates = RUNTIME_ITEM_REPLACEMENT_MAP // get handler
.get(IDExtenderCompat.getItemStackID(tag)); int id = IDExtenderCompat.getItemStackID(tag);
if (candidates == null) return; Pair<String, List<BiFunction<String, NBTTagCompound, Boolean>>> data = RUNTIME_ITEM_REPLACEMENT_MAP.get(id);
for (Pair<String, List<IItemStackTransformationHandler>> data : candidates) { // abort early if handler not found
for (IItemStackTransformationHandler transformer : data.getValue()) { if (data != null && !data.getValue()
if (transformer.apply(data.getKey(), tag)) return; .isEmpty()) {
// apply handlers
for (BiFunction<String, NBTTagCompound, Boolean> transformer : data.getValue()) {
if (transformer.apply(data.getKey(), tag)) {
return;
}
} }
} }
} }
@@ -1,40 +0,0 @@
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);
}
}
@@ -1,81 +0,0 @@
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));
}
}
@@ -1,33 +0,0 @@
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();
}
}
@@ -1,130 +0,0 @@
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);
}
}
+1 -4
View File
@@ -8,11 +8,8 @@
"mixins": [ "mixins": [
"MixinAnvilChunkLoader", "MixinAnvilChunkLoader",
"MixinChunk", "MixinChunk",
"MixinEntityPlayer",
"MixinEntityPlayerMP",
"MixinItemStack", "MixinItemStack",
"MixinNBTTagList", "MixinNBTTagList"
"MixinSaveHandler"
], ],
"client": [], "client": [],
"server": [] "server": []
@@ -1,52 +0,0 @@
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);
}
}
@@ -1,37 +0,0 @@
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 transformChunk(ChunkTransformContext ctx) {}
@Override
public void transformPlayer(PlayerDataTransformContext ctx) {}
@Override
public void transformCustomData(CustomDataTransformContext ctx) {
customData.accept(ctx);
}
}
@@ -1,33 +0,0 @@
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"));
}
}
@@ -1,96 +0,0 @@
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)));
}
}
@@ -1,62 +0,0 @@
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]);
}
}
@@ -1,34 +0,0 @@
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());
}
}
@@ -1,116 +0,0 @@
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);
}
}
@@ -1,35 +0,0 @@
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"));
}
}
@@ -1,34 +0,0 @@
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"));
}
}
@@ -1,79 +0,0 @@
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()));
}
}