feat: add Java material enumeration

This commit is contained in:
Algent committed 2026-09-04 23:30:54 +02:00
1 parent 9b78099d21
commit 2bb5e7ffc9
11 files changed
+267 -10

No files matched your search

@@ -3,6 +3,8 @@ package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.NetHandlerPlayServer;
@@ -22,6 +24,24 @@ import scala.Tuple2;
class MicroblockPacketHandlerFunctionalTest {
@Test
void javaEnumerationUsesTheSameIdsAsTheInitializedRegistryAndHandshake() {
PacketCustom outgoing = new PacketCustom("test", 1);
MicroMaterialRegistry.writeIDMap(outgoing);
PacketCustom incoming = new PacketCustom(outgoing.getByteBuf().copy());
int count = MicroMaterialRegistry.materialCount();
assertTrue(count > 0);
assertEquals(count, incoming.readInt());
for (int id = 0; id < count; id++) {
String name = MicroMaterialRegistry.materialName(id);
assertEquals(name, incoming.readString());
assertEquals(id, MicroMaterialRegistry.materialID(name));
assertNotNull(MicroMaterialRegistry.getMaterial(id));
assertSame(MicroMaterialRegistry.getMaterial(name), MicroMaterialRegistry.getMaterial(id));
}
assertEquals(0, incoming.getByteBuf().readableBytes());
}
@Test
void sendsTheCompleteMaterialIdMapDuringTheServerHandshake() {
MinecraftServer server = MinecraftServer.getServer();
@@ -89,6 +89,13 @@ public final class MicroMaterialRegistry$ {
return MicroMaterialRegistry.getMaterial(id);
}
/**
* Returns the same legacy backing array as {@link MicroMaterialRegistry#getIdMap()}.
*
* @deprecated For enumeration, use {@link MicroMaterialRegistry#materialCount()},
* {@link MicroMaterialRegistry#materialName(int)} and {@link MicroMaterialRegistry#getMaterial(int)}.
*/
@Deprecated
public Tuple2<String, IMicroMaterial>[] getIdMap() {
return MicroMaterialRegistry.getIdMap();
}
@@ -241,6 +241,15 @@ public final class MicroMaterialRegistry {
return idWriter.read(data);
}
/**
* Returns the persistent name at a numeric ID in the active material map. IDs may change when the map is rebuilt or
* synchronized with a server; store material names rather than numeric IDs in persistent data.
*
* @param id an ID from zero (inclusive) to {@link #materialCount()} (exclusive)
* @throws ArrayIndexOutOfBoundsException if the ID is outside the active map
* @throws NullPointerException if the map is uninitialized or the ID is unresolved after a failed
* handshake
*/
public static String materialName(int id) {
return idMap[id]._1();
}
@@ -258,10 +267,47 @@ public final class MicroMaterialRegistry {
return typeMap.get(remapped(name));
}
/**
* Returns the registered material instance at an ID in the active material map; no copy is made.
*
* @param id an ID from zero (inclusive) to {@link #materialCount()} (exclusive)
* @throws ArrayIndexOutOfBoundsException if the ID is outside the active map
* @throws NullPointerException if the map is uninitialized or the ID is unresolved after a failed
* handshake
*/
public static IMicroMaterial getMaterial(int id) {
return idMap[id]._2();
}
/**
* Returns the number of numeric ID slots in the active material map, including the missing-material placeholder
* when present. Enumerate IDs from zero (inclusive) to this count (exclusive) with {@link #materialName(int)} and
* {@link #getMaterial(int)}.
*
* FMP builds the map during post-initialization and before server startup. A multiplayer handshake replaces the
* client map with server ID order. Enumerate on the game/lifecycle thread after initialization; multiplayer clients
* must also finish the handshake successfully. The map must not be rebuilt during enumeration. Do not cache numeric
* IDs across map replacements. A failed handshake can leave unresolved slots, which this count includes; it is not
* a readiness check.
*
* @return the active map length, or zero for an initialized empty map
* @throws IllegalStateException if FMP has not initialized the material ID map
*/
public static int materialCount() {
if (idMap == null) {
throw new IllegalStateException("The material ID map has not been initialized.");
}
return idMap.length;
}
/**
* Returns the legacy live backing array, or null before ID-map initialization. A map replacement leaves earlier
* array references pointing at the old map; unresolved IDs after a failed handshake contain null.
*
* @deprecated For enumeration, use {@link #materialCount()}, {@link #materialName(int)} and
* {@link #getMaterial(int)}. The Scala array descriptor is retained for existing consumers.
*/
@Deprecated
public static Tuple2<String, IMicroMaterial>[] getIdMap() {
return idMap;
}
@@ -35,11 +35,12 @@ import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Vector3;
import codechicken.microblock.MicroMaterialRegistry.IMicroHighlightRenderer;
import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial;
import codechicken.microblock.examples.MaterialEnumerationExample;
/**
* The registry is global mutable state, so everything is registered once in {@link #registerAndFreezeIdMap()} and the
* cases below only read it. Error paths are not covered: they call the microblock logger, which is null until
* MicroblockProxy.preInit runs, so they cannot execute headless.
* cases below restore any temporary state changes. Logger-backed error paths require MicroblockProxy.preInit and cannot
* execute headless.
*/
class MicroMaterialRegistryCharacterizationTest {
@@ -129,6 +130,48 @@ class MicroMaterialRegistryCharacterizationTest {
assertEquals(java.lang.reflect.Array.getLength(original), MicroMaterialRegistry.getIdMap().length);
}
@Test
void javaExampleEnumeratesTheSameMaterialsWithoutExposingTheLegacyArray() throws Exception {
String[] names = Arrays.stream(MicroMaterialRegistry.getIdMap()).map(entry -> entry._1())
.toArray(String[]::new);
assertEquals(names.length, MicroMaterialRegistry.materialCount());
assertEquals(Arrays.asList(names), MaterialEnumerationExample.materialNames());
assertTrue(MicroMaterialRegistry.class.getMethod("getIdMap").isAnnotationPresent(Deprecated.class));
assertTrue(MicroMaterialRegistry$.class.getMethod("getIdMap").isAnnotationPresent(Deprecated.class));
}
@Test
void javaEnumerationTracksServerOrderMissingSlotsAndEmptyMaps() {
try {
MicroMaterialRegistry.readIDMap(incomingMap("test:stone", "test:glass"));
assertEquals(2, MicroMaterialRegistry.materialCount());
assertEquals(Arrays.asList("test:stone", "test:glass"), MaterialEnumerationExample.materialNames());
MicroMaterialRegistry.readIDMap(incomingMap("test:stone", "server:unavailable", "test:glass"));
assertEquals(3, MicroMaterialRegistry.materialCount());
assertThrows(NullPointerException.class, MaterialEnumerationExample::materialNames);
MicroMaterialRegistry.readIDMap(incomingMap());
assertEquals(0, MicroMaterialRegistry.materialCount());
assertEquals(Collections.emptyList(), MaterialEnumerationExample.materialNames());
} finally {
MicroMaterialRegistry$.MODULE$.setupIDMap();
}
}
@Test
void materialCountRejectsAnUninitializedMapInsteadOfReportingAnEmptyRegistry() throws Exception {
Field idMap = MicroMaterialRegistry.class.getDeclaredField("idMap");
idMap.setAccessible(true);
Object original = idMap.get(null);
try {
idMap.set(null, null);
assertThrows(IllegalStateException.class, MicroMaterialRegistry::materialCount);
} finally {
idMap.set(null, original);
}
}
@Test
void getMaterialByNameResolvesRemapsAndReturnsNullWhenUnknown() {
assertSame(GLASS, MicroMaterialRegistry.getMaterial("test:glass"));
@@ -0,0 +1,21 @@
package codechicken.microblock.examples;
import java.util.ArrayList;
import java.util.List;
import codechicken.microblock.MicroMaterialRegistry;
/** Compiling example for docs/api/MATERIAL_ENUMERATION.md; call after material IDs are ready. */
public final class MaterialEnumerationExample {
private MaterialEnumerationExample() {}
public static List<String> materialNames() {
int count = MicroMaterialRegistry.materialCount();
List<String> names = new ArrayList<>(count);
for (int id = 0; id < count; id++) {
names.add(MicroMaterialRegistry.materialName(id));
}
return names;
}
}