Write imported structure objects through the object codec

The structure importers build GeneratedObject and encode it with the pack's object codec instead of writing IrisObject
files. The codec test now round-trips a block entity and refuses markers, and validation has a test that a pool below
its minimum weight is reported by its field.
This commit is contained in:
piexel committed 2026-11-10 03:01:42 +01:00
1 parent 3d209b393c
commit 2961ed6b7d
8 files changed
+218 -45

No files matched your search

@@ -0,0 +1,120 @@
package art.arcane.iris.core.structure;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockBox;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.BlockEntityData;
import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Objects as the structure tools write them: a declared size, with blocks placed from the object's minimum corner. Iris
* keeps an object's blocks as offsets from its center, which sits half the size in from that corner.
*/
public final class DeclaredObjects {
private static final BlockPosition ANCHOR = new BlockPosition(0, 0, 0);
private DeclaredObjects() {
}
public static Builder builder(int width, int height, int depth) {
return new Builder(width, height, depth);
}
/** An object of the given size without a block. */
public static GeneratedObject empty(int width, int height, int depth) {
return builder(width, height, depth).build();
}
/** The size {@code object} declares. */
public static BlockPosition sizeOf(GeneratedObject object) {
BlockBox bounds = object.bounds();
return new BlockPosition(bounds.maxX() - bounds.minX(), bounds.maxY() - bounds.minY(), bounds.maxZ() - bounds.minZ());
}
/**
* {@code object} cut down to the box its blocks fill, centered the way every object is; an object without blocks
* stays as it is.
*/
public static GeneratedObject shrinkwrapped(GeneratedObject object) {
List<ObjectBlock> blocks = object.blocks();
if (blocks.isEmpty()) {
return object;
}
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int minZ = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
int maxZ = Integer.MIN_VALUE;
for (ObjectBlock block : blocks) {
BlockPosition position = block.position();
minX = Math.min(minX, position.x());
minY = Math.min(minY, position.y());
minZ = Math.min(minZ, position.z());
maxX = Math.max(maxX, position.x());
maxY = Math.max(maxY, position.y());
maxZ = Math.max(maxZ, position.z());
}
Builder wrapped = builder(maxX - minX + 1, maxY - minY + 1, maxZ - minZ + 1);
for (ObjectBlock block : blocks) {
BlockPosition position = block.position();
wrapped.state(position.x() - minX, position.y() - minY, position.z() - minZ, block.state());
int cornerX = position.x() - minX;
int cornerY = position.y() - minY;
int cornerZ = position.z() - minZ;
block.blockEntity().ifPresent(entity -> wrapped.blockEntity(cornerX, cornerY, cornerZ, entity));
}
return wrapped.build();
}
/** {@code local}, an offset from the object's center, as a position counted from its minimum corner. */
public static BlockPosition fromCorner(GeneratedObject object, BlockPosition local) {
BlockBox bounds = object.bounds();
return new BlockPosition(local.x() - bounds.minX(), local.y() - bounds.minY(), local.z() - bounds.minZ());
}
public static final class Builder {
private final int width;
private final int height;
private final int depth;
private final Map<BlockPosition, BlockState> states = new LinkedHashMap<>();
private final Map<BlockPosition, BlockEntityData> entities = new LinkedHashMap<>();
private Builder(int width, int height, int depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
/** Sets the block at a position counted from the minimum corner. */
public Builder state(int x, int y, int z, BlockState state) {
states.put(new BlockPosition(x, y, z), state);
return this;
}
/** Gives the block at a position counted from the minimum corner a block entity. */
public Builder blockEntity(int x, int y, int z, BlockEntityData entity) {
entities.put(new BlockPosition(x, y, z), entity);
return this;
}
public GeneratedObject build() {
int centerX = width / 2;
int centerY = height / 2;
int centerZ = depth / 2;
List<ObjectBlock> blocks = new ArrayList<>(states.size());
states.forEach((position, state) -> blocks.add(new ObjectBlock(
new BlockPosition(position.x() - centerX, position.y() - centerY, position.z() - centerZ), state,
Optional.ofNullable(entities.get(position)))));
BlockBox declared = new BlockBox(-centerX, -centerY, -centerZ, width - centerX, height - centerY, depth - centerZ);
return new GeneratedObject(declared, ANCHOR, blocks, List.of());
}
}
}
@@ -20,7 +20,8 @@ package art.arcane.iris.core.structure;
import art.arcane.iris.core.structure.tooling.SenderText;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.engine.object.prefab.IrisObject;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.GeneratedObject;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.CapturedStructure;
@@ -104,14 +105,15 @@ public final class StructureCaptureImporter {
for (String key : targets) {
String name = StructureImporter.deriveName(key);
try {
IrisObject object = captureOne(area, key, cellIndex++);
if (object == null || object.getBlocks().isEmpty()) {
GeneratedObject captured = captureOne(area, key, cellIndex++);
if (captured == null || captured.blocks().isEmpty()) {
skipped++;
SenderText.send(sender, TextColor.YELLOW, "[skip] " + key
+ ": did not place a capturable structure here (too large, wrong dimension, or no valid placement in a flat world). Stays vanilla-generated.");
continue;
}
object.shrinkwrap();
GeneratedObject object = DeclaredObjects.shrinkwrapped(captured);
BlockPosition size = DeclaredObjects.sizeOf(object);
StructureImporter.Result result = StructureImporter.writeSinglePieceStructure(
pack, name, key, object, "CENTER_HEIGHT", activeMode);
if (!result.success()) {
@@ -121,7 +123,7 @@ public final class StructureCaptureImporter {
}
imported++;
SenderText.send(sender, TextColor.GRAY, "[capture] " + key + " -> objects/" + name + ".iob ("
+ object.getW() + "x" + object.getH() + "x" + object.getD() + ")");
+ size.x() + "x" + size.y() + "x" + size.z() + ")");
} catch (Throwable e) {
failed++;
SenderText.send(sender, TextColor.RED, "[fail] " + key + ": " + e.getMessage());
@@ -174,19 +176,19 @@ public final class StructureCaptureImporter {
return normalized;
}
private static IrisObject captureOne(PlatformStructures.CaptureArea area, String key, int cellIndex) {
private static GeneratedObject captureOne(PlatformStructures.CaptureArea area, String key, int cellIndex) {
long seed = key.hashCode() * 0x9E3779B97F4A7C15L + cellIndex * 0x100000001B3L + 0x5DEECE66DL;
Optional<CapturedStructure> captured = area.capture(ResourceId.parse(key), seed, MAX_SPAN);
return captured.map(StructureCaptureImporter::objectOf).orElse(null);
}
private static IrisObject objectOf(CapturedStructure captured) {
IrisObject object = new IrisObject(captured.size().x(), captured.size().y(), captured.size().z());
private static GeneratedObject objectOf(CapturedStructure captured) {
DeclaredObjects.Builder object = DeclaredObjects.builder(captured.size().x(), captured.size().y(), captured.size().z());
for (TemplateBlock block : captured.blocks()) {
object.setUnsignedState(block.position().x(), block.position().y(), block.position().z(), block.state());
object.state(block.position().x(), block.position().y(), block.position().z(), block.state());
block.blockEntity().ifPresent(entity ->
object.setUnsignedBlockEntity(block.position().x(), block.position().y(), block.position().z(), entity));
object.blockEntity(block.position().x(), block.position().y(), block.position().z(), entity));
}
return object;
return object.build();
}
}
@@ -30,7 +30,7 @@ import art.arcane.iris.core.structure.authoring.StructureWriteMode;
import art.arcane.iris.core.structure.authoring.StructureWriteResult;
import art.arcane.iris.engine.framework.structure.StructureGraphValidationException;
import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler;
import art.arcane.iris.engine.object.prefab.IrisObject;
import com.volmit.object.GeneratedObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.volmit.block.BlockState;
@@ -104,7 +104,7 @@ public final class StructureImporter {
}
record CapturedStructure(
IrisObject object,
GeneratedObject object,
int blocks,
int nonAirBlocks,
int tiles,
@@ -182,7 +182,7 @@ public final class StructureImporter {
return new Result(false, "Failed to capture structure " + key + ": " + e.getMessage(), 0, List.of(), true);
}
IrisObject object = captured.object();
GeneratedObject object = captured.object();
int count = captured.blocks();
int tiles = captured.tiles();
int w = captured.width();
@@ -203,7 +203,7 @@ public final class StructureImporter {
? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK;
StructureSource source = StructureSource.of(sourceKind, sourceKey);
IrisStructureBundleFactory.SinglePieceOptions options = new IrisStructureBundleFactory.SinglePieceOptions(
bundleKey, source, name, object, Math.max(w, d), "CENTER_HEIGHT", objectOnly,
bundleKey, source, name, object, pack.objects(), Math.max(w, d), "CENTER_HEIGHT", objectOnly,
captured.capabilities(), losses);
StructureResourceBundle bundle = IrisStructureBundleFactory.singlePiece(options);
if (!objectOnly) {
@@ -241,7 +241,7 @@ public final class StructureImporter {
int w = Math.max(1, size.x());
int h = Math.max(1, size.y());
int d = Math.max(1, size.z());
IrisObject object = new IrisObject(w, h, d);
DeclaredObjects.Builder object = DeclaredObjects.builder(w, h, d);
int count = 0;
int nonAirBlocks = 0;
int tiles = 0;
@@ -275,13 +275,13 @@ public final class StructureImporter {
} else if (material.equals(STRUCTURE_BLOCK)) {
continue;
}
object.setUnsignedState(x, y, z, placed);
object.state(x, y, z, placed);
count++;
if (!isAir(placed)) {
nonAirBlocks++;
}
if (!structural && block.blockEntity().isPresent()) {
object.setUnsignedBlockEntity(x, y, z, block.blockEntity().get());
object.blockEntity(x, y, z, block.blockEntity().get());
tiles++;
}
}
@@ -292,7 +292,7 @@ public final class StructureImporter {
capabilities.add(StructureCapability.BLOCK_ENTITIES);
}
return new CapturedStructure(
object,
object.build(),
count,
nonAirBlocks,
tiles,
@@ -523,12 +523,13 @@ public final class StructureImporter {
ToolPack pack,
String name,
String vanillaSource,
IrisObject object,
GeneratedObject object,
String placeMode,
Mode mode
) {
Mode activeMode = mode == null ? Mode.ADD_ONLY : mode;
int span = Math.max(object.getW(), object.getD());
BlockPosition size = DeclaredObjects.sizeOf(object);
int span = Math.max(size.x(), size.z());
try {
StructureKey sourceKey = StructureKey.parse(vanillaSource, "minecraft");
StructureSource.Kind sourceKind = sourceKey.namespace().equals("minecraft")
@@ -538,6 +539,7 @@ public final class StructureImporter {
StructureSource.of(sourceKind, sourceKey),
name,
object,
pack.objects(),
span,
placeMode,
false,
@@ -554,7 +556,7 @@ public final class StructureImporter {
writeResult.failure().isPresent());
}
return new Result(true, "Captured '" + vanillaSource + "' as '" + name + "'"
+ writeResultNote(writeResult), object.getBlocks().size(), List.of());
+ writeResultNote(writeResult), object.blocks().size(), List.of());
} catch (StructureGraphValidationException e) {
return new Result(false, "Failed writing capture for '" + name + "': " + e.getMessage(), 0, List.of());
} catch (Throwable e) {
@@ -29,7 +29,7 @@ import art.arcane.iris.core.structure.authoring.StructureWriteResult;
import art.arcane.iris.engine.framework.structure.StructureGraphValidationException;
import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler;
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy;
import art.arcane.iris.engine.object.prefab.IrisObject;
import com.volmit.object.GeneratedObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.volmit.geometry.BlockFace;
@@ -129,7 +129,7 @@ public final class VillageImporter {
Map<String, Map<String, Object>> emittedPools = new LinkedHashMap<>();
Map<String, Map<String, Object>> emittedPieces = new LinkedHashMap<>();
Map<String, IrisObject> emittedObjects = new LinkedHashMap<>();
Map<String, GeneratedObject> emittedObjects = new LinkedHashMap<>();
Map<String, ImportedTemplate> importedTemplates = new LinkedHashMap<>();
Set<StructureCapability> capabilities = new HashSet<>();
capabilities.add(StructureCapability.BLOCKS);
@@ -318,8 +318,8 @@ public final class VillageImporter {
? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK;
StructureSource source = new StructureSource(sourceKind, sourceKey, structure.gameVersion(), "");
Map<String, byte[]> objectResources = new LinkedHashMap<>();
for (Map.Entry<String, IrisObject> entry : emittedObjects.entrySet()) {
objectResources.put(entry.getKey(), serialize(entry.getValue()));
for (Map.Entry<String, GeneratedObject> entry : emittedObjects.entrySet()) {
objectResources.put(entry.getKey(), pack.objects().encode(entry.getValue()));
}
Map<String, Object> rootStructure = structureJson(
structureKey.toString(),
@@ -398,7 +398,7 @@ public final class VillageImporter {
}
record ImportedTemplate(
IrisObject object,
GeneratedObject object,
int blocks,
int nonAirBlocks,
List<Map<String, Object>> connectors,
@@ -695,12 +695,6 @@ public final class VillageImporter {
return StructureCapability.BLOCKS;
}
private static byte[] serialize(IrisObject object) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
object.write(output);
return output.toByteArray();
}
private static Result failed(String message, List<StructureLoss> losses) {
return new Result(false, message, 0, 0, losses);
}
@@ -1,10 +1,10 @@
package art.arcane.iris.core.structure.authoring;
import art.arcane.iris.engine.object.prefab.IrisObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.volmit.object.GeneratedObject;
import com.volmit.tooling.ObjectCodec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -26,7 +26,8 @@ public final class IrisStructureBundleFactory {
.backend(StructureBackend.SNAPSHOT)
.capabilities(activeOptions.capabilities())
.losses(activeOptions.losses())
.resource("objects/" + activeOptions.resourceKey() + ".iob", serialize(activeOptions.object()))
.resource("objects/" + activeOptions.resourceKey() + activeOptions.codec().extension(),
activeOptions.codec().encode(activeOptions.object()))
.textResource("jigsaw-pieces/" + activeOptions.resourceKey() + ".json",
GSON.toJson(pieceJson(activeOptions.resourceKey())));
if (!activeOptions.objectOnly()) {
@@ -39,12 +40,6 @@ public final class IrisStructureBundleFactory {
return bundle.build();
}
private static byte[] serialize(IrisObject object) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
object.write(output);
return output.toByteArray();
}
private static Map<String, Object> pieceJson(String resourceKey) {
Map<String, Object> piece = new LinkedHashMap<>();
piece.put("object", resourceKey);
@@ -78,7 +73,8 @@ public final class IrisStructureBundleFactory {
StructureKey bundleKey,
StructureSource source,
String resourceKey,
IrisObject object,
GeneratedObject object,
ObjectCodec codec,
int maxSpan,
String placeMode,
boolean objectOnly,
@@ -90,6 +86,7 @@ public final class IrisStructureBundleFactory {
Objects.requireNonNull(source);
Objects.requireNonNull(resourceKey);
Objects.requireNonNull(object);
Objects.requireNonNull(codec);
Objects.requireNonNull(placeMode);
Objects.requireNonNull(capabilities);
Objects.requireNonNull(losses);
@@ -269,6 +269,21 @@ public class PackValidatorStructureGraphTest {
assertSingleErrorStartsWith("structures/castle.json: Structure 'castle' cannot be loaded: ", "structures/castle.json");
}
@Test
public void reportsAPoolBelowItsMinimumWeightByItsFieldAndNotOnlyAsMissing() throws Exception {
File pack = pack("\"structures\":[{\"structures\":[\"castle\"]}]");
write(pack, "structures/castle.json", "{\"startPool\":\"castle/start\"}");
write(pack, "jigsaw-pools/castle/start.json", "{\"pieces\":[{\"piece\":\"castle/start\",\"weight\":0}]}");
write(pack, "jigsaw-pieces/castle/start.json", "{\"object\":\"castle/start\"}");
writeObjectHeader(pack, "objects/castle/start.iob", 3, 9, 3);
List<String> errors = blockingErrors(pack);
assertTrue(errors.toString(), errors.contains(
"jigsaw-pools/castle/start.json: Jigsaw pool 'castle/start' cannot be loaded: "
+ "pieces[0].weight is 0; it must be at least 1"));
}
@Test
public void reportsMalformedJigsawPoolJson() throws Exception {
assertSingleErrorStartsWith("jigsaw-pools/castle/start.json: Jigsaw pool 'castle/start' cannot be loaded: ",
@@ -20,7 +20,6 @@ package art.arcane.iris.core.structure;
import art.arcane.iris.core.structure.authoring.StructureCapability;
import art.arcane.iris.core.structure.authoring.StructureLoss;
import art.arcane.iris.engine.object.prefab.IrisObject;
import org.junit.Test;
import java.util.List;
@@ -275,7 +274,7 @@ public class VillageImporterListPoolElementTest {
@Test
public void omittedTemplateContributesNoBlocksOrCapturedCapabilities() {
VillageImporter.ImportedTemplate imported = new VillageImporter.ImportedTemplate(
new IrisObject(3, 3, 3),
DeclaredObjects.empty(3, 3, 3),
27,
4,
List.of(),
@@ -4,10 +4,18 @@ import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.core.modules.BlockEntities;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.volmlib.util.collection.KMap;
import com.google.gson.Gson;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockBox;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.BlockEntityData;
import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock;
import com.volmit.object.ObjectMarker;
import com.volmit.resource.ResourceId;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -20,9 +28,11 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -75,6 +85,40 @@ public class IrisObjectCodecTest {
}
}
@Test
public void aTileSurvivesTheRoundTripWithItsContent() throws IOException {
TileData.TileReader previousReader = TileData.bindPlatformReader(
in -> new TileData(in.readUTF(), new Gson().fromJson(in.readUTF(), KMap.class)));
try {
KMap<String, Object> properties = new KMap<>();
properties.put("CustomName", "vault");
properties.put("Lock", "key");
BlockEntityData chest = BlockEntities.of(new TileData("minecraft:chest", properties));
GeneratedObject original = new GeneratedObject(new BlockBox(-2, -1, -2, 3, 2, 3), new BlockPosition(0, 0, 0),
List.of(new ObjectBlock(new BlockPosition(1, 0, -1), new BlockState("minecraft:chest"), Optional.of(chest)),
new ObjectBlock(new BlockPosition(0, 1, 0), new BlockState("minecraft:stone")),
new ObjectBlock(new BlockPosition(-2, -1, 2), new BlockState("minecraft:oak_planks"))),
List.of());
GeneratedObject again = codec.decode(codec.encode(original));
assertEquals(original.bounds(), again.bounds());
assertEquals(original.anchor(), again.anchor());
assertEquals(original.blocks(), again.blocks());
assertEquals(original.markers(), again.markers());
} finally {
TileData.restorePlatformReader(previousReader);
}
}
@Test
public void anObjectWithMarkersIsRefusedInsteadOfLosingThem() {
GeneratedObject marked = new GeneratedObject(new BlockBox(0, 0, 0, 1, 1, 1), new BlockPosition(0, 0, 0), List.of(),
List.of(new ObjectMarker(new BlockPosition(0, 0, 0), ResourceId.parse("test:spawn"), Map.of())));
assertThrows(IOException.class, () -> codec.encode(marked));
}
private static Map<BlockPosition, BlockState> blocksOf(GeneratedObject object) {
Map<BlockPosition, BlockState> blocks = new HashMap<>();
object.blocks().forEach(block -> blocks.put(block.position(), block.state()));