Compare commits

..
Author SHA1 Message Date
Guillaume Mercier 4916cc2fbf fix doc 2026-01-30 21:15:16 -05:00
Guillaume Mercier cf3d0c2df1 god i love typos 2026-01-30 20:18:37 -05:00
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
48 changed files with 186 additions and 1849 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:
+4 -93
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.
@@ -11,9 +11,6 @@ runtime. Allowing developers to replace, migrate or modify game elements based o
4. **Simple Replacement API**: Efficiently replace or remap large amounts of blocks and items at scale without incurring any noticeable performance impact. 4. **Simple Replacement API**: Efficiently replace or remap large amounts of blocks and items at scale without incurring any noticeable performance impact.
5. **Missing Mapping Replacement API**: A set of API endpoints to register actions to be taken when FML detects a missing mapping for a given ID. 5. **Missing Mapping Replacement API**: A set of API endpoints to register actions to be taken when FML detects a missing mapping for a given ID.
6. **Numeric ID Identification for Removed Content**: A way to identify the ID of any content that has ceased to exist. 6. **Numeric ID Identification for Removed Content**: A way to identify the ID of any content that has ceased to exist.
7. **Versioned Chunk and Player Transformers**: transform a chunk or a player's data exactly once per version of your content, however many sessions it was saved across.
8. **Retired Id Table**: names of removed content keep resolving in every later session.
9. **Custom World Data Transformers**: versioned transformation of a mod's own world storage, offered by the mod that owns it.
## Examples ## Examples
@@ -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]
> >
@@ -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'
} }
@@ -14,13 +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.IVersionedTransformer;
import com.gtnewhorizons.postea.api.ItemStackReplacementManager; import com.gtnewhorizons.postea.api.ItemStackReplacementManager;
import com.gtnewhorizons.postea.api.PlayerDataTransformContext;
import com.gtnewhorizons.postea.api.TileEntityReplacementManager; import com.gtnewhorizons.postea.api.TileEntityReplacementManager;
import com.gtnewhorizons.postea.api.VersionedReplacementManager;
import com.gtnewhorizons.postea.utility.BlockConversionInfo; import com.gtnewhorizons.postea.utility.BlockConversionInfo;
import com.gtnewhorizons.postea.utility.BlockInfo; import com.gtnewhorizons.postea.utility.BlockInfo;
@@ -36,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 {
@@ -352,47 +347,4 @@ abstract class ExampleMigrators {
BlockReplacementManager.ignoreMissingMapping("IC2:blockCrop"); BlockReplacementManager.ignoreMissingMapping("IC2:blockCrop");
} }
} }
public static final class VersionedExample implements IVersionedTransformer {
public static void postLoad() {
VersionedReplacementManager.register(new VersionedExample());
}
@Override
public String key() {
return "examplemod:gemIndex";
}
// The version the running mod writes gems under; bump it whenever the index assignment changes.
@Override
public int currentVersion() {
return 2;
}
@Override
public void transformChunk(ChunkTransformContext ctx) {
// Data saved before this transformer existed carries no stamp.
if (ctx.storedVersion() == ChunkTransformContext.UNSTAMPED || ctx.storedVersion() == 1) {
int gemBlockId = Block.getIdFromBlock(Blocks.wool);
ctx.forEachBlock((x, y, z, id, meta) -> { if (id == gemBlockId) ctx.setBlock(x, y, z, id, meta + 1); });
ctx.forEachItemStackTag(stack -> {
if (IDExtenderCompat.getItemStackID(stack) == Item.getIdFromItem(Items.dye)) {
stack.setShort("Damage", (short) (stack.getShort("Damage") + 1));
}
});
}
}
@Override
public void transformPlayer(PlayerDataTransformContext ctx) {
if (ctx.storedVersion() == PlayerDataTransformContext.UNSTAMPED || ctx.storedVersion() == 1) {
ctx.forEachItemStackTag(stack -> {
if (IDExtenderCompat.getItemStackID(stack) == Item.getIdFromItem(Items.dye)) {
stack.setShort("Damage", (short) (stack.getShort("Damage") + 1));
}
});
}
}
}
} }
@@ -1,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,22 +0,0 @@
package com.gtnewhorizons.postea.api;
/**
* A block referenced by its namespaced id, together with a meta value. Returned by
* {@link BlockReplacementManager#transformBlock(String, int)}.
*/
public final class BlockNameAndMeta {
/**
* The namespaced id of the block.
*/
public final String name;
/**
* The meta value of the block.
*/
public final int metadata;
public BlockNameAndMeta(String name, int metadata) {
this.name = name;
this.metadata = metadata;
}
}
@@ -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,32 +56,6 @@ public abstract class BlockReplacementManager {
// endregion custom transformer registration // endregion custom transformer registration
// region lookup
/**
* Runs the block transformers registered for the given id on a block that isn't placed in the world, and returns
* what it would be transformed into.<br>
* <br>
* This is meant for mods that store blocks by their namespaced id inside their own NBT (e.g.: blocks that are
* made out of other blocks), which Postea can't reach while converting chunks. Calling this when such a block is
* loaded applies every migration registered to Postea to it.
*
* @apiNote Only call this while a world is loaded, transformers rely on the numeric ids resolved for that world.
* The transformers are given a {@link com.gtnewhorizons.postea.utility.BlockConversionInfo} without a
* world, and with all coordinates set to 0. Tile entity transformers are not run.
*
* @param name The namespaced id of the block.
* @param metadata The meta value of the block.
* @return The namespaced id and meta value of the block to use instead, or null if no transformer applies.
*/
@SuppressWarnings("unused")
public static @Nullable BlockNameAndMeta transformBlock(@Nonnull String name, int metadata) {
if (name == null) throw new NullPointerException("name cannot be null");
return TransformerRegistry.transformBlock(name, metadata);
}
// endregion lookup
// region id resolving // region id resolving
// spotless:off // spotless:off
@@ -1,166 +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;
import com.gtnewhorizons.postea.utility.VersionStamps;
/**
* A chunk as handed to {@link IVersionedTransformer#transformChunk}: its block storage and the raw {@code Level}
* tag as read from disk, before tile entities and entities are parsed. Coordinates are chunk-local
* ({@code 0..15}, {@code y 0..255}); block ids and metadata are the world's numeric values at full EndlessIDs
* width. The world is not loaded yet: block access through {@link #world()} is not possible. When a transformer
* changed a block id, Postea recomputes the height map and flags the chunk for a relight once all transformers ran.
*/
public final class ChunkTransformContext {
public static final int UNSTAMPED = VersionStamps.UNSTAMPED;
private final Chunk chunk;
private final World world;
private final NBTTagCompound levelTag;
private final int storedVersion;
private final int currentVersion;
private final SubChunkAccess[] sections = new SubChunkAccess[16];
private boolean blockIdsChanged;
public ChunkTransformContext(Chunk chunk, World world, NBTTagCompound levelTag, int storedVersion,
int currentVersion) {
this.chunk = chunk;
this.world = world;
this.levelTag = levelTag;
this.storedVersion = storedVersion;
this.currentVersion = currentVersion;
}
public Chunk chunk() {
return chunk;
}
public World world() {
return world;
}
public int chunkX() {
return chunk.xPosition;
}
public int chunkZ() {
return chunk.zPosition;
}
/**
* The chunk's {@code Level} tag. Changes to its {@code TileEntities} and {@code Entities} lists are loaded by
* the game.
*/
public NBTTagCompound levelTag() {
return levelTag;
}
public NBTTagList tileEntityTags() {
return NbtLists.compoundList(levelTag, "TileEntities");
}
public NBTTagList entityTags() {
return NbtLists.compoundList(levelTag, "Entities");
}
/**
* The version this transformer's key was stamped with when the chunk was saved, or {@link #UNSTAMPED}.
*/
public int storedVersion() {
return storedVersion;
}
public int currentVersion() {
return currentVersion;
}
/**
* The block id at a chunk-local position; 0 for a missing section.
*/
public int getBlockId(int x, int y, int z) {
SubChunkAccess access = section(y >> 4, false);
return access == null ? 0 : access.getBlockId(x, y & 15, z);
}
public int getMetadata(int x, int y, int z) {
SubChunkAccess access = section(y >> 4, false);
return access == null ? 0 : access.getMeta(x, y & 15, z);
}
/**
* Sets the block at a chunk-local position, creating the section when a non-air block goes into a missing one.
*/
public void setBlock(int x, int y, int z, int blockId, int metadata) {
SubChunkAccess access = section(y >> 4, blockId != 0);
if (access == null) return;
if (access.getBlockId(x, y & 15, z) != blockId) blockIdsChanged = true;
access.setBlockId(x, y & 15, z, blockId);
access.setMeta(x, y & 15, z, metadata);
}
/**
* Visits every non-air block of every present section.
*/
public void forEachBlock(BlockVisitor visitor) {
ExtendedBlockStorage[] storage = chunk.getBlockStorageArray();
for (int index = 0; index < storage.length; index++) {
if (storage[index] == null) continue;
SubChunkAccess access = section(index, false);
int base = index << 4;
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
int id = access.getBlockId(x, y, z);
if (id != 0) visitor.visit(x, base + y, z, id, access.getMeta(x, y, z));
}
}
}
}
}
/**
* Visits every serialized item stack held by the chunk's tile entities and entities; see
* {@link NbtItemStacks#forEach}.
*/
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(tileEntityTags(), visitor);
NbtItemStacks.forEach(entityTags(), visitor);
}
/**
* Whether a block id (not only metadata) was rewritten.
*/
public boolean blockIdsChanged() {
return blockIdsChanged;
}
private SubChunkAccess section(int index, boolean create) {
if (index < 0 || index >= sections.length) return null;
if (sections[index] == null) {
ExtendedBlockStorage[] storage = chunk.getBlockStorageArray();
if (storage[index] == null) {
if (!create) return null;
storage[index] = new ExtendedBlockStorage(index << 4, !world.provider.hasNoSky);
}
sections[index] = Compat.getSubChunkAccess(storage[index]);
}
return sections[index];
}
@FunctionalInterface
public interface BlockVisitor {
void visit(int x, int y, int z, int blockId, int metadata);
}
}
@@ -1,64 +0,0 @@
package com.gtnewhorizons.postea.api;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ReportedException;
import com.gtnewhorizons.postea.Postea;
import com.gtnewhorizons.postea.utility.ChunkFixerUtility;
import com.gtnewhorizons.postea.utility.IDRegistry;
import com.gtnewhorizons.postea.utility.VersionStamps;
import com.gtnewhorizons.postea.utility.VersionedTransformerLog;
import cpw.mods.fml.common.FMLCommonHandler;
/**
* Manages applying an {@link IVersionedTransformer} to mods' custom storage files.
* <ul>
* <li>Call {@link #transform} once on the root read from disk, before consuming it, and persist that root (stamps
* included) when writing the storage back.</li>
* <li>A save path that rebuilds its NBT from scratch calls {@link #stamp} on the fresh root instead.</li>
* </ul>
*/
public abstract class CustomDataReplacementManager {
/**
* Transforms {@code root} in place through every registered transformer whose stamp differs from its current
* version, then writes the updated stamps onto {@code root}. Does nothing without a running server. Throws
* {@link IllegalStateException} when called before the world's saved id mappings were applied.
*/
public static void transform(String storageId, NBTTagCompound root) {
// Not the effective side: mods save their storage from worker threads, which 1.7.10 reports as client.
if (FMLCommonHandler.instance()
.getMinecraftServerInstance() == null) return;
if (!IDRegistry.isMappingApplied()) {
throw new IllegalStateException(
"Custom data " + storageId
+ " was offered for transformation before the world's id mappings were applied");
}
NBTTagCompound stamps = VersionStamps.read(root);
for (IVersionedTransformer transformer : VersionedReplacementManager.transformers()) {
int current = transformer.currentVersion();
int stored = VersionStamps.stored(stamps, transformer.key());
if (stored == current) continue;
VersionedTransformerLog.announce(transformer, stored, current);
Postea.LOG.debug("{}: custom data {} from version {} to {}", transformer.key(), storageId, stored, current);
try {
transformer.transformCustomData(new CustomDataTransformContext(storageId, root, stored, current));
} catch (Throwable t) {
throw new ReportedException(
ChunkFixerUtility.describe(t, transformer, stored, current, "Custom data", storageId));
}
}
VersionStamps.write(root, stamps, VersionedReplacementManager.transformers());
}
/**
* Stamps a freshly built root about to be written to disk with every registered transformer's current version.
* Does nothing without a running server.
*/
public static void stamp(NBTTagCompound root) {
if (FMLCommonHandler.instance()
.getMinecraftServerInstance() == null) return;
VersionStamps.write(root, VersionStamps.read(root), VersionedReplacementManager.transformers());
}
}
@@ -1,59 +0,0 @@
package com.gtnewhorizons.postea.api;
import java.util.function.Consumer;
import net.minecraft.nbt.NBTTagCompound;
import com.gtnewhorizons.postea.utility.NbtItemStacks;
import com.gtnewhorizons.postea.utility.VersionStamps;
/**
* Context for a mod's custom world storage, used by {@link IVersionedTransformer#transformCustomData}. Stacks here
* may have string {@code id}s instead of numeric ones; {@link #forEachItemStackTag} visits both.
*/
public final class CustomDataTransformContext {
public static final int UNSTAMPED = VersionStamps.UNSTAMPED;
private final String storageId;
private final NBTTagCompound root;
private final int storedVersion;
private final int currentVersion;
public CustomDataTransformContext(String storageId, NBTTagCompound root, int storedVersion, int currentVersion) {
this.storageId = storageId;
this.root = root;
this.storedVersion = storedVersion;
this.currentVersion = currentVersion;
}
/**
* The storage's identity as its owner registered it, e.g. {@code "betterquesting:questDatabase"}.
*/
public String storageId() {
return storageId;
}
public NBTTagCompound root() {
return root;
}
/**
* The version this transformer's key was stamped with when the storage was written, or {@link #UNSTAMPED}.
*/
public int storedVersion() {
return storedVersion;
}
public int currentVersion() {
return currentVersion;
}
/**
* Visits every serialized item stack in the storage, including stacks whose {@code id} is a string name; see
* {@link NbtItemStacks#forEach}.
*/
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(root, visitor, true);
}
}
@@ -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,49 +0,0 @@
package com.gtnewhorizons.postea.api;
/**
* A transformer that brings saved data written under an older version of its owner's content up to the current
* version. Postea stamps every chunk and every player it saves with {@link #currentVersion()} under {@link #key()}
* and, when reading, invokes the transformer only for data whose stamp differs, so each chunk and player is seen
* exactly once per version change no matter how many sessions passed in between. Data saved before the transformer
* existed reads as {@link ChunkTransformContext#UNSTAMPED}; the transformer decides what that means.
* <p>
* Register through {@link VersionedReplacementManager#register(IVersionedTransformer)} during mod loading, postInit
* at the latest. Transformers run in registration order and before every other Postea pass, so a transformer whose
* output depends on another mod's versioned data (for example one that writes that mod's indices) must register
* after that mod; FML's dependency ordering guarantees this when both register in the same lifecycle phase.
* <p>
* Chunk transformers may run on a chunk I/O thread, several concurrently for different chunks. They must not touch
* world state beyond the context and their own state must be safe to read concurrently.
* <p>
* Mods that keep item stacks in their own world storage offer it through {@link CustomDataReplacementManager};
* such storage is stamped the same way and reaches the transformer through {@link #transformCustomData}.
*/
public interface IVersionedTransformer {
/**
* The stamp key, unique across all registered transformers, e.g. {@code "examplemod:idList"}.
*/
String key();
/**
* The version the transformer's output is written under. Sampled at every read and every save.
*/
int currentVersion();
/**
* Brings a chunk stamped at {@link ChunkTransformContext#storedVersion()} to {@link #currentVersion()}.
*/
default void transformChunk(ChunkTransformContext ctx) {}
/**
* Brings a player's saved data stamped at {@link PlayerDataTransformContext#storedVersion()} to
* {@link #currentVersion()}.
*/
default void transformPlayer(PlayerDataTransformContext ctx) {}
/**
* Brings a mod's custom world storage stamped at {@link CustomDataTransformContext#storedVersion()} to
* {@link #currentVersion()}. Stacks in such storage may carry a string {@code id} instead of a numeric one.
*/
default void transformCustomData(CustomDataTransformContext ctx) {}
}
@@ -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,55 +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.gtnewhorizons.postea.utility.NbtItemStacks;
import com.gtnewhorizons.postea.utility.VersionStamps;
/**
* A player's saved data as handed to {@link IVersionedTransformer#transformPlayer}: the root tag about to be
* loaded into the player, which holds the inventory, ender chest, {@code ForgeData}, and every extended-properties
* compound. The player object is constructed but not yet loaded from the tag.
*/
public final class PlayerDataTransformContext {
public static final int UNSTAMPED = VersionStamps.UNSTAMPED;
private final EntityPlayerMP player;
private final NBTTagCompound playerTag;
private final int storedVersion;
private final int currentVersion;
public PlayerDataTransformContext(EntityPlayerMP player, NBTTagCompound playerTag, int storedVersion,
int currentVersion) {
this.player = player;
this.playerTag = playerTag;
this.storedVersion = storedVersion;
this.currentVersion = currentVersion;
}
public EntityPlayerMP player() {
return player;
}
public NBTTagCompound playerTag() {
return playerTag;
}
public int storedVersion() {
return storedVersion;
}
public int currentVersion() {
return currentVersion;
}
/**
* Visits every serialized item stack anywhere in the player's data; see {@link NbtItemStacks#forEach}.
*/
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(playerTag, visitor);
}
}
@@ -1,36 +0,0 @@
package com.gtnewhorizons.postea.api;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Registration of {@link IVersionedTransformer}s. See that interface for the execution contract.
*/
public abstract class VersionedReplacementManager {
private static final List<IVersionedTransformer> TRANSFORMERS = new CopyOnWriteArrayList<>();
/**
* Registers a transformer. Throws {@link IllegalArgumentException} when its key is empty or already registered.
*/
public static void register(IVersionedTransformer transformer) {
String key = Objects.requireNonNull(transformer.key(), "key must not be null");
if (key.isEmpty()) throw new IllegalArgumentException("Versioned transformer key must not be empty");
for (IVersionedTransformer existing : TRANSFORMERS) {
if (existing.key()
.equals(key)) {
throw new IllegalArgumentException("A versioned transformer is already registered for " + key);
}
}
TRANSFORMERS.add(transformer);
}
/**
* The registered transformers in registration order.
*/
public static List<IVersionedTransformer> transformers() {
return Collections.unmodifiableList(TRANSFORMERS);
}
}
@@ -14,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;
@@ -45,8 +45,6 @@ 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("MixinEntity");
mixins.add("MixinEntityPlayer");
mixins.add("MixinAnvilChunkLoader"); mixins.add("MixinAnvilChunkLoader");
mixins.add("MixinNBTTagList"); mixins.add("MixinNBTTagList");
return mixins; return mixins;
@@ -12,18 +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 {
// Forge-added funnel for sync and async loads; runs after relocation fix-ups and after ChunkAPI's own // This hook is compatible with Vanilla/NEID/EIDs
// readChunkFromNBT replacement, so covers vanilla, NEID, EndlessIDs, and ChunkAPI. @Inject(method = "readChunkFromNBT", at = @At("RETURN"), require = 1)
@Inject(method = "checkedReadChunkFromNBT__Async", at = @At("RETURN"), remap = false, require = 1) private void postea$chunkHook(CallbackInfoReturnable<Chunk> cir, @Local Chunk chunk,
private void postea$chunkHook(CallbackInfoReturnable<Object[]> cir) { @Local(argsOnly = true) World world, @Local(ordinal = 0, argsOnly = true) NBTTagCompound tag) {
Object[] data = cir.getReturnValue(); ChunkFixerUtility.onChunkRead(chunk, world, tag);
if (data == null) return;
Chunk chunk = (Chunk) data[0];
ChunkFixerUtility.onChunkRead(chunk, chunk.worldObj, ((NBTTagCompound) data[1]).getCompoundTag("Level"));
} }
@Inject(method = "loadChunk", at = @At("RETURN")) @Inject(method = "loadChunk", at = @At("RETURN"))
@@ -31,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; 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,46 +0,0 @@
package com.gtnewhorizons.postea.mixins.early;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.gtnewhorizons.postea.mixins.interfaces.IPlayerStampsMixin;
import com.gtnewhorizons.postea.utility.PlayerDataFixerUtility;
@Mixin(Entity.class)
public abstract class MixinEntity implements IPlayerStampsMixin {
// The stamps a server player's data was read with; carried across respawns by MixinEntityPlayer.
@Unique
private NBTTagCompound postea$versionStamps;
@Unique
public NBTTagCompound Postea$getVersionStamps() {
return postea$versionStamps;
}
@Unique
public void Postea$setVersionStamps(NBTTagCompound stamps) {
this.postea$versionStamps = stamps;
}
@Inject(method = "readFromNBT", at = @At("HEAD"), require = 1)
private void postea$transformPlayerData(NBTTagCompound tag, CallbackInfo ci) {
if ((Object) this instanceof EntityPlayerMP player) {
postea$versionStamps = PlayerDataFixerUtility.onPlayerRead(player, tag);
}
}
@Inject(method = "writeToNBT", at = @At("RETURN"), require = 1)
private void postea$stampPlayerData(NBTTagCompound tag, CallbackInfo ci) {
if ((Object) this instanceof EntityPlayerMP) {
PlayerDataFixerUtility.onPlayerWrite(tag, postea$versionStamps);
}
}
}
@@ -1,20 +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;
@Mixin(EntityPlayer.class)
public abstract class MixinEntityPlayer {
// A respawned player is a fresh entity built from the old one without going through NBT.
@Inject(method = "clonePlayer", at = @At("RETURN"), require = 1)
private void postea$carryVersionStamps(EntityPlayer oldPlayer, boolean respawn, CallbackInfo ci) {
((IPlayerStampsMixin) this).Postea$setVersionStamps(((IPlayerStampsMixin) oldPlayer).Postea$getVersionStamps());
}
}
@@ -1,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);
}
@@ -6,19 +6,13 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.ReportedException;
import net.minecraft.world.World; 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;
@@ -39,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);
@@ -66,86 +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, current);
VersionedTransformerLog.announce(transformer, stored, current);
try {
transformer.transformChunk(ctx);
} catch (Throwable t) {
throw new ReportedException(
describe(
t,
transformer,
stored,
current,
"Chunk",
chunk.xPosition + "," + chunk.zPosition + " in dimension " + world.provider.dimensionId));
}
chunkMixin.Postea$setVersionedDirty(true);
blockIdsChanged |= ctx.blockIdsChanged();
}
if (!blockIdsChanged) return;
// A section's block count is what decides whether it is saved at all, and writing through SubChunkAccess
// bypasses the bookkeeping ExtendedBlockStorage does in its own setters.
for (ExtendedBlockStorage section : chunk.getBlockStorageArray()) {
if (section != null) section.removeInvalidBlocks();
}
regenerateHeightMap(chunk);
chunk.isLightPopulated = false;
}
// Chunk.generateHeightMap is client-only and generateSkylightMap reaches into the world, so the height map is
// rebuilt here from the chunk's own storage, which is safe on the chunk I/O thread.
private static void regenerateHeightMap(Chunk chunk) {
int top = chunk.getTopFilledSegment() + 16 - 1;
chunk.heightMapMinimum = Integer.MAX_VALUE;
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
chunk.precipitationHeightMap[x + (z << 4)] = -999;
int y = top;
while (y > 0 && chunk.func_150808_b(x, y - 1, z) == 0) {
y--;
}
if (y > 0) {
chunk.heightMap[z << 4 | x] = y;
chunk.heightMapMinimum = Math.min(chunk.heightMapMinimum, y);
}
}
}
}
public static CrashReport describe(Throwable cause, IVersionedTransformer transformer, int stored, int current,
String subjectName, String subject) {
CrashReport report = CrashReport.makeCrashReport(cause, "Running versioned transformer " + transformer.key());
CrashReportCategory category = report.makeCategory("Postea versioned transformer");
category.addCrashSection("Key", transformer.key());
category.addCrashSection("Stored version", stored);
category.addCrashSection("Current version", current);
category.addCrashSection(subjectName, subject);
return report;
}
public static void onChunkLoaded(Chunk chunk) { 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);
} }
} }
@@ -169,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 +1,17 @@
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 or held in the active world: the live registry id, the id * A simple utility to resolve the IDs of any namepsaced ID that has ever been registered to an active world's id list.
* the world's own saved map assigns it, and the ids recorded in the world's {@link WorldIdTable} for content that
* has since been removed. A retired id counts only while FML still blocks it and no live content occupies it.
*/ */
public abstract class IDRegistry { public abstract class IDRegistry {
@@ -36,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;
/**
* Opens the retired id table of the world about to load. Until {@link #endWorld()} the saved id map is captured
* and its missing names merged into it.
*/
public static void beginWorld(File worldDirectory) {
tableFile = new File(new File(worldDirectory, Postea.MODID), WorldIdTable.FILE_NAME);
table = WorldIdTable.load(tableFile);
// A world without a level.dat has no saved id map: the live registries already are its mapping, and
// FML fires no remap event on its first session.
mappingApplied = !new File(worldDirectory, "level.dat").exists();
}
public static void endWorld() {
tableFile = null;
table = new WorldIdTable();
blockedIds = null;
mappingApplied = false;
BLOCK_NAME_TO_ID.clear();
ITEM_NAME_TO_ID.clear();
}
/**
* Whether FML has applied the loading world's saved id map in this session.
*/
public static boolean isMappingApplied() {
return mappingApplied;
}
/** /**
* Triggers all the callbacks registered by other mods that wish to identify a block that may no longer exist. * 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.
@@ -78,140 +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); int id = getItemId(kv.getKey());
} for (Consumer<Integer> resolver : kv.getValue()) {
} resolver.accept(id);
for (Map.Entry<String, Collection<Consumer<Integer>>> kv : ITEM_ID_RESOLVERS.asMap() }
.entrySet()) { });
int id = getItemId(kv.getKey()); ITEM_ID_RESOLVERS.asMap()
for (Consumer<Integer> resolver : kv.getValue()) { .entrySet()
resolver.accept(id); .parallelStream()
} .forEach(kv -> {
} int id = getItemId(kv.getKey());
for (Consumer<Integer> resolver : kv.getValue()) {
resolver.accept(id);
}
});
} }
/** /**
* Called by {@link com.gtnewhorizons.postea.mixins.preinit.MixinGameData}, this function captures the world's * Called by {@link com.gtnewhorizons.postea.mixins.preinit.MixinGameData}, this function is used to register all
* saved name-to-id map before FML remaps the live registries onto it, and records the names no registered * the previously registered namespaced to numeric id mappings that have ever been seen into a world.<br>
* content answers to in the world's retired id table. Ignored outside a server world and off the server thread, * <br>
* since the client side of the FML handshake also injects a map. * 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 {@code name} currently holds in this world: the live registry id, or the id it held before its * Fetches the block numeric ID associated with the namespaced ID.
* content was removed, or -1 when the world never mapped it. *
* @param name the namespaced id of the block.
* @return The ID of the block, or -1 if the namespaced ID has never been registered while the current world was
* loaded.
*/ */
public static int getBlockId(String name) { public static int getBlockId(String name) {
int id = liveBlockId(name);
if (id >= 0) return id;
IntList retired = retiredBlockIds(name, id);
return retired.isEmpty() ? -1 : retired.getInt(retired.size() - 1);
}
/**
* The item id {@code name} currently holds in this world: the live registry id, or the id it held before its
* content was removed, or -1 when the world never mapped it.
*/
public static int getItemId(String name) {
int id = liveItemId(name);
if (id >= 0) return id;
IntList retired = retiredItemIds(name, id);
return retired.isEmpty() ? -1 : retired.getInt(retired.size() - 1);
}
/**
* Every block id {@code name} holds or held in this world, live id first. Empty when the world never mapped
* the name.
*/
public static IntList getBlockIds(String name) {
int live = liveBlockId(name);
IntList ids = retiredBlockIds(name, live);
if (live >= 0) {
ids.add(0, live);
} else if (!ids.isEmpty()) {
Postea.LOG.info("Block {} is no longer registered; its transformers target retired id(s) {}", name, ids);
}
return ids;
}
/**
* Every item id {@code name} holds or held in this world, live id first. Empty when the world never mapped
* the name.
*/
public static IntList getItemIds(String name) {
int live = liveItemId(name);
IntList ids = retiredItemIds(name, live);
if (live >= 0) {
ids.add(0, live);
} else if (!ids.isEmpty()) {
Postea.LOG.info("Item {} is no longer registered; its transformers target retired id(s) {}", name, ids);
}
return ids;
}
private static IntList retiredBlockIds(String name, int live) {
IntList ids = new IntArrayList();
for (int id : table.blockIds(name)) {
if (id != live && blockedIds().contains(id)
&& GameData.getBlockRegistry()
.getRaw(id) == null) {
ids.add(id);
}
}
return ids;
}
private static IntList retiredItemIds(String name, int live) {
IntList ids = new IntArrayList();
for (int id : table.itemIds(name)) {
if (id != live && blockedIds().contains(id)
&& GameData.getItemRegistry()
.getRaw(id) == null) {
ids.add(id);
}
}
return ids;
}
private static IntSet blockedIds() {
IntSet ids = blockedIds;
if (ids == null) {
ids = new IntOpenHashSet(GameData.getBlockedIds());
blockedIds = ids;
}
return ids;
}
private static int liveBlockId(String name) {
int id = BLOCK_NAME_TO_ID.getOrDefault(name, -1); int id = BLOCK_NAME_TO_ID.getOrDefault(name, -1);
if (id < 0) { if (id < 0) {
id = GameData.getBlockRegistry() id = GameData.getBlockRegistry()
@@ -221,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 numeric {@code id} or an
* EndlessIDs {@code idExt} together with a {@code Count}; in string-id mode a string {@code id} (a registry name,
* as quest databases store) also qualifies. String-id mode must not be used on chunk or player trees, where tile
* entity compounds carry a string {@code id} of their own. The walk is pre-order and descends into every compound
* and every list of compounds, so stacks nested inside another stack's {@code tag} (backpacks, storage cells) are
* visited too. Lists of lists are not descended. A visitor may change or remove keys of the stack it is given; it
* must not touch other parts of the tree.
*/
public final class NbtItemStacks {
private NbtItemStacks() {}
public static void forEach(NBTBase root, Consumer<NBTTagCompound> visitor) {
forEach(root, visitor, false);
}
public static void forEach(NBTBase root, Consumer<NBTTagCompound> visitor, boolean stringIds) {
if (root instanceof NBTTagCompound compound) {
if (isStack(compound, stringIds)) visitor.accept(compound);
for (Object key : compound.func_150296_c()) {
forEach(compound.getTag((String) key), visitor, stringIds);
}
} else if (root instanceof NBTTagList list && list.func_150303_d() == TAG_COMPOUND) {
for (int i = 0; i < list.tagCount(); i++) {
forEach(list.getCompoundTagAt(i), visitor, stringIds);
}
}
}
public static boolean isStack(NBTTagCompound compound) {
return isStack(compound, false);
}
public static boolean isStack(NBTTagCompound compound, boolean stringIds) {
return compound.hasKey("Count", TAG_ANY_NUMERIC)
&& (compound.hasKey("id", TAG_SHORT) || compound.hasKey("id", TAG_INT)
|| compound.hasKey("idExt", TAG_INT)
|| (stringIds && compound.hasKey("id", TAG_STRING)));
}
}
@@ -1,21 +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 {@code key}, attached to {@code parent} first when absent so that tags
* appended to it are part of {@code parent}.
*/
public static NBTTagList compoundList(NBTTagCompound parent, String key) {
if (!parent.hasKey(key, TAG_LIST)) parent.setTag(key, new NBTTagList());
return parent.getTagList(key, TAG_COMPOUND);
}
}
@@ -1,49 +0,0 @@
package com.gtnewhorizons.postea.utility;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ReportedException;
import com.gtnewhorizons.postea.api.IVersionedTransformer;
import com.gtnewhorizons.postea.api.PlayerDataTransformContext;
import com.gtnewhorizons.postea.api.VersionedReplacementManager;
/**
* Runs versioned transformers over a server player's NBT as it is read, and stamps it as it is written. Hooked on
* {@code Entity.readFromNBT}/{@code writeToNBT} so both the {@code playerdata/<uuid>.dat} files and the
* single-player host's copy inside {@code level.dat} are covered.
*/
public final class PlayerDataFixerUtility {
private PlayerDataFixerUtility() {}
/**
* Transforms {@code tag} in place and returns a copy of the stamps it carried (null when unstamped).
*/
public static NBTTagCompound onPlayerRead(EntityPlayerMP player, NBTTagCompound tag) {
NBTTagCompound stamps = VersionStamps.read(tag);
for (IVersionedTransformer transformer : VersionedReplacementManager.transformers()) {
int current = transformer.currentVersion();
int stored = VersionStamps.stored(stamps, transformer.key());
if (stored == current) continue;
VersionedTransformerLog.announce(transformer, stored, current);
try {
transformer.transformPlayer(new PlayerDataTransformContext(player, tag, stored, current));
} catch (Throwable t) {
throw new ReportedException(
ChunkFixerUtility.describe(
t,
transformer,
stored,
current,
"Player",
player.getCommandSenderName() + " (" + player.getUniqueID() + ")"));
}
}
return stamps == null ? null : (NBTTagCompound) stamps.copy();
}
public static void onPlayerWrite(NBTTagCompound tag, NBTTagCompound carried) {
VersionStamps.write(tag, carried, VersionedReplacementManager.transformers());
}
}
@@ -49,13 +49,13 @@ class SimpleTransformationMap<T> {
* The target meta/damage value for the transformation. * 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,44 +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();
/** /**
* Map of itemID -> originalName+transformationHandler. * Map of itemID -> originalName+transformationHandler.
* Pivoting on the id is faster than pivoting on the strings so this should help with perf a bit. * 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. An id carries several names when * Generated during the mapping update event whilst entering/loading a world.
* content that once held it has been removed.
*/ */
private static final Int2ObjectOpenHashMap<List<Pair<String, List<IItemStackTransformationHandler>>>> RUNTIME_ITEM_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>(); private static final Int2ObjectOpenHashMap<Pair<String, List<BiFunction<String, NBTTagCompound, Boolean>>>> RUNTIME_ITEM_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
/** /**
* Map of blockID -> originalName+transformationHandler. * Map of blockIO -> originalName+transformationHandler.
* Pivoting on the id is faster than pivoting on the strings so this should help with perf a bit. * 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. An id carries several names when * Generated during the mapping update event whilst entering/loading a world.
* content that once held it has been removed.
*/ */
private static final Int2ObjectOpenHashMap<List<Pair<String, List<IBlockTransformationHandler>>>> RUNTIME_BLOCK_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>(); 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
/** /**
@@ -72,27 +64,17 @@ 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)));
} }
} }
// create a lookup for source item ids. // create a lookup for source block ids.
for (String key : ITEM_REPLACEMENT_MAP.keySet()) { for (String key : ITEM_REPLACEMENT_MAP.keys()) {
IntList ids = IDRegistry.getItemIds(key); int id = IDRegistry.getItemId(key);
if (ids.isEmpty()) { if (id >= 0) {
Postea.LOG.debug("Item {} has no id in this world; its transformers stay inactive", key); RUNTIME_ITEM_REPLACEMENT_MAP.put(id, Pair.of(key, ITEM_REPLACEMENT_MAP.get(key)));
continue;
}
for (int id : ids) {
RUNTIME_ITEM_REPLACEMENT_MAP.computeIfAbsent(id, unused -> new ArrayList<>())
.add(Pair.of(key, ITEM_REPLACEMENT_MAP.get(key)));
} }
} }
} }
@@ -101,39 +83,51 @@ public class TransformerRegistry {
/** /**
* Registers a block transformation handler function for the given id. * Registers a block transformation handler function for the given id.
* *
* @implNote The id may name content that no longer exists: Postea resolves it through the world's saved id map * @implNote It doesn't matter if the id doesn't belong to an existing block, a dummy block will be created when
* and its retired-id table, so the handler runs on every numeric id the content held in this world. * Postea detects that the id isn't associated to a block during the FMLLoadCompleted event. Dependent
* mods don't need to worry about this as the block name in the BlockConversionInfo is automatically
* updated to the original id when attempting to transform a dummy block. When Postea runs a
* transformation on a dummy block and no handler return true, Postea will automatically convert it to
* air.
* *
* @param originalId The namespaced id of the block to transform. * @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the block. * @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 function for the given id. * Registers an item transformation handler function for the given id.
* *
* @implNote The id may name content that no longer exists: Postea resolves it through the world's saved id map * @implNote It doesn't matter if the id doesn't belong to an existing item, a dummy item will be created when
* and its retired-id table, so the handler runs on every numeric id the content held in this world. * 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 item to transform. * @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the stack. * @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 function for the given id. * Registers an item transformation handler function for the given id.
* *
* @implNote Keyed by the tile entity's saved {@code id}; handlers run in registration order until one returns a * @implNote It doesn't matter if the id doesn't belong to an existing item, a dummy item will be created when
* non-null {@link BlockInfo}. * 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 saved id of the tile entity to transform. * @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the tile entity. * @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) {
@@ -141,40 +135,22 @@ public class TransformerRegistry {
} }
// region transformation handlers // region transformation handlers
public static @Nullable BlockConversionInfo getBlockReplacement(int blockId, int metadata, World world, int x, public static @Nullable BlockConversionInfo getBlockReplacement(int blockId, 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;
// there is no position nor world, the block isn't placed anywhere
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;
@@ -183,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,48 +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 {@code POSTEA_VERSIONS} compound Postea keeps on data handled by {@link IVersionedTransformer}s, one
* int per registered transformer key. Keys of transformers that are not registered in the running session are
* carried through unchanged so a mod that is temporarily absent does not lose its stamps.
*/
public final class VersionStamps {
public static final String KEY = "POSTEA_VERSIONS";
public static final int UNSTAMPED = -1;
private VersionStamps() {}
/**
* The stamps stored on {@code container}, or null when it carries none.
*/
public static NBTTagCompound read(NBTTagCompound container) {
return container.hasKey(KEY, TAG_COMPOUND) ? container.getCompoundTag(KEY) : null;
}
/**
* The version stored for {@code key} in {@code stamps} (which may be null), or {@link #UNSTAMPED}.
*/
public static int stored(NBTTagCompound stamps, String key) {
return stamps != null && stamps.hasKey(key, TAG_INT) ? stamps.getInteger(key) : UNSTAMPED;
}
/**
* Writes the stamps onto {@code container}: {@code carried} (the stamps the data was read with, or null) with
* every registered transformer's key set to its current version.
*/
public static void write(NBTTagCompound container, NBTTagCompound carried,
Iterable<IVersionedTransformer> transformers) {
NBTTagCompound stamps = carried == null ? new NBTTagCompound() : (NBTTagCompound) carried.copy();
for (IVersionedTransformer transformer : transformers) {
stamps.setInteger(transformer.key(), transformer.currentVersion());
}
container.setTag(KEY, stamps);
}
}
@@ -1,31 +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;
/**
* Announces each version span a transformer is bringing data across once per world, instead of once per chunk.
*/
public final class VersionedTransformerLog {
private static final Set<String> ANNOUNCED = ConcurrentHashMap.newKeySet();
private VersionedTransformerLog() {}
public static void announce(IVersionedTransformer transformer, int stored, int current) {
if (ANNOUNCED.add(transformer.key() + ' ' + stored + ' ' + current)) {
Postea.LOG.info(
"{} is bringing saved data from version {} to {}",
transformer.key(),
stored == VersionStamps.UNSTAMPED ? "unstamped" : String.valueOf(stored),
current);
}
}
public static void clear() {
ANNOUNCED.clear();
}
}
@@ -1,137 +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 {@code level.dat} on the first save after its content disappears;
* this table keeps the name so transformers keyed on it keep resolving in later sessions. Persisted as
* {@code <world>/postea/known-ids.json}, format version 1:
*
* <pre>
* { "version": 1, "blocks": { "mod:block": [300, 301] }, "items": { "mod:item": [4200] } }
* </pre>
*/
public final class WorldIdTable {
static final String FILE_NAME = "known-ids.json";
/** FML prefixes block names with this character in a saved id map; items get U+0002. */
static final char BLOCK_PREFIX = 1;
private static final int FORMAT_VERSION = 1;
private final Map<String, IntList> blocks = new TreeMap<>();
private final Map<String, IntList> items = new TreeMap<>();
/**
* Loads {@code file}; an absent file yields an empty table. Throws {@link IllegalStateException} on a file that
* cannot be read or parsed.
*/
public static WorldIdTable load(File file) {
WorldIdTable table = new WorldIdTable();
if (!file.exists()) return table;
try {
JsonObject root = new JsonParser()
.parse(new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8))
.getAsJsonObject();
if (root.get("version")
.getAsInt() != FORMAT_VERSION) {
throw new IllegalStateException(file + " has an unsupported format version");
}
read(root.getAsJsonObject("blocks"), table.blocks);
read(root.getAsJsonObject("items"), table.items);
} catch (IOException | RuntimeException e) {
throw new IllegalStateException("Cannot read the retired id table " + file, e);
}
return table;
}
private static void read(JsonObject object, Map<String, IntList> into) {
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
IntList ids = new IntArrayList();
for (JsonElement id : entry.getValue()
.getAsJsonArray()) {
ids.add(id.getAsInt());
}
into.put(entry.getKey(), ids);
}
}
/**
* Writes the table through a temporary file so a crash mid-write never truncates it.
*/
public void save(File file) {
JsonObject root = new JsonObject();
root.addProperty("version", FORMAT_VERSION);
root.add("blocks", write(blocks));
root.add("items", write(items));
File temp = new File(file.getPath() + ".tmp");
try {
Files.createDirectories(
file.toPath()
.getParent());
Files.write(
temp.toPath(),
new GsonBuilder().create()
.toJson(root)
.getBytes(StandardCharsets.UTF_8));
Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new IllegalStateException("Cannot write the retired id table " + file, e);
}
}
private static JsonObject write(Map<String, IntList> from) {
JsonObject object = new JsonObject();
for (Map.Entry<String, IntList> entry : from.entrySet()) {
JsonArray ids = new JsonArray();
for (int id : entry.getValue()) {
ids.add(new JsonPrimitive(id));
}
object.add(entry.getKey(), ids);
}
return object;
}
/**
* Records entries of a world's saved name-to-id map, whose names FML prefixes with U+0001 for a block and
* U+0002 for an item. Returns whether any pair was new.
*/
public boolean merge(Map<String, Integer> dataList) {
boolean changed = false;
for (Map.Entry<String, Integer> entry : dataList.entrySet()) {
String prefixed = entry.getKey();
Map<String, IntList> into = prefixed.charAt(0) == BLOCK_PREFIX ? blocks : items;
IntList ids = into.computeIfAbsent(prefixed.substring(1), name -> new IntArrayList());
if (!ids.contains((int) entry.getValue())) {
ids.add((int) entry.getValue());
changed = true;
}
}
return changed;
}
public IntList blockIds(String name) {
return blocks.getOrDefault(name, IntLists.EMPTY_LIST);
}
public IntList itemIds(String name) {
return items.getOrDefault(name, IntLists.EMPTY_LIST);
}
}
@@ -8,8 +8,6 @@
"mixins": [ "mixins": [
"MixinAnvilChunkLoader", "MixinAnvilChunkLoader",
"MixinChunk", "MixinChunk",
"MixinEntity",
"MixinEntityPlayer",
"MixinItemStack", "MixinItemStack",
"MixinNBTTagList" "MixinNBTTagList"
], ],
@@ -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));
}
// Pins the split that keeps chunk and player walks safe: a string id with a Count is a stack only in
// string-id mode, which custom data uses and tile entity trees never do.
@Test
void stringIdStacksAreVisitedOnlyInStringIdMode() {
NBTTagCompound quest = new NBTTagCompound();
quest.setString("id", "examplemod:gem");
quest.setInteger("Count", 3);
quest.setShort("Damage", (short) 7);
NBTTagCompound root = new NBTTagCompound();
root.setTag("requiredItems", quest);
List<NBTTagCompound> wide = new ArrayList<>();
NbtItemStacks.forEach(root, wide::add, true);
assertEquals(Collections.emptyList(), visited(root));
assertEquals(Collections.singletonList(quest), wide);
}
@Test
void aVisitorMayInvalidateTheStackItIsGiven() {
NBTTagCompound first = stack(5, 1);
NBTTagCompound second = stack(5, 2);
NBTTagList items = new NBTTagList();
items.appendTag(first);
items.appendTag(second);
NBTTagCompound root = new NBTTagCompound();
root.setTag("Items", items);
List<NBTTagCompound> seen = new ArrayList<>();
NbtItemStacks.forEach(root, tag -> {
seen.add(tag);
tag.removeTag("id");
});
assertEquals(Arrays.asList(first, second), seen);
}
}
@@ -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,63 +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;
class VersionStampsTest {
private static IVersionedTransformer transformer(String key, int version) {
return new IVersionedTransformer() {
@Override
public String key() {
return key;
}
@Override
public int currentVersion() {
return version;
}
};
}
@Test
void anUnstampedContainerReadsAsUnstamped() {
NBTTagCompound container = new NBTTagCompound();
assertNull(VersionStamps.read(container));
assertEquals(VersionStamps.UNSTAMPED, VersionStamps.stored(null, "mod:key"));
}
@Test
void writeStampsRegisteredKeysAtTheirCurrentVersionAndCarriesUnknownKeys() {
NBTTagCompound carried = new NBTTagCompound();
carried.setInteger("absentmod:key", 7);
carried.setInteger("mod:key", 2);
NBTTagCompound container = new NBTTagCompound();
VersionStamps.write(container, carried, Collections.singletonList(transformer("mod:key", 3)));
NBTTagCompound stamps = VersionStamps.read(container);
assertEquals(3, VersionStamps.stored(stamps, "mod:key"));
assertEquals(7, VersionStamps.stored(stamps, "absentmod:key"));
assertEquals(2, carried.getInteger("mod:key"));
}
@Test
void writeWithoutCarriedStampsWritesOnlyRegisteredKeys() {
NBTTagCompound container = new NBTTagCompound();
VersionStamps.write(container, null, Collections.singletonList(transformer("mod:key", 1)));
assertEquals(1, VersionStamps.stored(VersionStamps.read(container), "mod:key"));
assertEquals(VersionStamps.UNSTAMPED, VersionStamps.stored(VersionStamps.read(container), "other:key"));
}
}
@@ -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()));
}
}