Documentation cleanup

This commit is contained in:
Ruling-0 committed 2026-11-25 14:45:57 -06:00
1 parent dd4bd60c3e
commit 05a424db34
23 files changed
+169 -291

No files matched your search

@@ -364,7 +364,6 @@ abstract class ExampleMigrators {
return "examplemod:gemIndex";
}
// The version the running mod writes gems under; bump it whenever the index assignment changes.
@Override
public int currentVersion() {
return 2;
@@ -372,7 +371,6 @@ abstract class ExampleMigrators {
@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); });
@@ -1,18 +1,11 @@
package com.gtnewhorizons.postea.api;
/**
* A block referenced by its namespaced id, together with a meta value. Returned by
* {@link BlockReplacementManager#transformBlock(String, int)}.
*/
/// A block's namespaced id and meta value, as returned by [BlockReplacementManager#transformBlock(String, int)].
public final class BlockNameAndMeta {
/**
* The namespaced id of the block.
*/
/// The namespaced id of the block.
public final String name;
/**
* The meta value of the block.
*/
/// The meta value of the block.
public final int metadata;
public BlockNameAndMeta(String name, int metadata) {
@@ -57,22 +57,17 @@ public abstract class BlockReplacementManager {
// 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.
*/
/// Runs the block transformers registered for `name` on a block that is not placed in the world, and returns what
/// it would be transformed into.
///
/// For mods that store blocks by namespaced id in their own NBT, which Postea cannot reach while converting
/// chunks. Call only while a world is loaded. Transformers
/// get a [com.gtnewhorizons.postea.utility.BlockConversionInfo] without a world and with all coordinates 0. Tile
/// entity transformers are not run.
///
/// @param name the namespaced id of the block
/// @param metadata the meta value of the block
/// @return the replacement block, or null if no transformer applies
@SuppressWarnings("unused")
public static @Nullable BlockNameAndMeta transformBlock(@Nonnull String name, int metadata) {
if (name == null) throw new NullPointerException("name cannot be null");
@@ -14,13 +14,12 @@ 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.
*/
/// A chunk's block storage and raw `Level` tag, as handed to [IVersionedTransformer#transformChunk].
///
/// The tag is as read from disk, before tile entities and entities are parsed. Coordinates are chunk-local (`0..15`,
/// `y 0..255`), and block ids and metadata are the world's numeric values at full EndlessIDs width. The world is not
/// loaded, so block access through [#world()] is not possible. When a transformer changes a block id, Postea
/// recomputes the height map and flags the chunk for a relight after all transformers ran.
public final class ChunkTransformContext {
public static final int UNSTAMPED = VersionStamps.UNSTAMPED;
@@ -58,10 +57,7 @@ public final class ChunkTransformContext {
return chunk.zPosition;
}
/**
* The chunk's {@code Level} tag. Changes to its {@code TileEntities} and {@code Entities} lists are loaded by
* the game.
*/
/// The chunk's `Level` tag. Changes to its `TileEntities` and `Entities` lists are loaded by the game.
public NBTTagCompound levelTag() {
return levelTag;
}
@@ -74,9 +70,7 @@ public final class ChunkTransformContext {
return NbtLists.compoundList(levelTag, "Entities");
}
/**
* The version this transformer's key was stamped with when the chunk was saved, or {@link #UNSTAMPED}.
*/
/// The version stamped under the transformer's key when the chunk was saved, or [#UNSTAMPED].
public int storedVersion() {
return storedVersion;
}
@@ -85,9 +79,7 @@ public final class ChunkTransformContext {
return currentVersion;
}
/**
* The block id at a chunk-local position; 0 for a missing section.
*/
/// The block id at a chunk-local position, or 0 for a missing section.
public int getBlockId(int x, int y, int z) {
SubChunkAccess access = section(y >> 4, false);
return access == null ? 0 : access.getBlockId(x, y & 15, z);
@@ -98,9 +90,7 @@ public final class ChunkTransformContext {
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.
*/
/// 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;
@@ -109,9 +99,7 @@ public final class ChunkTransformContext {
access.setMeta(x, y & 15, z, metadata);
}
/**
* Visits every non-air block of every present section.
*/
/// 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++) {
@@ -129,18 +117,14 @@ public final class ChunkTransformContext {
}
}
/**
* Visits every serialized item stack held by the chunk's tile entities and entities; see
* {@link NbtItemStacks#forEach}.
*/
/// Visits every serialized item stack held by the chunk's tile entities and entities. See
/// [NbtItemStacks#forEach].
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(tileEntityTags(), visitor);
NbtItemStacks.forEach(entityTags(), visitor);
}
/**
* Whether a block id (not only metadata) was rewritten.
*/
/// Whether a block id, not only metadata, was rewritten.
public boolean blockIdsChanged() {
return blockIdsChanged;
}
@@ -11,23 +11,21 @@ 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>
*/
/// Applies [IVersionedTransformer]s to a mod's custom storage files.
///
/// Call [#transform] once on the root read from disk, before consuming it, and persist that root, stamps included,
/// when writing the storage back. A save path that rebuilds its NBT from scratch calls [#stamp] on the fresh root
/// instead.
///
/// Custom data belongs to a world, so both methods do nothing unless a server runs in this JVM.
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.
*/
/// Transforms `root` in place through every registered transformer whose stamp differs from its current
/// version, then writes the updated stamps onto `root`. Throws [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.
// Custom data is only transformed while a server runs. Not getEffectiveSide(): mods save from worker
// threads, which 1.7.10 reports as client.
if (FMLCommonHandler.instance()
.getMinecraftServerInstance() == null) return;
if (!IDRegistry.isMappingApplied()) {
@@ -52,10 +50,7 @@ public abstract class CustomDataReplacementManager {
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.
*/
/// Stamps a freshly built root with every registered transformer's current version.
public static void stamp(NBTTagCompound root) {
if (FMLCommonHandler.instance()
.getMinecraftServerInstance() == null) return;
@@ -7,10 +7,8 @@ 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.
*/
/// A mod's custom world storage, as handed to [IVersionedTransformer#transformCustomData]. Stacks here may have
/// string `id`s instead of numeric ones, and [#forEachItemStackTag] visits both.
public final class CustomDataTransformContext {
public static final int UNSTAMPED = VersionStamps.UNSTAMPED;
@@ -27,9 +25,7 @@ public final class CustomDataTransformContext {
this.currentVersion = currentVersion;
}
/**
* The storage's identity as its owner registered it, e.g. {@code "betterquesting:questDatabase"}.
*/
/// The storage's identity as its owner registered it, e.g. `"betterquesting:questDatabase"`.
public String storageId() {
return storageId;
}
@@ -38,9 +34,7 @@ public final class CustomDataTransformContext {
return root;
}
/**
* The version this transformer's key was stamped with when the storage was written, or {@link #UNSTAMPED}.
*/
/// The version stamped under the transformer's key when the storage was written, or [#UNSTAMPED].
public int storedVersion() {
return storedVersion;
}
@@ -49,10 +43,8 @@ public final class CustomDataTransformContext {
return currentVersion;
}
/**
* Visits every serialized item stack in the storage, including stacks whose {@code id} is a string name; see
* {@link NbtItemStacks#forEach}.
*/
/// Visits every serialized item stack in the storage, including stacks whose `id` is a string name. See
/// [NbtItemStacks#forEach].
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(root, visitor, true);
}
@@ -1,49 +1,38 @@
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}.
*/
/// Upgrades saved chunks, players and custom world storage written under another version of a mod's content.
///
/// Postea stamps everything it saves with [#currentVersion()] under [#key()]. On read, the transformer runs for
/// every stored stamp that differs from [#currentVersion()], older or newer. The transformer decides what a newer
/// version means and throws if it cannot handle it. Data saved before the transformer existed reads as
/// [ChunkTransformContext#UNSTAMPED].
///
/// Register with [VersionedReplacementManager#register(IVersionedTransformer)] by postInit. Transformers run in
/// registration order, before every other Postea pass. One whose output depends on another mod's versioned data
/// must register after that mod.
///
/// Chunk transformers may run on chunk I/O threads, several at once for different chunks. They must touch no world
/// state beyond the context, and their own state must be safe to read concurrently.
///
/// Custom world storage offered through [CustomDataReplacementManager] is stamped the same way and reaches
/// [#transformCustomData].
public interface IVersionedTransformer {
/**
* The stamp key, unique across all registered transformers, e.g. {@code "examplemod:idList"}.
*/
/// The stamp key, unique across all registered transformers, e.g. `"examplemod:idList"`. Must return the same
/// value for the transformer's lifetime.
String key();
/**
* The version the transformer's output is written under. Sampled at every read and every save.
*/
/// The version the transformer's output is written under. Read on every load and save, and may differ between
/// reads.
int currentVersion();
/**
* Brings a chunk stamped at {@link ChunkTransformContext#storedVersion()} to {@link #currentVersion()}.
*/
/// Brings a chunk stamped at [ChunkTransformContext#storedVersion()] to [#currentVersion()].
default void transformChunk(ChunkTransformContext ctx) {}
/**
* Brings a player's saved data stamped at {@link PlayerDataTransformContext#storedVersion()} to
* {@link #currentVersion()}.
*/
/// Brings a player's saved data stamped at [PlayerDataTransformContext#storedVersion()] to [#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.
*/
/// Brings custom world storage stamped at [CustomDataTransformContext#storedVersion()] to [#currentVersion()].
/// Stacks in such storage may carry a string `id` instead of a numeric one.
default void transformCustomData(CustomDataTransformContext ctx) {}
}
@@ -8,11 +8,10 @@ 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.
*/
/// A player's saved data, as handed to [IVersionedTransformer#transformPlayer].
///
/// The root tag holds the inventory, ender chest, `ForgeData` and every extended-properties compound. The player
/// object is constructed but not yet loaded from the tag.
public final class PlayerDataTransformContext {
public static final int UNSTAMPED = VersionStamps.UNSTAMPED;
@@ -46,9 +45,7 @@ public final class PlayerDataTransformContext {
return currentVersion;
}
/**
* Visits every serialized item stack anywhere in the player's data; see {@link NbtItemStacks#forEach}.
*/
/// Visits every serialized item stack anywhere in the player's data. See [NbtItemStacks#forEach].
public void forEachItemStackTag(Consumer<NBTTagCompound> visitor) {
NbtItemStacks.forEach(playerTag, visitor);
}
@@ -5,16 +5,12 @@ 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.
*/
/// Registry of [IVersionedTransformer]s. See that interface for the execution contract.
public abstract class VersionedReplacementManager {
private static final List<IVersionedTransformer> TRANSFORMERS = new CopyOnWriteArrayList<>();
/**
* Registers a transformer. Throws {@link IllegalArgumentException} when its key is empty or already registered.
*/
/// Registers a transformer. Throws [IllegalArgumentException] when its key is empty or already registered.
public static void register(IVersionedTransformer transformer) {
String key = Objects.requireNonNull(transformer.key(), "key must not be null");
if (key.isEmpty()) throw new IllegalArgumentException("Versioned transformer key must not be empty");
@@ -27,9 +23,7 @@ public abstract class VersionedReplacementManager {
TRANSFORMERS.add(transformer);
}
/**
* The registered transformers in registration order.
*/
/// The registered transformers in registration order, as an unmodifiable view.
public static List<IVersionedTransformer> transformers() {
return Collections.unmodifiableList(TRANSFORMERS);
}
@@ -16,8 +16,7 @@ import com.gtnewhorizons.postea.utility.ChunkFixerUtility;
@Mixin(value = AnvilChunkLoader.class, priority = 1100)
public abstract class MixinAnvilChunkLoader {
// Forge-added funnel for sync and async loads; runs after relocation fix-ups and after ChunkAPI's own
// readChunkFromNBT replacement, so covers vanilla, NEID, EndlessIDs, and ChunkAPI.
/// Hooks the funnel shared by sync and async loads, which runs after ChunkAPI's `readChunkFromNBT` replacement.
@Inject(method = "checkedReadChunkFromNBT__Async", at = @At("RETURN"), remap = false, require = 1)
private void postea$chunkHook(CallbackInfoReturnable<Object[]> cir) {
Object[] data = cir.getReturnValue();
@@ -16,7 +16,7 @@ public class MixinChunk implements IChunkMixin {
@Unique
private long postea_GTNH$posteaID;
// The stamps the chunk was read with; null for a chunk generated this session.
/// The stamps the chunk was read with, or null for a chunk generated this session.
@Unique
private NBTTagCompound postea$versionStamps;
@@ -16,7 +16,7 @@ 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.
/// The stamps a server player's data was read with. [MixinEntityPlayer] carries them across respawns.
@Unique
private NBTTagCompound postea$versionStamps;
@@ -12,7 +12,7 @@ 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.
/// Copies the version stamps from the old player, because a respawned player is not built 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());
@@ -93,8 +93,8 @@ public class ChunkFixerUtility {
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.
// SubChunkAccess writes bypass the block counts that ExtendedBlockStorage's setters maintain and that decide
// whether a section is saved.
for (ExtendedBlockStorage section : chunk.getBlockStorageArray()) {
if (section != null) section.removeInvalidBlocks();
}
@@ -102,8 +102,8 @@ public class ChunkFixerUtility {
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.
/// Rebuilds the height map from the chunk's own storage, which is safe on the chunk I/O thread.
/// `Chunk.generateHeightMap` is client-only and `generateSkylightMap` reaches into the world.
private static void regenerateHeightMap(Chunk chunk) {
int top = chunk.getTopFilledSegment() + 16 - 1;
chunk.heightMapMinimum = Integer.MAX_VALUE;
@@ -20,11 +20,10 @@ import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
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
* 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.
*/
/// Resolves a namespaced id to the numeric ids it holds in the active world, or held before its content was removed.
///
/// Ids come from the live registry, the world's saved id map and the world's [WorldIdTable]. A retired id counts
/// only while FML still blocks it and no live content occupies it.
public abstract class IDRegistry {
// Part of a bi-map for lookups between block namespaced ids and numeric ids
@@ -41,15 +40,12 @@ public abstract class IDRegistry {
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.
*/
/// Loads the retired id table of the world about to load. [#registerWorldSpecificIDs] records into it until
/// [#endWorld()].
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.
// No level.dat means no saved id map, and FML fires no remap event.
mappingApplied = !new File(worldDirectory, "level.dat").exists();
}
@@ -62,9 +58,7 @@ public abstract class IDRegistry {
ITEM_NAME_TO_ID.clear();
}
/**
* Whether FML has applied the loading world's saved id map in this session.
*/
/// Whether FML has applied the loading world's saved id map.
public static boolean isMappingApplied() {
return mappingApplied;
}
@@ -95,12 +89,9 @@ public abstract class IDRegistry {
}
}
/**
* Called by {@link com.gtnewhorizons.postea.mixins.preinit.MixinGameData}, this function captures the world's
* saved name-to-id map before FML remaps the live registries onto it, and records the names no registered
* content answers to in the world's retired id table. Ignored outside a server world and off the server thread,
* since the client side of the FML handshake also injects a map.
*/
/// Captures the world's saved name-to-id map before FML remaps the live registries onto it, and records the names
/// no registered content answers to in the world's retired id table. Ignored outside a server world and off the
/// server thread.
public static void registerWorldSpecificIDs(Map<String, Integer> map) {
if (tableFile == null || !FMLCommonHandler.instance()
.getEffectiveSide()
@@ -126,10 +117,8 @@ public abstract class IDRegistry {
if (table.merge(missing)) table.save(tableFile);
}
/**
* The block id {@code name} currently holds in this world: the live registry id, or the id it held before its
* content was removed, or -1 when the world never mapped it.
*/
/// The block id `name` holds in this world: the live registry id, else the id it held before its content was
/// removed, or -1 if the world never mapped it.
public static int getBlockId(String name) {
int id = liveBlockId(name);
if (id >= 0) return id;
@@ -137,10 +126,8 @@ public abstract class IDRegistry {
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.
*/
/// The item id `name` holds in this world: the live registry id, else the id it held before its content was
/// removed, or -1 if the world never mapped it.
public static int getItemId(String name) {
int id = liveItemId(name);
if (id >= 0) return id;
@@ -148,10 +135,7 @@ public abstract class IDRegistry {
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.
*/
/// Every block id `name` holds or held in this world, live id first. Empty if the world never mapped the name.
public static IntList getBlockIds(String name) {
int live = liveBlockId(name);
IntList ids = retiredBlockIds(name, live);
@@ -163,10 +147,7 @@ public abstract class IDRegistry {
return ids;
}
/**
* Every item id {@code name} holds or held in this world, live id first. Empty when the world never mapped
* the name.
*/
/// Every item id `name` holds or held in this world, live id first. Empty if the world never mapped the name.
public static IntList getItemIds(String name) {
int live = liveItemId(name);
IntList ids = retiredItemIds(name, live);
@@ -12,15 +12,15 @@ 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.
*/
/// Visits every serialized item stack in an NBT tree.
///
/// A compound is a stack when it has a `Count` and a numeric `id` or an EndlessIDs `idExt`. In string-id mode, a
/// string `id` such as a registry name also qualifies. String-id mode must not be used on chunk or player trees,
/// where tile entity compounds carry a string `id` of their own.
///
/// The walk is pre-order and descends into every compound and every list of compounds, including a stack's own
/// `tag`. Lists of lists are not descended. A visitor may change or remove keys of the stack it is given, and must
/// not touch other parts of the tree.
public final class NbtItemStacks {
private NbtItemStacks() {}
@@ -10,10 +10,8 @@ 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}.
*/
/// The list of compounds stored under `key`. Adds an empty list to `parent` unless a list is already stored under
/// `key`, so appending to the result changes `parent`.
public static NBTTagList compoundList(NBTTagCompound parent, String key) {
if (!parent.hasKey(key, TAG_LIST)) parent.setTag(key, new NBTTagList());
return parent.getTagList(key, TAG_COMPOUND);
@@ -8,18 +8,15 @@ 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.
*/
/// Runs versioned transformers over a server player's NBT as it is read, and stamps it as it is written.
///
/// Hooks `Entity.readFromNBT` and `writeToNBT`, which covers `playerdata/<uuid>.dat` and the single-player host's
/// copy inside `level.dat`.
public final class PlayerDataFixerUtility {
private PlayerDataFixerUtility() {}
/**
* Transforms {@code tag} in place and returns a copy of the stamps it carried (null when unstamped).
*/
/// Transforms `tag` in place and returns a copy of the stamps it carried, or null if unstamped.
public static NBTTagCompound onPlayerRead(EntityPlayerMP player, NBTTagCompound tag) {
NBTTagCompound stamps = VersionStamps.read(tag);
for (IVersionedTransformer transformer : VersionedReplacementManager.transformers()) {
@@ -39,19 +39,11 @@ public class TransformerRegistry {
.create();
private static final LinkedListMultimap<String, TriFunction<NBTTagCompound, World, Chunk, BlockInfo>> TILE_ENTITY_REPLACEMENT_MAP = LinkedListMultimap
.create();
/**
* Map of itemID -> originalName+transformationHandler.
* Pivoting on the id is faster than pivoting on the strings so this should help with perf a bit.
* Generated during the mapping update event whilst entering/loading a world. An id carries several names when
* content that once held it has been removed.
*/
/// Maps an item id to the names that hold it and their handlers. Generated during the mapping update event when a
/// world loads. An id carries several names when content that once held it was removed.
private static final Int2ObjectOpenHashMap<List<Pair<String, List<IItemStackTransformationHandler>>>> RUNTIME_ITEM_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
/**
* Map of blockID -> originalName+transformationHandler.
* Pivoting on the id is faster than pivoting on the strings so this should help with perf a bit.
* Generated during the mapping update event whilst entering/loading a world. An id carries several names when
* content that once held it has been removed.
*/
/// Maps a block id to the names that hold it and their handlers. Generated during the mapping update event when a
/// world loads. An id carries several names when content that once held it was removed.
private static final Int2ObjectOpenHashMap<List<Pair<String, List<IBlockTransformationHandler>>>> RUNTIME_BLOCK_REPLACEMENT_MAP = new Int2ObjectOpenHashMap<>();
// region FML Life Cycle handlers
@@ -83,7 +75,6 @@ public class TransformerRegistry {
.add(Pair.of(key, BLOCK_REPLACEMENT_MAP.get(key)));
}
}
// create a lookup for source item ids.
for (String key : ITEM_REPLACEMENT_MAP.keySet()) {
IntList ids = IDRegistry.getItemIds(key);
if (ids.isEmpty()) {
@@ -98,43 +89,35 @@ public class TransformerRegistry {
}
// endregion FML Life Cycle handlers
/**
* 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
* and its retired-id table, so the handler runs on every numeric id the content held in this world.
*
* @param originalId The namespaced id of the block to transform.
* @param transformer The transformation handler that will execute a transformation on the block.
*/
/// Registers a block transformation handler for the given namespaced id.
///
/// The id may name content that no longer exists. The handler runs on every numeric id the content held in this
/// world, as resolved through the world's saved id map and retired id table.
///
/// @param originalId the namespaced id of the block to transform
/// @param transformer the handler that transforms the block
public static void addBlockTransformer(@Nonnull String originalId,
@Nonnull IBlockTransformationHandler transformer) {
BLOCK_REPLACEMENT_MAP.put(originalId, transformer);
}
/**
* 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
* and its retired-id table, so the handler runs on every numeric id the content held in this world.
*
* @param originalId The namespaced id of the item to transform.
* @param transformer The transformation handler that will execute a transformation on the stack.
*/
/// Registers an item transformation handler for the given namespaced id.
///
/// The id may name content that no longer exists. The handler runs on every numeric id the content held in this
/// world, as resolved through the world's saved id map and retired id table.
///
/// @param originalId the namespaced id of the item to transform
/// @param transformer the handler that transforms the stack
public static void addStackTransformer(@Nonnull String originalId,
@Nonnull IItemStackTransformationHandler transformer) {
ITEM_REPLACEMENT_MAP.put(originalId, transformer);
}
/**
* Registers a tile entity 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
* non-null {@link BlockInfo}.
*
* @param originalId The saved id of the tile entity to transform.
* @param transformer The transformation handler that will execute a transformation on the tile entity.
*/
/// Registers a tile entity transformation handler for the given saved tile entity id. Handlers run in
/// registration order until one returns a non-null [BlockInfo].
///
/// @param originalId the saved id of the tile entity to transform
/// @param transformer the handler that transforms the tile entity
public static void addTileEntityTransformer(@Nonnull String originalId,
@Nonnull TriFunction<NBTTagCompound, World, Chunk, BlockInfo> transformer) {
TILE_ENTITY_REPLACEMENT_MAP.put(originalId, transformer);
@@ -157,7 +140,6 @@ public class TransformerRegistry {
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(
name,
IDRegistry.getBlockId(name),
@@ -7,11 +7,10 @@ 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.
*/
/// The `POSTEA_VERSIONS` compound Postea keeps on data handled by [IVersionedTransformer]s, with one int per
/// transformer key.
///
/// Keys of transformers not registered in the running session are carried through unchanged.
public final class VersionStamps {
public static final String KEY = "POSTEA_VERSIONS";
@@ -19,24 +18,18 @@ public final class VersionStamps {
private VersionStamps() {}
/**
* The stamps stored on {@code container}, or null when it carries none.
*/
/// The stamps stored on `container`, or null if it carries none.
public static NBTTagCompound read(NBTTagCompound container) {
return container.hasKey(KEY, TAG_COMPOUND) ? container.getCompoundTag(KEY) : null;
}
/**
* The version stored for {@code key} in {@code stamps} (which may be null), or {@link #UNSTAMPED}.
*/
/// The version stored for `key` in `stamps`, or [#UNSTAMPED]. `stamps` may be null.
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.
*/
/// Writes the stamps onto `container`: `carried`, the stamps the data was read with or null, with every
/// transformer's key set to its current version.
public static void write(NBTTagCompound container, NBTTagCompound carried,
Iterable<IVersionedTransformer> transformers) {
NBTTagCompound stamps = carried == null ? new NBTTagCompound() : (NBTTagCompound) carried.copy();
@@ -6,9 +6,7 @@ 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.
*/
/// Logs each version span a transformer brings data across once per world, not once per chunk.
public final class VersionedTransformerLog {
private static final Set<String> ANNOUNCED = ConcurrentHashMap.newKeySet();
@@ -19,30 +19,27 @@ 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>
*/
/// Every namespaced block and item name whose content was missing when a world loaded, with every id it held,
/// oldest first.
///
/// FML drops a missing name from `level.dat` on the first save after its content disappears, so this table keeps
/// the name for transformers keyed on it. Persisted as `<world>/postea/known-ids.json`:
///
/// ```json
/// { "version": 1, "blocks": { "mod:block": [300, 301] }, "items": { "mod:item": [4200] } }
/// ```
public final class WorldIdTable {
static final String FILE_NAME = "known-ids.json";
/** FML prefixes block names with this character in a saved id map; items get U+0002. */
/// FML prefixes block names with this character in a saved id map, and item names with U+0002.
static final char BLOCK_PREFIX = 1;
private static final int FORMAT_VERSION = 1;
private final Map<String, IntList> blocks = new TreeMap<>();
private final Map<String, IntList> items = new TreeMap<>();
/**
* Loads {@code file}; an absent file yields an empty table. Throws {@link IllegalStateException} on a file that
* cannot be read or parsed.
*/
/// Loads `file`, or an empty table if it is absent. Throws [IllegalStateException] on a file that cannot be read
/// or parsed.
public static WorldIdTable load(File file) {
WorldIdTable table = new WorldIdTable();
if (!file.exists()) return table;
@@ -73,9 +70,7 @@ public final class WorldIdTable {
}
}
/**
* Writes the table through a temporary file so a crash mid-write never truncates it.
*/
/// 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);
@@ -109,10 +104,8 @@ public final class WorldIdTable {
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.
*/
/// Records entries of a world's saved name-to-id map, whose names carry FML's block and item prefixes
/// (see [#BLOCK_PREFIX]). Returns whether any pair was new.
public boolean merge(Map<String, Integer> dataList) {
boolean changed = false;
for (Map.Entry<String, Integer> entry : dataList.entrySet()) {
@@ -77,8 +77,8 @@ class NbtItemStacksTest {
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.
/// A string id with a `Count` is a stack only in string-id mode, which keeps chunk and player walks off tile
/// entity compounds.
@Test
void stringIdStacksAreVisitedOnlyInStringIdMode() {
NBTTagCompound quest = new NBTTagCompound();