mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 00:34:19 +00:00
Merge IrisApi into api/ with its history
git-subtree-dir: api git-subtree-mainline:cff15f93c5git-subtree-split:dac8baa3ab
This commit is contained in:
commit
925c942764
365 files changed
+29228
No files matched your search
@@ -0,0 +1,212 @@
|
||||
package com.volmit;
|
||||
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.host.ArrayHunk;
|
||||
import com.volmit.geometry.*;
|
||||
import com.volmit.object.*;
|
||||
import com.volmit.placement.PlacementRequest;
|
||||
import com.volmit.resource.*;
|
||||
import com.volmit.validation.Problem;
|
||||
import com.volmit.validation.Severity;
|
||||
import com.volmit.validation.Subject;
|
||||
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 aPackKeyBecomesTheIdOfItsResource() {
|
||||
assertEquals(ResourceId.parse("overworld:dungeon/chest"), ResourceId.ofPackKey("overworld", "dungeon/chest"));
|
||||
assertEquals(ResourceId.parse("overworld:dungeon/chest_1"), ResourceId.ofPackKey("overworld", "Dungeon/Chest 1"));
|
||||
assertEquals(ResourceId.parse("test:a/b"), new com.volmit.support.EmptyResources().idOf("a/b"));
|
||||
}
|
||||
|
||||
@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());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withPropertyChecksTheNewPropertyAndKeepsValueSemantics() {
|
||||
var log = new BlockState("minecraft:oak_log").withProperty("waterlogged", "false").withProperty("axis", "y");
|
||||
|
||||
assertEquals(new BlockState(ResourceId.parse("minecraft:oak_log"), Map.of("axis", "y", "waterlogged", "false")), log);
|
||||
assertEquals(Map.of("axis", "y", "waterlogged", "false").hashCode(), log.properties().hashCode());
|
||||
assertEquals("BlockState[material=minecraft:oak_log, properties={axis=y, waterlogged=false}]", log.toString());
|
||||
assertEquals(List.of("axis", "waterlogged"), List.copyOf(log.properties().keySet()));
|
||||
assertEquals(log, new BlockState(log.material(), log.properties()));
|
||||
assertThrows(UnsupportedOperationException.class, () -> log.properties().put("axis", "x"));
|
||||
assertThrows(IllegalArgumentException.class, () -> log.withProperty("Axis", "x"));
|
||||
assertThrows(IllegalArgumentException.class, () -> log.withProperty("axis", "X"));
|
||||
assertThrows(NullPointerException.class, () -> log.withProperty("axis", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blockStatesParseWhatTheirKeyWrites() {
|
||||
var log = new BlockState("minecraft:oak_log").withProperty("waterlogged", "false").withProperty("axis", "y");
|
||||
|
||||
assertEquals(log, BlockState.parse(log.key()));
|
||||
assertEquals(log, BlockState.parse("minecraft:oak_log[waterlogged=false,axis=y]"));
|
||||
assertEquals(new BlockState("minecraft:stone"), BlockState.parse("minecraft:stone"));
|
||||
assertEquals(new BlockState("minecraft:stone"), BlockState.parse("minecraft:stone[]"));
|
||||
assertThrows(IllegalArgumentException.class, () -> BlockState.parse("minecraft:oak_log[axis=y"));
|
||||
assertThrows(IllegalArgumentException.class, () -> BlockState.parse("minecraft:oak_log[axis]"));
|
||||
assertThrows(IllegalArgumentException.class, () -> BlockState.parse("minecraft:oak_log[axis=y,axis=x]"));
|
||||
assertThrows(IllegalArgumentException.class, () -> BlockState.parse("stone"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleInfoRequiresANameAndVersion() {
|
||||
var info = ModuleInfo.of("example:moss", "Moss", "1.0.0");
|
||||
assertEquals(ResourceId.parse("example:moss"), info.id());
|
||||
assertEquals("Moss", info.name());
|
||||
assertThrows(IllegalArgumentException.class, () -> ModuleInfo.of("example:moss", " ", "1.0.0"));
|
||||
assertThrows(IllegalArgumentException.class, () -> ModuleInfo.of("example:moss", "Moss", ""));
|
||||
assertThrows(NullPointerException.class, () -> ModuleInfo.of("example:moss", null, "1.0.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleInfoTextFitsOnOneLogLine() {
|
||||
for (var broken : List.of("Moss\nINFO forged line", "Moss\r", "Moss\tTabbed", "Moss\u2028Next")) {
|
||||
var failure = assertThrows(IllegalArgumentException.class, () -> ModuleInfo.of("example:moss", broken, "1.0.0"));
|
||||
assertEquals("Module name of example:moss contains a line break or other control character", failure.getMessage());
|
||||
}
|
||||
assertThrows(IllegalArgumentException.class, () -> ModuleInfo.of("example:moss", "Moss", "1.0\n"));
|
||||
assertEquals("Mosß é", ModuleInfo.of("example:moss", "Mosß é", "1.0.0").name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleIdsAreOneSegmentAndOwnTheIdsBelowThem() {
|
||||
var nested = assertThrows(IllegalArgumentException.class, () -> ModuleInfo.of("iris:stilt/extra", "Extra", "1"));
|
||||
assertEquals("Module id iris:stilt/extra must not contain '/': stage ids are a module id, '/' and a name, "
|
||||
+ "so iris:stilt/extra would name stages under another module's id", nested.getMessage());
|
||||
|
||||
var stilt = ModuleInfo.of("iris:stilt", "Stilt", "1");
|
||||
assertEquals("iris:stilt/", stilt.idPrefix());
|
||||
assertTrue(stilt.ownsStage(ResourceId.parse("iris:stilt/fill")));
|
||||
assertTrue(stilt.ownsStage(ResourceId.parse("iris:stilt/fill/deep")));
|
||||
assertFalse(stilt.ownsStage(ResourceId.parse("iris:stilt")));
|
||||
assertFalse(stilt.ownsStage(ResourceId.parse("iris:stilts/fill")));
|
||||
assertFalse(stilt.ownsStage(ResourceId.parse("iris:anchor/height")));
|
||||
assertFalse(stilt.ownsStage(ResourceId.parse("other:stilt/fill")));
|
||||
|
||||
assertTrue(stilt.ownsId(ResourceId.parse("iris:stilt")));
|
||||
assertTrue(stilt.ownsId(ResourceId.parse("iris:stilt/depth")));
|
||||
assertFalse(stilt.ownsId(ResourceId.parse("iris:stilts")));
|
||||
assertFalse(stilt.ownsId(ResourceId.parse("iris:stilt-depth")));
|
||||
assertFalse(stilt.ownsId(ResourceId.parse("iris:anchor")));
|
||||
assertFalse(stilt.ownsId(ResourceId.parse("other:stilt")));
|
||||
}
|
||||
|
||||
@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(object, new BlockPosition(-16, 64, -16));
|
||||
assertEquals(new BlockPosition(-16, 64, -16), request.worldPosition(object.anchor()));
|
||||
assertEquals(new BlockBox(-18, 62, -18, -15, 65, -15), request.footprint());
|
||||
var overflow = new PlacementRequest(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));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packBiomesAndRegionsAreImmutableValues() {
|
||||
var children = new ArrayList<>(List.of(ResourceId.parse("pack:dunes")));
|
||||
var desert = new PackBiome(ResourceId.parse("pack:desert"), "Desert", ResourceId.parse("minecraft:desert"), 2, children);
|
||||
children.clear();
|
||||
assertEquals(List.of(ResourceId.parse("pack:dunes")), desert.children());
|
||||
assertThrows(UnsupportedOperationException.class, () -> desert.children().clear());
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new PackBiome(desert.id(), "Desert", desert.platformBiome(), 0, List.of()));
|
||||
assertEquals(desert.platformBiome(), desert.vanillaBiome(), "vanilla sees the platform biome unless a pack says otherwise");
|
||||
var mesa = new PackBiome(ResourceId.parse("pack:mesa"), "Mesa", ResourceId.parse("minecraft:desert"),
|
||||
ResourceId.parse("minecraft:badlands"), 1, List.of());
|
||||
assertEquals(ResourceId.parse("minecraft:badlands"), mesa.vanillaBiome());
|
||||
|
||||
var land = List.of(desert.id());
|
||||
var arid = new PackRegion(ResourceId.parse("pack:arid"), "Arid", 1, land, List.of(), List.of(), List.of());
|
||||
assertEquals(land, arid.landBiomes());
|
||||
assertThrows(UnsupportedOperationException.class, () -> arid.caveBiomes().add(desert.id()));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new PackRegion(arid.id(), "Arid", 0, land, List.of(), List.of(), List.of()));
|
||||
}
|
||||
|
||||
static final class Keep {}
|
||||
|
||||
@Test
|
||||
void resourceKindsReadOneFolderIntoAConcreteClass() {
|
||||
assertTrue(ResourceKind.isFolderName("jigsaw-pools"));
|
||||
for (String folder : List.of("", ".", "..", "a/b", "Keeps", "a b")) {
|
||||
var failure = assertThrows(IllegalArgumentException.class, () -> ResourceKind.of("test:castle/keep", folder, Keep.class));
|
||||
assertTrue(failure.getMessage().startsWith("Folder '" + folder + "' of resource kind test:castle/keep is not a folder name"),
|
||||
failure.getMessage());
|
||||
}
|
||||
assertThrows(IllegalArgumentException.class, () -> ResourceKind.of("test:castle/keep", "keeps", Runnable.class));
|
||||
assertThrows(IllegalArgumentException.class, () -> ResourceKind.of("test:castle/keep", "keeps", int.class));
|
||||
assertThrows(IllegalArgumentException.class, () -> ResourceKind.of("keep", "keeps", Keep.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void problemsConcernAResourceOrAFileBelowThePackRoot() {
|
||||
var error = Problem.error(Subject.file("structures/castle.json"), "Castle never assembles.");
|
||||
var warning = Problem.warning(Subject.resource(ResourceId.parse("overworld:castle")), "Castle is large.");
|
||||
|
||||
assertEquals(Severity.ERROR, error.severity());
|
||||
assertEquals("structures/castle.json", error.subject().toString());
|
||||
assertEquals(Severity.WARNING, warning.severity());
|
||||
assertEquals("overworld:castle", warning.subject().toString());
|
||||
for (String path : List.of("", "/structures/castle.json", "../castle.json", "structures/../castle.json", "a//b", "a\\b", "./a")) {
|
||||
assertThrows(IllegalArgumentException.class, () -> Subject.file(path), path);
|
||||
}
|
||||
assertThrows(IllegalArgumentException.class, () -> Problem.error(Subject.file("a.json"), " "));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.volmit;
|
||||
|
||||
import com.volmit.config.*;
|
||||
import com.volmit.host.FeatureDescriptor;
|
||||
import com.volmit.host.OptionsMetadata;
|
||||
import com.volmit.resource.ResourceId;
|
||||
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", key = "fill", targets = Level.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 descriptorReadsFeatureIdentityAndAttachment() {
|
||||
var descriptor = FeatureDescriptor.of(FillOptions.class);
|
||||
assertEquals(ResourceId.parse("example:fill"), descriptor.id());
|
||||
assertEquals("fill", descriptor.key());
|
||||
assertEquals(java.util.Optional.empty(), descriptor.root());
|
||||
assertEquals(java.util.Set.of(Level.BIOME), descriptor.targets());
|
||||
assertEquals(1, descriptor.options().options().size());
|
||||
}
|
||||
|
||||
@Feature(id = "example:blank", name = "Blank", key = " ", targets = Level.BIOME)
|
||||
static class BlankKey implements IrisFeature {}
|
||||
|
||||
@Feature(id = "example:namespaced", name = "Namespaced", key = "example:namespaced", targets = Level.BIOME)
|
||||
static class NamespacedKey implements IrisFeature {}
|
||||
|
||||
@Feature(id = "example:list", name = "List", key = "items", root = "items", targets = Level.BIOME)
|
||||
static class ListRoot implements IrisFeature {
|
||||
private java.util.List<String> items = java.util.List.of();
|
||||
}
|
||||
|
||||
@Feature(id = "example:missing", name = "Missing", key = "missing", root = "absent", targets = Level.BIOME)
|
||||
static class RootNamingNoOption implements IrisFeature {
|
||||
private java.util.List<String> items = java.util.List.of();
|
||||
}
|
||||
|
||||
@Feature(id = "example:two", name = "Two", key = "two", root = "items", targets = Level.BIOME)
|
||||
static class RootWithAnotherOption implements IrisFeature {
|
||||
private java.util.List<String> items = java.util.List.of();
|
||||
private int unreachable = 1;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyIsAPlainFieldNameNotAnId() {
|
||||
var blank = assertThrows(IllegalArgumentException.class, () -> FeatureDescriptor.of(BlankKey.class));
|
||||
assertTrue(blank.getMessage().startsWith("Invalid key of feature example:blank: Field must not be blank"), blank.getMessage());
|
||||
var namespaced = assertThrows(IllegalArgumentException.class, () -> FeatureDescriptor.of(NamespacedKey.class));
|
||||
assertTrue(namespaced.getMessage().contains("Field example:namespaced contains ':'"), namespaced.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRootNamesTheOnlyOptionWhoseValueTheKeyHolds() {
|
||||
var descriptor = FeatureDescriptor.of(ListRoot.class);
|
||||
assertEquals("items", descriptor.key());
|
||||
assertEquals(java.util.Optional.of("items"), descriptor.root());
|
||||
|
||||
var absent = assertThrows(IllegalArgumentException.class, () -> FeatureDescriptor.of(RootNamingNoOption.class));
|
||||
assertEquals("Feature root 'absent' of " + RootNamingNoOption.class.getName() + " must name its only option, since the JSON"
|
||||
+ " under its key is that option's value; its options are [items]", absent.getMessage());
|
||||
var crowded = assertThrows(IllegalArgumentException.class, () -> FeatureDescriptor.of(RootWithAnotherOption.class));
|
||||
assertTrue(crowded.getMessage().endsWith("its options are [items, unreachable]"), crowded.getMessage());
|
||||
}
|
||||
|
||||
static class InvalidOptions {
|
||||
@MinNumber(10) @MaxNumber(2) private int value;
|
||||
}
|
||||
|
||||
static class NonnumericOptions {
|
||||
@MinNumber(0) private String value;
|
||||
}
|
||||
|
||||
static class MinItemsOnList {
|
||||
@MinItems(1) private java.util.List<String> values = java.util.List.of("a");
|
||||
@MinItems(2) private java.util.Set<String> unique = java.util.Set.of();
|
||||
@MinItems(0) private String[] array = {};
|
||||
}
|
||||
|
||||
static class MinItemsOnText {
|
||||
@MinItems(1) private String value;
|
||||
}
|
||||
|
||||
static class NegativeMinItems {
|
||||
@MinItems(-1) private java.util.List<String> values;
|
||||
}
|
||||
|
||||
@Test
|
||||
void minItemsFitsListsSetsAndArraysOnly() {
|
||||
var options = OptionsMetadata.inspect(MinItemsOnList.class).options();
|
||||
|
||||
assertEquals(java.util.List.of(1, 2, 0), options.stream().map(OptionsMetadata.Option::minItems).toList());
|
||||
assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(MinItemsOnText.class));
|
||||
assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(NegativeMinItems.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInconsistentAnnotationBounds() {
|
||||
assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(InvalidOptions.class));
|
||||
assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(NonnumericOptions.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.volmit;
|
||||
|
||||
import com.volmit.block.BlockSpec;
|
||||
import com.volmit.block.PaletteSpec;
|
||||
import com.volmit.host.OptionsMetadata;
|
||||
import com.volmit.config.Range;
|
||||
import com.volmit.noise.NoiseFactory;
|
||||
import com.volmit.noise.NoiseSampler;
|
||||
import com.volmit.noise.NoiseStyle;
|
||||
import com.volmit.noise.StyledRange;
|
||||
import com.volmit.random.WorldRandom;
|
||||
import com.volmit.vanilla.VanillaStructureRule;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import static com.volmit.vanilla.VanillaStructureRule.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** The value types settings hold and the rules of vanilla structure hooks. */
|
||||
class SettingsValuesTest {
|
||||
@Test
|
||||
void blockSpecsAreValuesWithTheDefaultsPacksGetWhenTheyLeaveOptionsOut() {
|
||||
var spec = BlockSpec.of("iron_ore").withProperty("waterlogged", "true").withWeight(3)
|
||||
.withBackup(BlockSpec.of("stone")).withTileData(Map.of("Delay", 20.0));
|
||||
|
||||
assertEquals("iron_ore", spec.block());
|
||||
assertEquals(Map.of("waterlogged", "true"), spec.data());
|
||||
assertEquals(3, spec.weight());
|
||||
assertEquals(Optional.of(BlockSpec.of("stone")), spec.backup());
|
||||
assertEquals(Map.of("Delay", 20.0), spec.tileData());
|
||||
assertEquals(spec, BlockSpec.of("iron_ore").withProperty("waterlogged", "true").withWeight(3)
|
||||
.withBackup(BlockSpec.of("stone")).withTileData(Map.of("Delay", 20.0)));
|
||||
assertNotEquals(spec, spec.withWeight(1));
|
||||
assertEquals(1, BlockSpec.of("stone").weight());
|
||||
assertEquals(Optional.empty(), BlockSpec.of("stone").backup());
|
||||
assertThrows(UnsupportedOperationException.class, () -> spec.data().clear());
|
||||
assertThrows(UnsupportedOperationException.class, () -> spec.tileData().clear());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noiseStylesNameTheHostsStyleAndAreFlatOnlyWithoutExpressionOrImageMap() {
|
||||
var simplex = NoiseStyle.of("SIMPLEX").withZoom(0.08);
|
||||
|
||||
assertEquals("SIMPLEX", simplex.style());
|
||||
assertEquals(0.08, simplex.zoom());
|
||||
assertEquals(1, NoiseStyle.of("SIMPLEX").zoom());
|
||||
assertEquals(simplex, NoiseStyle.of("SIMPLEX").withZoom(0.08));
|
||||
assertEquals(simplex.hashCode(), NoiseStyle.of("SIMPLEX").withZoom(0.08).hashCode());
|
||||
assertNotEquals(simplex, NoiseStyle.of("SIMPLEX"));
|
||||
assertTrue(NoiseStyle.of(NoiseStyle.FLAT).isFlat());
|
||||
assertFalse(simplex.isFlat());
|
||||
assertEquals(Optional.empty(), simplex.expression());
|
||||
assertEquals(Optional.empty(), simplex.fracture());
|
||||
}
|
||||
|
||||
@Test
|
||||
void palettesAreValuesWhoseDefaultsAreThoseOfIrisMaterialPalettes() {
|
||||
var options = OptionsMetadata.inspect(PaletteSpec.class);
|
||||
var palette = PaletteSpec.of(List.of(BlockSpec.of("stone"), BlockSpec.of("andesite").withWeight(2)));
|
||||
|
||||
assertEquals(List.of("style", "zoom", "palette"), options.options().stream().map(OptionsMetadata.Option::name).toList());
|
||||
assertEquals("palette", options.snippet());
|
||||
assertEquals(1, options.options().get(2).minItems());
|
||||
assertEquals(0.0001, options.options().get(1).minimum());
|
||||
assertEquals(NoiseStyle.of("STATIC"), palette.style());
|
||||
assertEquals(5, palette.zoom());
|
||||
assertEquals(palette.withZoom(8).withStyle(NoiseStyle.of("SIMPLEX")), palette.withStyle(NoiseStyle.of("SIMPLEX")).withZoom(8));
|
||||
assertNotEquals(palette, palette.withZoom(8));
|
||||
assertEquals(palette.hashCode(), PaletteSpec.of(palette.palette()).hashCode());
|
||||
assertThrows(UnsupportedOperationException.class, () -> palette.palette().clear());
|
||||
}
|
||||
|
||||
@Test
|
||||
void styledRangesPickBetweenTheirBoundsWithTheStylesNoise() {
|
||||
var asked = new ArrayList<String>();
|
||||
NoiseFactory noise = (style, seed) -> {
|
||||
asked.add(style.style() + "@" + seed);
|
||||
return fixed(0.25);
|
||||
};
|
||||
var styled = StyledRange.of(10, 30, NoiseStyle.of("SIMPLEX"));
|
||||
|
||||
assertEquals(15, styled.at(noise, 7, 100, 200));
|
||||
assertEquals(List.of("SIMPLEX@7"), asked);
|
||||
assertEquals(20, StyledRange.of(10, 30, NoiseStyle.of(NoiseStyle.FLAT)).at(noise, 7, 0, 0), "flat: halfway");
|
||||
assertEquals(10, StyledRange.of(10, 10, NoiseStyle.of("SIMPLEX")).at(noise, 7, 0, 0), "equal bounds");
|
||||
assertEquals(1, asked.size(), "neither flat nor equal bounds build noise");
|
||||
assertTrue(StyledRange.of(10, 10, NoiseStyle.of("SIMPLEX")).isFlat());
|
||||
assertFalse(styled.isFlat());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rangesIncludeBothBoundsAndPickWithOneDraw() {
|
||||
var range = Range.of(2, 6);
|
||||
|
||||
assertTrue(range.contains(2));
|
||||
assertTrue(range.contains(6));
|
||||
assertFalse(range.contains(6.5));
|
||||
var picks = new WorldRandom(42);
|
||||
var expected = new WorldRandom(42);
|
||||
assertEquals(2 + expected.nextDouble() * 4, range.pick(picks));
|
||||
assertEquals(expected.nextLong(), picks.nextLong(), "one draw per pick");
|
||||
assertEquals(3, Range.of(3, 3).pick(picks));
|
||||
assertEquals(expected.nextLong(), picks.nextLong(), "no draw when the bounds are equal");
|
||||
}
|
||||
|
||||
@Test
|
||||
void vanillaStructureRulesCombineBlockingAndPlacingWhateverTheOrder() {
|
||||
var expected = Map.of(
|
||||
List.of(GENERATE, GENERATE), GENERATE,
|
||||
List.of(GENERATE, ALSO_PLACE), ALSO_PLACE,
|
||||
List.of(GENERATE, BLOCK), BLOCK,
|
||||
List.of(ALSO_PLACE, BLOCK), REPLACE,
|
||||
List.of(GENERATE, REPLACE), REPLACE,
|
||||
List.of(BLOCK, BLOCK), BLOCK);
|
||||
expected.forEach((rules, combined) -> {
|
||||
assertEquals(combined, rules.get(0).and(rules.get(1)), rules.toString());
|
||||
assertEquals(combined, rules.get(1).and(rules.get(0)), rules.toString());
|
||||
});
|
||||
for (VanillaStructureRule rule : VanillaStructureRule.values()) {
|
||||
assertEquals(rule, rule.and(GENERATE), "GENERATE changes nothing");
|
||||
}
|
||||
assertTrue(REPLACE.blocksPlatform() && REPLACE.placedByModule());
|
||||
assertTrue(BLOCK.blocksPlatform() && !BLOCK.placedByModule());
|
||||
assertTrue(!ALSO_PLACE.blocksPlatform() && ALSO_PLACE.placedByModule());
|
||||
}
|
||||
|
||||
private static NoiseSampler fixed(double value) {
|
||||
return new NoiseSampler() {
|
||||
public double sample(double worldX, double worldZ) { return value; }
|
||||
public double sample(double worldX, double y, double worldZ) { return value; }
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.volmit;
|
||||
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.host.OptionsMetadata;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.service.LocateResult;
|
||||
import com.volmit.service.StructureLocator;
|
||||
import com.volmit.service.VanillaFeatures;
|
||||
import com.volmit.service.VanillaStructures;
|
||||
import com.volmit.vanilla.DecorationStep;
|
||||
import com.volmit.vanilla.JigsawOverrides;
|
||||
import com.volmit.vanilla.StartMemo;
|
||||
import com.volmit.vanilla.StartReach;
|
||||
import com.volmit.vanilla.TemplateCells;
|
||||
import com.volmit.vanilla.VanillaStructureContext;
|
||||
import com.volmit.vanilla.VanillaStructureRule;
|
||||
import com.volmit.vanilla.VanillaStructureSetup;
|
||||
import com.volmit.vanilla.VanillaStructureStart;
|
||||
import com.volmit.world.PackWorld;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** The values a vanilla structures provider answers with and how the host combines several modules' answers. */
|
||||
class VanillaStructureValuesTest {
|
||||
private static final ResourceId VILLAGES = ResourceId.parse("minecraft:villages");
|
||||
private static final ResourceId CITY = ResourceId.parse("minecraft:ancient_city");
|
||||
private static final ResourceId CASTLE = ResourceId.parse("test:castle");
|
||||
|
||||
@Test
|
||||
void jigsawOverridesKeepThePacksJsonNamesAndDefaults() {
|
||||
assertEquals(List.of("startPool", "startJigsawName", "maxDepth", "maxDistanceHorizontal", "maxDistanceVertical",
|
||||
"useExpansionHack", "projectStartToHeightmap", "dimensionPaddingBottom", "dimensionPaddingTop",
|
||||
"liquidSettings"), names(JigsawOverrides.class));
|
||||
assertEquals(OptionalInt.empty(), JigsawOverrides.none().maxDepth());
|
||||
assertEquals(Optional.empty(), JigsawOverrides.none().projectStartToHeightmap());
|
||||
assertEquals(Optional.empty(), JigsawOverrides.none().liquidSettings());
|
||||
assertEquals(Optional.empty(), JigsawOverrides.none().startPool());
|
||||
assertEquals(Optional.empty(), JigsawOverrides.none().startJigsawName());
|
||||
assertFalse(JigsawOverrides.none().removesStartJigsaw());
|
||||
assertEquals(Optional.of(JigsawOverrides.Liquids.IGNORE_WATERLOGGING),
|
||||
JigsawOverrides.none().withLiquids(JigsawOverrides.Liquids.IGNORE_WATERLOGGING).liquidSettings());
|
||||
var pool = com.volmit.resource.ResourceId.parse("minecraft:village/plains/town_centers");
|
||||
var overrides = JigsawOverrides.none().withStartPool(pool).withMaxDepth(4)
|
||||
.withMaxDistance(80, 120).withHeightmap(JigsawOverrides.Heightmap.NONE);
|
||||
assertEquals(Optional.of(pool), overrides.startPool());
|
||||
assertTrue(JigsawOverrides.none().withoutStartJigsaw().removesStartJigsaw());
|
||||
assertNotEquals(JigsawOverrides.none(), JigsawOverrides.none().withoutStartJigsaw());
|
||||
assertEquals(OptionalInt.of(4), overrides.maxDepth());
|
||||
assertEquals(OptionalInt.of(120), overrides.maxDistanceVertical());
|
||||
assertEquals(Optional.empty(), overrides.useExpansionHack());
|
||||
assertNotEquals(JigsawOverrides.none(), overrides);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reachesAreThePlatformsOrANumberOfBlocks() {
|
||||
assertTrue(StartReach.PLATFORM.platform());
|
||||
assertEquals(StartReach.blocks(0), StartReach.blocks(0));
|
||||
assertFalse(StartReach.blocks(12).platform());
|
||||
assertEquals(12, StartReach.blocks(12).blocks());
|
||||
assertThrows(IllegalArgumentException.class, () -> StartReach.blocks(-1));
|
||||
assertThrows(IllegalArgumentException.class, () -> new StartReach(true, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void templateCellsKeepTheirCellsAndMarkRemovedBlocks() {
|
||||
var stone = new BlockState("minecraft:stone");
|
||||
var cells = TemplateCells.of(new int[]{1, 2}, new int[]{60, 61}, new int[]{-3, -4}, new BlockState[]{stone, null}, 7);
|
||||
|
||||
assertTrue(cells.resolved());
|
||||
assertEquals(2, cells.size());
|
||||
assertEquals(7, cells.readBlocks());
|
||||
assertEquals(61, cells.y(1));
|
||||
assertSame(stone, cells.state(0));
|
||||
assertTrue(cells.removed(1));
|
||||
assertFalse(TemplateCells.UNRESOLVED.resolved());
|
||||
assertEquals(0, TemplateCells.UNRESOLVED.size());
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> TemplateCells.of(new int[]{1}, new int[0], new int[]{1}, new BlockState[]{stone}, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyTheUndergroundStepsAreUnderground() {
|
||||
assertEquals(List.of(DecorationStep.UNDERGROUND_STRUCTURES, DecorationStep.STRONGHOLDS, DecorationStep.UNDERGROUND_DECORATION),
|
||||
java.util.Arrays.stream(DecorationStep.values()).filter(DecorationStep::isUnderground).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setupsMultiplyFrequenciesAndProtectTheDefinitionsWhenEitherDoes() {
|
||||
var doubled = VanillaStructureSetup.UNCHANGED.withFrequency(VILLAGES, 2);
|
||||
var protecting = VanillaStructureSetup.UNCHANGED.withFrequency(VILLAGES, 1.5).protectingVanillaDefinitions();
|
||||
|
||||
assertEquals(3, doubled.and(protecting).frequency(VILLAGES));
|
||||
assertEquals(doubled.and(protecting), protecting.and(doubled));
|
||||
assertTrue(doubled.and(protecting).protectsVanillaDefinitions());
|
||||
assertEquals(1, doubled.frequency(CITY), "a set the setup leaves alone");
|
||||
assertEquals(4, doubled.withFrequency(VILLAGES, 4).frequency(VILLAGES), "the later multiplier of one setup wins");
|
||||
assertEquals(Map.of(VILLAGES, 2.0), doubled.frequencies());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startsSitOnTheSurfaceWithoutAMemoUnlessTheModuleSaysOtherwise() {
|
||||
var start = VanillaStructureStart.at(CITY, 12, -7, 40);
|
||||
|
||||
assertFalse(start.isUnderground());
|
||||
assertFalse(start.replacesPlatformStart());
|
||||
assertEquals(Optional.empty(), start.memo());
|
||||
var memo = new StartMemo("{\"mode\":\"VACUUM\"}");
|
||||
assertEquals(Optional.of(memo), start.withMemo(memo).memo());
|
||||
assertNotEquals(start, start.withMemo(memo));
|
||||
assertEquals(Optional.empty(), start.jigsaw());
|
||||
var underground = start.underground().replacingPlatformStart()
|
||||
.withJigsaw(JigsawOverrides.none().withMaxDepth(3));
|
||||
assertTrue(underground.isUnderground());
|
||||
assertTrue(underground.replacesPlatformStart());
|
||||
assertEquals(Optional.of(JigsawOverrides.none().withMaxDepth(3)), underground.jigsaw());
|
||||
assertEquals(underground, start.replacingPlatformStart().underground()
|
||||
.withJigsaw(JigsawOverrides.none().withMaxDepth(3)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aProviderThatOnlyRulesChangesNothingElse() {
|
||||
VanillaStructures provider = new VanillaStructures() {
|
||||
@Override
|
||||
public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) {
|
||||
return VanillaStructureRule.BLOCK;
|
||||
}
|
||||
};
|
||||
|
||||
assertEquals(VanillaStructureRule.BLOCK, provider.rule(CITY, null));
|
||||
assertEquals(List.of(), provider.starts(0, 0, null));
|
||||
assertEquals(0, provider.shift(null, null));
|
||||
assertEquals(StartReach.PLATFORM, provider.reach(CITY, true, Optional.empty(), null));
|
||||
assertEquals(VanillaStructureSetup.UNCHANGED, provider.setup(null));
|
||||
assertEquals(VanillaStructureRule.GENERATE, new VanillaStructures() { }.rule(CITY, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aLocatorPlacesWhatItCanLocateUnlessItSaysMore() {
|
||||
StructureLocator locator = new StructureLocator() {
|
||||
@Override
|
||||
public Set<ResourceId> structures(PackResources pack) {
|
||||
return Set.of(CASTLE, ResourceId.parse("test:tower"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<ResourceId> locatable(PackWorld world) {
|
||||
return Set.of(CASTLE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocateResult locate(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRadiusChunks) {
|
||||
return LocateResult.NOT_FOUND;
|
||||
}
|
||||
};
|
||||
|
||||
assertEquals(Set.of(CASTLE), locator.placed(null));
|
||||
assertEquals(Set.of(), locator.startedStructures(null), "a locator that starts no platform structure finds none");
|
||||
assertEquals(Set.of(), locator.locatableStarts(null));
|
||||
assertEquals(LocateResult.NOT_FOUND, locator.locateStart(null, CITY, 0, 0, 8, (chunkX, chunkZ) -> true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFeatureProviderThatSaysNothingLeavesThePlatformsFeaturesOff() {
|
||||
VanillaFeatures silent = new VanillaFeatures() { };
|
||||
|
||||
assertFalse(silent.generates(null));
|
||||
assertTrue(silent.generatesStep(null, Optional.of(DecorationStep.UNDERGROUND_ORES)));
|
||||
assertTrue(silent.generatesStep(null, Optional.empty()));
|
||||
assertTrue(silent.generatesFeature(null, ResourceId.parse("minecraft:ore_diamond")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyDecorationStepDescribesItselfForStudio() throws NoSuchFieldException {
|
||||
assertNotNull(DecorationStep.class.getAnnotation(com.volmit.config.Desc.class));
|
||||
for (DecorationStep step : DecorationStep.values()) {
|
||||
assertNotNull(DecorationStep.class.getField(step.name()).getAnnotation(com.volmit.config.Desc.class), step.name());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> names(Class<?> type) {
|
||||
return OptionsMetadata.inspect(type).options().stream().map(OptionsMetadata.Option::name).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.volmit.config;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.FeatureSettings.Entry;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.support.ColumnSettings;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SettingsStackTest {
|
||||
private static final ResourceId DIMENSION = ResourceId.parse("pack:dimension/overworld");
|
||||
private static final ResourceId REGION = ResourceId.parse("pack:region/temperate");
|
||||
private static final ResourceId PLAINS = ResourceId.parse("pack:biome/plains");
|
||||
private static final ResourceId SWAMP = ResourceId.parse("pack:biome/swamp");
|
||||
private static final ResourceId TREE = ResourceId.parse("pack:object/tree");
|
||||
|
||||
@Feature(id = "test:depth", name = "Depth", key = "depth", targets = {Level.DIMENSION, Level.REGION, Level.BIOME, Level.PLACEMENT})
|
||||
record Depth(int value) implements IrisFeature {}
|
||||
|
||||
private static Entry<Depth> entry(Level level, ResourceId source, int depth) {
|
||||
return new Entry<>(level, source, new Depth(depth));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sortsByLevelAndKeepsTheOrderWithinALevel() {
|
||||
var swamp = entry(Level.BIOME, SWAMP, 3);
|
||||
var plains = entry(Level.BIOME, PLAINS, 4);
|
||||
var region = entry(Level.REGION, REGION, 2);
|
||||
var dimension = entry(Level.DIMENSION, DIMENSION, 1);
|
||||
|
||||
var stack = SettingsStack.of(List.of(swamp, region, plains, dimension));
|
||||
|
||||
assertEquals(List.of(dimension, region, swamp, plains), stack.entries());
|
||||
assertEquals(List.of(1, 2, 3, 4), stack.values().stream().map(Depth::value).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void picksTheDimensionALevelOrTheMostSpecificValue() {
|
||||
var stack = SettingsStack.of(List.of(entry(Level.PLACEMENT, TREE, 9), entry(Level.BIOME, SWAMP, 3),
|
||||
entry(Level.BIOME, PLAINS, 4), entry(Level.DIMENSION, DIMENSION, 1)));
|
||||
|
||||
assertEquals(Optional.of(new Depth(1)), stack.dimension());
|
||||
assertEquals(Optional.of(new Depth(3)), stack.level(Level.BIOME), "the first entry of the level");
|
||||
assertEquals(Optional.empty(), stack.level(Level.REGION));
|
||||
assertEquals(Optional.of(new Depth(9)), stack.mostSpecific());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyStackHasNothingToPick() {
|
||||
var empty = SettingsStack.<Depth>of(List.of());
|
||||
|
||||
assertSame(SettingsStack.empty(), empty);
|
||||
assertTrue(empty.isEmpty());
|
||||
assertEquals(Optional.empty(), empty.dimension());
|
||||
assertEquals(Optional.empty(), empty.mostSpecific());
|
||||
assertEquals(List.of(), empty.values());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stacksOfEqualEntriesAreEqualAndImmutable() {
|
||||
var first = SettingsStack.of(List.of(entry(Level.BIOME, PLAINS, 4)));
|
||||
var second = SettingsStack.of(List.of(entry(Level.BIOME, PLAINS, 4)));
|
||||
|
||||
assertEquals(first, second);
|
||||
assertEquals(first.hashCode(), second.hashCode());
|
||||
assertThrows(UnsupportedOperationException.class, () -> first.entries().clear());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChunkDeclaresEveryDistinctEntryOfItsColumnsInLevelOrder() {
|
||||
var dimension = entry(Level.DIMENSION, DIMENSION, 1);
|
||||
var swamp = entry(Level.BIOME, SWAMP, 3);
|
||||
var plains = entry(Level.BIOME, PLAINS, 4);
|
||||
var settings = new ColumnSettings((x, z) -> List.of(Math.floorMod(x, 16) < 8 ? swamp : plains, dimension));
|
||||
|
||||
assertEquals(List.of(dimension, swamp, plains), settings.declaredInChunk(Depth.class, -1, 2).entries());
|
||||
assertTrue(ColumnSettings.NONE.declaredInChunk(Depth.class, 0, 0).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChunkReadsItsOwnColumnsOnly() {
|
||||
var plains = entry(Level.BIOME, PLAINS, 4);
|
||||
var onlyChunkOneZero = new ColumnSettings((x, z) -> x >= 16 && x < 32 && z >= 0 && z < 16 ? List.of(plains) : List.of());
|
||||
|
||||
assertEquals(List.of(plains), onlyChunkOneZero.declaredInChunk(Depth.class, 1, 0).entries());
|
||||
assertTrue(onlyChunkOneZero.declaredInChunk(Depth.class, 0, 0).isEmpty());
|
||||
assertTrue(onlyChunkOneZero.declaredInChunk(Depth.class, 2, 0).isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package com.volmit.example;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.config.Feature;
|
||||
import com.volmit.config.FeatureSettings.Entry;
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.example.chunk.GrassModule;
|
||||
import com.volmit.example.chunk.GrassSettings;
|
||||
import com.volmit.example.chunk.TerrainModule;
|
||||
import com.volmit.example.chunk.VeinModule;
|
||||
import com.volmit.example.chunk.VeinSettings;
|
||||
import com.volmit.host.ArrayHunk;
|
||||
import com.volmit.host.ChunkRunner;
|
||||
import com.volmit.host.DiscoveredModule;
|
||||
import com.volmit.host.LoadedModules;
|
||||
import com.volmit.host.MantleRunner;
|
||||
import com.volmit.host.StageTimings;
|
||||
import com.volmit.hunk.Hunk;
|
||||
import com.volmit.geometry.BlockBox;
|
||||
import com.volmit.mantle.CarvedVoid;
|
||||
import com.volmit.mantle.MantleLayer;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.stage.ChunkStageContext;
|
||||
import com.volmit.stage.Pipeline;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.support.ColumnSettings;
|
||||
import com.volmit.support.DeclaredSettings;
|
||||
import com.volmit.support.MemoryMantle;
|
||||
import com.volmit.support.TestContexts;
|
||||
import com.volmit.support.TestSetups;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiConsumer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** The chunk pipeline runs on the same graph machinery as placement; the mantle pipeline feeds it. */
|
||||
class ChunkPipelineTest {
|
||||
private static final int SIZE = 4;
|
||||
private static final int HEIGHT = 8;
|
||||
private static final int CHUNK = 16;
|
||||
private static final int BOTTOM = 0;
|
||||
private static final int TOP = 384;
|
||||
private static final BlockState AIR = new BlockState("minecraft:air");
|
||||
private static final BlockState GRASS = new BlockState("minecraft:grass_block");
|
||||
private static final ResourceId DIMENSION = ResourceId.parse("pack:dimension/overworld");
|
||||
private static final ResourceId PLAINS = ResourceId.parse("pack:biome/plains");
|
||||
private static final ResourceId SWAMP = ResourceId.parse("pack:biome/swamp");
|
||||
|
||||
@Feature(id = "test:levels", name = "Levels", key = "levels", targets = {Level.DIMENSION, Level.BIOME})
|
||||
static final class Marker implements IrisFeature {}
|
||||
|
||||
private static ChunkRunner runner() {
|
||||
var graph = TestSetups.stages(new GrassModule(), new TerrainModule()).resolve(Pipeline.CHUNK);
|
||||
assertEquals(List.of("iris:terrain/surface", "example:grass/top"),
|
||||
graph.stages().stream().map(stage -> stage.stage().id().toString()).toList());
|
||||
assertTrue(graph.blockPasses().isEmpty());
|
||||
return new ChunkRunner(graph);
|
||||
}
|
||||
|
||||
private static Hunk<BlockState> generate(ColumnSettings settings) {
|
||||
var blocks = new ArrayHunk<>(BlockState.class, SIZE, HEIGHT, SIZE, AIR);
|
||||
runner().generate(TestContexts.generation(blocks, settings, null), TestContexts.SEED, StageTimings.NONE);
|
||||
return blocks;
|
||||
}
|
||||
|
||||
private static Entry<GrassSettings> grass(ResourceId biome) {
|
||||
return new Entry<>(Level.BIOME, biome, new GrassSettings());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decorationReadsTerrainOutputWhenConfigured() {
|
||||
var blocks = generate(ColumnSettings.everywhere(grass(PLAINS)));
|
||||
|
||||
for (int x = 0; x < SIZE; x++) {
|
||||
for (int z = 0; z < SIZE; z++) {
|
||||
int height = TerrainModule.surfaceHeight(x, z);
|
||||
assertEquals(TerrainModule.STONE, blocks.get(x, height - 2, z));
|
||||
assertEquals(GRASS, blocks.get(x, height - 1, z));
|
||||
assertEquals(AIR, blocks.get(x, height, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void decorationIsInactiveWithoutItsSettings() {
|
||||
var blocks = generate(ColumnSettings.NONE);
|
||||
|
||||
int height = TerrainModule.surfaceHeight(0, 0);
|
||||
assertEquals(TerrainModule.STONE, blocks.get(0, height - 1, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStageRunsWhenAnyColumnHasItsSettingsAndReadsThemPerColumn() {
|
||||
var farCorner = new ColumnSettings((x, z) -> x == CHUNK - 1 && z == CHUNK - 1 ? List.of(grass(PLAINS)) : List.of());
|
||||
var blocks = generate(farCorner);
|
||||
assertEquals(TerrainModule.STONE, blocks.get(0, TerrainModule.surfaceHeight(0, 0) - 1, 0),
|
||||
"the stage ran because one column has grass, but this column has none");
|
||||
|
||||
var border = new ColumnSettings((x, z) -> x < 2 ? List.of(grass(PLAINS)) : List.of());
|
||||
blocks = generate(border);
|
||||
assertEquals(GRASS, blocks.get(1, TerrainModule.surfaceHeight(1, 0) - 1, 0));
|
||||
assertEquals(TerrainModule.STONE, blocks.get(2, TerrainModule.surfaceHeight(2, 0) - 1, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void levelsStackAndTheBodyGetsEveryDistinctEntryOfTheChunkInLevelOrder() {
|
||||
var dimension = new Entry<>(Level.DIMENSION, DIMENSION, new Marker());
|
||||
var plains = new Entry<>(Level.BIOME, PLAINS, new Marker());
|
||||
var swamp = new Entry<>(Level.BIOME, SWAMP, new Marker());
|
||||
var received = new ArrayList<List<ResourceId>>();
|
||||
var stage = Stage.chunk("test:levels/read");
|
||||
IrisModule module = new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:levels", "Levels", "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(stage).when(Marker.class).run(context -> {
|
||||
received.add(context.configured(Marker.class).entries().stream().map(Entry::source).toList());
|
||||
received.add(context.settings().at(Marker.class, 0, 0).entries().stream().map(Entry::source).toList());
|
||||
});
|
||||
}
|
||||
};
|
||||
var settings = new ColumnSettings((x, z) -> List.of(dimension, x < 8 ? swamp : plains));
|
||||
|
||||
new ChunkRunner(TestSetups.stages(module).resolve(Pipeline.CHUNK))
|
||||
.generate(TestContexts.generation(null,settings, null), TestContexts.SEED, StageTimings.NONE);
|
||||
|
||||
assertEquals(List.of(List.of(DIMENSION, SWAMP, PLAINS), List.of(DIMENSION, SWAMP)), received,
|
||||
"the body sees every level of every column, a column read that column's levels");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mantleStagesWriteBeyondTheirChunkAndChunkStagesReadTheirOwnPart() {
|
||||
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(new VeinModule())), Map.of(), Set.of(), Set.of());
|
||||
var vein = new Entry<>(Level.BIOME, PLAINS, new VeinSettings(12, 4));
|
||||
int reach = loaded.mantle().stages().getFirst().reachBlocks(new DeclaredSettings(vein));
|
||||
assertEquals(3, reach, "a 12 block vein from the centre column runs 3 blocks into the next chunk");
|
||||
var mantle = new MemoryMantle();
|
||||
var reachArea = new BlockBox(-reach, BOTTOM, -reach, CHUNK + reach, TOP, CHUNK + reach);
|
||||
|
||||
new MantleRunner(loaded.mantle()).generate(VeinModule.PLAN,
|
||||
TestContexts.mantle(0, 0, ColumnSettings.everywhere(vein), mantle.within(reachArea)), TestContexts.SEED, StageTimings.NONE);
|
||||
assertEquals(1, mantle.get(VeinModule.ORE, 18, 4, 7), "the vein runs on into the next chunk");
|
||||
|
||||
var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, AIR);
|
||||
var chunkArea = new BlockBox(0, BOTTOM, 0, CHUNK, TOP, CHUNK);
|
||||
new ChunkRunner(loaded.chunk()).generate(
|
||||
TestContexts.generation(blocks, ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED,
|
||||
StageTimings.NONE);
|
||||
assertEquals(VeinModule.ORE_BLOCK, blocks.get(7, 4, 7));
|
||||
assertEquals(VeinModule.ORE_BLOCK, blocks.get(15, 4, 7));
|
||||
assertEquals(AIR, blocks.get(6, 4, 7));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chunkStagesCopyTheBlocksPlacementsPlannedButCannotPlanAny() {
|
||||
var mantle = new MemoryMantle();
|
||||
var stone = new BlockState("minecraft:stone");
|
||||
mantle.plan(3, 2, 5, stone);
|
||||
mantle.plan(4, 2, 5, AIR);
|
||||
var chunkArea = new BlockBox(0, BOTTOM, 0, CHUNK, TOP, CHUNK);
|
||||
var copy = Stage.chunk("test:copy/insert");
|
||||
IrisModule module = new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:copy", "Copy", "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(copy).run(context -> {
|
||||
var blocks = context.blocks();
|
||||
context.mantle().blocks().visit(chunkArea, (x, y, z, block) -> blocks.set(x, y, z, block));
|
||||
});
|
||||
}
|
||||
};
|
||||
var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, GRASS);
|
||||
|
||||
new ChunkRunner(TestSetups.stages(module).resolve(Pipeline.CHUNK)).generate(
|
||||
TestContexts.generation(blocks, ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED,
|
||||
StageTimings.NONE);
|
||||
|
||||
assertEquals(stone, blocks.get(3, 2, 5));
|
||||
assertEquals(AIR, blocks.get(4, 2, 5), "air a placement planned replaces what the chunk had");
|
||||
assertEquals(GRASS, blocks.get(5, 2, 5));
|
||||
assertThrows(UnsupportedOperationException.class, () -> mantle.within(chunkArea).blocks().set(0, 0, 0, stone));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chunkStagesReadWhereTheMantleCarvedVoidsButCannotCarveAny() {
|
||||
var mantle = new MemoryMantle();
|
||||
mantle.carve(6, 9, 2);
|
||||
var chunkArea = new BlockBox(0, BOTTOM, 0, CHUNK, TOP, CHUNK);
|
||||
var carved = new ArrayList<String>();
|
||||
var probe = Stage.chunk("test:caves/probe");
|
||||
IrisModule module = new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:caves", "Caves", "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(probe).run(context -> {
|
||||
carved.add(String.valueOf(context.mantle().carved().get(6, 9, 2)));
|
||||
carved.add(String.valueOf(context.mantle().carved().get(6, 10, 2)));
|
||||
carved.add(assertThrows(UnsupportedOperationException.class,
|
||||
() -> context.mantle().carved().set(6, 10, 2, CarvedVoid.AIR)).getMessage());
|
||||
carved.add(assertThrows(UnsupportedOperationException.class,
|
||||
() -> context.mantle().carved().remove(6, 9, 2)).getMessage());
|
||||
});
|
||||
}
|
||||
};
|
||||
var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, AIR);
|
||||
|
||||
new ChunkRunner(TestSetups.stages(module).resolve(Pipeline.CHUNK)).generate(
|
||||
TestContexts.generation(blocks, ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED,
|
||||
StageTimings.NONE);
|
||||
|
||||
var cannotCarve = "Carved voids are planned by mantle stages (Stage.mantle), not by chunk stages";
|
||||
assertEquals(List.of(CarvedVoid.OPEN.toString(), "null", cannotCarve, cannotCarve), carved);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRunnerReportsHowLongEachStageThatRanTook() {
|
||||
var timed = new ArrayList<String>();
|
||||
var blocks = new ArrayHunk<>(BlockState.class, SIZE, HEIGHT, SIZE, AIR);
|
||||
|
||||
runner().generate(TestContexts.generation(blocks, ColumnSettings.NONE, null), TestContexts.SEED,
|
||||
(stage, nanos) -> timed.add(stage.stage().id() + (nanos >= 0 ? "" : " ran backwards")));
|
||||
|
||||
assertEquals(List.of("iris:terrain/surface"), timed, "grass has no settings here, so it does not run and is not reported");
|
||||
}
|
||||
|
||||
@Test
|
||||
void chunkStagesWriteTheMantleOfTheirOwnChunkOnly() {
|
||||
var mantle = new MemoryMantle();
|
||||
var aroundTheChunk = new BlockBox(-CHUNK, BOTTOM, -CHUNK, 2 * CHUNK, TOP, 2 * CHUNK);
|
||||
var graph = TestSetups.stages(oreWriter((context, layer) -> layer.set(15, 3, 0, 1))).resolve(Pipeline.CHUNK);
|
||||
|
||||
new ChunkRunner(graph).generate(TestContexts.generation(null,ColumnSettings.NONE, mantle.within(aroundTheChunk)),
|
||||
TestContexts.SEED, StageTimings.NONE);
|
||||
|
||||
assertEquals(1, mantle.get(VeinModule.ORE, 15, 3, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneChunkInvocationMakesItsMantleViewsOnce() {
|
||||
var mantle = new MemoryMantle();
|
||||
var aroundTheChunk = new BlockBox(-CHUNK, BOTTOM, -CHUNK, 2 * CHUNK, TOP, 2 * CHUNK);
|
||||
var views = new ArrayList<Object>();
|
||||
var graph = TestSetups.stages(oreWriter((context, layer) -> {
|
||||
views.add(context.mantle());
|
||||
views.add(context.mantle());
|
||||
views.add(layer);
|
||||
views.add(context.mantle().layer(VeinModule.ORE));
|
||||
views.add(context.mantle().blocks());
|
||||
views.add(context.mantle().blocks());
|
||||
})).resolve(Pipeline.CHUNK);
|
||||
|
||||
new ChunkRunner(graph).generate(TestContexts.generation(null,ColumnSettings.NONE, mantle.within(aroundTheChunk)),
|
||||
TestContexts.SEED, StageTimings.NONE);
|
||||
|
||||
assertSame(views.get(0), views.get(1));
|
||||
assertSame(views.get(2), views.get(3));
|
||||
assertSame(views.get(4), views.get(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chunkStagesReadTheirNeighboursMantleButCannotWriteIt() {
|
||||
var mantle = new MemoryMantle();
|
||||
var aroundTheChunk = new BlockBox(-CHUNK, BOTTOM, -CHUNK, 2 * CHUNK, TOP, 2 * CHUNK);
|
||||
var read = new ArrayList<Integer>();
|
||||
var graph = TestSetups.stages(oreWriter((context, layer) -> {
|
||||
read.add(layer.get(CHUNK, 0, 0));
|
||||
layer.set(CHUNK, 0, 0, 1);
|
||||
})).resolve(Pipeline.CHUNK);
|
||||
var inputs = TestContexts.generation(null,ColumnSettings.NONE, mantle.within(aroundTheChunk));
|
||||
|
||||
var failure = assertThrows(UnsupportedOperationException.class,
|
||||
() -> new ChunkRunner(graph).generate(inputs, TestContexts.SEED, StageTimings.NONE));
|
||||
assertEquals("A chunk stage writes the mantle of its own chunk only; write around it from a mantle stage"
|
||||
+ " (Stage.mantle), which runs before the chunks it reaches; 16,0,0 is outside BlockBox[minX=0, minY=0,"
|
||||
+ " minZ=0, maxX=16, maxY=384, maxZ=16]", failure.getMessage());
|
||||
assertEquals(Collections.singletonList(null), read, "the neighbour is read before the write fails");
|
||||
assertNull(mantle.get(VeinModule.ORE, CHUNK, 0, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chunkStagesSetPlatformBiomesInTheirOwnChunkOnly() {
|
||||
var mantle = new MemoryMantle();
|
||||
var aroundTheChunk = new BlockBox(-CHUNK, BOTTOM, -CHUNK, 2 * CHUNK, TOP, 2 * CHUNK);
|
||||
var sky = ResourceId.parse("minecraft:plains");
|
||||
var graph = TestSetups.stages(oreWriter((context, layer) -> {
|
||||
context.mantle().setPlatformBiome(15, 200, 0, sky);
|
||||
context.mantle().setPlatformBiome(CHUNK, 200, 0, sky);
|
||||
})).resolve(Pipeline.CHUNK);
|
||||
var inputs = TestContexts.generation(null, ColumnSettings.NONE, mantle.within(aroundTheChunk));
|
||||
|
||||
assertThrows(UnsupportedOperationException.class,
|
||||
() -> new ChunkRunner(graph).generate(inputs, TestContexts.SEED, StageTimings.NONE));
|
||||
assertEquals(sky, mantle.platformBiome(15, 200, 0));
|
||||
assertNull(mantle.platformBiome(CHUNK, 200, 0));
|
||||
}
|
||||
|
||||
private static IrisModule oreWriter(BiConsumer<ChunkStageContext, MantleLayer<Integer>> body) {
|
||||
var stage = Stage.chunk("test:writer/work");
|
||||
return new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:writer", "Writer", "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(stage).run(context -> body.accept(context, context.mantle().layer(VeinModule.ORE)));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package com.volmit.example;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.example.placement.*;
|
||||
import com.volmit.host.ConfiguredSettings;
|
||||
import com.volmit.host.LoadedModules;
|
||||
import com.volmit.host.PlacementRunner;
|
||||
import com.volmit.host.ResolvedGraph;
|
||||
import com.volmit.host.StageStreams;
|
||||
import com.volmit.host.StageTimings;
|
||||
import com.volmit.geometry.BlockBox;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.object.GeneratedObject;
|
||||
import com.volmit.object.ObjectBlock;
|
||||
import com.volmit.placement.PlacedBlock;
|
||||
import com.volmit.placement.PlacementRequest;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.stage.Pipeline;
|
||||
import com.volmit.stage.PlacementStage;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.support.MemoryEdit;
|
||||
import com.volmit.support.TestContexts;
|
||||
import com.volmit.support.TestSetups;
|
||||
import com.volmit.support.TestTerrain;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** The ported slice of Iris's place() lifecycle, composed only from module-owned stages. */
|
||||
class PlacementLifecyclePortTest {
|
||||
private static final ResourceId PLACEMENT = ResourceId.parse("pack:object/tree");
|
||||
private static final BlockState PLANKS = new BlockState("minecraft:oak_planks");
|
||||
private static final int ANCHOR_GROUND = 10;
|
||||
private static final int SURROUNDING_GROUND = 7;
|
||||
private static final BlockPosition SURFACE_ANCHOR = new BlockPosition(0, ANCHOR_GROUND, 0);
|
||||
|
||||
private static final List<String> EXPECTED_ORDER = List.of(
|
||||
"iris:prepare/transforms", "iris:anchor/height", "iris:prepare/rotate", "iris:blocks/write",
|
||||
"iris:snow/collect", "iris:stilt/bounds", "iris:blocks/complete", "iris:stilt/fill",
|
||||
"iris:snow/finish", "example:moss/spread");
|
||||
|
||||
private static final String EXPECTED_DESCRIPTION = """
|
||||
PLACEMENT pipeline: 10 stages, 1 block pass
|
||||
order:
|
||||
1. iris:prepare/transforms [invocation] module iris:prepare
|
||||
2. iris:anchor/height [invocation] module iris:anchor
|
||||
requires iris:prepare/transforms
|
||||
3. iris:prepare/rotate [block pass 1] module iris:prepare
|
||||
requires iris:prepare/transforms
|
||||
4. iris:blocks/write [block pass 1] module iris:blocks
|
||||
requires iris:anchor/height, iris:prepare/rotate
|
||||
5. iris:snow/collect [block pass 1] module iris:snow when iris:snow
|
||||
requires iris:blocks/write
|
||||
6. iris:stilt/bounds [block pass 1] module iris:stilt when iris:stilt
|
||||
requires iris:anchor/height, iris:prepare/rotate
|
||||
7. iris:blocks/complete [invocation] module iris:blocks
|
||||
requires iris:blocks/write
|
||||
8. iris:stilt/fill [invocation] module iris:stilt when iris:stilt
|
||||
requires iris:stilt/bounds, iris:blocks/complete
|
||||
9. iris:snow/finish [invocation] module iris:snow when iris:snow
|
||||
requires iris:snow/collect, iris:blocks/complete
|
||||
soft after iris:stilt/fill
|
||||
absent soft targets iris:vacuum/finish
|
||||
10. example:moss/spread [invocation] module example:moss when example:moss
|
||||
requires iris:anchor/height, iris:blocks/complete
|
||||
soft after iris:snow/finish
|
||||
block passes:
|
||||
pass 1: iris:prepare/rotate, iris:blocks/write, iris:snow/collect, iris:stilt/bounds
|
||||
mutually unordered:
|
||||
iris:anchor/height <-> iris:prepare/rotate
|
||||
iris:blocks/write <-> iris:stilt/bounds
|
||||
iris:snow/collect <-> iris:stilt/bounds
|
||||
iris:snow/collect <-> iris:blocks/complete
|
||||
iris:snow/collect <-> iris:stilt/fill
|
||||
iris:stilt/bounds <-> iris:blocks/complete
|
||||
""";
|
||||
|
||||
private static ResolvedGraph resolve(List<? extends IrisModule> modules) {
|
||||
return TestSetups.stages(modules.toArray(IrisModule[]::new)).resolve(Pipeline.PLACEMENT);
|
||||
}
|
||||
|
||||
private static List<String> order(ResolvedGraph graph) {
|
||||
return graph.stages().stream().map(stage -> stage.stage().id().toString()).toList();
|
||||
}
|
||||
|
||||
/** An L-shaped object: two bottom blocks and one block stacked on the second. */
|
||||
private static PlacementRequest request() {
|
||||
var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 2, 1), new BlockPosition(0, 0, 0),
|
||||
List.of(new ObjectBlock(new BlockPosition(0, 0, 0), PLANKS),
|
||||
new ObjectBlock(new BlockPosition(1, 0, 0), PLANKS),
|
||||
new ObjectBlock(new BlockPosition(1, 1, 0), PLANKS)),
|
||||
List.of());
|
||||
return new PlacementRequest(object,new BlockPosition(0, 0, 0));
|
||||
}
|
||||
|
||||
private static TestTerrain terrain() {
|
||||
return new TestTerrain((x, z) -> x == 0 && z == 0 ? ANCHOR_GROUND : SURROUNDING_GROUND);
|
||||
}
|
||||
|
||||
private static MemoryEdit place(ResolvedGraph graph, ConfiguredSettings settings) {
|
||||
var terrain = terrain();
|
||||
var edit = new MemoryEdit(terrain);
|
||||
var outcome = new PlacementRunner(graph).place(request(), edit, TestContexts.placement(terrain), TestContexts.SEED, settings,
|
||||
StageTimings.NONE);
|
||||
assertTrue(outcome.isPlaced());
|
||||
return edit;
|
||||
}
|
||||
|
||||
/** World position of a local block after the seeded rotation and surface anchoring. The rotation
|
||||
* is the first draw of the transforms stage's own stream.
|
||||
*/
|
||||
private static BlockPosition placed(int x, int y, int z) {
|
||||
var transforms = new Transforms(StageStreams.stream(TestContexts.SEED, PrepareModule.TRANSFORMS.id()).nextInt(4));
|
||||
var rotated = transforms.rotate(new BlockPosition(x, y, z), new BlockPosition(0, 0, 0));
|
||||
return rotated.add(SURFACE_ANCHOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesThePortedLifecycleWithOneFusedBlockPass() {
|
||||
var graph = resolve(PlacementModules.all());
|
||||
|
||||
assertEquals(EXPECTED_ORDER, order(graph));
|
||||
assertEquals(1, graph.blockPasses().size());
|
||||
assertEquals(EXPECTED_DESCRIPTION, graph.describe());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvedOrderIsIndependentOfModuleInstallOrder() {
|
||||
var expected = resolve(PlacementModules.all()).describe();
|
||||
var modules = new ArrayList<>(PlacementModules.all());
|
||||
Collections.reverse(modules);
|
||||
assertEquals(expected, resolve(modules).describe());
|
||||
for (long seed = 0; seed < 16; seed++) {
|
||||
Collections.shuffle(modules, new Random(seed));
|
||||
assertEquals(expected, resolve(modules).describe(), "install order " + modules);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void placesObjectThenStiltSnowAndMossFromTypedOutputs() {
|
||||
var edit = place(resolve(PlacementModules.all()),
|
||||
ConfiguredSettings.placement(PLACEMENT, new StiltSettings(), new SnowSettings(2), new MossSettings()));
|
||||
|
||||
var bottom = placed(0, 0, 0);
|
||||
var corner = placed(1, 0, 0);
|
||||
var top = placed(1, 1, 0);
|
||||
var snow = SnowModule.SNOW.withProperty("layers", "2");
|
||||
var expected = new HashMap<BlockPosition, BlockState>();
|
||||
expected.put(bottom, PLANKS);
|
||||
expected.put(corner, PLANKS);
|
||||
expected.put(top, PLANKS);
|
||||
for (int y = SURROUNDING_GROUND; y < ANCHOR_GROUND; y++) {
|
||||
expected.put(new BlockPosition(corner.x(), y, corner.z()), PLANKS);
|
||||
}
|
||||
expected.put(bottom.add(new BlockPosition(0, 1, 0)), snow);
|
||||
expected.put(top.add(new BlockPosition(0, 1, 0)), snow);
|
||||
expected.put(new BlockPosition(0, ANCHOR_GROUND - 1, 0), MossModule.MOSS);
|
||||
|
||||
assertTrue(edit.committed());
|
||||
assertEquals(expected, edit.published());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unconfiguredFeaturesStayInactiveWhileTheCoreStillPlaces() {
|
||||
var edit = place(resolve(PlacementModules.all()), ConfiguredSettings.none());
|
||||
|
||||
assertEquals(Map.of(placed(0, 0, 0), PLANKS, placed(1, 0, 0), PLANKS, placed(1, 1, 0), PLANKS), edit.published());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inactiveRequirementDeactivatesThirdPartyDependents() {
|
||||
var capModule = new IrisModule() {
|
||||
static final PlacementStage<Void> CAP = Stage.placement("example:cap/top");
|
||||
public ModuleInfo info() { return ModuleInfo.of("example:cap", "Cap", "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(CAP).requires(StiltModule.FILL).run(context -> context.access().set(
|
||||
new PlacedBlock(new BlockPosition(5, 20, 5), PLANKS, Optional.empty())));
|
||||
}
|
||||
};
|
||||
var modules = new ArrayList<IrisModule>(PlacementModules.all());
|
||||
modules.add(capModule);
|
||||
var graph = resolve(modules);
|
||||
|
||||
var withoutStilt = place(graph, ConfiguredSettings.placement(PLACEMENT, new SnowSettings(), new MossSettings()));
|
||||
assertEquals(TestTerrain.AIR, withoutStilt.publishedAt(5, 20, 5));
|
||||
assertEquals(MossModule.MOSS, withoutStilt.publishedAt(0, ANCHOR_GROUND - 1, 0));
|
||||
|
||||
var withStilt = place(graph, ConfiguredSettings.placement(PLACEMENT, new StiltSettings()));
|
||||
assertEquals(PLANKS, withStilt.publishedAt(5, 20, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadingThePortCatalogsEveryConditioningSettingsType() {
|
||||
var loaded = LoadedModules.load(PlacementModules.builtIns(), Map.of(), Set.of(), Set.of());
|
||||
|
||||
assertEquals(List.of("example:moss", "iris:snow", "iris:stilt"),
|
||||
loaded.catalog().settings().stream().map(settings -> settings.id().toString()).toList());
|
||||
assertEquals(EXPECTED_ORDER, order(loaded.placement()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.volmit.example.chunk;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.stage.ChunkStage;
|
||||
import com.volmit.stage.ChunkStageContext;
|
||||
import com.volmit.stage.Stage;
|
||||
|
||||
/** Third-party decoration: tops terrain columns using the terrain module's typed output. It runs where any
|
||||
* column of the chunk has grass and reads the settings per column, so a biome border inside the chunk
|
||||
* keeps grass on its own side.
|
||||
*/
|
||||
public final class GrassModule implements IrisModule {
|
||||
public static final ChunkStage<Void> TOP = Stage.chunk("example:grass/top");
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("example:grass", "Grass", "1.0.0");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(TOP)
|
||||
.when(GrassSettings.class)
|
||||
.requires(TerrainModule.SURFACE)
|
||||
.run(GrassModule::cover);
|
||||
}
|
||||
|
||||
private static void cover(ChunkStageContext context) {
|
||||
var heights = context.output(TerrainModule.SURFACE);
|
||||
var blocks = context.blocks();
|
||||
for (int x = 0; x < blocks.width(); x++) {
|
||||
for (int z = 0; z < blocks.depth(); z++) {
|
||||
var here = context.settings().at(GrassSettings.class, context.originX() + x, context.originZ() + z).mostSpecific();
|
||||
int height = heights.at(x, z);
|
||||
if (here.isEmpty() || height <= 0) {
|
||||
continue;
|
||||
}
|
||||
blocks.set(x, height - 1, z, here.get().block());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.volmit.example.chunk;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.config.Desc;
|
||||
import com.volmit.config.Feature;
|
||||
import com.volmit.config.Level;
|
||||
|
||||
@Desc("Covers the top of every terrain column")
|
||||
@Feature(id = "example:grass", name = "Grass", key = "grass", targets = Level.BIOME)
|
||||
public final class GrassSettings implements IrisFeature {
|
||||
@Desc("Block placed on top of each column")
|
||||
private BlockState block = new BlockState("minecraft:grass_block");
|
||||
|
||||
public BlockState block() {
|
||||
return block;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.volmit.example.chunk;
|
||||
|
||||
/** Per-chunk output: the first air y of each local column. */
|
||||
public final class SurfaceHeights {
|
||||
private final int width;
|
||||
private final int[] heights;
|
||||
|
||||
SurfaceHeights(int width, int depth) {
|
||||
this.width = width;
|
||||
heights = new int[width * depth];
|
||||
}
|
||||
|
||||
void set(int x, int z, int height) {
|
||||
heights[z * width + x] = height;
|
||||
}
|
||||
|
||||
public int at(int x, int z) {
|
||||
return heights[z * width + x];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.volmit.example.chunk;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.stage.ChunkStage;
|
||||
import com.volmit.stage.ChunkStageContext;
|
||||
import com.volmit.stage.Stage;
|
||||
|
||||
/** Core terrain shaping as an ordinary module: fills stone and reports surface heights. */
|
||||
public final class TerrainModule implements IrisModule {
|
||||
public static final ChunkStage<SurfaceHeights> SURFACE = Stage.chunk("iris:terrain/surface", SurfaceHeights.class);
|
||||
public static final BlockState STONE = new BlockState("minecraft:stone");
|
||||
private static final int BASE_HEIGHT = 3;
|
||||
private static final int RIPPLE = 3;
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("iris:terrain", "Terrain", "test");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(SURFACE).produce(TerrainModule::shape);
|
||||
}
|
||||
|
||||
public static int surfaceHeight(int worldX, int worldZ) {
|
||||
return BASE_HEIGHT + Math.floorMod(worldX + worldZ, RIPPLE);
|
||||
}
|
||||
|
||||
private static SurfaceHeights shape(ChunkStageContext context) {
|
||||
var blocks = context.blocks();
|
||||
var heights = new SurfaceHeights(blocks.width(), blocks.depth());
|
||||
for (int x = 0; x < blocks.width(); x++) {
|
||||
for (int z = 0; z < blocks.depth(); z++) {
|
||||
int height = Math.min(surfaceHeight(context.originX() + x, context.originZ() + z), blocks.height());
|
||||
for (int y = 0; y < height; y++) {
|
||||
blocks.set(x, y, z, STONE);
|
||||
}
|
||||
heights.set(x, z, height);
|
||||
}
|
||||
}
|
||||
return heights;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.volmit.example.chunk;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.generation.ChunkContext;
|
||||
import com.volmit.geometry.BlockBox;
|
||||
import com.volmit.data.StorageCodec;
|
||||
import com.volmit.mantle.MantleKey;
|
||||
import com.volmit.mantle.MantleLifetime;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.stage.ChunkStage;
|
||||
import com.volmit.stage.ChunkStageContext;
|
||||
import com.volmit.stage.MantleStage;
|
||||
import com.volmit.stage.MantleStageContext;
|
||||
import com.volmit.stage.Stage;
|
||||
import java.io.DataInput;
|
||||
import java.io.DataOutput;
|
||||
import java.io.IOException;
|
||||
|
||||
/** Work across chunks: a mantle stage plans veins into the mantle, past its own chunk, and a chunk stage
|
||||
* later turns its own chunk's part of the mantle into blocks. The two pipelines meet only in the mantle.
|
||||
* How far a vein runs past its chunk depends on the longest vein the pack configures, so the stage works
|
||||
* its reach out when the pack loads.
|
||||
*/
|
||||
public final class VeinModule implements IrisModule {
|
||||
public static final MantleKey<Integer> ORE = new MantleKey<>(ResourceId.parse("example:veins/ore"),Integer.class);
|
||||
public static final MantleStage PLAN = Stage.mantle("example:veins/plan");
|
||||
public static final ChunkStage<Void> PLACE = Stage.chunk("example:veins/place");
|
||||
public static final BlockState ORE_BLOCK = new BlockState("minecraft:iron_ore");
|
||||
private static final int PLANNED = 1;
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("example:veins", "Veins", "1.0.0");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.registry().registerMantle(ORE, MantleLifetime.GENERATION, new IntegerCodec());
|
||||
setup.stages().define(PLAN).when(VeinSettings.class).reach(VeinModule::reach).writesMantle(ORE).run(VeinModule::plan);
|
||||
setup.stages().define(PLACE).run(VeinModule::place);
|
||||
}
|
||||
|
||||
/** How far the longest vein any level of the pack declares runs past its chunk. */
|
||||
public static int reach(PackSettings settings) {
|
||||
int longest = settings.declared(VeinSettings.class).values().stream().mapToInt(VeinSettings::length).max().orElse(0);
|
||||
return Math.max(0, longest - (ChunkContext.CHUNK_WIDTH - ChunkContext.CENTRE_COLUMN));
|
||||
}
|
||||
|
||||
/** One vein per level that configures veins at the chunk's centre column: levels stack. */
|
||||
private static void plan(MantleStageContext context) {
|
||||
int startX = context.centreX();
|
||||
int z = context.centreZ();
|
||||
var ore = context.mantle().layer(ORE);
|
||||
for (var vein : context.settings().at(VeinSettings.class, startX, z).values()) {
|
||||
for (int step = 0; step < vein.length(); step++) {
|
||||
ore.set(startX + step, vein.y(), z, PLANNED);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void place(ChunkStageContext context) {
|
||||
var blocks = context.blocks();
|
||||
var chunk = new BlockBox(context.originX(), 0, context.originZ(),
|
||||
context.originX() + blocks.width(), blocks.height(), context.originZ() + blocks.depth());
|
||||
context.mantle().layer(ORE).visit(chunk, (x, y, z, planned) ->
|
||||
blocks.set(x - context.originX(), y, z - context.originZ(), ORE_BLOCK));
|
||||
}
|
||||
|
||||
private static final class IntegerCodec implements StorageCodec<Integer> {
|
||||
public int version() { return 0; }
|
||||
public void write(DataOutput output, Integer value) throws IOException { output.writeInt(value); }
|
||||
public Integer read(DataInput input, int storedVersion) throws IOException { return input.readInt(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.volmit.example.chunk;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.Desc;
|
||||
import com.volmit.config.Feature;
|
||||
import com.volmit.config.Level;
|
||||
|
||||
@Desc("Plans a horizontal ore vein from the centre of each chunk, which may run into the next chunk")
|
||||
@Feature(id = "example:veins", name = "Veins", key = "veins", targets = {Level.DIMENSION, Level.BIOME})
|
||||
public final class VeinSettings implements IrisFeature {
|
||||
@Desc("Blocks along X, starting at the chunk's centre column")
|
||||
private int length = 12;
|
||||
|
||||
@Desc("Height of the vein above the dimension's bottom")
|
||||
private int y = 4;
|
||||
|
||||
public VeinSettings() {}
|
||||
|
||||
public VeinSettings(int length, int y) {
|
||||
this.length = length;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
public int length() {
|
||||
return length;
|
||||
}
|
||||
|
||||
public int y() {
|
||||
return y;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.volmit.example.hosttypes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Stands for a host class such as Iris's material palette: the host describes it in studio itself. */
|
||||
public final class Palette {
|
||||
private List<String> blocks = List.of("minecraft:stone");
|
||||
private java.util.UUID anything;
|
||||
|
||||
public List<String> blocks() {
|
||||
return blocks;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.stage.PlacementStage;
|
||||
import com.volmit.stage.PlacementStageContext;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
|
||||
/** Port of PlacementModuleAnchor with center-height sampling: rest the anchor on the surface. */
|
||||
public final class AnchorModule implements IrisModule {
|
||||
public static final PlacementStage<AnchorResult> HEIGHT = Stage.placement("iris:anchor/height", AnchorResult.class);
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("iris:anchor", "Anchor", "test");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(HEIGHT)
|
||||
.requires(PrepareModule.TRANSFORMS)
|
||||
.produce(AnchorModule::restOnSurface);
|
||||
}
|
||||
|
||||
private static AnchorResult restOnSurface(PlacementStageContext context) {
|
||||
var requested = context.request().anchor();
|
||||
int firstAirAboveGround = context.placementTerrain().highest(requested.x(), requested.z(), false) + 1;
|
||||
return new AnchorResult(new BlockPosition(requested.x(), firstAirAboveGround, requested.z()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.placement.PlacementRequest;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
|
||||
/** The world position the object's local anchor is placed at. */
|
||||
public record AnchorResult(BlockPosition anchor) {
|
||||
public BlockPosition worldPosition(PlacementRequest request, BlockPosition local) {
|
||||
return new PlacementRequest(request.object(), anchor).worldPosition(local);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.placement.PlacedBlock;
|
||||
import com.volmit.stage.BlockStage;
|
||||
import com.volmit.stage.BlockStageContext;
|
||||
import com.volmit.stage.PlacementStage;
|
||||
import com.volmit.stage.Stage;
|
||||
|
||||
/** Port of PlacementModuleBlocks: write each transformed block; COMPLETE marks the pass done. */
|
||||
public final class BlocksModule implements IrisModule {
|
||||
public static final BlockStage<Void> WRITE = Stage.placementBlock("iris:blocks/write");
|
||||
/** Milestone: stages requiring it run after every object block has been written. */
|
||||
public static final PlacementStage<Void> COMPLETE = Stage.placement("iris:blocks/complete");
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("iris:blocks", "Blocks", "test");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
var stages = setup.stages();
|
||||
stages.define(WRITE)
|
||||
.requires(PrepareModule.ROTATE, AnchorModule.HEIGHT)
|
||||
.run(BlocksModule::write);
|
||||
stages.define(COMPLETE)
|
||||
.requires(WRITE)
|
||||
.run(context -> {});
|
||||
}
|
||||
|
||||
private static void write(BlockStageContext context) {
|
||||
var block = context.block();
|
||||
var position = context.output(AnchorModule.HEIGHT).worldPosition(context.request(), block.position());
|
||||
context.access().set(new PlacedBlock(position, block.state(), block.blockEntity()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.block.BlockState;
|
||||
|
||||
final class ExampleBlocks {
|
||||
static final BlockState AIR = new BlockState("minecraft:air");
|
||||
|
||||
private ExampleBlocks() {}
|
||||
|
||||
static boolean isAir(BlockState state) {
|
||||
return state.material().equals(AIR.material());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.stage.PlacementStage;
|
||||
import com.volmit.stage.PlacementStageContext;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.stage.StageRef;
|
||||
|
||||
/** Third-party module: turns the ground under the anchor into moss. It requires the core
|
||||
* anchor height (typed output) and block completion, and runs after snow only if snow exists.
|
||||
*/
|
||||
public final class MossModule implements IrisModule {
|
||||
public static final PlacementStage<Void> SPREAD = Stage.placement("example:moss/spread");
|
||||
public static final BlockState MOSS = new BlockState("minecraft:moss_block");
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("example:moss", "Moss", "1.0.0");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(SPREAD)
|
||||
.when(MossSettings.class)
|
||||
.requires(AnchorModule.HEIGHT, BlocksModule.COMPLETE)
|
||||
.softAfter(StageRef.of("iris:snow/finish"))
|
||||
.run(MossModule::spread);
|
||||
}
|
||||
|
||||
private static void spread(PlacementStageContext context) {
|
||||
var moss = context.configured(MossSettings.class).mostSpecific().orElseThrow(); // a placement declares its settings once
|
||||
var anchor = context.output(AnchorModule.HEIGHT).anchor();
|
||||
var access = context.access();
|
||||
int groundY = anchor.y() - 1;
|
||||
for (int dx = -moss.radius(); dx <= moss.radius(); dx++) {
|
||||
for (int dz = -moss.radius(); dz <= moss.radius(); dz++) {
|
||||
int x = anchor.x() + dx;
|
||||
int z = anchor.z() + dz;
|
||||
if (!ExampleBlocks.isAir(access.get(x, groundY, z))) {
|
||||
access.set(x, groundY, z, MOSS);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.Feature;
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.config.MinNumber;
|
||||
|
||||
@Feature(id = "example:moss", name = "Moss", key = "moss", targets = Level.PLACEMENT)
|
||||
public final class MossSettings implements IrisFeature {
|
||||
@MinNumber(0)
|
||||
private int radius;
|
||||
|
||||
public MossSettings() {}
|
||||
|
||||
public MossSettings(int radius) {
|
||||
this.radius = radius;
|
||||
}
|
||||
|
||||
public int radius() {
|
||||
return radius;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.host.DiscoveredModule;
|
||||
import java.util.List;
|
||||
|
||||
public final class PlacementModules {
|
||||
private PlacementModules() {}
|
||||
|
||||
/** The ported core lifecycle slice plus one third-party module. */
|
||||
public static List<IrisModule> all() {
|
||||
return List.of(new PrepareModule(), new AnchorModule(), new BlocksModule(),
|
||||
new StiltModule(), new SnowModule(), new MossModule());
|
||||
}
|
||||
|
||||
/** {@link #all()} as modules shipped with the host. */
|
||||
public static List<DiscoveredModule> builtIns() {
|
||||
return all().stream().map(DiscoveredModule::builtIn).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.object.ObjectBlock;
|
||||
import com.volmit.stage.BlockStage;
|
||||
import com.volmit.stage.BlockStageContext;
|
||||
import com.volmit.stage.PlacementStage;
|
||||
import com.volmit.stage.Stage;
|
||||
|
||||
/** Port of PlacementModulePreparation: choose transforms once, rotate each block in the pass. */
|
||||
public final class PrepareModule implements IrisModule {
|
||||
public static final PlacementStage<Transforms> TRANSFORMS = Stage.placement("iris:prepare/transforms", Transforms.class);
|
||||
public static final BlockStage<Void> ROTATE = Stage.placementBlock("iris:prepare/rotate");
|
||||
private static final int QUARTER_TURNS = 4;
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("iris:prepare", "Prepare", "test");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
var stages = setup.stages();
|
||||
stages.define(TRANSFORMS)
|
||||
.produce(context -> new Transforms(context.random().nextInt(QUARTER_TURNS)));
|
||||
stages.define(ROTATE)
|
||||
.requires(TRANSFORMS)
|
||||
.run(PrepareModule::rotate);
|
||||
}
|
||||
|
||||
private static void rotate(BlockStageContext context) {
|
||||
var transforms = context.output(TRANSFORMS);
|
||||
var block = context.block();
|
||||
var pivot = context.request().object().anchor();
|
||||
context.replace(new ObjectBlock(transforms.rotate(block.position(), pivot), block.state(), block.blockEntity()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/** Per-placement accumulator: the highest written world block of each column. */
|
||||
public final class SnowHeights {
|
||||
private final Map<Column, Integer> highest = new TreeMap<>();
|
||||
|
||||
public void include(BlockPosition written) {
|
||||
highest.merge(new Column(written.x(), written.z()), written.y(), Math::max);
|
||||
}
|
||||
|
||||
public List<BlockPosition> tops() {
|
||||
return highest.entrySet().stream()
|
||||
.map(entry -> new BlockPosition(entry.getKey().x(), entry.getValue(), entry.getKey().z()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private record Column(int x, int z) implements Comparable<Column> {
|
||||
@Override
|
||||
public int compareTo(Column other) {
|
||||
int result = Integer.compare(x, other.x);
|
||||
return result == 0 ? Integer.compare(z, other.z) : result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.stage.BlockStage;
|
||||
import com.volmit.stage.PlacementStage;
|
||||
import com.volmit.stage.PlacementStageContext;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.stage.StageRef;
|
||||
|
||||
/** Port of PlacementModuleSnow: collect written tops, then cover them after the finishing work
|
||||
* of whichever stilt or vacuum module is installed (soft, so neither is required).
|
||||
*/
|
||||
public final class SnowModule implements IrisModule {
|
||||
public static final BlockStage<SnowHeights> COLLECT = Stage.placementBlock("iris:snow/collect", SnowHeights.class);
|
||||
public static final PlacementStage<Void> FINISH = Stage.placement("iris:snow/finish");
|
||||
public static final BlockState SNOW = new BlockState("minecraft:snow");
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("iris:snow", "Snow", "test");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
var stages = setup.stages();
|
||||
stages.define(COLLECT)
|
||||
.when(SnowSettings.class)
|
||||
.requires(BlocksModule.WRITE)
|
||||
.accumulate(SnowHeights::new, (context, heights) -> heights.include(
|
||||
context.output(AnchorModule.HEIGHT).worldPosition(context.request(), context.block().position())));
|
||||
stages.define(FINISH)
|
||||
.when(SnowSettings.class)
|
||||
.requires(COLLECT, BlocksModule.COMPLETE)
|
||||
.softAfter(StageRef.of("iris:stilt/fill"), StageRef.of("iris:vacuum/finish"))
|
||||
.run(SnowModule::cover);
|
||||
}
|
||||
|
||||
private static void cover(PlacementStageContext context) {
|
||||
var snow = context.configured(SnowSettings.class).mostSpecific().orElseThrow(); // a placement declares its settings once
|
||||
var layer = SNOW.withProperty("layers", Integer.toString(snow.layers()));
|
||||
var access = context.access();
|
||||
for (var top : context.output(COLLECT).tops()) {
|
||||
int aboveY = top.y() + 1;
|
||||
if (ExampleBlocks.isAir(access.get(top.x(), aboveY, top.z()))) {
|
||||
access.set(top.x(), aboveY, top.z(), layer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.Feature;
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.config.MaxNumber;
|
||||
import com.volmit.config.MinNumber;
|
||||
|
||||
@Feature(id = "iris:snow", name = "Snow", key = "snow", targets = Level.PLACEMENT)
|
||||
public final class SnowSettings implements IrisFeature {
|
||||
@MinNumber(1)
|
||||
@MaxNumber(8)
|
||||
private int layers = 1;
|
||||
|
||||
public SnowSettings() {}
|
||||
|
||||
public SnowSettings(int layers) {
|
||||
this.layers = layers;
|
||||
}
|
||||
|
||||
public int layers() {
|
||||
return layers;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.object.ObjectBlock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Per-placement accumulator: the transformed blocks of the object's lowest layer. */
|
||||
public final class StiltBounds {
|
||||
private int lowestY = Integer.MAX_VALUE;
|
||||
private final List<ObjectBlock> lowestLayer = new ArrayList<>();
|
||||
|
||||
public void include(ObjectBlock block) {
|
||||
int y = block.position().y();
|
||||
if (y < lowestY) {
|
||||
lowestY = y;
|
||||
lowestLayer.clear();
|
||||
}
|
||||
if (y == lowestY) {
|
||||
lowestLayer.add(block);
|
||||
}
|
||||
}
|
||||
|
||||
public List<ObjectBlock> lowestLayer() {
|
||||
return List.copyOf(lowestLayer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.object.ObjectBlock;
|
||||
import com.volmit.stage.BlockStage;
|
||||
import com.volmit.stage.PlacementStage;
|
||||
import com.volmit.stage.PlacementStageContext;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
|
||||
/** Port of PlacementModuleStilt: collect the lowest layer per block, then fill down after writes. */
|
||||
public final class StiltModule implements IrisModule {
|
||||
public static final BlockStage<StiltBounds> BOUNDS = Stage.placementBlock("iris:stilt/bounds", StiltBounds.class);
|
||||
public static final PlacementStage<Void> FILL = Stage.placement("iris:stilt/fill");
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("iris:stilt", "Stilts", "test");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
var stages = setup.stages();
|
||||
stages.define(BOUNDS)
|
||||
.when(StiltSettings.class)
|
||||
.requires(PrepareModule.ROTATE, AnchorModule.HEIGHT)
|
||||
.accumulate(StiltBounds::new, (context, bounds) -> bounds.include(context.block()));
|
||||
stages.define(FILL)
|
||||
.when(StiltSettings.class)
|
||||
.requires(BOUNDS, BlocksModule.COMPLETE)
|
||||
.run(StiltModule::fill);
|
||||
}
|
||||
|
||||
private static void fill(PlacementStageContext context) {
|
||||
var stilt = context.configured(StiltSettings.class).mostSpecific().orElseThrow(); // a placement declares its settings once
|
||||
var anchor = context.output(AnchorModule.HEIGHT);
|
||||
for (var block : context.output(BOUNDS).lowestLayer()) {
|
||||
var bottom = anchor.worldPosition(context.request(), block.position());
|
||||
fillColumnBelow(context, bottom, block, stilt.maxDepth());
|
||||
}
|
||||
}
|
||||
|
||||
private static void fillColumnBelow(PlacementStageContext context, BlockPosition bottom,
|
||||
ObjectBlock source, int maxDepth) {
|
||||
var access = context.access();
|
||||
for (int depth = 1; depth <= maxDepth; depth++) {
|
||||
int y = bottom.y() - depth;
|
||||
if (y < access.bounds().minY() || !ExampleBlocks.isAir(access.get(bottom.x(), y, bottom.z()))) {
|
||||
return;
|
||||
}
|
||||
access.set(bottom.x(), y, bottom.z(), source.state());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.Desc;
|
||||
import com.volmit.config.Feature;
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.config.MinNumber;
|
||||
|
||||
@Desc("Fills the space below an object down to the ground")
|
||||
@Feature(id = "iris:stilt", name = "Stilt", key = "stilt", targets = Level.PLACEMENT)
|
||||
public final class StiltSettings implements IrisFeature {
|
||||
@Desc("Maximum blocks filled below each lowest object block")
|
||||
@MinNumber(1)
|
||||
private int maxDepth = 16;
|
||||
|
||||
public StiltSettings() {}
|
||||
|
||||
public StiltSettings(int maxDepth) {
|
||||
this.maxDepth = maxDepth;
|
||||
}
|
||||
|
||||
public int maxDepth() {
|
||||
return maxDepth;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.volmit.example.placement;
|
||||
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
|
||||
/** Placement-wide rotation chosen once per attempt, like Iris's spin kernel. */
|
||||
public record Transforms(int quarterTurns) {
|
||||
/** Rotates a local position clockwise around the pivot's vertical axis. */
|
||||
public BlockPosition rotate(BlockPosition local, BlockPosition pivot) {
|
||||
int dx = local.x() - pivot.x();
|
||||
int dz = local.z() - pivot.z();
|
||||
for (int turn = 0; turn < quarterTurns; turn++) {
|
||||
int rotatedX = -dz;
|
||||
dz = dx;
|
||||
dx = rotatedX;
|
||||
}
|
||||
return new BlockPosition(pivot.x() + dx, local.y(), pivot.z() + dz);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.volmit.example.terrain;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
|
||||
/** A built-in module whose settings use host types; it only registers them. */
|
||||
public final class LayersModule implements IrisModule {
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("iris:layers", "Layers", "test");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.registry().registerSettings(LayersSettings.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.volmit.example.terrain;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.Desc;
|
||||
import com.volmit.config.Feature;
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.example.hosttypes.Palette;
|
||||
import java.util.List;
|
||||
|
||||
/** Built-in settings holding host types, written in pack JSON as a bare list: {@code "layers": [...]}. */
|
||||
@Feature(id = "iris:layers", name = "Layers", key = "layers", targets = Level.BIOME)
|
||||
public final class LayersSettings implements IrisFeature {
|
||||
@Desc("Rock layers from the surface down")
|
||||
private List<Palette> layers = List.of();
|
||||
|
||||
public List<Palette> layers() {
|
||||
return layers;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.volmit.example.world;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleLifecycle;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.host.ChunkRunner;
|
||||
import com.volmit.host.DiscoveredModule;
|
||||
import com.volmit.host.LifecycleRunner;
|
||||
import com.volmit.host.LoadedModules;
|
||||
import com.volmit.host.StageTimings;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.service.ObjectsAt;
|
||||
import com.volmit.stage.ChunkStage;
|
||||
import com.volmit.stage.ChunkStageContext;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.support.ColumnSettings;
|
||||
import com.volmit.support.TestContexts;
|
||||
import com.volmit.support.TestWorld;
|
||||
import com.volmit.world.PackWorld;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** A module that remembers, per world, which chunks it planted ruins in: its chunk stage writes the world's state,
|
||||
* its {@link ObjectsAt} service reads it, and its lifecycle builds the state when the world starts.
|
||||
*/
|
||||
class WorldStateExampleTest {
|
||||
static final class RuinsModule implements IrisModule, ModuleLifecycle {
|
||||
static final ChunkStage<Void> PLANT = Stage.chunk("example:ruins/plant");
|
||||
static final ResourceId ARCH = new ResourceId("test", "ruins/arch");
|
||||
|
||||
/** What ruins keeps per world. A field of the module would be shared by every world. */
|
||||
static final class PlantedChunks {
|
||||
final long seed;
|
||||
final Set<Long> chunks = ConcurrentHashMap.newKeySet();
|
||||
|
||||
PlantedChunks(PackWorld world) {
|
||||
this.seed = world.seed();
|
||||
}
|
||||
}
|
||||
|
||||
public ModuleInfo info() { return ModuleInfo.of("example:ruins", "Ruins", "1"); }
|
||||
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(PLANT).run(RuinsModule::plant);
|
||||
var registry = setup.registry();
|
||||
registry.registerLifecycle(this);
|
||||
registry.registerService(ObjectsAt.class, new ObjectsAt() {
|
||||
@Override
|
||||
public Set<ResourceId> objectsAt(PackWorld world, int chunkX, int chunkZ) {
|
||||
return RuinsModule.objectsAt(world, chunkX, chunkZ);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlacedBy placedBy(PackWorld world, ResourceId object) {
|
||||
return PlacedBy.NOTHING;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void worldStarted(PackWorld world) {
|
||||
planted(world);
|
||||
}
|
||||
|
||||
static PlantedChunks planted(PackWorld world) {
|
||||
return world.state(PlantedChunks.class, PlantedChunks::new);
|
||||
}
|
||||
|
||||
private static void plant(ChunkStageContext context) {
|
||||
planted(context.world()).chunks.add(key(context.chunkX(), context.chunkZ()));
|
||||
}
|
||||
|
||||
private static Set<ResourceId> objectsAt(PackWorld world, int chunkX, int chunkZ) {
|
||||
return planted(world).chunks.contains(key(chunkX, chunkZ)) ? Set.of(ARCH) : Set.of();
|
||||
}
|
||||
|
||||
private static long key(int chunkX, int chunkZ) {
|
||||
return ((long) chunkX << 32) ^ (chunkZ & 0xFFFFFFFFL);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stagesServicesAndHooksShareTheStateOfTheirWorldAndANewWorldStartsEmpty() {
|
||||
var pack = LoadedModules.load(List.of(DiscoveredModule.builtIn(new RuinsModule())), Map.of(), Set.of(), Set.of());
|
||||
var lifecycles = new LifecycleRunner(pack.catalog());
|
||||
ObjectsAt objects = pack.catalog().services(ObjectsAt.class).getFirst();
|
||||
|
||||
try (var world = new TestWorld()) {
|
||||
lifecycles.worldStarted(world);
|
||||
var startedWith = RuinsModule.planted(world);
|
||||
assertEquals(TestContexts.SEED, startedWith.seed);
|
||||
|
||||
new ChunkRunner(pack.chunk()).generate(TestContexts.generation(null,ColumnSettings.NONE, null, world), TestContexts.SEED,
|
||||
StageTimings.NONE);
|
||||
|
||||
assertSame(startedWith, RuinsModule.planted(world), "the stage used the state the hook built");
|
||||
assertEquals(Set.of(RuinsModule.ARCH), objects.objectsAt(world, 0, 0));
|
||||
assertEquals(Set.of(), objects.objectsAt(world, 1, 0));
|
||||
lifecycles.worldStopped(world);
|
||||
}
|
||||
|
||||
try (var reloaded = new TestWorld()) {
|
||||
assertEquals(Set.of(), objects.objectsAt(reloaded, 0, 0), "a new world starts with empty state");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.Feature;
|
||||
import com.volmit.config.FeatureSettings.Entry;
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ConfiguredSettingsTest {
|
||||
private static final ResourceId DIMENSION = ResourceId.parse("pack:dimension/overworld");
|
||||
private static final ResourceId BIOME = ResourceId.parse("pack:biome/plains");
|
||||
private static final ResourceId OBJECT = ResourceId.parse("pack:object/tree");
|
||||
|
||||
@Feature(id = "test:levels", name = "Levels", key = "levels", targets = {Level.DIMENSION, Level.BIOME, Level.PLACEMENT})
|
||||
static final class Levels implements IrisFeature {}
|
||||
|
||||
@Feature(id = "test:other", name = "Other", key = "other", targets = Level.BIOME)
|
||||
static final class Other implements IrisFeature {}
|
||||
|
||||
@Test
|
||||
void entriesAreGroupedByTypeInLevelOrderAndNeverMerged() {
|
||||
var biome = new Entry<>(Level.BIOME, BIOME, new Levels());
|
||||
var dimension = new Entry<>(Level.DIMENSION, DIMENSION, new Levels());
|
||||
|
||||
var settings = ConfiguredSettings.of(List.of(biome, dimension));
|
||||
|
||||
assertEquals(List.of(dimension, biome), settings.find(Levels.class).entries());
|
||||
assertTrue(settings.find(Other.class).isEmpty());
|
||||
assertTrue(ConfiguredSettings.none().find(Levels.class).isEmpty());
|
||||
}
|
||||
|
||||
@Feature(id = "test:base", name = "Base", key = "base", targets = {Level.BIOME, Level.PLACEMENT})
|
||||
static class Base implements IrisFeature {}
|
||||
|
||||
static final class Refined extends Base {}
|
||||
|
||||
@Test
|
||||
void aSubclassValueIsFoundUnderTheTypeThatDeclaresItsFeature() {
|
||||
var refined = new Entry<>(Level.BIOME, BIOME, new Refined());
|
||||
|
||||
assertEquals(List.of(refined), ConfiguredSettings.of(List.of(refined)).find(Base.class).entries());
|
||||
var twice = assertThrows(IllegalArgumentException.class, () -> ConfiguredSettings.placement(OBJECT, new Base(), new Refined()));
|
||||
assertEquals("Settings configured twice: " + Base.class.getName(), twice.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlacementDeclaresEachTypeOnce() {
|
||||
var levels = new Levels();
|
||||
assertEquals(List.of(new Entry<>(Level.PLACEMENT, OBJECT, levels)),
|
||||
ConfiguredSettings.placement(OBJECT, levels).find(Levels.class).entries());
|
||||
var twice = assertThrows(IllegalArgumentException.class, () -> ConfiguredSettings.placement(OBJECT, new Levels(), new Levels()));
|
||||
assertEquals("Settings configured twice: " + Levels.class.getName(), twice.getMessage());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.stage.Stage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class DiscoveredModuleTest {
|
||||
/** Answers with its first identity once, then with another one. */
|
||||
private static final class ShiftingIdentity implements IrisModule {
|
||||
private int infoCalls;
|
||||
|
||||
public ModuleInfo info() {
|
||||
infoCalls++;
|
||||
return infoCalls == 1 ? ModuleInfo.of("first:core", "First", "1") : ModuleInfo.of("second:core", "Second", "2");
|
||||
}
|
||||
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(Stage.placement("first:core/mark")).run(context -> {});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void builtInReadsInfoOnceAndLoadingUsesOnlyThatValue() {
|
||||
var module = new ShiftingIdentity();
|
||||
var discovered = DiscoveredModule.builtIn(module);
|
||||
|
||||
var loaded = LoadedModules.load(List.of(discovered), Map.of(), Set.of(), Set.of());
|
||||
|
||||
assertEquals("first:core", discovered.info().id().toString());
|
||||
assertEquals(List.of("first:core/mark"),
|
||||
loaded.placement().stages().stream().map(stage -> stage.stage().id().toString()).toList());
|
||||
assertEquals(1, module.infoCalls);
|
||||
}
|
||||
|
||||
@Test
|
||||
void builtInWhoseInfoIsNullFailsNamingTheClass() {
|
||||
var module = new IrisModule() {
|
||||
public ModuleInfo info() { return null; }
|
||||
public void setup(ModuleSetup setup) {}
|
||||
};
|
||||
|
||||
var error = assertThrows(NullPointerException.class, () -> DiscoveredModule.builtIn(module));
|
||||
|
||||
assertTrue(error.getMessage().contains(module.getClass().getName()), error.getMessage());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import example.builtin.CarveModule;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ExposedHostClassLoaderTest {
|
||||
private static final ClassLoader HOST = IrisModule.class.getClassLoader();
|
||||
private static final String HOST_LIBRARY_SERVICE_FILE = "META-INF/services/org.junit.platform.engine.TestEngine";
|
||||
|
||||
private final ExposedHostClassLoader loader = new ExposedHostClassLoader(HOST, ExposedPackages.apiOnly());
|
||||
|
||||
private static String classFile(Class<?> type) {
|
||||
return type.getName().replace('.', '/') + ".class";
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsApiClassesFromTheHostAndJdkClassesFromThePlatform() throws Exception {
|
||||
assertSame(IrisModule.class, loader.loadClass(IrisModule.class.getName()));
|
||||
assertSame(List.class, loader.loadClass(List.class.getName()));
|
||||
assertSame(java.sql.Connection.class, loader.loadClass(java.sql.Connection.class.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void hidesHostClassesOutsideTheExposedPackages() {
|
||||
assertDoesNotThrow(() -> HOST.loadClass(Test.class.getName()));
|
||||
assertThrows(ClassNotFoundException.class, () -> loader.loadClass(Test.class.getName()));
|
||||
assertThrows(ClassNotFoundException.class, () -> loader.loadClass(CarveModule.class.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsClassesAndResourcesOfExtraExposedPackagesFromTheHost() throws Exception {
|
||||
var exposing = new ExposedHostClassLoader(HOST, ExposedPackages.apiAnd(List.of(CarveModule.class.getPackageName())));
|
||||
|
||||
assertSame(CarveModule.class, exposing.loadClass(CarveModule.class.getName()));
|
||||
assertSame(IrisModule.class, exposing.loadClass(IrisModule.class.getName()));
|
||||
assertNotNull(exposing.getResource(classFile(CarveModule.class)));
|
||||
assertTrue(exposing.hasClass(CarveModule.class.getName()));
|
||||
assertThrows(ClassNotFoundException.class, () -> exposing.loadClass(Test.class.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourcesFollowTheSameRuleAsClasses() throws Exception {
|
||||
assertNotNull(loader.getResource(classFile(IrisModule.class)));
|
||||
assertNotNull(loader.getResource(classFile(List.class)));
|
||||
assertNull(loader.getResource(classFile(Test.class)));
|
||||
assertNull(loader.getResource(classFile(CarveModule.class)));
|
||||
assertFalse(Collections.list(HOST.getResources(HOST_LIBRARY_SERVICE_FILE)).isEmpty());
|
||||
assertTrue(Collections.list(loader.getResources(HOST_LIBRARY_SERVICE_FILE)).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void knowsWhichClassesItHasWithoutLoadingThem() {
|
||||
assertTrue(loader.hasClass(IrisModule.class.getName()));
|
||||
assertTrue(loader.hasClass("java.lang.String"));
|
||||
assertFalse(loader.hasClass(Test.class.getName()));
|
||||
assertFalse(loader.hasClass("com.volmit.DoesNotExist"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void knowsWhichClassesTheHostHasEvenWhenItHidesThem() {
|
||||
assertTrue(loader.hostHasClass(Test.class.getName()));
|
||||
assertTrue(loader.hostHasClass(IrisModule.class.getName()));
|
||||
assertFalse(loader.hostHasClass("org.nowhere.Missing"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ExposedPackagesTest {
|
||||
@Test
|
||||
void apiIsAlwaysExposedWithItsSubpackages() {
|
||||
var exposed = ExposedPackages.apiOnly();
|
||||
|
||||
assertEquals("com.volmit", ExposedPackages.API_PACKAGE);
|
||||
assertTrue(exposed.exposes("com.volmit.IrisModule"));
|
||||
assertTrue(exposed.exposes("com.volmit.stage.Stage"));
|
||||
assertTrue(ExposedPackages.apiAnd(List.of("example.builtin")).exposes("com.volmit.IrisModule"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHostSideIsNeverExposed() {
|
||||
var exposed = ExposedPackages.apiAnd(List.of("com"));
|
||||
|
||||
assertEquals("com.volmit.host", ExposedPackages.HOST_PACKAGE);
|
||||
assertFalse(exposed.exposes("com.volmit.host.PackModules"));
|
||||
assertFalse(exposed.exposes("com.volmit.host.schema.PackSchema"));
|
||||
assertFalse(exposed.exposesResource("com/volmit/host/PackModules.class"));
|
||||
assertTrue(exposed.exposes("com.volmit.hosting.Other"));
|
||||
assertTrue(ExposedPackages.isApiClass("com.volmit.host.PackModules"));
|
||||
|
||||
var failure = assertThrows(IllegalArgumentException.class,
|
||||
() -> ExposedPackages.apiAnd(List.of("com.volmit.host.schema")));
|
||||
assertEquals("Exposed package 'com.volmit.host.schema' is IrisApi's host side, which packs never see", failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void platformToolingPackagesAreNeverExposedButTheNeutralToolingApiIs() {
|
||||
var exposed = ExposedPackages.apiAnd(List.of("com"));
|
||||
|
||||
assertEquals("com.volmit.tooling", ExposedPackages.TOOLING_PACKAGE);
|
||||
assertTrue(exposed.exposes("com.volmit.tooling.Command"));
|
||||
assertTrue(exposed.exposes("com.volmit.tooling.Command$Builder"));
|
||||
assertFalse(exposed.exposes("com.volmit.tooling.bukkit.BukkitToolPart"));
|
||||
assertFalse(exposed.exposes("com.volmit.tooling.modded.deep.ModdedToolPart"));
|
||||
assertTrue(exposed.exposes("com.volmit.toolingx.Other"));
|
||||
assertTrue(exposed.exposes("com.volmit.tool.bukkit.Other"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void platformToolingResourcesAreHiddenLikeTheirClasses() {
|
||||
var exposed = ExposedPackages.apiOnly();
|
||||
|
||||
assertTrue(exposed.exposesResource("com/volmit/tooling/Command.class"));
|
||||
assertFalse(exposed.exposesResource("com/volmit/tooling/bukkit/BukkitToolPart.class"));
|
||||
assertFalse(exposed.exposesResource("com/volmit/tooling/bukkit/part.yml"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyWholePackageNamesMatch() {
|
||||
var exposed = ExposedPackages.apiAnd(List.of("example.builtin"));
|
||||
|
||||
assertTrue(exposed.exposes("example.builtin.CarveModule"));
|
||||
assertTrue(exposed.exposes("example.builtin.deep.Stage"));
|
||||
assertFalse(exposed.exposes("example.builtinx.CarveModule"));
|
||||
assertFalse(exposed.exposes("example.Other"));
|
||||
assertFalse(exposed.exposes("com.volmitx.Fake"));
|
||||
assertFalse(exposed.exposes("com.volmit"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourcesMatchByPath() {
|
||||
var exposed = ExposedPackages.apiAnd(List.of("example.builtin"));
|
||||
|
||||
assertTrue(exposed.exposesResource("example/builtin/CarveModule.class"));
|
||||
assertTrue(exposed.exposesResource("example/builtin/carve.json"));
|
||||
assertTrue(exposed.exposesResource("com/volmit/IrisModule.class"));
|
||||
assertFalse(exposed.exposesResource("example/builtinx/carve.json"));
|
||||
assertFalse(exposed.exposesResource("META-INF/services/com.volmit.IrisModule"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void trailingDotIsAccepted() {
|
||||
assertTrue(ExposedPackages.apiAnd(List.of("example.builtin.")).exposes("example.builtin.CarveModule"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " ", ".", "example..builtin", ".example", "example.*", "example.builtin.**", "1example", "example builtin"})
|
||||
void rejectsWhatIsNotAPackageName(String name) {
|
||||
var message = assertThrows(IllegalArgumentException.class, () -> ExposedPackages.apiAnd(List.of(name))).getMessage();
|
||||
|
||||
assertTrue(message.startsWith("Exposed package '" + name + "' is not a package name"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void namesTheMostSpecificExposedPackageOfAClass() {
|
||||
var exposed = ExposedPackages.apiAnd(List.of("example", "example.builtin"));
|
||||
|
||||
assertEquals("example.builtin", exposed.packageOf("example.builtin.CarveModule"));
|
||||
assertEquals("example", exposed.packageOf("example.Other"));
|
||||
assertEquals("com.volmit", exposed.packageOf("com.volmit.IrisModule"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleLog;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.config.FeatureSettings;
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.generation.GenerationContext;
|
||||
import com.volmit.hunk.Hunk;
|
||||
import com.volmit.mantle.Mantle;
|
||||
import com.volmit.placement.Placements;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.stage.Pipeline;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.support.TestContexts;
|
||||
import com.volmit.support.TestSetups;
|
||||
import com.volmit.world.PackWorld;
|
||||
import com.volmit.world.RunningWorld;
|
||||
import com.volmit.world.TerrainSampler;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** What a host offers its own modules beyond the API reaches the stages through the world and the invocation. */
|
||||
class ExtensionsTest {
|
||||
/** Something a host offers for a whole world. */
|
||||
record WorldOffer(String name) {}
|
||||
|
||||
/** Something a host offers for one invocation. */
|
||||
record ChunkOffer(int chunkX) {}
|
||||
|
||||
@Test
|
||||
void aStageReachesWhatTheHostOffersForItsWorldAndItsInvocation() {
|
||||
var seen = new ArrayList<Object>();
|
||||
var stage = Stage.chunk("test:offers/read");
|
||||
IrisModule module = new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:offers", "Offers", "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(stage).run(context -> {
|
||||
seen.add(context.world().extension(WorldOffer.class));
|
||||
seen.add(context.extension(ChunkOffer.class));
|
||||
seen.add(context.world().extension(ChunkOffer.class));
|
||||
seen.add(context.extension(WorldOffer.class));
|
||||
seen.add(context.world().log() == ModuleLogs.discarding() ? "host's log" : "module's log");
|
||||
});
|
||||
}
|
||||
};
|
||||
var world = new OfferingWorld(new WorldOffer("iris"));
|
||||
var inputs = new OfferingChunk(TestContexts.generation(null, null, null, world), new ChunkOffer(0));
|
||||
|
||||
new ChunkRunner(TestSetups.stages(module).resolve(Pipeline.CHUNK)).generate(inputs, TestContexts.SEED, StageTimings.NONE);
|
||||
|
||||
assertEquals(List.of(Optional.of(new WorldOffer("iris")), Optional.of(new ChunkOffer(0)), Optional.empty(), Optional.empty(),
|
||||
"module's log"), seen, "the module's view of the world keeps the host's offers, with the module's own log");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aModulesViewOfAWorldCreatesStateWithThatView() {
|
||||
var world = new OfferingWorld(new WorldOffer("iris"));
|
||||
var log = ModuleLogs.discarding();
|
||||
PackWorld view = ModuleWorld.of(ModuleWorld.of(world, ModuleLogs.discarding()), log);
|
||||
|
||||
PackWorld createdWith = view.state(PackWorld.class, Function.identity());
|
||||
|
||||
assertSame(view, createdWith);
|
||||
assertSame(createdWith, world.state(PackWorld.class, ignored -> null), "the state lives in the host's world");
|
||||
assertEquals(Optional.of(new WorldOffer("iris")), view.extension(WorldOffer.class));
|
||||
}
|
||||
|
||||
private static final class OfferingWorld implements PackWorld {
|
||||
private final WorldStates states = new WorldStates();
|
||||
private final WorldOffer offer;
|
||||
|
||||
OfferingWorld(WorldOffer offer) {
|
||||
this.offer = offer;
|
||||
}
|
||||
|
||||
public long seed() { return TestContexts.SEED; }
|
||||
public PackResources resources() { throw new AssertionError("Unused resources"); }
|
||||
public PackSettings settings() { throw new AssertionError("Unused settings"); }
|
||||
public int minWorldY() { return 0; }
|
||||
public Optional<RunningWorld> running() { return Optional.empty(); }
|
||||
public Placements placements() { throw new AssertionError("Unused placements"); }
|
||||
public <T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create) { return states.state(type, () -> create.apply(this)); }
|
||||
public ModuleLog log() { return ModuleLogs.discarding(); }
|
||||
|
||||
@Override
|
||||
public <T> Optional<T> extension(Class<T> type) {
|
||||
return type.isInstance(offer) ? Optional.of(type.cast(offer)) : Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private record OfferingChunk(GenerationContext inputs, ChunkOffer offer) implements GenerationContext {
|
||||
public int originX() { return inputs.originX(); }
|
||||
public int originZ() { return inputs.originZ(); }
|
||||
public TerrainSampler terrain() { return inputs.terrain(); }
|
||||
public FeatureSettings settings() { return inputs.settings(); }
|
||||
public Mantle mantle() { return inputs.mantle(); }
|
||||
public Hunk<BlockState> blocks() { return inputs.blocks(); }
|
||||
public PackWorld world() { return inputs.world(); }
|
||||
|
||||
@Override
|
||||
public <T> Optional<T> extension(Class<T> type) {
|
||||
return type.isInstance(offer) ? Optional.of(type.cast(offer)) : Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class HostClassesLeftOutTest {
|
||||
@Test
|
||||
void nothingIsLeftOutWithoutEntries() {
|
||||
assertFalse(HostClassesLeftOut.none().leavesOut("a.B"));
|
||||
assertFalse(HostClassesLeftOut.parse(List.of("", " # only a comment")).leavesOut("a.B"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEntryWithoutSuffixOrWildcardNamesAClassAndItsNestedClasses() {
|
||||
var leftOut = HostClassesLeftOut.parse(List.of("a/b/C"));
|
||||
|
||||
assertTrue(leftOut.leavesOut("a.b.C"));
|
||||
assertTrue(leftOut.leavesOut("a.b.C$Inner"));
|
||||
assertFalse(leftOut.leavesOut("a.b.Cat"));
|
||||
assertFalse(leftOut.leavesOut("a.b.sub.C"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void doubleStarCrossesPackagesAndSingleStarDoesNot() {
|
||||
var leftOut = HostClassesLeftOut.parse(List.of("a/noise/**", "a/stream/Basic*.class"));
|
||||
|
||||
assertTrue(leftOut.leavesOut("a.noise.Simplex"));
|
||||
assertTrue(leftOut.leavesOut("a.noise.deep.Cell"));
|
||||
assertTrue(leftOut.leavesOut("a.stream.BasicStream"));
|
||||
assertFalse(leftOut.leavesOut("a.stream.sub.BasicStream"));
|
||||
assertFalse(leftOut.leavesOut("a.stream.Other"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void commentsAndBlankLinesAreIgnored() {
|
||||
var leftOut = HostClassesLeftOut.parse(List.of("# header", "", " a/b/C # why", "a/D"));
|
||||
|
||||
assertTrue(leftOut.leavesOut("a.b.C"));
|
||||
assertTrue(leftOut.leavesOut("a.D"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleLifecycle;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.PackContext;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.support.EmptyResources;
|
||||
import com.volmit.support.TestWorld;
|
||||
import com.volmit.world.PackWorld;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class LifecycleRunnerTest {
|
||||
/** A module whose hooks record themselves into {@code calls} and throw on the named hook. */
|
||||
private static IrisModule module(String id, List<String> calls, String failingHook) {
|
||||
return new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(id, "Lifecycle " + id, "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.registry().registerLifecycle(new ModuleLifecycle() {
|
||||
@Override public void packLoaded(PackContext pack) { record("loaded"); }
|
||||
public void worldStarted(PackWorld world) { record("started"); }
|
||||
public void warmUp(PackWorld world) { record("warmed"); }
|
||||
public void worldStopped(PackWorld world) { record("stopped"); }
|
||||
|
||||
private void record(String hook) {
|
||||
calls.add(hook + " " + id);
|
||||
if (hook.equals(failingHook)) {
|
||||
throw new IllegalStateException(id + " cannot be " + hook);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static LifecycleRunner runner(IrisModule... modules) {
|
||||
var discovered = Arrays.stream(modules).map(DiscoveredModule::builtIn).toList();
|
||||
return new LifecycleRunner(LoadedModules.load(discovered, Map.of(), Set.of(), Set.of()).catalog());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startsInModuleIdOrderAndStopsInReverse() {
|
||||
var calls = new ArrayList<String>();
|
||||
var runner = runner(module("test:zeta", calls, null), module("test:alpha", calls, null));
|
||||
try (var world = new TestWorld()) {
|
||||
runner.worldStarted(world);
|
||||
runner.worldStopped(world);
|
||||
}
|
||||
|
||||
assertEquals(List.of("started test:alpha", "started test:zeta", "stopped test:zeta", "stopped test:alpha"), calls);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedStartStopsTheModulesThatStartedAndNamesTheModule() {
|
||||
var calls = new ArrayList<String>();
|
||||
var runner = runner(module("test:alpha", calls, null), module("test:beta", calls, "started"), module("test:gamma", calls, null));
|
||||
try (var world = new TestWorld()) {
|
||||
var failure = assertThrows(IllegalStateException.class, () -> runner.worldStarted(world));
|
||||
assertTrue(failure.getMessage().startsWith("Module test:beta from host classpath failed while starting a world"),
|
||||
failure.getMessage());
|
||||
}
|
||||
|
||||
assertEquals(List.of("started test:alpha", "started test:beta", "stopped test:alpha"), calls);
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyModuleStopsEvenWhenOneFailsAndEveryFailureIsReported() {
|
||||
var calls = new ArrayList<String>();
|
||||
var runner = runner(module("test:alpha", calls, "stopped"), module("test:beta", calls, null), module("test:gamma", calls, "stopped"));
|
||||
try (var world = new TestWorld()) {
|
||||
var failure = assertThrows(IllegalStateException.class, () -> runner.worldStopped(world));
|
||||
assertTrue(failure.getMessage().startsWith("Module test:gamma from host classpath failed while stopping a world"),
|
||||
failure.getMessage());
|
||||
assertEquals(1, failure.getSuppressed().length);
|
||||
assertTrue(failure.getSuppressed()[0].getMessage().startsWith("Module test:alpha"));
|
||||
}
|
||||
|
||||
assertEquals(List.of("stopped test:gamma", "stopped test:beta", "stopped test:alpha"), calls);
|
||||
}
|
||||
|
||||
@Test
|
||||
void warmsUpInModuleIdOrderAfterTheModulesStarted() {
|
||||
var calls = new ArrayList<String>();
|
||||
var runner = runner(module("test:zeta", calls, null), module("test:alpha", calls, null));
|
||||
try (var world = new TestWorld()) {
|
||||
runner.worldStarted(world);
|
||||
runner.warmUp(world);
|
||||
}
|
||||
|
||||
assertEquals(List.of("started test:alpha", "started test:zeta", "warmed test:alpha", "warmed test:zeta"), calls);
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyModuleWarmsUpEvenWhenOneFailsAndEveryFailureIsReported() {
|
||||
var calls = new ArrayList<String>();
|
||||
var runner = runner(module("test:alpha", calls, "warmed"), module("test:beta", calls, null), module("test:gamma", calls, "warmed"));
|
||||
try (var world = new TestWorld()) {
|
||||
var failure = assertThrows(IllegalStateException.class, () -> runner.warmUp(world));
|
||||
assertTrue(failure.getMessage().startsWith("Module test:alpha from host classpath failed while warming up a world"),
|
||||
failure.getMessage());
|
||||
assertEquals(1, failure.getSuppressed().length);
|
||||
assertTrue(failure.getSuppressed()[0].getMessage().startsWith("Module test:gamma"));
|
||||
}
|
||||
|
||||
assertEquals(List.of("warmed test:alpha", "warmed test:beta", "warmed test:gamma"), calls);
|
||||
}
|
||||
|
||||
@Test
|
||||
void modulesWithoutAWarmUpHookWarmUpNothing() {
|
||||
var module = new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:plain", "Plain", "1"); }
|
||||
public void setup(ModuleSetup setup) { setup.registry().registerLifecycle(new ModuleLifecycle() {}); }
|
||||
};
|
||||
try (var world = new TestWorld()) {
|
||||
runner(module).warmUp(world);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedPackLoadNamesTheModuleAndSkipsTheRest() {
|
||||
var calls = new ArrayList<String>();
|
||||
var runner = runner(module("test:alpha", calls, "loaded"), module("test:beta", calls, null));
|
||||
PackResources resources = new EmptyResources();
|
||||
|
||||
var failure = assertThrows(IllegalStateException.class, () -> runner.packLoaded(resources, new TestWorld().settings()));
|
||||
|
||||
assertTrue(failure.getMessage().startsWith("Module test:alpha from host classpath failed while loading pack test:pack"),
|
||||
failure.getMessage());
|
||||
assertEquals(List.of("loaded test:alpha"), calls);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.support.TestModuleJar;
|
||||
import example.builtin.CarveModule;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static com.volmit.support.TestModuleJar.module;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class LoadedPackTest {
|
||||
private static final String LOADER_PROPERTY = "irisapi.test.packClassLoader";
|
||||
private static final String UNUSED_CLASS = "pack.user.Unused";
|
||||
private static final String NO_MEMBERS = "";
|
||||
private static final String NO_STAGES = "";
|
||||
private static final ModuleHost HOST = ModuleHost.of(List.of(new CarveModule()))
|
||||
.exposing(CarveModule.class.getPackageName());
|
||||
|
||||
@TempDir
|
||||
Path pack;
|
||||
|
||||
@AfterEach
|
||||
void forgetLoader() {
|
||||
System.getProperties().remove(LOADER_PROPERTY);
|
||||
}
|
||||
|
||||
/** A pack module that hands its class loader to the test when constructed, plus a class nothing loads. */
|
||||
private void writeModule(String moduleId, String install) {
|
||||
module("pack.user.User", moduleId,
|
||||
"public User() { System.getProperties().put(\"" + LOADER_PROPERTY + "\", getClass().getClassLoader()); }",
|
||||
install)
|
||||
.source(UNUSED_CLASS, "package pack.user; final class Unused {}")
|
||||
.compileAgainstHostOf(CarveModule.class)
|
||||
.writeInto(pack, "user.jar");
|
||||
}
|
||||
|
||||
private static ClassLoader packLoader() {
|
||||
return (ClassLoader) System.getProperties().get(LOADER_PROPERTY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsPackModulesWithTheHostsBuiltInsAndResolvesBothPipelines() {
|
||||
writeModule("user:core", "graph.define(Stage.placement(\"user:core/carved\"))"
|
||||
+ ".requires(example.builtin.CarveModule.CLEAR).run(context -> {});");
|
||||
|
||||
try (var loaded = LoadedPack.load(pack, HOST)) {
|
||||
assertEquals(List.of("user:core"), loaded.packModules().stream().map(found -> found.info().id().toString()).toList());
|
||||
assertEquals(List.of("iris:carve/clear", "user:core/carved"),
|
||||
loaded.placement().stages().stream().map(stage -> stage.stage().id().toString()).toList());
|
||||
assertTrue(loaded.chunk().stages().isEmpty());
|
||||
assertTrue(loaded.missingClasses().isEmpty());
|
||||
assertTrue(loaded.catalog().settings().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingThePackReleasesItsClassLoader() {
|
||||
writeModule("user:core", NO_STAGES);
|
||||
|
||||
try (var ignored = LoadedPack.load(pack, HOST)) {
|
||||
assertNotNull(packLoader());
|
||||
}
|
||||
|
||||
assertThrows(ClassNotFoundException.class, () -> packLoader().loadClass(UNUSED_CLASS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedLoadLeavesNothingOpen() {
|
||||
writeModule("iris:carve", NO_STAGES);
|
||||
|
||||
var error = assertThrows(ModuleLoadException.class, () -> LoadedPack.load(pack, HOST));
|
||||
|
||||
assertTrue(error.getMessage().contains("Duplicate module iris:carve"), error.getMessage());
|
||||
assertEquals("iris:carve", error.moduleId().orElseThrow().toString());
|
||||
assertTrue(error.origin().orElseThrow().startsWith("modules/"), error.origin().toString());
|
||||
assertNotNull(packLoader(), "the module was constructed before installation failed");
|
||||
assertThrows(ClassNotFoundException.class, () -> packLoader().loadClass(UNUSED_CLASS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidHostConfigurationFailsWhenBuilt() {
|
||||
var host = ModuleHost.of(List.of());
|
||||
assertThrows(IllegalArgumentException.class, () -> host.exposing("org.*"));
|
||||
assertThrows(IllegalArgumentException.class, () -> host.reservingFields(Map.of(Level.BIOME, Set.of(" "))));
|
||||
assertThrows(IllegalArgumentException.class, () -> host.reservingFields(Map.of(Level.BIOME, Set.of("iris:carve"))));
|
||||
assertEquals(List.of(), host.builtIns());
|
||||
assertEquals(Set.of(), host.exposedHostPackages());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyHostSettingAddsToWhatEarlierCallsConfigured() {
|
||||
var host = ModuleHost.of(List.of())
|
||||
.exposing("example.first")
|
||||
.exposing("example.second")
|
||||
.reservingFields(Map.of(Level.BIOME, Set.of("carving"), Level.REGION, Set.of("spawns")))
|
||||
.reservingFields(Map.of(Level.BIOME, Set.of("objects")))
|
||||
.reservingFolders("biomes")
|
||||
.reservingFolders("regions");
|
||||
|
||||
assertEquals(Set.of("example.first", "example.second"), host.exposedHostPackages());
|
||||
assertEquals(Map.of(Level.BIOME, Set.of("carving", "objects"), Level.REGION, Set.of("spawns")), host.reservedHostFields());
|
||||
assertEquals(Set.of("biomes", "regions"), host.reservedFolders());
|
||||
}
|
||||
|
||||
@Test
|
||||
void copiesJarsWhereTheHostSaysAndLogsToTheHostsLogger(@TempDir Path cache) throws java.io.IOException {
|
||||
writeModule("user:core", NO_STAGES);
|
||||
var copies = cache.resolve("module-jars");
|
||||
var log = new RecordingLogger();
|
||||
|
||||
try (var ignored = LoadedPack.load(pack, HOST.copyingJarsTo(copies).loggingTo(log))) {
|
||||
assertTrue(java.nio.file.Files.exists(copies), "a missing copy directory is created");
|
||||
try (var entries = java.nio.file.Files.list(copies)) {
|
||||
assertEquals(1, entries.filter(entry -> entry.getFileName().toString().startsWith(JarSnapshot.DIRECTORY_PREFIX)).count());
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(List.of("INFO Pack " + pack.getFileName() + " uses 1 module:"), log.levelsAndFirstLines());
|
||||
}
|
||||
|
||||
@Test
|
||||
void bundledJarsLoadWithEveryPackBeforeItsOwnJarsInItsClassLoader(@TempDir Path build) {
|
||||
var bundledJar = module("host.bundled.BundledModule", "bundled:core",
|
||||
"public static final PlacementStage<Void> MARK = Stage.placement(\"bundled:core/mark\");",
|
||||
"graph.define(MARK).run(context -> {});")
|
||||
.writeInto(build, "bundled.jar");
|
||||
module("pack.user.User", "user:core", NO_MEMBERS,
|
||||
"graph.define(Stage.placement(\"user:core/after\")).requires(host.bundled.BundledModule.MARK).run(context -> {});")
|
||||
.compileAgainst(bundledJar)
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
try (var loaded = LoadedPack.load(pack, HOST.bundlingJars(bundledJar))) {
|
||||
assertEquals(List.of("bundled.jar" + PackModules.BUNDLED_ORIGIN_SUFFIX, Path.of("modules", "user.jar").toString()),
|
||||
loaded.packModules().stream().map(DiscoveredModule::origin).toList());
|
||||
var order = loaded.placement().stages().stream().map(stage -> stage.stage().id().toString()).toList();
|
||||
assertTrue(order.indexOf("bundled:core/mark") < order.indexOf("user:core/after"), order.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPackCopyOfABundledJarFailsNamingBothJars(@TempDir Path build) {
|
||||
var bundled = module("host.bundled.BundledModule", "bundled:core", NO_MEMBERS, NO_STAGES);
|
||||
var bundledJar = bundled.writeInto(build, "bundled.jar");
|
||||
bundled.writeInto(pack, "bundled.jar");
|
||||
|
||||
var error = assertThrows(ModuleLoadException.class, () -> LoadedPack.load(pack, HOST.bundlingJars(bundledJar)));
|
||||
|
||||
assertTrue(error.getMessage().contains("Class host.bundled.BundledModule is in both module jars bundled.jar"
|
||||
+ PackModules.BUNDLED_ORIGIN_SUFFIX + " and " + Path.of("modules", "bundled.jar")), error.getMessage());
|
||||
}
|
||||
|
||||
/** Keeps the level and first line of every message, which is enough to see where the summary went. */
|
||||
private static final class RecordingLogger implements System.Logger {
|
||||
private final List<String> lines = new java.util.ArrayList<>();
|
||||
|
||||
List<String> levelsAndFirstLines() { return lines; }
|
||||
public String getName() { return "recording"; }
|
||||
public boolean isLoggable(Level level) { return true; }
|
||||
public void log(Level level, java.util.ResourceBundle bundle, String message, Throwable thrown) { record(level, message); }
|
||||
public void log(Level level, java.util.ResourceBundle bundle, String format, Object... parameters) { record(level, format); }
|
||||
|
||||
private void record(Level level, String message) {
|
||||
lines.add(level + " " + message.lines().findFirst().orElse(""));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class MissingClassesWarningTest {
|
||||
private static final String HEADER = "Pack overworld: module jars use classes that neither the pack, Iris nor the JDK"
|
||||
+ " has, usually optional dependencies of a bundled library. The jars load, but code that needs these"
|
||||
+ " classes throws NoClassDefFoundError when it runs:";
|
||||
|
||||
@Test
|
||||
void listsTheMissingClassesOfEveryJarOnOneLine() {
|
||||
var jars = List.of(
|
||||
new MissingClasses("modules/moss.jar", List.of("org.slf4j.Logger", "org.slf4j.LoggerFactory")),
|
||||
new MissingClasses("modules/snow.jar", List.of("com.google.gson.Gson")));
|
||||
|
||||
assertEquals(HEADER
|
||||
+ "\n modules/moss.jar: org.slf4j.Logger, org.slf4j.LoggerFactory"
|
||||
+ "\n modules/snow.jar: com.google.gson.Gson",
|
||||
MissingClassesWarning.describe("overworld", jars));
|
||||
}
|
||||
|
||||
@Test
|
||||
void capsLongListsPerJar() {
|
||||
var classNames = IntStream.rangeClosed(1, 214).mapToObj(index -> "lib.Missing%03d".formatted(index)).toList();
|
||||
var jars = List.of(new MissingClasses("modules/big.jar", classNames));
|
||||
|
||||
assertEquals(HEADER
|
||||
+ "\n modules/big.jar: lib.Missing001, lib.Missing002, lib.Missing003, lib.Missing004, lib.Missing005 and 209 more",
|
||||
MissingClassesWarning.describe("overworld", jars));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAtTheCapHasNoRemainder() {
|
||||
var classNames = IntStream.rangeClosed(1, MissingClassesWarning.MAX_LISTED_CLASSES_PER_JAR)
|
||||
.mapToObj(index -> "lib.Missing" + index).toList();
|
||||
var jars = List.of(new MissingClasses("modules/big.jar", classNames));
|
||||
|
||||
assertEquals(HEADER + "\n modules/big.jar: lib.Missing1, lib.Missing2, lib.Missing3, lib.Missing4, lib.Missing5",
|
||||
MissingClassesWarning.describe("overworld", jars));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.support.FakePlatformApi;
|
||||
import com.volmit.support.TestModuleJar;
|
||||
import example.builtin.CarveModule;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import static com.volmit.support.TestModuleJar.module;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ModuleJarCheckTest {
|
||||
private static final String NO_MEMBERS = "";
|
||||
private static final String NO_STAGES = "";
|
||||
private static final String USES_JUNIT = "static Object used() { return org.junit.jupiter.api.Test.class; }";
|
||||
private static final List<String> NO_EXPOSED_PACKAGES = List.of();
|
||||
|
||||
@TempDir
|
||||
Path build;
|
||||
|
||||
private static String failure(Executable check) {
|
||||
return assertThrows(ModuleLoadException.class, check).getMessage();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarOfSeveralModulesPassesAndReturnsThemInListedOrder() {
|
||||
var jar = module("pack.First", "first:core", NO_MEMBERS, NO_STAGES)
|
||||
.alsoModule("pack.Second", "second:core", NO_MEMBERS, NO_STAGES)
|
||||
.writeInto(build, "two.jar");
|
||||
|
||||
assertEquals(List.of("pack.First", "pack.Second"), ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarThatUsesAnExposedHostPackagePasses() {
|
||||
var jar = module("pack.User", "user:core", NO_MEMBERS,
|
||||
"graph.define(Stage.placement(\"user:core/carved\")).requires(example.builtin.CarveModule.CLEAR).run(context -> {});")
|
||||
.compileAgainstHostOf(CarveModule.class)
|
||||
.writeInto(build, "user.jar");
|
||||
|
||||
assertEquals(List.of("pack.User"), ModuleJarCheck.check(jar, List.of(CarveModule.class.getPackageName())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarThatUsesAHiddenHostClassFailsNamingTheClass() {
|
||||
var jar = module("pack.User", "user:core", USES_JUNIT, NO_STAGES)
|
||||
.compileAgainstHostOf(Test.class)
|
||||
.writeInto(build, "user.jar");
|
||||
|
||||
var message = failure(() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES));
|
||||
|
||||
assertTrue(message.contains("hidden from modules"), message);
|
||||
assertTrue(message.contains("pack.User -> org.junit.jupiter.api.Test"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarThatUsesAHostClassItsHostDoesNotExposeFails() {
|
||||
var jar = module("pack.User", "user:core", NO_MEMBERS,
|
||||
"graph.define(Stage.placement(\"user:core/carved\")).requires(example.builtin.CarveModule.CLEAR).run(context -> {});")
|
||||
.compileAgainstHostOf(CarveModule.class)
|
||||
.writeInto(build, "user.jar");
|
||||
|
||||
var message = failure(() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES));
|
||||
|
||||
assertTrue(message.contains("pack.User -> example.builtin.CarveModule"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleClassOutsideTheJarFailsNamingTheJarAndTheClass() {
|
||||
var jar = module("pack.User", "user:core", NO_MEMBERS, NO_STAGES)
|
||||
.entryPoint("pack.Elsewhere")
|
||||
.writeInto(build, "user.jar");
|
||||
|
||||
var message = failure(() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES));
|
||||
|
||||
assertTrue(message.contains(jar.toString()), message);
|
||||
assertTrue(message.contains("lists pack.Elsewhere"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarThatListsNoModuleFails() {
|
||||
var jar = new TestModuleJar().source("pack.Plain", "package pack; public final class Plain {}").writeInto(build, "plain.jar");
|
||||
|
||||
assertTrue(failure(() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES)).contains("has no entry point"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarThatUsesAnExposedClassTheHostJarLeavesOutFailsNamingTheClass() {
|
||||
var jar = module("pack.User", "user:core", NO_MEMBERS,
|
||||
"graph.define(Stage.placement(\"user:core/carved\")).requires(example.builtin.CarveModule.CLEAR).run(context -> {});")
|
||||
.compileAgainstHostOf(CarveModule.class)
|
||||
.writeInto(build, "user.jar");
|
||||
var exposed = List.of(CarveModule.class.getPackageName());
|
||||
var leftOut = List.of("# stripped from the host jar", "example/builtin/CarveModule");
|
||||
|
||||
var message = failure(() -> ModuleJarCheck.check(jar, exposed, leftOut));
|
||||
|
||||
assertTrue(message.contains("leaves out"), message);
|
||||
assertTrue(message.contains("pack.User -> example.builtin.CarveModule"), message);
|
||||
}
|
||||
|
||||
private static final String BUKKIT_PART = "pack.tools.bukkit.StudioPart";
|
||||
private static final String MODDED_PART = "pack.tools.modded.ModdedPart";
|
||||
|
||||
@TempDir
|
||||
Path work;
|
||||
|
||||
private Path platformJar(String... classNames) {
|
||||
try (var platform = FakePlatformApi.of(work, classNames)) {
|
||||
return platform.jar();
|
||||
}
|
||||
}
|
||||
|
||||
private static String partWith(String className, String members) {
|
||||
int dot = className.lastIndexOf('.');
|
||||
return "package " + className.substring(0, dot) + "; public final class " + className.substring(dot + 1) + " { " + members + " }";
|
||||
}
|
||||
|
||||
private static String usingClass(String className) {
|
||||
return "static final Class<?> USED = " + className + ".class;";
|
||||
}
|
||||
|
||||
private static TestModuleJar moduleWithPart(String part, String partMembers, String platform) {
|
||||
return module("pack.User", "user:core", NO_MEMBERS, NO_STAGES)
|
||||
.source(part, partWith(part, partMembers))
|
||||
.toolingParts(platform + "=" + part);
|
||||
}
|
||||
|
||||
private static ModuleJarCheck.CheckedPlatform bukkitWith(Path apiJar) {
|
||||
return new ModuleJarCheck.CheckedPlatform(ToolingPlatform.BUKKIT, apiJar);
|
||||
}
|
||||
|
||||
@Test
|
||||
void partsAreSkippedWithoutAPlatformAndTheOutputSaysSo() {
|
||||
var jar = moduleWithPart(BUKKIT_PART, usingClass("org.junit.jupiter.api.Test"), "bukkit")
|
||||
.compileAgainstHostOf(Test.class)
|
||||
.writeInto(build, "user.jar");
|
||||
|
||||
var outcome = ModuleJarCheck.run(jar, NO_EXPOSED_PACKAGES, List.of(), Optional.empty());
|
||||
|
||||
assertEquals(List.of("pack.User"), outcome.modules());
|
||||
assertTrue(outcome.summary().contains("passes the pack module checks: [pack.User]"), outcome.summary());
|
||||
assertTrue(outcome.summary().contains("Skipped tooling parts (name a platform with --platform=<name>:<platform api jar> to check them): "
|
||||
+ "[bukkit=" + BUKKIT_PART + "]"), outcome.summary());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarWithoutPartsHasNoSkipNote() {
|
||||
var jar = module("pack.User", "user:core", NO_MEMBERS, NO_STAGES).writeInto(build, "user.jar");
|
||||
|
||||
assertFalse(ModuleJarCheck.run(jar, NO_EXPOSED_PACKAGES, List.of(), Optional.empty()).summary().contains("Skipped"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generationClassUsingAPartFailsWithoutAPlatformToo() {
|
||||
var jar = module("pack.User", "user:core", "static Object leak() { return new " + BUKKIT_PART + "(); }", NO_STAGES)
|
||||
.source(BUKKIT_PART, partWith(BUKKIT_PART, "public StudioPart() {}"))
|
||||
.toolingParts("bukkit=" + BUKKIT_PART)
|
||||
.writeInto(build, "user.jar");
|
||||
|
||||
var message = failure(() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES));
|
||||
|
||||
assertTrue(message.contains("pack.User -> " + BUKKIT_PART), message);
|
||||
assertTrue(message.contains("Generation code cannot use the bukkit part; move the call into the part."), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void partOfTheNamedPlatformPassesAgainstThePlatformJar() {
|
||||
var api = platformJar("org.bukkit.Bukkit");
|
||||
var jar = moduleWithPart(BUKKIT_PART, usingClass("org.bukkit.Bukkit"), "bukkit")
|
||||
.compileAgainst(api)
|
||||
.writeInto(build, "user.jar");
|
||||
|
||||
var outcome = ModuleJarCheck.run(jar, NO_EXPOSED_PACKAGES, List.of(), Optional.of(bukkitWith(api)));
|
||||
|
||||
assertEquals(List.of("pack.User"), outcome.modules());
|
||||
assertEquals(List.of(), outcome.skippedParts());
|
||||
assertFalse(outcome.summary().contains("Skipped"), outcome.summary());
|
||||
assertEquals(List.of("pack.User"), ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES, List.of(), ToolingPlatform.BUKKIT, api));
|
||||
}
|
||||
|
||||
@Test
|
||||
void partUsingAClassThePlatformJarLacksFailsNamingBothClasses() {
|
||||
var buildApi = platformJar("org.bukkit.Bukkit", "org.bukkit.entity.Player");
|
||||
var checkedApi = platformJar("org.bukkit.Bukkit");
|
||||
var jar = moduleWithPart(BUKKIT_PART, usingClass("org.bukkit.entity.Player"), "bukkit")
|
||||
.compileAgainst(buildApi)
|
||||
.writeInto(build, "user.jar");
|
||||
|
||||
var message = failure(() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES, List.of(), ToolingPlatform.BUKKIT, checkedApi));
|
||||
|
||||
assertTrue(message.contains(BUKKIT_PART + " -> org.bukkit.entity.Player"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void partUsingADeniedClassFailsNamingTheJarAndBothClasses() {
|
||||
var api = platformJar("org.bukkit.craftbukkit.CraftServer");
|
||||
var jar = moduleWithPart(BUKKIT_PART, usingClass("org.bukkit.craftbukkit.CraftServer"), "bukkit")
|
||||
.compileAgainst(api)
|
||||
.writeInto(build, "user.jar");
|
||||
|
||||
var message = failure(() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES, List.of(), ToolingPlatform.BUKKIT, api));
|
||||
|
||||
assertTrue(message.contains(jar.toString()), message);
|
||||
assertTrue(message.contains(BUKKIT_PART + " -> org.bukkit.craftbukkit.CraftServer"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void partOfAnotherPlatformIsSkippedAndListed() {
|
||||
var api = platformJar("org.bukkit.Bukkit");
|
||||
var jar = moduleWithPart(MODDED_PART, usingClass("org.junit.jupiter.api.Test"), "modded")
|
||||
.compileAgainstHostOf(Test.class)
|
||||
.writeInto(build, "user.jar");
|
||||
|
||||
var outcome = ModuleJarCheck.run(jar, NO_EXPOSED_PACKAGES, List.of(), Optional.of(bukkitWith(api)));
|
||||
|
||||
assertTrue(outcome.summary().contains("Skipped tooling parts of other platforms: [modded=" + MODDED_PART + "]"), outcome.summary());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingPlatformJarFailsNamingIt() {
|
||||
var jar = module("pack.User", "user:core", NO_MEMBERS, NO_STAGES).writeInto(build, "user.jar");
|
||||
var missing = work.resolve("missing-api.jar");
|
||||
|
||||
var failure = assertThrows(IllegalArgumentException.class,
|
||||
() -> ModuleJarCheck.check(jar, NO_EXPOSED_PACKAGES, List.of(), ToolingPlatform.BUKKIT, missing));
|
||||
|
||||
assertTrue(failure.getMessage().contains(missing.toString()), failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void platformOptionNamesAKnownPlatformAndAJar() {
|
||||
var parsed = ModuleJarCheck.CheckedPlatform.parse("bukkit:libs/paper-api.jar");
|
||||
|
||||
assertSame(ToolingPlatform.BUKKIT, parsed.platform());
|
||||
assertEquals(Path.of("libs/paper-api.jar"), parsed.apiJar());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"bukkit", "bukkit:", ":paper-api.jar", "modded:paper-api.jar"})
|
||||
void malformedPlatformOptionFails(String option) {
|
||||
assertThrows(IllegalArgumentException.class, () -> ModuleJarCheck.CheckedPlatform.parse(option));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarThatUsesAnExposedClassNotLeftOutStillPasses() {
|
||||
var jar = module("pack.User", "user:core", NO_MEMBERS,
|
||||
"graph.define(Stage.placement(\"user:core/carved\")).requires(example.builtin.CarveModule.CLEAR).run(context -> {});")
|
||||
.compileAgainstHostOf(CarveModule.class)
|
||||
.writeInto(build, "user.jar");
|
||||
|
||||
assertEquals(List.of("pack.User"), ModuleJarCheck.check(jar, List.of(CarveModule.class.getPackageName()),
|
||||
List.of("example/builtin/OtherModule")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleLifecycle;
|
||||
import com.volmit.ModuleLog;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.PackContext;
|
||||
import com.volmit.stage.ChunkStage;
|
||||
import com.volmit.stage.Pipeline;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.support.EmptyResources;
|
||||
import com.volmit.support.TestContexts;
|
||||
import com.volmit.support.TestModuleJar;
|
||||
import com.volmit.support.TestSetups;
|
||||
import com.volmit.support.TestWorld;
|
||||
import com.volmit.world.PackWorld;
|
||||
import java.lang.System.Logger.Level;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.ResourceBundle;
|
||||
import java.util.Set;
|
||||
import java.nio.file.Path;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ModuleLogTest {
|
||||
private static final String ALPHA = "test:alpha";
|
||||
private static final String BETA = "test:beta";
|
||||
private static final int ONCE_KEY_CAP = 512;
|
||||
|
||||
/** A host logger that remembers what it was asked to write. */
|
||||
private static final class RecordingLogger implements System.Logger {
|
||||
record Line(Level level, String message, Throwable thrown) {}
|
||||
|
||||
final List<Line> lines = new ArrayList<>();
|
||||
boolean debugEnabled = true;
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "recording";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLoggable(Level level) {
|
||||
return level != Level.DEBUG || debugEnabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void log(Level level, ResourceBundle bundle, String message, Throwable thrown) {
|
||||
lines.add(new Line(level, message, thrown));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void log(Level level, ResourceBundle bundle, String format, Object... params) {
|
||||
lines.add(new Line(level, format, null));
|
||||
}
|
||||
|
||||
List<String> messages() {
|
||||
return lines.stream().map(Line::message).toList();
|
||||
}
|
||||
}
|
||||
|
||||
private static IrisModule module(String id) {
|
||||
return new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(id, "Log " + id, "1"); }
|
||||
public void setup(ModuleSetup setup) {}
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void labelsEveryLineWithTheModuleIdAndKeepsTheLevel() {
|
||||
var logger = new RecordingLogger();
|
||||
var log = ModuleLogs.labelled(ALPHA, logger);
|
||||
|
||||
log.debug("d");
|
||||
log.info("i");
|
||||
log.warn("w");
|
||||
log.error("e", null);
|
||||
|
||||
assertEquals(List.of("[test:alpha] d", "[test:alpha] i", "[test:alpha] w", "[test:alpha] e"), logger.messages());
|
||||
assertEquals(List.of(Level.DEBUG, Level.INFO, Level.WARNING, Level.ERROR),
|
||||
logger.lines.stream().map(RecordingLogger.Line::level).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMessageIsPlainTextNotAFormat() {
|
||||
var logger = new RecordingLogger();
|
||||
|
||||
ModuleLogs.labelled(ALPHA, logger).warn("100% {0} %s");
|
||||
|
||||
assertEquals(List.of("[test:alpha] 100% {0} %s"), logger.messages());
|
||||
}
|
||||
|
||||
@Test
|
||||
void debugIsWrittenOnlyWhenTheHostLogsDebug() {
|
||||
var logger = new RecordingLogger();
|
||||
logger.debugEnabled = false;
|
||||
var log = ModuleLogs.labelled(ALPHA, logger);
|
||||
|
||||
log.debug("hidden");
|
||||
log.info("shown");
|
||||
logger.debugEnabled = true;
|
||||
log.debug("now shown");
|
||||
|
||||
assertEquals(List.of("[test:alpha] shown", "[test:alpha] now shown"), logger.messages());
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorHandsTheCauseToTheHostToReport() {
|
||||
var logger = new RecordingLogger();
|
||||
var cause = new IllegalStateException("boom");
|
||||
|
||||
ModuleLogs.labelled(ALPHA, logger).error("Failed to place", cause);
|
||||
|
||||
assertEquals(1, logger.lines.size());
|
||||
assertEquals(Level.ERROR, logger.lines.get(0).level());
|
||||
assertEquals("[test:alpha] Failed to place", logger.lines.get(0).message());
|
||||
assertSame(cause, logger.lines.get(0).thrown());
|
||||
}
|
||||
|
||||
@Test
|
||||
void warnOnceWarnsTheFirstTimeAndDebugsAfterwards() {
|
||||
var logger = new RecordingLogger();
|
||||
var log = ModuleLogs.labelled(ALPHA, logger);
|
||||
|
||||
log.warnOnce("empty", "first");
|
||||
log.warnOnce("empty", "second");
|
||||
log.warnOnce("other", "third");
|
||||
|
||||
assertEquals(List.of(Level.WARNING, Level.DEBUG, Level.WARNING),
|
||||
logger.lines.stream().map(RecordingLogger.Line::level).toList());
|
||||
assertEquals(List.of("[test:alpha] first", "[test:alpha] second", "[test:alpha] third"), logger.messages());
|
||||
}
|
||||
|
||||
@Test
|
||||
void warnOnceKeysBelongToTheModule() {
|
||||
var logger = new RecordingLogger();
|
||||
var alpha = ModuleLogs.labelled(ALPHA, logger);
|
||||
var beta = ModuleLogs.labelled(BETA, logger);
|
||||
|
||||
alpha.warnOnce("shared", "alpha says");
|
||||
beta.warnOnce("shared", "beta says");
|
||||
|
||||
assertEquals(List.of(Level.WARNING, Level.WARNING), logger.lines.stream().map(RecordingLogger.Line::level).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void warnOnceStopsClaimingKeysPastTheCap() {
|
||||
var logger = new RecordingLogger();
|
||||
var log = ModuleLogs.labelled(ALPHA, logger);
|
||||
for (int key = 0; key < ONCE_KEY_CAP; key++) {
|
||||
log.warnOnce("key" + key, "claimed");
|
||||
}
|
||||
logger.lines.clear();
|
||||
|
||||
log.warnOnce("one too many", "dropped to debug");
|
||||
|
||||
assertEquals(List.of(Level.DEBUG), logger.lines.stream().map(RecordingLogger.Line::level).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void discardingLogWritesNothingAndNeverThrows() {
|
||||
var log = ModuleLogs.discarding();
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
log.debug("d");
|
||||
log.info("i");
|
||||
log.warn("w");
|
||||
log.warnOnce("k", "m");
|
||||
log.error("e", new RuntimeException());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void builtInModulesLogThroughTheHostLogger() {
|
||||
var logger = new RecordingLogger();
|
||||
var host = ModuleHost.of(List.of(module(ALPHA))).loggingTo(logger);
|
||||
|
||||
host.builtIns().get(0).log().warn("hello");
|
||||
|
||||
assertEquals(List.of("[test:alpha] hello"), logger.messages());
|
||||
}
|
||||
|
||||
@Test
|
||||
void packModulesLogThroughTheLoadersLogger(@TempDir Path pack, @TempDir Path copies) {
|
||||
var logger = new RecordingLogger();
|
||||
TestModuleJar.module("pack.gamma.GammaModule", "gamma:core", "", "")
|
||||
.writeInto(pack, "gamma.jar");
|
||||
|
||||
try (var modules = PackModules.load(pack, List.of(), copies, logger)) {
|
||||
logger.lines.clear();
|
||||
modules.modules().get(0).log().warn("from a jar");
|
||||
}
|
||||
|
||||
assertEquals(List.of("[gamma:core] from a jar"), logger.messages());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setupGivesTheModuleItsOwnLog() {
|
||||
var logger = new RecordingLogger();
|
||||
var logs = new ArrayList<ModuleLog>();
|
||||
var settingUp = new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(BETA, "Sets up", "1"); }
|
||||
public void setup(ModuleSetup setup) { logs.add(setup.log()); }
|
||||
};
|
||||
|
||||
TestSetups.install(new StageGraphBuilder(), DiscoveredModule.builtIn(settingUp).loggingTo(logger));
|
||||
logs.get(0).info("set up");
|
||||
|
||||
assertEquals(List.of("[test:beta] set up"), logger.messages());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStageBodySeesItsOwnModulesLogOnTheContextAndOnTheWorld() {
|
||||
var logger = new RecordingLogger();
|
||||
var alphaStage = Stage.chunk("test:alpha/first");
|
||||
var betaStage = Stage.chunk("test:beta/second");
|
||||
var builder = new StageGraphBuilder();
|
||||
TestSetups.install(builder, DiscoveredModule.builtIn(stagedModule(ALPHA, alphaStage, null)).loggingTo(logger));
|
||||
TestSetups.install(builder, DiscoveredModule.builtIn(stagedModule(BETA, betaStage, alphaStage)).loggingTo(logger));
|
||||
var runner = new ChunkRunner(builder.resolve(Pipeline.CHUNK));
|
||||
|
||||
try (var world = new TestWorld()) {
|
||||
runner.generate(TestContexts.generation(null, null, null, world), TestContexts.SEED, StageTimings.NONE);
|
||||
}
|
||||
|
||||
assertEquals(List.of("[test:alpha] context", "[test:alpha] world", "[test:beta] context", "[test:beta] world"),
|
||||
logger.messages());
|
||||
}
|
||||
|
||||
private static IrisModule stagedModule(String id, ChunkStage<Void> stage, ChunkStage<Void> after) {
|
||||
return new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(id, "Stage " + id, "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
var definition = setup.stages().define(stage);
|
||||
if (after != null) {
|
||||
definition.softAfter(after);
|
||||
}
|
||||
definition.run(context -> {
|
||||
context.log().info("context");
|
||||
context.world().log().info("world");
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void lifecycleHooksAndServicesGetAWorldWhoseLogIsTheModules() {
|
||||
var logger = new RecordingLogger();
|
||||
var seen = new ArrayList<ModuleLog>();
|
||||
var module = new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(ALPHA, "Hooks", "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.registry().registerLifecycle(new ModuleLifecycle() {
|
||||
public void worldStarted(PackWorld world) { seen.add(world.log()); }
|
||||
});
|
||||
}
|
||||
};
|
||||
var discovered = DiscoveredModule.builtIn(module).loggingTo(logger);
|
||||
var catalog = LoadedModules.load(List.of(discovered), Map.of(), Set.of(), Set.of()).catalog();
|
||||
|
||||
try (var world = new TestWorld()) {
|
||||
new LifecycleRunner(catalog).worldStarted(world);
|
||||
new ServiceRegistration(Runnable.class, (Runnable) () -> {}, discovered).scope(world).log().warn("from a service");
|
||||
}
|
||||
seen.get(0).info("from a hook");
|
||||
|
||||
assertEquals(List.of("[test:alpha] from a service", "[test:alpha] from a hook"), logger.messages());
|
||||
}
|
||||
|
||||
@Test
|
||||
void packLoadedGetsThePackWithTheModulesOwnLog() {
|
||||
var logger = new RecordingLogger();
|
||||
var module = new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(ALPHA, "Loads", "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.registry().registerLifecycle(new ModuleLifecycle() {
|
||||
@Override
|
||||
public void packLoaded(PackContext pack) { pack.log().info("loaded " + pack.resources().packId()); }
|
||||
});
|
||||
}
|
||||
};
|
||||
var catalog = LoadedModules.load(List.of(DiscoveredModule.builtIn(module).loggingTo(logger)), Map.of(), Set.of(), Set.of())
|
||||
.catalog();
|
||||
|
||||
try (var world = new TestWorld()) {
|
||||
new LifecycleRunner(catalog).packLoaded(new EmptyResources(), world.settings());
|
||||
}
|
||||
|
||||
assertEquals(List.of("[test:alpha] loaded test:pack"), logger.messages());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStageBodySeesTheSameScopedWorldOnEveryInvocationOfTheSameWorld() {
|
||||
var seen = new ArrayList<PackWorld>();
|
||||
var stage = Stage.chunk("test:alpha/scope");
|
||||
var module = new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(ALPHA, "Scope", "1"); }
|
||||
public void setup(ModuleSetup setup) { setup.stages().define(stage).run(context -> seen.add(context.world())); }
|
||||
};
|
||||
var runner = new ChunkRunner(TestSetups.stages(module).resolve(Pipeline.CHUNK));
|
||||
|
||||
try (var first = new TestWorld(); var second = new TestWorld()) {
|
||||
for (var world : List.of(first, first, second)) {
|
||||
runner.generate(TestContexts.generation(null, null, null, world), TestContexts.SEED, StageTimings.NONE);
|
||||
}
|
||||
}
|
||||
|
||||
assertSame(seen.get(0), seen.get(1), "the module's view of a world is built once, not per invocation");
|
||||
assertNotSame(seen.get(1), seen.get(2), "another world gets its own view");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,625 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.*;
|
||||
import com.volmit.config.Feature;
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.data.SavedKey;
|
||||
import com.volmit.data.StorageCodec;
|
||||
import com.volmit.mantle.*;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
import com.volmit.service.Providers;
|
||||
import com.volmit.service.Service;
|
||||
import com.volmit.validation.Validator;
|
||||
import com.volmit.service.VanillaStructures;
|
||||
import com.volmit.stage.PlacementStage;
|
||||
import com.volmit.stage.Stage;
|
||||
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.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ModuleRegistryTest {
|
||||
@Feature(id = "test:core/one", name = "One", key = "coreOne", targets = Level.BIOME)
|
||||
static class One implements IrisFeature {}
|
||||
@Feature(id = "test:core/two", name = "Two", key = "coreTwo", targets = Level.DIMENSION)
|
||||
static class Two implements IrisFeature {}
|
||||
@Feature(id = "test:core/one", name = "Duplicate", key = "coreOne", targets = Level.REGION)
|
||||
static class Duplicate implements IrisFeature {}
|
||||
@Feature(id = "test:ores", name = "Ores", key = "deposits", targets = {Level.BIOME, Level.REGION})
|
||||
static class Ores implements IrisFeature {}
|
||||
@Feature(id = "test:minerals", name = "Minerals", key = "deposits", targets = Level.REGION)
|
||||
static class Minerals implements IrisFeature {}
|
||||
@Feature(id = "test:veins", name = "Veins", key = "deposits", targets = Level.DIMENSION)
|
||||
static class Veins implements IrisFeature {}
|
||||
@Feature(id = "test:named", name = "Named", key = "name", targets = Level.BIOME)
|
||||
static class Named implements IrisFeature {}
|
||||
@Feature(id = "test:seams", name = "Seams", key = "deposits", targets = Level.PLACEMENT)
|
||||
static class Seams implements IrisFeature {}
|
||||
static class Placement {}
|
||||
static class OtherPlacement {}
|
||||
static class MissingAnnotation implements IrisFeature {}
|
||||
@Feature(id = "test:core/abstract", name = "Abstract", key = "coreAbstract", targets = Level.BIOME)
|
||||
abstract static class AbstractFeature implements IrisFeature {}
|
||||
|
||||
/** Runs {@code registrations} as the setup(...) of a built-in module with the given id. */
|
||||
private static void registerAs(ModuleRegistry registry, String moduleId, Consumer<FeatureRegistry> registrations) {
|
||||
ModuleSetups.run(DiscoveredModule.builtIn(new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(moduleId, "Test module " + moduleId, "1"); }
|
||||
public void setup(ModuleSetup setup) { registrations.accept(setup.registry()); }
|
||||
}), new StageGraphBuilder(), registry);
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatesIdsTypesAndFieldsAcrossFeatureKindsWithoutPartialRegistration() {
|
||||
var registry = new ModuleRegistry();
|
||||
registerAs(registry, "test:core", settings -> settings.registerSettings(One.class));
|
||||
registry.registerStageSettings(One.class);
|
||||
registerAs(registry, "test:core", settings -> {
|
||||
settings.registerSettings(Two.class);
|
||||
assertThrows(IllegalArgumentException.class, () -> settings.registerSettings(Duplicate.class));
|
||||
});
|
||||
var catalog = registry.freeze();
|
||||
assertEquals(List.of("test:core/one", "test:core/two"), catalog.settings().stream().map(value -> value.id().toString()).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidFeatures() {
|
||||
var registry = new ModuleRegistry();
|
||||
assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(MissingAnnotation.class));
|
||||
assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(AbstractFeature.class));
|
||||
registerAs(registry, "test:core", settings -> settings.registerSettings(Two.class));
|
||||
assertSame(registry.freeze(), registry.freeze());
|
||||
assertThrows(IllegalStateException.class, () -> registry.registerStageSettings(One.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mantleIdsAreUniqueAndCodecVersionIsSnapshotted() {
|
||||
var registry = new ModuleRegistry();
|
||||
var key = new MantleKey<>(ResourceId.parse("test:core/layer"), String.class);
|
||||
var codec = codec(3);
|
||||
registerAs(registry, "test:core", layers -> {
|
||||
layers.registerMantle(key, MantleLifetime.GENERATION, codec);
|
||||
assertThrows(IllegalArgumentException.class, () -> layers.registerMantle(key, MantleLifetime.PERSISTENT, codec));
|
||||
assertThrows(IllegalArgumentException.class, () -> layers.registerMantle(new MantleKey<>(ResourceId.parse("test:core/bad"), String.class), MantleLifetime.GENERATION, codec(-1)));
|
||||
});
|
||||
assertEquals(3, registry.freeze().mantle().getFirst().version());
|
||||
assertEquals(1, registry.freeze().mantle().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsIdsAndMantleKeysAreTheRegisteringModulesIdOrBelowIt() {
|
||||
var registry = new ModuleRegistry();
|
||||
var sameNamespace = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:other",
|
||||
settings -> settings.registerSettings(Two.class)));
|
||||
assertTrue(sameNamespace.getMessage().contains("must be test:other or start with test:other/"), sameNamespace.getMessage());
|
||||
|
||||
var mantle = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "iris:snow",
|
||||
layers -> layers.registerMantle(new MantleKey<>(ResourceId.parse("iris:snowdepth"), String.class), MantleLifetime.GENERATION, codec(1))));
|
||||
assertEquals("Mantle layer iris:snowdepth must be iris:snow or start with iris:snow/, the id of its registering module "
|
||||
+ "iris:snow from host classpath", mantle.getMessage());
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> registry.registerMantle(new MantleKey<>(ResourceId.parse("test:loose"), String.class),
|
||||
MantleLifetime.GENERATION, codec(1)));
|
||||
assertTrue(registry.freeze().settings().isEmpty());
|
||||
assertTrue(registry.freeze().mantle().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void studioViewsHaveIdsUniqueAcrossKindsTheirModuleOwnsAndAreCataloguedById() {
|
||||
var registry = new ModuleRegistry();
|
||||
ModuleSetups.run(DiscoveredModule.builtIn(new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of("iris:objects", "Objects", "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.tooling().registerView(sceneView("iris:objects/procedural"));
|
||||
setup.tooling().registerView(sceneView("iris:objects"));
|
||||
setup.tooling().registerView(patternView("iris:objects/footprints"));
|
||||
var duplicate = assertThrows(IllegalArgumentException.class,
|
||||
() -> setup.tooling().registerView(patternView("iris:objects")));
|
||||
assertTrue(duplicate.getMessage().contains("Studio view iris:objects is registered by module"), duplicate.getMessage());
|
||||
var foreign = assertThrows(IllegalArgumentException.class,
|
||||
() -> setup.tooling().registerView(sceneView("iris:terrain/palettes")));
|
||||
assertTrue(foreign.getMessage().contains("must be iris:objects or start with iris:objects/"), foreign.getMessage());
|
||||
}
|
||||
}), new StageGraphBuilder(), registry);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> registry.registerView(sceneView("iris:objects/loose")));
|
||||
var views = registry.freeze().studioViews();
|
||||
assertEquals(List.of("iris:objects", "iris:objects/footprints", "iris:objects/procedural"),
|
||||
views.stream().map(view -> view.view().id().toString()).toList());
|
||||
assertTrue(views.get(1).toString().startsWith("pattern view iris:objects/footprints of module"), views.get(1).toString());
|
||||
}
|
||||
|
||||
private static IrisModule commandModule(String id, com.volmit.tooling.Command... roots) {
|
||||
return new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(id, id, "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
for (var root : roots) setup.tooling().registerCommand(root);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void rootCommandsAreCataloguedByNameAndKeepTheirModule() {
|
||||
var registry = new ModuleRegistry();
|
||||
ModuleSetups.run(DiscoveredModule.builtIn(commandModule("test:b",
|
||||
com.volmit.tooling.Command.named("zeta"))), new StageGraphBuilder(), registry);
|
||||
ModuleSetups.run(DiscoveredModule.builtIn(commandModule("test:a",
|
||||
com.volmit.tooling.Command.named("alpha").alias("a"))), new StageGraphBuilder(), registry);
|
||||
|
||||
var commands = registry.freeze().commands();
|
||||
assertEquals(List.of("alpha", "zeta"), commands.stream().map(root -> root.command().name()).toList());
|
||||
assertEquals("test:a", commands.getFirst().module().info().id().toString());
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> registry.registerCommand(com.volmit.tooling.Command.named("late")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoModulesClaimingOneRootNameOrAliasFailNamingBoth() {
|
||||
var registry = new ModuleRegistry();
|
||||
ModuleSetups.run(DiscoveredModule.builtIn(commandModule("test:first",
|
||||
com.volmit.tooling.Command.named("structure").alias("str"))), new StageGraphBuilder(), registry);
|
||||
|
||||
var sameName = assertThrows(IllegalArgumentException.class, () -> ModuleSetups.run(DiscoveredModule.builtIn(
|
||||
commandModule("test:second", com.volmit.tooling.Command.named("structure"))), new StageGraphBuilder(), registry));
|
||||
assertTrue(sameName.getMessage().contains("Command root structure is registered by module"), sameName.getMessage());
|
||||
assertTrue(sameName.getMessage().contains("test:first") && sameName.getMessage().contains("test:second"), sameName.getMessage());
|
||||
|
||||
var aliasOfFirst = assertThrows(IllegalArgumentException.class, () -> ModuleSetups.run(DiscoveredModule.builtIn(
|
||||
commandModule("test:third", com.volmit.tooling.Command.named("str"))), new StageGraphBuilder(), registry));
|
||||
assertTrue(aliasOfFirst.getMessage().contains("Command root str is registered by module"), aliasOfFirst.getMessage());
|
||||
assertEquals(1, registry.freeze().commands().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPackLoadFailsWhenTwoModulesClaimOneRootName() {
|
||||
var failure = assertThrows(ModuleLoadException.class, () -> LoadedModules.load(List.of(
|
||||
DiscoveredModule.builtIn(commandModule("test:first", com.volmit.tooling.Command.named("tools"))),
|
||||
DiscoveredModule.builtIn(commandModule("test:second", com.volmit.tooling.Command.named("tools")))),
|
||||
Map.of(), List.of(), List.of()));
|
||||
assertTrue(failure.getMessage().contains("test:first") && failure.getMessage().contains("test:second"), failure.getMessage());
|
||||
}
|
||||
|
||||
private static com.volmit.tooling.PatternView patternView(String id) {
|
||||
return new com.volmit.tooling.PatternView() {
|
||||
public com.volmit.resource.ResourceId id() { return com.volmit.resource.ResourceId.parse(id); }
|
||||
public String label() { return id; }
|
||||
public String description() { return id; }
|
||||
public List<com.volmit.tooling.PatternEntry> entries(com.volmit.world.PackWorld world) { return List.of(); }
|
||||
public Optional<com.volmit.tooling.BlockPattern> pattern(com.volmit.world.PackWorld world, String key, int depth,
|
||||
com.volmit.tooling.PatternArea area) {
|
||||
return Optional.empty();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static com.volmit.tooling.SceneView sceneView(String id) {
|
||||
return new com.volmit.tooling.SceneView() {
|
||||
public com.volmit.resource.ResourceId id() { return com.volmit.resource.ResourceId.parse(id); }
|
||||
public String label() { return id; }
|
||||
public String description() { return id; }
|
||||
public List<com.volmit.tooling.SceneEntry> entries(com.volmit.world.PackWorld world) { return List.of(); }
|
||||
public Optional<com.volmit.object.GeneratedObject> scene(com.volmit.world.PackWorld world, String key, int variant) {
|
||||
return Optional.empty();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static SavedKey<String> saved(String id) {
|
||||
return new SavedKey<>(ResourceId.parse(id), String.class, codec(1), () -> "");
|
||||
}
|
||||
|
||||
@Test
|
||||
void savedKeysAreOwnedByTheRegisteringModuleAndUnique() {
|
||||
var registry = new ModuleRegistry();
|
||||
var key = saved("test:core/book");
|
||||
registerAs(registry, "test:core", saves -> {
|
||||
saves.registerSaved(key);
|
||||
assertThrows(IllegalArgumentException.class, () -> saves.registerSaved(saved("test:core/book")));
|
||||
assertThrows(NullPointerException.class, () -> saves.registerSaved(null));
|
||||
});
|
||||
assertEquals(List.of(key), registry.freeze().saved());
|
||||
|
||||
var foreign = assertThrows(IllegalArgumentException.class, () -> registerAs(new ModuleRegistry(), "test:other",
|
||||
saves -> saves.registerSaved(key)));
|
||||
assertTrue(foreign.getMessage().contains("must be test:other or start with test:other/"), foreign.getMessage());
|
||||
assertThrows(IllegalStateException.class, () -> new ModuleRegistry().registerSaved(key));
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleMayRegisterItsOwnIdAndIdsBelowIt() {
|
||||
var registry = new ModuleRegistry();
|
||||
registerAs(registry, "iris:snow", layers -> {
|
||||
layers.registerMantle(new MantleKey<>(ResourceId.parse("iris:snow"), String.class), MantleLifetime.GENERATION, codec(1));
|
||||
layers.registerMantle(new MantleKey<>(ResourceId.parse("iris:snow/depth/deep"), String.class), MantleLifetime.GENERATION, codec(1));
|
||||
});
|
||||
|
||||
assertEquals(List.of("iris:snow", "iris:snow/depth/deep"),
|
||||
registry.freeze().mantle().stream().map(layer -> layer.key().id().toString()).sorted().toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadingModulesCatalogsStageSettingsAndRegistrationsTogether() {
|
||||
var conditioned = new IrisModule() {
|
||||
static final PlacementStage<Void> WORK = Stage.placement("test:core/work");
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:core", "Conditioned", "1"); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(WORK).when(One.class).run(context -> {});
|
||||
setup.registry().registerSettings(Two.class);
|
||||
}
|
||||
};
|
||||
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), Map.of(), Set.of(), Set.of());
|
||||
assertEquals(List.of("test:core/one", "test:core/two"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList());
|
||||
assertEquals(1, loaded.placement().stages().size());
|
||||
assertTrue(loaded.chunk().stages().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoModulesWithOneIdRefuseTheLoadNamingBothSoASettingsKeyIsNeverShared() {
|
||||
var first = ownerOfOne("First");
|
||||
var second = ownerOfOne("Second");
|
||||
|
||||
var clash = assertThrows(ModuleLoadException.class,
|
||||
() -> LoadedModules.load(List.of(DiscoveredModule.builtIn(first), DiscoveredModule.builtIn(second)), Map.of(), Set.of(), Set.of()));
|
||||
|
||||
assertTrue(clash.getMessage().startsWith("Duplicate module test:core from "), clash.getMessage());
|
||||
assertTrue(clash.getMessage().contains("already loaded from "), clash.getMessage());
|
||||
}
|
||||
|
||||
private static IrisModule settingsModule(String id, Class<? extends IrisFeature> settings) {
|
||||
return new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(id, id, "1"); }
|
||||
public void setup(ModuleSetup setup) { setup.registry().registerSettings(settings); }
|
||||
};
|
||||
}
|
||||
|
||||
private static List<DiscoveredModule> discovered(IrisModule... modules) {
|
||||
return java.util.Arrays.stream(modules).map(DiscoveredModule::builtIn).toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoModulesTakingOneKeyAtOneTargetRefuseTheLoadNamingKeyTargetAndBothClaimants() {
|
||||
var ores = settingsModule("test:ores", Ores.class);
|
||||
var minerals = settingsModule("test:minerals", Minerals.class);
|
||||
|
||||
var clash = assertThrows(ModuleLoadException.class,
|
||||
() -> LoadedModules.load(discovered(ores, minerals), Map.of(), Set.of(), Set.of()));
|
||||
|
||||
assertEquals("region key \"deposits\" is claimed by test:minerals (host classpath) and test:ores (host classpath);"
|
||||
+ " give one of the settings another key in its @Feature", clash.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameKeyAtDifferentTargetsIsNotAClash() {
|
||||
var loaded = LoadedModules.load(discovered(settingsModule("test:ores", Ores.class), settingsModule("test:veins", Veins.class)),
|
||||
Map.of(), Set.of(), Set.of());
|
||||
|
||||
assertEquals(List.of("test:ores", "test:veins"), loaded.catalog().settings().stream().map(value -> value.id().toString()).sorted().toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyTheHostUsesAsAFieldOfTheTargetIsRefusedNamingIris() {
|
||||
var reserved = Map.of(Level.BIOME, Set.of("name", "generators"));
|
||||
|
||||
var clash = assertThrows(ModuleLoadException.class,
|
||||
() -> LoadedModules.load(discovered(settingsModule("test:named", Named.class)), reserved, Set.of(), Set.of()));
|
||||
|
||||
assertEquals("biome key \"name\" is claimed by Iris and test:named (host classpath);"
|
||||
+ " give one of the settings another key in its @Feature", clash.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHostFieldOfAnotherTargetDoesNotTakeTheKey() {
|
||||
var reserved = Map.of(Level.REGION, Set.of("name"));
|
||||
|
||||
var loaded = LoadedModules.load(discovered(settingsModule("test:named", Named.class)), reserved, Set.of(), Set.of());
|
||||
|
||||
assertEquals(1, loaded.catalog().settings().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClashingRegisteredOrStageSettingsTypeClaimsTheKeyToo() {
|
||||
var registry = new ModuleRegistry();
|
||||
registerAs(registry, "test:ores", settings -> settings.registerSettings(Ores.class));
|
||||
var registered = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:minerals",
|
||||
settings -> settings.registerSettings(Minerals.class)));
|
||||
assertTrue(registered.getMessage().startsWith("region key \"deposits\" is claimed by test:minerals (host classpath) and test:ores"), registered.getMessage());
|
||||
|
||||
var conditioned = new IrisModule() {
|
||||
static final PlacementStage<Void> WORK = Stage.placement("test:minerals/work");
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:minerals", "Minerals", "1"); }
|
||||
public void setup(ModuleSetup setup) { setup.stages().define(WORK).when(Minerals.class).run(context -> {}); }
|
||||
};
|
||||
var stage = assertThrows(ModuleLoadException.class,
|
||||
() -> LoadedModules.load(discovered(settingsModule("test:ores", Ores.class), conditioned), Map.of(), Set.of(), Set.of()));
|
||||
assertTrue(stage.getMessage().startsWith("region key \"deposits\" is claimed by test:minerals (host classpath) and test:ores"), stage.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlacementTypeIsKeptWithItsFieldsAndReservesThemAsKeysOfThePlacementLevel() {
|
||||
var registry = new ModuleRegistry();
|
||||
registerAs(registry, "test:objects", placements -> placements.registerPlacementType(Placement.class, Set.of("place", "chance")));
|
||||
|
||||
var declared = registry.freeze().placementType().orElseThrow();
|
||||
|
||||
assertEquals(Placement.class, declared.type());
|
||||
assertEquals(Set.of("place", "chance"), declared.jsonFields());
|
||||
assertTrue(new ModuleRegistry().freeze().placementType().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSchemaNamesThePlacementTypeForStudio() {
|
||||
var objects = new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:objects", "Objects", "1"); }
|
||||
public void setup(ModuleSetup setup) { setup.registry().registerPlacementType(Placement.class, Set.of("place")); }
|
||||
};
|
||||
|
||||
var loaded = LoadedModules.load(discovered(objects), Map.of(), Set.of(), Set.of());
|
||||
|
||||
assertEquals(Optional.of(Placement.class.getName()), loaded.schema().placementType());
|
||||
assertTrue(LoadedModules.load(discovered(), Map.of(), Set.of(), Set.of()).schema().placementType().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSettingsKeyThatIsAFieldOfThePlacementTypeIsRefusedInEitherOrder() {
|
||||
var placementFirst = new ModuleRegistry();
|
||||
registerAs(placementFirst, "test:objects", placements -> placements.registerPlacementType(Placement.class, Set.of("deposits")));
|
||||
var late = assertThrows(IllegalArgumentException.class,
|
||||
() -> registerAs(placementFirst, "test:seams", settings -> settings.registerSettings(Seams.class)));
|
||||
assertEquals("placement key \"deposits\" is claimed by the fields of " + Placement.class.getName()
|
||||
+ " (host classpath) and test:seams (host classpath); give one of the settings another key in its @Feature", late.getMessage());
|
||||
|
||||
var settingsFirst = new ModuleRegistry();
|
||||
registerAs(settingsFirst, "test:seams", settings -> settings.registerSettings(Seams.class));
|
||||
var early = assertThrows(IllegalArgumentException.class,
|
||||
() -> registerAs(settingsFirst, "test:objects", placements -> placements.registerPlacementType(Placement.class, Set.of("deposits"))));
|
||||
assertEquals("placement key \"deposits\" is claimed by the fields of " + Placement.class.getName()
|
||||
+ " (host classpath) and test:seams (host classpath); give the setting another key in its @Feature", early.getMessage());
|
||||
assertTrue(settingsFirst.freeze().placementType().isEmpty(), "a refused placement type is not kept");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPackHasOnePlacementType() {
|
||||
var registry = new ModuleRegistry();
|
||||
registerAs(registry, "test:objects", placements -> placements.registerPlacementType(Placement.class, Set.of("place")));
|
||||
|
||||
var second = assertThrows(IllegalArgumentException.class,
|
||||
() -> registerAs(registry, "test:other", placements -> placements.registerPlacementType(OtherPlacement.class, Set.of("kind"))));
|
||||
|
||||
assertTrue(second.getMessage().startsWith("A pack has one placement type: placement type " + Placement.class.getName()
|
||||
+ " from module test:objects from host classpath declared it already"), second.getMessage());
|
||||
assertEquals(Placement.class, registry.freeze().placementType().orElseThrow().type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedKeyLeavesNothingClaimedByTheFailedFeature() {
|
||||
var registry = new ModuleRegistry(Map.of(Level.REGION, Set.of("deposits")), Set.of());
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:ores", settings -> settings.registerSettings(Ores.class)));
|
||||
|
||||
registerAs(registry, "test:veins", settings -> settings.registerSettings(Veins.class));
|
||||
assertEquals(List.of("test:veins"), registry.freeze().settings().stream().map(value -> value.id().toString()).toList());
|
||||
}
|
||||
|
||||
private static IrisModule ownerOfOne(String name) {
|
||||
return new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:core", name, "1"); }
|
||||
public void setup(ModuleSetup setup) { setup.registry().registerSettings(One.class); }
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleRegistersItsOwnSettingsExplicitlyAndRepeatingItChangesNothing() {
|
||||
var registry = new ModuleRegistry();
|
||||
registerAs(registry, "test:core", settings -> {
|
||||
settings.registerSettings(One.class);
|
||||
settings.registerSettings(One.class);
|
||||
});
|
||||
registry.registerStageSettings(One.class);
|
||||
|
||||
assertEquals(List.of("test:core/one"), registry.freeze().settings().stream().map(value -> value.id().toString()).toList());
|
||||
assertTrue(registry.registeredByOwner(One.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitSettingsFollowTheRegisteringModulesIdAndStillCollide() {
|
||||
var registry = new ModuleRegistry();
|
||||
var foreign = assertThrows(IllegalArgumentException.class,
|
||||
() -> registerAs(registry, "test:other", settings -> settings.registerSettings(One.class)));
|
||||
assertEquals("Settings " + One.class.getName() + " with feature id test:core/one must be test:other or start with "
|
||||
+ "test:other/, the id of its registering module test:other from host classpath", foreign.getMessage());
|
||||
assertThrows(IllegalStateException.class, () -> registry.registerSettings(One.class));
|
||||
|
||||
registerAs(registry, "test:core", settings -> settings.registerSettings(One.class));
|
||||
var collision = assertThrows(IllegalArgumentException.class,
|
||||
() -> registerAs(registry, "test:core", settings -> settings.registerSettings(Duplicate.class)));
|
||||
assertEquals("Duplicate feature: test:core/one", collision.getMessage());
|
||||
assertEquals(List.of(One.class), registry.freeze().settings().stream().map(FeatureDescriptor::type).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsTheirOwnerRegisteredMayBeNamedByAnyModule() {
|
||||
var owner = new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:core", "Owner", "1"); }
|
||||
public void setup(ModuleSetup setup) { setup.registry().registerSettings(One.class); }
|
||||
};
|
||||
var user = new IrisModule() {
|
||||
static final PlacementStage<Void> WORK = Stage.placement("test:user/work");
|
||||
public ModuleInfo info() { return ModuleInfo.of("test:user", "User", "1"); }
|
||||
public void setup(ModuleSetup setup) { setup.stages().define(WORK).when(One.class).run(context -> {}); }
|
||||
};
|
||||
|
||||
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(owner), DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of());
|
||||
assertEquals(List.of("test:core/one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList());
|
||||
|
||||
var unowned = assertThrows(ModuleLoadException.class,
|
||||
() -> LoadedModules.load(List.of(DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of()));
|
||||
assertTrue(unowned.getMessage().contains("which none of the modules naming it in when(...) owns"), unowned.getMessage());
|
||||
}
|
||||
|
||||
static class Castle {}
|
||||
static class Pool {}
|
||||
|
||||
@Test
|
||||
void resourceKindsHaveOwnedIdsAndOneIdTypeAndFolderEach() {
|
||||
var registry = new ModuleRegistry(Map.of(), Set.of("biomes"));
|
||||
var castles = ResourceKind.of("test:core/castle", "castles", Castle.class);
|
||||
registerAs(registry, "test:core", kinds -> {
|
||||
kinds.registerResourceKind(castles);
|
||||
var duplicate = assertThrows(IllegalArgumentException.class, () -> kinds.registerResourceKind(castles));
|
||||
assertEquals("Duplicate resource kind: test:core/castle of module test:core from host classpath", duplicate.getMessage());
|
||||
});
|
||||
|
||||
var foreign = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:other",
|
||||
kinds -> kinds.registerResourceKind(ResourceKind.of("test:core/pool", "pools", Pool.class))));
|
||||
assertEquals("Resource kind test:core/pool must be test:other or start with test:other/, the id of its registering"
|
||||
+ " module test:other from host classpath", foreign.getMessage());
|
||||
|
||||
var sameType = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:other",
|
||||
kinds -> kinds.registerResourceKind(ResourceKind.of("test:other/castle", "keeps", Castle.class))));
|
||||
assertEquals("resource kind test:other/castle of module test:other from host classpath reads into " + Castle.class.getName()
|
||||
+ ", which resource kind test:core/castle of module test:core from host classpath reads into already; resources"
|
||||
+ " are found by their type, so each kind needs a class of its own", sameType.getMessage());
|
||||
|
||||
var sameFolder = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:other",
|
||||
kinds -> kinds.registerResourceKind(ResourceKind.of("test:other/pool", "castles", Pool.class))));
|
||||
assertEquals("resource kind test:other/pool of module test:other from host classpath reads folder 'castles', which"
|
||||
+ " resource kind test:core/castle of module test:core from host classpath reads already; a folder holds one kind,"
|
||||
+ " so give one of them a folder of its own", sameFolder.getMessage());
|
||||
|
||||
var hostFolder = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:other",
|
||||
kinds -> kinds.registerResourceKind(ResourceKind.of("test:other/pool", "biomes", Pool.class))));
|
||||
assertEquals("Resource kind test:other/pool of module test:other from host classpath reads folder 'biomes', which the"
|
||||
+ " host reads itself; give the kind a folder of its own", hostFolder.getMessage());
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> registry.registerResourceKind(ResourceKind.of("test:core/pool", "pools", Pool.class)));
|
||||
assertEquals(List.of(castles), registry.freeze().resourceKinds().stream().map(ResourceKindRegistration::kind).toList());
|
||||
assertEquals("test:core", registry.freeze().resourceKinds().getFirst().module().info().id().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatorsAreCataloguedByModuleIdInTheOrderEachModuleRegisteredThem() {
|
||||
var registry = new ModuleRegistry();
|
||||
Validator first = pack -> {};
|
||||
Validator second = pack -> {};
|
||||
Validator other = pack -> {};
|
||||
registerAs(registry, "test:zeta", validators -> validators.registerValidator(other));
|
||||
registerAs(registry, "test:alpha", validators -> {
|
||||
validators.registerValidator(first);
|
||||
validators.registerValidator(second);
|
||||
});
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> registry.registerValidator(pack -> {}));
|
||||
assertEquals(List.of(first, second, other), registry.freeze().validators().stream().map(ValidatorRegistration::validator).toList());
|
||||
assertEquals("test:alpha", registry.freeze().validators().getFirst().module().info().id().toString());
|
||||
assertThrows(IllegalStateException.class, () -> registry.registerValidator(pack -> {}), "registration has ended");
|
||||
}
|
||||
|
||||
@Service(Providers.ALL)
|
||||
interface Greeting { String greet(); }
|
||||
@Service(Providers.ONE)
|
||||
interface Clock { long now(); }
|
||||
interface NotAService { void run(); }
|
||||
|
||||
@Test
|
||||
void lifecyclesAreCataloguedByModuleIdInTheOrderEachModuleRegisteredThem() {
|
||||
var registry = new ModuleRegistry();
|
||||
ModuleLifecycle first = new ModuleLifecycle() {};
|
||||
ModuleLifecycle second = new ModuleLifecycle() {};
|
||||
ModuleLifecycle other = new ModuleLifecycle() {};
|
||||
registerAs(registry, "test:zeta", hooks -> hooks.registerLifecycle(other));
|
||||
registerAs(registry, "test:alpha", hooks -> {
|
||||
hooks.registerLifecycle(first);
|
||||
hooks.registerLifecycle(second);
|
||||
});
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> registry.registerLifecycle(new ModuleLifecycle() {}),
|
||||
"registration outside IrisModule.setup");
|
||||
var catalog = registry.freeze();
|
||||
assertEquals(List.of(first, second, other), catalog.lifecycles().stream().map(LifecycleRegistration::lifecycle).toList());
|
||||
assertEquals("test:alpha", catalog.lifecycles().getFirst().module().info().id().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceProvidersComeInModuleIdOrderAndEachModulesInRegistrationOrder() {
|
||||
var registry = new ModuleRegistry();
|
||||
Greeting zeta = () -> "zeta";
|
||||
Greeting alphaFirst = () -> "alpha 1";
|
||||
Greeting alphaSecond = () -> "alpha 2";
|
||||
registerAs(registry, "test:zeta", services -> services.registerService(Greeting.class, zeta));
|
||||
registerAs(registry, "test:alpha", services -> {
|
||||
services.registerService(Greeting.class, alphaFirst);
|
||||
services.registerService(Greeting.class, alphaSecond);
|
||||
});
|
||||
|
||||
var catalog = registry.freeze();
|
||||
assertEquals(List.of(alphaFirst, alphaSecond, zeta), catalog.services(Greeting.class));
|
||||
assertEquals(List.of(), catalog.services(Clock.class), "a service nobody provides has no providers");
|
||||
assertEquals(Optional.empty(), catalog.service(Clock.class));
|
||||
var several = assertThrows(IllegalArgumentException.class, () -> catalog.service(Greeting.class));
|
||||
assertTrue(several.getMessage().contains("services(...)"), several.getMessage());
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.services(NotAService.class));
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.registrations(NotAService.class), "asking again still refuses it");
|
||||
assertEquals(List.of(alphaFirst, alphaSecond, zeta),
|
||||
catalog.registrations(Greeting.class).stream().map(ServiceRegistration::provider).toList());
|
||||
assertEquals(List.of(), catalog.registrations(Clock.class));
|
||||
assertThrows(UnsupportedOperationException.class, () -> catalog.services(Greeting.class).clear(), "the catalog is frozen");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceWithOneProviderFailsTheLoadWhenASecondModuleProvidesIt() {
|
||||
var registry = new ModuleRegistry();
|
||||
Clock clock = () -> 1L;
|
||||
registerAs(registry, "test:alpha", services -> services.registerService(Clock.class, clock));
|
||||
registerAs(registry, "test:zeta", services -> {
|
||||
var duplicate = assertThrows(IllegalArgumentException.class, () -> services.registerService(Clock.class, () -> 2L));
|
||||
assertTrue(duplicate.getMessage().contains("test:alpha from host classpath"), duplicate.getMessage());
|
||||
assertTrue(duplicate.getMessage().contains("test:zeta from host classpath"), duplicate.getMessage());
|
||||
});
|
||||
|
||||
assertEquals(Optional.of(clock), registry.freeze().service(Clock.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"}) // A raw class lets a provider of the wrong type reach the check.
|
||||
void servicesMustBeMarkedInterfacesThatTheProviderImplements() {
|
||||
var registry = new ModuleRegistry();
|
||||
registerAs(registry, "test:alpha", services -> {
|
||||
var unmarked = assertThrows(IllegalArgumentException.class,
|
||||
() -> services.registerService(NotAService.class, () -> {}));
|
||||
assertTrue(unmarked.getMessage().contains("@" + Service.class.getName()), unmarked.getMessage());
|
||||
assertThrows(IllegalArgumentException.class, () -> services.registerService(Object.class, new Object()));
|
||||
assertThrows(IllegalArgumentException.class, () -> services.registerService((Class) Greeting.class, (Clock) () -> 1L));
|
||||
assertThrows(NullPointerException.class, () -> services.registerService(Greeting.class, null));
|
||||
});
|
||||
assertThrows(IllegalStateException.class, () -> registry.registerService(Greeting.class, () -> "outside"));
|
||||
assertEquals(List.of(), registry.freeze().services(Greeting.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vanillaStructuresAreAServiceEveryModuleMayProvide() {
|
||||
var registry = new ModuleRegistry();
|
||||
VanillaStructures first = new VanillaStructures() { };
|
||||
VanillaStructures other = new VanillaStructures() { };
|
||||
registerAs(registry, "test:zeta", services -> services.registerService(VanillaStructures.class, other));
|
||||
registerAs(registry, "test:alpha", services -> services.registerService(VanillaStructures.class, first));
|
||||
|
||||
assertEquals(List.of(first, other), registry.freeze().services(VanillaStructures.class));
|
||||
var registrations = registry.freeze().registrations(VanillaStructures.class);
|
||||
assertEquals(List.of(first, other), registrations.stream().map(ServiceRegistration::provider).toList());
|
||||
assertEquals("test:alpha", registrations.getFirst().module().info().id().toString());
|
||||
}
|
||||
|
||||
private static StorageCodec<String> codec(int version) {
|
||||
return new StorageCodec<>() {
|
||||
public int version() { return version; }
|
||||
public void write(DataOutput output, String value) {}
|
||||
public String read(DataInput input, int storedVersion) { return ""; }
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.host.NonExportedJdkPackages.JdkPackage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.Optional;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class NonExportedJdkPackagesTest {
|
||||
@Test
|
||||
void namesPackagesTheirModuleDoesNotExport() {
|
||||
assertEquals(Optional.of(new JdkPackage("jdk.internal.misc", "java.base")),
|
||||
NonExportedJdkPackages.packageOf("jdk.internal.misc.Unsafe"));
|
||||
assertEquals(Optional.of(new JdkPackage("sun.nio.ch", "java.base")), NonExportedJdkPackages.packageOf("sun.nio.ch.Net"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packagesExportedOnlyToNamedModulesAreNotExported() {
|
||||
assertEquals(Optional.of(new JdkPackage("jdk.internal.access", "java.base")),
|
||||
NonExportedJdkPackages.packageOf("jdk.internal.access.SharedSecrets"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void exportedPackagesAreUsable() {
|
||||
assertEquals(Optional.empty(), NonExportedJdkPackages.packageOf("sun.misc.Unsafe"));
|
||||
assertEquals(Optional.empty(), NonExportedJdkPackages.packageOf("java.lang.String"));
|
||||
assertEquals(Optional.empty(), NonExportedJdkPackages.packageOf("java.sql.Connection"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void modulesOutsideThePlatformLoaderAndNonJdkClassesAreNotListed() {
|
||||
assertEquals(Optional.empty(), NonExportedJdkPackages.packageOf("com.sun.tools.javac.code.Type"));
|
||||
assertEquals(Optional.empty(), NonExportedJdkPackages.packageOf("org.slf4j.Logger"));
|
||||
assertEquals(Optional.empty(), NonExportedJdkPackages.packageOf("TopLevel"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.support.TestModuleJar;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import static com.volmit.support.TestModuleJar.module;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PackJarSnapshotTest {
|
||||
private static final String NO_MEMBERS = "";
|
||||
private static final String NO_STAGES = "";
|
||||
private static final String UNUSED_CLASS = "pack.gamma.Unused";
|
||||
private static final long EXITED_PROCESS = Long.MAX_VALUE;
|
||||
|
||||
@TempDir
|
||||
Path pack;
|
||||
|
||||
@TempDir
|
||||
Path temporaryRoot;
|
||||
|
||||
private static String origin(String jarName) {
|
||||
return Path.of(PackModules.MODULES_DIRECTORY, jarName).toString();
|
||||
}
|
||||
|
||||
private Path writeGamma() {
|
||||
return module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_STAGES)
|
||||
.source(UNUSED_CLASS, "package pack.gamma; final class Unused {}")
|
||||
.writeInto(pack, "gamma.jar");
|
||||
}
|
||||
|
||||
private PackModules load() {
|
||||
return PackModules.load(pack, List.of(), temporaryRoot);
|
||||
}
|
||||
|
||||
private List<Path> snapshotDirectories() throws IOException {
|
||||
try (var entries = Files.list(temporaryRoot)) {
|
||||
return entries.filter(entry -> entry.getFileName().toString().startsWith(JarSnapshot.DIRECTORY_PREFIX)).toList();
|
||||
}
|
||||
}
|
||||
|
||||
private Path staleDirectory(String name, String ownerRecord) throws IOException {
|
||||
var directory = Files.createDirectory(temporaryRoot.resolve(JarSnapshot.DIRECTORY_PREFIX + name));
|
||||
Files.writeString(directory.resolve(JarSnapshot.OWNER_FILE), ownerRecord);
|
||||
Files.write(directory.resolve("moss.jar"), new byte[] {1, 2, 3});
|
||||
return directory;
|
||||
}
|
||||
|
||||
@Test
|
||||
void loaderReadsFromACopySoTheOriginalCanBeReplacedWhileLoaded() throws Exception {
|
||||
var original = writeGamma();
|
||||
|
||||
try (var packModules = load()) {
|
||||
var module = packModules.modules().getFirst();
|
||||
var location = Path.of(module.module().getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||
assertEquals(1, snapshotDirectories().size());
|
||||
assertEquals(snapshotDirectories().getFirst().resolve("0-gamma.jar"), location);
|
||||
assertEquals(origin("gamma.jar"), module.origin());
|
||||
|
||||
Files.delete(original);
|
||||
Files.write(original, new byte[] {0});
|
||||
assertNotNull(module.module().getClass().getClassLoader().loadClass(UNUSED_CLASS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void copiesAreDeletedWhenThePackCloses() throws Exception {
|
||||
writeGamma();
|
||||
|
||||
try (var ignored = load()) {
|
||||
assertEquals(1, snapshotDirectories().size());
|
||||
}
|
||||
|
||||
assertTrue(snapshotDirectories().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void copiesAreDeletedWhenTheLoadFails() throws Exception {
|
||||
writeGamma();
|
||||
new TestModuleJar().writeInto(pack, "broken.jar");
|
||||
assertThrows(ModuleLoadException.class, this::load);
|
||||
assertTrue(snapshotDirectories().isEmpty(), "failure while reading jars");
|
||||
|
||||
Files.delete(pack.resolve(PackModules.MODULES_DIRECTORY).resolve("broken.jar"));
|
||||
module("pack.throwing.Throwing", "throwing:core", "public Throwing() { throw new IllegalStateException(\"boom\"); }", NO_STAGES)
|
||||
.writeInto(pack, "throwing.jar");
|
||||
assertThrows(ModuleLoadException.class, this::load);
|
||||
assertTrue(snapshotDirectories().isEmpty(), "failure after the class loader exists");
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorsNameTheOriginalJarNeverItsCopy() {
|
||||
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "alpha.jar");
|
||||
new TestModuleJar().entryPoint("pack.alpha.Alpha").writeInto(pack, "beta.jar");
|
||||
|
||||
var message = assertThrows(ModuleLoadException.class, this::load).getMessage();
|
||||
|
||||
assertEquals("Module jar " + origin("beta.jar") + " has a broken entry point pack.alpha.Alpha: class is loaded from "
|
||||
+ origin("alpha.jar") + ", not from this jar", message);
|
||||
assertFalse(message.contains(temporaryRoot.toString()), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadRemovesCopiesOfExitedProcessesOnly() throws Exception {
|
||||
var exited = staleDirectory("exited", JarSnapshot.ownerRecord(EXITED_PROCESS));
|
||||
var running = staleDirectory("running", JarSnapshot.ownerRecord(ProcessHandle.current().pid()));
|
||||
var unmarked = Files.createDirectory(temporaryRoot.resolve(JarSnapshot.DIRECTORY_PREFIX + "unmarked"));
|
||||
var foreignHeader = staleDirectory("foreign", "Something else\n" + EXITED_PROCESS + "\n");
|
||||
var unexpectedContent = staleDirectory("unexpected", JarSnapshot.ownerRecord(EXITED_PROCESS));
|
||||
Files.writeString(unexpectedContent.resolve("notes.txt"), "not ours");
|
||||
var otherName = Files.createDirectory(temporaryRoot.resolve("other-" + JarSnapshot.DIRECTORY_PREFIX));
|
||||
Files.writeString(otherName.resolve(JarSnapshot.OWNER_FILE), JarSnapshot.ownerRecord(EXITED_PROCESS));
|
||||
|
||||
try (var ignored = load()) {
|
||||
assertFalse(Files.exists(exited));
|
||||
for (var kept : List.of(running, unmarked, foreignHeader, unexpectedContent, otherName)) {
|
||||
assertTrue(Files.exists(kept), kept.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import static com.volmit.support.TestModuleJar.module;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Runs only in the {@code addExportsTest} task, whose JVM is started with
|
||||
* {@code --add-exports java.base/jdk.internal.misc=ALL-UNNAMED}, like a server that grants modules
|
||||
* that package.
|
||||
*/
|
||||
@Tag(PackModulesAddExportsTest.ADD_EXPORTS_TAG)
|
||||
class PackModulesAddExportsTest {
|
||||
static final String ADD_EXPORTS_TAG = "jdk-add-exports";
|
||||
|
||||
@TempDir
|
||||
Path pack;
|
||||
|
||||
@Test
|
||||
void packageExportedToAllUnnamedModulesOnTheCommandLineIsUsable() {
|
||||
module("pack.user.User", "user:core", "static Object unsafe() { return jdk.internal.misc.Unsafe.class; }", "")
|
||||
.compileWithAccessTo("java.base", "jdk.internal.misc")
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(List.of(), packModules.missingClasses());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyTheExportedPackageBecomesUsable() {
|
||||
assertEquals(Optional.empty(), NonExportedJdkPackages.packageOf("jdk.internal.misc.Unsafe"),
|
||||
"this JVM must run with --add-exports java.base/jdk.internal.misc=ALL-UNNAMED (gradle addExportsTest)");
|
||||
assertTrue(NonExportedJdkPackages.packageOf("sun.nio.ch.Net").isPresent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.example.placement.MossModule;
|
||||
import com.volmit.example.placement.SnowModule;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class PackModulesSummaryTest {
|
||||
private static DiscoveredModule pack(IrisModule module, String origin) {
|
||||
return DiscoveredModule.fromJar(module, module.info(), origin);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listsNameIdVersionAndJarOfEveryModuleInLoadOrder() {
|
||||
var modules = List.of(
|
||||
pack(new MossModule(), "modules/moss.jar"),
|
||||
pack(new SnowModule(), "modules/snow.jar"));
|
||||
|
||||
assertEquals("""
|
||||
Pack overworld uses 2 modules:
|
||||
Moss (example:moss 1.0.0) from modules/moss.jar
|
||||
Snow (iris:snow test) from modules/snow.jar""",
|
||||
PackModulesSummary.describe("overworld", modules));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleModuleReadsAsOneModule() {
|
||||
var modules = List.of(pack(new MossModule(), "modules/moss.jar"));
|
||||
|
||||
assertEquals("""
|
||||
Pack overworld uses 1 module:
|
||||
Moss (example:moss 1.0.0) from modules/moss.jar""",
|
||||
PackModulesSummary.describe("overworld", modules));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packWithoutModulesSaysSo() {
|
||||
assertEquals("Pack overworld uses no modules: no jars in its modules directory",
|
||||
PackModulesSummary.describe("overworld", List.of()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,744 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.example.placement.AnchorModule;
|
||||
import com.volmit.example.placement.MossModule;
|
||||
import com.volmit.example.placement.PlacementModules;
|
||||
import com.volmit.support.TestModuleJar;
|
||||
import example.builtin.CarveModule;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static com.volmit.support.TestModuleJar.module;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PackModulesTest {
|
||||
private static final String ALPHA_MEMBERS =
|
||||
"public static final PlacementStage<Void> MARK = Stage.placement(\"alpha:core/mark\");";
|
||||
private static final String NO_MEMBERS = "";
|
||||
private static final String NO_SETUP = "";
|
||||
private static final String SHARED_CLASS = "pack.shared.Util";
|
||||
private static final String SHARED_SOURCE = "package pack.shared; public final class Util {}";
|
||||
private static final byte[] UNUSED_CLASS_BYTES = {(byte) 0xCA, (byte) 0xFE};
|
||||
private static final String VERSIONED_SHARED_CLASS = "META-INF/versions/9/pack/shared/Util.class";
|
||||
private static final String DEFINED_PROPERTY = "irisapi.test.packModuleConstructed";
|
||||
private static final String OPTIONAL_CLASS = "org.optional.Feature";
|
||||
private static final String BUILT_IN_PACKAGE = CarveModule.class.getPackageName();
|
||||
private static final String REQUIRES_BUILT_IN_STAGE =
|
||||
"graph.define(Stage.placement(\"user:core/carved\")).requires(example.builtin.CarveModule.CLEAR).run(context -> {});";
|
||||
|
||||
@TempDir
|
||||
Path pack;
|
||||
|
||||
private static String origin(String jarName) {
|
||||
return Path.of(PackModules.MODULES_DIRECTORY, jarName).toString();
|
||||
}
|
||||
|
||||
private static LoadedModules loadWithBuiltIns(PackModules packModules) {
|
||||
var modules = new ArrayList<>(PlacementModules.builtIns());
|
||||
modules.addAll(packModules.modules());
|
||||
return LoadedModules.load(modules, Map.of(), Set.of(), Set.of());
|
||||
}
|
||||
|
||||
/** Versioned entries of a multi-release jar are read like any class, so they must be real class files. */
|
||||
private byte[] sharedClassFile() {
|
||||
return TestModuleJar.compileClass(pack, SHARED_CLASS, SHARED_SOURCE);
|
||||
}
|
||||
|
||||
/** A jar of empty public classes, for modules to compile against without shipping it. */
|
||||
private static Path library(Path build, String jarName, String... classNames) {
|
||||
var library = new TestModuleJar();
|
||||
for (var className : classNames) {
|
||||
int dot = className.lastIndexOf('.');
|
||||
library.source(className, "package %s; public final class %s {}".formatted(className.substring(0, dot), className.substring(dot + 1)));
|
||||
}
|
||||
return library.writeInto(build, jarName);
|
||||
}
|
||||
|
||||
/** Module members that use each class, so its class file references them. */
|
||||
private static String using(String... classNames) {
|
||||
return "static Object[] used() { return new Object[] {" + String.join(".class, ", classNames) + ".class}; }";
|
||||
}
|
||||
|
||||
private static String failure(Executable load) {
|
||||
return assertThrows(ModuleLoadException.class, load).getMessage();
|
||||
}
|
||||
|
||||
private static void assertMentions(String message, String... parts) {
|
||||
for (var part : parts) assertTrue(message.contains(part), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void packWithoutModulesDirectoryHasNoModules() {
|
||||
try (var modules = PackModules.load(pack)) {
|
||||
assertTrue(modules.modules().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsOneModulePerJarInFileNameOrderAndResolvesThemWithBuiltIns(@TempDir Path build) throws Exception {
|
||||
var alpha = module("pack.alpha.AlphaModule", "alpha:core", ALPHA_MEMBERS,
|
||||
"graph.define(MARK).requires(com.volmit.example.placement.AnchorModule.HEIGHT).run(context -> {});")
|
||||
.compileAgainstHostOf(AnchorModule.class);
|
||||
var alphaJar = alpha.writeInto(build, "alpha.jar");
|
||||
module("pack.beta.BetaModule", "beta:core", NO_MEMBERS,
|
||||
"graph.define(Stage.placement(\"beta:core/use\")).requires(pack.alpha.AlphaModule.MARK).run(context -> {});")
|
||||
.compileAgainst(alphaJar)
|
||||
.writeInto(pack, "beta.jar");
|
||||
alpha.writeInto(pack, "alpha.jar");
|
||||
Files.writeString(pack.resolve(PackModules.MODULES_DIRECTORY).resolve("notes.txt"), "not a module");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(List.of(origin("alpha.jar"), origin("beta.jar")),
|
||||
packModules.modules().stream().map(DiscoveredModule::origin).toList());
|
||||
assertEquals(List.of("alpha:core", "beta:core"),
|
||||
packModules.modules().stream().map(found -> found.info().id().toString()).toList());
|
||||
assertNotSame(PackModules.class.getClassLoader(), packModules.modules().getFirst().module().getClass().getClassLoader());
|
||||
assertTrue(packModules.missingClasses().isEmpty());
|
||||
|
||||
var order = loadWithBuiltIns(packModules).placement().stages().stream()
|
||||
.map(stage -> stage.stage().id().toString()).toList();
|
||||
assertTrue(order.indexOf("iris:anchor/height") < order.indexOf("alpha:core/mark"), order.toString());
|
||||
assertTrue(order.indexOf("alpha:core/mark") < order.indexOf("beta:core/use"), order.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void packClassLoaderSeesOnlyTheApiTheJdkAndThePack() throws Exception {
|
||||
module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_SETUP).writeInto(pack, "gamma.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
var loader = packModules.modules().getFirst().module().getClass().getClassLoader();
|
||||
assertSame(IrisModule.class, loader.loadClass(IrisModule.class.getName()));
|
||||
assertSame(List.class, loader.loadClass(List.class.getName()));
|
||||
assertThrows(ClassNotFoundException.class, () -> loader.loadClass(Test.class.getName()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingThePackStopsItsClassLoaderFromLoadingMoreClasses() throws Exception {
|
||||
module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_SETUP)
|
||||
.source("pack.gamma.Unused", "package pack.gamma; final class Unused {}")
|
||||
.writeInto(pack, "gamma.jar");
|
||||
|
||||
ClassLoader loader;
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
loader = packModules.modules().getFirst().module().getClass().getClassLoader();
|
||||
assertNotNull(loader.loadClass("pack.gamma.GammaModule"));
|
||||
}
|
||||
assertThrows(ClassNotFoundException.class, () -> loader.loadClass("pack.gamma.Unused"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarWithoutEntryPointFails() {
|
||||
new TestModuleJar().source("pack.Lonely", "package pack; public final class Lonely {}").writeInto(pack, "lonely.jar");
|
||||
|
||||
assertMentions(failure(() -> PackModules.load(pack)),
|
||||
"Module jar " + origin("lonely.jar") + " has no entry point", ModuleJar.ENTRY_POINT_FILE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarNamingSeveralEntryPointsLoadsEachModuleInListedOrder() {
|
||||
module("pack.First", "first:core", NO_MEMBERS, NO_SETUP)
|
||||
.alsoModule("pack.Second", "second:core", NO_MEMBERS, NO_SETUP)
|
||||
.writeInto(pack, "two.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(List.of("first:core", "second:core"),
|
||||
packModules.modules().stream().map(found -> found.info().id().toString()).toList());
|
||||
assertEquals(List.of(origin("two.jar"), origin("two.jar")),
|
||||
packModules.modules().stream().map(DiscoveredModule::origin).toList());
|
||||
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void secondEntryPointOfAJarThatBreaksNamesItsClass() {
|
||||
module("pack.First", "first:core", NO_MEMBERS, NO_SETUP)
|
||||
.entryPoint("pack.Missing")
|
||||
.writeInto(pack, "two.jar");
|
||||
|
||||
assertMentions(failure(() -> PackModules.load(pack)),
|
||||
"Module jar " + origin("two.jar") + " has a broken entry point pack.Missing: class cannot be loaded");
|
||||
}
|
||||
|
||||
@Test
|
||||
void entryPointOfAnotherJarFailsNamingTheJarThatListsIt() {
|
||||
module("pack.First", "first:core", NO_MEMBERS, NO_SETUP).writeInto(pack, "first.jar");
|
||||
new TestModuleJar().entryPoint("pack.First").writeInto(pack, "second.jar");
|
||||
|
||||
assertMentions(failure(() -> PackModules.load(pack)),
|
||||
"Module jar " + origin("second.jar") + " has a broken entry point pack.First",
|
||||
"loaded from " + origin("first.jar") + ", not from this jar");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aJarsOptionalPackagesExcuseTheMissingClassesOfAllItsModules(@TempDir Path build) {
|
||||
module("pack.First", "first:core", List.of("org.optional"), NO_MEMBERS, NO_SETUP)
|
||||
.alsoModule("pack.Second", "second:core", using(OPTIONAL_CLASS), NO_SETUP)
|
||||
.compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS))
|
||||
.writeInto(pack, "two.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(List.of(), packModules.missingClasses());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void brokenEntryClassesFailNamingTheJar() {
|
||||
var missing = pack.resolve("missing");
|
||||
new TestModuleJar().entryPoint("pack.Missing").writeInto(missing, "missing.jar");
|
||||
assertMentions(failure(() -> PackModules.load(missing)),
|
||||
"Module jar " + origin("missing.jar") + " has a broken entry point pack.Missing: class cannot be loaded");
|
||||
|
||||
var unrelated = pack.resolve("unrelated");
|
||||
new TestModuleJar().source("pack.Plain", "package pack; public final class Plain {}")
|
||||
.entryPoint("pack.Plain").writeInto(unrelated, "plain.jar");
|
||||
assertMentions(failure(() -> PackModules.load(unrelated)),
|
||||
"Module jar " + origin("plain.jar") + " has a broken entry point pack.Plain: class does not implement com.volmit.IrisModule");
|
||||
|
||||
var throwing = pack.resolve("throwing");
|
||||
module("pack.Throwing", "throwing:core", "public Throwing() { throw new IllegalStateException(\"boom\"); }", NO_SETUP)
|
||||
.writeInto(throwing, "throwing.jar");
|
||||
assertMentions(failure(() -> PackModules.load(throwing)),
|
||||
"Module jar " + origin("throwing.jar") + " has a broken entry point pack.Throwing: constructor threw",
|
||||
"boom");
|
||||
|
||||
var shadowed = pack.resolve("shadowed");
|
||||
new TestModuleJar().entryPoint("com.volmit.example.placement.MossModule").writeInto(shadowed, "moss.jar");
|
||||
assertMentions(failure(() -> PackModules.load(shadowed)),
|
||||
"Module jar " + origin("moss.jar") + " has a broken entry point com.volmit.example.placement.MossModule",
|
||||
"not from this jar");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameClassInTwoJarsFailsBeforeAnyModuleIsConstructed() {
|
||||
var constructorMarker = "public %s() { System.setProperty(\"" + DEFINED_PROPERTY + "\", \"true\"); }";
|
||||
module("pack.alpha.Alpha", "alpha:core", constructorMarker.formatted("Alpha"), NO_SETUP)
|
||||
.source(SHARED_CLASS, SHARED_SOURCE).writeInto(pack, "alpha.jar");
|
||||
module("pack.beta.Beta", "beta:core", constructorMarker.formatted("Beta"), NO_SETUP)
|
||||
.source(SHARED_CLASS, SHARED_SOURCE).writeInto(pack, "beta.jar");
|
||||
|
||||
try {
|
||||
assertMentions(failure(() -> PackModules.load(pack)),
|
||||
"Class " + SHARED_CLASS + " is in both module jars " + origin("alpha.jar") + " and " + origin("beta.jar"));
|
||||
assertNull(System.getProperty(DEFINED_PROPERTY), "a module was constructed before the duplicate was found");
|
||||
} finally {
|
||||
System.clearProperty(DEFINED_PROPERTY);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleDescriptorsMayRepeatAcrossJars() {
|
||||
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
|
||||
.resource("module-info.class", UNUSED_CLASS_BYTES).writeInto(pack, "alpha.jar");
|
||||
module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_SETUP)
|
||||
.resource("module-info.class", UNUSED_CLASS_BYTES).writeInto(pack, "beta.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(2, packModules.modules().size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionedClassOfAMultiReleaseJarCountsUnderItsBaseName() {
|
||||
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
|
||||
.source(SHARED_CLASS, SHARED_SOURCE).writeInto(pack, "alpha.jar");
|
||||
module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_SETUP)
|
||||
.multiRelease()
|
||||
.resource(VERSIONED_SHARED_CLASS, sharedClassFile())
|
||||
.writeInto(pack, "beta.jar");
|
||||
|
||||
assertMentions(failure(() -> PackModules.load(pack)),
|
||||
"Class " + SHARED_CLASS + " is in both module jars " + origin("alpha.jar") + " and " + origin("beta.jar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionedEntriesOutsideAMultiReleaseJarAreNotClasses() {
|
||||
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
|
||||
.source(SHARED_CLASS, SHARED_SOURCE)
|
||||
.resource(VERSIONED_SHARED_CLASS, UNUSED_CLASS_BYTES)
|
||||
.writeInto(pack, "alpha.jar");
|
||||
module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_SETUP)
|
||||
.resource(VERSIONED_SHARED_CLASS, UNUSED_CLASS_BYTES)
|
||||
.writeInto(pack, "beta.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(2, packModules.modules().size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void multiReleaseJarMayHoldAVersionedCopyOfItsOwnClass() {
|
||||
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
|
||||
.source(SHARED_CLASS, SHARED_SOURCE)
|
||||
.multiRelease()
|
||||
.resource(VERSIONED_SHARED_CLASS, sharedClassFile())
|
||||
.writeInto(pack, "alpha.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(1, packModules.modules().size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void apiClassInAJarFailsNamingTheJarAndTheClass() {
|
||||
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
|
||||
.source("com.volmit.extra.Helper", "package com.volmit.extra; public final class Helper {}")
|
||||
.source("com.volmit.extra.Other", "package com.volmit.extra; public final class Other {}")
|
||||
.writeInto(pack, "alpha.jar");
|
||||
|
||||
assertEquals("Module jar " + origin("alpha.jar") + " contains Iris API class com.volmit.extra.Helper and 1 more;"
|
||||
+ " Iris provides the API at runtime, so mark the Iris API dependency compileOnly (Maven: provided)"
|
||||
+ " and keep module classes out of com.volmit.*",
|
||||
failure(() -> PackModules.load(pack)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void referenceToAHostLibraryFailsNamingTheJarAndBothClasses() {
|
||||
module("pack.user.User", "user:core", "static Object probe() { return org.junit.jupiter.api.Test.class; }", NO_SETUP)
|
||||
.compileAgainstHostOf(Test.class)
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
assertEquals("Module jar " + origin("user.jar") + " uses classes that exist in Iris but are hidden from modules:\n"
|
||||
+ " pack.user.User -> org.junit.jupiter.api.Test\n"
|
||||
+ "Modules cannot use Iris's own classes or its copies of libraries; ship the library in a module"
|
||||
+ " jar of the pack, or use the Iris API.",
|
||||
failure(() -> PackModules.load(pack)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void referenceToAJdkModuleOutsideThePlatformLoaderFailsNamingTheModule() {
|
||||
module("pack.user.User", "user:core", using("com.sun.source.tree.Tree", "java.sql.Connection"), NO_SETUP)
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
assertEquals("Module jar " + origin("user.jar") + " uses classes of JDK modules that are not available to modules:\n"
|
||||
+ " pack.user.User -> com.sun.source.tree.Tree (JDK module jdk.compiler)\n"
|
||||
+ "Modules can use only the JDK modules of the platform class loader, such as java.base, java.sql and"
|
||||
+ " java.net.http.",
|
||||
failure(() -> PackModules.load(pack)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void referenceToANonExportedJdkPackageFailsNamingThePackageAndModule() {
|
||||
module("pack.user.User", "user:core", using("jdk.internal.misc.Unsafe", "java.lang.String"), NO_SETUP)
|
||||
.compileWithAccessTo("java.base", "jdk.internal.misc")
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
assertEquals("Module jar " + origin("user.jar") + " uses classes of JDK packages that are not exported to modules:\n"
|
||||
+ " pack.user.User -> jdk.internal.misc.Unsafe (package jdk.internal.misc of java.base is not exported)\n"
|
||||
+ "Use the supported alternative where there is one, such as sun.misc.Unsafe from jdk.unsupported"
|
||||
+ " instead of jdk.internal.misc.Unsafe. Otherwise the server must be started with"
|
||||
+ " --add-exports <module>/<package>=ALL-UNNAMED.",
|
||||
failure(() -> PackModules.load(pack)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void supportedUnsafeFromJdkUnsupportedIsUsable() {
|
||||
module("pack.user.User", "user:core", using("sun.misc.Unsafe", "java.lang.String"), NO_SETUP)
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(List.of(), packModules.missingClasses());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneFailureReportsEveryKindOfUnusableClass() {
|
||||
module("pack.user.User", "user:core", using("org.junit.jupiter.api.Test", "com.sun.source.tree.Tree"), NO_SETUP)
|
||||
.compileAgainstHostOf(Test.class)
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
assertEquals("Module jar " + origin("user.jar") + " uses classes that exist in Iris but are hidden from modules:\n"
|
||||
+ " pack.user.User -> org.junit.jupiter.api.Test\n"
|
||||
+ "Modules cannot use Iris's own classes or its copies of libraries; ship the library in a module"
|
||||
+ " jar of the pack, or use the Iris API.\n"
|
||||
+ "Module jar " + origin("user.jar") + " uses classes of JDK modules that are not available to modules:\n"
|
||||
+ " pack.user.User -> com.sun.source.tree.Tree (JDK module jdk.compiler)\n"
|
||||
+ "Modules can use only the JDK modules of the platform class loader, such as java.base, java.sql and"
|
||||
+ " java.net.http.",
|
||||
failure(() -> PackModules.load(pack)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void classesNobodyHasAreReportedWithoutFailingTheLoad(@TempDir Path build) {
|
||||
var optionalLibrary = new TestModuleJar()
|
||||
.source(OPTIONAL_CLASS, "package org.optional; public final class Feature { public static void use() {} }")
|
||||
.writeInto(build, "optional.jar");
|
||||
module("pack.user.User", "user:core", "static void useWhenPresent() { org.optional.Feature.use(); }",
|
||||
"graph.define(Stage.placement(\"user:core/work\")).run(context -> {});")
|
||||
.compileAgainst(optionalLibrary)
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(List.of(new MissingClasses(origin("user.jar"), List.of(OPTIONAL_CLASS))), packModules.missingClasses());
|
||||
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void hiddenHostClassFailsEvenWhenOtherMissingClassesAreOptional(@TempDir Path build) {
|
||||
var optionalLibrary = new TestModuleJar()
|
||||
.source(OPTIONAL_CLASS, "package org.optional; public final class Feature {}")
|
||||
.writeInto(build, "optional.jar");
|
||||
module("pack.user.User", "user:core", """
|
||||
static Object optional() { return org.optional.Feature.class; }
|
||||
static Object hidden() { return org.junit.jupiter.api.Test.class; }
|
||||
""", NO_SETUP)
|
||||
.compileAgainst(optionalLibrary)
|
||||
.compileAgainstHostOf(Test.class)
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
var message = failure(() -> PackModules.load(pack));
|
||||
assertMentions(message, "pack.user.User -> org.junit.jupiter.api.Test");
|
||||
assertFalse(message.contains(OPTIONAL_CLASS), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingClassesInDeclaredOptionalPackagesDoNotWarn(@TempDir Path build) {
|
||||
module("pack.user.User", "user:core", List.of("org.optional", "org.other."), using(OPTIONAL_CLASS, "org.other.deep.Thing"), NO_SETUP)
|
||||
.compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS, "org.other.deep.Thing"))
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(List.of(), packModules.missingClasses());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingClassesOutsideDeclaredOptionalPackagesStillWarn(@TempDir Path build) {
|
||||
module("pack.user.User", "user:core", List.of("org.optional"), using(OPTIONAL_CLASS, "org.optionalx.Other", "org.slf4j.Logger"), NO_SETUP)
|
||||
.compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS, "org.optionalx.Other", "org.slf4j.Logger"))
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(List.of(new MissingClasses(origin("user.jar"), List.of("org.optionalx.Other", "org.slf4j.Logger"))),
|
||||
packModules.missingClasses());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void optionalPackagesExcuseOnlyTheirOwnJar(@TempDir Path build) {
|
||||
var optionalLibrary = library(build, "optional.jar", OPTIONAL_CLASS);
|
||||
module("pack.alpha.Alpha", "alpha:core", List.of("org.optional"), using(OPTIONAL_CLASS), NO_SETUP)
|
||||
.compileAgainst(optionalLibrary)
|
||||
.writeInto(pack, "alpha.jar");
|
||||
module("pack.beta.Beta", "beta:core", using(OPTIONAL_CLASS), NO_SETUP)
|
||||
.compileAgainst(optionalLibrary)
|
||||
.writeInto(pack, "beta.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals(List.of(new MissingClasses(origin("beta.jar"), List.of(OPTIONAL_CLASS))), packModules.missingClasses());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void optionalPackagesNeverExcuseALoadError(@TempDir Path build) {
|
||||
var hidden = pack.resolve("hidden");
|
||||
module("pack.user.User", "user:core", List.of("org.junit"), using("org.junit.jupiter.api.Test"), NO_SETUP)
|
||||
.compileAgainstHostOf(Test.class)
|
||||
.writeInto(hidden, "user.jar");
|
||||
assertMentions(failure(() -> PackModules.load(hidden)),
|
||||
"uses classes that exist in Iris but are hidden from modules:\n pack.user.User -> org.junit.jupiter.api.Test");
|
||||
|
||||
var newerApi = pack.resolve("newer-api");
|
||||
module("pack.user.User", "user:core", List.of("com.volmit"), using("com.volmit.Newer"), NO_SETUP)
|
||||
.compileAgainst(library(build, "newer-api.jar", "com.volmit.Newer"))
|
||||
.writeInto(newerApi, "user.jar");
|
||||
assertMentions(failure(() -> PackModules.load(newerApi)),
|
||||
"uses classes that this Iris does not have, in packages Iris provides to modules:\n pack.user.User -> com.volmit.Newer");
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidOptionalPackageFailsNamingTheJar() {
|
||||
module("pack.user.User", "user:core", List.of("org.*"), NO_MEMBERS, NO_SETUP).writeInto(pack, "user.jar");
|
||||
|
||||
assertMentions(failure(() -> PackModules.load(pack)),
|
||||
"Module jar " + origin("user.jar") + " declares optional package 'org.*' in Iris-Optional-Packages,"
|
||||
+ " which is not a package name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void referenceToAMissingApiClassPointsAtADifferentApiBuild(@TempDir Path build) {
|
||||
var newerApi = new TestModuleJar()
|
||||
.source("com.volmit.Newer", "package com.volmit; public final class Newer {}")
|
||||
.writeInto(build, "newer-api.jar");
|
||||
module("pack.user.User", "user:core", "static Object probe() { return com.volmit.Newer.class; }", NO_SETUP)
|
||||
.compileAgainst(newerApi)
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
assertMentions(failure(() -> PackModules.load(pack)),
|
||||
"uses classes that this Iris does not have, in packages Iris provides to modules:\n pack.user.User -> com.volmit.Newer",
|
||||
"The jar was built against a different Iris API or Iris version.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void referencesToTheJdkTheApiAndOtherPackJarsLoad(@TempDir Path build) throws Exception {
|
||||
var marker = new TestModuleJar()
|
||||
.source("pack.marker.Marker", """
|
||||
package pack.marker;
|
||||
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
|
||||
public @interface Marker {}
|
||||
""")
|
||||
.writeInto(build, "marker.jar");
|
||||
var alpha = module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
|
||||
.source("pack.alpha.Shared", """
|
||||
package pack.alpha;
|
||||
public record Shared(int[] values, String[][] names) {
|
||||
public enum Kind { SMALL, LARGE }
|
||||
}
|
||||
""");
|
||||
var alphaJar = alpha.writeInto(build, "alpha.jar");
|
||||
alpha.writeInto(pack, "alpha.jar");
|
||||
module("pack.beta.Beta", "beta:core", """
|
||||
@pack.marker.Marker
|
||||
static final pack.alpha.Shared[] SHARED = { new pack.alpha.Shared(new int[] {1}, new String[][] {{"a"}}) };
|
||||
|
||||
static int size(pack.alpha.Shared.Kind kind) {
|
||||
return switch (kind) { case SMALL -> 1; case LARGE -> 2; };
|
||||
}
|
||||
""", """
|
||||
java.util.function.IntSupplier size = () -> size(pack.alpha.Shared.Kind.LARGE) + SHARED[0].values().length;
|
||||
graph.define(Stage.placement("beta:core/size")).run(context -> java.util.List.of(size).forEach(java.util.function.IntSupplier::getAsInt));
|
||||
""")
|
||||
.compileAgainst(alphaJar)
|
||||
.compileAgainst(marker)
|
||||
.writeInto(pack, "beta.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
var loaded = LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of());
|
||||
assertTrue(loaded.placement().stages().stream().anyMatch(stage -> stage.stage().id().toString().equals("beta:core/size")));
|
||||
var beta = packModules.modules().getLast().module().getClass();
|
||||
assertEquals(0, beta.getDeclaredField("SHARED").getAnnotations().length,
|
||||
"the annotation type is not in the pack, so the JVM skips it");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void packJarRequiresAStageOfABuiltInModuleInAnExposedPackage() {
|
||||
module("pack.user.User", "user:core", NO_MEMBERS, REQUIRES_BUILT_IN_STAGE)
|
||||
.compileAgainstHostOf(CarveModule.class)
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack, List.of(BUILT_IN_PACKAGE))) {
|
||||
var modules = new ArrayList<>(List.of(DiscoveredModule.builtIn(new CarveModule())));
|
||||
modules.addAll(packModules.modules());
|
||||
var order = LoadedModules.load(modules, Map.of(), Set.of(), Set.of()).placement().stages().stream()
|
||||
.map(stage -> stage.stage().id().toString()).toList();
|
||||
assertEquals(List.of("iris:carve/clear", "user:core/carved"), order);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void builtInModuleOutsideTheExposedPackagesIsHidden() {
|
||||
module("pack.user.User", "user:core", NO_MEMBERS, REQUIRES_BUILT_IN_STAGE)
|
||||
.compileAgainstHostOf(CarveModule.class)
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
assertMentions(failure(() -> PackModules.load(pack)),
|
||||
"Module jar " + origin("user.jar") + " uses classes that exist in Iris but are hidden from modules:\n"
|
||||
+ " pack.user.User -> example.builtin.CarveModule\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void referenceToAMissingClassOfAnExposedPackagePointsAtADifferentBuild(@TempDir Path build) {
|
||||
var newerBuiltIns = new TestModuleJar()
|
||||
.source("example.builtin.Newer", "package example.builtin; public final class Newer {}")
|
||||
.writeInto(build, "newer-built-ins.jar");
|
||||
module("pack.user.User", "user:core", "static Object probe() { return example.builtin.Newer.class; }", NO_SETUP)
|
||||
.compileAgainst(newerBuiltIns)
|
||||
.writeInto(pack, "user.jar");
|
||||
|
||||
assertMentions(failure(() -> PackModules.load(pack, List.of(BUILT_IN_PACKAGE))),
|
||||
"pack.user.User -> example.builtin.Newer", "built against a different Iris API or Iris version");
|
||||
}
|
||||
|
||||
@Test
|
||||
void classOfAnExposedHostPackageInAJarFails() {
|
||||
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
|
||||
.source("example.builtin.Copy", "package example.builtin; public final class Copy {}")
|
||||
.writeInto(pack, "alpha.jar");
|
||||
|
||||
assertEquals("Module jar " + origin("alpha.jar") + " contains class example.builtin.Copy of package example.builtin,"
|
||||
+ " which Iris provides to modules at runtime; compile against it compileOnly (Maven: provided)"
|
||||
+ " instead of shipping it, and keep module classes out of example.builtin.*",
|
||||
failure(() -> PackModules.load(pack, List.of(BUILT_IN_PACKAGE))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidExposedPackageFailsBeforeReadingJars() {
|
||||
var invalid = assertThrows(IllegalArgumentException.class, () -> PackModules.load(pack, List.of("example.*")));
|
||||
assertMentions(invalid.getMessage(), "Exposed package 'example.*' is not a package name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void packModuleInfoIsReadOnceAtDiscovery() {
|
||||
var answersOnce = """
|
||||
private static boolean answered;
|
||||
|
||||
public ModuleInfo info() {
|
||||
if (answered) throw new IllegalStateException("info() called twice");
|
||||
answered = true;
|
||||
return ModuleInfo.of("once:core", "Once", "1.0.0");
|
||||
}
|
||||
""";
|
||||
new TestModuleJar()
|
||||
.source("pack.once.Once", """
|
||||
package pack.once;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.stage.*;
|
||||
|
||||
public final class Once implements IrisModule {
|
||||
%s
|
||||
public void setup(com.volmit.ModuleSetup setup) {
|
||||
setup.stages().define(Stage.placement("once:core/mark")).run(context -> {});
|
||||
}
|
||||
}
|
||||
""".formatted(answersOnce))
|
||||
.entryPoint("pack.once.Once")
|
||||
.writeInto(pack, "once.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
var loaded = assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()));
|
||||
assertEquals("once:core", packModules.modules().getFirst().info().id().toString());
|
||||
assertEquals(1, loaded.placement().stages().size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void methodMissingAtSetupFailsNamingTheJar(@TempDir Path build) {
|
||||
var libraryWithMethod = new TestModuleJar()
|
||||
.source("pack.lib.Lib", "package pack.lib; public final class Lib { public static void added() {} }")
|
||||
.writeInto(build, "lib.jar");
|
||||
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
|
||||
.source("pack.lib.Lib", "package pack.lib; public final class Lib {}")
|
||||
.writeInto(pack, "alpha.jar");
|
||||
module("pack.beta.Beta", "beta:core", NO_MEMBERS, "pack.lib.Lib.added();")
|
||||
.compileAgainst(libraryWithMethod)
|
||||
.writeInto(pack, "beta.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
|
||||
"Module beta:core from " + origin("beta.jar") + " failed to link or initialize a class during setup",
|
||||
"java.lang.NoSuchMethodError", "pack.lib.Lib.added()");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsWithoutAKeyFailNamingTheModuleTheClassAndTheKeyToAdd(@TempDir Path build) {
|
||||
var apiWithoutKeys = new TestModuleJar().source("com.volmit.config.Feature", """
|
||||
package com.volmit.config;
|
||||
import java.lang.annotation.*;
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface Feature {
|
||||
String id();
|
||||
String name();
|
||||
com.volmit.config.Level[] targets();
|
||||
}
|
||||
""").writeInto(build, "api-without-keys.jar");
|
||||
module("pack.old.Old", "old:flora", """
|
||||
@com.volmit.config.Feature(id = "old:flora/wild-patch", name = "Patch", targets = com.volmit.config.Level.BIOME)
|
||||
public static final class Patch implements com.volmit.IrisFeature {}
|
||||
""", "registry.registerSettings(Patch.class);")
|
||||
.compileAgainstOlderApi(apiWithoutKeys)
|
||||
.writeInto(pack, "old.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals("Module old:flora from " + origin("old.jar") + ": The @Feature of settings class pack.old.Old$Patch"
|
||||
+ " has no key, the JSON field packs write the settings under; add key = \"floraWildPatch\" (or"
|
||||
+ " another plain field name) to it and rebuild the jar",
|
||||
failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateModuleIdsAcrossJarsFailNamingBothJars() {
|
||||
module("pack.one.Duplicate", "dup:core", NO_MEMBERS, NO_SETUP).writeInto(pack, "one.jar");
|
||||
module("pack.two.Duplicate", "dup:core", NO_MEMBERS, NO_SETUP).writeInto(pack, "two.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
|
||||
"Duplicate module dup:core from " + origin("two.jar") + " (pack.two.Duplicate); already loaded from "
|
||||
+ origin("one.jar") + " (pack.one.Duplicate)");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateOfABuiltInModuleFailsNamingTheJar() {
|
||||
module("pack.Moss", "example:moss", NO_MEMBERS, NO_SETUP).writeInto(pack, "moss.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertMentions(failure(() -> loadWithBuiltIns(packModules)),
|
||||
"Duplicate module example:moss from " + origin("moss.jar") + " (pack.Moss); already loaded from host classpath ("
|
||||
+ MossModule.class.getName() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsKeyTakenByABuiltInFailsNamingBothModulesAndTheirJars() {
|
||||
module("pack.Clash", "mine:core", NO_MEMBERS, "registry.registerSettings(ClashSettings.class);")
|
||||
.source("pack.ClashSettings", """
|
||||
package pack;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.Feature;
|
||||
|
||||
@Feature(id = "mine:core/clash", name = "Clash", key = "moss", targets = Level.PLACEMENT)
|
||||
public final class ClashSettings implements IrisFeature {
|
||||
}
|
||||
""")
|
||||
.writeInto(pack, "clash.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertEquals("placement key \"moss\" is claimed by example:moss (host classpath) and mine:core/clash ("
|
||||
+ origin("clash.jar") + "); give one of the settings another key in its @Feature",
|
||||
failure(() -> loadWithBuiltIns(packModules)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stageOutsideTheModuleIdFailsNamingTheJar() {
|
||||
module("pack.Foreign", "mine:core", NO_MEMBERS,
|
||||
"graph.define(Stage.placement(\"mine:other/work\")).run(context -> {});")
|
||||
.writeInto(pack, "foreign.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
|
||||
"Stage mine:other/work must start with mine:core/, the id of its defining module mine:core from " + origin("foreign.jar"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateModuleIdWithinOneJarFailsNamingBothClasses() {
|
||||
module("pack.One", "dup:core", NO_MEMBERS, NO_SETUP)
|
||||
.alsoModule("pack.Two", "dup:core", NO_MEMBERS, NO_SETUP)
|
||||
.writeInto(pack, "both.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
|
||||
"Duplicate module dup:core from " + origin("both.jar") + " (pack.Two); already loaded from "
|
||||
+ origin("both.jar") + " (pack.One)");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void packModuleMayUseAnyNamespaceIncludingIris() {
|
||||
module("pack.Stilt", "iris:stilt", NO_MEMBERS,
|
||||
"graph.define(Stage.placement(\"iris:stilt/fill\")).run(context -> {});")
|
||||
.writeInto(pack, "stilt.jar");
|
||||
|
||||
try (var packModules = PackModules.load(pack)) {
|
||||
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,852 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.config.Reference;
|
||||
import com.volmit.example.chunk.GrassModule;
|
||||
import com.volmit.example.chunk.TerrainModule;
|
||||
import com.volmit.example.hosttypes.Palette;
|
||||
import com.volmit.example.placement.PlacementModules;
|
||||
import com.volmit.example.terrain.LayersModule;
|
||||
import com.volmit.host.schema.FeatureSchema;
|
||||
import com.volmit.host.schema.ObjectType;
|
||||
import com.volmit.host.schema.PackSchema;
|
||||
import com.volmit.host.schema.ResourceKindSchema;
|
||||
import com.volmit.host.schema.SchemaOption;
|
||||
import com.volmit.host.schema.TextFormat;
|
||||
import com.volmit.host.schema.ValueKind.AnyKind;
|
||||
import com.volmit.host.schema.ValueKind.BooleanKind;
|
||||
import com.volmit.host.schema.ValueKind.DecimalKind;
|
||||
import com.volmit.host.schema.ValueKind.EnumConstant;
|
||||
import com.volmit.host.schema.ValueKind.EnumKind;
|
||||
import com.volmit.host.schema.ValueKind.HostKind;
|
||||
import com.volmit.host.schema.ValueKind.IntegerKind;
|
||||
import com.volmit.host.schema.ValueKind.ListKind;
|
||||
import com.volmit.host.schema.ValueKind.MapKind;
|
||||
import com.volmit.host.schema.ValueKind.ObjectKind;
|
||||
import com.volmit.host.schema.ValueKind.ReferenceKind;
|
||||
import com.volmit.host.schema.ValueKind.ResourceReferenceKind;
|
||||
import com.volmit.host.schema.ValueKind.TextKind;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
import com.volmit.support.TestModuleJar;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.function.Function;
|
||||
import static com.volmit.support.TestModuleJar.displayName;
|
||||
import static com.volmit.support.TestModuleJar.module;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Loads real module jars and checks what the pack tells studio about their settings. */
|
||||
class PackSchemaTest {
|
||||
private static final ModuleHost NO_BUILT_INS = ModuleHost.of(List.of());
|
||||
private static final String FLORA = "example:flora";
|
||||
private static final String HOST_TYPES = "com.volmit.example.hosttypes";
|
||||
private static final String FLORA_SOURCE = "settings example:flora (module example:flora from modules/flora.jar)";
|
||||
private static final String NO_MEMBERS = "";
|
||||
|
||||
@TempDir
|
||||
Path packs;
|
||||
private int brokenPacks;
|
||||
|
||||
private static final String FLORA_SETUP = """
|
||||
registry.registerSettings(WindSettings.class);
|
||||
registry.registerSettings(FloraSettings.class);
|
||||
registry.registerSettings(BushSettings.class);
|
||||
graph.define(Stage.chunk("example:flora/plant")).when(FloraSettings.class).run(context -> {});
|
||||
""";
|
||||
|
||||
private static final String FLORA_SETTINGS = """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.config.*;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import java.util.*;
|
||||
|
||||
@Desc("Plants flowers and bushes")
|
||||
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = {Level.REGION, Level.BIOME})
|
||||
public final class FloraSettings implements IrisFeature {
|
||||
@Desc("Plants per chunk") @Required @MinNumber(0) @MaxNumber(64)
|
||||
private int density = 4;
|
||||
private double chance = 0.25;
|
||||
private float spread = 0.1f;
|
||||
private Long seedOffset;
|
||||
private boolean enabled = true;
|
||||
private String label = "flora";
|
||||
private ResourceId palette = ResourceId.parse("example:flora/default");
|
||||
@Ref(Reference.BLOCK)
|
||||
private String ground = "minecraft:grass_block";
|
||||
@ResourceRef(com.volmit.world.PackBiome.class) @MinItems(1)
|
||||
private List<String> biomes = List.of("plains", "forest");
|
||||
@Ref(Reference.ITEM)
|
||||
private ResourceId[] drops = {};
|
||||
private BlockState flower = new BlockState("minecraft:poppy");
|
||||
private Season season = Season.SPRING;
|
||||
private Set<Season> seasons = new HashSet<>(Set.of(Season.SUMMER, Season.AUTUMN));
|
||||
private Map<String, Integer> weights = Map.of("rose", 2, "daisy", 1);
|
||||
private Patch patch = new Patch();
|
||||
private List<Patch> extra = List.of();
|
||||
private transient int cache;
|
||||
private static int counter;
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String SEASON = """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.config.Desc;
|
||||
|
||||
public enum Season {
|
||||
@Desc("Early in the year") SPRING,
|
||||
SUMMER,
|
||||
AUTUMN
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String PATCH = """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.config.*;
|
||||
|
||||
@Desc("A patch of plants")
|
||||
@Snippet("example/flora/patch")
|
||||
final class Patch {
|
||||
@MinNumber(1)
|
||||
private int radius = 3;
|
||||
private Season bloom = Season.SUMMER;
|
||||
@Desc("A smaller patch inside this one")
|
||||
private Patch child;
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String WIND_SETTINGS = """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.*;
|
||||
|
||||
@Feature(id = "example:flora/wind", name = "Wind", key = "floraWind", targets = Level.DIMENSION)
|
||||
public final class WindSettings implements IrisFeature {
|
||||
@Desc("How far plants sway")
|
||||
private double strength = 1.5;
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String BUSH_SETTINGS = """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.*;
|
||||
|
||||
@Snippet("example/flora/bush")
|
||||
@Feature(id = "example:flora/bush", name = "Bush", key = "floraBush", targets = Level.PLACEMENT)
|
||||
public final class BushSettings implements IrisFeature {
|
||||
private int height = 2;
|
||||
}
|
||||
""";
|
||||
|
||||
private static TestModuleJar flora() {
|
||||
return module("pack.flora.FloraModule", FLORA, NO_MEMBERS, FLORA_SETUP)
|
||||
.source("pack.flora.FloraSettings", FLORA_SETTINGS)
|
||||
.source("pack.flora.Season", SEASON)
|
||||
.source("pack.flora.Patch", PATCH)
|
||||
.source("pack.flora.WindSettings", WIND_SETTINGS)
|
||||
.source("pack.flora.BushSettings", BUSH_SETTINGS);
|
||||
}
|
||||
|
||||
private Path pack(String name) {
|
||||
try {
|
||||
return Files.createDirectories(packs.resolve(name));
|
||||
} catch (java.io.IOException exception) {
|
||||
throw new java.io.UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static PackSchema schemaOf(Path pack, ModuleHost host) {
|
||||
try (var loaded = LoadedPack.load(pack, host)) {
|
||||
return loaded.schema();
|
||||
}
|
||||
}
|
||||
|
||||
private PackSchema floraSchema() {
|
||||
var pack = pack("flora");
|
||||
flora().writeInto(pack, "flora.jar");
|
||||
return schemaOf(pack, NO_BUILT_INS);
|
||||
}
|
||||
|
||||
private static SchemaOption option(ObjectType type, String name) {
|
||||
return type.options().stream().filter(option -> option.name().equals(name)).findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
private static List<String> names(List<FeatureSchema> features, Function<FeatureSchema, Object> name) {
|
||||
return features.stream().map(name).map(Object::toString).toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachesEveryModuleFeatureToItsTargetsUnderItsDeclaredKey() {
|
||||
var schema = floraSchema();
|
||||
|
||||
assertEquals(List.of("flora"), names(schema.fields(Level.BIOME), FeatureSchema::key));
|
||||
assertEquals(List.of("flora"), names(schema.fields(Level.REGION), FeatureSchema::key));
|
||||
assertEquals(List.of("floraWind"), names(schema.fields(Level.DIMENSION), FeatureSchema::key));
|
||||
assertEquals(List.of("floraBush"), names(schema.fields(Level.PLACEMENT), FeatureSchema::key));
|
||||
assertEquals(List.of("example:flora", "example:flora/bush", "example:flora/wind"), names(schema.features(), FeatureSchema::id));
|
||||
|
||||
var flora = schema.features().getFirst();
|
||||
assertEquals("Flora", flora.name());
|
||||
assertEquals(FLORA, flora.module().id().toString());
|
||||
assertEquals(displayName(FLORA), flora.module().name());
|
||||
assertEquals(List.of(Level.REGION, Level.BIOME), List.copyOf(flora.targets()));
|
||||
assertEquals("pack.flora.FloraSettings", flora.settings().name());
|
||||
assertEquals("Plants flowers and bushes", flora.settings().description());
|
||||
assertEquals(Optional.empty(), flora.settings().snippet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describesOptionsInDeclarationOrderWithChecksAndDefaults() {
|
||||
var settings = floraSchema().type("pack.flora.FloraSettings");
|
||||
|
||||
assertEquals(List.of("density", "chance", "spread", "seedOffset", "enabled", "label", "palette", "ground", "biomes",
|
||||
"drops", "flower", "season", "seasons", "weights", "patch", "extra"),
|
||||
settings.options().stream().map(SchemaOption::name).toList());
|
||||
assertEquals(new SchemaOption("density", new IntegerKind(), "Plants per chunk", true,
|
||||
OptionalDouble.of(0), OptionalDouble.of(64), OptionalInt.empty(), Optional.of(4L)), option(settings, "density"));
|
||||
assertEquals(new SchemaOption("chance", new DecimalKind(), "", false,
|
||||
OptionalDouble.empty(), OptionalDouble.empty(), OptionalInt.empty(), Optional.of(0.25)), option(settings, "chance"));
|
||||
assertEquals(Optional.of(0.1), option(settings, "spread").defaultValue(), "floats keep their own decimal form");
|
||||
assertEquals(new IntegerKind(), option(settings, "seedOffset").kind());
|
||||
assertEquals(Optional.empty(), option(settings, "seedOffset").defaultValue(), "a null field has no default");
|
||||
assertEquals(new BooleanKind(), option(settings, "enabled").kind());
|
||||
assertEquals(Optional.of(true), option(settings, "enabled").defaultValue());
|
||||
assertEquals(new TextKind(TextFormat.PLAIN), option(settings, "label").kind());
|
||||
assertEquals(new TextKind(TextFormat.RESOURCE_ID), option(settings, "palette").kind());
|
||||
assertEquals(Optional.of("example:flora/default"), option(settings, "palette").defaultValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describesEnumsCollectionsAndMaps() {
|
||||
var settings = floraSchema().type("pack.flora.FloraSettings");
|
||||
|
||||
var season = new EnumKind("pack.flora.Season", List.of(new EnumConstant("SPRING", "Early in the year"),
|
||||
new EnumConstant("SUMMER", ""), new EnumConstant("AUTUMN", "")));
|
||||
assertEquals(season, option(settings, "season").kind());
|
||||
assertEquals(Optional.of("SPRING"), option(settings, "season").defaultValue());
|
||||
assertEquals(new ListKind(season, true), option(settings, "seasons").kind());
|
||||
assertEquals(Optional.of(List.of("AUTUMN", "SUMMER")), option(settings, "seasons").defaultValue(), "sets are sorted");
|
||||
assertEquals(new MapKind(new IntegerKind()), option(settings, "weights").kind());
|
||||
assertEquals(Optional.of(Map.of("daisy", 1L, "rose", 2L)), option(settings, "weights").defaultValue());
|
||||
assertEquals(List.of("daisy", "rose"), List.copyOf(((Map<?, ?>) option(settings, "weights").defaultValue().orElseThrow()).keySet()));
|
||||
assertEquals(new ListKind(new ObjectKind("pack.flora.Patch"), false), option(settings, "extra").kind());
|
||||
assertEquals(Optional.of(List.of()), option(settings, "extra").defaultValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describesReferencesOnTextCollectionsArraysAndBlockStates() {
|
||||
var settings = floraSchema().type("pack.flora.FloraSettings");
|
||||
|
||||
assertEquals(new ReferenceKind(Reference.BLOCK, TextFormat.PLAIN), option(settings, "ground").kind());
|
||||
assertEquals(new ListKind(new ResourceReferenceKind(PackResources.BIOMES.id()), false), option(settings, "biomes").kind());
|
||||
assertEquals(Optional.of(List.of("plains", "forest")), option(settings, "biomes").defaultValue());
|
||||
assertEquals(OptionalInt.of(1), option(settings, "biomes").minItems(), "@MinItems is described");
|
||||
assertEquals(OptionalInt.empty(), option(settings, "drops").minItems());
|
||||
assertEquals(new ListKind(new ReferenceKind(Reference.ITEM, TextFormat.RESOURCE_ID), false), option(settings, "drops").kind());
|
||||
assertEquals(new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE), option(settings, "flower").kind(),
|
||||
"BlockState names a block without @Ref");
|
||||
assertEquals(Optional.of("minecraft:poppy"), option(settings, "flower").defaultValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describesNestedTypesOnceAndEndsCyclesAtTheTypesName() {
|
||||
var schema = floraSchema();
|
||||
var settings = schema.type("pack.flora.FloraSettings");
|
||||
var patch = schema.type("pack.flora.Patch");
|
||||
|
||||
assertEquals(List.of("pack.flora.BushSettings", "pack.flora.FloraSettings", "pack.flora.Patch", "pack.flora.WindSettings"),
|
||||
schema.types().stream().map(ObjectType::name).toList());
|
||||
assertEquals(new ObjectKind("pack.flora.Patch"), option(settings, "patch").kind());
|
||||
assertEquals(Optional.of(Map.of("bloom", "SUMMER", "radius", 3L)), option(settings, "patch").defaultValue(),
|
||||
"an object default holds the options that have one");
|
||||
assertEquals("A patch of plants", patch.description());
|
||||
assertEquals(List.of("radius", "bloom", "child"), patch.options().stream().map(SchemaOption::name).toList());
|
||||
assertEquals(new ObjectKind("pack.flora.Patch"), option(patch, "child").kind());
|
||||
assertEquals("A smaller patch inside this one", option(patch, "child").description());
|
||||
assertEquals(OptionalDouble.of(1), option(patch, "radius").minimum());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listsSnippetsAndExplicitlyRegisteredSettings() {
|
||||
var schema = floraSchema();
|
||||
|
||||
assertEquals(List.of("example/flora/bush", "example/flora/patch"), schema.snippets().stream().map(type -> type.snippet().orElseThrow()).toList());
|
||||
assertEquals(List.of("pack.flora.BushSettings", "pack.flora.Patch"), schema.snippets().stream().map(ObjectType::name).toList());
|
||||
|
||||
var bush = schema.fields(Level.PLACEMENT).getFirst();
|
||||
assertEquals("example:flora/bush", bush.id().toString());
|
||||
assertEquals(Optional.of(2L), option(bush.settings(), "height").defaultValue());
|
||||
|
||||
var wind = schema.fields(Level.DIMENSION).getFirst();
|
||||
assertEquals("example:flora/wind", wind.id().toString());
|
||||
assertEquals(new SchemaOption("strength", new DecimalKind(), "How far plants sway", false,
|
||||
OptionalDouble.empty(), OptionalDouble.empty(), OptionalInt.empty(), Optional.of(1.5)), option(wind.settings(), "strength"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameModulesGiveTheSameDescriptionWhateverTheJarOrder() {
|
||||
var other = module("pack.other.OtherModule", "example:other", NO_MEMBERS, "");
|
||||
var first = pack("first");
|
||||
flora().writeInto(first, "a.jar");
|
||||
other.writeInto(first, "b.jar");
|
||||
var second = pack("second");
|
||||
other.writeInto(second, "a.jar");
|
||||
flora().writeInto(second, "b.jar");
|
||||
|
||||
var schema = schemaOf(first, NO_BUILT_INS);
|
||||
|
||||
assertEquals(schema, schemaOf(first, NO_BUILT_INS));
|
||||
assertEquals(schema, schemaOf(second, NO_BUILT_INS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describesBuiltInModulesWithThePack() {
|
||||
var builtIns = new ArrayList<>(PlacementModules.all());
|
||||
builtIns.add(new TerrainModule());
|
||||
builtIns.add(new GrassModule());
|
||||
var schema = schemaOf(pack("empty"), ModuleHost.of(builtIns));
|
||||
|
||||
assertEquals(List.of("example:grass", "example:moss", "iris:snow", "iris:stilt"), names(schema.features(), FeatureSchema::id));
|
||||
assertEquals(List.of("moss", "snow", "stilt"), names(schema.fields(Level.PLACEMENT), FeatureSchema::key));
|
||||
|
||||
var stilt = schema.fields(Level.PLACEMENT).get(2);
|
||||
assertEquals("Stilts", stilt.module().name());
|
||||
assertEquals(new ObjectType("com.volmit.example.placement.StiltSettings", "Fills the space below an object down to the ground",
|
||||
Optional.empty(), List.of(new SchemaOption("maxDepth", new IntegerKind(), "Maximum blocks filled below each lowest object block",
|
||||
false, OptionalDouble.of(1), OptionalDouble.empty(), OptionalInt.empty(), Optional.of(16L)))), stilt.settings());
|
||||
|
||||
var grass = schema.fields(Level.BIOME).getFirst();
|
||||
assertEquals(new SchemaOption("block", new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE), "Block placed on top of each column",
|
||||
false, OptionalDouble.empty(), OptionalDouble.empty(), OptionalInt.empty(), Optional.of("minecraft:grass_block")), grass.settings().options().getFirst());
|
||||
}
|
||||
|
||||
@Test
|
||||
void builtInSettingsMayHoldHostTypesWhichTheHostDescribesItself() {
|
||||
var builtIns = List.<com.volmit.IrisModule>of(new LayersModule());
|
||||
var schema = schemaOf(pack("layers"), ModuleHost.of(builtIns).describingHostTypesIn(HOST_TYPES));
|
||||
|
||||
var layers = schema.fields(Level.BIOME).getFirst();
|
||||
var option = layers.settings().options().getFirst();
|
||||
assertEquals(new ListKind(new HostKind(Palette.class.getName()), false), option.kind());
|
||||
assertEquals(Optional.of(List.of()), option.defaultValue());
|
||||
assertTrue(schema.types().stream().noneMatch(type -> type.name().equals(Palette.class.getName())),
|
||||
"the host describes its own types, so their fields are never read");
|
||||
|
||||
var undeclared = assertThrows(ModuleLoadException.class, () -> schemaOf(pack("layers"), ModuleHost.of(builtIns)));
|
||||
assertTrue(undeclared.getMessage().startsWith("Field " + Palette.class.getName() + ".anything of settings iris:layers"),
|
||||
undeclared.getMessage());
|
||||
assertThrows(IllegalArgumentException.class, () -> NO_BUILT_INS.describingHostTypesIn("not a package"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packModulesCannotUseHostTypes() {
|
||||
var host = NO_BUILT_INS.exposing(HOST_TYPES).describingHostTypesIn(HOST_TYPES);
|
||||
assertEquals("Field pack.flora.FloraSettings.palette of " + FLORA_SOURCE + " uses " + Palette.class.getName()
|
||||
+ ", a class the host describes itself, which only settings of modules that ship with the host may use; "
|
||||
+ ValueKinds.SUPPORTED_TYPES,
|
||||
loadFailure(host, "private " + Palette.class.getName() + " palette;").getMessage());
|
||||
}
|
||||
|
||||
/** A pack whose module example:flora registers pack.flora.FloraSettings with {@code body} as its class body. */
|
||||
private ModuleLoadException loadFailure(String body, String... otherSources) {
|
||||
return loadFailure(NO_BUILT_INS, body, otherSources);
|
||||
}
|
||||
|
||||
private ModuleLoadException loadFailure(ModuleHost host, String body, String... otherSources) {
|
||||
var jar = module("pack.flora.FloraModule", FLORA,
|
||||
NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
|
||||
.compileAgainstHostOf(Palette.class)
|
||||
.source("pack.flora.FloraSettings", """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.config.*;
|
||||
import com.volmit.resource.*;
|
||||
import java.util.*;
|
||||
|
||||
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Level.BIOME)
|
||||
public final class FloraSettings implements IrisFeature {
|
||||
%s
|
||||
}
|
||||
""".formatted(body));
|
||||
for (int index = 0; index < otherSources.length; index += 2) {
|
||||
jar.source(otherSources[index], otherSources[index + 1]);
|
||||
}
|
||||
var pack = pack("broken-" + ++brokenPacks);
|
||||
jar.writeInto(pack, "flora.jar");
|
||||
return assertThrows(ModuleLoadException.class, () -> LoadedPack.load(pack, host));
|
||||
}
|
||||
|
||||
private void assertLoadFails(String expected, String body, String... otherSources) {
|
||||
assertEquals(expected, loadFailure(body, otherSources).getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsWhoseJsonIsOneOptionsValueNameThatOptionAsTheRoot() {
|
||||
var pack = pack("rooted");
|
||||
module("pack.flora.FloraModule", FLORA,
|
||||
NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
|
||||
.source("pack.flora.FloraSettings", """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.*;
|
||||
import java.util.*;
|
||||
|
||||
@Feature(id = "example:flora", name = "Flora", key = "flowers", root = "flowers", targets = Level.BIOME)
|
||||
public final class FloraSettings implements IrisFeature {
|
||||
@MinItems(1) private List<String> flowers = List.of("poppy");
|
||||
}
|
||||
""")
|
||||
.writeInto(pack, "flora.jar");
|
||||
|
||||
var flora = schemaOf(pack, NO_BUILT_INS).fields(Level.BIOME).getFirst();
|
||||
|
||||
assertEquals("flowers", flora.key());
|
||||
assertEquals(Optional.of("flowers"), flora.root());
|
||||
assertEquals(option(flora.settings(), "flowers"), flora.rootOption().orElseThrow());
|
||||
assertEquals(new ListKind(new TextKind(TextFormat.PLAIN), false), flora.rootOption().orElseThrow().kind());
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsWithoutARootHaveNoRootOption() {
|
||||
assertEquals(Optional.empty(), floraSchema().features().getFirst().rootOption());
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsMayHoldTheApisValueTypesWhichAreDescribedLikeSettings() {
|
||||
var pack = pack("values");
|
||||
module("pack.flora.FloraModule", FLORA,
|
||||
NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
|
||||
.source("pack.flora.FloraSettings", """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.block.BlockSpec;
|
||||
import com.volmit.block.PaletteSpec;
|
||||
import com.volmit.config.Feature;
|
||||
import com.volmit.config.Range;
|
||||
import com.volmit.noise.NoiseStyle;
|
||||
import com.volmit.noise.StyledRange;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import java.util.*;
|
||||
|
||||
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Level.BIOME)
|
||||
public final class FloraSettings implements IrisFeature {
|
||||
private List<BlockSpec> palette = List.of(BlockSpec.of("poppy"));
|
||||
private NoiseStyle style = NoiseStyle.of("SIMPLEX").withZoom(4);
|
||||
private PaletteSpec ground = PaletteSpec.of(List.of(BlockSpec.of("grass_block")));
|
||||
private StyledRange height = StyledRange.of(2, 5, NoiseStyle.of("SIMPLEX"));
|
||||
private Range light = Range.of(0, 15);
|
||||
private BlockPosition offset = new BlockPosition(1, 2, 3);
|
||||
private Object extra;
|
||||
}
|
||||
""")
|
||||
.writeInto(pack, "flora.jar");
|
||||
var schema = schemaOf(pack, NO_BUILT_INS);
|
||||
var settings = schema.type("pack.flora.FloraSettings");
|
||||
|
||||
assertEquals(new ListKind(new ObjectKind("com.volmit.block.BlockSpec"), false), option(settings, "palette").kind());
|
||||
assertEquals(Optional.of(List.of(Map.of("block", "poppy", "data", Map.of(), "tileData", Map.of(), "weight", 1L))),
|
||||
option(settings, "palette").defaultValue());
|
||||
assertEquals(new ObjectKind("com.volmit.noise.NoiseStyle"), option(settings, "style").kind());
|
||||
assertEquals(new ObjectKind("com.volmit.block.PaletteSpec"), option(settings, "ground").kind());
|
||||
assertEquals(new ObjectKind("com.volmit.noise.StyledRange"), option(settings, "height").kind());
|
||||
assertEquals(new ObjectKind("com.volmit.config.Range"), option(settings, "light").kind());
|
||||
assertEquals(Optional.of(Map.of("max", 15.0, "min", 0.0)), option(settings, "light").defaultValue());
|
||||
assertEquals(new ObjectKind("com.volmit.geometry.BlockPosition"), option(settings, "offset").kind());
|
||||
assertEquals(Optional.of(Map.of("x", 1L, "y", 2L, "z", 3L)), option(settings, "offset").defaultValue());
|
||||
assertEquals(new AnyKind(), option(settings, "extra").kind(), "Object holds any JSON value");
|
||||
|
||||
var block = schema.type("com.volmit.block.BlockSpec");
|
||||
assertEquals(List.of("block", "data", "weight", "backup", "tileData"), block.options().stream().map(SchemaOption::name).toList());
|
||||
assertEquals(new ReferenceKind(Reference.BLOCK, TextFormat.PLAIN), option(block, "block").kind());
|
||||
assertEquals(new MapKind(new TextKind(TextFormat.PLAIN)), option(block, "data").kind());
|
||||
assertEquals(new MapKind(new AnyKind()), option(block, "tileData").kind());
|
||||
assertEquals(new ObjectKind("com.volmit.block.BlockSpec"), option(block, "backup").kind());
|
||||
assertEquals(Optional.of("air"), option(block, "block").defaultValue());
|
||||
|
||||
var ground = schema.type("com.volmit.block.PaletteSpec");
|
||||
assertEquals(Optional.of("palette"), ground.snippet());
|
||||
assertEquals(List.of("style", "zoom", "palette"), ground.options().stream().map(SchemaOption::name).toList());
|
||||
assertEquals(new ListKind(new ObjectKind("com.volmit.block.BlockSpec"), false), option(ground, "palette").kind());
|
||||
assertTrue(option(ground, "palette").required());
|
||||
assertEquals(OptionalInt.of(1), option(ground, "palette").minItems());
|
||||
assertEquals(OptionalDouble.of(0.0001), option(ground, "zoom").minimum());
|
||||
assertEquals(Optional.of(5.0), option(ground, "zoom").defaultValue());
|
||||
|
||||
var style = schema.type("com.volmit.noise.NoiseStyle");
|
||||
assertEquals(Optional.of("style"), style.snippet(), "API classes keep the snippet folders packs already use");
|
||||
assertEquals(new ReferenceKind(Reference.NOISE_STYLE, TextFormat.PLAIN), option(style, "style").kind());
|
||||
assertEquals(new ResourceReferenceKind(PackResources.EXPRESSIONS.id()), option(style, "expression").kind());
|
||||
assertEquals(new ResourceReferenceKind(PackResources.IMAGE_MAPS.id()), option(style, "imageMap").kind());
|
||||
assertEquals(Optional.of("FLAT"), option(style, "style").defaultValue());
|
||||
assertEquals(List.of("palette", "range", "style", "style-range"), schema.snippets().stream().map(type -> type.snippet().orElseThrow()).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClassWithJsonFormsHoldsAnyJsonValueAndIsNeitherCreatedNorWalked() {
|
||||
var pack = pack("forms");
|
||||
module("pack.flora.FloraModule", FLORA,
|
||||
NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
|
||||
.source("pack.flora.FloraSettings", """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.Feature;
|
||||
import java.util.*;
|
||||
|
||||
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Level.BIOME)
|
||||
public final class FloraSettings implements IrisFeature {
|
||||
private Height height = new Height(4);
|
||||
private List<Height> steps = List.of();
|
||||
}
|
||||
""")
|
||||
.source("pack.flora.Height", """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.config.JsonForms;
|
||||
|
||||
@JsonForms(Height.Forms.class)
|
||||
public final class Height {
|
||||
private final Thread notASettingsField;
|
||||
|
||||
Height(double blocks) {
|
||||
notASettingsField = null;
|
||||
}
|
||||
|
||||
public static final class Forms implements JsonForms.Codec<Height> {
|
||||
@Override
|
||||
public Height read(Object json) {
|
||||
return new Height((Double) json);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object write(Height value) {
|
||||
return 4.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
""")
|
||||
.writeInto(pack, "flora.jar");
|
||||
var schema = schemaOf(pack, NO_BUILT_INS);
|
||||
var settings = schema.type("pack.flora.FloraSettings");
|
||||
|
||||
assertEquals(new AnyKind(), option(settings, "height").kind());
|
||||
assertEquals(Optional.empty(), option(settings, "height").defaultValue());
|
||||
assertEquals(new ListKind(new AnyKind(), false), option(settings, "steps").kind());
|
||||
assertTrue(schema.types().stream().noneMatch(type -> type.name().equals("pack.flora.Height")), "the host describes no more of it");
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultsLeaveOutWhatJsonCannotHold() {
|
||||
var pack = pack("defaults");
|
||||
module("pack.flora.FloraModule", FLORA,
|
||||
NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
|
||||
.source("pack.flora.FloraSettings", """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.Feature;
|
||||
import java.util.*;
|
||||
|
||||
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Level.BIOME)
|
||||
public final class FloraSettings implements IrisFeature {
|
||||
private Node node = new Node();
|
||||
private double ratio = Double.NaN;
|
||||
private List<String> names = Arrays.asList("a", null);
|
||||
private Set<Node> nodes = Set.of(new Node());
|
||||
}
|
||||
""")
|
||||
.source("pack.flora.Node", "package pack.flora; final class Node { private Node self = this; private int size = 1; }")
|
||||
.writeInto(pack, "flora.jar");
|
||||
var settings = schemaOf(pack, NO_BUILT_INS).type("pack.flora.FloraSettings");
|
||||
|
||||
assertEquals(Optional.of(Map.of("size", 1L)), option(settings, "node").defaultValue(), "a reference back to itself is left out");
|
||||
assertEquals(Optional.empty(), option(settings, "ratio").defaultValue());
|
||||
assertEquals(Optional.empty(), option(settings, "names").defaultValue());
|
||||
assertEquals(Optional.empty(), option(settings, "nodes").defaultValue(), "a set of objects has no order to write");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedFieldTypesFailTheLoadNamingClassFieldAndModule() {
|
||||
assertLoadFails("Field pack.flora.FloraSettings.id of " + FLORA_SOURCE + " uses java.util.UUID, a JDK class settings cannot use; "
|
||||
+ ValueKinds.SUPPORTED_TYPES, "private UUID id;");
|
||||
assertLoadFails("Field pack.flora.FloraSettings.name of " + FLORA_SOURCE + " uses java.util.Optional<java.lang.String>;"
|
||||
+ " only List, Set and Map may have type arguments", "private Optional<String> name;");
|
||||
assertLoadFails("Field pack.flora.FloraSettings.names of " + FLORA_SOURCE + " uses java.util.List without type arguments;"
|
||||
+ " declare it as List<...>, Set<...> or Map<String, ...>", "@SuppressWarnings(\"rawtypes\") private List names;");
|
||||
assertLoadFails("Field pack.flora.FloraSettings.names of " + FLORA_SOURCE + " uses java.util.ArrayList<java.lang.String>;"
|
||||
+ " declare it as List<...>, Set<...> or Map<String, ...>", "private ArrayList<String> names;");
|
||||
assertLoadFails("Field pack.flora.FloraSettings.weights of " + FLORA_SOURCE + " uses java.util.Map<java.lang.Integer, java.lang.String>;"
|
||||
+ " map keys must be String", "private Map<Integer, String> weights;");
|
||||
assertLoadFails("Field pack.flora.FloraSettings.letter of " + FLORA_SOURCE + " uses char, which settings cannot use; "
|
||||
+ ValueKinds.SUPPORTED_TYPES, "private char letter;");
|
||||
assertLoadFails("Field pack.flora.FloraSettings.names of " + FLORA_SOURCE + " uses ? extends java.lang.String, which is not a"
|
||||
+ " concrete type; name the type, such as List<String>", "private List<? extends String> names;");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedClassesMustBeConcreteStaticAndConstructible() {
|
||||
assertLoadFails("Field pack.flora.FloraSettings.shape of " + FLORA_SOURCE + " uses pack.flora.Shape, which is abstract;"
|
||||
+ " settings fields need a concrete class", "private Shape shape;", "pack.flora.Shape", "package pack.flora; interface Shape {}");
|
||||
assertLoadFails("Field pack.flora.FloraSettings.inner of " + FLORA_SOURCE + " uses pack.flora.FloraSettings$Inner, which is an"
|
||||
+ " inner class; declare it static", "private Inner inner; class Inner {}");
|
||||
assertLoadFails("Class pack.flora.Shape of " + FLORA_SOURCE + " has no no-argument constructor; the host creates settings with it"
|
||||
+ " and reads their defaults from it, so declare one, private if nothing else should use it",
|
||||
"private Shape shape;", "pack.flora.Shape", "package pack.flora; record Shape(int size) {}");
|
||||
|
||||
var throwing = loadFailure("private Shape shape;", "pack.flora.Shape",
|
||||
"package pack.flora; final class Shape { Shape() { throw new IllegalStateException(\"no shapes today\"); } }");
|
||||
assertEquals("The no-argument constructor of pack.flora.Shape of " + FLORA_SOURCE + " threw java.lang.IllegalStateException:"
|
||||
+ " no shapes today; the host creates settings with it, so it must not fail", throwing.getMessage());
|
||||
var describeFailure = throwing.getCause();
|
||||
assertEquals("no shapes today", describeFailure.getCause().getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void referencesOnIncompatibleFieldsFailTheLoad() {
|
||||
assertLoadFails("Field pack.flora.FloraSettings.count of " + FLORA_SOURCE + " has @Ref(BLOCK) on int, but @Ref fits only String"
|
||||
+ " and ResourceId and lists, sets and arrays of them", "@Ref(Reference.BLOCK) private int count;");
|
||||
assertLoadFails("Field pack.flora.FloraSettings.flower of " + FLORA_SOURCE + " has @Ref(ITEM) on BlockState, which always names"
|
||||
+ " a block; remove the @Ref or use String or ResourceId", "@Ref(Reference.ITEM) private BlockState flower;");
|
||||
assertLoadFails("Field pack.flora.FloraSettings.blocks of " + FLORA_SOURCE + " has @Ref(BLOCK) on java.util.Map<java.lang.String,"
|
||||
+ " java.lang.String>, but @Ref fits only String and ResourceId and lists, sets and arrays of them",
|
||||
"@Ref(Reference.BLOCK) private Map<String, String> blocks;");
|
||||
assertTrue(loadFailure("@Ref(Reference.ENTITY) private List<Integer> counts;").getMessage()
|
||||
.contains("has @Ref(ENTITY) on java.lang.Integer"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void snippetNamesAreFolderPathsThatBelongToOneClass() {
|
||||
var notAPath = "is not a folder path; packs write snippets under snippet/<name>/, so use lowercase letters, digits, '-', '_'"
|
||||
+ " and '.', with '/' between folders";
|
||||
assertLoadFails("Snippet name 'example/flora/Big Patch' of pack.flora.Patch of " + FLORA_SOURCE + " " + notAPath,
|
||||
"private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/Big Patch\") final class Patch {}");
|
||||
assertLoadFails("Snippet name 'example/flora/../moss' of pack.flora.Patch of " + FLORA_SOURCE + " " + notAPath,
|
||||
"private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/../moss\") final class Patch {}");
|
||||
assertLoadFails("Snippet name 'example/flora/patch' is used by pack.flora.Patch of " + FLORA_SOURCE + " and by pack.flora.Plot of " + FLORA_SOURCE
|
||||
+ "; studio describes snippet/example/flora/patch/ by one class, so give each its own name",
|
||||
"private Patch patch; private Plot plot;",
|
||||
"pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/patch\") final class Patch {}",
|
||||
"pack.flora.Plot", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/patch\") final class Plot {}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void packSnippetsLiveUnderTheirModulesFolder() {
|
||||
assertLoadFails("Snippet name 'patch' of pack.flora.Patch of " + FLORA_SOURCE + " is not under a module of the pack; snippets of pack"
|
||||
+ " modules start with their module's id as a folder path, such as 'example/flora/patch' (folder snippet/example/flora/patch/)",
|
||||
"private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"patch\") final class Patch {}");
|
||||
assertLoadFails("Snippet name 'example/florae/patch' of pack.flora.Patch of " + FLORA_SOURCE + " is not under a module of the pack;"
|
||||
+ " snippets of pack modules start with their module's id as a folder path, such as 'example/flora/patch'"
|
||||
+ " (folder snippet/example/flora/patch/)",
|
||||
"private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/florae/patch\") final class Patch {}");
|
||||
|
||||
var pack = pack("module-folder");
|
||||
module("pack.flora.FloraModule", FLORA,
|
||||
NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
|
||||
.source("pack.flora.FloraSettings", """
|
||||
package pack.flora;
|
||||
|
||||
@com.volmit.config.Snippet("example/flora")
|
||||
@com.volmit.config.Feature(id = "example:flora", name = "Flora", key = "flora", targets = com.volmit.config.Level.BIOME)
|
||||
public final class FloraSettings implements com.volmit.IrisFeature {}
|
||||
""")
|
||||
.writeInto(pack, "flora.jar");
|
||||
assertEquals(List.of("example/flora"), schemaOf(pack, NO_BUILT_INS).snippets().stream()
|
||||
.map(type -> type.snippet().orElseThrow()).toList(), "the module's own folder is under its path");
|
||||
}
|
||||
|
||||
@Test
|
||||
void packReferencesOnResourceIdsAreWrittenAsKeys() {
|
||||
var pack = pack("pack-ids");
|
||||
module("pack.flora.FloraModule", FLORA, NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
|
||||
.source("pack.flora.FloraSettings", """
|
||||
package pack.flora;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.*;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import java.util.*;
|
||||
|
||||
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Level.BIOME)
|
||||
public final class FloraSettings implements IrisFeature {
|
||||
@ResourceRef(com.volmit.world.PackBiome.class) private ResourceId home;
|
||||
@ResourceRef(com.volmit.object.GeneratedObject.class) private List<ResourceId> objects = List.of();
|
||||
}
|
||||
""")
|
||||
.writeInto(pack, "flora.jar");
|
||||
|
||||
var settings = schemaOf(pack, NO_BUILT_INS).type("pack.flora.FloraSettings");
|
||||
|
||||
assertEquals(new ResourceReferenceKind(PackResources.BIOMES.id()), option(settings, "home").kind());
|
||||
assertEquals(new ListKind(new ResourceReferenceKind(PackResources.OBJECTS.id()), false), option(settings, "objects").kind());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inheritedOptionsComeBeforeTheirSubclasssOwn() {
|
||||
var pack = pack("inherited");
|
||||
module("pack.flora.FloraModule", FLORA,
|
||||
NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
|
||||
.source("pack.flora.Base", "package pack.flora; abstract class Base { private int zeta; private int alpha; }")
|
||||
.source("pack.flora.FloraSettings", """
|
||||
package pack.flora;
|
||||
|
||||
@com.volmit.config.Feature(id = "example:flora", name = "Flora", key = "flora", targets = com.volmit.config.Level.BIOME)
|
||||
public final class FloraSettings extends Base implements com.volmit.IrisFeature { private int omega; private int beta; }
|
||||
""")
|
||||
.writeInto(pack, "flora.jar");
|
||||
|
||||
var settings = schemaOf(pack, NO_BUILT_INS).type("pack.flora.FloraSettings");
|
||||
|
||||
assertEquals(List.of("zeta", "alpha", "omega", "beta"), settings.options().stream().map(SchemaOption::name).toList());
|
||||
}
|
||||
|
||||
private static final String CASTLE = "example:castle";
|
||||
private static final String CASTLE_SETUP = """
|
||||
registry.registerResourceKind(com.volmit.resource.ResourceKind.of("example:castle/keep", "keeps", Keep.class));
|
||||
registry.registerSettings(CastleSettings.class);
|
||||
""";
|
||||
|
||||
private static TestModuleJar castle() {
|
||||
return module("pack.castle.CastleModule", CASTLE, NO_MEMBERS, CASTLE_SETUP)
|
||||
.source("pack.castle.Keep", """
|
||||
package pack.castle;
|
||||
|
||||
import com.volmit.config.*;
|
||||
|
||||
@Desc("A keep of a castle")
|
||||
public final class Keep {
|
||||
@Desc("Towers on the walls") @MinNumber(1)
|
||||
private int towers = 4;
|
||||
@ResourceRef(Keep.class)
|
||||
private String next = "";
|
||||
}
|
||||
""")
|
||||
.source("pack.castle.CastleSettings", """
|
||||
package pack.castle;
|
||||
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.*;
|
||||
import java.util.List;
|
||||
|
||||
@Feature(id = "example:castle", name = "Castle", key = "castle", targets = Level.BIOME)
|
||||
public final class CastleSettings implements IrisFeature {
|
||||
@ResourceRef(Keep.class)
|
||||
private List<String> keeps = List.of("main");
|
||||
}
|
||||
""");
|
||||
}
|
||||
|
||||
private PackSchema castleSchema(ModuleHost host) {
|
||||
var pack = pack("castle-" + ++brokenPacks);
|
||||
castle().writeInto(pack, "castle.jar");
|
||||
return schemaOf(pack, host);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describesResourceKindsLikeSettingsAndReferencesToThem() {
|
||||
var schema = castleSchema(NO_BUILT_INS);
|
||||
var keepKind = ResourceId.parse("example:castle/keep");
|
||||
|
||||
var kind = schema.resources().getFirst();
|
||||
assertEquals(new ResourceKindSchema(keepKind, kind.module(), "keeps", new ObjectKind("pack.castle.Keep")), kind);
|
||||
assertEquals(CASTLE, kind.module().id().toString());
|
||||
assertSame(kind, schema.resource(keepKind));
|
||||
var keep = schema.type("pack.castle.Keep");
|
||||
assertEquals("A keep of a castle", keep.description());
|
||||
assertEquals(new SchemaOption("towers", new IntegerKind(), "Towers on the walls", false, OptionalDouble.of(1),
|
||||
OptionalDouble.empty(), OptionalInt.empty(), Optional.of(4L)), keep.options().getFirst());
|
||||
assertEquals(new ResourceReferenceKind(keepKind), keep.options().get(1).kind(), "a resource may name others of its kind");
|
||||
var keeps = schema.fields(Level.BIOME).getFirst().settings().options().getFirst();
|
||||
assertEquals(new ListKind(new ResourceReferenceKind(keepKind), false), keeps.kind());
|
||||
assertEquals(Optional.of(List.of("main")), keeps.defaultValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void builtInKindsMayReadIntoHostTypesWhichTheHostDescribesItself() {
|
||||
var builtIn = registering("iris:palettes", ResourceKind.of("iris:palettes/palette", "palettes", Palette.class));
|
||||
var schema = schemaOf(pack("palettes"), ModuleHost.of(List.of(builtIn)).describingHostTypesIn(HOST_TYPES));
|
||||
|
||||
assertEquals(new HostKind(Palette.class.getName()), schema.resources().getFirst().type());
|
||||
assertTrue(schema.types().isEmpty(), "the host describes its own types");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kindFoldersBelongToOneKindAndNeverToTheHost() {
|
||||
var builtIn = registering("iris:keeps", ResourceKind.of("iris:keeps/keep", "keeps", Palette.class));
|
||||
var shared = assertThrows(ModuleLoadException.class, () -> castleSchema(ModuleHost.of(List.of(builtIn))));
|
||||
assertEquals("resource kind example:castle/keep of module example:castle from modules/castle.jar reads folder 'keeps',"
|
||||
+ " which resource kind iris:keeps/keep of module iris:keeps from host classpath reads already; a folder holds"
|
||||
+ " one kind, so give one of them a folder of its own", shared.getMessage());
|
||||
|
||||
var reserved = assertThrows(ModuleLoadException.class, () -> castleSchema(NO_BUILT_INS.reservingFolders("keeps")));
|
||||
assertEquals("Resource kind example:castle/keep of module example:castle from modules/castle.jar reads folder 'keeps',"
|
||||
+ " which the host reads itself; give the kind a folder of its own", reserved.getMessage());
|
||||
assertThrows(IllegalArgumentException.class, () -> NO_BUILT_INS.reservingFolders("not/a/folder"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packKindsCannotReadIntoHostTypes() {
|
||||
var jar = module("pack.castle.CastleModule", CASTLE, NO_MEMBERS, """
|
||||
registry.registerResourceKind(com.volmit.resource.ResourceKind.of("example:castle/palette", "palettes",
|
||||
%s.class));
|
||||
""".formatted(Palette.class.getName())).compileAgainstHostOf(Palette.class);
|
||||
var pack = pack("castle-host-type");
|
||||
jar.writeInto(pack, "castle.jar");
|
||||
var host = NO_BUILT_INS.exposing(HOST_TYPES).describingHostTypesIn(HOST_TYPES);
|
||||
|
||||
var failure = assertThrows(ModuleLoadException.class, () -> LoadedPack.load(pack, host));
|
||||
assertEquals("Resource kind example:castle/palette of module example:castle from modules/castle.jar reads into "
|
||||
+ Palette.class.getName() + ", a class the host describes itself, which only modules that ship with the host"
|
||||
+ " may use; read the files into a class of the module", failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourceReferencesNameARegisteredKindOnPlainText() {
|
||||
assertLoadFails("Field pack.flora.FloraSettings.keep of " + FLORA_SOURCE + " has @ResourceRef(java.lang.Integer), but"
|
||||
+ " neither the host nor a module of the pack has a resource kind read into that class; name the type of a"
|
||||
+ " PackResources kind or of a kind registered with FeatureRegistry.registerResourceKind",
|
||||
"@ResourceRef(Integer.class) private String keep;");
|
||||
assertLoadFails("Field pack.flora.FloraSettings.count of " + FLORA_SOURCE + " has @ResourceRef(java.lang.Integer) on int,"
|
||||
+ " but @ResourceRef fits only String and ResourceId and lists, sets and arrays of them",
|
||||
"@ResourceRef(Integer.class) private int count;");
|
||||
assertLoadFails("Option keep has both @Ref and @ResourceRef; it names either a registry entry or a pack resource",
|
||||
"@Ref(Reference.BLOCK) @ResourceRef(Integer.class) private String keep;");
|
||||
}
|
||||
|
||||
/** A built-in module {@code id} that registers {@code kind}. */
|
||||
private static com.volmit.IrisModule registering(String id, ResourceKind<?> kind) {
|
||||
return new com.volmit.IrisModule() {
|
||||
public com.volmit.ModuleInfo info() { return com.volmit.ModuleInfo.of(id, "Kinds", "test"); }
|
||||
public void setup(com.volmit.ModuleSetup setup) { setup.registry().registerResourceKind(kind); }
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,704 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.FeatureRegistry;
|
||||
import com.volmit.config.Level;
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.config.Feature;
|
||||
import com.volmit.config.FeatureSettings.Entry;
|
||||
import com.volmit.geometry.BlockBox;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.data.StorageCodec;
|
||||
import com.volmit.mantle.MantleKey;
|
||||
import com.volmit.mantle.MantleLifetime;
|
||||
import com.volmit.object.GeneratedObject;
|
||||
import com.volmit.object.ObjectBlock;
|
||||
import com.volmit.placement.PlacedBlock;
|
||||
import com.volmit.placement.PlacementEdit;
|
||||
import com.volmit.placement.PlacementOutcome;
|
||||
import com.volmit.placement.PlacementRequest;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.stage.BlockStageContext;
|
||||
import com.volmit.stage.ChunkStage;
|
||||
import com.volmit.stage.Pipeline;
|
||||
import com.volmit.stage.PlacementStage;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.stage.StageGraph;
|
||||
import com.volmit.stage.StageRef;
|
||||
import com.volmit.support.ColumnSettings;
|
||||
import com.volmit.support.DeclaredSettings;
|
||||
import com.volmit.support.MemoryEdit;
|
||||
import com.volmit.support.MemoryMantle;
|
||||
import com.volmit.support.TestContexts;
|
||||
import com.volmit.support.TestSetups;
|
||||
import com.volmit.support.TestTerrain;
|
||||
import com.volmit.example.placement.SnowModule;
|
||||
import com.volmit.example.placement.SnowSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class StageGraphTest {
|
||||
private static final BlockState STONE = new BlockState("minecraft:stone");
|
||||
|
||||
@Feature(id = "test:owner/toggle", name = "Toggle", key = "ownerToggle", targets = Level.PLACEMENT)
|
||||
static final class Toggle implements IrisFeature {}
|
||||
|
||||
static final class Unannotated implements IrisFeature {}
|
||||
|
||||
private static IrisModule module(String id, Consumer<StageGraph> install) {
|
||||
return new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(id, "Test module " + id, "1"); }
|
||||
public void setup(ModuleSetup setup) { install.accept(setup.stages()); }
|
||||
};
|
||||
}
|
||||
|
||||
private static ResolvedGraph resolve(Pipeline pipeline, IrisModule... modules) {
|
||||
return TestSetups.stages(modules).resolve(pipeline);
|
||||
}
|
||||
|
||||
private static List<Class<? extends IrisFeature>> resolveSettings(IrisModule... modules) {
|
||||
return TestSetups.stages(modules).settingsTypes(type -> false);
|
||||
}
|
||||
|
||||
private static List<String> order(ResolvedGraph graph) {
|
||||
return graph.stages().stream().map(stage -> stage.stage().id().toString()).toList();
|
||||
}
|
||||
|
||||
private static List<List<String>> passes(ResolvedGraph graph) {
|
||||
return graph.blockPasses().stream().map(pass -> pass.stream().map(ResourceId::toString).toList()).toList();
|
||||
}
|
||||
|
||||
private static PlacementRequest twoBlockRequest() {
|
||||
var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 1, 1), new BlockPosition(0, 0, 0),
|
||||
List.of(new ObjectBlock(new BlockPosition(0, 0, 0), STONE), new ObjectBlock(new BlockPosition(1, 0, 0), STONE)),
|
||||
List.of());
|
||||
return new PlacementRequest(object,new BlockPosition(0, 10, 0));
|
||||
}
|
||||
|
||||
private static MemoryEdit flatEdit() {
|
||||
return new MemoryEdit(new TestTerrain((x, z) -> 5));
|
||||
}
|
||||
|
||||
private static PlacementOutcome place(ResolvedGraph graph, MemoryEdit edit, ConfiguredSettings settings) {
|
||||
return place(graph, edit, settings, StageTimings.NONE);
|
||||
}
|
||||
|
||||
private static PlacementOutcome place(ResolvedGraph graph, MemoryEdit edit, ConfiguredSettings settings, StageTimings timings) {
|
||||
return new PlacementRunner(graph).place(twoBlockRequest(), edit, TestContexts.placement(), TestContexts.SEED, settings, timings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void adjacentBlockStagesShareOnePassAndRunPerBlockInOrder() {
|
||||
var first = Stage.placementBlock("test:blocks/first");
|
||||
var second = Stage.placementBlock("test:blocks/second");
|
||||
var events = new ArrayList<String>();
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:blocks", stages -> {
|
||||
stages.define(second).requires(first).run(context -> events.add("second@" + context.block().position().x()));
|
||||
stages.define(first).run(context -> events.add("first@" + context.block().position().x()));
|
||||
}));
|
||||
|
||||
assertEquals(List.of(List.of("test:blocks/first", "test:blocks/second")), passes(graph));
|
||||
assertTrue(place(graph, flatEdit(), ConfiguredSettings.none()).isPlaced());
|
||||
assertEquals(List.of("first@0", "second@0", "first@1", "second@1"), events);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiredInvocationStageBetweenBlockStagesSplitsThePass() {
|
||||
var collect = Stage.placementBlock("test:split/collect", Counter.class);
|
||||
var middle = Stage.placement("test:split/middle", Integer.class);
|
||||
var paint = Stage.placementBlock("test:split/paint");
|
||||
var events = new ArrayList<String>();
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:split", stages -> {
|
||||
stages.define(collect).accumulate(Counter::new, (context, counter) -> {
|
||||
counter.count++;
|
||||
events.add("collect");
|
||||
});
|
||||
stages.define(middle).requires(collect).produce(context -> {
|
||||
events.add("middle");
|
||||
return context.output(collect).count;
|
||||
});
|
||||
stages.define(paint).requires(middle).run(context -> events.add("paint:" + context.output(middle)));
|
||||
}));
|
||||
|
||||
assertEquals(List.of(List.of("test:split/collect"), List.of("test:split/paint")), passes(graph));
|
||||
assertTrue(place(graph, flatEdit(), ConfiguredSettings.none()).isPlaced());
|
||||
assertEquals(List.of("collect", "collect", "middle", "paint:2", "paint:2"), events);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unrelatedInvocationStagesRunOutsideBlockPassesSoTheyDoNotSplitThem() {
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:fusion", stages -> {
|
||||
stages.define(Stage.placementBlock("test:fusion/a")).run(context -> {});
|
||||
stages.define(Stage.placement("test:fusion/b")).run(context -> {});
|
||||
stages.define(Stage.placementBlock("test:fusion/c")).run(context -> {});
|
||||
}));
|
||||
|
||||
assertEquals(List.of("test:fusion/b", "test:fusion/a", "test:fusion/c"), order(graph));
|
||||
assertEquals(List.of(List.of("test:fusion/a", "test:fusion/c")), passes(graph));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unorderedStagesFollowLexicalIdsRegardlessOfInstallOrder() {
|
||||
var zebra = module("zeta:module", stages -> stages.define(Stage.placement("zeta:module/work")).run(context -> {}));
|
||||
var alpha = module("alpha:module", stages -> stages.define(Stage.placement("alpha:module/work")).run(context -> {}));
|
||||
var forward = resolve(Pipeline.PLACEMENT, zebra, alpha);
|
||||
var reversed = resolve(Pipeline.PLACEMENT, alpha, zebra);
|
||||
|
||||
assertEquals(List.of("alpha:module/work", "zeta:module/work"), order(forward));
|
||||
assertEquals(forward.describe(), reversed.describe());
|
||||
assertEquals(List.of(new ResolvedGraph.UnorderedPair(ResourceId.parse("alpha:module/work"), ResourceId.parse("zeta:module/work"))),
|
||||
forward.unorderedPairs());
|
||||
}
|
||||
|
||||
@Test
|
||||
void softEdgesOrderOnlyInstalledStagesAndReportAbsentTargets() {
|
||||
var late = Stage.placement("test:soft/late");
|
||||
var early = Stage.placement("test:soft/early");
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:soft", stages -> {
|
||||
stages.define(early).softAfter(StageRef.of("test:soft/late")).run(context -> {});
|
||||
stages.define(late).softBefore(StageRef.of("other:gone/missing")).run(context -> {});
|
||||
}));
|
||||
|
||||
assertEquals(List.of("test:soft/late", "test:soft/early"), order(graph));
|
||||
var earlyStage = graph.stages().get(1);
|
||||
assertEquals(List.of(new StageEdge(late.id(), early.id(), StageEdge.Kind.SOFT)), earlyStage.incoming());
|
||||
assertEquals(List.of(StageRef.of("other:gone/missing")), graph.stages().get(0).absentSoftTargets());
|
||||
assertTrue(graph.describe().contains("absent soft targets other:gone/missing"));
|
||||
assertTrue(graph.unorderedPairs().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void softEdgesTakeTheStageConstantLikeItsId() {
|
||||
var late = Stage.placement("test:soft/late");
|
||||
var early = Stage.placement("test:soft/early");
|
||||
var last = Stage.placement("test:soft/last");
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:soft", stages -> {
|
||||
stages.define(early).softAfter(late).run(context -> {});
|
||||
stages.define(last).run(context -> {});
|
||||
stages.define(late).softBefore(last).run(context -> {});
|
||||
}));
|
||||
|
||||
assertEquals(List.of("test:soft/late", "test:soft/early", "test:soft/last"), order(graph));
|
||||
assertEquals(List.of(new StageEdge(late.id(), early.id(), StageEdge.Kind.SOFT)), graph.stages().get(1).incoming());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingRequirementNamesBothStagesAndTheirModules() {
|
||||
var absent = Stage.placement("other:gone/absent");
|
||||
var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT,
|
||||
module("test:needy", stages -> stages.define(Stage.placement("test:needy/work")).requires(absent).run(context -> {}))));
|
||||
|
||||
assertEquals("Stage test:needy/work (module test:needy) requires other:gone/absent, which no installed module "
|
||||
+ "defines (expected a module in namespace 'other')", error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void requirementMustBeTheOwnersDeclarationNotACopyWithTheSameId() {
|
||||
var owned = Stage.placement("test:owner/owned");
|
||||
var copy = Stage.placement("test:owner/owned");
|
||||
var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT,
|
||||
module("test:owner", stages -> stages.define(owned).run(context -> {})),
|
||||
module("test:user", stages -> stages.define(Stage.placement("test:user/work")).requires(copy).run(context -> {}))));
|
||||
|
||||
assertTrue(error.getMessage().contains("different declaration of test:owner/owned (module test:owner)"), error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cyclesListEveryStageWithItsModuleAndEdgeKind() {
|
||||
var a = Stage.placement("test:first/a");
|
||||
var b = Stage.placement("other:second/b");
|
||||
var c = Stage.placement("test:first/c");
|
||||
var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT,
|
||||
module("test:first", stages -> {
|
||||
stages.define(a).requires(b).run(context -> {});
|
||||
stages.define(c).requires(a).run(context -> {});
|
||||
}),
|
||||
module("other:second", stages -> stages.define(b).softAfter(c).run(context -> {}))));
|
||||
|
||||
assertEquals("Stage cycle in pipeline PLACEMENT: other:second/b (module other:second) -[required]-> "
|
||||
+ "test:first/a (module test:first) -[required]-> test:first/c (module test:first) -[soft]-> "
|
||||
+ "other:second/b (module other:second)", error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stageIdsMustStartWithTheirModuleIdAndDefinitionsAreUnique() {
|
||||
var foreign = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT,
|
||||
module("test:module", stages -> stages.define(Stage.placement("iris:stolen/work")).run(context -> {}))));
|
||||
assertEquals("Stage iris:stolen/work must start with test:module/, the id of its defining module test:module "
|
||||
+ "from host classpath", foreign.getMessage());
|
||||
|
||||
for (var outside : List.of("test:other/work", "test:module", "test:modules/work")) {
|
||||
var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT,
|
||||
module("test:module", stages -> stages.define(Stage.placement(outside)).run(context -> {}))));
|
||||
assertTrue(error.getMessage().contains("must start with test:module/"), error.getMessage());
|
||||
}
|
||||
|
||||
var shared = Stage.placement("test:one/shared");
|
||||
var duplicate = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT,
|
||||
module("test:one", stages -> {
|
||||
stages.define(shared).run(context -> {});
|
||||
stages.define(shared).run(context -> {});
|
||||
})));
|
||||
assertTrue(duplicate.getMessage().contains("already defined by module test:one"), duplicate.getMessage());
|
||||
|
||||
var module = module("test:twice", stages -> {});
|
||||
var builder = TestSetups.stages(module);
|
||||
assertThrows(IllegalArgumentException.class, () -> TestSetups.install(builder, DiscoveredModule.builtIn(module)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsMustBeOwnedByAModuleThatNamesThem() {
|
||||
var foreign = assertThrows(IllegalArgumentException.class, () -> resolveSettings(
|
||||
module("other:user", stages -> stages.define(Stage.placement("other:user/work")).when(Toggle.class).run(context -> {}))));
|
||||
assertEquals("Settings type " + Toggle.class.getName() + " has feature id test:owner/toggle, which none of the modules "
|
||||
+ "naming it in when(...) owns: other:user from host classpath. A feature id is the id of the module that owns "
|
||||
+ "the settings, such as other:user, or starts with it and '/', such as other:user/toggle", foreign.getMessage());
|
||||
|
||||
var sameNamespace = assertThrows(IllegalArgumentException.class, () -> resolveSettings(
|
||||
module("test:user", stages -> stages.define(Stage.placement("test:user/work")).when(Toggle.class).run(context -> {}))));
|
||||
assertTrue(sameNamespace.getMessage().contains("none of the modules naming it in when(...) owns: test:user from host classpath"),
|
||||
sameNamespace.getMessage());
|
||||
|
||||
var shared = resolveSettings(
|
||||
module("test:owner", stages -> stages.define(Stage.placement("test:owner/work")).when(Toggle.class).run(context -> {})),
|
||||
module("other:user", stages -> stages.define(Stage.placement("other:user/work")).when(Toggle.class).run(context -> {})));
|
||||
assertEquals(List.of(Toggle.class), shared);
|
||||
|
||||
var snowOnMoss = resolveSettings(new SnowModule(), module("example:moss", stages ->
|
||||
stages.define(Stage.placement("example:moss/on-snow")).when(SnowSettings.class).run(context -> {})));
|
||||
assertTrue(snowOnMoss.contains(SnowSettings.class), "moss may condition on iris:snow, which iris:snow owns");
|
||||
}
|
||||
|
||||
@Test
|
||||
void dependenciesCannotCrossPipelines() {
|
||||
var placementStage = Stage.placement("test:hard/placed");
|
||||
ChunkStage<Void> chunkStage = Stage.chunk("test:hard/chunk");
|
||||
var hard = module("test:hard", stages -> {
|
||||
stages.define(placementStage).run(context -> {});
|
||||
stages.define(chunkStage).requires(placementStage).run(context -> {});
|
||||
});
|
||||
var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, hard));
|
||||
assertTrue(error.getMessage().contains("in pipeline CHUNK depends on test:hard/placed (module test:hard) in pipeline PLACEMENT"),
|
||||
error.getMessage());
|
||||
|
||||
var soft = module("test:soft", stages -> {
|
||||
stages.define(Stage.placement("test:soft/placed")).run(context -> {});
|
||||
stages.define(Stage.chunk("test:soft/chunk")).softAfter(StageRef.of("test:soft/placed")).run(context -> {});
|
||||
});
|
||||
assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, soft));
|
||||
}
|
||||
|
||||
@Test
|
||||
void definitionsNeedExactlyOneBodyOfTheRightKind() {
|
||||
var withOutput = Stage.placement("test:bodies/output", Integer.class);
|
||||
var withoutOutput = Stage.placement("test:bodies/plain");
|
||||
var accumulating = Stage.placementBlock("test:bodies/acc", Counter.class);
|
||||
|
||||
var run = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT,
|
||||
module("test:bodies", stages -> stages.define(withOutput).run(context -> {}))));
|
||||
assertTrue(run.getMessage().contains("declares output Integer; define it with produce(...)"), run.getMessage());
|
||||
assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT,
|
||||
module("test:bodies", stages -> stages.define(withoutOutput).produce(context -> null))));
|
||||
assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT,
|
||||
module("test:bodies", stages -> stages.define(accumulating).run(context -> {}))));
|
||||
var missing = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT,
|
||||
module("test:bodies", stages -> stages.define(withoutOutput).requires())));
|
||||
assertTrue(missing.getMessage().contains("has no body"), missing.getMessage());
|
||||
assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT, module("test:bodies", stages -> {
|
||||
var definition = stages.define(withoutOutput);
|
||||
definition.run(context -> {});
|
||||
definition.requires(withOutput);
|
||||
})));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidDeclarationsFailDuringSetup() {
|
||||
assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:self", stages -> {
|
||||
var self = Stage.placement("test:self/work");
|
||||
stages.define(self).requires(self).run(context -> {});
|
||||
})));
|
||||
assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT, module("test:twice", stages -> {
|
||||
var definition = stages.define(Stage.placement("test:twice/work"));
|
||||
definition.when(Toggle.class);
|
||||
definition.when(Toggle.class);
|
||||
})));
|
||||
assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:plain", stages ->
|
||||
stages.define(Stage.placement("test:plain/work")).when(Unannotated.class).run(context -> {}))));
|
||||
|
||||
var retained = new ArrayList<StageGraph>();
|
||||
TestSetups.stages(module("test:retained", retained::add));
|
||||
assertThrows(IllegalStateException.class, () -> retained.getFirst().define(Stage.placement("test:retained/late")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void outputsAreReadableOnlyThroughTransitiveRequirementsAndAfterTheirPass() {
|
||||
var height = Stage.placement("test:outputs/height", Integer.class);
|
||||
var offset = Stage.placement("test:outputs/offset", Integer.class);
|
||||
var counted = Stage.placementBlock("test:outputs/counted", Counter.class);
|
||||
var observed = new ArrayList<Object>();
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:outputs", stages -> {
|
||||
stages.define(height).produce(context -> 10);
|
||||
stages.define(offset).requires(height).produce(context -> context.output(height) + 1);
|
||||
stages.define(counted).requires(offset).accumulate(Counter::new, (context, counter) -> {
|
||||
counter.count++;
|
||||
observed.add(context.output(height));
|
||||
});
|
||||
stages.define(Stage.placementBlock("test:outputs/peek")).requires(counted).run(context -> observed.add(
|
||||
assertThrows(IllegalStateException.class, () -> context.output(counted)).getMessage()));
|
||||
stages.define(Stage.placement("test:outputs/reader")).requires(counted).run(context -> observed.add(context.output(counted).count));
|
||||
stages.define(Stage.placement("test:outputs/snoop")).run(context -> observed.add(
|
||||
assertThrows(IllegalStateException.class, () -> context.output(height)).getMessage()));
|
||||
}));
|
||||
|
||||
assertTrue(place(graph, flatEdit(), ConfiguredSettings.none()).isPlaced());
|
||||
assertEquals(10, observed.get(1));
|
||||
assertTrue(observed.get(2).toString().contains("before it completed"), observed.get(2).toString());
|
||||
assertTrue(observed.contains(2));
|
||||
assertTrue(observed.contains("Stage test:outputs/snoop read the output of test:outputs/height without requiring it; "
|
||||
+ "add requires(test:outputs/height) to its definition"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullOutputsFailTheInvocation() {
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:nulls", stages ->
|
||||
stages.define(Stage.placement("test:nulls/value", Integer.class)).produce(context -> null)));
|
||||
var edit = flatEdit();
|
||||
assertThrows(NullPointerException.class, () -> place(graph, edit, ConfiguredSettings.none()));
|
||||
assertEquals(MemoryEdit.Status.CLOSED, edit.status());
|
||||
assertFalse(edit.committed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void conditionalStagesCascadeToDependentsWithoutAnyError() {
|
||||
var toggled = Stage.placement("test:cascade/toggled", Integer.class);
|
||||
var dependent = Stage.placement("test:cascade/dependent");
|
||||
var unrelated = Stage.placement("test:cascade/unrelated");
|
||||
var events = new ArrayList<String>();
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:cascade", stages -> {
|
||||
stages.define(toggled).when(Toggle.class).produce(context -> {
|
||||
events.add("toggled");
|
||||
return 1;
|
||||
});
|
||||
stages.define(dependent).requires(toggled).run(context -> events.add("dependent:" + context.output(toggled)));
|
||||
stages.define(unrelated).run(context -> events.add("unrelated"));
|
||||
}));
|
||||
|
||||
place(graph, flatEdit(), ConfiguredSettings.none());
|
||||
assertEquals(List.of("unrelated"), events);
|
||||
events.clear();
|
||||
place(graph, flatEdit(), ConfiguredSettings.placement(ResourceId.parse("test:placement"), new Toggle()));
|
||||
assertEquals(List.of("toggled", "dependent:1", "unrelated"), events);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConditionedStageReadsOnlyTheSettingsItIsConditionedOn() {
|
||||
var configured = new ArrayList<Object>();
|
||||
var refusals = new ArrayList<String>();
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:owner", stages -> {
|
||||
stages.define(Stage.placement("test:owner/toggled")).when(Toggle.class).run(context -> {
|
||||
configured.add(context.configured(Toggle.class).mostSpecific().orElseThrow());
|
||||
refusals.add(assertThrows(IllegalStateException.class, () -> context.configured(SnowSettings.class)).getMessage());
|
||||
});
|
||||
stages.define(Stage.placement("test:owner/plain")).run(context -> refusals.add(
|
||||
assertThrows(IllegalStateException.class, () -> context.configured(Toggle.class)).getMessage()));
|
||||
}));
|
||||
var toggle = new Toggle();
|
||||
|
||||
place(graph, flatEdit(), ConfiguredSettings.placement(ResourceId.parse("test:placement"), toggle));
|
||||
|
||||
assertEquals(List.of(toggle), configured);
|
||||
assertEquals(List.of(
|
||||
"Stage test:owner/plain read configured(Toggle) but is not conditioned on it; add when(Toggle.class) to its"
|
||||
+ " definition, or read other settings through settings()",
|
||||
"Stage test:owner/toggled read configured(SnowSettings) but is not conditioned on it; add when(SnowSettings.class)"
|
||||
+ " to its definition, or read other settings through settings()"), refusals);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aProducerThatRejectsTheAttemptMayReturnNull() {
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:reject", stages ->
|
||||
stages.define(Stage.placement("test:reject/height", Integer.class)).produce(context -> {
|
||||
context.reject("no ground");
|
||||
return null;
|
||||
})));
|
||||
var edit = flatEdit();
|
||||
|
||||
var outcome = place(graph, edit, ConfiguredSettings.none());
|
||||
assertEquals(PlacementOutcome.Status.REJECTED, outcome.status());
|
||||
assertEquals(Optional.of("no ground"), outcome.rejection());
|
||||
assertFalse(edit.committed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void placementTimesEachStageThatRanOnceAndABlockStageOncePerPass() {
|
||||
var prepare = Stage.placement("test:timed/prepare");
|
||||
var write = Stage.placementBlock("test:timed/write");
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:timed", stages -> {
|
||||
stages.define(prepare).run(context -> {});
|
||||
stages.define(write).requires(prepare).run(context -> {});
|
||||
stages.define(Stage.placement("test:timed/off")).when(Toggle.class).run(context -> {});
|
||||
}));
|
||||
var timed = new ArrayList<String>();
|
||||
|
||||
place(graph, flatEdit(), ConfiguredSettings.none(), (stage, nanos) -> {
|
||||
assertTrue(nanos >= 0);
|
||||
timed.add(stage.stage().id().toString());
|
||||
});
|
||||
|
||||
assertEquals(List.of("test:timed/prepare", "test:timed/write"), timed);
|
||||
}
|
||||
|
||||
@Test
|
||||
void skippedBlocksAreHiddenFromLaterStagesOfThePass() {
|
||||
var written = new ArrayList<Integer>();
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:skip", stages -> {
|
||||
var filter = Stage.placementBlock("test:skip/filter");
|
||||
stages.define(filter).run(context -> {
|
||||
if (context.block().position().x() == 0) context.skip();
|
||||
});
|
||||
stages.define(Stage.placementBlock("test:skip/write")).requires(filter).run(context -> written.add(context.block().position().x()));
|
||||
}));
|
||||
|
||||
place(graph, flatEdit(), ConfiguredSettings.none());
|
||||
assertEquals(List.of(1), written);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectionStopsTheAttemptAndCommitsNothing() {
|
||||
var events = new ArrayList<String>();
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:reject", stages -> {
|
||||
var write = Stage.placementBlock("test:reject/write");
|
||||
stages.define(write).run(context -> {
|
||||
events.add("write");
|
||||
context.access().set(new PlacedBlock(new BlockPosition(0, 10, 0), STONE, Optional.empty()));
|
||||
context.reject("blocked");
|
||||
context.reject("ignored");
|
||||
});
|
||||
stages.define(Stage.placement("test:reject/after")).requires(write).run(context -> events.add("after"));
|
||||
}));
|
||||
var edit = flatEdit();
|
||||
|
||||
var outcome = place(graph, edit, ConfiguredSettings.none());
|
||||
assertEquals(PlacementOutcome.Status.REJECTED, outcome.status());
|
||||
assertEquals(Optional.of("blocked"), outcome.rejection());
|
||||
assertEquals(List.of("write"), events);
|
||||
assertFalse(edit.committed());
|
||||
assertEquals(MemoryEdit.Status.CLOSED, edit.status());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stagesGetBufferedAccessWithoutTransactionOwnershipAndViewsExpire() {
|
||||
var retained = new ArrayList<com.volmit.placement.PlacementAccess>();
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:access", stages ->
|
||||
stages.define(Stage.placement("test:access/write")).run(context -> {
|
||||
assertFalse(context.access() instanceof PlacementEdit);
|
||||
assertThrows(IllegalStateException.class, () -> ((BlockStageContext) context).block());
|
||||
context.access().set(new PlacedBlock(new BlockPosition(1, 10, 1), STONE, Optional.empty()));
|
||||
context.access().set(2, 10, 1, STONE);
|
||||
assertEquals(STONE, context.access().get(1, 10, 1));
|
||||
var outside = context.access().bounds().maxX();
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> context.access().set(outside, 10, 1, STONE));
|
||||
retained.add(context.access());
|
||||
})));
|
||||
var edit = flatEdit();
|
||||
|
||||
assertTrue(place(graph, edit, ConfiguredSettings.none()).isPlaced());
|
||||
assertEquals(STONE, edit.publishedAt(1, 10, 1));
|
||||
assertEquals(STONE, edit.publishedAt(2, 10, 1));
|
||||
assertThrows(IllegalStateException.class, () -> retained.getFirst().get(1, 10, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onePlacementInvocationMakesItsMantleViewsOnce() {
|
||||
var key = new MantleKey<>(ResourceId.parse("test:views/depth"),Integer.class);
|
||||
var views = new ArrayList<Object>();
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:views", stages ->
|
||||
stages.define(Stage.placement("test:views/read")).run(context -> {
|
||||
var mantle = context.access().mantle();
|
||||
views.add(mantle);
|
||||
views.add(context.access().mantle());
|
||||
views.add(mantle.layer(key));
|
||||
views.add(mantle.layer(key));
|
||||
views.add(mantle.blocks());
|
||||
views.add(mantle.blocks());
|
||||
})));
|
||||
var terrain = new TestTerrain((x, z) -> 5);
|
||||
var edit = new MemoryEdit(terrain, new MemoryMantle().within(terrain.bounds()));
|
||||
|
||||
assertTrue(place(graph, edit, ConfiguredSettings.none()).isPlaced());
|
||||
assertSame(views.get(0), views.get(1));
|
||||
assertSame(views.get(2), views.get(3));
|
||||
assertSame(views.get(4), views.get(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failuresDiscardBufferedWrites() {
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("test:fail", stages ->
|
||||
stages.define(Stage.placement("test:fail/work")).run(context -> {
|
||||
context.access().set(new PlacedBlock(new BlockPosition(1, 10, 1), STONE, Optional.empty()));
|
||||
throw new IllegalStateException("boom");
|
||||
})));
|
||||
var edit = flatEdit();
|
||||
assertThrows(IllegalStateException.class, () -> place(graph, edit, ConfiguredSettings.none()));
|
||||
assertFalse(edit.committed());
|
||||
assertEquals(MemoryEdit.Status.CLOSED, edit.status());
|
||||
}
|
||||
|
||||
@Test
|
||||
void runnersOnlyAcceptTheirOwnPipeline() {
|
||||
var empty = resolve(Pipeline.CHUNK);
|
||||
assertThrows(IllegalArgumentException.class, () -> new PlacementRunner(empty));
|
||||
assertThrows(IllegalArgumentException.class, () -> new ChunkRunner(resolve(Pipeline.PLACEMENT)));
|
||||
assertThrows(IllegalArgumentException.class, () -> new MantleRunner(empty));
|
||||
assertThrows(IllegalArgumentException.class, () -> new ChunkRunner(resolve(Pipeline.MANTLE)));
|
||||
assertTrue(empty.describe().contains("CHUNK pipeline: 0 stages, 0 block passes"));
|
||||
}
|
||||
|
||||
static final class Counter {
|
||||
int count;
|
||||
}
|
||||
|
||||
@Test
|
||||
void reachIsDeclaredPerStageAndCollectedPerPipelineAndLayer() {
|
||||
var depth = new MantleKey<>(ResourceId.parse("test:reach/depth"), Integer.class);
|
||||
var marks = new MantleKey<>(ResourceId.parse("test:reach/marks"), String.class);
|
||||
var carve = Stage.mantle("test:reach/carve");
|
||||
var mark = Stage.mantle("test:reach/mark");
|
||||
var plain = Stage.mantle("test:reach/plain");
|
||||
var paint = Stage.placementBlock("test:reach/paint");
|
||||
var reach = module("test:reach", stages -> {
|
||||
stages.define(carve).reach(24).writesMantle(depth).run(context -> {});
|
||||
stages.define(mark).reach(8).writesMantle(depth, marks).run(context -> {});
|
||||
stages.define(plain).run(context -> {});
|
||||
stages.define(paint).reach(2).run(context -> {});
|
||||
});
|
||||
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(reach, depth, marks))), Map.of(), Set.of(), Set.of());
|
||||
|
||||
assertEquals(new StageReach(24, List.of(depth)), loaded.mantle().stages().getFirst().reach());
|
||||
assertEquals(StageReach.NONE, loaded.mantle().stages().get(2).reach(), "an undeclared reach is 0 with no layers");
|
||||
assertEquals(new PipelineReach(24, Map.of(depth.id(), 24, marks.id(), 8)), loaded.mantle().reach());
|
||||
assertEquals(new PipelineReach(2, Map.of()), loaded.placement().reach());
|
||||
assertEquals(new PipelineReach(0, Map.of()), loaded.chunk().reach());
|
||||
assertTrue(loaded.mantle().describe().contains(" reach 24 blocks, writes mantle test:reach/depth\n"), loaded.mantle().describe());
|
||||
assertTrue(loaded.mantle().describe().contains(" reach 8 blocks, writes mantle test:reach/depth, test:reach/marks\n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMantleStageWorksOutItsReachWhenThePackLoads() {
|
||||
var carve = Stage.mantle("test:reach/carve");
|
||||
var mark = Stage.mantle("test:reach/mark");
|
||||
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages -> {
|
||||
stages.define(carve).reach(settings -> settings.declared(Toggle.class).isEmpty() ? 4 : 40).run(context -> {});
|
||||
stages.define(mark).reach(2).run(context -> {});
|
||||
}))), Map.of(), Set.of(), Set.of());
|
||||
var computed = loaded.mantle().stages().getFirst();
|
||||
var toggled = new DeclaredSettings(new Entry<>(Level.DIMENSION, ResourceId.parse("pack:dimension/main"), new Toggle()));
|
||||
|
||||
assertEquals(4, computed.reachBlocks(DeclaredSettings.NONE));
|
||||
assertEquals(40, computed.reachBlocks(toggled));
|
||||
assertEquals(2, loaded.mantle().stages().get(1).reachBlocks(toggled), "a declared number is the same for every pack");
|
||||
assertTrue(loaded.mantle().describe().contains(" reach worked out when the pack loads\n"), loaded.mantle().describe());
|
||||
var pipeline = assertThrows(IllegalStateException.class, () -> loaded.mantle().reach());
|
||||
assertEquals("Stage test:reach/carve of module test:reach works out its reach when the pack loads;"
|
||||
+ " ask each mantle stage with ResolvedStage.reachBlocks(settings)", pipeline.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkedOutReachIsNeverNegativeAndIsDeclaredOnce() {
|
||||
var negative = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages ->
|
||||
stages.define(Stage.mantle("test:reach/carve")).reach(settings -> -1).run(context -> {})))), Map.of(), Set.of(), Set.of());
|
||||
var failure = assertThrows(IllegalStateException.class, () -> negative.mantle().stages().getFirst().reachBlocks(DeclaredSettings.NONE));
|
||||
assertEquals("Stage test:reach/carve of module test:reach worked out a negative reach of -1 blocks for this pack", failure.getMessage());
|
||||
|
||||
var twice = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.MANTLE, module("test:reach", stages ->
|
||||
stages.define(Stage.mantle("test:reach/carve")).reach(2).reach(settings -> 1).run(context -> {}))));
|
||||
assertEquals("Stage test:reach/carve (module test:reach) already declares a reach of 2 blocks", twice.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theMantleRunnerRunsOneStageWhereItAndWhatItRequiresAreActive() {
|
||||
var toggled = Stage.mantle("test:owner/toggled");
|
||||
var follower = Stage.mantle("test:owner/follower");
|
||||
var ran = new ArrayList<String>();
|
||||
var graph = resolve(Pipeline.MANTLE, module("test:owner", stages -> {
|
||||
stages.define(toggled).when(Toggle.class).run(context -> ran.add("toggled"));
|
||||
stages.define(follower).requires(toggled).run(context -> ran.add("follower"));
|
||||
}));
|
||||
var runner = new MantleRunner(graph);
|
||||
var toggle = new Entry<>(Level.BIOME, ResourceId.parse("pack:biome/plains"), new Toggle());
|
||||
var nowhere = TestContexts.mantle(0, 0, ColumnSettings.NONE, null);
|
||||
var oneColumn = TestContexts.mantle(0, 0, new ColumnSettings((x, z) -> x == 15 && z == 0 ? List.of(toggle) : List.of()), null);
|
||||
|
||||
var timed = new ArrayList<String>();
|
||||
StageTimings timings = (stage, nanos) -> timed.add(stage.stage().id().toString());
|
||||
|
||||
runner.generate(follower, nowhere, TestContexts.SEED, timings);
|
||||
assertEquals(List.of(), ran, "a stage whose requirement is inactive in the chunk is inactive too");
|
||||
runner.generate(follower, oneColumn, TestContexts.SEED, timings);
|
||||
assertEquals(List.of("follower"), ran, "only the asked stage runs; its requirement ran in its own pass");
|
||||
runner.generate(toggled, oneColumn, TestContexts.SEED, timings);
|
||||
assertEquals(List.of("follower", "toggled"), ran);
|
||||
assertEquals(List.of("test:owner/follower", "test:owner/toggled"), timed, "only stages that ran are timed");
|
||||
var foreign = assertThrows(IllegalArgumentException.class,
|
||||
() -> runner.generate(Stage.mantle("test:owner/absent"), nowhere, TestContexts.SEED, StageTimings.NONE));
|
||||
assertEquals("Stage test:owner/absent is not a stage of this mantle graph", foreign.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reachMustBeValidAndNameRegisteredLayers() {
|
||||
var depth = new MantleKey<>(ResourceId.parse("test:reach/depth"), Integer.class);
|
||||
var carve = Stage.mantle("test:reach/carve");
|
||||
|
||||
var negative = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.MANTLE,
|
||||
module("test:reach", stages -> stages.define(carve).reach(-1).run(context -> {}))));
|
||||
assertEquals("Stage test:reach/carve (module test:reach) declares a negative reach of -1 blocks", negative.getMessage());
|
||||
var twice = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.MANTLE,
|
||||
module("test:reach", stages -> stages.define(carve).reach(1).reach(2).run(context -> {}))));
|
||||
assertEquals("Stage test:reach/carve (module test:reach) already declares a reach of 1 blocks", twice.getMessage());
|
||||
assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.MANTLE,
|
||||
module("test:reach", stages -> stages.define(carve).writesMantle(depth, depth).run(context -> {}))));
|
||||
|
||||
var unregistered = assertThrows(ModuleLoadException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(
|
||||
module("test:reach", stages -> stages.define(carve).writesMantle(depth).run(context -> {})))), Map.of(), Set.of(), Set.of()));
|
||||
assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth, which no module registers;"
|
||||
+ " its owner registers it with FeatureRegistry.registerMantle", unregistered.getMessage());
|
||||
|
||||
var asText = new MantleKey<>(ResourceId.parse("test:reach/depth"), String.class);
|
||||
var mismatch = assertThrows(ModuleLoadException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(
|
||||
module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Map.of(), Set.of(), Set.of()));
|
||||
assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth as java.lang.String,"
|
||||
+ " but it is registered as java.lang.Integer", mismatch.getMessage());
|
||||
}
|
||||
|
||||
/** {@code module}, also registering {@code layers}. */
|
||||
private static IrisModule withMantle(IrisModule module, MantleKey<?>... layers) {
|
||||
return new IrisModule() {
|
||||
public ModuleInfo info() { return module.info(); }
|
||||
public void setup(ModuleSetup setup) {
|
||||
module.setup(setup);
|
||||
for (var layer : layers) registerLayer(setup.registry(), layer);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static <T> void registerLayer(FeatureRegistry registry, MantleKey<T> layer) {
|
||||
registry.registerMantle(layer, MantleLifetime.GENERATION, codec(layer));
|
||||
}
|
||||
|
||||
private static <T> StorageCodec<T> codec(MantleKey<T> layer) {
|
||||
return new StorageCodec<>() {
|
||||
public int version() { return 0; }
|
||||
public void write(java.io.DataOutput output, T value) {}
|
||||
public T read(java.io.DataInput input, int storedVersion) { throw new UnsupportedOperationException(); }
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.geometry.BlockBox;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.object.GeneratedObject;
|
||||
import com.volmit.object.ObjectBlock;
|
||||
import com.volmit.placement.PlacementRequest;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.stage.Pipeline;
|
||||
import com.volmit.stage.Stage;
|
||||
import com.volmit.stage.StageContext;
|
||||
import com.volmit.stage.StageGraph;
|
||||
import com.volmit.support.MemoryEdit;
|
||||
import com.volmit.support.TestContexts;
|
||||
import com.volmit.support.TestSetups;
|
||||
import com.volmit.support.TestTerrain;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.IntStream;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class StageStreamsTest {
|
||||
private static final BlockState STONE = new BlockState("minecraft:stone");
|
||||
private static final int BLOCKS = 3;
|
||||
private static final int BOUND = 1_000_000;
|
||||
private static final int INVOCATION_DRAWS = 4;
|
||||
private static final int NOISY_DRAWS = 37;
|
||||
|
||||
/** Every draw each stage made, by stage id, in the order it made them. */
|
||||
private final Map<String, List<Long>> draws = new LinkedHashMap<>();
|
||||
|
||||
private static IrisModule module(String id, Consumer<StageGraph> install) {
|
||||
return new IrisModule() {
|
||||
public ModuleInfo info() { return ModuleInfo.of(id, "Test module " + id, "1"); }
|
||||
public void setup(ModuleSetup setup) { install.accept(setup.stages()); }
|
||||
};
|
||||
}
|
||||
|
||||
private static ResolvedGraph resolve(Pipeline pipeline, IrisModule... modules) {
|
||||
return TestSetups.stages(modules).resolve(pipeline);
|
||||
}
|
||||
|
||||
private static PlacementRequest request() {
|
||||
var blocks = IntStream.range(0, BLOCKS).mapToObj(x -> new ObjectBlock(new BlockPosition(x, 0, 0), STONE)).toList();
|
||||
var object = new GeneratedObject(new BlockBox(0, 0, 0, BLOCKS, 1, 1), new BlockPosition(0, 0, 0), blocks, List.of());
|
||||
return new PlacementRequest(object,new BlockPosition(0, 10, 0));
|
||||
}
|
||||
|
||||
private Map<String, List<Long>> place(ResolvedGraph graph, long invocationSeed) {
|
||||
draws.clear();
|
||||
var outcome = new PlacementRunner(graph).place(request(), new MemoryEdit(new TestTerrain((x, z) -> 5)),
|
||||
TestContexts.placement(), invocationSeed, ConfiguredSettings.none(), StageTimings.NONE);
|
||||
assertTrue(outcome.isPlaced());
|
||||
return Map.copyOf(draws);
|
||||
}
|
||||
|
||||
private void draw(String stage, StageContext context, int count) {
|
||||
var drawn = draws.computeIfAbsent(stage, ignored -> new ArrayList<>());
|
||||
for (int index = 0; index < count; index++) drawn.add((long) context.random().nextInt(BOUND));
|
||||
}
|
||||
|
||||
/** One invocation stage and one block stage that draw from their streams. */
|
||||
private IrisModule drawingModule(String moduleId, int invocationDraws, int drawsPerBlock) {
|
||||
var pick = moduleId + "/pick";
|
||||
var scatter = moduleId + "/scatter";
|
||||
return module(moduleId, graph -> {
|
||||
graph.define(Stage.placement(pick)).run(context -> draw(pick, context, invocationDraws));
|
||||
graph.define(Stage.placementBlock(scatter)).run(context -> draw(scatter, context, drawsPerBlock));
|
||||
});
|
||||
}
|
||||
|
||||
private static List<Long> firstDraws(long invocationSeed, String stageId, int count) {
|
||||
var stream = StageStreams.stream(invocationSeed, ResourceId.parse(stageId));
|
||||
return IntStream.range(0, count).mapToObj(ignored -> (long) stream.nextInt(BOUND)).toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void insertingAModuleThatDrawsLeavesOtherStagesDrawsUnchanged() {
|
||||
var first = drawingModule("a:mod", INVOCATION_DRAWS, 1);
|
||||
var inserted = drawingModule("b:mod", NOISY_DRAWS, NOISY_DRAWS);
|
||||
var last = drawingModule("c:mod", INVOCATION_DRAWS, 1);
|
||||
|
||||
var without = place(resolve(Pipeline.PLACEMENT, first, last), TestContexts.SEED);
|
||||
var with = resolve(Pipeline.PLACEMENT, first, inserted, last);
|
||||
assertEquals(List.of("a:mod/pick", "b:mod/pick", "c:mod/pick", "a:mod/scatter", "b:mod/scatter", "c:mod/scatter"),
|
||||
with.stages().stream().map(stage -> stage.stage().id().toString()).toList());
|
||||
assertEquals(1, with.blockPasses().size(), "the inserted block stage interleaves with the others per block");
|
||||
var withInserted = place(with, TestContexts.SEED);
|
||||
|
||||
for (var stage : List.of("a:mod/pick", "a:mod/scatter", "c:mod/pick", "c:mod/scatter")) {
|
||||
assertEquals(without.get(stage), withInserted.get(stage), stage);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameStageInTheSameInvocationDrawsTheSameSequenceEveryRun() {
|
||||
var graph = resolve(Pipeline.PLACEMENT, drawingModule("a:mod", INVOCATION_DRAWS, 1));
|
||||
|
||||
assertEquals(place(graph, TestContexts.SEED), place(graph, TestContexts.SEED));
|
||||
assertNotEquals(place(graph, TestContexts.SEED), place(graph, TestContexts.SEED + 1));
|
||||
assertEquals(firstDraws(TestContexts.SEED, "a:mod/pick", INVOCATION_DRAWS), place(graph, TestContexts.SEED).get("a:mod/pick"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blockStageDrawsOneStreamAcrossTheBlocksOfItsPass() {
|
||||
var graph = resolve(Pipeline.PLACEMENT, drawingModule("a:mod", 0, 2));
|
||||
|
||||
assertEquals(firstDraws(TestContexts.SEED, "a:mod/scatter", 2 * BLOCKS), place(graph, TestContexts.SEED).get("a:mod/scatter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void differentStagesDrawFromDifferentStreams() {
|
||||
var graph = resolve(Pipeline.PLACEMENT, drawingModule("a:mod", INVOCATION_DRAWS, 0), drawingModule("c:mod", INVOCATION_DRAWS, 0));
|
||||
var drawn = place(graph, TestContexts.SEED);
|
||||
|
||||
assertNotEquals(drawn.get("a:mod/pick"), drawn.get("c:mod/pick"));
|
||||
assertNotEquals(StageStreams.idHash(ResourceId.parse("a:mod/pick")), StageStreams.idHash(ResourceId.parse("c:mod/pick")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chunkStagesDrawFromTheirOwnStreams() {
|
||||
var drawn = new ArrayList<Long>();
|
||||
var graph = resolve(Pipeline.CHUNK, module("a:mod", stages -> stages.define(Stage.chunk("a:mod/ores"))
|
||||
.run(context -> drawn.add((long) context.random().nextInt(BOUND)))));
|
||||
|
||||
new ChunkRunner(graph).generate(TestContexts.generation(null), TestContexts.SEED, StageTimings.NONE);
|
||||
|
||||
assertEquals(firstDraws(TestContexts.SEED, "a:mod/ores", 1), drawn);
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamIsOnlyAvailableWhileItsStageRuns() {
|
||||
var retained = new ArrayList<StageContext>();
|
||||
var graph = resolve(Pipeline.PLACEMENT, module("a:mod", stages -> stages.define(Stage.placement("a:mod/keep")).run(retained::add)));
|
||||
place(graph, TestContexts.SEED);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> retained.getFirst().random());
|
||||
}
|
||||
|
||||
/** Pins the documented derivation with values computed outside Java from its specification, so a
|
||||
* change to the derivation fails here instead of silently changing worlds. {@code WorldRandomTest}
|
||||
* pins the generator itself.
|
||||
*/
|
||||
@Test
|
||||
void derivationMatchesItsSpecification() {
|
||||
var stage = ResourceId.parse("iris:stilt/fill");
|
||||
assertEquals(0xd11cde74d6a9508aL, StageStreams.idHash(stage), "64-bit FNV-1a of iris:stilt/fill");
|
||||
|
||||
assertEquals(-3593301659158072667L, StageStreams.streamSeed(TestContexts.SEED, StageStreams.idHash(stage)));
|
||||
|
||||
var stream = StageStreams.stream(TestContexts.SEED, stage);
|
||||
assertEquals(2676194909693269196L, stream.nextLong());
|
||||
assertEquals(1649978757, stream.nextInt());
|
||||
assertEquals(868252, stream.nextInt(BOUND));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.support.FakePlatformApi;
|
||||
import com.volmit.support.TestModuleJar;
|
||||
import example.builtin.CarveModule;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import static com.volmit.support.TestModuleJar.module;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ToolingPartCheckTest {
|
||||
private static final String BUKKIT_PART = "pack.tools.bukkit.StudioPart";
|
||||
private static final String MODDED_PART = "pack.tools.modded.ModdedPart";
|
||||
private static final String BUKKIT_PART_DECLARATION = "bukkit=" + BUKKIT_PART;
|
||||
private static final String GENERATION_CLASS = "pack.model.Thing";
|
||||
private static final String PART_PACKAGE_NOTICE = "Generation code cannot use the bukkit part; move the call into the part.";
|
||||
|
||||
@TempDir
|
||||
Path pack;
|
||||
@TempDir
|
||||
Path work;
|
||||
|
||||
private FakePlatformApi platform;
|
||||
|
||||
@AfterEach
|
||||
void closePlatform() {
|
||||
if (platform != null) platform.close();
|
||||
}
|
||||
|
||||
private PlatformApi bukkitApi(String... classNames) {
|
||||
platform = FakePlatformApi.of(work, classNames);
|
||||
return platform.asApiOf(ToolingPlatform.BUKKIT);
|
||||
}
|
||||
|
||||
private static String classWith(String className, String body) {
|
||||
int dot = className.lastIndexOf('.');
|
||||
return "package " + className.substring(0, dot) + "; public final class " + className.substring(dot + 1) + " { " + body + " }";
|
||||
}
|
||||
|
||||
private static String using(String className) {
|
||||
return "static final Class<?> " + className.replace('.', '_') + " = " + className + ".class; ";
|
||||
}
|
||||
|
||||
private static TestModuleJar jar(String generationMembers) {
|
||||
return module("pack.User", "user:core", generationMembers, "")
|
||||
.source(GENERATION_CLASS, classWith(GENERATION_CLASS, ""));
|
||||
}
|
||||
|
||||
private PackModules load(TestModuleJar jar, Optional<PlatformApi> runningPlatform) {
|
||||
jar.writeInto(pack, "user.jar");
|
||||
return PackModules.load(pack, List.of(), List.of(), work, PackModules.DEFAULT_LOGGER, runningPlatform);
|
||||
}
|
||||
|
||||
private String loadFailure(TestModuleJar jar, Optional<PlatformApi> runningPlatform) {
|
||||
return assertThrows(ModuleLoadException.class, () -> load(jar, runningPlatform)).getMessage();
|
||||
}
|
||||
|
||||
@Test
|
||||
void partOfTheRunningPlatformMayUseItsPackagesGenerationClassesAndThePlatformApi() {
|
||||
var api = bukkitApi("org.bukkit.Bukkit", "io.papermc.paper.Paper");
|
||||
var jar = jar("")
|
||||
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("org.bukkit.Bukkit") + using("io.papermc.paper.Paper")
|
||||
+ using("pack.tools.bukkit.deep.Helper") + using(GENERATION_CLASS)))
|
||||
.source("pack.tools.bukkit.deep.Helper", classWith("pack.tools.bukkit.deep.Helper", ""))
|
||||
.compileAgainst(platform.jar())
|
||||
.toolingParts(BUKKIT_PART_DECLARATION);
|
||||
|
||||
try (var modules = load(jar, Optional.of(api))) {
|
||||
assertEquals(List.of(BUKKIT_PART_DECLARATION), modules.toolingParts().stream().map(ToolingPart::declaration).toList());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void generationClassUsingAPartClassFailsNamingBothClassesAndTheMove() {
|
||||
var api = bukkitApi("org.bukkit.Bukkit");
|
||||
var jar = jar("static Object leak() { return new " + BUKKIT_PART + "(); }")
|
||||
.source(BUKKIT_PART, classWith(BUKKIT_PART, "public StudioPart() {}"))
|
||||
.toolingParts(BUKKIT_PART_DECLARATION);
|
||||
|
||||
var message = loadFailure(jar, Optional.of(api));
|
||||
|
||||
assertTrue(message.contains("modules/user.jar"), message);
|
||||
assertTrue(message.contains("pack.User -> " + BUKKIT_PART), message);
|
||||
assertTrue(message.contains(PART_PACKAGE_NOTICE), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generationClassUsingAPartClassFailsWhateverPlatformTheHostRunsOn() {
|
||||
var jar = jar("static Object leak() { return new " + MODDED_PART + "(); }")
|
||||
.source(MODDED_PART, classWith(MODDED_PART, "public ModdedPart() {}"))
|
||||
.toolingParts("modded=" + MODDED_PART);
|
||||
|
||||
var message = loadFailure(jar, Optional.empty());
|
||||
|
||||
assertTrue(message.contains("pack.User -> " + MODDED_PART), message);
|
||||
assertTrue(message.contains("Generation code cannot use the modded part; move the call into the part."), message);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"org.bukkit.craftbukkit.CraftServer", "net.minecraft.MinecraftServer", "com.mojang.Brigadier",
|
||||
"art.arcane.iris.Engine", "art.arcane.iris.engine.Deep"})
|
||||
void partClassUsingADeniedPackageFailsNamingBothClasses(String denied) {
|
||||
var api = bukkitApi("org.bukkit.craftbukkit.CraftServer", "net.minecraft.MinecraftServer", "com.mojang.Brigadier",
|
||||
"art.arcane.iris.Engine", "art.arcane.iris.engine.Deep");
|
||||
var jar = jar("")
|
||||
.source(BUKKIT_PART, classWith(BUKKIT_PART, using(denied)))
|
||||
.compileAgainst(platform.jar())
|
||||
.toolingParts(BUKKIT_PART_DECLARATION);
|
||||
|
||||
var message = loadFailure(jar, Optional.of(api));
|
||||
|
||||
assertTrue(message.contains("bukkit part classes that use classes parts cannot see"), message);
|
||||
assertTrue(message.contains(BUKKIT_PART + " -> " + denied), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void partClassUsingTheHostSideOfIrisApiFails() {
|
||||
var api = bukkitApi("org.bukkit.Bukkit");
|
||||
var jar = jar("")
|
||||
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("com.volmit.host.ModuleHost")))
|
||||
.compileAgainstHostOf(ModuleHost.class)
|
||||
.toolingParts(BUKKIT_PART_DECLARATION);
|
||||
|
||||
var message = loadFailure(jar, Optional.of(api));
|
||||
|
||||
assertTrue(message.contains(BUKKIT_PART + " -> com.volmit.host.ModuleHost"), message);
|
||||
}
|
||||
|
||||
/** A platform that denies all of {@code example}, where the built-in module classes of the tests live. */
|
||||
private PlatformApi platformDenyingExample() {
|
||||
platform = FakePlatformApi.of(work, "org.bukkit.Bukkit");
|
||||
var denied = List.of(new PackageName("example"));
|
||||
return platform.asApiOf(new ToolingPlatform("bukkit", List.of(new PackageName("org.bukkit")), denied));
|
||||
}
|
||||
|
||||
private TestModuleJar partUsingTheBuiltInModule() {
|
||||
return jar("")
|
||||
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("example.builtin.CarveModule")))
|
||||
.compileAgainstHostOf(CarveModule.class)
|
||||
.toolingParts(BUKKIT_PART_DECLARATION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniedPackageStaysDeniedWhenTheHostDoesNotExposeIt() {
|
||||
var message = loadFailure(partUsingTheBuiltInModule(), Optional.of(platformDenyingExample()));
|
||||
|
||||
assertTrue(message.contains(BUKKIT_PART + " -> example.builtin.CarveModule"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniedPackageIsUsableWhenTheHostExposesTheClassToModules() {
|
||||
partUsingTheBuiltInModule().writeInto(pack, "user.jar");
|
||||
var exposed = List.of(CarveModule.class.getPackageName());
|
||||
|
||||
try (var modules = PackModules.load(pack, exposed, List.of(), work, PackModules.DEFAULT_LOGGER, Optional.of(platformDenyingExample()))) {
|
||||
assertEquals(1, modules.toolingParts().size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void platformApiClassThePlatformLacksFailsNamingBothClasses() {
|
||||
var buildApi = FakePlatformApi.of(work, "org.bukkit.Bukkit", "org.bukkit.entity.Player");
|
||||
var jar = jar("")
|
||||
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("org.bukkit.entity.Player")))
|
||||
.compileAgainst(buildApi.jar())
|
||||
.toolingParts(BUKKIT_PART_DECLARATION);
|
||||
buildApi.close();
|
||||
|
||||
var message = loadFailure(jar, Optional.of(bukkitApi("org.bukkit.Bukkit")));
|
||||
|
||||
assertTrue(message.contains("bukkit API classes this server does not have"), message);
|
||||
assertTrue(message.contains(BUKKIT_PART + " -> org.bukkit.entity.Player"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void partClassUsingAClassOfAnotherPartFails() {
|
||||
var api = bukkitApi("org.bukkit.Bukkit");
|
||||
var otherPart = "pack.other.bukkit.ImportPart";
|
||||
var jar = jar("")
|
||||
.source(BUKKIT_PART, classWith(BUKKIT_PART, using(otherPart)))
|
||||
.source(otherPart, classWith(otherPart, ""))
|
||||
.toolingParts(BUKKIT_PART_DECLARATION + " bukkit=" + otherPart);
|
||||
|
||||
var message = loadFailure(jar, Optional.of(api));
|
||||
|
||||
assertTrue(message.contains("bukkit part classes that use classes of another part"), message);
|
||||
assertTrue(message.contains(BUKKIT_PART + " -> " + otherPart), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void partOfAnotherPlatformIsSkippedUnread() {
|
||||
var api = bukkitApi("org.bukkit.Bukkit");
|
||||
var jar = jar("")
|
||||
.source(MODDED_PART, classWith(MODDED_PART, using("org.junit.jupiter.api.Test") + using("net.minecraft.MinecraftServer")))
|
||||
.compileAgainstHostOf(org.junit.jupiter.api.Test.class)
|
||||
.source("net.minecraft.MinecraftServer", classWith("net.minecraft.MinecraftServer", ""))
|
||||
.toolingParts("modded=" + MODDED_PART);
|
||||
|
||||
try (var modules = load(jar, Optional.of(api))) {
|
||||
assertEquals(List.of(), modules.toolingParts());
|
||||
assertEquals(List.of(), modules.missingClasses());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void partsAreSkippedWhenTheHostRunsOnNoPlatform() {
|
||||
var jar = jar("")
|
||||
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("org.junit.jupiter.api.Test")))
|
||||
.compileAgainstHostOf(org.junit.jupiter.api.Test.class)
|
||||
.toolingParts(BUKKIT_PART_DECLARATION);
|
||||
|
||||
try (var modules = load(jar, Optional.empty())) {
|
||||
assertEquals(List.of(), modules.toolingParts());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameClassOutsideAPartIsStillCheckedAsGenerationCode() {
|
||||
var api = bukkitApi("org.bukkit.Bukkit");
|
||||
var jar = jar(using("org.junit.jupiter.api.Test"))
|
||||
.compileAgainstHostOf(org.junit.jupiter.api.Test.class)
|
||||
.source(MODDED_PART, classWith(MODDED_PART, ""))
|
||||
.toolingParts("modded=" + MODDED_PART);
|
||||
|
||||
var message = loadFailure(jar, Optional.of(api));
|
||||
|
||||
assertTrue(message.contains("pack.User -> org.junit.jupiter.api.Test"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void partClassUsingAHiddenClassFailsLikeGenerationCode() {
|
||||
var api = bukkitApi("org.bukkit.Bukkit");
|
||||
var jar = jar("")
|
||||
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("org.junit.jupiter.api.Test")))
|
||||
.compileAgainstHostOf(org.junit.jupiter.api.Test.class)
|
||||
.toolingParts(BUKKIT_PART_DECLARATION);
|
||||
|
||||
var message = loadFailure(jar, Optional.of(api));
|
||||
|
||||
assertTrue(message.contains("hidden from modules"), message);
|
||||
assertTrue(message.contains(BUKKIT_PART + " -> org.junit.jupiter.api.Test"), message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.support.FakePlatformApi;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import static com.volmit.support.TestModuleJar.module;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ToolingPartLoaderTest {
|
||||
private static final String PART = "pack.tools.bukkit.StudioPart";
|
||||
private static final String PART_HELPER = "pack.tools.bukkit.deep.Helper";
|
||||
private static final String GENERATION_CLASS = "pack.model.Thing";
|
||||
private static final String PLATFORM_CLASS = "org.bukkit.Bukkit";
|
||||
|
||||
@TempDir
|
||||
Path pack;
|
||||
@TempDir
|
||||
Path work;
|
||||
|
||||
private FakePlatformApi platform;
|
||||
private PackModules modules;
|
||||
|
||||
@BeforeEach
|
||||
void loadPackWithABukkitPart() {
|
||||
platform = FakePlatformApi.of(work, PLATFORM_CLASS, "org.bukkit.craftbukkit.CraftServer", "net.minecraft.MinecraftServer",
|
||||
"com.mojang.Brigadier", "art.arcane.iris.Engine");
|
||||
module("pack.User", "user:core", "", "")
|
||||
.source(GENERATION_CLASS, "package pack.model; public final class Thing {}")
|
||||
.source(PART, """
|
||||
package pack.tools.bukkit;
|
||||
public final class StudioPart {
|
||||
public static Class<?> thing() { return pack.model.Thing.class; }
|
||||
public static Class<?> platform() { return org.bukkit.Bukkit.class; }
|
||||
public static Class<?> helper() { return pack.tools.bukkit.deep.Helper.class; }
|
||||
}
|
||||
""")
|
||||
.source(PART_HELPER, "package pack.tools.bukkit.deep; public final class Helper {}")
|
||||
.compileAgainst(platform.jar())
|
||||
.toolingParts("bukkit=" + PART)
|
||||
.writeInto(pack, "user.jar");
|
||||
modules = PackModules.load(pack, List.of(), List.of(), work, PackModules.DEFAULT_LOGGER,
|
||||
Optional.of(platform.asApiOf(ToolingPlatform.BUKKIT)));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
modules.close();
|
||||
platform.close();
|
||||
}
|
||||
|
||||
private ClassLoader packLoader() {
|
||||
return modules.modules().getFirst().module().getClass().getClassLoader();
|
||||
}
|
||||
|
||||
private ToolingPartLoader openThePart() {
|
||||
return modules.openToolingPart(modules.toolingParts().getFirst());
|
||||
}
|
||||
|
||||
private static Class<?> call(Class<?> type, String method) throws ReflectiveOperationException {
|
||||
return (Class<?>) type.getMethod(method).invoke(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void definesTheEntryClassAndTheRestOfThePartItselfFromTheSameJarCopy() throws Exception {
|
||||
try (var loader = openThePart()) {
|
||||
var entry = loader.loadEntryClass();
|
||||
var helper = call(entry, "helper");
|
||||
|
||||
assertEquals(PART, entry.getName());
|
||||
assertNotSame(packLoader(), entry.getClassLoader());
|
||||
assertSame(entry.getClassLoader(), helper.getClassLoader());
|
||||
assertNotSame(packLoader().loadClass(PART), entry);
|
||||
assertEquals(modules.toolingParts().getFirst().jar().toUri().toURL(), entry.getProtectionDomain().getCodeSource().getLocation());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void childOfThePackLoader() throws Exception {
|
||||
try (var loader = openThePart()) {
|
||||
assertSame(packLoader(), loader.loadEntryClass().getClassLoader().getParent());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void delegatesPlatformPackagesToThePlatformLoader() throws Exception {
|
||||
try (var loader = openThePart()) {
|
||||
var fromPart = call(loader.loadEntryClass(), "platform");
|
||||
|
||||
assertSame(platform.classes().loadClass(PLATFORM_CLASS), fromPart);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsTheClassObjectsTheModuleRegisteredForGenerationClasses() throws Exception {
|
||||
try (var loader = openThePart()) {
|
||||
var fromPart = call(loader.loadEntryClass(), "thing");
|
||||
|
||||
assertSame(packLoader().loadClass(GENERATION_CLASS), fromPart);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"org.bukkit.craftbukkit.CraftServer", "net.minecraft.MinecraftServer", "com.mojang.Brigadier",
|
||||
"art.arcane.iris.Engine", "com.volmit.host.ModuleHost"})
|
||||
void refusesWhatAPartMustNotSee(String denied) {
|
||||
try (var loader = openThePart()) {
|
||||
var partLoader = loader.loadEntryClass().getClassLoader();
|
||||
|
||||
assertThrows(ClassNotFoundException.class, () -> partLoader.loadClass(denied));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingItLeavesThePackLoaderAndThePlatformOpen() throws Exception {
|
||||
var loader = openThePart();
|
||||
var partLoader = loader.loadEntryClass().getClassLoader();
|
||||
|
||||
loader.close();
|
||||
|
||||
assertSame(packLoader().loadClass(GENERATION_CLASS), packLoader().loadClass(GENERATION_CLASS));
|
||||
assertNotNull(platform.classes().loadClass(PLATFORM_CLASS));
|
||||
assertThrows(ClassNotFoundException.class, () -> partLoader.loadClass(PART_HELPER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void entryClassThatCannotBeLoadedIsReportedNamingTheJarAndThePart() {
|
||||
var unlisted = new ToolingPart("bukkit", "pack.tools.bukkit.Nowhere", new PackageName("pack.tools.bukkit"),
|
||||
"modules/user.jar", modules.toolingParts().getFirst().jar());
|
||||
try (var loader = ToolingPartLoader.open(unlisted, packLoader(), ExposedPackages.apiOnly(), platform.asApiOf(ToolingPlatform.BUKKIT))) {
|
||||
var failure = assertThrows(ModuleLoadException.class, loader::loadEntryClass);
|
||||
|
||||
assertTrue(failure.getMessage().contains("modules/user.jar"), failure.getMessage());
|
||||
assertTrue(failure.getMessage().contains("bukkit=pack.tools.bukkit.Nowhere"), failure.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void openingAPartThePackDoesNotListFails() {
|
||||
var stranger = new ToolingPart("bukkit", PART, new PackageName("pack.tools.bukkit"), "modules/other.jar", pack);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> modules.openToolingPart(stranger));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadedPackListsAndOpensThePartsOfTheHostsPlatform() throws Exception {
|
||||
var host = ModuleHost.of(List.of()).runningOn(platform.asApiOf(ToolingPlatform.BUKKIT));
|
||||
|
||||
try (var loaded = LoadedPack.load(pack, host); var loader = loaded.openToolingPart(loaded.toolingParts().getFirst())) {
|
||||
assertEquals(PART, loader.loadEntryClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void hostWithoutAPlatformHasNoPartsToOpen() {
|
||||
try (var loaded = LoadedPack.load(pack, ModuleHost.of(List.of()))) {
|
||||
assertEquals(List.of(), loaded.toolingParts());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import com.volmit.support.TestModuleJar;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import static com.volmit.support.TestModuleJar.module;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ToolingPartTest {
|
||||
private static final String ORIGIN = "modules/user.jar";
|
||||
|
||||
@TempDir
|
||||
Path pack;
|
||||
|
||||
private static TestModuleJar jarWithPartClasses(String... classNames) {
|
||||
var jar = module("pack.User", "user:core", "", "");
|
||||
for (var className : classNames) {
|
||||
int dot = className.lastIndexOf('.');
|
||||
jar.source(className, "package " + className.substring(0, dot) + "; public final class " + className.substring(dot + 1) + " {}");
|
||||
}
|
||||
return jar;
|
||||
}
|
||||
|
||||
private ModuleJar read(TestModuleJar jar) {
|
||||
return ModuleJar.read(new JarSnapshot.CopiedJar(ORIGIN, jar.writeInto(pack, "user.jar")));
|
||||
}
|
||||
|
||||
private String failureOf(TestModuleJar jar) {
|
||||
return assertThrows(ModuleLoadException.class, () -> read(jar)).getMessage();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jarWithoutTheAttributeHasNoParts() {
|
||||
assertEquals(List.of(), read(jarWithPartClasses()).toolingParts());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankAttributeHasNoParts() {
|
||||
assertEquals(List.of(), read(jarWithPartClasses().toolingParts(" ")).toolingParts());
|
||||
}
|
||||
|
||||
@Test
|
||||
void severalEntriesAreReadInListedOrderAndAPlatformMayRepeat() {
|
||||
var jar = jarWithPartClasses("pack.tools.bukkit.StudioPart", "pack.other.bukkit.ImportPart", "pack.tools.modded.ModdedPart")
|
||||
.toolingParts("bukkit=pack.tools.bukkit.StudioPart modded=pack.tools.modded.ModdedPart\tbukkit=pack.other.bukkit.ImportPart");
|
||||
|
||||
var parts = read(jar).toolingParts();
|
||||
|
||||
assertEquals(List.of("bukkit=pack.tools.bukkit.StudioPart", "modded=pack.tools.modded.ModdedPart",
|
||||
"bukkit=pack.other.bukkit.ImportPart"), parts.stream().map(ToolingPart::declaration).toList());
|
||||
assertEquals(new PackageName("pack.tools.bukkit"), parts.getFirst().packageName());
|
||||
assertEquals(ORIGIN, parts.getFirst().jarOrigin());
|
||||
assertTrue(parts.getFirst().contains("pack.tools.bukkit.deep.Helper"));
|
||||
assertFalse(parts.getFirst().contains("pack.tools.bukkitx.Helper"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoEntriesOfOnePlatformMayShareAPackage() {
|
||||
var jar = jarWithPartClasses("pack.tools.bukkit.StudioPart", "pack.tools.bukkit.ImportPart")
|
||||
.toolingParts("bukkit=pack.tools.bukkit.StudioPart bukkit=pack.tools.bukkit.ImportPart");
|
||||
|
||||
assertEquals(2, read(jar).toolingParts().size());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"bukkit", "bukkit=", "=pack.tools.StudioPart", "Bukkit=pack.tools.StudioPart", "1bukkit=pack.tools.StudioPart",
|
||||
"bukkit=StudioPart", "bukkit=pack.tools.", "bukkit=pack..StudioPart", "bukkit=pack.tools.StudioPart=again", "bukkit:pack.tools.StudioPart"})
|
||||
void malformedEntryFailsNamingTheJarAndTheEntry(String entry) {
|
||||
var message = failureOf(jarWithPartClasses("pack.tools.StudioPart").toolingParts("modded=pack.tools.StudioPart " + entry));
|
||||
|
||||
assertTrue(message.contains(ORIGIN), message);
|
||||
assertTrue(message.contains("'" + entry + "'"), message);
|
||||
assertTrue(message.contains("Iris-Tooling-Parts"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void entryClassThatTheJarDoesNotHoldFailsNamingTheJarAndTheEntry() {
|
||||
var message = failureOf(jarWithPartClasses("pack.tools.StudioPart").toolingParts("bukkit=pack.tools.MissingPart"));
|
||||
|
||||
assertTrue(message.contains(ORIGIN), message);
|
||||
assertTrue(message.contains("bukkit=pack.tools.MissingPart"), message);
|
||||
assertTrue(message.contains("holds no class pack.tools.MissingPart"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void partsOfDifferentPlatformsInOnePackageFail() {
|
||||
var jar = jarWithPartClasses("pack.tools.BukkitPart", "pack.tools.ModdedPart")
|
||||
.toolingParts("bukkit=pack.tools.BukkitPart modded=pack.tools.ModdedPart");
|
||||
|
||||
var message = failureOf(jar);
|
||||
|
||||
assertTrue(message.contains(ORIGIN), message);
|
||||
assertTrue(message.contains("overlapping tooling parts bukkit=pack.tools.BukkitPart and modded=pack.tools.ModdedPart"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void partInsideAnotherPartsPackageFails() {
|
||||
var jar = jarWithPartClasses("pack.tools.StudioPart", "pack.tools.deep.ImportPart")
|
||||
.toolingParts("bukkit=pack.tools.StudioPart bukkit=pack.tools.deep.ImportPart");
|
||||
|
||||
assertTrue(failureOf(jar).contains("overlapping tooling parts"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ToolingPlatformTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"com.volmit.tooling.bukkit.BukkitToolPart", "org.bukkit.Bukkit", "org.bukkit.entity.Player", "io.papermc.paper.Paper",
|
||||
"com.destroystokyo.paper.Event", "net.kyori.adventure.text.Component"})
|
||||
void bukkitApiPackagesAreThePlatformsApi(String className) {
|
||||
assertTrue(ToolingPlatform.BUKKIT.hasApiPackageOf(className));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"org.bukkitx.Other", "com.volmit.tooling.Command", "com.google.gson.Gson", "java.lang.String"})
|
||||
void otherClassesAreNotBukkitApi(String className) {
|
||||
assertFalse(ToolingPlatform.BUKKIT.hasApiPackageOf(className));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"art.arcane.iris.Iris", "art.arcane.iris.builtin.Thing", "net.minecraft.world.level.Level", "org.bukkit.craftbukkit.CraftServer",
|
||||
"org.bukkit.craftbukkit.v26.CraftWorld", "com.mojang.brigadier.Command", "com.volmit.host.PackModules"})
|
||||
void bukkitDeniesIrisInternalsTheServerAndTheHost(String className) {
|
||||
assertTrue(ToolingPlatform.BUKKIT.deniesPackageOf(className));
|
||||
}
|
||||
|
||||
@Test
|
||||
void bukkitDoesNotDenyItsOwnApiOrTheIrisApi() {
|
||||
assertFalse(ToolingPlatform.BUKKIT.deniesPackageOf("org.bukkit.Bukkit"));
|
||||
assertFalse(ToolingPlatform.BUKKIT.deniesPackageOf("com.volmit.IrisModule"));
|
||||
assertFalse(ToolingPlatform.BUKKIT.deniesPackageOf("art.arcane.irisx.Other"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void namedFindsTheDescriptionsTheHostKnows() {
|
||||
assertSame(ToolingPlatform.BUKKIT, ToolingPlatform.named("bukkit"));
|
||||
assertTrue(assertThrows(IllegalArgumentException.class, () -> ToolingPlatform.named("modded")).getMessage()
|
||||
.contains("Unknown tooling platform 'modded'"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "Bukkit", "1bukkit", "bu-kkit", "bukkit.paper"})
|
||||
void platformNameIsLowerCaseLettersAndDigits(String name) {
|
||||
assertThrows(IllegalArgumentException.class, () -> new ToolingPlatform(name, List.of(), List.of()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.Optional;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class UnavailableJdkModulesTest {
|
||||
@Test
|
||||
void namesJdkModulesOutsideThePlatformLoader() {
|
||||
assertEquals(Optional.of("jdk.compiler"), UnavailableJdkModules.moduleOf("com.sun.source.tree.Tree"));
|
||||
assertEquals(Optional.of("jdk.jshell"), UnavailableJdkModules.moduleOf("jdk.jshell.JShell"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void modulesOfTheBootAndPlatformLoadersAreAvailable() {
|
||||
assertEquals(Optional.empty(), UnavailableJdkModules.moduleOf("java.lang.String"));
|
||||
assertEquals(Optional.empty(), UnavailableJdkModules.moduleOf("java.sql.Connection"));
|
||||
assertEquals(Optional.empty(), UnavailableJdkModules.moduleOf("javax.tools.ToolProvider"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void classesOutsideTheJdkAreNotJdkModules() {
|
||||
assertEquals(Optional.empty(), UnavailableJdkModules.moduleOf("org.slf4j.Logger"));
|
||||
assertEquals(Optional.empty(), UnavailableJdkModules.moduleOf("TopLevel"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class WorldStatesTest {
|
||||
static final class Cache {}
|
||||
static final class Index {
|
||||
final Cache cache;
|
||||
Index(Cache cache) { this.cache = cache; }
|
||||
}
|
||||
static final class Loop {}
|
||||
static final class Other {}
|
||||
|
||||
record Closing(String name, List<String> closed, boolean fails) implements AutoCloseable {
|
||||
@Override
|
||||
public void close() {
|
||||
closed.add(name);
|
||||
if (fails) {
|
||||
throw new IllegalStateException(name + " broke");
|
||||
}
|
||||
}
|
||||
}
|
||||
static final class ClosingA {}
|
||||
|
||||
@Test
|
||||
void createsEachTypeOnceAndHandsEveryCallerTheSameInstance() {
|
||||
var states = new WorldStates();
|
||||
var created = new AtomicInteger();
|
||||
Cache first = states.state(Cache.class, () -> {
|
||||
created.incrementAndGet();
|
||||
return new Cache();
|
||||
});
|
||||
Cache second = states.state(Cache.class, () -> {
|
||||
created.incrementAndGet();
|
||||
return new Cache();
|
||||
});
|
||||
|
||||
assertSame(first, second);
|
||||
assertEquals(1, created.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void racingThreadsShareOneCreation() throws Exception {
|
||||
var states = new WorldStates();
|
||||
var created = new AtomicInteger();
|
||||
var start = new CountDownLatch(1);
|
||||
var threads = 8;
|
||||
try (var executor = Executors.newFixedThreadPool(threads)) {
|
||||
var results = new ArrayList<Future<Cache>>();
|
||||
for (int thread = 0; thread < threads; thread++) {
|
||||
results.add(executor.submit(() -> {
|
||||
start.await();
|
||||
return states.state(Cache.class, () -> {
|
||||
created.incrementAndGet();
|
||||
return new Cache();
|
||||
});
|
||||
}));
|
||||
}
|
||||
start.countDown();
|
||||
Cache shared = results.getFirst().get(10, TimeUnit.SECONDS);
|
||||
for (var result : results) {
|
||||
assertSame(shared, result.get(10, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
assertEquals(1, created.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFactoryMayAskForOtherStateButNotForItself() {
|
||||
var states = new WorldStates();
|
||||
Index index = states.state(Index.class, () -> new Index(states.state(Cache.class, Cache::new)));
|
||||
assertSame(index.cache, states.state(Cache.class, Cache::new));
|
||||
|
||||
var loop = assertThrows(IllegalStateException.class, () -> states.state(Loop.class, () -> {
|
||||
states.state(Other.class, () -> {
|
||||
states.state(Loop.class, Loop::new);
|
||||
return new Other();
|
||||
});
|
||||
return new Loop();
|
||||
}));
|
||||
assertTrue(loop.getMessage().contains(Loop.class.getName() + " -> " + Other.class.getName() + " -> " + Loop.class.getName()),
|
||||
loop.getMessage());
|
||||
assertNotNull(states.state(Loop.class, Loop::new), "a failed creation keeps nothing, so the next call creates it");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFactoryThatFailsOrReturnsNullKeepsNothing() {
|
||||
var states = new WorldStates();
|
||||
assertThrows(IllegalArgumentException.class, () -> states.state(Cache.class, () -> {
|
||||
throw new IllegalArgumentException("not yet");
|
||||
}));
|
||||
var nothing = assertThrows(NullPointerException.class, () -> states.state(Cache.class, () -> null));
|
||||
assertTrue(nothing.getMessage().contains(Cache.class.getName()), nothing.getMessage());
|
||||
|
||||
var cache = new Cache();
|
||||
assertSame(cache, states.state(Cache.class, () -> cache));
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingClosesEveryCloseableStateNewestFirstAndEndsTheStore() {
|
||||
var states = new WorldStates();
|
||||
var closed = new ArrayList<String>();
|
||||
states.state(Closing.class, () -> new Closing("first", closed, false));
|
||||
states.state(Cache.class, Cache::new);
|
||||
states.state(ClosingA.class, ClosingA::new);
|
||||
states.state(AutoCloseable.class, () -> () -> closed.add("second"));
|
||||
|
||||
states.close();
|
||||
states.close();
|
||||
|
||||
assertEquals(List.of("second", "first"), closed);
|
||||
var after = assertThrows(IllegalStateException.class, () -> states.state(Cache.class, Cache::new));
|
||||
assertTrue(after.getMessage().contains("after the world stopped"), after.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingContinuesPastAFailureAndReportsEveryOne() {
|
||||
var states = new WorldStates();
|
||||
var closed = new ArrayList<String>();
|
||||
states.state(Closing.class, () -> new Closing("first", closed, true));
|
||||
states.state(AutoCloseable.class, () -> new Closing("second", closed, true));
|
||||
|
||||
var failure = assertThrows(IllegalStateException.class, states::close);
|
||||
|
||||
assertEquals(List.of("second", "first"), closed);
|
||||
assertTrue(failure.getMessage().contains("second broke"), failure.getMessage());
|
||||
assertEquals(1, failure.getSuppressed().length);
|
||||
assertTrue(failure.getSuppressed()[0].getMessage().contains("first broke"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.FeatureSettings;
|
||||
import com.volmit.config.SettingsStack;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
/** Settings declared per world column by a function, for chunk and mantle tests. */
|
||||
public final class ColumnSettings implements FeatureSettings {
|
||||
public static final ColumnSettings NONE = new ColumnSettings((x, z) -> List.of());
|
||||
|
||||
private final BiFunction<Integer, Integer, List<Entry<?>>> columns;
|
||||
|
||||
public ColumnSettings(BiFunction<Integer, Integer, List<Entry<?>>> columns) {
|
||||
this.columns = columns;
|
||||
}
|
||||
|
||||
/** The same entries at every column. */
|
||||
public static ColumnSettings everywhere(Entry<?>... entries) {
|
||||
var all = List.of(entries);
|
||||
return new ColumnSettings((x, z) -> all);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked") // Filtered by the requested type.
|
||||
public <F extends IrisFeature> SettingsStack<F> at(Class<F> featureType, int worldX, int worldZ) {
|
||||
return SettingsStack.of(columns.apply(worldX, worldZ).stream()
|
||||
.filter(entry -> featureType.isInstance(entry.value()))
|
||||
.map(entry -> (Entry<F>) entry)
|
||||
.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <F extends IrisFeature> Optional<F> declaredBy(ResourceId biome, Class<F> featureType) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.object.BlockEntityData;
|
||||
import com.volmit.placement.PlacedMarker;
|
||||
import com.volmit.placement.PlacementRecord;
|
||||
import com.volmit.placement.PlacementTerrain;
|
||||
import com.volmit.placement.StructureVolumes;
|
||||
import com.volmit.world.BlockView;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Placement terrain over test blocks that answers column heights and reads; anything else fails the test. */
|
||||
public final class ColumnTerrain implements PlacementTerrain {
|
||||
private final BlockView blocks;
|
||||
|
||||
public ColumnTerrain(BlockView blocks) {
|
||||
this.blocks = blocks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int highest(int x, int z, boolean ignoreFluid) {
|
||||
var bounds = blocks.bounds();
|
||||
for (int y = bounds.maxY() - 1; y >= bounds.minY(); y--) {
|
||||
if (!blocks.get(x, y, z).material().equals(TestTerrain.AIR.material())) {
|
||||
return y;
|
||||
}
|
||||
}
|
||||
return bounds.minY() - 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockState get(int x, int y, int z) {
|
||||
return blocks.get(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(int x, int y, int z, BlockState state) { throw unused("set"); }
|
||||
|
||||
@Override
|
||||
public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { throw unused("set"); }
|
||||
|
||||
@Override
|
||||
public boolean isCarved(int x, int y, int z) { throw unused("isCarved"); }
|
||||
|
||||
@Override
|
||||
public boolean isSurfaceSolid(int x, int y, int z) { throw unused("isSurfaceSolid"); }
|
||||
|
||||
@Override
|
||||
public boolean isUnderwater(int x, int z) { throw unused("isUnderwater"); }
|
||||
|
||||
@Override
|
||||
public int fluidHeight() { throw unused("fluidHeight"); }
|
||||
|
||||
@Override
|
||||
public boolean preventsDecay() { throw unused("preventsDecay"); }
|
||||
|
||||
@Override
|
||||
public void recordPlacement(int x, int y, int z, PlacementRecord placement) { throw unused("recordPlacement"); }
|
||||
|
||||
@Override
|
||||
public Optional<PlacementRecord> placementAt(int x, int y, int z) { throw unused("placementAt"); }
|
||||
|
||||
@Override
|
||||
public StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ) { throw unused("structureVolumes"); }
|
||||
|
||||
@Override
|
||||
public void mark(PlacedMarker marker) { throw unused("mark"); }
|
||||
|
||||
private static AssertionError unused(String method) {
|
||||
return new AssertionError("Unused placement terrain " + method);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.config.FeatureSettings.Entry;
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.config.SettingsStack;
|
||||
import com.volmit.resource.PackResources;
|
||||
import java.util.List;
|
||||
|
||||
/** A pack's settings as a fixed list of declarations, for reach tests. */
|
||||
public final class DeclaredSettings implements PackSettings {
|
||||
public static final DeclaredSettings NONE = new DeclaredSettings();
|
||||
|
||||
private final List<Entry<?>> entries;
|
||||
|
||||
public DeclaredSettings(Entry<?>... entries) {
|
||||
this.entries = List.of(entries);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked") // Filtered by the requested type.
|
||||
public <F extends IrisFeature> SettingsStack<F> declared(Class<F> featureType) {
|
||||
return SettingsStack.of(entries.stream()
|
||||
.filter(entry -> featureType.isInstance(entry.value()))
|
||||
.map(entry -> (Entry<F>) entry)
|
||||
.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackResources resources() {
|
||||
return new EmptyResources();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.block.BlockRegistry;
|
||||
import com.volmit.item.ItemRegistry;
|
||||
import com.volmit.noise.NoiseFactory;
|
||||
import com.volmit.object.PackObjects;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/** A pack {@code test:pack} without resources. */
|
||||
public final class EmptyResources implements PackResources {
|
||||
private final UUID snapshot = UUID.randomUUID();
|
||||
|
||||
@Override
|
||||
public ResourceId packId() {
|
||||
return new ResourceId("test", "pack");
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID snapshotId() {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockRegistry blocks() {
|
||||
throw new AssertionError("Unused blocks");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemRegistry items() {
|
||||
throw new AssertionError("Unused items");
|
||||
}
|
||||
|
||||
@Override
|
||||
public NoiseFactory noise() {
|
||||
throw new AssertionError("Unused noise");
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackObjects objects() {
|
||||
throw new AssertionError("Unused objects");
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Optional<T> find(ResourceKind<T> kind, ResourceId id) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourceId> ids(ResourceKind<?> kind) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.host.PlatformApi;
|
||||
import com.volmit.host.ToolingPlatform;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** A tiny stand-in for a platform's api jar, such as paper-api: a jar of empty public classes, and a loader that defines
|
||||
* only them, like the platform plugin's loader would. Close it to release the jar.
|
||||
*/
|
||||
public final class FakePlatformApi implements AutoCloseable {
|
||||
private final Path jar;
|
||||
private final URLClassLoader classes;
|
||||
|
||||
private FakePlatformApi(Path jar, URLClassLoader classes) {
|
||||
this.jar = jar;
|
||||
this.classes = classes;
|
||||
}
|
||||
|
||||
/** Writes a jar below {@code workDirectory} that holds one empty public class per name, such as {@code org.bukkit.Bukkit}. */
|
||||
public static FakePlatformApi of(Path workDirectory, String... classNames) {
|
||||
try {
|
||||
var jarSource = new TestModuleJar();
|
||||
for (var className : classNames) {
|
||||
int dot = className.lastIndexOf('.');
|
||||
jarSource.source(className, "package " + className.substring(0, dot) + "; public class " + className.substring(dot + 1) + " {}");
|
||||
}
|
||||
var jar = jarSource.writeInto(Files.createTempDirectory(workDirectory, "platform"), "platform-api.jar");
|
||||
return new FakePlatformApi(jar, new URLClassLoader("fake-platform", new URL[] {jar.toUri().toURL()}, null));
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
public Path jar() {
|
||||
return jar;
|
||||
}
|
||||
|
||||
public ClassLoader classes() {
|
||||
return classes;
|
||||
}
|
||||
|
||||
public PlatformApi asApiOf(ToolingPlatform platform) {
|
||||
return new PlatformApi(platform, classes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
classes.close();
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.geometry.BlockBox;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.mantle.Mantle;
|
||||
import com.volmit.placement.PlacedBlock;
|
||||
import com.volmit.placement.PlacedMarker;
|
||||
import com.volmit.placement.PlacementEdit;
|
||||
import com.volmit.world.BlockView;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** In-memory transactional test adapter over a base view; production storage is absent. */
|
||||
public final class MemoryEdit implements PlacementEdit {
|
||||
public enum Status { OPEN, COMMITTED, CLOSED }
|
||||
|
||||
private final BlockView base;
|
||||
private final Mantle mantle;
|
||||
private final Map<BlockPosition, BlockState> pending = new HashMap<>();
|
||||
private final Map<BlockPosition, BlockState> published = new HashMap<>();
|
||||
private final List<PlacedMarker> pendingMarkers = new ArrayList<>();
|
||||
private final List<PlacedMarker> publishedMarkers = new ArrayList<>();
|
||||
private Status status = Status.OPEN;
|
||||
private boolean committed;
|
||||
|
||||
public MemoryEdit(BlockView base) {
|
||||
this(base, null);
|
||||
}
|
||||
|
||||
/** An edit whose placement has {@code mantle}; null for none. */
|
||||
public MemoryEdit(BlockView base, Mantle mantle) {
|
||||
this.base = base;
|
||||
this.mantle = mantle;
|
||||
}
|
||||
|
||||
public boolean committed() { return committed; }
|
||||
public Status status() { return status; }
|
||||
public Map<BlockPosition, BlockState> published() { return Map.copyOf(published); }
|
||||
public List<PlacedMarker> publishedMarkers() { return List.copyOf(publishedMarkers); }
|
||||
|
||||
public BlockState publishedAt(int x, int y, int z) {
|
||||
return published.getOrDefault(new BlockPosition(x, y, z), base.get(x, y, z));
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockBox bounds() {
|
||||
checkOpen();
|
||||
return base.bounds();
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockState get(int x, int y, int z) {
|
||||
checkOpen();
|
||||
return pending.getOrDefault(new BlockPosition(x, y, z), base.get(x, y, z));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(int x, int y, int z, BlockState state) {
|
||||
checkOpen();
|
||||
if (!base.bounds().contains(x, y, z)) {
|
||||
throw new IndexOutOfBoundsException("Write outside prepared area: " + new BlockPosition(x, y, z));
|
||||
}
|
||||
pending.put(new BlockPosition(x, y, z), state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(PlacedBlock block) {
|
||||
var position = block.position();
|
||||
set(position.x(), position.y(), position.z(), block.state());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void marker(PlacedMarker marker) {
|
||||
checkOpen();
|
||||
pendingMarkers.add(marker);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mantle mantle() {
|
||||
checkOpen();
|
||||
if (mantle == null) throw new AssertionError("Unused mantle");
|
||||
return mantle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void commit() {
|
||||
checkOpen();
|
||||
published.putAll(pending);
|
||||
publishedMarkers.addAll(pendingMarkers);
|
||||
committed = true;
|
||||
status = Status.COMMITTED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
pending.clear();
|
||||
pendingMarkers.clear();
|
||||
status = Status.CLOSED;
|
||||
}
|
||||
|
||||
private void checkOpen() {
|
||||
if (status != Status.OPEN) throw new IllegalStateException("Edit is " + status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.geometry.BlockBox;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.mantle.CarvedVoid;
|
||||
import com.volmit.mantle.Mantle;
|
||||
import com.volmit.mantle.MantleEdit;
|
||||
import com.volmit.mantle.MantleKey;
|
||||
import com.volmit.mantle.MantleLayer;
|
||||
import com.volmit.mantle.MantleVisitor;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/** An in-memory mantle over fixed bounds; an invocation sees it through {@link #within(BlockBox)}. */
|
||||
public final class MemoryMantle {
|
||||
private static final Comparator<BlockPosition> VISIT_ORDER = Comparator.comparingInt(BlockPosition::x)
|
||||
.thenComparingInt(BlockPosition::y).thenComparingInt(BlockPosition::z);
|
||||
|
||||
/** Where the planned blocks are kept; the host owns them, so no module registers this layer. */
|
||||
private static final MantleKey<BlockState> PLANNED_BLOCKS = new MantleKey<>(ResourceId.parse("host:planned-blocks"),BlockState.class);
|
||||
|
||||
/** Where the carved voids are kept; the host owns them, so no module registers this layer. */
|
||||
private static final MantleKey<CarvedVoid> CAVERNS = new MantleKey<>(ResourceId.parse("host:caverns"),CarvedVoid.class);
|
||||
|
||||
/** Where the platform biomes stages set are kept; the host owns them, so no module registers this layer. */
|
||||
private static final MantleKey<ResourceId> PLATFORM_BIOMES = new MantleKey<>(ResourceId.parse("host:platform-biomes"),ResourceId.class);
|
||||
|
||||
private final Map<ResourceId, TreeMap<BlockPosition, Object>> layers = new HashMap<>();
|
||||
|
||||
/** A view that accepts reads and writes inside {@code bounds} only. */
|
||||
public Mantle within(BlockBox bounds) {
|
||||
return new Mantle() {
|
||||
public BlockBox bounds() { return bounds; }
|
||||
public <T> MantleLayer<T> layer(MantleKey<T> key) { return new Layer<>(key, bounds, true); }
|
||||
public MantleLayer<BlockState> blocks() { return new Layer<>(PLANNED_BLOCKS, bounds, false); }
|
||||
public MantleLayer<CarvedVoid> carved() { return new Layer<>(CAVERNS, bounds, true); }
|
||||
public void setPlatformBiome(int x, int y, int z, ResourceId biome) {
|
||||
if (!bounds.contains(x, y, z)) throw new IndexOutOfBoundsException("Outside the mantle view: " + x + "," + y + "," + z);
|
||||
values(PLATFORM_BIOMES).put(new BlockPosition(x, y, z), biome);
|
||||
}
|
||||
public MantleEdit edit() { throw new UnsupportedOperationException("Edits are not used in these tests"); }
|
||||
};
|
||||
}
|
||||
|
||||
/** Puts a planned block into the mantle, as a placement would; stages only read them. */
|
||||
public void plan(int x, int y, int z, BlockState block) {
|
||||
values(PLANNED_BLOCKS).put(new BlockPosition(x, y, z), block);
|
||||
}
|
||||
|
||||
/** Carves an open void into the mantle, as the cave planner would. */
|
||||
public void carve(int x, int y, int z) {
|
||||
values(CAVERNS).put(new BlockPosition(x, y, z), CarvedVoid.OPEN);
|
||||
}
|
||||
|
||||
/** The platform biome a stage set at the block; null where none did. */
|
||||
public ResourceId platformBiome(int x, int y, int z) {
|
||||
return get(PLATFORM_BIOMES, x, y, z);
|
||||
}
|
||||
|
||||
public <T> T get(MantleKey<T> key, int x, int y, int z) {
|
||||
return key.type().cast(values(key).get(new BlockPosition(x, y, z)));
|
||||
}
|
||||
|
||||
private TreeMap<BlockPosition, Object> values(MantleKey<?> key) {
|
||||
return layers.computeIfAbsent(key.id(), ignored -> new TreeMap<>(VISIT_ORDER));
|
||||
}
|
||||
|
||||
private final class Layer<T> implements MantleLayer<T> {
|
||||
private final MantleKey<T> key;
|
||||
private final BlockBox bounds;
|
||||
private final boolean writable;
|
||||
|
||||
Layer(MantleKey<T> key, BlockBox bounds, boolean writable) {
|
||||
this.key = key;
|
||||
this.bounds = bounds;
|
||||
this.writable = writable;
|
||||
}
|
||||
|
||||
public T get(int x, int y, int z) {
|
||||
requireInside(x, y, z);
|
||||
return MemoryMantle.this.get(key, x, y, z);
|
||||
}
|
||||
|
||||
public void set(int x, int y, int z, T value) {
|
||||
requireWritable();
|
||||
requireInside(x, y, z);
|
||||
values(key).put(new BlockPosition(x, y, z), key.type().cast(value));
|
||||
}
|
||||
|
||||
public void remove(int x, int y, int z) {
|
||||
requireWritable();
|
||||
requireInside(x, y, z);
|
||||
values(key).remove(new BlockPosition(x, y, z));
|
||||
}
|
||||
|
||||
public void visit(BlockBox area, MantleVisitor<T> visitor) {
|
||||
if (!bounds.contains(area)) throw new IndexOutOfBoundsException("Outside the mantle view: " + area);
|
||||
values(key).forEach((position, value) -> {
|
||||
if (area.contains(position.x(), position.y(), position.z())) {
|
||||
visitor.accept(position.x(), position.y(), position.z(), key.type().cast(value));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void clear(BlockBox area) {
|
||||
requireWritable();
|
||||
if (!bounds.contains(area)) throw new IndexOutOfBoundsException("Outside the mantle view: " + area);
|
||||
values(key).keySet().removeIf(position -> area.contains(position.x(), position.y(), position.z()));
|
||||
}
|
||||
|
||||
private void requireWritable() {
|
||||
if (!writable) throw new UnsupportedOperationException("Planned blocks are read-only to stages");
|
||||
}
|
||||
|
||||
private void requireInside(int x, int y, int z) {
|
||||
if (!bounds.contains(x, y, z)) throw new IndexOutOfBoundsException("Outside the mantle view: " + x + "," + y + "," + z);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.config.FeatureSettings;
|
||||
import com.volmit.generation.GenerationContext;
|
||||
import com.volmit.generation.MantleGenerationContext;
|
||||
import com.volmit.hunk.Hunk;
|
||||
import com.volmit.mantle.Mantle;
|
||||
import com.volmit.placement.PlacementContext;
|
||||
import com.volmit.placement.PlacementTerrain;
|
||||
import java.util.Optional;
|
||||
import com.volmit.world.TerrainSampler;
|
||||
import com.volmit.world.BlockView;
|
||||
import com.volmit.world.PackWorld;
|
||||
|
||||
/** Tests needing no platform facilities fail loudly if code starts using one. */
|
||||
public final class TestContexts {
|
||||
public static final long SEED = 42;
|
||||
|
||||
private TestContexts() {}
|
||||
|
||||
/** The chunk at the origin; a null {@code blocks} fails when used. */
|
||||
public static GenerationContext generation(Hunk<BlockState> blocks) {
|
||||
return generation(blocks, null, null);
|
||||
}
|
||||
|
||||
/** The chunk at the origin; a null {@code blocks}, {@code settings} or {@code mantle} fails when used. */
|
||||
public static GenerationContext generation(Hunk<BlockState> blocks, FeatureSettings settings, Mantle mantle) {
|
||||
return generation(blocks, settings, mantle, null);
|
||||
}
|
||||
|
||||
/** The chunk at the origin in {@code world}; a null {@code blocks}, {@code settings}, {@code mantle} or {@code world}
|
||||
* fails when used.
|
||||
*/
|
||||
public static GenerationContext generation(Hunk<BlockState> blocks, FeatureSettings settings, Mantle mantle, PackWorld world) {
|
||||
return new GenerationContext() {
|
||||
public int originX() { return 0; }
|
||||
public int originZ() { return 0; }
|
||||
public PackWorld world() { return used(world, "world"); }
|
||||
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
|
||||
public FeatureSettings settings() { return used(settings, "settings"); }
|
||||
public Mantle mantle() { return used(mantle, "mantle"); }
|
||||
public Hunk<BlockState> blocks() { return used(blocks, "blocks"); }
|
||||
};
|
||||
}
|
||||
|
||||
/** The mantle invocation of the chunk whose first block is ({@code originX}, {@code originZ}). */
|
||||
public static MantleGenerationContext mantle(int originX, int originZ, FeatureSettings settings, Mantle mantle) {
|
||||
return new MantleGenerationContext() {
|
||||
public int originX() { return originX; }
|
||||
public int originZ() { return originZ; }
|
||||
public PackWorld world() { throw new AssertionError("Unused world"); }
|
||||
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
|
||||
public FeatureSettings settings() { return settings; }
|
||||
public Mantle mantle() { return mantle; }
|
||||
public PlacementTerrain placementTerrain() { throw new AssertionError("Unused placement terrain"); }
|
||||
};
|
||||
}
|
||||
|
||||
public static PlacementContext placement() {
|
||||
return placement(null);
|
||||
}
|
||||
|
||||
/** A placement whose terrain answers from {@code blocks}; a null {@code blocks} fails when used. */
|
||||
public static PlacementContext placement(BlockView blocks) {
|
||||
return new PlacementContext() {
|
||||
public PackWorld world() { throw new AssertionError("Unused world"); }
|
||||
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
|
||||
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
|
||||
public PlacementTerrain placementTerrain() { return new ColumnTerrain(used(blocks, "placement terrain")); }
|
||||
public <T> Optional<T> input(Class<T> type) { return Optional.empty(); }
|
||||
};
|
||||
}
|
||||
|
||||
private static <T> T used(T value, String name) {
|
||||
if (value == null) throw new AssertionError("Unused " + name);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.jar.Attributes;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarOutputStream;
|
||||
import java.util.jar.Manifest;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.tools.DiagnosticCollector;
|
||||
import javax.tools.JavaFileObject;
|
||||
import javax.tools.SimpleJavaFileObject;
|
||||
import javax.tools.ToolProvider;
|
||||
|
||||
/** Builds a real module jar from Java source at test time. Its classes are not on the test
|
||||
* classpath, so only a pack class loader can define them. Sources compile against the API's main
|
||||
* classes only, like a real module; built-in example modules and host libraries must be added with
|
||||
* {@link #compileAgainstHostOf}, so a jar cannot depend on test support classes by accident.
|
||||
*/
|
||||
public final class TestModuleJar {
|
||||
private static final String SERVICES_FILE = "META-INF/services/" + IrisModule.class.getName();
|
||||
|
||||
private final Map<String, String> sources = new LinkedHashMap<>();
|
||||
private final Map<String, byte[]> resources = new LinkedHashMap<>();
|
||||
private static final String OPTIONAL_PACKAGES_ATTRIBUTE = "Iris-Optional-Packages";
|
||||
private static final String TOOLING_PARTS_ATTRIBUTE = "Iris-Tooling-Parts";
|
||||
private boolean multiRelease;
|
||||
private String toolingParts;
|
||||
private final List<String> optionalPackages = new ArrayList<>();
|
||||
private final List<String> entryPoints = new ArrayList<>();
|
||||
private final List<Path> classpath = new ArrayList<>(List.of(classesOf(IrisModule.class)));
|
||||
private final List<String> compilerExports = new ArrayList<>();
|
||||
|
||||
/** An entry class with the given module id whose setup body may use {@code graph} and {@code registry}. */
|
||||
public static TestModuleJar module(String className, String moduleId, String members, String install) {
|
||||
return module(className, moduleId, List.of(), members, install);
|
||||
}
|
||||
|
||||
/** Like {@link #module(String, String, String, String)}, in a jar whose manifest declares {@code optionalPackages}. */
|
||||
public static TestModuleJar module(String className, String moduleId, List<String> optionalPackages, String members, String install) {
|
||||
var jar = new TestModuleJar();
|
||||
jar.optionalPackages.addAll(optionalPackages);
|
||||
return jar.source(className, moduleSource(className, moduleInfo(moduleId), members, install)).entryPoint(className);
|
||||
}
|
||||
|
||||
/** Another entry class in the same jar, with the given module id; see {@link #module(String, String, String, String)}. */
|
||||
public TestModuleJar alsoModule(String className, String moduleId, String members, String install) {
|
||||
var info = moduleInfo(moduleId);
|
||||
return source(className, moduleSource(className, info, members, install)).entryPoint(className);
|
||||
}
|
||||
|
||||
/** Compiles one class on its own and returns its class file, for raw entries such as versioned classes. */
|
||||
public static byte[] compileClass(Path workDirectory, String className, String code) {
|
||||
try {
|
||||
var classes = new TestModuleJar().source(className, code).compile(Files.createTempDirectory(workDirectory, "classes"));
|
||||
return Files.readAllBytes(classes.resolve(className.replace('.', '/') + ".class"));
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
public TestModuleJar source(String className, String code) {
|
||||
sources.put(className, code);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Adds one line to the jar's entry point file. */
|
||||
public TestModuleJar entryPoint(String className) {
|
||||
entryPoints.add(className);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Adds a raw jar entry, such as a versioned class file, without compiling anything. */
|
||||
public TestModuleJar resource(String entryName, byte[] content) {
|
||||
resources.put(entryName, content.clone());
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Marks the jar {@code Multi-Release: true}, so its {@code META-INF/versions} entries count. */
|
||||
public TestModuleJar multiRelease() {
|
||||
multiRelease = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Sets the manifest's {@code Iris-Tooling-Parts} attribute to {@code declaration}, verbatim. */
|
||||
public TestModuleJar toolingParts(String declaration) {
|
||||
toolingParts = declaration;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Puts a jar or class directory on the compile classpath only; it is not packaged. */
|
||||
public TestModuleJar compileAgainst(Path classes) {
|
||||
classpath.add(classes);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Puts a jar or class directory before the API on the compile classpath, so the sources compile against an
|
||||
* older copy of an API class it holds; it is not packaged.
|
||||
*/
|
||||
public TestModuleJar compileAgainstOlderApi(Path classes) {
|
||||
classpath.addFirst(classes);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Compiles against wherever {@code type} was loaded from, such as a host library jar. */
|
||||
public TestModuleJar compileAgainstHostOf(Class<?> type) {
|
||||
return compileAgainst(classesOf(type));
|
||||
}
|
||||
|
||||
/** Lets the sources use a JDK package its module does not export, as javac's
|
||||
* {@code --add-exports <module>/<package>=ALL-UNNAMED} does. Only compiling is affected.
|
||||
*/
|
||||
public TestModuleJar compileWithAccessTo(String module, String packageName) {
|
||||
compilerExports.addAll(List.of("--add-exports", module + "/" + packageName + "=ALL-UNNAMED"));
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Writes {@code <packRoot>/modules/<jarName>} and returns its path. */
|
||||
public Path writeInto(Path packRoot, String jarName) {
|
||||
try {
|
||||
var jar = Files.createDirectories(packRoot.resolve("modules")).resolve(jarName);
|
||||
var classes = compile(Files.createTempDirectory(packRoot, "classes"));
|
||||
try (var output = new JarOutputStream(Files.newOutputStream(jar), manifest())) {
|
||||
writeClasses(output, classes);
|
||||
writeResources(output);
|
||||
writeEntryPoints(output);
|
||||
}
|
||||
return jar;
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private Path compile(Path classes) {
|
||||
if (sources.isEmpty()) return classes;
|
||||
var compiler = ToolProvider.getSystemJavaCompiler();
|
||||
var diagnostics = new DiagnosticCollector<JavaFileObject>();
|
||||
var units = sources.entrySet().stream().map(source -> new StringSource(source.getKey(), source.getValue())).toList();
|
||||
var options = new ArrayList<>(List.of("-d", classes.toString(), "-proc:none", "-classpath",
|
||||
classpath.stream().map(Path::toString).collect(Collectors.joining(File.pathSeparator))));
|
||||
options.addAll(compilerExports);
|
||||
if (!compiler.getTask(null, null, diagnostics, options, null, units).call()) {
|
||||
throw new IllegalStateException("Test module does not compile: " + diagnostics.getDiagnostics());
|
||||
}
|
||||
return classes;
|
||||
}
|
||||
|
||||
private static void writeClasses(JarOutputStream output, Path classes) throws IOException {
|
||||
try (var files = Files.walk(classes)) {
|
||||
for (var file : files.filter(Files::isRegularFile).sorted().toList()) {
|
||||
output.putNextEntry(new JarEntry(classes.relativize(file).toString().replace(File.separatorChar, '/')));
|
||||
output.write(Files.readAllBytes(file));
|
||||
output.closeEntry();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Manifest manifest() {
|
||||
var manifest = new Manifest();
|
||||
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
|
||||
if (multiRelease) manifest.getMainAttributes().put(Attributes.Name.MULTI_RELEASE, "true");
|
||||
if (!optionalPackages.isEmpty()) {
|
||||
manifest.getMainAttributes().putValue(OPTIONAL_PACKAGES_ATTRIBUTE, String.join(" ", optionalPackages));
|
||||
}
|
||||
if (toolingParts != null) manifest.getMainAttributes().putValue(TOOLING_PARTS_ATTRIBUTE, toolingParts);
|
||||
return manifest;
|
||||
}
|
||||
|
||||
private void writeResources(JarOutputStream output) throws IOException {
|
||||
for (var resource : resources.entrySet()) {
|
||||
output.putNextEntry(new JarEntry(resource.getKey()));
|
||||
output.write(resource.getValue());
|
||||
output.closeEntry();
|
||||
}
|
||||
}
|
||||
|
||||
private void writeEntryPoints(JarOutputStream output) throws IOException {
|
||||
if (entryPoints.isEmpty()) return;
|
||||
output.putNextEntry(new JarEntry(SERVICES_FILE));
|
||||
output.write(("# entry point\n" + String.join("\n", entryPoints) + "\n").getBytes(StandardCharsets.UTF_8));
|
||||
output.closeEntry();
|
||||
}
|
||||
|
||||
private static String moduleInfo(String moduleId) {
|
||||
return "ModuleInfo.of(\"%s\", \"%s\", \"1.0.0\")".formatted(moduleId, displayName(moduleId));
|
||||
}
|
||||
|
||||
private static String moduleSource(String className, String info, String members, String install) {
|
||||
int dot = className.lastIndexOf('.');
|
||||
return """
|
||||
package %s;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.stage.*;
|
||||
|
||||
public final class %s implements IrisModule {
|
||||
%s
|
||||
|
||||
public ModuleInfo info() { return %s; }
|
||||
|
||||
public void setup(com.volmit.ModuleSetup setup) {
|
||||
StageGraph graph = setup.stages();
|
||||
com.volmit.FeatureRegistry registry = setup.registry();
|
||||
%s
|
||||
}
|
||||
}
|
||||
""".formatted(className.substring(0, dot), className.substring(dot + 1), members, info, install);
|
||||
}
|
||||
|
||||
/** The display name test modules get, so assertions can predict it from the id. */
|
||||
public static String displayName(String moduleId) {
|
||||
return "Test " + moduleId;
|
||||
}
|
||||
|
||||
private static Path classesOf(Class<?> type) {
|
||||
try {
|
||||
return Path.of(type.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||
} catch (URISyntaxException exception) {
|
||||
throw new IllegalStateException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class StringSource extends SimpleJavaFileObject {
|
||||
private final String code;
|
||||
|
||||
StringSource(String className, String code) {
|
||||
super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.host.DiscoveredModule;
|
||||
import com.volmit.host.ModuleRegistry;
|
||||
import com.volmit.host.ModuleSetups;
|
||||
import com.volmit.host.StageGraphBuilder;
|
||||
|
||||
/** Sets modules up into a stage graph for tests that only need their stages; registrations go to a registry of
|
||||
* their own.
|
||||
*/
|
||||
public final class TestSetups {
|
||||
private TestSetups() {}
|
||||
|
||||
/** A builder with every module set up as a built-in. */
|
||||
public static StageGraphBuilder stages(IrisModule... modules) {
|
||||
var builder = new StageGraphBuilder();
|
||||
for (var module : modules) {
|
||||
install(builder, DiscoveredModule.builtIn(module));
|
||||
}
|
||||
return builder;
|
||||
}
|
||||
|
||||
public static void install(StageGraphBuilder builder, DiscoveredModule module) {
|
||||
ModuleSetups.run(module, builder, new ModuleRegistry());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.geometry.BlockBox;
|
||||
import com.volmit.world.BlockView;
|
||||
import java.util.function.IntBinaryOperator;
|
||||
|
||||
/** Prepared pre-placement blocks: stone below a per-column ground height, air above. */
|
||||
public final class TestTerrain implements BlockView {
|
||||
public static final BlockState STONE = new BlockState("minecraft:stone");
|
||||
public static final BlockState AIR = new BlockState("minecraft:air");
|
||||
public static final BlockBox BOUNDS = new BlockBox(-16, 0, -16, 16, 32, 16);
|
||||
|
||||
private final IntBinaryOperator groundHeight;
|
||||
|
||||
public TestTerrain(IntBinaryOperator groundHeight) {
|
||||
this.groundHeight = groundHeight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockBox bounds() {
|
||||
return BOUNDS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockState get(int x, int y, int z) {
|
||||
if (!BOUNDS.contains(x, y, z)) throw new IndexOutOfBoundsException("Outside test terrain: " + x + "," + y + "," + z);
|
||||
return y < groundHeight.applyAsInt(x, z) ? STONE : AIR;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.volmit.support;
|
||||
|
||||
import com.volmit.IrisFeature;
|
||||
import com.volmit.ModuleLog;
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.config.SettingsStack;
|
||||
import com.volmit.host.ModuleLogs;
|
||||
import com.volmit.host.WorldStates;
|
||||
import com.volmit.placement.Placements;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.world.PackWorld;
|
||||
import com.volmit.world.RunningWorld;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** A world for tests: the test seed, no resources, no declared settings, and a real state store. */
|
||||
public final class TestWorld implements PackWorld, AutoCloseable {
|
||||
private final WorldStates states;
|
||||
private final ModuleLog log;
|
||||
|
||||
public TestWorld() {
|
||||
this(new WorldStates(), ModuleLogs.discarding());
|
||||
}
|
||||
|
||||
private TestWorld(WorldStates states, ModuleLog log) {
|
||||
this.states = states;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long seed() {
|
||||
return TestContexts.SEED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackResources resources() {
|
||||
throw new AssertionError("Unused resources");
|
||||
}
|
||||
|
||||
@Override
|
||||
public PackSettings settings() {
|
||||
return new PackSettings() {
|
||||
public <F extends IrisFeature> SettingsStack<F> declared(Class<F> featureType) {
|
||||
return SettingsStack.empty();
|
||||
}
|
||||
|
||||
public PackResources resources() {
|
||||
return TestWorld.this.resources();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public int minWorldY() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RunningWorld> running() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Placements placements() {
|
||||
throw new AssertionError("Unused placements");
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create) {
|
||||
return states.state(type, () -> create.apply(this));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModuleLog log() {
|
||||
return log;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
states.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package example.builtin;
|
||||
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.ModuleSetup;
|
||||
import com.volmit.stage.PlacementStage;
|
||||
import com.volmit.stage.Stage;
|
||||
|
||||
/** A built-in module outside the API's package, like the engine modules inside Iris. Pack jars can
|
||||
* require its stages only when the host exposes this package.
|
||||
*/
|
||||
public final class CarveModule implements IrisModule {
|
||||
public static final PlacementStage<Void> CLEAR = Stage.placement("iris:carve/clear");
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("iris:carve", "Carve", "test");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setup(ModuleSetup setup) {
|
||||
setup.stages().define(CLEAR).run(context -> {});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user