Baseline IrisApi draft before stage-graph redesign

This commit is contained in:
piexel committed 2026-10-05 17:01:18 +02:00
commit 9043d93fbd
91 files changed
+4045

No files matched your search

@@ -0,0 +1,79 @@
package com.volmit;
import com.volmit.block.BlockState;
import com.volmit.host.ArrayHunk;
import com.volmit.mantle.BlockBox;
import com.volmit.object.*;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.*;
import com.volmit.world.*;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import static org.junit.jupiter.api.Assertions.*;
class ApiValuesTest {
@Test
void idsAndStateKeysAreExplicitCanonicalImmutableValues() {
for (String invalid : List.of("stone", "Minecraft:stone", "a:b:c", "a:", ":a")) {
assertThrows(IllegalArgumentException.class, () -> ResourceId.parse(invalid));
}
var properties = new HashMap<>(Map.of("waterlogged", "false", "axis", "y"));
var state = new BlockState(ResourceId.parse("minecraft:oak_log"), properties);
properties.clear();
assertEquals("minecraft:oak_log[axis=y,waterlogged=false]", state.key());
assertEquals("y", state.properties().get("axis"));
assertEquals("x", state.withProperty("axis", "x").properties().get("axis"));
assertThrows(UnsupportedOperationException.class, () -> state.properties().clear());
assertThrows(IllegalArgumentException.class, () -> new ResourceKey<>("test:value", int.class));
}
@Test
void sparseObjectsCopySortAndRejectDuplicateOrOutOfBoundsBlocks() {
var a = new ObjectBlock(new BlockPosition(-1, 0, 0), new BlockState("minecraft:stone"));
var b = new ObjectBlock(new BlockPosition(1, 0, 0), new BlockState("minecraft:stone"));
var blocks = new ArrayList<>(List.of(b, a));
var bounds = new BlockBox(-1, 0, 0, 2, 1, 1);
var object = new GeneratedObject(bounds, new BlockPosition(0, 0, 0), blocks, List.of());
blocks.clear();
assertEquals(List.of(a, b), object.blocks());
assertThrows(IllegalArgumentException.class, () -> new GeneratedObject(bounds, object.anchor(), List.of(a, a), List.of()));
assertThrows(IllegalArgumentException.class, () -> new GeneratedObject(new BlockBox(0, 0, 0, 1, 1, 1), object.anchor(), List.of(a), List.of()));
}
@Test
void payloadBuffersDoNotEscapeAndHaveValueEquality() {
byte[] source = {1, 2};
var payload = new BlockEntityData(ResourceId.parse("test:tile"), 1, source);
source[0] = 99;
payload.payload()[0] = 98;
assertArrayEquals(new byte[]{1, 2}, payload.payload());
assertEquals(payload, new BlockEntityData(ResourceId.parse("test:tile"), 1, new byte[]{1, 2}));
}
@Test
void placementAlignsAnchorsAndCheckedArithmeticNeverWraps() {
var object = new GeneratedObject(new BlockBox(-1, -1, -1, 2, 2, 2), new BlockPosition(1, 1, 1), List.of(), List.of());
var request = new PlacementRequest(ResourceId.parse("test:placement"), object, new BlockPosition(-16, -64, -16));
assertEquals(new BlockPosition(-16, -64, -16), request.worldPosition(object.anchor()));
assertEquals(new BlockBox(-18, -66, -18, -15, -63, -15), request.footprint());
var overflow = new PlacementRequest(request.id(), object, new BlockPosition(Integer.MAX_VALUE, 0, 0));
assertThrows(ArithmeticException.class, overflow::footprint);
}
@Test
void boundedHunksAndTerrainSamplesRejectInvalidInputs() {
var hunk = new ArrayHunk<>(String.class, 2, 3, 4, "air");
hunk.set(1, 2, 3, "stone");
assertEquals("stone", hunk.get(1, 2, 3));
assertEquals("air", hunk.get(0, 0, 0));
assertThrows(IndexOutOfBoundsException.class, () -> hunk.get(2, 0, 0));
assertThrows(IndexOutOfBoundsException.class, () -> hunk.set(-1, 0, 0, "stone"));
assertThrows(NullPointerException.class, () -> hunk.set(0, 0, 0, null));
assertThrows(IllegalArgumentException.class, () -> new TerrainSample(Double.NaN, OptionalInt.empty(), 0));
assertThrows(IllegalArgumentException.class, () -> new TerrainSample(0, OptionalInt.empty(), -1));
}
}
@@ -0,0 +1,77 @@
package com.volmit;
import com.volmit.config.*;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.host.ArrayHunk;
import com.volmit.host.ModuleRegistry;
import com.volmit.resource.ResourceId;
import com.volmit.support.TestContexts;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FeatureContractTest {
@Desc("Example settings")
@Snippet("fill-settings")
@Feature(id = "example:fill", name = "Fill", field = "fill", targets = FeatureAttachment.Target.BIOME)
public static class FillOptions implements IrisFeature {
@Desc("Replacement value")
@MinNumber(0)
@MaxNumber(128)
private int value = 12;
private transient int cache;
private static int ignored;
}
@Test
void readsPrivateAnnotatedOptionsWithoutIncludingRuntimeState() {
var metadata = OptionsMetadata.inspect(FillOptions.class);
assertEquals("Example settings", metadata.description());
assertEquals("fill-settings", metadata.snippet());
assertEquals(1, metadata.options().size());
var option = metadata.options().getFirst();
assertEquals("value", option.name());
assertEquals(int.class, option.type());
assertEquals("Replacement value", option.description());
assertEquals(0.0, option.minimum());
assertEquals(128.0, option.maximum());
}
@Test
void registryBindsDecodedOptionsToTheCorrectModifier() {
var host = new ModuleRegistry();
host.register(FillOptions.class, Integer.class, FillModifier::new);
var registration = host.freeze().generation(FillOptions.class, Integer.class);
var modifier = registration.configure(ResourceId.parse("test:fill/0"), new FillOptions());
var output = new ArrayHunk<>(Integer.class, 1, 1, 1, 0);
modifier.modify(TestContexts.generation(), output);
assertEquals(12, output.get(0, 0, 0));
}
private static class FillModifier extends GenerationModifier<Integer> {
private final FillOptions options;
FillModifier(FillOptions options) {
this.options = options;
}
public String id() { return "example:fill-modifier"; }
public void modify(GenerationContext context, Hunk<Integer> volume) {
volume.set(0, 0, 0, options.value);
}
}
static class InvalidOptions {
@MinNumber(10) @MaxNumber(2) private int value;
}
static class NonnumericOptions {
@MinNumber(0) private String value;
}
@Test
void rejectsInconsistentAnnotationBounds() {
assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(InvalidOptions.class));
assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(NonnumericOptions.class));
}
}
@@ -0,0 +1,54 @@
package com.volmit.generation;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class DependenciesTest {
@Test
void accumulatesAndDeduplicatesWithoutMutatingEarlierDeclarations() {
var original = Dependencies.requires("iris:terrain", "iris:terrain");
var result = original.andRequires("iris:carving")
.afterIfPresent("example:caves").afterIfPresent("example:lakes")
.beforeIfPresent("iris:ores").beforeIfPresent("iris:ores", "iris:objects");
assertEquals(Set.of("iris:terrain"), original.required());
assertTrue(original.after().isEmpty());
assertTrue(original.before().isEmpty());
assertEquals(Set.of("iris:terrain", "iris:carving"), result.required());
assertEquals(Set.of("example:caves", "example:lakes"), result.after());
assertEquals(Set.of("iris:ores", "iris:objects"), result.before());
}
@Test
void copiesInputsAndExposesImmutableSets() {
var ids = new HashSet<>(Set.of("iris:terrain"));
var result = new Dependencies(ids, ids, ids);
ids.clear();
assertEquals(Set.of("iris:terrain"), result.required());
assertThrows(UnsupportedOperationException.class, () -> result.required().clear());
assertThrows(UnsupportedOperationException.class, () -> result.after().clear());
assertThrows(UnsupportedOperationException.class, () -> result.before().clear());
String[] input = {"iris:terrain"};
var fromArray = Dependencies.requires(input);
input[0] = "iris:ores";
assertEquals(Set.of("iris:terrain"), fromArray.required());
}
@Test
void supportsEmptyAndOptionalOnlyDeclarations() {
assertEquals(new Dependencies(Set.of(), Set.of(), Set.of()), Dependencies.none());
assertEquals(Dependencies.none(), Dependencies.requires());
assertEquals(Set.of("iris:ores"), Dependencies.none().beforeIfPresent("iris:ores").before());
}
@Test
void rejectsNullAndBlankIds() {
assertThrows(IllegalArgumentException.class, () -> Dependencies.requires(" "));
assertThrows(IllegalArgumentException.class, () -> Dependencies.none().afterIfPresent(""));
assertThrows(IllegalArgumentException.class, () -> Dependencies.none().beforeIfPresent("\n"));
assertThrows(NullPointerException.class, () -> Dependencies.requires((String) null));
assertThrows(NullPointerException.class, () -> Dependencies.requires((String[]) null));
assertThrows(NullPointerException.class, () -> new Dependencies(null, Set.of(), Set.of()));
}
}
@@ -0,0 +1,85 @@
package com.volmit.host;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class GenerationPlanTest {
private static ResourceId id(String path) { return ResourceId.parse("test:" + path); }
private static ConfiguredModifier<String> binding(String occurrence, String name, Dependencies dependencies) {
return new ConfiguredModifier<>(id(occurrence), String.class, new Modifier(name, dependencies));
}
private static class Modifier extends GenerationModifier<String> {
private final String name;
private final Dependencies dependencies;
Modifier(String name, Dependencies dependencies) { this.name = name; this.dependencies = dependencies; }
public String id() { return "test:" + name; }
public Dependencies depends() { return dependencies; }
public void modify(GenerationContext context, Hunk<String> output) {}
}
@Test
void orderingIsIndependentOfDiscoveryAndIncludesRepeatedOccurrences() {
var first = binding("terrain/1", "terrain", Dependencies.none());
var second = binding("terrain/0", "terrain", Dependencies.none());
var caves = binding("caves/0", "caves", Dependencies.requires("test:terrain"));
var decoration = binding("decoration/0", "decoration", Dependencies.requires("test:caves").beforeIfPresent("test:missing"));
var a = GenerationPlan.resolve(List.of(decoration, first, caves, second));
var b = GenerationPlan.resolve(List.of(second, caves, decoration, first));
var expected = List.of(id("terrain/0"), id("terrain/1"), id("caves/0"), id("decoration/0"));
assertEquals(expected, a.ordered().stream().map(ConfiguredModifier::occurrence).toList());
assertEquals(expected, b.ordered().stream().map(ConfiguredModifier::occurrence).toList());
var executed = new ArrayList<ResourceId>();
a.execute(new GenerationPlan.Executor() {
public <T> void execute(ConfiguredModifier<T> modifier) { executed.add(modifier.occurrence()); }
});
assertEquals(expected, executed);
assertThrows(UnsupportedOperationException.class, () -> a.ordered().clear());
}
@Test
void rejectsMissingRequirementsSelfEdgesAndCycles() {
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.requires("test:missing"))));
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.none().beforeIfPresent("test:a"))));
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.requires("test:b"), id("b"), Dependencies.requires("test:a"))));
}
@Test
void rejectsDuplicateOccurrencesAndConflictingImplementationsOrDeclarations() {
var a = binding("a/0", "a", Dependencies.none());
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a, a)));
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a,
binding("a/1", "a", Dependencies.none().afterIfPresent("test:b")))));
var otherImplementation = new ConfiguredModifier<>(id("a/2"), String.class, new Modifier("a", Dependencies.none()) {});
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a, otherImplementation)));
}
@Test
void repeatedEdgesAreCountedOnceAndIndependentIdsUseLexicalOrder() {
var graph = Map.of(id("a"), Dependencies.none(), id("z"), Dependencies.none(),
id("b"), Dependencies.requires("test:a").afterIfPresent("test:a"));
assertEquals(List.of(id("a"), id("b"), id("z")), DependencyOrder.resolve(graph));
}
@Test
void failuresStopDispatchAndNegativeReachFailsAtPackLoad() {
var plan = GenerationPlan.resolve(List.of(binding("a", "a", Dependencies.none()), binding("b", "b", Dependencies.none())));
var visited = new ArrayList<ResourceId>();
assertThrows(IllegalStateException.class, () -> plan.execute(new GenerationPlan.Executor() {
public <T> void execute(ConfiguredModifier<T> modifier) {
visited.add(modifier.id());
throw new IllegalStateException("Failed output");
}
}));
assertEquals(List.of(id("a")), visited);
assertThrows(IllegalArgumentException.class, () -> new ConfiguredModifier<>(id("negative"), String.class,
new Modifier("a", Dependencies.none()) { public int mantleRadius() { return -1; } }));
}
}
@@ -0,0 +1,95 @@
package com.volmit.host;
import com.volmit.*;
import com.volmit.config.Feature;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.*;
import com.volmit.placement.PlacementModifier;
import org.junit.jupiter.api.Test;
import java.io.DataInput;
import java.io.DataOutput;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class ModuleRegistryTest {
@Feature(id = "test:one", name = "One", field = "shared", targets = FeatureAttachment.Target.BIOME)
static class One implements IrisFeature {}
@Feature(id = "test:two", name = "Two", field = "shared", targets = FeatureAttachment.Target.DIMENSION)
static class Two implements IrisFeature {}
@Feature(id = "test:collision", name = "Collision", field = "shared", targets = {FeatureAttachment.Target.DIMENSION, FeatureAttachment.Target.BIOME})
static class Collision implements IrisFeature {}
@Feature(id = "test:one", name = "Duplicate", field = "different", targets = FeatureAttachment.Target.REGION)
static class Duplicate implements IrisFeature {}
@Feature(id = "test:placement", name = "Placement", field = "foundation", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
static class Placement implements IrisFeature {}
static class MissingAnnotation implements IrisFeature {}
@Feature(id = "test:abstract", name = "Abstract", field = "abstract", targets = FeatureAttachment.Target.BIOME)
abstract static class AbstractFeature implements IrisFeature {}
private static GenerationModifier<String> modifier(IrisFeature ignored) {
return new GenerationModifier<>() {
public String id() { return "test:modifier"; }
public void modify(GenerationContext context, Hunk<String> output) {}
};
}
@Test
void validatesIdsTypesAndFieldsAcrossFeatureKindsWithoutPartialRegistration() {
var registry = new ModuleRegistry();
registry.register(One.class, String.class, ModuleRegistryTest::modifier);
assertThrows(IllegalArgumentException.class, () -> registry.register(Collision.class, String.class, ModuleRegistryTest::modifier));
registry.register(Two.class, String.class, ModuleRegistryTest::modifier);
assertThrows(IllegalArgumentException.class, () -> registry.registerObject(Duplicate.class, ignored -> context -> null));
assertThrows(IllegalArgumentException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
var catalog = registry.freeze();
assertEquals(List.of("test:one", "test:two"), catalog.generation().stream().map(value -> value.descriptor().id().toString()).toList());
assertThrows(IllegalArgumentException.class, () -> catalog.generation(One.class, Integer.class));
}
@Test
void reservesHostFieldsAndRejectsInvalidFeaturesOrFactories() {
var registry = new ModuleRegistry(Map.of(FeatureAttachment.Target.BIOME, Set.of("shared")));
assertThrows(IllegalArgumentException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
assertThrows(IllegalArgumentException.class, () -> registry.register(MissingAnnotation.class, String.class, ModuleRegistryTest::modifier));
assertThrows(IllegalArgumentException.class, () -> registry.register(AbstractFeature.class, String.class, ModuleRegistryTest::modifier));
assertThrows(NullPointerException.class, () -> registry.register(Two.class, String.class, null));
registry.register(Two.class, String.class, ModuleRegistryTest::modifier);
}
@Test
void placementMustAttachToPlacementAndFreezeEndsRegistration() {
var registry = new ModuleRegistry();
assertThrows(IllegalArgumentException.class, () -> registry.registerPlacement(One.class, ignored -> new PlacementModifier() {
public String id() { return "test:placement"; }
}));
registry.registerPlacement(Placement.class, ignored -> new PlacementModifier() {
public String id() { return "test:placement"; }
});
assertEquals(1, registry.freeze().placement().size());
assertSame(registry.freeze(), registry.freeze());
assertThrows(IllegalStateException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
}
@Test
void mantleIdsAreUniqueAndCodecVersionIsSnapshotted() {
var registry = new ModuleRegistry();
var key = new MantleKey<>("test:owners", String.class);
var codec = codec(3);
registry.registerMantle(key, MantleLifetime.GENERATION, codec);
assertThrows(IllegalArgumentException.class, () -> registry.registerMantle(key, MantleLifetime.PERSISTENT, codec));
assertThrows(IllegalArgumentException.class, () -> registry.registerMantle(new MantleKey<>("test:bad", String.class), MantleLifetime.GENERATION, codec(-1)));
assertEquals(3, registry.freeze().mantle().getFirst().version());
assertEquals(1, registry.freeze().mantle().size());
}
private static MantleCodec<String> codec(int version) {
return new MantleCodec<>() {
public int version() { return version; }
public void write(DataOutput output, String value) {}
public String read(DataInput input, int storedVersion) { return ""; }
};
}
}
@@ -0,0 +1,259 @@
package com.volmit.host;
import com.volmit.block.BlockState;
import com.volmit.generation.Dependencies;
import com.volmit.mantle.*;
import com.volmit.object.*;
import com.volmit.placement.*;
import com.volmit.resource.ResourceId;
import com.volmit.support.TestContexts;
import com.volmit.world.BlockPosition;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
class PlacementPipelineTest {
private static final BlockState STONE = new BlockState("minecraft:stone");
private static final BlockState AIR = new BlockState("minecraft:air");
private static ResourceId id(String name) { return ResourceId.parse("test:" + name); }
private static PlacementRequest request() {
var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 1, 1), new BlockPosition(1, 0, 0),
List.of(new ObjectBlock(new BlockPosition(1, 0, 0), STONE), new ObjectBlock(new BlockPosition(0, 0, 0), STONE)),
List.of(new ObjectMarker(new BlockPosition(1, 0, 0), id("owner"), Map.of("name", "column"))));
return new PlacementRequest(id("attempt"), object, new BlockPosition(-2, -60, -3));
}
private static ConfiguredPlacementModifier configured(PlacementModifier modifier) {
return new ConfiguredPlacementModifier(ResourceId.parse(modifier.id() + "/0"), modifier);
}
@Test
void validatesCompletePlanBeforeWritesAndAfterHooksSeeOverlayAndActualBounds() {
var events = new ArrayList<String>();
var modifier = new PlacementModifier() {
public String id() { return "test:foundation"; }
public Optional<PlacementRequest> prepare(PlacementContext context, PlacementRequest request) {
events.add("prepare"); return Optional.of(request);
}
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
events.add("map");
return block.position().x() == -3 ? Optional.empty() : Optional.of(block);
}
public boolean validate(PlacementContext context, PlacementPlan plan) {
events.add("validate");
assertEquals(1, plan.blocks().size());
return true;
}
public void beforePlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
events.add("before");
assertEquals(AIR, access.get(-2, -60, -3));
}
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan written) {
events.add("after");
assertEquals(STONE, access.get(-2, -60, -3));
assertEquals(new BlockBox(-2, -60, -3, -1, -59, -2), written.writtenBounds().orElseThrow());
assertFalse(access instanceof PlacementEdit);
access.set(new PlacedBlock(new BlockPosition(-2, -61, -3), STONE, Optional.empty()));
}
};
var pipeline = PlacementPipeline.resolve(List.of(configured(modifier)));
var edit = new RecordingEdit(events);
var result = pipeline.place(request(), edit, ignored -> TestContexts.placement(), plan -> {
events.add("host-validate"); assertEquals(0, edit.mutations); return true;
});
assertTrue(result.isPresent());
assertEquals(List.of("prepare", "map", "map", "host-validate", "validate", "before", "write", "marker", "after", "write", "commit", "close"), events);
assertEquals(2, edit.published.size());
assertEquals(1, edit.publishedMarkers.size());
assertThrows(IllegalStateException.class, () -> edit.get(-2, -60, -3));
}
@Test
void validationRejectionPublishesNothingAndDoesNotStartMutating() {
var modifier = new PlacementModifier() {
public String id() { return "test:reject"; }
public boolean validate(PlacementContext context, PlacementPlan plan) { return false; }
};
var edit = new RecordingEdit(new ArrayList<>());
assertTrue(PlacementPipeline.resolve(List.of(configured(modifier)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true).isEmpty());
assertEquals(0, edit.mutations);
assertTrue(edit.published.isEmpty());
assertTrue(edit.closed);
}
@Test
void failureAfterBufferedObjectWritesDiscardsEntireAttempt() {
var modifier = new PlacementModifier() {
public String id() { return "test:failure"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
access.set(new PlacedBlock(new BlockPosition(-2, -61, -3), STONE, Optional.empty()));
throw new IllegalStateException("Foundation failed");
}
};
var edit = new RecordingEdit(new ArrayList<>());
assertThrows(IllegalStateException.class, () -> PlacementPipeline.resolve(List.of(configured(modifier)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true));
assertTrue(edit.mutations > 0);
assertTrue(edit.published.isEmpty());
assertTrue(edit.publishedMarkers.isEmpty());
assertTrue(edit.closed);
}
@Test
void prepareRejectionAndFailedCommitCloseWithoutPublication() {
var rejection = new PlacementModifier() {
public String id() { return "test:prepare-reject"; }
public Optional<PlacementRequest> prepare(PlacementContext context, PlacementRequest request) { return Optional.empty(); }
};
var rejected = new RecordingEdit(new ArrayList<>());
assertTrue(PlacementPipeline.resolve(List.of(configured(rejection)))
.place(request(), rejected, ignored -> TestContexts.placement(), ignored -> true).isEmpty());
assertEquals(0, rejected.mutations);
var failed = new RecordingEdit(new ArrayList<>());
failed.failCommit = true;
assertThrows(IllegalStateException.class, () -> PlacementPipeline.resolve(List.of())
.place(request(), failed, ignored -> TestContexts.placement(), ignored -> true));
assertTrue(failed.closed);
assertTrue(failed.published.isEmpty());
}
@Test
void rejectsMappedBoundsDuplicateWritesAndInsufficientPreparedReachBeforeMutation() {
var escape = new PlacementModifier() {
public String id() { return "test:escape"; }
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
return Optional.of(new PlacedBlock(new BlockPosition(5, -60, -3), block.state(), block.blockEntity()));
}
};
var escaped = new RecordingEdit(new ArrayList<>());
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(escape)))
.place(request(), escaped, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, escaped.mutations);
var radius = new PlacementModifier() {
public String id() { return "test:radius"; }
public int writeRadius() { return 32; }
};
var unprepared = new RecordingEdit(new ArrayList<>());
assertThrows(IndexOutOfBoundsException.class, () -> PlacementPipeline.resolve(List.of(configured(radius)))
.place(request(), unprepared, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, unprepared.mutations);
}
@Test
void hooksCannotWriteBeyondReachOrRetainUsableViews() {
var retained = new AtomicReference<PlacementAccess>();
var retainedLayer = new AtomicReference<MantleLayer<String>>();
var modifier = new PlacementModifier() {
public String id() { return "test:bounded"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
retained.set(access);
retainedLayer.set(access.mantle().layer(new MantleKey<>("test:owner", String.class)));
assertThrows(IndexOutOfBoundsException.class, () -> access.set(new PlacedBlock(new BlockPosition(5, -60, -3), STONE, Optional.empty())));
assertThrows(UnsupportedOperationException.class, () -> access.mantle().edit());
assertThrows(IndexOutOfBoundsException.class, () -> access.mantle().layer(new MantleKey<>("test:owner", String.class)).get(5, -60, -3));
}
};
var edit = new RecordingEdit(new ArrayList<>());
PlacementPipeline.resolve(List.of(configured(modifier))).place(request(), edit, ignored -> TestContexts.placement(), ignored -> true);
assertThrows(IllegalStateException.class, () -> retained.get().get(-2, -60, -3));
assertThrows(IllegalStateException.class, () -> retainedLayer.get().get(-2, -60, -3));
}
@Test
void placementDependenciesStayInTheirOwnGraphAndRejectConflicts() {
var first = new PlacementModifier() { public String id() { return "test:first"; } };
var second = new PlacementModifier() {
public String id() { return "test:second"; }
public Dependencies depends() { return Dependencies.requires("test:first"); }
};
assertEquals(List.of(ResourceId.parse("test:first"), ResourceId.parse("test:second")),
PlacementPipeline.resolve(List.of(configured(second), configured(first))).ordered().stream().map(ConfiguredPlacementModifier::id).toList());
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(second))));
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(first), configured(first))));
}
@Test
void mappedWritesOutsideReachFailBeforeMutationAndEachHookKeepsItsOwnReach() {
var moved = new PlacementModifier() {
public String id() { return "test:moved"; }
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
return Optional.of(new PlacedBlock(block.position().add(new BlockPosition(8, 0, 0)), block.state(), block.blockEntity()));
}
};
var edit = new RecordingEdit(new ArrayList<>());
assertThrows(IndexOutOfBoundsException.class, () -> PlacementPipeline.resolve(List.of(configured(moved)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, edit.mutations);
var large = new PlacementModifier() {
public String id() { return "test:large"; }
public int writeRadius() { return 2; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
assertEquals(AIR, access.get(0, -60, -3));
assertEquals(new BlockBox(-5, -64, -5, 1, 320, 0), access.mantle().bounds());
assertNull(access.mantle().layer(new MantleKey<>("test:owner", String.class))
.get(0, -60, -3));
}
};
var small = new PlacementModifier() {
public String id() { return "test:small"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
assertThrows(IndexOutOfBoundsException.class, () -> access.get(0, -60, -3));
assertEquals(new BlockBox(-3, -64, -3, -1, 320, -2), access.mantle().bounds());
assertThrows(IndexOutOfBoundsException.class, () -> access.mantle()
.layer(new MantleKey<>("test:owner", String.class)).get(0, -60, -3));
}
};
assertTrue(PlacementPipeline.resolve(List.of(configured(small), configured(large)))
.place(request(), new RecordingEdit(new ArrayList<>()), ignored -> TestContexts.placement(), ignored -> true).isPresent());
}
/** In-memory transactional test adapter; production storage/persistence is deliberately absent. */
private static class RecordingEdit implements PlacementEdit {
final List<String> events;
final Map<BlockPosition, BlockState> pending = new HashMap<>();
final Map<BlockPosition, BlockState> published = new HashMap<>();
final List<PlacedMarker> pendingMarkers = new ArrayList<>();
final List<PlacedMarker> publishedMarkers = new ArrayList<>();
boolean closed;
boolean failCommit;
int mutations;
RecordingEdit(List<String> events) { this.events = events; }
private void checkOpen() { if (closed) throw new IllegalStateException("Closed edit"); }
public BlockBox bounds() { checkOpen(); return new BlockBox(-16, -64, -16, 16, 320, 16); }
public BlockState get(int x, int y, int z) { checkOpen(); return pending.getOrDefault(new BlockPosition(x, y, z), AIR); }
public void set(PlacedBlock block) { checkOpen(); mutations++; events.add("write"); pending.put(block.position(), block.state()); }
public void marker(PlacedMarker marker) { checkOpen(); mutations++; events.add("marker"); pendingMarkers.add(marker); }
public Mantle mantle() {
checkOpen();
return new Mantle() {
public BlockBox bounds() { return RecordingEdit.this.bounds(); }
public MantleEdit edit() { throw new UnsupportedOperationException(); }
public <T> MantleLayer<T> layer(MantleKey<T> key) {
return new MantleLayer<>() {
public T get(int x, int y, int z) { checkOpen(); return null; }
public void set(int x, int y, int z, T value) { throw new AssertionError("Unused mantle mutation"); }
public void remove(int x, int y, int z) { throw new AssertionError("Unused mantle mutation"); }
public void clear(BlockBox area) { throw new AssertionError("Unused mantle mutation"); }
public void visit(BlockBox area, MantleVisitor<T> visitor) { checkOpen(); }
};
}
};
}
public void commit() {
checkOpen();
if (failCommit) throw new IllegalStateException("Commit failed");
events.add("commit"); published.putAll(pending); publishedMarkers.addAll(pendingMarkers); closed = true;
}
public void close() {
if (!events.contains("close")) events.add("close");
closed = true; pending.clear(); pendingMarkers.clear();
}
}
}
@@ -0,0 +1,50 @@
package com.volmit.mantle;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class MantleValueTest {
@Test
void boundsUseWorldCoordinatesAndExclusiveMaximum() {
var box = new BlockBox(-16, -64, -16, 16, 320, 16);
assertTrue(box.contains(-16, -64, -16));
assertTrue(box.contains(15, 319, 15));
assertFalse(box.contains(16, 0, 0));
assertFalse(box.contains(0, 320, 0));
assertFalse(box.contains(0, 0, 16));
assertFalse(box.contains(0, -65, 0));
assertTrue(box.contains(box));
assertTrue(box.contains(new BlockBox(0, 0, 0, 1, 1, 1)));
assertFalse(box.contains(new BlockBox(-17, 0, 0, 1, 1, 1)));
assertThrows(NullPointerException.class, () -> box.contains(null));
}
@Test
void rejectsInversionButAllowsEmptyBounds() {
assertThrows(IllegalArgumentException.class, () -> new BlockBox(1, 0, 0, 0, 1, 1));
assertThrows(IllegalArgumentException.class, () -> new BlockBox(0, 1, 0, 1, 0, 1));
assertThrows(IllegalArgumentException.class, () -> new BlockBox(0, 0, 1, 1, 1, 0));
assertFalse(new BlockBox(0, 0, 0, 0, 0, 0).contains(0, 0, 0));
var extremes = new BlockBox(Integer.MIN_VALUE, -64, 0, Integer.MAX_VALUE, 320, 1);
assertTrue(extremes.contains(Integer.MIN_VALUE, 0, 0));
}
@Test
void keysSeparateSameTypedLayersAndHaveValueEquality() {
var owner = new MantleKey<>("example:object-owner", String.class);
assertEquals(owner, new MantleKey<>("example:object-owner", String.class));
assertNotEquals(owner, new MantleKey<>("example:quest/location", String.class));
assertNotEquals(owner, new MantleKey<>("example:object-owner", Integer.class));
}
@Test
void rejectsInvalidKeys() {
for (String id : new String[]{"", "owner", ":owner", "example:", "Example:owner", "a:b:c", "a: b"}) {
assertThrows(IllegalArgumentException.class, () -> new MantleKey<>(id, String.class));
}
assertThrows(NullPointerException.class, () -> new MantleKey<>(null, String.class));
assertThrows(NullPointerException.class, () -> new MantleKey<>("a:b", null));
assertThrows(IllegalArgumentException.class, () -> new MantleKey<>("a:b", int.class));
}
}
@@ -0,0 +1,45 @@
package com.volmit.support;
import com.volmit.config.FeatureSettings;
import com.volmit.generation.GenerationContext;
import com.volmit.mantle.Mantle;
import com.volmit.object.ObjectTransformer;
import com.volmit.placement.PlacementContext;
import com.volmit.resource.PackResources;
import com.volmit.world.TerrainSampler;
import com.volmit.world.BlockView;
import java.util.Random;
import java.util.random.RandomGenerator;
/** Tests needing no platform facilities fail loudly if code starts using one. */
public final class TestContexts {
private TestContexts() {}
public static GenerationContext generation() {
return new GenerationContext() {
private final RandomGenerator random = new Random(42);
public int originX() { return 0; }
public int originY() { return -64; }
public int originZ() { return 0; }
public long worldSeed() { return 42; }
public RandomGenerator random() { return random; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
public Mantle mantle() { throw new AssertionError("Unused mantle"); }
};
}
public static PlacementContext placement() {
return new PlacementContext() {
private final RandomGenerator random = new Random(42);
public long worldSeed() { return 42; }
public RandomGenerator random() { return random; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
public ObjectTransformer objects() { throw new AssertionError("Unused transforms"); }
public BlockView blocks() { throw new AssertionError("Unused blocks"); }
};
}
}