Batch 4 of the API review: api and host artifacts, ModuleLoadException

- Split into Gradle subprojects api (com.volmit:iris-api) and host
  (com.volmit:iris-host). ExposedPackages never exposes com.volmit.host.
- One unchecked ModuleLoadException(moduleId, origin, message, cause)
  for every load error; messages unchanged.
- PlacementAccess.set(x, y, z, state) next to set(PlacedBlock).
- BlockState: precompiled patterns, withProperty copies once.
- Mantle and layer views are made once per invocation.
- Hunk getters are width(), height(), depth().
- Held types and host types are deprecated for removal at the cut-over.
- Docs: artifacts, one-or-more modules per jar, no option shorthand.
This commit is contained in:
piexel committed 2026-10-24 04:19:39 +02:00
1 parent 3a307b5b8e
commit b6c2992752
309 files changed
+547 -178

No files matched your search

@@ -0,0 +1,88 @@
package com.volmit.host;
import com.volmit.hunk.Hunk;
import java.util.Arrays;
import java.util.Objects;
/** Reference dense volume with checked local coordinates and non-null values.
* Each invocation owns its volume; concurrent writes to the same volume are unsupported.
*/
public final class ArrayHunk<T> implements Hunk<T> {
private final Class<T> type;
private final int width;
private final int height;
private final int depth;
private final Object[] values;
public ArrayHunk(Class<T> type, int width, int height, int depth, T initial) {
this.type = Objects.requireNonNull(type, "type");
if (type.isPrimitive()) {
throw new IllegalArgumentException("Hunk requires a reference type");
}
validateDimensions(width, height, depth);
this.width = width;
this.height = height;
this.depth = depth;
values = new Object[valueCount(width, height, depth)];
Arrays.fill(values, type.cast(Objects.requireNonNull(initial, "initial")));
}
public int width() {
return width;
}
public int height() {
return height;
}
public int depth() {
return depth;
}
public T get(int x, int y, int z) {
return type.cast(values[index(x, y, z)]);
}
public void set(int x, int y, int z, T value) {
int valueIndex = index(x, y, z);
values[valueIndex] = type.cast(Objects.requireNonNull(value, "value"));
}
private static void validateDimensions(int width, int height, int depth) {
if (width < 0) {
throw negativeDimension();
}
if (height < 0) {
throw negativeDimension();
}
if (depth < 0) {
throw negativeDimension();
}
}
private static IllegalArgumentException negativeDimension() {
return new IllegalArgumentException("Negative hunk dimension");
}
private static int valueCount(int width, int height, int depth) {
return Math.multiplyExact(Math.multiplyExact(width, height), depth);
}
private int index(int x, int y, int z) {
if (x < 0 || x >= width) {
throw outOfBounds(x, y, z);
}
if (y < 0 || y >= height) {
throw outOfBounds(x, y, z);
}
if (z < 0 || z >= depth) {
throw outOfBounds(x, y, z);
}
return (y * depth + z) * width + x;
}
private static IndexOutOfBoundsException outOfBounds(int x, int y, int z) {
return new IndexOutOfBoundsException("Local hunk position: " + x + "," + y + "," + z);
}
}
@@ -0,0 +1,92 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
import com.volmit.stage.BlockCollector;
import com.volmit.stage.BlockStageContext;
import com.volmit.stage.BlockStageDefinition;
import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageRef;
import java.util.Objects;
import java.util.function.Supplier;
/** Builder behind {@link BlockStageDefinition}. */
final class BlockStageDraft<O> implements BlockStageDefinition<O> {
private final StageDeclaration declaration;
BlockStageDraft(StageDeclaration declaration) {
this.declaration = declaration;
}
@Override
public BlockStageDraft<O> requires(Stage<?>... stages) {
declaration.require(stages);
return this;
}
@Override
public BlockStageDraft<O> softAfter(Stage<?>... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public BlockStageDraft<O> softAfter(StageRef... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public BlockStageDraft<O> softBefore(Stage<?>... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public BlockStageDraft<O> softBefore(StageRef... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public BlockStageDraft<O> reach(int blocks) {
declaration.reach(blocks);
return this;
}
@Override
public BlockStageDraft<O> writesMantle(MantleKey<?>... layers) {
declaration.writesMantle(layers);
return this;
}
@Override
public BlockStageDraft<O> when(Class<? extends IrisFeature> settingsType) {
declaration.condition(settingsType);
return this;
}
@Override
public void run(StageAction<BlockStageContext> action) {
Objects.requireNonNull(action, "action");
complete(null, (context, accumulator) -> action.run(context));
}
@Override
public void accumulate(Supplier<O> initial, BlockCollector<O> collector) {
Objects.requireNonNull(collector, "collector");
complete(Objects.requireNonNull(initial, "initial"),
(context, accumulator) -> collector.collect(context, cast(accumulator)));
}
private void complete(Supplier<?> initial, StageBody.BlockWork work) {
boolean accumulates = initial != null;
declaration.complete(new StageBody.Block(initial, work), accumulates, accumulates ? "run" : "accumulate");
}
@SuppressWarnings("unchecked") // The executor passes the accumulator this stage was declared with.
private static <T> T cast(Object value) {
return (T) value;
}
}
@@ -0,0 +1,89 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings;
import com.volmit.config.SettingsStack;
import com.volmit.generation.GenerationContext;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.random.WorldRandom;
import com.volmit.world.PackWorld;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.TerrainSampler;
import java.util.Objects;
import java.util.Optional;
/** The context every stage of one chunk invocation receives. The mantle is writable in the chunk's own columns only;
* its view is made once, on first use.
*/
final class ChunkInvocation implements ChunkStageContext {
private final StageInvocation stages;
private final GenerationContext inputs;
private ChunkMantle mantle;
ChunkInvocation(StageInvocation stages, GenerationContext inputs) {
this.stages = stages;
this.inputs = Objects.requireNonNull(inputs, "inputs");
}
StageInvocation stages() {
return stages;
}
@Override
public <O> O output(Stage<O> stage) {
return stages.output(stage);
}
@Override
public <S extends IrisFeature> SettingsStack<S> configured(Class<S> settingsType) {
return stages.configured(settingsType);
}
@Override
public int originX() {
return inputs.originX();
}
@Override
public int originZ() {
return inputs.originZ();
}
@Override
public TerrainSampler terrain() {
return inputs.terrain();
}
@Override
public FeatureSettings settings() {
return inputs.settings();
}
@Override
public Mantle mantle() {
if (mantle == null) mantle = new ChunkMantle(inputs.mantle(), inputs.originX(), inputs.originZ());
return mantle;
}
@Override
public <T> Hunk<T> hunk(Class<T> type) {
return inputs.hunk(type);
}
@Override
public PackWorld world() {
return stages.world(inputs.world());
}
@Override
public <T> Optional<T> extension(Class<T> type) {
return inputs.extension(type);
}
@Override
public WorldRandom random() {
return stages.random();
}
}
@@ -0,0 +1,137 @@
package com.volmit.host;
import com.volmit.block.BlockState;
import com.volmit.generation.ChunkContext;
import com.volmit.mantle.BlockBox;
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 java.util.HashMap;
import java.util.Map;
/** The mantle as chunk stages see it: reads pass through everywhere the host's mantle reaches, writes to module layers
* only inside the chunk's own 16 by 16 columns. The mantle pipeline has finished around the chunk by then, and its
* neighbours may already be generated, so their mantle stays as the pipeline left it. The host's blocks are read-only.
* One view per chunk invocation, which keeps its layer views.
*/
final class ChunkMantle implements Mantle {
private static final String NEIGHBOUR_WRITE = "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";
private static final String HOST_BLOCKS = "The mantle's blocks are written by placements, not by stages";
private final Mantle mantle;
private final BlockBox ownChunk;
private final Map<MantleKey<?>, MantleLayer<?>> layers = new HashMap<>();
private MantleLayer<BlockState> blocks;
ChunkMantle(Mantle mantle, int originX, int originZ) {
this.mantle = mantle;
BlockBox bounds = mantle.bounds();
this.ownChunk = new BlockBox(originX, bounds.minY(), originZ, originX + ChunkContext.CHUNK_WIDTH, bounds.maxY(),
originZ + ChunkContext.CHUNK_WIDTH);
}
@Override
public BlockBox bounds() {
return mantle.bounds();
}
@Override
@SuppressWarnings("unchecked")
public <T> MantleLayer<T> layer(MantleKey<T> key) {
return (MantleLayer<T>) layers.computeIfAbsent(key, _ -> new OwnChunkLayer<>(mantle.layer(key)));
}
@Override
public MantleLayer<BlockState> blocks() {
if (blocks == null) blocks = new ReadOnlyLayer<>(mantle.blocks());
return blocks;
}
@Override
public boolean isCarved(int x, int y, int z) {
return mantle.isCarved(x, y, z);
}
@Override
public MantleEdit edit() {
throw new UnsupportedOperationException("Chunk stages write mantle layers directly, without an edit");
}
private void requireOwnChunk(int x, int y, int z) {
if (!ownChunk.contains(x, y, z)) {
throw new UnsupportedOperationException(NEIGHBOUR_WRITE + "; " + x + "," + y + "," + z + " is outside " + ownChunk);
}
}
private void requireOwnChunk(BlockBox area) {
if (!ownChunk.contains(area)) {
throw new UnsupportedOperationException(NEIGHBOUR_WRITE + "; " + area + " reaches outside " + ownChunk);
}
}
private final class OwnChunkLayer<T> implements MantleLayer<T> {
private final MantleLayer<T> layer;
OwnChunkLayer(MantleLayer<T> layer) {
this.layer = layer;
}
@Override
public T get(int x, int y, int z) {
return layer.get(x, y, z);
}
@Override
public void set(int x, int y, int z, T value) {
requireOwnChunk(x, y, z);
layer.set(x, y, z, value);
}
@Override
public void remove(int x, int y, int z) {
requireOwnChunk(x, y, z);
layer.remove(x, y, z);
}
@Override
public void visit(BlockBox area, MantleVisitor<T> visitor) {
layer.visit(area, visitor);
}
@Override
public void clear(BlockBox area) {
requireOwnChunk(area);
layer.clear(area);
}
}
private record ReadOnlyLayer<T>(MantleLayer<T> layer) implements MantleLayer<T> {
@Override
public T get(int x, int y, int z) {
return layer.get(x, y, z);
}
@Override
public void set(int x, int y, int z, T value) {
throw new UnsupportedOperationException(HOST_BLOCKS);
}
@Override
public void remove(int x, int y, int z) {
throw new UnsupportedOperationException(HOST_BLOCKS);
}
@Override
public void visit(BlockBox area, MantleVisitor<T> visitor) {
layer.visit(area, visitor);
}
@Override
public void clear(BlockBox area) {
throw new UnsupportedOperationException(HOST_BLOCKS);
}
}
}
@@ -0,0 +1,46 @@
package com.volmit.host;
import com.volmit.generation.GenerationContext;
import com.volmit.stage.Pipeline;
import java.util.Objects;
/** Reference executor of a resolved chunk graph: active stages run once, in resolved order.
* It does not schedule neighbors or roll back hunks; a failed invocation must prevent the host
* from publishing the chunk. Stages write the mantle in the chunk's own columns only.
*/
public final class ChunkRunner {
private final ResolvedGraph graph;
public ChunkRunner(ResolvedGraph graph) {
this.graph = Objects.requireNonNull(graph, "graph");
if (graph.pipeline() != Pipeline.CHUNK) {
throw new IllegalArgumentException("Expected a chunk graph, got " + graph.pipeline());
}
}
/** Runs one chunk and reports to {@code timings} how long each stage that ran took. A conditional stage is active
* when any of the chunk's 16 by 16 columns has an entry of its settings in {@code inputs.settings()}, and reads
* every distinct entry of those columns. The host derives {@code invocationSeed} from the world seed and the chunk
* position; each stage draws from its own stream of that seed ({@link StageStreams}).
*/
public void generate(GenerationContext inputs, long invocationSeed, StageTimings timings) {
Objects.requireNonNull(timings, "timings");
if (graph.size() == 0) {
return;
}
var settings = ChunkSettings.collect(graph.settingsTypes(), inputs::settings, inputs.originX(), inputs.originZ());
var chunk = new ChunkInvocation(new StageInvocation(graph, invocationSeed, settings), inputs);
for (int position = 0; position < graph.size(); position++) {
runTimed(chunk, position, timings);
}
}
private void runTimed(ChunkInvocation chunk, int position, StageTimings timings) {
if (!chunk.stages().isActive(position)) {
return;
}
long started = System.nanoTime();
chunk.stages().runInvocationStage(position, chunk);
timings.record(graph.stages().get(position), System.nanoTime() - started);
}
}
@@ -0,0 +1,32 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings;
import com.volmit.config.SettingsStack;
import com.volmit.generation.ChunkContext;
import java.util.HashMap;
import java.util.List;
import java.util.function.Supplier;
/** The settings one chunk's stages see: for every settings type the running stages condition on, each
* distinct entry of the chunk's 16 by 16 columns ({@link FeatureSettings#declaredInChunk}). A stage is therefore
* active when any column of the chunk configures its settings, also where a biome border crosses the chunk.
*/
final class ChunkSettings {
private ChunkSettings() {}
/** {@code settings} is asked only when {@code types} is not empty. */
static ConfiguredSettings collect(List<Class<?>> types, Supplier<FeatureSettings> settings, int originX, int originZ) {
if (types.isEmpty()) {
return ConfiguredSettings.none();
}
var view = settings.get();
int chunkX = Math.floorDiv(originX, ChunkContext.CHUNK_WIDTH);
int chunkZ = Math.floorDiv(originZ, ChunkContext.CHUNK_WIDTH);
var stacks = new HashMap<Class<?>, SettingsStack<?>>();
for (var type : types) {
stacks.put(type, view.declaredInChunk(type.asSubclass(IrisFeature.class), chunkX, chunkZ));
}
return ConfiguredSettings.ofStacks(stacks);
}
}
@@ -0,0 +1,64 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.ChunkStageDefinition;
import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageFunction;
import com.volmit.stage.StageRef;
/** Builder behind {@link ChunkStageDefinition}. */
final class ChunkStageDraft<O> implements ChunkStageDefinition<O> {
private final StageDeclaration declaration;
ChunkStageDraft(StageDeclaration declaration) {
this.declaration = declaration;
}
@Override
public ChunkStageDraft<O> requires(Stage<?>... stages) {
declaration.require(stages);
return this;
}
@Override
public ChunkStageDraft<O> softAfter(Stage<?>... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public ChunkStageDraft<O> softAfter(StageRef... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public ChunkStageDraft<O> softBefore(Stage<?>... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public ChunkStageDraft<O> softBefore(StageRef... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public ChunkStageDraft<O> when(Class<? extends IrisFeature> settingsType) {
declaration.condition(settingsType);
return this;
}
@Override
public void run(StageAction<ChunkStageContext> action) {
declaration.run(action);
}
@Override
public void produce(StageFunction<ChunkStageContext, O> function) {
declaration.produce(function);
}
}
@@ -0,0 +1,71 @@
package com.volmit.host;
import java.lang.classfile.ClassFile;
import java.lang.classfile.constantpool.ClassEntry;
import java.lang.classfile.constantpool.MethodTypeEntry;
import java.lang.classfile.constantpool.NameAndTypeEntry;
import java.lang.classfile.constantpool.PoolEntry;
import java.lang.constant.ClassDesc;
import java.lang.constant.MethodTypeDesc;
import java.util.Collections;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
/** The classes one class file links against, as binary names: every class in its constant pool
* (supertypes, instantiated, cast, caught and called-on types) and every type in the descriptors of
* its fields, methods and the members it uses. Arrays count as their element type; primitives do
* not count.
*
* <p>Annotations and generic signatures are left out. The JVM never resolves them while linking,
* and reflection skips annotations whose type is missing.
*/
final class ClassReferences {
private static final String METHOD_DESCRIPTOR_START = "(";
private ClassReferences() {}
/** Throws {@link IllegalArgumentException} when the bytes are not a valid class file. */
static SortedSet<String> read(byte[] classFile) {
var model = ClassFile.of().parse(classFile);
var references = new TreeSet<String>();
for (var entry : model.constantPool()) addPoolEntry(entry, references);
model.fields().forEach(field -> addType(field.fieldTypeSymbol(), references));
model.methods().forEach(method -> addMethodType(method.methodTypeSymbol(), references));
return Collections.unmodifiableSortedSet(references);
}
private static void addPoolEntry(PoolEntry entry, Set<String> references) {
switch (entry) {
case ClassEntry type -> addType(type.asSymbol(), references);
case NameAndTypeEntry member -> addDescriptor(member.type().stringValue(), references);
case MethodTypeEntry methodType -> addMethodType(methodType.asSymbol(), references);
default -> {}
}
}
private static void addDescriptor(String descriptor, Set<String> references) {
if (descriptor.startsWith(METHOD_DESCRIPTOR_START)) {
addMethodType(MethodTypeDesc.ofDescriptor(descriptor), references);
} else {
addType(ClassDesc.ofDescriptor(descriptor), references);
}
}
private static void addMethodType(MethodTypeDesc type, Set<String> references) {
addType(type.returnType(), references);
type.parameterList().forEach(parameter -> addType(parameter, references));
}
private static void addType(ClassDesc type, Set<String> references) {
var element = type;
while (element.isArray()) element = element.componentType();
if (element.isPrimitive()) return;
references.add(binaryName(element));
}
private static String binaryName(ClassDesc type) {
var descriptor = type.descriptorString();
return descriptor.substring(1, descriptor.length() - 1).replace('/', '.');
}
}
@@ -0,0 +1,87 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.config.Level;
import com.volmit.config.SettingsStack;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/** The settings configured for one invocation, one {@link SettingsStack} per settings type. A stage
* conditioned on a type is active when its stack is not empty, and reads it with
* {@link com.volmit.stage.StageContext#configured}. For a placement these are the placement's own declarations; for
* a chunk the runners collect every distinct entry of the chunk's columns themselves. Entries are grouped by their
* declared settings type ({@link FeatureDescriptor#declaredType}), so a value of a subclass counts as the type it is
* declared as. Build once and reuse it for every invocation with the same configuration.
*/
public final class ConfiguredSettings {
private static final ConfiguredSettings NONE = new ConfiguredSettings(Map.of());
private final Map<Class<?>, SettingsStack<?>> stacks;
private ConfiguredSettings(Map<Class<?>, SettingsStack<?>> stacks) {
this.stacks = Map.copyOf(stacks);
}
public static ConfiguredSettings none() {
return NONE;
}
/** These entries, grouped by declared settings type, each group in level order and otherwise as given. */
public static ConfiguredSettings of(List<? extends Entry<?>> entries) {
var grouped = new HashMap<Class<?>, List<Entry<?>>>();
for (var entry : entries) {
Objects.requireNonNull(entry, "entry");
grouped.computeIfAbsent(FeatureDescriptor.declaredType(entry.value().getClass()), ignored -> new ArrayList<>()).add(entry);
}
if (grouped.isEmpty()) {
return NONE;
}
var stacks = new HashMap<Class<?>, SettingsStack<?>>();
grouped.forEach((type, group) -> stacks.put(type, stackOf(group)));
return new ConfiguredSettings(stacks);
}
/** The stacks of these types, each kept under its own type; empty stacks are left out. */
static ConfiguredSettings ofStacks(Map<Class<?>, SettingsStack<?>> stacks) {
var configured = new HashMap<Class<?>, SettingsStack<?>>();
stacks.forEach((type, stack) -> {
if (!stack.isEmpty()) {
configured.put(type, stack);
}
});
return configured.isEmpty() ? NONE : new ConfiguredSettings(configured);
}
/** One placement's own settings, at most one value per declared type, declared by {@code source}. */
public static ConfiguredSettings placement(ResourceId source, IrisFeature... settings) {
Objects.requireNonNull(source, "source");
var entries = new ArrayList<Entry<?>>();
var types = new HashMap<Class<?>, IrisFeature>();
for (var value : settings) {
Objects.requireNonNull(value, "settings");
var declared = FeatureDescriptor.declaredType(value.getClass());
if (types.putIfAbsent(declared, value) != null) {
throw new IllegalArgumentException("Settings configured twice: " + declared.getName());
}
entries.add(new Entry<>(Level.PLACEMENT, source, value));
}
return of(entries);
}
/** The stack of {@code type}; empty when nothing configures it. */
@SuppressWarnings("unchecked") // Stacks are grouped by the declared type of their values.
public <S extends IrisFeature> SettingsStack<S> find(Class<S> type) {
var found = stacks.get(type);
return found == null ? SettingsStack.empty() : (SettingsStack<S>) found;
}
@SuppressWarnings({"unchecked", "rawtypes"}) // A group holds entries of one declared type.
private static SettingsStack<?> stackOf(List<Entry<?>> group) {
return SettingsStack.of((List) group);
}
}
@@ -0,0 +1,55 @@
package com.volmit.host;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.lang.classfile.ClassFile;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/** Orders a class's own fields as its source declares them. {@link Class#getDeclaredFields()} promises
* no order, but the class file lists fields in declaration order, so this reads it.
*/
final class DeclaredFieldOrder {
private static final String CLASS_FILE_SUFFIX = ".class";
private DeclaredFieldOrder() {}
static List<Field> of(Class<?> type) {
var names = fieldNames(type);
return Arrays.stream(type.getDeclaredFields())
.sorted(Comparator.comparingInt((Field field) -> position(names, field, type)))
.toList();
}
private static int position(List<String> names, Field field, Class<?> type) {
int position = names.indexOf(field.getName());
if (position < 0) {
throw new IllegalArgumentException("Field " + field.getName() + " of " + type.getName()
+ " is not in its class file, so its declaration order is unknown");
}
return position;
}
private static List<String> fieldNames(Class<?> type) {
try (var classFile = openClassFile(type)) {
return ClassFile.of().parse(classFile.readAllBytes()).fields().stream()
.map(field -> field.fieldName().stringValue())
.toList();
} catch (IOException failure) {
throw new UncheckedIOException("Cannot read the class file of " + type.getName(), failure);
}
}
private static InputStream openClassFile(Class<?> type) {
var resource = "/" + type.getName().replace('.', '/') + CLASS_FILE_SUFFIX;
var stream = type.getResourceAsStream(resource);
if (stream == null) {
throw new IllegalArgumentException("Cannot read the class file of " + type.getName()
+ " to order its options as declared; settings classes must come from a jar or a class directory");
}
return stream;
}
}
@@ -0,0 +1,124 @@
package com.volmit.host;
import com.volmit.block.BlockState;
import com.volmit.host.schema.ValueKind;
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.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 java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
/** Turns a field's default value into the JSON-shaped value {@link com.volmit.host.schema.SchemaOption}
* documents, or empty when it has none. Objects are read through the options of their described
* class, so a subclass instance shows only the declared class's options.
*/
@SuppressWarnings("removal") // host kinds are transitional, until the cut-over
final class DefaultValues {
private final Map<String, TypeDrafts.TypeDraft> types;
private final Set<Object> converting = Collections.newSetFromMap(new IdentityHashMap<>());
DefaultValues(Map<String, TypeDrafts.TypeDraft> types) {
this.types = types;
}
Optional<Object> of(Object value, ValueKind kind) {
if (value == null) return Optional.empty();
return switch (kind) {
case BooleanKind _ -> Optional.of(value);
case IntegerKind _ -> Optional.of(((Number) value).longValue());
case DecimalKind _ -> decimal((Number) value);
case TextKind _, ReferenceKind _, ResourceReferenceKind _ -> Optional.of(text(value));
case EnumKind _ -> Optional.of(((Enum<?>) value).name());
case ListKind list -> list(elements(value), list);
case MapKind map -> map((Map<?, ?>) value, map.value());
case ObjectKind object -> object(value, types.get(object.type()));
case HostKind _, AnyKind _ -> Optional.empty();
};
}
/** A float keeps its own shortest decimal form: 0.1f is 0.1, not 0.10000000149011612. */
private static Optional<Object> decimal(Number value) {
double converted = value instanceof Float single ? Double.parseDouble(Float.toString(single)) : value.doubleValue();
if (!Double.isFinite(converted)) return Optional.empty();
return Optional.of(converted);
}
private static String text(Object value) {
if (value instanceof BlockState state) return state.key();
return value.toString();
}
private static List<?> elements(Object value) {
if (value instanceof Collection<?> collection) return new ArrayList<>(collection);
var elements = new ArrayList<>();
for (int index = 0; index < Array.getLength(value); index++) {
elements.add(Array.get(value, index));
}
return elements;
}
private Optional<Object> list(List<?> elements, ListKind kind) {
var converted = new ArrayList<Object>();
for (var element : elements) {
var value = of(element, kind.element());
if (value.isEmpty()) return Optional.empty();
converted.add(value.get());
}
if (kind.unique()) return sortedSet(converted);
return Optional.of(List.copyOf(converted));
}
/** Set elements are all of one kind; only scalar ones have a natural order to sort by. */
@SuppressWarnings({"unchecked", "rawtypes"})
private static Optional<Object> sortedSet(List<Object> elements) {
if (!elements.stream().allMatch(element -> element instanceof Comparable)) return Optional.empty();
elements.sort((left, right) -> ((Comparable) left).compareTo(right));
return Optional.of(List.copyOf(elements));
}
private Optional<Object> map(Map<?, ?> entries, ValueKind valueKind) {
var converted = new TreeMap<String, Object>();
for (var entry : entries.entrySet()) {
var value = of(entry.getValue(), valueKind);
if (entry.getKey() == null || value.isEmpty()) return Optional.empty();
converted.put((String) entry.getKey(), value.get());
}
return Optional.of(Collections.unmodifiableMap(converted));
}
private Optional<Object> object(Object value, TypeDrafts.TypeDraft type) {
if (!converting.add(value)) return Optional.empty();
var converted = new TreeMap<String, Object>();
for (var option : type.options()) {
of(read(option, value), option.kind()).ifPresent(field -> converted.put(option.option().name(), field));
}
converting.remove(value);
return Optional.of(Collections.unmodifiableMap(converted));
}
/** {@link TypeDrafts} made every option field accessible while reading the class's own defaults. */
private static Object read(TypeDrafts.OptionDraft option, Object instance) {
try {
return option.option().field().get(instance);
} catch (IllegalAccessException impossible) {
throw new IllegalStateException(impossible);
}
}
}
@@ -0,0 +1,99 @@
package com.volmit.host;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleLog;
import java.util.Objects;
/** A module, its identity and where the host found it. Load errors name the origin so the author
* knows which jar to fix.
*
* <p>{@link IrisModule#info()} is read once, when the module is discovered, and only that value is
* used afterwards. A module whose {@code info()} changes between calls cannot give the host
* inconsistent answers.
*/
public final class DiscoveredModule {
static final String HOST_CLASSPATH = "host classpath";
/** Where a module comes from: the host's classpath or a pack jar. */
enum Source { HOST, PACK }
private final IrisModule module;
private final ModuleInfo info;
private final String origin;
private final Source source;
private final ModuleLog log;
private DiscoveredModule(IrisModule module, ModuleInfo info, String origin, Source source, ModuleLog log) {
this.module = Objects.requireNonNull(module, "module");
this.info = Objects.requireNonNull(info, "info");
this.origin = Objects.requireNonNull(origin, "origin");
this.source = Objects.requireNonNull(source, "source");
this.log = Objects.requireNonNull(log, "log");
if (origin.isBlank()) {
throw new IllegalArgumentException("Blank module origin: " + module.getClass().getName());
}
}
/** A module that ships with the host instead of a pack. Reads its {@code info()}; a failure
* propagates unchanged.
*/
public static DiscoveredModule builtIn(IrisModule module) {
Objects.requireNonNull(module, "module");
var info = readInfo(module);
return new DiscoveredModule(module, info, HOST_CLASSPATH, Source.HOST, defaultLog(info));
}
/** A pack module whose {@code info()} the jar loader has already read and checked. */
static DiscoveredModule fromJar(IrisModule module, ModuleInfo info, String origin) {
return new DiscoveredModule(module, info, origin, Source.PACK, defaultLog(info));
}
private static ModuleLog defaultLog(ModuleInfo info) {
return ModuleLogs.labelled(info.id().toString(), PackModules.DEFAULT_LOGGER);
}
private static ModuleInfo readInfo(IrisModule module) {
return Objects.requireNonNull(module.info(), () -> "info() of " + module.getClass().getName() + " returned null");
}
public IrisModule module() {
return module;
}
/** The module's identity, as {@code info()} returned it at discovery. */
public ModuleInfo info() {
return info;
}
/** This module with a log of its own that writes to {@code logger}; the module keeps no keys of the log it had
* ({@link ModuleLog#warnOnce}). The host does it once for a module it hands out.
*/
public DiscoveredModule loggingTo(System.Logger logger) {
return new DiscoveredModule(module, info, origin, source, ModuleLogs.labelled(info.id().toString(), logger));
}
/** The module's own log, labelled with its id. */
public ModuleLog log() {
return log;
}
/** The jar path relative to the pack, a bundled jar's name, or "host classpath" for built-in modules. */
public String origin() {
return origin;
}
/** The origin and the module's class, which tells apart two modules of one jar. */
String locationWithClass() {
return origin + " (" + module.getClass().getName() + ")";
}
Source source() {
return source;
}
@Override
public String toString() {
return info.id() + " from " + origin;
}
}
@@ -0,0 +1,31 @@
package com.volmit.host;
import com.volmit.stage.Stage;
/** Execution data of one resolved stage. Indices are positions in the resolved order.
* readableStages/readablePositions are the transitive requirements whose outputs it may read.
* settingsSlot indexes the graph's distinct settings types, or is NO_SETTINGS. idHash keys the
* stage's random stream ({@link StageStreams}), computed once per pack load. worlds gives the world as the module
* that defined the stage sees it, shared by that module's stages.
*/
record ExecutableStage(
Stage<?> stage,
StageBody body,
int[] requirements,
Stage<?>[] readableStages,
int[] readablePositions,
int settingsSlot,
long idHash,
ScopedWorlds worlds) {
static final int NO_SETTINGS = -1;
static final int NOT_READABLE = -1;
int readablePosition(Stage<?> requested) {
for (int index = 0; index < readableStages.length; index++) {
if (readableStages[index] == requested) {
return readablePositions[index];
}
}
return NOT_READABLE;
}
}
@@ -0,0 +1,90 @@
package com.volmit.host;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Objects;
/** Parent of every pack class loader. It shows a pack the exposed host packages and the JDK and
* nothing else: classes in an {@link ExposedPackages exposed package}, always including the Iris
* API, come from the host's loader, every other class from the platform class loader. Iris
* internals and the libraries Iris bundles stay hidden even though they sit in the host's loader,
* so a module can use only the exposed packages, the JDK and the classes of its own pack's jars.
*
* <p>Resources follow the same rule, by path: {@code com/volmit/...} and the paths of other
* exposed packages from the host's loader, everything else from the platform loader. A class and
* its class file therefore always come from the same place, and a pack never sees Iris's own
* resources, such as its service files.
*
* <p>This loader defines no classes itself.
*/
final class ExposedHostClassLoader extends ClassLoader {
private static final String CLASS_FILE_SUFFIX = ".class";
private static final String NAME = "iris-exposed-host-and-jdk";
static {
registerAsParallelCapable();
}
private final ClassLoader hostLoader;
private final ExposedPackages exposed;
private final HostClassesLeftOut leftOut;
/** {@code hostLoader} is the loader that defines the API; in production the Iris plugin's. */
ExposedHostClassLoader(ClassLoader hostLoader, ExposedPackages exposed) {
this(hostLoader, exposed, HostClassesLeftOut.none());
}
/** For a build that checks a jar against more classes than the real host has: {@code leftOut} names the
* classes the real host's loader lacks, which {@link #hasClass} then denies and {@link #leavesOut} reports.
*/
ExposedHostClassLoader(ClassLoader hostLoader, ExposedPackages exposed, HostClassesLeftOut leftOut) {
super(NAME, ClassLoader.getPlatformClassLoader());
this.hostLoader = Objects.requireNonNull(hostLoader, "hostLoader");
this.exposed = Objects.requireNonNull(exposed, "exposed");
this.leftOut = Objects.requireNonNull(leftOut, "leftOut");
}
ExposedPackages exposed() {
return exposed;
}
/** Whether this loader can load the class, judged by its class file so that nothing is loaded. */
boolean hasClass(String binaryName) {
return !leavesOut(binaryName) && getResource(classFile(binaryName)) != null;
}
/** Whether the real host lacks the class although the loader a build checks against has it. */
boolean leavesOut(String binaryName) {
return leftOut.leavesOut(binaryName);
}
/** Whether the host's loader has the class, whether or not this loader shows it to packs. In
* production that loader also holds Iris internals and the libraries Iris bundles.
*/
boolean hostHasClass(String binaryName) {
return hostLoader.getResource(classFile(binaryName)) != null;
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (exposed.exposes(name)) return hostLoader.loadClass(name);
return super.loadClass(name, resolve);
}
@Override
public URL getResource(String name) {
if (exposed.exposesResource(name)) return hostLoader.getResource(name);
return super.getResource(name);
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
if (exposed.exposesResource(name)) return hostLoader.getResources(name);
return super.getResources(name);
}
private static String classFile(String binaryName) {
return binaryName.replace('.', '/') + CLASS_FILE_SUFFIX;
}
}
@@ -0,0 +1,84 @@
package com.volmit.host;
import com.volmit.IrisModule;
import com.volmit.PackageName;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.TreeSet;
/** The host packages pack modules may use: always the Iris API, plus whatever the host adds, such
* as the packages of built-in modules whose stages packs may require. A package is exposed with
* all its subpackages, and only whole package names match: {@code com.volmit} does not expose
* {@code com.volmitx}. The host side of IrisApi, {@code com.volmit.host}, lies inside the API's
* root package but is never exposed: it loads and runs modules, and no module may reach it.
*/
final class ExposedPackages {
/** The root package of the Iris API. Module classes must not use it. */
static final String API_PACKAGE = IrisModule.class.getPackageName();
/** The host side of IrisApi, which packs never see, though it lies inside {@link #API_PACKAGE}. */
static final String HOST_PACKAGE = ExposedPackages.class.getPackageName();
private static final PackageName API = new PackageName(API_PACKAGE);
private static final PackageName HOST = new PackageName(HOST_PACKAGE);
private static final char PACKAGE_SEPARATOR = '.';
private static final char PATH_SEPARATOR = '/';
private final List<PackageName> packages;
private ExposedPackages(List<PackageName> packages) {
this.packages = List.copyOf(packages);
}
static ExposedPackages apiOnly() {
return apiAnd(List.of());
}
/** The API plus {@code hostPackages}. A trailing dot is accepted; anything that is not a package
* name, such as a blank string or a wildcard, is rejected.
*/
static ExposedPackages apiAnd(Collection<String> hostPackages) {
Objects.requireNonNull(hostPackages, "hostPackages");
var packages = new TreeSet<PackageName>();
packages.add(API);
hostPackages.forEach(name -> packages.add(requireExposable(requirePackageName(name))));
return new ExposedPackages(List.copyOf(packages));
}
/** Whether the class lies in the API's root package, the hidden host side included; module classes must not. */
static boolean isApiClass(String binaryName) {
return API.contains(binaryName);
}
boolean exposes(String binaryName) {
return !HOST.contains(binaryName) && packages.stream().anyMatch(name -> name.contains(binaryName));
}
/** Whether a resource path, such as {@code com/volmit/IrisModule.class}, lies in an exposed package. */
boolean exposesResource(String path) {
return exposes(path.replace(PATH_SEPARATOR, PACKAGE_SEPARATOR));
}
/** The exposed package a class is in; the most specific one when exposed packages nest. */
String packageOf(String binaryName) {
return packages.stream()
.filter(name -> name.contains(binaryName))
.map(PackageName::name)
.max(Comparator.comparingInt(String::length))
.orElseThrow(() -> new IllegalArgumentException(binaryName + " is not in an exposed package"));
}
private static PackageName requireExposable(PackageName name) {
if (name.equals(HOST) || HOST.contains(name.name())) {
throw new IllegalArgumentException("Exposed package '" + name + "' is IrisApi's host side, which packs never see");
}
return name;
}
private static PackageName requirePackageName(String name) {
Objects.requireNonNull(name, "exposed package");
return PackageName.tryParse(name).orElseThrow(() -> new IllegalArgumentException("Exposed package '" + name
+ "' is not a package name; name a package such as art.arcane.iris.engine, which exposes that package"
+ " and its subpackages"));
}
}
@@ -0,0 +1,177 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.service.Providers;
import com.volmit.service.Service;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators, lifecycle hooks, service
* providers are in module id order, each module's in the order it registered them, so
* nothing depends on discovery. Factory, codec, validator, hook and provider implementations must themselves obey their
* concurrency contracts.
*/
@SuppressWarnings("removal") // held types are transitional, until the cut-over
public final class FeatureCatalog {
/** Services are asked for on the generation hot path, so each type's annotation is read once. */
private static final ClassValue<Providers> SERVICE_PROVIDERS = new ClassValue<>() {
@Override
protected Providers computeValue(Class<?> type) {
var service = type.isInterface() ? type.getAnnotation(Service.class) : null;
if (service == null) {
throw new IllegalArgumentException(type.getName() + " is not a service: services are interfaces marked @"
+ Service.class.getName());
}
return service.value();
}
};
private final Map<Class<?>, FeatureDescriptor<?>> settings;
private final Map<Class<?>, ObjectRegistration<?>> objects;
private final Map<String, MantleRegistration<?>> mantle;
private final List<ResourceKindRegistration> resourceKinds;
private final List<HeldTypeRegistration> heldTypes;
private final List<ValidatorRegistration> validators;
private final List<LifecycleRegistration> lifecycles;
private final Map<Class<?>, List<ServiceRegistration>> registrationsByService;
private final Map<Class<?>, List<?>> providersByService;
FeatureCatalog(
Map<Class<?>, FeatureDescriptor<?>> settings,
Map<Class<?>, ObjectRegistration<?>> objects,
Map<String, MantleRegistration<?>> mantle,
Collection<ResourceKindRegistration> resourceKinds,
Collection<HeldTypeRegistration> heldTypes,
List<ValidatorRegistration> validators,
List<LifecycleRegistration> lifecycles,
List<ServiceRegistration> services) {
this.settings = Map.copyOf(settings);
this.objects = Map.copyOf(objects);
this.mantle = Map.copyOf(mantle);
this.resourceKinds = sorted(resourceKinds, registration -> registration.kind().id());
this.heldTypes = sorted(heldTypes, registration -> registration.type().getName());
this.validators = inModuleOrder(validators, ValidatorRegistration::module);
this.lifecycles = inModuleOrder(lifecycles, LifecycleRegistration::module);
this.registrationsByService = byService(inModuleOrder(services, ServiceRegistration::module));
this.providersByService = providersByService(registrationsByService);
}
/** Settings types that activate stages; the host decodes them from pack JSON. */
public List<FeatureDescriptor<?>> settings() {
return sorted(settings.values(), FeatureDescriptor::id);
}
public List<ObjectRegistration<?>> objects() {
return sorted(objects.values(), registration -> registration.descriptor().id());
}
public List<MantleRegistration<?>> mantle() {
return sorted(mantle.values(), registration -> registration.key().id());
}
/** The pack resource kinds modules read, by kind id. */
public List<ResourceKindRegistration> resourceKinds() {
return resourceKinds;
}
/** The classes built-in modules described because Iris's own classes hold them, by class name.
*
* @deprecated Transitional, until the cut-over; see {@link com.volmit.FeatureRegistry#registerHeldType}.
*/
@Deprecated(forRemoval = true)
public List<HeldTypeRegistration> heldTypes() {
return heldTypes;
}
/** The validators modules registered, by module id, each module's in the order it registered them. */
public List<ValidatorRegistration> validators() {
return validators;
}
/** The lifecycle hooks modules registered, by module id, each module's in the order it registered them. */
public List<LifecycleRegistration> lifecycles() {
return lifecycles;
}
/** Every provider of {@code service}, an interface marked {@link Service}, in module id order and each module's in the
* order it registered them; empty when no module provides it.
*/
@SuppressWarnings("unchecked") // ModuleRegistry.registerService checked that every provider implements its service.
public <S> List<S> services(Class<S> service) {
var providers = providersByService.get(service);
if (providers == null) {
providersOf(service);
return List.of();
}
return (List<S>) providers;
}
/** Every provider of {@code service} with the module that registered it, in the order of {@link #services}, so the host
* can name the module whose provider failed.
*/
public List<ServiceRegistration> registrations(Class<?> service) {
var registrations = registrationsByService.get(service);
if (registrations == null) {
providersOf(service);
return List.of();
}
return registrations;
}
/** The one provider of {@code service}, a service whose providers are {@link Providers#ONE}, if a module provides it. */
public <S> Optional<S> service(Class<S> service) {
if (providersOf(service) != Providers.ONE) {
throw new IllegalArgumentException("Service " + service.getName() + " may have several providers; ask for all of"
+ " them with services(...)");
}
var providers = services(service);
return providers.isEmpty() ? Optional.empty() : Optional.of(providers.getFirst());
}
/** How many modules may provide {@code service}, which must be an interface marked {@link Service}. */
static Providers providersOf(Class<?> service) {
return SERVICE_PROVIDERS.get(service);
}
private static Map<Class<?>, List<ServiceRegistration>> byService(List<ServiceRegistration> inModuleOrder) {
return Map.copyOf(inModuleOrder.stream()
.collect(Collectors.groupingBy(ServiceRegistration::service, Collectors.toUnmodifiableList())));
}
private static Map<Class<?>, List<?>> providersByService(Map<Class<?>, List<ServiceRegistration>> registrationsByService) {
var providers = new HashMap<Class<?>, List<?>>();
registrationsByService.forEach((service, registrations) ->
providers.put(service, registrations.stream().map(ServiceRegistration::provider).toList()));
return Map.copyOf(providers);
}
private static <T> List<T> inModuleOrder(List<T> registrations, Function<? super T, DiscoveredModule> module) {
return registrations.stream()
.sorted(Comparator.comparing(registration -> module.apply(registration).info().id()))
.toList();
}
private static <T, K extends Comparable<? super K>> List<T> sorted(
Collection<T> registrations,
Function<? super T, ? extends K> key) {
return registrations.stream()
.sorted(Comparator.comparing(key))
.toList();
}
@SuppressWarnings("unchecked") // The registry key is the factory's feature type.
public <F extends IrisFeature> ObjectRegistration<F> object(Class<F> type) {
var registration = objects.get(type);
if (registration == null) {
throw new NoSuchElementException("No object feature: " + type.getName());
}
return (ObjectRegistration<F>) registration;
}
}
@@ -0,0 +1,138 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.config.Feature;
import com.volmit.config.Level;
import com.volmit.resource.ResourceId;
import java.lang.annotation.IncompleteAnnotationException;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/** Validated settings metadata. It describes configuration, not executable ordering.
*
* @param key the JSON key packs write the settings under at each target; see {@link Feature#key}
* @param root the option whose value the key holds, when the JSON is one option's value instead of an object
* of options; see {@link Feature#root}
* @param targets the levels whose pack files hold the key, at least one
*/
public record FeatureDescriptor<F extends IrisFeature>(
ResourceId id,
String name,
String key,
Optional<String> root,
Class<F> type,
Set<Level> targets,
OptionsMetadata options) {
private static final char NAMESPACE_SEPARATOR = ':';
public FeatureDescriptor {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(name, "name");
if (name.isBlank()) {
throw new IllegalArgumentException("Blank feature name");
}
requireKey(id, key);
Objects.requireNonNull(root, "root");
Objects.requireNonNull(type, "type");
targets = requireTargets(targets);
Objects.requireNonNull(options, "options");
root.ifPresent(option -> requireOnlyOption(type, option, options));
}
/** Checks a JSON field name that is not a feature id: a settings key or a field the host itself uses.
* It is not blank and has no ':', which every feature id has.
*/
public static String requireFieldName(String name) {
Objects.requireNonNull(name, "name");
if (name.isBlank()) {
throw new IllegalArgumentException("Field must not be blank");
}
if (name.indexOf(NAMESPACE_SEPARATOR) >= 0) {
throw new IllegalArgumentException("Field " + name + " contains ':', which only feature ids may contain");
}
return name;
}
private static Set<Level> requireTargets(Set<Level> targets) {
Objects.requireNonNull(targets, "targets");
if (targets.isEmpty()) {
throw new IllegalArgumentException("At least one target is required");
}
return Collections.unmodifiableSet(EnumSet.copyOf(targets));
}
/** Reads the @Feature declaration of a concrete settings class. */
public static <F extends IrisFeature> FeatureDescriptor<F> of(Class<F> type) {
Objects.requireNonNull(type, "featureType");
requireConcreteFeature(type);
var annotation = type.getDeclaredAnnotation(Feature.class);
if (annotation == null) {
throw new IllegalArgumentException("Missing @Feature: " + type.getName());
}
try {
return new FeatureDescriptor<>(
ResourceId.parse(annotation.id()),
annotation.name(),
annotation.key(),
annotation.root().isEmpty() ? Optional.empty() : Optional.of(annotation.root()),
type,
Set.of(annotation.targets()),
OptionsMetadata.inspect(type));
} catch (IncompleteAnnotationException missing) {
throw IncompleteFeatureException.of(type, annotation, missing);
}
}
/** The settings type a value of {@code valueClass} is configured as: the nearest class of its hierarchy that
* declares {@code @Feature}, so a subclass without its own declaration counts as its declared superclass.
*/
public static Class<?> declaredType(Class<?> valueClass) {
return DECLARED_TYPES.get(Objects.requireNonNull(valueClass, "valueClass"));
}
private static final ClassValue<Class<?>> DECLARED_TYPES = new ClassValue<>() {
@Override
protected Class<?> computeValue(Class<?> valueClass) {
for (Class<?> type = valueClass; type != null; type = type.getSuperclass()) {
if (type.getDeclaredAnnotation(Feature.class) != null) {
return type;
}
}
throw new IllegalArgumentException("Missing @Feature: " + valueClass.getName() + " and its superclasses declare none");
}
};
private static void requireKey(ResourceId id, String key) {
try {
requireFieldName(key);
} catch (IllegalArgumentException invalid) {
throw new IllegalArgumentException("Invalid key of feature " + id + ": " + invalid.getMessage()
+ "; a key is a plain JSON field name such as \"deposits\"", invalid);
}
}
private static void requireOnlyOption(Class<?> type, String root, OptionsMetadata options) {
var names = options.options().stream().map(OptionsMetadata.Option::name).toList();
if (names.equals(List.of(root))) {
return;
}
throw new IllegalArgumentException("Feature root '" + root + "' of " + type.getName() + " must name its only option,"
+ " since the JSON under its key is that option's value; its options are " + names);
}
private static void requireConcreteFeature(Class<?> type) {
if (!IrisFeature.class.isAssignableFrom(type)
|| type.isInterface()
|| Modifier.isAbstract(type.getModifiers())) {
throw new IllegalArgumentException(
"Feature type must be a concrete IrisFeature: " + type.getName());
}
}
}
@@ -0,0 +1,18 @@
package com.volmit.host;
import com.volmit.config.PackSettings;
import com.volmit.stage.PackReach;
/** A reach declared as a number during setup, the same for every pack. */
record FixedReach(int blocks) implements PackReach {
static final FixedReach NONE = new FixedReach(0);
FixedReach {
if (blocks < 0) throw new IllegalArgumentException("Negative reach: " + blocks);
}
@Override
public int blocks(PackSettings settings) {
return blocks;
}
}
@@ -0,0 +1,108 @@
package com.volmit.host;
import com.volmit.mantle.MantleKey;
import com.volmit.resource.ResourceId;
import com.volmit.stage.PackReach;
import com.volmit.stage.StageKind;
import java.util.List;
import java.util.stream.Collectors;
/** Text rendering of a resolved graph for pack authors and logs. */
final class GraphDescription {
private static final String INDENT = " ";
private static final String DETAIL_INDENT = " ";
private GraphDescription() {}
static String describe(ResolvedGraph graph) {
var text = new StringBuilder();
var passes = graph.blockPasses();
text.append(graph.pipeline()).append(" pipeline: ")
.append(graph.stages().size()).append(" stages, ")
.append(passes.size()).append(passes.size() == 1 ? " block pass\n" : " block passes\n");
appendOrder(text, graph, passes);
appendBlockPasses(text, passes);
appendUnorderedPairs(text, graph.unorderedPairs());
return text.toString();
}
private static void appendOrder(StringBuilder text, ResolvedGraph graph, List<List<ResourceId>> passes) {
text.append("order:\n");
var stages = graph.stages();
for (int position = 0; position < stages.size(); position++) {
var stage = stages.get(position);
text.append(INDENT).append(position + 1).append(". ").append(stage.stage().id())
.append(" [").append(kindLabel(stage, passes)).append("] module ").append(stage.module());
stage.settings().ifPresent(settings -> text.append(" when ").append(settings.id()));
text.append('\n');
appendEdges(text, stage.incoming(), StageEdge.Kind.REQUIRED, "requires ");
appendEdges(text, stage.incoming(), StageEdge.Kind.SOFT, "soft after ");
appendReach(text, stage.reach());
if (!stage.absentSoftTargets().isEmpty()) {
text.append(DETAIL_INDENT).append("absent soft targets ").append(joined(stage.absentSoftTargets())).append('\n');
}
}
}
private static void appendReach(StringBuilder text, StageReach reach) {
if (reach.equals(StageReach.NONE)) {
return;
}
text.append(DETAIL_INDENT).append("reach ").append(reachText(reach.blocks()));
if (!reach.mantleLayers().isEmpty()) {
text.append(", writes mantle ").append(joined(reach.mantleLayers().stream().map(MantleKey::id).toList()));
}
text.append('\n');
}
private static String reachText(PackReach reach) {
if (!(reach instanceof FixedReach fixed)) {
return "worked out when the pack loads";
}
return fixed.blocks() + (fixed.blocks() == 1 ? " block" : " blocks");
}
private static String kindLabel(ResolvedStage stage, List<List<ResourceId>> passes) {
if (stage.stage().kind() == StageKind.INVOCATION) {
return "invocation";
}
for (int pass = 0; pass < passes.size(); pass++) {
if (passes.get(pass).contains(stage.stage().id())) {
return "block pass " + (pass + 1);
}
}
throw new IllegalStateException("Block stage outside every pass: " + stage.stage());
}
private static void appendEdges(StringBuilder text, List<StageEdge> edges, StageEdge.Kind kind, String label) {
var sources = edges.stream().filter(edge -> edge.kind() == kind).map(StageEdge::from).toList();
if (sources.isEmpty()) {
return;
}
text.append(DETAIL_INDENT).append(label).append(joined(sources)).append('\n');
}
private static void appendBlockPasses(StringBuilder text, List<List<ResourceId>> passes) {
text.append("block passes:\n");
if (passes.isEmpty()) {
text.append(INDENT).append("none\n");
}
for (int pass = 0; pass < passes.size(); pass++) {
text.append(INDENT).append("pass ").append(pass + 1).append(": ").append(joined(passes.get(pass))).append('\n');
}
}
private static void appendUnorderedPairs(StringBuilder text, List<ResolvedGraph.UnorderedPair> pairs) {
text.append("mutually unordered:\n");
if (pairs.isEmpty()) {
text.append(INDENT).append("none\n");
}
for (var pair : pairs) {
text.append(INDENT).append(pair.first()).append(" <-> ").append(pair.second()).append('\n');
}
}
private static String joined(List<?> values) {
return values.stream().map(Object::toString).collect(Collectors.joining(", "));
}
}
@@ -0,0 +1,274 @@
package com.volmit.host;
import com.volmit.ModuleLog;
import com.volmit.resource.ResourceId;
import com.volmit.stage.Pipeline;
import com.volmit.stage.Stage;
import com.volmit.stage.StageKind;
import com.volmit.stage.StageRef;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
/** Validates and orders the stages of one pipeline. Nodes are numbered in lexical id order,
* which makes every choice below independent of module setup order.
*/
final class GraphResolver {
private final Pipeline pipeline;
private final Map<ResourceId, StageDeclaration> installed = new HashMap<>();
private final List<StageDeclaration> nodes;
private final Map<ResourceId, Integer> nodeById = new HashMap<>();
private final List<Map<Integer, StageEdge.Kind>> predecessors = new ArrayList<>();
private final List<List<StageRef>> absentSoftTargets = new ArrayList<>();
private GraphResolver(Pipeline pipeline, Collection<StageDeclaration> declarations) {
this.pipeline = pipeline;
declarations.forEach(declaration -> installed.put(declaration.stage().id(), declaration));
nodes = declarations.stream()
.filter(declaration -> declaration.stage().pipeline() == pipeline)
.sorted(Comparator.comparing(declaration -> declaration.stage().id()))
.toList();
for (int node = 0; node < nodes.size(); node++) {
nodeById.put(nodes.get(node).stage().id(), node);
predecessors.add(new TreeMap<>());
absentSoftTargets.add(new ArrayList<>());
}
}
static ResolvedGraph resolve(Pipeline pipeline, Collection<StageDeclaration> declarations) {
var resolver = new GraphResolver(pipeline, declarations);
resolver.addDeclaredEdges();
return resolver.toResolvedGraph(resolver.executionOrder());
}
private void addDeclaredEdges() {
for (int node = 0; node < nodes.size(); node++) {
addRequiredEdges(node);
addSoftEdges(node);
}
}
private void addRequiredEdges(int node) {
var declaration = nodes.get(node);
for (var required : declaration.requirements()) {
var target = findRequired(declaration, required);
addEdge(nodeById.get(target.stage().id()), node, StageEdge.Kind.REQUIRED);
}
}
private void addSoftEdges(int node) {
var declaration = nodes.get(node);
for (var reference : declaration.softAfter()) {
findSoftTarget(declaration, reference).ifPresentOrElse(
target -> addEdge(target, node, StageEdge.Kind.SOFT),
() -> absentSoftTargets.get(node).add(reference));
}
for (var reference : declaration.softBefore()) {
findSoftTarget(declaration, reference).ifPresentOrElse(
target -> addEdge(node, target, StageEdge.Kind.SOFT),
() -> absentSoftTargets.get(node).add(reference));
}
}
private StageDeclaration findRequired(StageDeclaration dependent, Stage<?> required) {
var target = installed.get(required.id());
if (target == null) {
throw new IllegalArgumentException("Stage " + dependent + " requires " + required
+ ", which no installed module defines (expected a module in namespace '"
+ required.id().namespace() + "')");
}
requireSamePipeline(dependent, target);
if (target.stage() != required) {
throw new IllegalArgumentException("Stage " + dependent + " requires a different declaration of "
+ target + "; reference the owning module's stage constant");
}
return target;
}
private Optional<Integer> findSoftTarget(StageDeclaration dependent, StageRef reference) {
var target = installed.get(reference.id());
if (target == null) {
return Optional.empty();
}
requireSamePipeline(dependent, target);
return Optional.of(nodeById.get(reference.id()));
}
private void requireSamePipeline(StageDeclaration dependent, StageDeclaration target) {
if (target.stage().pipeline() == pipeline) {
return;
}
throw new IllegalArgumentException("Stage " + dependent + " in pipeline " + pipeline
+ " depends on " + target + " in pipeline " + target.stage().pipeline()
+ "; dependencies cannot cross pipelines");
}
private void addEdge(int from, int to, StageEdge.Kind kind) {
predecessors.get(to).merge(from, kind, StageEdge.Kind::strongest);
}
private int[] executionOrder() {
int[] waitingOn = new int[nodes.size()];
var successors = successors();
var ready = new ReadyStages();
for (int node = 0; node < nodes.size(); node++) {
waitingOn[node] = predecessors.get(node).size();
if (waitingOn[node] == 0) {
ready.add(node, kind(node));
}
}
int[] order = new int[nodes.size()];
int ordered = 0;
while (!ready.isEmpty()) {
int node = ready.next();
order[ordered++] = node;
for (int successor : successors.get(node)) {
if (--waitingOn[successor] == 0) {
ready.add(successor, kind(successor));
}
}
}
if (ordered != nodes.size()) {
throw cycleError(waitingOn);
}
return order;
}
private List<List<Integer>> successors() {
var successors = new ArrayList<List<Integer>>();
nodes.forEach(ignored -> successors.add(new ArrayList<>()));
for (int node = 0; node < nodes.size(); node++) {
for (int predecessor : predecessors.get(node).keySet()) {
successors.get(predecessor).add(node);
}
}
return successors;
}
private StageKind kind(int node) {
return nodes.get(node).stage().kind();
}
private IllegalArgumentException cycleError(int[] waitingOn) {
var cycle = findCycle(waitingOn);
var description = new StringBuilder(nodes.get(cycle.getFirst()).toString());
for (int index = 0; index < cycle.size(); index++) {
int from = cycle.get(index);
int to = cycle.get((index + 1) % cycle.size());
var kind = predecessors.get(to).get(from).name().toLowerCase();
description.append(" -[").append(kind).append("]-> ").append(nodes.get(to));
}
return new IllegalArgumentException("Stage cycle in pipeline " + pipeline + ": " + description);
}
/** Every unordered node still waits on an unordered predecessor, so walking predecessors
* from any of them must revisit a node; the revisited stretch is a cycle.
*/
private List<Integer> findCycle(int[] waitingOn) {
int current = firstWaiting(waitingOn);
var walk = new ArrayList<Integer>();
var walkIndex = new HashMap<Integer, Integer>();
while (!walkIndex.containsKey(current)) {
walkIndex.put(current, walk.size());
walk.add(current);
current = firstWaitingPredecessor(current, waitingOn);
}
var cycle = new ArrayList<>(walk.subList(walkIndex.get(current), walk.size()));
Collections.reverse(cycle);
Collections.rotate(cycle, -cycle.indexOf(Collections.min(cycle)));
return cycle;
}
private static int firstWaiting(int[] waitingOn) {
for (int node = 0; node < waitingOn.length; node++) {
if (waitingOn[node] > 0) {
return node;
}
}
throw new IllegalStateException("No stage is waiting");
}
private int firstWaitingPredecessor(int node, int[] waitingOn) {
return predecessors.get(node).keySet().stream()
.filter(predecessor -> waitingOn[predecessor] > 0)
.findFirst()
.orElseThrow();
}
private ResolvedGraph toResolvedGraph(int[] order) {
int[] position = new int[order.length];
for (int index = 0; index < order.length; index++) {
position[order[index]] = index;
}
var stages = new ArrayList<ResolvedStage>(order.length);
var executables = new ExecutableStage[order.length];
var readable = new BitSet[order.length];
var settingsTypes = new ArrayList<Class<?>>();
var worldsByLog = new IdentityHashMap<ModuleLog, ScopedWorlds>();
for (int index = 0; index < order.length; index++) {
int node = order[index];
var declaration = nodes.get(node);
int[] requirements = requiredPositions(node, position);
readable[index] = transitiveRequirements(requirements, readable);
executables[index] = new ExecutableStage(
declaration.stage(),
declaration.body(),
requirements,
readable[index].stream().mapToObj(readablePosition -> nodes.get(order[readablePosition]).stage())
.toArray(Stage<?>[]::new),
readable[index].stream().toArray(),
settingsSlot(declaration, settingsTypes),
StageStreams.idHash(declaration.stage().id()),
worldsByLog.computeIfAbsent(declaration.log(), ScopedWorlds::new));
stages.add(new ResolvedStage(declaration.stage(), declaration.module(), declaration.settings(),
incomingEdges(node, position), absentSoftTargets.get(node), declaration.reach()));
}
return new ResolvedGraph(pipeline, stages, List.of(executables), settingsTypes);
}
private int[] requiredPositions(int node, int[] position) {
return predecessors.get(node).entrySet().stream()
.filter(edge -> edge.getValue() == StageEdge.Kind.REQUIRED)
.mapToInt(edge -> position[edge.getKey()])
.sorted()
.toArray();
}
private static BitSet transitiveRequirements(int[] requirements, BitSet[] readable) {
var result = new BitSet();
for (int required : requirements) {
result.set(required);
result.or(readable[required]);
}
return result;
}
private static int settingsSlot(StageDeclaration declaration, List<Class<?>> settingsTypes) {
if (declaration.settings().isEmpty()) {
return ExecutableStage.NO_SETTINGS;
}
var type = declaration.settings().orElseThrow().type();
if (!settingsTypes.contains(type)) {
settingsTypes.add(type);
}
return settingsTypes.indexOf(type);
}
private List<StageEdge> incomingEdges(int node, int[] position) {
var target = nodes.get(node).stage().id();
return predecessors.get(node).entrySet().stream()
.sorted(Comparator.comparingInt(edge -> position[edge.getKey()]))
.map(edge -> new StageEdge(nodes.get(edge.getKey()).stage().id(), target, edge.getValue()))
.toList();
}
}
@@ -0,0 +1,20 @@
package com.volmit.host;
import java.util.Objects;
/** A class of a built-in module that Iris's own classes hold, and the module that registered it.
*
* @deprecated Transitional, until the cut-over; see {@link com.volmit.FeatureRegistry#registerHeldType}.
*/
@Deprecated(forRemoval = true)
public record HeldTypeRegistration(Class<?> type, DiscoveredModule module) {
public HeldTypeRegistration {
Objects.requireNonNull(type, "type");
Objects.requireNonNull(module, "module");
}
@Override
public String toString() {
return "held type " + type.getName() + " of module " + module;
}
}
@@ -0,0 +1,71 @@
package com.volmit.host;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/** Classes that exist on the class path a build checks a module jar against, but that the real host leaves
* out of its jar, such as the parts of a shared library Iris strips when it packages itself. A module that
* uses one passes a check against the full library and fails on a server, so the check treats them as
* absent.
*
* <p>Entries are class file paths relative to the class root, as Ant patterns: {@code **} crosses
* packages, {@code *} does not. An entry that neither ends in {@code .class} nor contains {@code *} names a
* class and takes its nested classes with it.
*/
final class HostClassesLeftOut {
private static final HostClassesLeftOut NONE = new HostClassesLeftOut(List.of());
private static final String CLASS_FILE_SUFFIX = ".class";
private static final String COMMENT_START = "#";
private final List<Pattern> patterns;
private HostClassesLeftOut(List<Pattern> patterns) {
this.patterns = List.copyOf(patterns);
}
static HostClassesLeftOut none() {
return NONE;
}
/** The entries of a list file's lines; blank lines and text after {@code #} are ignored. */
static HostClassesLeftOut parse(Collection<String> lines) {
Objects.requireNonNull(lines, "lines");
var patterns = lines.stream()
.map(line -> line.contains(COMMENT_START) ? line.substring(0, line.indexOf(COMMENT_START)) : line)
.map(String::strip)
.filter(entry -> !entry.isEmpty())
.flatMap(HostClassesLeftOut::classFilePatterns)
.map(HostClassesLeftOut::compile)
.toList();
return patterns.isEmpty() ? NONE : new HostClassesLeftOut(patterns);
}
boolean leavesOut(String binaryName) {
var classFile = binaryName.replace('.', '/') + CLASS_FILE_SUFFIX;
return patterns.stream().anyMatch(pattern -> pattern.matcher(classFile).matches());
}
private static Stream<String> classFilePatterns(String entry) {
if (entry.endsWith(CLASS_FILE_SUFFIX) || entry.contains("*")) return Stream.of(entry);
return Stream.of(entry + CLASS_FILE_SUFFIX, entry + "$*" + CLASS_FILE_SUFFIX);
}
private static Pattern compile(String antPattern) {
var regex = new StringBuilder();
for (int at = 0; at < antPattern.length(); at++) {
char c = antPattern.charAt(at);
if (c != '*') {
regex.append(Pattern.quote(String.valueOf(c)));
} else if (at + 1 < antPattern.length() && antPattern.charAt(at + 1) == '*') {
regex.append(".*");
at++;
} else {
regex.append("[^/]*");
}
}
return Pattern.compile(regex.toString());
}
}
@@ -0,0 +1,32 @@
package com.volmit.host;
import com.volmit.PackageName;
import java.util.Collection;
import java.util.List;
/** Classes the host describes in studio itself, such as Iris's palettes and noise styles, which built-in
* settings may hold. Given as packages, each with its subpackages. Pack modules cannot use them.
*/
final class HostTypes {
static final HostTypes NONE = new HostTypes(List.of());
private final List<PackageName> packages;
private HostTypes(List<PackageName> packages) {
this.packages = packages;
}
static HostTypes of(Collection<String> packages) {
return new HostTypes(packages.stream().map(HostTypes::parse).toList());
}
boolean contains(Class<?> type) {
var name = type.getName();
return packages.stream().anyMatch(packageName -> packageName.contains(name));
}
private static PackageName parse(String name) {
return PackageName.tryParse(name).orElseThrow(() -> new IllegalArgumentException(
"Host type package '" + name + "' is not a package name, such as art.arcane.iris.engine.object"));
}
}
@@ -0,0 +1,38 @@
package com.volmit.host;
import com.volmit.config.Feature;
import java.lang.annotation.IncompleteAnnotationException;
import java.util.Arrays;
import java.util.stream.Collectors;
/** A settings class whose {@code @Feature} lacks an element the API requires, such as a class compiled before
* {@code key} existed. The load names the module around it ({@link LoadedModules}).
*/
final class IncompleteFeatureException extends IllegalArgumentException {
private static final String KEY = "key";
private IncompleteFeatureException(String message, Throwable cause) {
super(message, cause);
}
static IncompleteFeatureException of(Class<?> type, Feature feature, IncompleteAnnotationException missing) {
if (!KEY.equals(missing.elementName())) {
return new IncompleteFeatureException("The @Feature of settings class " + type.getName() + " has no "
+ missing.elementName() + "; add " + missing.elementName() + " = ... to it and rebuild the jar", missing);
}
return new IncompleteFeatureException("The @Feature of settings class " + type.getName() + " has no key, the JSON"
+ " field packs write the settings under; add key = \"" + suggestedKey(feature) + "\" (or another plain field"
+ " name) to it and rebuild the jar", missing);
}
/** The feature id's path in camel case, such as {@code mossCover} for {@code example:moss/cover}. */
private static String suggestedKey(Feature feature) {
String id = feature.id();
String path = id.substring(id.indexOf(':') + 1);
String camel = Arrays.stream(path.split("[/_.-]+"))
.filter(word -> !word.isEmpty())
.map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
.collect(Collectors.joining());
return camel.isEmpty() ? "settings" : Character.toLowerCase(camel.charAt(0)) + camel.substring(1);
}
}
@@ -0,0 +1,130 @@
package com.volmit.host;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/** Copies of one pack load's module jars in a fresh temporary directory. The load reads, checks and
* defines classes from the copies only, so it sees one consistent snapshot even if a jar is rebuilt
* meanwhile, and the pack's class loader never holds the originals open: on Windows an open jar
* cannot be replaced, which would stop a module author from rebuilding while studio has the pack
* loaded.
*
* <p>The directory is named {@code iris-pack-modules-*} and holds the copies plus an owner file
* naming the process that made it. {@link #delete()} removes it when the pack closes or its load
* fails; {@link StaleJarSnapshots} removes those a crashed process left behind.
*/
final class JarSnapshot {
static final String DIRECTORY_PREFIX = "iris-pack-modules-";
static final String OWNER_FILE = "owner.txt";
static final String OWNER_HEADER = "Iris pack module jar copies";
private static final String COPY_NAME_SEPARATOR = "-";
/** A module jar to copy: its origin, which every message names, and the file. */
record SourceJar(String origin, Path file) {
SourceJar {
Objects.requireNonNull(origin, "origin");
Objects.requireNonNull(file, "file");
}
}
/** A module jar: its origin, which every message names, and its copy. */
record CopiedJar(String origin, Path copy) {
CopiedJar {
Objects.requireNonNull(origin, "origin");
Objects.requireNonNull(copy, "copy");
}
}
private final Path directory;
private final List<CopiedJar> jars;
private JarSnapshot(Path directory, List<CopiedJar> jars) {
this.directory = directory;
this.jars = List.copyOf(jars);
}
/** Copies {@code jars} into a new directory below {@code temporaryRoot}, each copy named by its place in the list so
* jars of the same file name from different places do not collide. Leaves nothing behind if a copy fails.
*/
static JarSnapshot take(List<SourceJar> jars, Path temporaryRoot) {
var directory = createOwnedDirectory(temporaryRoot);
var copies = new ArrayList<CopiedJar>(jars.size());
try {
for (int index = 0; index < jars.size(); index++) {
copies.add(copy(jars.get(index), directory.resolve(index + COPY_NAME_SEPARATOR + jars.get(index).file().getFileName())));
}
return new JarSnapshot(directory, copies);
} catch (RuntimeException | Error failure) {
new JarSnapshot(directory, copies).deleteAfterFailure(failure);
throw failure;
}
}
List<CopiedJar> jars() {
return jars;
}
/** The origin of a copy, or {@code null} if {@code location} is not one of them. */
String originOf(Path location) {
return jars.stream()
.filter(jar -> jar.copy().equals(location))
.map(CopiedJar::origin)
.findFirst()
.orElse(null);
}
/** Deletes the copies, the owner file and the directory. Call only once the pack's class loader
* is closed; on Windows an open copy cannot be deleted.
*/
void delete() {
try {
for (var jar : jars) {
Files.deleteIfExists(jar.copy());
}
Files.deleteIfExists(directory.resolve(OWNER_FILE));
Files.deleteIfExists(directory);
} catch (IOException exception) {
throw new UncheckedIOException("Cannot delete the module jar copies in " + directory, exception);
}
}
void deleteAfterFailure(Throwable failure) {
try {
delete();
} catch (UncheckedIOException exception) {
failure.addSuppressed(exception);
}
}
private static Path createOwnedDirectory(Path temporaryRoot) {
try {
Files.createDirectories(temporaryRoot);
var directory = Files.createTempDirectory(temporaryRoot, DIRECTORY_PREFIX);
Files.writeString(directory.resolve(OWNER_FILE), ownerRecord(ProcessHandle.current().pid()), StandardCharsets.UTF_8);
return directory;
} catch (IOException exception) {
throw new ModuleLoadException(null, null, "Cannot create a directory for module jar copies in " + temporaryRoot,
exception);
}
}
/** What the owner file holds: a fixed header, then the id of the process that made the directory. */
static String ownerRecord(long pid) {
return OWNER_HEADER + "\n" + pid + "\n";
}
private static CopiedJar copy(SourceJar jar, Path copy) {
try {
Files.copy(jar.file(), copy);
return new CopiedJar(jar.origin(), copy);
} catch (IOException exception) {
throw new ModuleLoadException(null, jar.origin(), "Cannot copy module jar " + jar.origin(), exception);
}
}
}
@@ -0,0 +1,60 @@
package com.volmit.host;
import com.volmit.ModuleLog;
import java.lang.System.Logger.Level;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/** A module's log on the host's {@link System.Logger}; see {@link ModuleLogs#labelled}. */
final class LabelledModuleLog implements ModuleLog {
/** What keeps a key space nobody bounded, such as block names, from growing without end. */
private static final int MAX_ONCE_KEYS = 512;
private final String label;
private final System.Logger logger;
private final Set<String> claimedKeys = ConcurrentHashMap.newKeySet();
LabelledModuleLog(String moduleId, System.Logger logger) {
this.label = "[" + moduleId + "] ";
this.logger = logger;
}
@Override
public void debug(String message) {
if (!logger.isLoggable(Level.DEBUG)) {
return;
}
logger.log(Level.DEBUG, label + message);
}
@Override
public void info(String message) {
logger.log(Level.INFO, label + message);
}
@Override
public void warn(String message) {
logger.log(Level.WARNING, label + message);
}
@Override
public void warnOnce(String key, String message) {
if (!claim(key)) {
debug(message);
return;
}
warn(message);
}
@Override
public void error(String message, Throwable cause) {
logger.log(Level.ERROR, label + message, cause);
}
private boolean claim(String key) {
if (claimedKeys.size() >= MAX_ONCE_KEYS) {
return false;
}
return claimedKeys.add(String.valueOf(key));
}
}
@@ -0,0 +1,31 @@
package com.volmit.host;
import com.volmit.ModuleLifecycle;
import com.volmit.ModuleLog;
import com.volmit.PackContext;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import java.util.Objects;
/** Lifecycle hooks and the module that registered them, which the host names when a hook fails. */
public record LifecycleRegistration(ModuleLifecycle lifecycle, DiscoveredModule module) {
public LifecycleRegistration {
Objects.requireNonNull(lifecycle, "lifecycle");
Objects.requireNonNull(module, "module");
}
/** {@code world} as this hook's module sees it, which the host hands to the hook so that {@link PackWorld#log} is the
* module's own.
*/
PackWorld scope(PackWorld world) {
return ModuleWorld.of(world, module.log());
}
/** The pack snapshot as this hook's module sees it, whose {@link PackContext#log} is the module's own. */
PackContext pack(PackResources resources, PackSettings settings) {
return new LoadedPackContext(resources, settings, module.log());
}
private record LoadedPackContext(PackResources resources, PackSettings settings, ModuleLog log) implements PackContext {}
}
@@ -0,0 +1,121 @@
package com.volmit.host;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
/** Calls the lifecycle hooks of one pack's modules ({@link FeatureCatalog#lifecycles()}) the way
* {@link com.volmit.ModuleLifecycle} promises: loading and starting in module id order, stopping in reverse.
*
* <pre>{@code
* var lifecycles = new LifecycleRunner(pack.catalog());
* lifecycles.packLoaded(resources, packSettings); // once per pack snapshot, before its first world starts
* lifecycles.worldStarted(world); // before the world generates anything
* lifecycles.warmUp(world); // then, possibly on another thread, before its first generation
* ...
* lifecycles.worldStopped(world); // then close the world's state
* }</pre>
*
* A failure names the module whose hook failed. The runner keeps no state: the host decides when a snapshot is loaded
* and which worlds run, and calls one method at a time per world.
*/
public final class LifecycleRunner {
private final List<LifecycleRegistration> lifecycles;
public LifecycleRunner(FeatureCatalog catalog) {
this.lifecycles = Objects.requireNonNull(catalog, "catalog").lifecycles();
}
/** Runs every {@code packLoaded} hook in order, each with a {@link com.volmit.PackContext} whose log is its module's;
* the first that throws ends the run with an IllegalStateException naming its module, and the hooks after it do not
* run.
*/
public void packLoaded(PackResources resources, PackSettings settings) {
Objects.requireNonNull(resources, "resources");
Objects.requireNonNull(settings, "settings");
for (var registration : lifecycles) {
try {
registration.lifecycle().packLoaded(registration.pack(resources, settings));
} catch (RuntimeException failure) {
throw failed("loading pack " + resources.packId(), registration, failure);
}
}
}
/** Runs every {@code worldStarted} hook in order. When one throws, the modules started before it are stopped again,
* in reverse, and an IllegalStateException naming the failed module is thrown, with failures of those stops
* suppressed in it.
*/
public void worldStarted(PackWorld world) {
Objects.requireNonNull(world, "world");
for (int index = 0; index < lifecycles.size(); index++) {
var registration = lifecycles.get(index);
try {
registration.lifecycle().worldStarted(registration.scope(world));
} catch (RuntimeException failure) {
var startFailure = failed("starting a world", registration, failure);
stopInReverse(world, index - 1, startFailure);
throw startFailure;
}
}
}
/** Runs every {@code warmUp} hook in order, each even when an earlier one threw; afterwards throws the first
* failure, naming its module, with the later ones suppressed. The caller picks the thread and waits for this
* before the world generates.
*/
public void warmUp(PackWorld world) {
Objects.requireNonNull(world, "world");
IllegalStateException failure = null;
for (var registration : lifecycles) {
try {
registration.lifecycle().warmUp(registration.scope(world));
} catch (RuntimeException warmFailure) {
var named = failed("warming up a world", registration, warmFailure);
if (failure == null) {
failure = named;
} else {
failure.addSuppressed(named);
}
}
}
if (failure != null) {
throw failure;
}
}
/** Runs every {@code worldStopped} hook in reverse order, each even when an earlier one threw; afterwards throws the
* first failure, naming its module, with the later ones suppressed.
*/
public void worldStopped(PackWorld world) {
Objects.requireNonNull(world, "world");
IllegalStateException failure = stopInReverse(world, lifecycles.size() - 1, null);
if (failure != null) {
throw failure;
}
}
/** Stops the modules from {@code last} down to the first, collecting failures into {@code failure}. */
private IllegalStateException stopInReverse(PackWorld world, int last, IllegalStateException failure) {
for (int index = last; index >= 0; index--) {
var registration = lifecycles.get(index);
try {
registration.lifecycle().worldStopped(registration.scope(world));
} catch (RuntimeException stopFailure) {
var named = failed("stopping a world", registration, stopFailure);
if (failure == null) {
failure = named;
} else {
failure.addSuppressed(named);
}
}
}
return failure;
}
private static IllegalStateException failed(String action, LifecycleRegistration registration, RuntimeException cause) {
return new IllegalStateException("Module " + registration.module() + " failed while " + action + ": " + cause, cause);
}
}
@@ -0,0 +1,109 @@
package com.volmit.host;
import com.volmit.config.Level;
import com.volmit.host.schema.PackSchema;
import com.volmit.stage.Pipeline;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/** Everything one pack load derives from its modules: the frozen feature catalog (including the
* settings types stages are conditioned on, resource kinds and validators), its description for studio and one
* resolved graph per pipeline.
*/
public record LoadedModules(
FeatureCatalog catalog, PackSchema schema, ResolvedGraph placement, ResolvedGraph chunk, ResolvedGraph mantle) {
public LoadedModules {
Objects.requireNonNull(catalog, "catalog");
Objects.requireNonNull(schema, "schema");
Objects.requireNonNull(placement, "placement");
Objects.requireNonNull(chunk, "chunk");
Objects.requireNonNull(mantle, "mantle");
}
/** Pass the built-in modules together with {@link PackModules#modules()} of the pack.
*
* @param reservedHostFields JSON fields the host itself uses, per attachment target, which no settings key may take
* @param hostTypePackages packages whose classes the host describes itself, each with its
* subpackages; only built-in modules' settings may use them (see {@link ModuleHost#describingHostTypesIn})
* @param reservedFolders pack folders the host reads itself, which no resource kind may read (see
* {@link ModuleHost#reservingFolders})
* @throws ModuleLoadException when the modules cannot load, naming the module when the error is one module's
*/
public static LoadedModules load(
List<DiscoveredModule> modules,
Map<Level, Set<String>> reservedHostFields,
Collection<String> hostTypePackages,
Collection<String> reservedFolders) {
var registry = new ModuleRegistry(reservedHostFields, Set.copyOf(reservedFolders));
var stages = new StageGraphBuilder();
for (var discovered : modules) {
setUpModule(discovered, stages, registry);
}
try {
return assemble(modules, hostTypePackages, registry, stages);
} catch (RuntimeException failure) {
throw ModuleLoadException.of(failure);
}
}
/** Everything after the modules' setup: the catalog, its description and the resolved pipelines. */
private static LoadedModules assemble(
List<DiscoveredModule> modules, Collection<String> hostTypePackages, ModuleRegistry registry,
StageGraphBuilder stages) {
stages.settingsTypes(registry::registeredByOwner).forEach(registry::registerStageSettings);
var catalog = registry.freeze();
var schema = PackSchemaBuilder.describe(catalog, modules, HostTypes.of(hostTypePackages));
var placement = stages.resolve(Pipeline.PLACEMENT);
var chunk = stages.resolve(Pipeline.CHUNK);
var mantle = stages.resolve(Pipeline.MANTLE);
requireRegisteredMantleLayers(catalog, placement);
requireRegisteredMantleLayers(catalog, mantle);
return new LoadedModules(catalog, schema, placement, chunk, mantle);
}
/** A stage's reach names the layers it writes; a layer nobody registered has no codec or lifetime. */
private static void requireRegisteredMantleLayers(FeatureCatalog catalog, ResolvedGraph graph) {
for (var stage : graph.stages()) {
for (var layer : stage.reach().mantleLayers()) {
var registered = catalog.mantle().stream()
.map(MantleRegistration::key)
.filter(key -> key.id().equals(layer.id()))
.findFirst()
.orElseThrow(() -> stageError(stage, "Stage " + stage.stage().id() + " of module "
+ stage.module() + " writes mantle layer " + layer.id() + ", which no module registers;"
+ " its owner registers it with FeatureRegistry.registerMantle"));
if (registered.type() != layer.type()) {
throw stageError(stage, "Stage " + stage.stage().id() + " of module " + stage.module()
+ " writes mantle layer " + layer.id() + " as " + layer.type().getName()
+ ", but it is registered as " + registered.type().getName());
}
}
}
}
private static ModuleLoadException stageError(ResolvedStage stage, String message) {
return new ModuleLoadException(stage.module(), null, message, null);
}
/** The pack load checks that every class a module uses exists, not that every method or field
* it uses does, so a jar built against another Iris API can still fail to link here. Anything the setup throws is
* that module's load error.
*/
private static void setUpModule(DiscoveredModule discovered, StageGraphBuilder stages, ModuleRegistry registry) {
try {
ModuleSetups.run(discovered, stages, registry);
} catch (LinkageError error) {
throw new ModuleLoadException(discovered.info().id(), discovered.origin(), "Module " + discovered.info().id()
+ " from " + discovered.origin() + " failed to link or initialize a class during setup: " + error
+ "; a missing method or field means the jar was built against a different Iris API", error);
} catch (IncompleteFeatureException incomplete) {
throw new ModuleLoadException(discovered.info().id(), discovered.origin(), "Module " + discovered.info().id()
+ " from " + discovered.origin() + ": " + incomplete.getMessage(), incomplete);
} catch (RuntimeException failure) {
throw ModuleLoadException.of(discovered, failure);
}
}
}
@@ -0,0 +1,98 @@
package com.volmit.host;
import com.volmit.host.schema.PackSchema;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
/** One loaded pack: its module jars and everything derived from them together with the host's
* built-in modules. This is the host's entry point for loading and unloading a pack's modules.
*
* <pre>{@code
* try (var pack = LoadedPack.load(packRoot, host)) {
* var placer = new PlacementRunner(pack.placement());
* ...
* }
* }</pre>
*
* A load either returns a complete pack or throws with nothing left open. Close the pack when it
* unloads, after the host has stopped using its graphs, catalog and runners: closing releases the
* pack's class loader and deletes its copies of the module jars. The original jars are never held
* open, so a module author can rebuild them while the pack is loaded.
*/
public final class LoadedPack implements AutoCloseable {
private final PackModules packModules;
private final LoadedModules loaded;
private LoadedPack(PackModules packModules, LoadedModules loaded) {
this.packModules = packModules;
this.loaded = loaded;
}
/** Loads the pack's module jars, sets them up with the host's built-in modules and resolves the
* pipelines.
*
* @throws ModuleLoadException with the first load error, naming the jar or module at fault
*/
public static LoadedPack load(Path packRoot, ModuleHost host) {
Objects.requireNonNull(host, "host");
var packModules = PackModules.load(packRoot, host.exposedHostPackages(), host.bundledJars(), host.jarCopyRoot(),
host.logger());
try {
var loaded = LoadedModules.load(host.withPackModules(packModules.modules()),
host.reservedHostFields(), host.hostTypePackages(), host.reservedFolders());
return new LoadedPack(packModules, loaded);
} catch (ModuleLoadException | Error failure) {
closeAfterFailure(packModules, failure);
throw failure;
}
}
/** The modules of the host's bundled jars, in the order the host lists them, then the pack's own, one per jar, in jar
* file name order.
*/
public List<DiscoveredModule> packModules() {
return packModules.modules();
}
/** Classes the pack's jars use that nobody has, per jar; see {@link PackModules#missingClasses()}. */
public List<MissingClasses> missingClasses() {
return packModules.missingClasses();
}
public FeatureCatalog catalog() {
return loaded.catalog();
}
/** What the pack's modules, built-in ones included, add to the pack's JSON, for studio's schema
* and completion. Built with the pack, so a load that returns has a complete description.
*/
public PackSchema schema() {
return loaded.schema();
}
public ResolvedGraph placement() {
return loaded.placement();
}
public ResolvedGraph chunk() {
return loaded.chunk();
}
public ResolvedGraph mantle() {
return loaded.mantle();
}
@Override
public void close() {
packModules.close();
}
private static void closeAfterFailure(PackModules packModules, Throwable failure) {
try {
packModules.close();
} catch (RuntimeException exception) {
failure.addSuppressed(exception);
}
}
}
@@ -0,0 +1,79 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings;
import com.volmit.config.SettingsStack;
import com.volmit.generation.MantleGenerationContext;
import com.volmit.mantle.Mantle;
import com.volmit.random.WorldRandom;
import com.volmit.world.PackWorld;
import com.volmit.stage.MantleStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.TerrainSampler;
import java.util.Objects;
import java.util.Optional;
/** The context every stage of one mantle invocation receives. */
final class MantleInvocation implements MantleStageContext {
private final StageInvocation stages;
private final MantleGenerationContext inputs;
MantleInvocation(StageInvocation stages, MantleGenerationContext inputs) {
this.stages = stages;
this.inputs = Objects.requireNonNull(inputs, "inputs");
}
StageInvocation stages() {
return stages;
}
@Override
public <O> O output(Stage<O> stage) {
return stages.output(stage);
}
@Override
public <S extends IrisFeature> SettingsStack<S> configured(Class<S> settingsType) {
return stages.configured(settingsType);
}
@Override
public int originX() {
return inputs.originX();
}
@Override
public int originZ() {
return inputs.originZ();
}
@Override
public TerrainSampler terrain() {
return inputs.terrain();
}
@Override
public FeatureSettings settings() {
return inputs.settings();
}
@Override
public Mantle mantle() {
return inputs.mantle();
}
@Override
public PackWorld world() {
return stages.world(inputs.world());
}
@Override
public <T> Optional<T> extension(Class<T> type) {
return inputs.extension(type);
}
@Override
public WorldRandom random() {
return stages.random();
}
}
@@ -0,0 +1,21 @@
package com.volmit.host;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import java.util.Objects;
public record MantleRegistration<T>(
MantleKey<T> key,
MantleLifetime lifetime,
MantleCodec<T> codec,
int version) {
public MantleRegistration {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(lifetime, "lifetime");
Objects.requireNonNull(codec, "codec");
if (version < 0) {
throw new IllegalArgumentException("Negative mantle codec version");
}
}
}
@@ -0,0 +1,82 @@
package com.volmit.host;
import com.volmit.generation.MantleGenerationContext;
import com.volmit.stage.Pipeline;
import com.volmit.stage.Stage;
import java.util.BitSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.IntStream;
/** Reference executor of a resolved mantle graph, one stage at a time. Every mantle stage is its own pass:
* the host runs a stage for every chunk within that stage's reach plus the reach of every later stage of
* a chunk, each chunk once, before the next stage starts, and before that chunk generates. Each call gives
* the stage the mantle around one chunk as far as the stage's own reach. It does not roll back mantle
* writes; a failed invocation must stop the host from generating the chunks it reaches.
*/
public final class MantleRunner {
private final ResolvedGraph graph;
private final Map<Stage<?>, Integer> positions = new IdentityHashMap<>();
private final List<List<Class<?>>> activationSettings;
public MantleRunner(ResolvedGraph graph) {
this.graph = Objects.requireNonNull(graph, "graph");
if (graph.pipeline() != Pipeline.MANTLE) {
throw new IllegalArgumentException("Expected a mantle graph, got " + graph.pipeline());
}
for (int position = 0; position < graph.size(); position++) {
positions.put(graph.executable(position).stage(), position);
}
activationSettings = activationSettings(graph);
}
/** Runs {@code stage} for one chunk, if it is active there, and reports to {@code timings} how long it took. A
* conditional stage is active when any of the chunk's 16 by 16 columns has an entry of its settings, and reads
* every distinct entry of those columns; it is inactive wherever a stage it requires is. The host derives
* {@code invocationSeed} from the world seed and the chunk position; each stage draws from its own stream of it.
*/
public void generate(Stage<?> stage, MantleGenerationContext inputs, long invocationSeed, StageTimings timings) {
Objects.requireNonNull(timings, "timings");
int position = position(stage);
var settings = ChunkSettings.collect(activationSettings.get(position), inputs::settings, inputs.originX(), inputs.originZ());
var mantle = new MantleInvocation(new StageInvocation(graph, invocationSeed, settings), inputs);
if (!mantle.stages().isActive(position)) {
return;
}
long started = System.nanoTime();
mantle.stages().runInvocationStage(position, mantle);
timings.record(graph.stages().get(position), System.nanoTime() - started);
}
private int position(Stage<?> stage) {
Integer position = positions.get(Objects.requireNonNull(stage, "stage"));
if (position == null) {
throw new IllegalArgumentException("Stage " + stage + " is not a stage of this mantle graph");
}
return position;
}
/** Per position, the settings types that decide whether the stage is active: its own and those of every
* stage it transitively requires, in the graph's order. Requirements come earlier in the order, so one
* forward sweep completes each stage's set before a dependent merges it.
*/
private static List<List<Class<?>>> activationSettings(ResolvedGraph graph) {
var slots = new BitSet[graph.size()];
for (int position = 0; position < slots.length; position++) {
var executable = graph.executable(position);
slots[position] = new BitSet();
if (executable.settingsSlot() != ExecutableStage.NO_SETTINGS) {
slots[position].set(executable.settingsSlot());
}
for (int requirement : executable.requirements()) {
slots[position].or(slots[requirement]);
}
}
var types = graph.settingsTypes();
return IntStream.range(0, slots.length)
.mapToObj(position -> slots[position].stream().<Class<?>>mapToObj(types::get).toList())
.toList();
}
}
@@ -0,0 +1,78 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
import com.volmit.stage.MantleStageContext;
import com.volmit.stage.MantleStageDefinition;
import com.volmit.stage.PackReach;
import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageRef;
/** Builder behind {@link MantleStageDefinition}. */
final class MantleStageDraft implements MantleStageDefinition {
private final StageDeclaration declaration;
MantleStageDraft(StageDeclaration declaration) {
this.declaration = declaration;
}
@Override
public MantleStageDraft requires(Stage<?>... stages) {
declaration.require(stages);
return this;
}
@Override
public MantleStageDraft softAfter(Stage<?>... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public MantleStageDraft softAfter(StageRef... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public MantleStageDraft softBefore(Stage<?>... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public MantleStageDraft softBefore(StageRef... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public MantleStageDraft reach(int blocks) {
declaration.reach(blocks);
return this;
}
@Override
public MantleStageDraft reach(PackReach reach) {
declaration.reach(reach);
return this;
}
@Override
public MantleStageDraft writesMantle(MantleKey<?>... layers) {
declaration.writesMantle(layers);
return this;
}
@Override
public MantleStageDraft when(Class<? extends IrisFeature> settingsType) {
declaration.condition(settingsType);
return this;
}
@Override
public void run(StageAction<MantleStageContext> action) {
declaration.run(action);
}
}
@@ -0,0 +1,33 @@
package com.volmit.host;
import com.volmit.ModuleInfo;
import com.volmit.PackageName;
import java.util.List;
import java.util.Objects;
/** Classes a module jar uses that neither its pack, Iris nor the JDK has, usually optional
* dependencies of a library the jar bundles, and that the jar's module does not declare
* {@linkplain ModuleInfo#optionalPackages() optional}. The jar still loads; code that needs one of
* these classes throws {@link NoClassDefFoundError} when it runs.
*
* @param origin the jar path relative to its pack
* @param classNames the missing classes as sorted binary names
*/
public record MissingClasses(String origin, List<String> classNames) {
public MissingClasses {
Objects.requireNonNull(origin, "origin");
classNames = List.copyOf(classNames);
}
/** These classes without those in any of {@code packages}. */
MissingClasses outside(List<PackageName> packages) {
var remaining = classNames.stream()
.filter(className -> packages.stream().noneMatch(name -> name.contains(className)))
.toList();
return new MissingClasses(origin, remaining);
}
boolean isEmpty() {
return classNames.isEmpty();
}
}
@@ -0,0 +1,31 @@
package com.volmit.host;
import java.util.List;
/** The one warning a pack load writes when its jars use classes nobody has. One line per jar,
* with a capped list of classes, so a large bundled library cannot flood the log.
*/
final class MissingClassesWarning {
static final int MAX_LISTED_CLASSES_PER_JAR = 5;
private static final String INDENT = " ";
private MissingClassesWarning() {}
/** Expects at least one jar; a pack without missing classes logs no warning. */
static String describe(String packName, List<MissingClasses> jars) {
var text = new StringBuilder("Pack ").append(packName)
.append(": 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:");
for (var jar : jars) {
text.append('\n').append(INDENT).append(jar.origin()).append(": ").append(listClasses(jar.classNames()));
}
return text.toString();
}
private static String listClasses(List<String> classNames) {
var listed = String.join(", ", classNames.subList(0, Math.min(classNames.size(), MAX_LISTED_CLASSES_PER_JAR)));
int unlisted = classNames.size() - MAX_LISTED_CLASSES_PER_JAR;
return unlisted > 0 ? listed + " and " + unlisted + " more" : listed;
}
}
@@ -0,0 +1,182 @@
package com.volmit.host;
import com.volmit.IrisModule;
import com.volmit.config.Level;
import com.volmit.resource.ResourceKind;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
/** The host's side of every pack load, the same for all packs: its built-in modules, the module jars it bundles, the host
* packages pack modules may use besides the Iris API, the JSON fields the host itself uses (which no
* settings key may take), the packages of the classes the host describes itself and the pack folders it
* reads itself (which no resource kind may read). Build it once and pass it to every
* {@link LoadedPack#load(java.nio.file.Path, ModuleHost)}.
*
* <pre>{@code
* var host = ModuleHost.of(builtInModules)
* .exposing("art.arcane.iris.engine.modules")
* .reservingFields(reservedHostFields)
* .reservingFolders("biomes", "regions");
* }</pre>
*
* Every method adds to what earlier calls configured, so a host can build the configuration in steps.
* Built-in modules' {@code info()} is read here, once. Exposed package names, host type packages,
* reserved folders and reserved field names are checked here, so a mistake fails when the host starts rather than at the
* first pack load.
*/
public record ModuleHost(
List<DiscoveredModule> builtIns,
Set<String> exposedHostPackages,
Map<Level, Set<String>> reservedHostFields,
Set<String> hostTypePackages,
Set<String> reservedFolders,
List<Path> bundledJars,
Path jarCopyRoot,
System.Logger logger) {
private static final String TEMPORARY_DIRECTORY_PROPERTY = "java.io.tmpdir";
public ModuleHost {
builtIns = List.copyOf(builtIns);
exposedHostPackages = Set.copyOf(exposedHostPackages);
reservedHostFields = copyOf(reservedHostFields);
hostTypePackages = Set.copyOf(hostTypePackages);
reservedFolders = Set.copyOf(reservedFolders);
bundledJars = List.copyOf(bundledJars);
Objects.requireNonNull(jarCopyRoot, "jarCopyRoot");
Objects.requireNonNull(logger, "logger");
ExposedPackages.apiAnd(exposedHostPackages);
HostTypes.of(hostTypePackages);
requireFieldNames(reservedHostFields);
requireFolderNames(reservedFolders);
}
/** The given built-in modules, exposing only the Iris API and reserving nothing. Jar copies go to
* {@code java.io.tmpdir} and the load log to the {@link System.Logger} named after {@link PackModules}.
*/
public static ModuleHost of(List<? extends IrisModule> builtInModules) {
var builtIns = builtInModules.stream().map(DiscoveredModule::builtIn).toList();
return new ModuleHost(builtIns, Set.of(), Map.of(), Set.of(), Set.of(), List.of(), systemTemporaryDirectory(),
PackModules.DEFAULT_LOGGER);
}
/** This configuration with {@code packages}, each with its subpackages, also exposed to pack
* modules, such as the packages that hold built-in modules' stage constants.
*/
public ModuleHost exposing(String... packages) {
return new ModuleHost(builtIns, union(exposedHostPackages, packages), reservedHostFields,
hostTypePackages, reservedFolders, bundledJars, jarCopyRoot, logger);
}
/** This configuration with {@code fields} also reserved as JSON fields the host itself uses,
* merged per level with the fields reserved before.
*/
public ModuleHost reservingFields(Map<Level, Set<String>> fields) {
return new ModuleHost(builtIns, exposedHostPackages, merge(reservedHostFields, fields),
hostTypePackages, reservedFolders, bundledJars, jarCopyRoot, logger);
}
/** This configuration with the classes in {@code packages}, each with its subpackages, described by
* the host itself: built-in settings may hold them, such as Iris's palettes, and the pack's
* {@link com.volmit.host.schema.PackSchema} names them as {@link com.volmit.host.schema.ValueKind.HostKind}
* instead of describing their fields. Pack modules' settings cannot use them.
*
* @deprecated Transitional, until the cut-over: only while built-in settings still hold Iris's own classes.
* Removed once they do not.
*/
@Deprecated(forRemoval = true)
public ModuleHost describingHostTypesIn(String... packages) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields,
union(hostTypePackages, packages), reservedFolders, bundledJars, jarCopyRoot, logger);
}
/** This configuration with {@code folders}, folder names directly below a pack's root, also read by the host
* itself, such as its biome and object folders. A module resource kind that reads one fails the pack load.
*/
public ModuleHost reservingFolders(String... folders) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
union(reservedFolders, folders), bundledJars, jarCopyRoot, logger);
}
/** This configuration also loading {@code jars}, module jars the host ships, with every pack, as if they were in its
* {@code modules} folder: before the pack's own jars, in the given order, in the same class loader. Whether they exist
* is checked when a pack loads.
*/
public ModuleHost bundlingJars(Path... jars) {
var bundled = new ArrayList<>(bundledJars);
bundled.addAll(Arrays.asList(jars));
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages, reservedFolders,
bundled, jarCopyRoot, logger);
}
/** This configuration copying module jars into new directories below {@code directory}, such as a
* cache directory of the host, which is created when missing. The last call wins.
*/
public ModuleHost copyingJarsTo(Path directory) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
reservedFolders, bundledJars, directory, logger);
}
/** This configuration logging each pack load's module summary and missing-classes warning, and every module's own
* log ({@link com.volmit.ModuleLog}), to {@code logger}, such as an adapter to the host's own log. A module's lines
* carry its id and its {@link System.Logger.Level#ERROR} lines the failure to report. The last call wins.
*/
public ModuleHost loggingTo(System.Logger logger) {
Objects.requireNonNull(logger, "logger");
var loggedBuiltIns = builtIns.stream().map(builtIn -> builtIn.loggingTo(logger)).toList();
return new ModuleHost(loggedBuiltIns, exposedHostPackages, reservedHostFields, hostTypePackages,
reservedFolders, bundledJars, jarCopyRoot, logger);
}
/** The built-in modules followed by a pack's modules, in the order {@link LoadedModules} sets them up. */
List<DiscoveredModule> withPackModules(List<DiscoveredModule> packModules) {
var modules = new ArrayList<>(builtIns);
modules.addAll(Objects.requireNonNull(packModules, "packModules"));
return modules;
}
private static Path systemTemporaryDirectory() {
return Path.of(System.getProperty(TEMPORARY_DIRECTORY_PROPERTY));
}
private static Map<Level, Set<String>> copyOf(Map<Level, Set<String>> fields) {
var copy = new EnumMap<Level, Set<String>>(Level.class);
fields.forEach((target, names) -> copy.put(target, Set.copyOf(names)));
return Map.copyOf(copy);
}
/** A blank field name, or one with ':' like a feature id, fails here, as it would as a settings key. */
private static void requireFieldNames(Map<Level, Set<String>> fields) {
fields.values().forEach(names -> names.forEach(FeatureDescriptor::requireFieldName));
}
private static void requireFolderNames(Set<String> folders) {
for (var folder : folders) {
if (!ResourceKind.isFolderName(folder)) {
throw new IllegalArgumentException("Reserved folder '" + folder + "' is not a folder name directly below the"
+ " pack root, such as biomes");
}
}
}
private static Map<Level, Set<String>> merge(
Map<Level, Set<String>> existing,
Map<Level, Set<String>> added) {
var merged = new EnumMap<Level, Set<String>>(Level.class);
existing.forEach((target, names) -> merged.put(target, new TreeSet<>(names)));
added.forEach((target, names) -> merged.computeIfAbsent(target, ignored -> new TreeSet<>()).addAll(names));
return merged;
}
private static Set<String> union(Set<String> existing, String... added) {
var names = new TreeSet<>(existing);
names.addAll(Arrays.asList(added));
return names;
}
}
@@ -0,0 +1,225 @@
package com.volmit.host;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.SortedSet;
import java.util.function.Predicate;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipFile;
/** One jar in a pack's modules directory, the entry classes it names and the classes it holds,
* each with the classes it links against. {@code path} is the load's copy of the jar
* ({@link JarSnapshot}); {@code origin}, the original's path relative to the pack or a bundled jar's name, is what
* every message names.
*
* <p>The entry points are the jar's own {@code META-INF/services/com.volmit.IrisModule} file, in
* the format {@link java.util.ServiceLoader} reads: one module class per line, so a jar holds as many
* modules as it lists. The host reads that file from this jar only:
* {@code ServiceLoader} would also return providers from parent class loaders and could not tell
* which jar a broken entry came from.
*/
record ModuleJar(Path path, String origin, List<String> entryClasses, List<JarClass> classes) {
static final String ENTRY_POINT_FILE = "META-INF/services/" + IrisModule.class.getName();
private static final String COMMENT_START = "#";
private static final String CLASS_FILE_SUFFIX = ".class";
private static final String MODULE_DESCRIPTOR = "module-info" + CLASS_FILE_SUFFIX;
private static final String META_INF = "META-INF/";
ModuleJar {
Objects.requireNonNull(path, "path");
Objects.requireNonNull(origin, "origin");
entryClasses = List.copyOf(entryClasses);
classes = List.copyOf(classes);
}
/** A class in the jar, by binary name, and the binary names of the classes it links against. */
record JarClass(String name, SortedSet<String> references) {
JarClass {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(references, "references");
}
}
/** Reads the entry classes a jar names and the classes it holds. Fails if the jar names no
* entry class or a class file cannot be parsed.
*/
static ModuleJar read(JarSnapshot.CopiedJar copied) {
var origin = copied.origin();
var jar = copied.copy();
try (var file = openAsClassLoaderSeesIt(jar)) {
var entryClasses = requireEntryClasses(origin, readEntryClasses(file));
var classEntries = findClassEntries(file);
return new ModuleJar(jar, origin, entryClasses, readClasses(origin, file, classEntries));
} catch (IOException exception) {
throw new ModuleLoadException(null, origin, "Module jar " + origin + " is not a readable jar", exception);
}
}
List<String> classNames() {
return classes.stream().map(JarClass::name).toList();
}
URL url() {
try {
return path.toUri().toURL();
} catch (MalformedURLException exception) {
throw new ModuleLoadException(null, origin, "Module jar " + origin + " has no URL form", exception);
}
}
/** Loads and instantiates every entry class through the pack's class loader, in the order the
* jar lists them. Each class must come from this jar, so a copy on the host classpath cannot
* silently replace the jar's module.
*/
List<DiscoveredModule> createModules(ClassLoader packLoader, JarSnapshot snapshot) {
return entryClasses.stream().map(entryClass -> createModule(entryClass, packLoader, snapshot)).toList();
}
private DiscoveredModule createModule(String entryClass, ClassLoader packLoader, JarSnapshot snapshot) {
var type = loadEntryClass(entryClass, packLoader);
requireDefinedHere(entryClass, type, snapshot);
var module = instantiate(entryClass, type);
return DiscoveredModule.fromJar(module, readIdentity(entryClass, module), origin);
}
/** Opens the jar with the runtime's multi-release version, like the pack class loader does, so
* class names below match the classes that loader can define.
*/
private static JarFile openAsClassLoaderSeesIt(Path jar) throws IOException {
return new JarFile(jar.toFile(), true, ZipFile.OPEN_READ, JarFile.runtimeVersion());
}
private static List<String> requireEntryClasses(String origin, List<String> entryClasses) {
if (!entryClasses.isEmpty()) return entryClasses;
throw ModuleLoadException.ofJar(origin, "Module jar " + origin + " has no entry point; name its "
+ IrisModule.class.getSimpleName() + " classes in " + ENTRY_POINT_FILE + ", one per line");
}
private static List<String> readEntryClasses(JarFile file) throws IOException {
var entry = file.getJarEntry(ENTRY_POINT_FILE);
if (entry == null) return List.of();
try (var reader = new BufferedReader(new InputStreamReader(file.getInputStream(entry), StandardCharsets.UTF_8))) {
return reader.lines()
.map(ModuleJar::withoutComment)
.map(String::strip)
.filter(Predicate.not(String::isEmpty))
.distinct()
.toList();
}
}
/** The class file entries of the jar, sorted by name. A multi-release jar contributes each class
* once, under its base name, in the version this runtime would load. Anything left below
* {@code META-INF/}, such as versioned entries of a jar that is not multi-release, cannot be
* loaded as a class: {@code META-INF} is not a valid package name.
*/
private static List<JarEntry> findClassEntries(JarFile file) {
return file.versionedStream()
.filter(Predicate.not(JarEntry::isDirectory))
.filter(entry -> isClassFile(entry.getName()))
.sorted(Comparator.comparing(entry -> toBinaryName(entry.getName())))
.toList();
}
private static boolean isClassFile(String entryName) {
return entryName.endsWith(CLASS_FILE_SUFFIX)
&& !entryName.equals(MODULE_DESCRIPTOR)
&& !entryName.startsWith(META_INF);
}
private static List<JarClass> readClasses(String origin, JarFile file, List<JarEntry> classEntries) throws IOException {
var classes = new ArrayList<JarClass>(classEntries.size());
for (var entry : classEntries) {
classes.add(new JarClass(toBinaryName(entry.getName()), readReferences(origin, file, entry)));
}
return classes;
}
private static SortedSet<String> readReferences(String origin, JarFile file, JarEntry entry) throws IOException {
try (var input = file.getInputStream(entry)) {
return ClassReferences.read(input.readAllBytes());
} catch (IllegalArgumentException exception) {
throw new ModuleLoadException(null, origin, "Module jar " + origin + " holds a class file this runtime cannot"
+ " read, " + entry.getRealName() + ": " + exception.getMessage(), exception);
}
}
private static String toBinaryName(String entryName) {
return entryName.substring(0, entryName.length() - CLASS_FILE_SUFFIX.length()).replace('/', '.');
}
private static String withoutComment(String line) {
int comment = line.indexOf(COMMENT_START);
return comment < 0 ? line : line.substring(0, comment);
}
private Class<? extends IrisModule> loadEntryClass(String entryClass, ClassLoader packLoader) {
Class<?> type;
try {
type = Class.forName(entryClass, false, packLoader);
} catch (ClassNotFoundException | LinkageError exception) {
throw brokenEntryPoint(entryClass, "class cannot be loaded: " + exception, exception);
}
if (!IrisModule.class.isAssignableFrom(type)) {
throw brokenEntryPoint(entryClass, "class does not implement " + IrisModule.class.getName(), null);
}
return type.asSubclass(IrisModule.class);
}
private void requireDefinedHere(String entryClass, Class<?> type, JarSnapshot snapshot) {
var source = type.getProtectionDomain().getCodeSource();
var location = source == null ? null : source.getLocation();
if (location != null && location.toExternalForm().equals(url().toExternalForm())) return;
throw brokenEntryPoint(entryClass, "class is loaded from " + describeLocation(location, snapshot) + ", not from this jar", null);
}
/** Another jar of the pack by its origin, never by the path of its copy. */
private static String describeLocation(URL location, JarSnapshot snapshot) {
if (location == null) return "an unknown location";
try {
var origin = snapshot.originOf(Path.of(location.toURI()));
return origin == null ? location.toString() : origin;
} catch (URISyntaxException | IllegalArgumentException | java.nio.file.FileSystemNotFoundException exception) {
return location.toString();
}
}
private IrisModule instantiate(String entryClass, Class<? extends IrisModule> type) {
try {
return type.getConstructor().newInstance();
} catch (InvocationTargetException exception) {
throw brokenEntryPoint(entryClass, "constructor threw " + exception.getCause(), exception.getCause());
} catch (ReflectiveOperationException exception) {
throw brokenEntryPoint(entryClass, "class needs to be public and concrete with a public no-argument constructor", exception);
} catch (LinkageError exception) {
throw brokenEntryPoint(entryClass, "class cannot be initialized: " + exception, exception);
}
}
private ModuleInfo readIdentity(String entryClass, IrisModule module) {
try {
return Objects.requireNonNull(module.info(), "info() returned null");
} catch (RuntimeException | LinkageError exception) {
throw brokenEntryPoint(entryClass, "info() failed: " + exception, exception);
}
}
private ModuleLoadException brokenEntryPoint(String entryClass, String problem, Throwable cause) {
return new ModuleLoadException(null, origin, "Module jar " + origin + " has a broken entry point "
+ entryClass + ": " + problem, cause);
}
}
@@ -0,0 +1,85 @@
package com.volmit.host;
import com.volmit.IrisModule;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
/** The checks a pack load makes on a module jar's classes, for a build to run on a jar it has just
* written: the jar names at least one module, every module class is in the jar, and no class uses
* what pack modules cannot see (Iris internals, JDK modules or packages packs may not use, missing
* classes of exposed packages). Nothing is loaded or instantiated. A jar that passes can still fail
* a pack load, for example on duplicate module ids, which only the pack's other modules reveal.
*
* <p>The host classes come from the class loader that defines the API, so run this with the API and the
* host's classes on the class path. {@link #main} takes a jar path followed by the host packages that
* pack modules may use, and exits with 1 and the message on stderr when the jar fails.
*
* <p>The class path the check runs on may hold classes of an exposed library that the real host's jar
* leaves out. {@code --left-out=<file>} (or the {@code leftOutClasses} parameter) lists them, one entry per
* line as described by {@code HostClassesLeftOut}, and a module that references one fails the check naming it.
*/
public final class ModuleJarCheck {
private static final int FAILED_EXIT_CODE = 1;
private static final int MISSING_ARGUMENT_EXIT_CODE = 2;
private static final String LEFT_OUT_OPTION = "--left-out=";
private ModuleJarCheck() {}
/** Returns the module classes the jar names, in the order it lists them, or throws a {@link ModuleLoadException}
* naming the jar.
*/
public static List<String> check(Path jar, Collection<String> exposedHostPackages) {
return check(jar, exposedHostPackages, List.of());
}
/** Like {@link #check(Path, Collection)}, treating the classes {@code leftOutClasses} describes as missing from the host. */
public static List<String> check(Path jar, Collection<String> exposedHostPackages, Collection<String> leftOutClasses) {
Objects.requireNonNull(jar, "jar");
var host = new ExposedHostClassLoader(IrisModule.class.getClassLoader(), ExposedPackages.apiAnd(exposedHostPackages),
HostClassesLeftOut.parse(leftOutClasses));
var read = ModuleJar.read(new JarSnapshot.CopiedJar(jar.toString(), jar));
requireEntryClassesInJar(read);
PackClassCheck.requireLinkable(List.of(read), host);
return read.entryClasses();
}
private static void requireEntryClassesInJar(ModuleJar jar) {
var held = jar.classNames();
for (var entryClass : jar.entryClasses()) {
if (held.contains(entryClass)) continue;
throw ModuleLoadException.ofJar(jar.origin(), "Module jar " + jar.origin() + " lists " + entryClass + " in "
+ ModuleJar.ENTRY_POINT_FILE + ", but the jar holds no such class; a module class must be in the jar that lists it");
}
}
public static void main(String[] arguments) {
var options = Arrays.stream(arguments).filter(argument -> argument.startsWith(LEFT_OUT_OPTION)).toList();
var positional = Arrays.stream(arguments).filter(argument -> !argument.startsWith(LEFT_OUT_OPTION)).toList();
if (positional.isEmpty()) {
System.err.println("Usage: ModuleJarCheck <module jar> [--left-out=<file>] [exposed host package...]");
System.exit(MISSING_ARGUMENT_EXIT_CODE);
}
try {
var leftOut = options.stream().flatMap(option -> readLines(Path.of(option.substring(LEFT_OUT_OPTION.length()))).stream()).toList();
var modules = check(Path.of(positional.getFirst()), positional.subList(1, positional.size()), leftOut);
System.out.println("Module jar " + positional.getFirst() + " passes the pack module checks: " + modules);
} catch (RuntimeException failure) {
System.err.println(failure.getMessage());
System.exit(FAILED_EXIT_CODE);
}
}
private static List<String> readLines(Path file) {
try {
return Files.readAllLines(file);
} catch (IOException unreadable) {
throw new UncheckedIOException("Cannot read the left-out classes file " + file, unreadable);
}
}
}
@@ -0,0 +1,57 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import java.util.Optional;
/** A pack whose modules cannot load: a jar that breaks the pack rules, a module whose setup fails, or modules that do not
* fit together. Every load error of {@link LoadedPack#load}, {@link PackModules#load} and {@link LoadedModules#load} is
* one, so a host catches this type alone. The message is complete on its own and names the jar or module at fault.
*/
public final class ModuleLoadException extends RuntimeException {
private final ResourceId moduleId;
private final String origin;
/** {@code moduleId} and {@code origin} (the jar, such as {@code modules/moss.jar}, or {@code host classpath}) are null
* when the error is not one module's or one jar's, such as a dependency cycle between modules; {@code cause} is null
* when there is none.
*/
public ModuleLoadException(ResourceId moduleId, String origin, String message, Throwable cause) {
super(message, cause);
this.moduleId = moduleId;
this.origin = origin;
}
/** The module at fault, when the error is one module's. */
public Optional<ResourceId> moduleId() {
return Optional.ofNullable(moduleId);
}
/** Where the module or jar at fault comes from, when the error is one module's or one jar's. */
public Optional<String> origin() {
return Optional.ofNullable(origin);
}
/** A jar's error, before any of its modules exists. */
static ModuleLoadException ofJar(String origin, String message) {
return new ModuleLoadException(null, origin, message, null);
}
/** An error that is not one module's or one jar's. */
static ModuleLoadException ofPack(String message) {
return new ModuleLoadException(null, null, message, null);
}
/** {@code failure} as a load error of {@code module}, with its message unchanged; a load error already is one. */
static ModuleLoadException of(DiscoveredModule module, RuntimeException failure) {
if (failure instanceof ModuleLoadException loadError) return loadError;
return new ModuleLoadException(module.info().id(), module.origin(), failure.getMessage(), failure);
}
/** {@code failure} as a load error that is not one module's or one jar's, with its message unchanged; a load error
* already is one.
*/
static ModuleLoadException of(RuntimeException failure) {
if (failure instanceof ModuleLoadException loadError) return loadError;
return new ModuleLoadException(null, null, failure.getMessage(), failure);
}
}
@@ -0,0 +1,49 @@
package com.volmit.host;
import com.volmit.ModuleLog;
import java.util.Objects;
/** The logs a host hands to modules. */
public final class ModuleLogs {
private static final ModuleLog DISCARDING = new DiscardingLog();
private ModuleLogs() {
}
/** A module's log writing to {@code logger} with the module's id in front of each message, such as
* {@code [iris:decorant] Empty Block Data for plains}. {@link ModuleLog#debug} writes at
* {@link System.Logger.Level#DEBUG} and only when {@code logger} is loggable at that level;
* {@link ModuleLog#error} passes its cause to the logger, which is where the host reports it. A log keeps its
* {@link ModuleLog#warnOnce} keys, so make one per module, not one per message.
*/
public static ModuleLog labelled(String moduleId, System.Logger logger) {
return new LabelledModuleLog(Objects.requireNonNull(moduleId, "moduleId"), Objects.requireNonNull(logger, "logger"));
}
/** A log that writes nothing, for tests and tools that run module code without a host. */
public static ModuleLog discarding() {
return DISCARDING;
}
private static final class DiscardingLog implements ModuleLog {
@Override
public void debug(String message) {
}
@Override
public void info(String message) {
}
@Override
public void warn(String message) {
}
@Override
public void warnOnce(String key, String message) {
}
@Override
public void error(String message, Throwable cause) {
}
}
}
@@ -0,0 +1,343 @@
package com.volmit.host;
import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.ModuleLifecycle;
import com.volmit.config.Level;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import com.volmit.service.Providers;
import com.volmit.validation.Validator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/** Reference host registry. Single-threaded registration ends with freeze(); the catalog is
* immutable. IDs are unique across feature kinds. A feature's JSON key (see {@link com.volmit.config.Feature#key})
* is unique per attachment target, and may not equal a host JSON field passed in to reserve it; a clash fails the
* registration naming the key, the target and both claimants. Modules register during their setup
* ({@link ModuleSetups#run}); object feature ids, mantle keys, resource kind ids and explicitly registered
* settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}).
* Resource kinds have unique ids, types and folders, and no kind may read a folder the host reserves for its own
* files. Lifecycle hooks and service providers are registered by the module that owns them; a service whose providers
* are {@link Providers#ONE} has at most one. A failed registration leaves the registry unchanged. A failed module callback
* invalidates the host's whole build. This does not decode JSON, discover modules or instantiate
* settings.
*/
@SuppressWarnings("removal") // held types are transitional, until the cut-over
public final class ModuleRegistry implements FeatureRegistry {
private final Map<Class<?>, FeatureDescriptor<?>> settings = new HashMap<>();
private final Map<Class<?>, ObjectRegistration<?>> objects = new HashMap<>();
private final Map<String, MantleRegistration<?>> mantle = new HashMap<>();
private final Set<ResourceId> featureIds = new HashSet<>();
private final Set<Class<?>> featureTypes = new HashSet<>();
private final Set<Class<?>> registeredByOwner = new HashSet<>();
private final Map<KeyAtTarget, KeyClaimant> keyClaimants = new HashMap<>();
private final Map<ResourceId, ResourceKindRegistration> resourceKinds = new HashMap<>();
private final Map<Class<?>, HeldTypeRegistration> heldTypes = new HashMap<>();
private final List<ValidatorRegistration> validators = new ArrayList<>();
private final List<LifecycleRegistration> lifecycles = new ArrayList<>();
private final List<ServiceRegistration> services = new ArrayList<>();
private final Set<String> reservedFolders;
private final List<DiscoveredModule> registered = new ArrayList<>();
private FeatureCatalog catalog;
private DiscoveredModule registering;
public ModuleRegistry() {
this(Map.of(), Set.of());
}
/**
* @param reservedHostFields JSON fields the host itself uses, per level, which no settings key may take
* @param reservedFolders folders below the pack root that the host reads itself, which no resource kind may read
*/
public ModuleRegistry(Map<Level, Set<String>> reservedHostFields, Set<String> reservedFolders) {
reservedHostFields.forEach((target, names) -> names.forEach(name -> reserveHostField(target, name)));
this.reservedFolders = Set.copyOf(reservedFolders);
}
/** Accepts {@code discovered}'s registrations until {@link #endSetup()}; see {@link ModuleSetups#run}. */
void beginSetup(DiscoveredModule discovered) {
Objects.requireNonNull(discovered, "discovered");
checkOpen();
if (registering != null) {
throw new IllegalStateException("Module " + discovered.info().id() + " set up during " + registering.info().id());
}
registering = discovered;
registered.add(discovered);
}
void endSetup() {
registering = null;
}
@Override
public <F extends IrisFeature> void registerObject(
Class<F> featureType,
ObjectGeneratorFactory<F> factory) {
checkOpen();
var descriptor = FeatureDescriptor.of(featureType);
requireOwnedId("Object generator settings " + featureType.getName() + " with feature id", descriptor.id());
var registration = new ObjectRegistration<>(descriptor, factory);
claim(descriptor, registering);
objects.put(featureType, registration);
}
@Override
public <T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, MantleCodec<T> codec) {
checkOpen();
Objects.requireNonNull(key, "key");
Objects.requireNonNull(codec, "codec");
requireOwnedId("Mantle layer", ResourceId.parse(key.id()));
var registration = new MantleRegistration<>(key, lifetime, codec, codec.version());
if (mantle.putIfAbsent(key.id(), registration) != null) {
throw new IllegalArgumentException("Duplicate mantle layer: " + key.id());
}
}
@Override
public void registerSettings(Class<? extends IrisFeature>... settingsTypes) {
checkOpen();
for (var settingsType : settingsTypes) {
registerOneSettings(settingsType);
}
}
private void registerOneSettings(Class<? extends IrisFeature> settingsType) {
var descriptor = FeatureDescriptor.of(settingsType);
requireOwnedId("Settings " + settingsType.getName() + " with feature id", descriptor.id());
catalogSettings(descriptor, registering);
registeredByOwner.add(settingsType);
}
/** @deprecated Transitional, until the cut-over; see {@link FeatureRegistry#registerHeldType}. */
@Override
@Deprecated(forRemoval = true)
public void registerHeldType(Class<?> type) {
checkOpen();
Objects.requireNonNull(type, "type");
requireRegistering("Held type " + type.getName());
if (registering.source() != DiscoveredModule.Source.HOST && type.getClassLoader() == registering.module().getClass().getClassLoader()) {
throw new IllegalArgumentException("Held type " + type.getName() + " of module " + registering + " is a class of the pack module's"
+ " own jar; only a class the host loads, such as one of an exposed package, can be held by Iris's own classes");
}
heldTypes.putIfAbsent(type, new HeldTypeRegistration(type, registering));
}
@Override
public <T> void registerResourceKind(ResourceKind<T> kind) {
checkOpen();
Objects.requireNonNull(kind, "kind");
requireOwnedId("Resource kind", kind.id());
var registration = new ResourceKindRegistration(kind, registering);
requireUnclaimedKind(registration);
resourceKinds.put(kind.id(), registration);
}
@Override
public void registerValidator(Validator validator) {
checkOpen();
Objects.requireNonNull(validator, "validator");
if (registering == null) {
throw new IllegalStateException("Validator " + validator + " registered outside IrisModule.setup");
}
validators.add(new ValidatorRegistration(validator, registering));
}
@Override
public void registerLifecycle(ModuleLifecycle lifecycle) {
checkOpen();
Objects.requireNonNull(lifecycle, "lifecycle");
requireRegistering("Lifecycle " + lifecycle);
lifecycles.add(new LifecycleRegistration(lifecycle, registering));
}
@Override
public <S> void registerService(Class<S> service, S provider) {
checkOpen();
Objects.requireNonNull(service, "service");
Objects.requireNonNull(provider, "provider");
requireRegistering("Provider of " + service.getName());
var providers = FeatureCatalog.providersOf(service);
if (!service.isInstance(provider)) {
throw new IllegalArgumentException("Provider " + provider + " of module " + registering + " does not implement "
+ service.getName());
}
var added = new ServiceRegistration(service, provider, registering);
if (providers == Providers.ONE) {
requireNoProvider(added);
}
services.add(added);
}
/** Catalogs a settings type named by a stage's when(...), whose owner {@link StageGraphBuilder}
* has checked. Several stages, and the owner's {@link #registerSettings}, may name one type. Call
* it after every module has registered, so the owner is known.
*/
void registerStageSettings(Class<? extends IrisFeature> settingsType) {
checkOpen();
if (settings.containsKey(settingsType)) {
return;
}
var descriptor = FeatureDescriptor.of(settingsType);
catalogSettings(descriptor, ownerOf(descriptor));
}
/** Whether the module owning {@code settingsType} registered it through {@link #registerSettings}. */
boolean registeredByOwner(Class<?> settingsType) {
return registeredByOwner.contains(settingsType);
}
public FeatureCatalog freeze() {
if (catalog == null) {
catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), heldTypes.values(),
validators, lifecycles, services);
}
return catalog;
}
private void catalogSettings(FeatureDescriptor<?> descriptor, DiscoveredModule owner) {
if (settings.containsKey(descriptor.type())) {
return;
}
claim(descriptor, owner);
settings.put(descriptor.type(), descriptor);
}
private DiscoveredModule ownerOf(FeatureDescriptor<?> descriptor) {
return registered.stream()
.filter(module -> module.info().ownsId(descriptor.id()))
.findFirst()
.orElseThrow(() -> new IllegalStateException("No registered module owns feature id " + descriptor.id()));
}
private void requireOwnedId(String registration, ResourceId id) {
if (registering == null) {
throw new IllegalStateException(registration + " " + id + " registered outside IrisModule.setup");
}
var info = registering.info();
if (info.ownsId(id)) return;
throw new IllegalArgumentException(registration + " " + id + " must be " + info.id() + " or start with "
+ info.idPrefix() + ", the id of its registering module " + registering);
}
private void requireRegistering(String registration) {
if (registering == null) {
throw new IllegalStateException(registration + " registered outside IrisModule.setup");
}
}
/** A service a pack has one provider of: a second provider, from this module or another, fails. */
private void requireNoProvider(ServiceRegistration added) {
for (var existing : services) {
if (existing.service() == added.service()) {
throw new IllegalArgumentException("Service " + added.service().getName() + " is provided by module "
+ existing.module() + " already, and module " + added.module() + " provides it too; a pack has"
+ " one provider of it (Providers.ONE), so remove one of them");
}
}
}
/** One id, one type and one folder per kind: the host finds resources by type and reads each folder as one kind. */
private void requireUnclaimedKind(ResourceKindRegistration added) {
var kind = added.kind();
if (resourceKinds.containsKey(kind.id())) {
throw new IllegalArgumentException("Duplicate resource kind: " + kind.id() + " of module " + added.module());
}
if (reservedFolders.contains(kind.folder())) {
throw new IllegalArgumentException("Resource kind " + kind.id() + " of module " + added.module() + " reads folder '"
+ kind.folder() + "', which the host reads itself; give the kind a folder of its own");
}
for (var existing : resourceKinds.values()) {
if (existing.kind().type() == kind.type()) {
throw new IllegalArgumentException(added + " reads into " + kind.type().getName() + ", which " + existing
+ " reads into already; resources are found by their type, so each kind needs a class of its own");
}
if (existing.kind().folder().equals(kind.folder())) {
throw new IllegalArgumentException(added + " reads folder '" + kind.folder() + "', which " + existing
+ " reads already; a folder holds one kind, so give one of them a folder of its own");
}
}
}
private void reserveHostField(Level target, String name) {
keyClaimants.put(new KeyAtTarget(target, FeatureDescriptor.requireFieldName(name)), KeyClaimant.hostField());
}
private void claim(FeatureDescriptor<?> descriptor, DiscoveredModule owner) {
requireNewFeature(descriptor);
requireUnclaimedKeys(descriptor, owner);
featureTypes.add(descriptor.type());
featureIds.add(descriptor.id());
descriptor.targets().forEach(target ->
keyClaimants.put(new KeyAtTarget(target, descriptor.key()), KeyClaimant.of(descriptor, owner)));
}
private void requireNewFeature(FeatureDescriptor<?> descriptor) {
if (featureTypes.contains(descriptor.type()) || featureIds.contains(descriptor.id())) {
throw new IllegalArgumentException("Duplicate feature: " + descriptor.id());
}
}
/** One JSON key means one setting at a target: the pack's JSON could not say which one it meant. The message
* names the claimants in a fixed order, so it does not depend on which module registered first.
*/
private void requireUnclaimedKeys(FeatureDescriptor<?> descriptor, DiscoveredModule owner) {
for (var target : descriptor.targets()) {
var earlier = keyClaimants.get(new KeyAtTarget(target, descriptor.key()));
if (earlier == null) continue;
var later = KeyClaimant.of(descriptor, owner);
var first = earlier.compareTo(later) <= 0 ? earlier : later;
var second = first == earlier ? later : earlier;
throw new IllegalArgumentException(targetName(target) + " key \"" + descriptor.key() + "\" is claimed by " + first
+ " and " + second + "; give one of the settings another key in its @Feature");
}
}
private static String targetName(Level target) {
return target.name().toLowerCase(Locale.ROOT);
}
private void checkOpen() {
if (catalog != null) {
throw new IllegalStateException("Registration has ended");
}
}
private record KeyAtTarget(Level target, String key) {}
/** Who holds a key: a field of the host's own JSON, a built-in module's feature or a pack module's, in that order. */
private record KeyClaimant(Source source, String feature, String text) implements Comparable<KeyClaimant> {
private enum Source { HOST_FIELD, BUILT_IN, PACK }
static KeyClaimant hostField() {
return new KeyClaimant(Source.HOST_FIELD, "", "Iris");
}
static KeyClaimant of(FeatureDescriptor<?> descriptor, DiscoveredModule owner) {
var source = owner.source() == DiscoveredModule.Source.HOST ? Source.BUILT_IN : Source.PACK;
return new KeyClaimant(source, descriptor.id().toString(), descriptor.id() + " (" + owner.origin() + ")");
}
@Override
public int compareTo(KeyClaimant other) {
var bySource = source.compareTo(other.source);
return bySource != 0 ? bySource : feature.compareTo(other.feature);
}
@Override
public String toString() {
return text;
}
}
}
@@ -0,0 +1,33 @@
package com.volmit.host;
import com.volmit.FeatureRegistry;
import com.volmit.ModuleLog;
import com.volmit.ModuleSetup;
import com.volmit.stage.StageGraph;
import java.util.Objects;
/** Runs a module's {@link com.volmit.IrisModule#setup} against one pack load's stage graph and registry. While it
* runs, the graph accepts the module's stages and the registry its registrations, both scoped to the module; after
* it returns, every stage the module defined must have a body.
*/
public final class ModuleSetups {
private ModuleSetups() {}
public static void run(DiscoveredModule discovered, StageGraphBuilder stages, ModuleRegistry registry) {
Objects.requireNonNull(discovered, "discovered");
Objects.requireNonNull(stages, "stages");
Objects.requireNonNull(registry, "registry");
stages.beginSetup(discovered);
registry.beginSetup(discovered);
boolean completed = false;
try {
discovered.module().setup(new Setup(stages, registry, discovered.log()));
completed = true;
} finally {
registry.endSetup();
stages.endSetup(completed);
}
}
private record Setup(StageGraph stages, FeatureRegistry registry, ModuleLog log) implements ModuleSetup {}
}
@@ -0,0 +1,72 @@
package com.volmit.host;
import com.volmit.ModuleLog;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
/** A world as one module sees it: everything is the host's world, state and extensions included, except the log, which
* is the module's own. The host hands such a view to every stage body, service call and lifecycle hook, so a line is
* labelled with the module that wrote it. A state created through the view is created with the view.
*/
final class ModuleWorld implements PackWorld {
private final PackWorld world;
private final ModuleLog log;
private ModuleWorld(PackWorld world, ModuleLog log) {
this.world = world;
this.log = log;
}
/** {@code world} as the module whose log is {@code log} sees it; a view of a view wraps the host's world itself. */
static PackWorld of(PackWorld world, ModuleLog log) {
Objects.requireNonNull(world, "world");
Objects.requireNonNull(log, "log");
PackWorld hostWorld = world instanceof ModuleWorld view ? view.world : world;
return new ModuleWorld(hostWorld, log);
}
@Override
public long seed() {
return world.seed();
}
@Override
public PackResources resources() {
return world.resources();
}
@Override
public PackSettings settings() {
return world.settings();
}
@Override
public int minHeight() {
return world.minHeight();
}
@Override
public <T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create) {
Objects.requireNonNull(create, "create");
return world.state(type, ignored -> create.apply(this));
}
@Override
public <T> Optional<T> extension(Class<T> type) {
return world.extension(type);
}
@Override
public ModuleLog log() {
return log;
}
@Override
public String toString() {
return world + " as " + log;
}
}
@@ -0,0 +1,55 @@
package com.volmit.host;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** The packages of available JDK modules that pack modules can load classes from but not use. The
* platform class loader finds every class of its modules, but a module lets other code use only the
* packages it exports to it, so a class such as {@code jdk.internal.misc.Unsafe} fails with an
* {@link IllegalAccessError} once code touches it. Pack classes live in their loader's unnamed
* module, so a package counts as exported only when every unnamed module may use it: exported
* unqualified, or opened up with {@code --add-exports <module>/<package>=ALL-UNNAMED} on the server's
* command line. Exports to named modules only do not count. Judged from the boot layer's modules, so
* nothing is loaded.
*
* <p>Modules the platform loader does not provide are {@link UnavailableJdkModules}, not listed here.
*/
final class NonExportedJdkPackages {
private static final char PACKAGE_SEPARATOR = '.';
private NonExportedJdkPackages() {}
/** A JDK package and the module that holds it. */
record JdkPackage(String name, String module) {}
/** The class's package, if an available JDK module holds it without exporting it to packs. */
static Optional<JdkPackage> packageOf(String binaryName) {
int separator = binaryName.lastIndexOf(PACKAGE_SEPARATOR);
if (separator < 0) return Optional.empty();
return Optional.ofNullable(PackagesByName.NOT_EXPORTED.get(binaryName.substring(0, separator)));
}
private static Stream<JdkPackage> packagesNotExportedToPacks(Module module) {
return module.getPackages().stream()
.filter(name -> !module.isExported(name, PackagesByName.UNNAMED_MODULE_LIKE_A_PACK))
.map(name -> new JdkPackage(name, module.getName()));
}
/** Built on first use, once per runtime: the boot layer's exports are fixed at startup. */
private static final class PackagesByName {
/** The unnamed module of a loader that defines nothing and that no export names, so it may use
* exactly what every unnamed module may use, like a new pack loader's.
*/
static final Module UNNAMED_MODULE_LIKE_A_PACK = new ClassLoader("iris-jdk-export-probe", null) {}.getUnnamedModule();
static final Map<String, JdkPackage> NOT_EXPORTED = ModuleLayer.boot().modules().stream()
.filter(UnavailableJdkModules::platformLoaderProvides)
.flatMap(NonExportedJdkPackages::packagesNotExportedToPacks)
.collect(Collectors.toUnmodifiableMap(JdkPackage::name, Function.identity()));
private PackagesByName() {}
}
}
@@ -0,0 +1,20 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.object.ObjectGenerator;
import com.volmit.object.ObjectGeneratorFactory;
import java.util.Objects;
public record ObjectRegistration<F extends IrisFeature>(
FeatureDescriptor<F> descriptor,
ObjectGeneratorFactory<F> factory) {
public ObjectRegistration {
Objects.requireNonNull(descriptor, "descriptor");
Objects.requireNonNull(factory, "factory");
}
public ObjectGenerator configure(F feature) {
var configuredFeature = descriptor.type().cast(Objects.requireNonNull(feature, "feature"));
return Objects.requireNonNull(factory.create(configuredFeature), "generator");
}
}
@@ -0,0 +1,104 @@
package com.volmit.host;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinItems;
import com.volmit.config.MinNumber;
import com.volmit.config.Ref;
import com.volmit.config.Reference;
import com.volmit.config.Required;
import com.volmit.config.ResourceRef;
import com.volmit.config.Snippet;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
/** For the host: the options a settings class declares with their annotations, independent of JSON libraries, as
* studio descriptions and settings decoders read them. Does not decode or validate values.
*/
public record OptionsMetadata(String description, String snippet, List<Option> options) {
public OptionsMetadata {
options = List.copyOf(options);
}
/** One field of a settings type. {@code minimum}, {@code maximum}, {@code minItems}, {@code reference} and
* {@code resource} are null when not declared; {@code resource} is the class of {@link ResourceRef}.
*/
public record Option(Field field, String description, boolean required,
Double minimum, Double maximum, Integer minItems, Reference reference, Class<?> resource) {
public String name() {
return field.getName();
}
public Type type() {
return field.getGenericType();
}
}
/** Reads private and inherited fields without constructing settings or accessing values. Options are
* in declaration order, a superclass's before its subclass's. Nested object types are preserved for
* the schema builder to inspect recursively.
*/
public static OptionsMetadata inspect(Class<?> type) {
var options = new ArrayList<Option>();
var names = new HashSet<String>();
for (var current : hierarchy(type)) {
for (var field : DeclaredFieldOrder.of(current)) {
int modifiers = field.getModifiers();
if (field.isSynthetic() || Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) {
continue;
}
if (!names.add(field.getName())) {
throw new IllegalArgumentException("Duplicate option: " + field.getName());
}
var desc = field.getAnnotation(Desc.class);
var min = field.getAnnotation(MinNumber.class);
var max = field.getAnnotation(MaxNumber.class);
var minItems = field.getAnnotation(MinItems.class);
var ref = field.getAnnotation(Ref.class);
var resourceRef = field.getAnnotation(ResourceRef.class);
if ((min != null || max != null) && !isNumeric(field.getType())) {
throw new IllegalArgumentException("Numeric bounds on nonnumeric option: " + field.getName());
}
if ((min != null && !Double.isFinite(min.value()))
|| (max != null && !Double.isFinite(max.value()))
|| (min != null && max != null && min.value() > max.value())) {
throw new IllegalArgumentException("Invalid bounds for option: " + field.getName());
}
if (minItems != null && (!isCollection(field.getType()) || minItems.value() < 0)) {
throw new IllegalArgumentException("Invalid @MinItems on option: " + field.getName()
+ "; it fits lists, sets and arrays, and its value is not negative");
}
options.add(new Option(field, desc == null ? "" : desc.value(), field.isAnnotationPresent(Required.class),
min == null ? null : min.value(), max == null ? null : max.value(),
minItems == null ? null : minItems.value(),
ref == null ? null : ref.value(), resourceRef == null ? null : resourceRef.value()));
}
}
var desc = type.getAnnotation(Desc.class);
var snippet = type.getAnnotation(Snippet.class);
return new OptionsMetadata(desc == null ? "" : desc.value(),
snippet == null ? "" : snippet.value(), options);
}
/** {@code type} and its superclasses below Object, the topmost first. */
private static List<Class<?>> hierarchy(Class<?> type) {
var classes = new ArrayList<Class<?>>();
for (Class<?> current = type; current != null && current != Object.class; current = current.getSuperclass()) {
classes.addFirst(current);
}
return classes;
}
private static boolean isCollection(Class<?> type) {
return List.class.isAssignableFrom(type) || java.util.Set.class.isAssignableFrom(type) || type.isArray();
}
private static boolean isNumeric(Class<?> type) {
return Number.class.isAssignableFrom(type) || type == byte.class || type == short.class
|| type == int.class || type == long.class || type == float.class || type == double.class;
}
}
@@ -0,0 +1,71 @@
package com.volmit.host;
import java.util.HashMap;
import java.util.List;
/** Checks the classes of all jars of one pack before its class loader exists, so a pack that
* cannot link fails at load with the jar to fix, not later with a {@link NoClassDefFoundError}
* during setup or generation.
*/
final class PackClassCheck {
private PackClassCheck() {}
/** Fails when a jar holds a class of an exposed host package, when a class is in two jars, or
* when a class uses a class that Iris hides from modules or that is missing from an exposed
* package. Returns the classes that nobody has, per jar; they fail only when code that needs them
* runs.
*/
static List<MissingClasses> requireLinkable(List<ModuleJar> jars, ExposedHostClassLoader host) {
jars.forEach(jar -> requireNoHostClasses(jar, host.exposed()));
requireDistinctClasses(jars);
return PackReferenceCheck.requireResolvable(jars, host);
}
/** Exposed packages belong to the host. The pack loader asks the host for their classes first, so
* a packaged copy would be silently replaced by the host's, and a module's own class there could be
* replaced by a later host class of that name.
*/
private static void requireNoHostClasses(ModuleJar jar, ExposedPackages exposed) {
var hostClasses = jar.classNames().stream()
.filter(className -> exposed.exposes(className) || ExposedPackages.isApiClass(className))
.toList();
if (hostClasses.isEmpty()) return;
var apiClasses = hostClasses.stream().filter(ExposedPackages::isApiClass).toList();
throw apiClasses.isEmpty() ? shippedHostClasses(jar, hostClasses, exposed) : shippedApiClasses(jar, apiClasses);
}
private static ModuleLoadException shippedApiClasses(ModuleJar jar, List<String> apiClasses) {
return ModuleLoadException.ofJar(jar.origin(), "Module jar " + jar.origin() + " contains Iris API class "
+ firstAndCount(apiClasses) + "; Iris provides the API at runtime, so mark the Iris API dependency"
+ " compileOnly (Maven: provided) and keep module classes out of " + ExposedPackages.API_PACKAGE + ".*");
}
private static ModuleLoadException shippedHostClasses(ModuleJar jar, List<String> hostClasses, ExposedPackages exposed) {
var hostPackage = exposed.packageOf(hostClasses.getFirst());
return ModuleLoadException.ofJar(jar.origin(), "Module jar " + jar.origin() + " contains class " + firstAndCount(hostClasses)
+ " of package " + hostPackage + ", which Iris provides to modules at runtime; compile against it"
+ " compileOnly (Maven: provided) instead of shipping it, and keep module classes out of " + hostPackage + ".*");
}
private static String firstAndCount(List<String> classNames) {
var others = classNames.size() == 1 ? "" : " and " + (classNames.size() - 1) + " more";
return classNames.getFirst() + others;
}
/** The shared pack loader would otherwise silently use whichever copy comes first in file name order. */
private static void requireDistinctClasses(List<ModuleJar> jars) {
var owners = new HashMap<String, ModuleJar>();
for (var jar : jars) {
for (var className : jar.classNames()) {
var owner = owners.putIfAbsent(className, jar);
if (owner != null) throw duplicateClass(className, owner, jar);
}
}
}
private static ModuleLoadException duplicateClass(String className, ModuleJar first, ModuleJar second) {
return ModuleLoadException.ofJar(second.origin(), "Class " + className + " is in both module jars " + first.origin()
+ " and " + second.origin() + "; every class of a pack must come from one jar, so relocate"
+ " shaded libraries or keep shared classes in one module");
}
}
@@ -0,0 +1,243 @@
package com.volmit.host;
import com.volmit.IrisModule;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.System.Logger.Level;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** The module jars of one pack: every {@code <pack>/modules/*.jar}, each with the modules it lists,
* ordered by file name so the result never depends on directory listing order. Hosts normally load packs
* through {@link LoadedPack}, which uses this.
*
* <p>The load first copies the jars into a fresh temporary directory ({@link JarSnapshot}) and works
* only on the copies, so the originals stay free to be replaced, even on Windows, and the load sees one
* consistent set of jars. Messages and origins name the originals ({@code modules/moss.jar}). Copies
* are deleted when the pack closes or its load fails; copies a crashed process left behind are removed
* by a later load ({@link StaleJarSnapshots}).
*
* <p>All jars of a pack share one class loader. A pack jar can therefore name another pack jar's
* stage constants in {@code requires(...)}. Besides the pack's own classes, that loader sees only
* the exposed host packages and the JDK ({@link ExposedHostClassLoader}); packs do not see each
* other or Iris internals. The Iris API is always exposed; the host may expose more packages, such
* as those of built-in modules whose stages packs may require. Before the loader exists, the load
* fails if a jar holds classes of an exposed package, if a class is in two jars, or if a class uses
* a class that Iris hides from modules or that is missing from an exposed package.
* Classes that nobody has are not an error, because the JVM only needs them when code that uses
* them runs; they are reported as {@link #missingClasses()}, except those in the optional packages
* the jar's module declares in its {@link com.volmit.ModuleInfo}.
*
* <p>A successful load logs one INFO summary of the pack's modules through a {@link System.Logger}, by
* default the one named after this class, or the host's from {@link ModuleHost#loggingTo}, and one
* WARNING listing the missing classes, if any.
*
* <p>Close this when the pack unloads, after dropping everything built from its modules, such as
* {@link LoadedModules}. Classes not loaded before then can no longer be loaded.
*/
public final class PackModules implements AutoCloseable {
public static final String MODULES_DIRECTORY = "modules";
static final String JAR_EXTENSION = ".jar";
static final String BUNDLED_ORIGIN_SUFFIX = " (bundled with the host)";
private static final String TEMPORARY_DIRECTORY_PROPERTY = "java.io.tmpdir";
static final System.Logger DEFAULT_LOGGER = System.getLogger(PackModules.class.getName());
private final List<DiscoveredModule> modules;
private final List<MissingClasses> missingClasses;
private final URLClassLoader loader;
private final JarSnapshot snapshot;
private PackModules(
List<DiscoveredModule> modules, List<MissingClasses> missingClasses, URLClassLoader loader, JarSnapshot snapshot) {
this.modules = List.copyOf(modules);
this.missingClasses = List.copyOf(missingClasses);
this.loader = loader;
this.snapshot = snapshot;
}
/** Loads the modules of the pack at {@code packRoot}, exposing only the Iris API. */
public static PackModules load(Path packRoot) {
return load(packRoot, List.of());
}
/** Loads the modules of the pack at {@code packRoot}. A pack without a modules directory has
* no modules. A load error is a {@link ModuleLoadException} that names the offending jar relative to the pack root.
*
* @param exposedHostPackages host packages pack modules may use besides the Iris API, which is
* always exposed, such as the packages of built-in modules whose stages packs may require.
* Each exposes the package and its subpackages from the loader that defines the API. A
* trailing dot is accepted; blank names and wildcards are rejected.
*/
public static PackModules load(Path packRoot, Collection<String> exposedHostPackages) {
return load(packRoot, exposedHostPackages, systemTemporaryDirectory());
}
/** Like {@link #load(Path, Collection)}, copying the jars below {@code temporaryRoot}. */
static PackModules load(Path packRoot, Collection<String> exposedHostPackages, Path temporaryRoot) {
return load(packRoot, exposedHostPackages, temporaryRoot, DEFAULT_LOGGER);
}
/** Like {@link #load(Path, Collection)}, copying the jars below {@code temporaryRoot} and logging to {@code logger}. */
static PackModules load(Path packRoot, Collection<String> exposedHostPackages, Path temporaryRoot, System.Logger logger) {
return load(packRoot, exposedHostPackages, List.of(), temporaryRoot, logger);
}
/** Like {@link #load(Path, Collection, Path, System.Logger)}, also loading the host's {@code bundledJars} as if they were
* in the pack, before its own jars and in the given order.
*/
static PackModules load(Path packRoot, Collection<String> exposedHostPackages, List<Path> bundledJars, Path temporaryRoot,
System.Logger logger) {
Objects.requireNonNull(packRoot, "packRoot");
Objects.requireNonNull(logger, "logger");
var host = new ExposedHostClassLoader(IrisModule.class.getClassLoader(), ExposedPackages.apiAnd(exposedHostPackages));
StaleJarSnapshots.remove(temporaryRoot);
var snapshot = JarSnapshot.take(sourceJars(packRoot, bundledJars, findModuleJars(packRoot)), temporaryRoot);
try {
var packModules = loadSnapshot(packRoot, snapshot, host, logger);
logLoad(logger, packName(packRoot), packModules);
return packModules;
} catch (RuntimeException failure) {
snapshot.deleteAfterFailure(failure);
throw ModuleLoadException.of(failure);
} catch (Error failure) {
snapshot.deleteAfterFailure(failure);
throw failure;
}
}
/** The modules of all jars, in jar file name order and, within a jar, in the order it lists them. */
public List<DiscoveredModule> modules() {
return modules;
}
/** Per jar that uses any, in jar file name order, the classes that neither the pack, Iris nor the
* JDK has and that are outside the optional packages the jar's module declares. Empty when every
* class the jars use exists or is declared optional.
*/
public List<MissingClasses> missingClasses() {
return missingClasses;
}
/** Closes the class loader, then deletes the jar copies, which an open loader would keep locked on Windows. */
@Override
public void close() {
try {
loader.close();
} catch (IOException exception) {
var failure = new UncheckedIOException("Cannot close module class loader " + loader.getName(), exception);
snapshot.deleteAfterFailure(failure);
throw failure;
}
snapshot.delete();
}
private static Path systemTemporaryDirectory() {
return Path.of(System.getProperty(TEMPORARY_DIRECTORY_PROPERTY));
}
private static PackModules loadSnapshot(Path packRoot, JarSnapshot snapshot, ExposedHostClassLoader host, System.Logger logger) {
var jars = snapshot.jars().stream().map(ModuleJar::read).toList();
var missingClasses = PackClassCheck.requireLinkable(jars, host);
return defineModules(packRoot, jars, missingClasses, host, snapshot, logger);
}
private static List<Path> findModuleJars(Path packRoot) {
var directory = packRoot.resolve(MODULES_DIRECTORY);
if (!Files.isDirectory(directory)) return List.of();
try (var entries = Files.list(directory)) {
return entries
.filter(PackModules::isJar)
.sorted(Comparator.comparing(jar -> jar.getFileName().toString()))
.toList();
} catch (IOException exception) {
throw new ModuleLoadException(null, null, "Cannot list module jars in " + directory, exception);
}
}
private static List<JarSnapshot.SourceJar> sourceJars(Path packRoot, List<Path> bundledJars, List<Path> packJars) {
var bundled = bundledJars.stream().map(jar -> new JarSnapshot.SourceJar(bundledOrigin(jar), jar));
var own = packJars.stream().map(jar -> new JarSnapshot.SourceJar(packRoot.relativize(jar).toString(), jar));
return Stream.concat(bundled, own).toList();
}
/** How messages name a bundled jar: its file name, marked as the host's. */
static String bundledOrigin(Path bundledJar) {
return fileName(bundledJar) + BUNDLED_ORIGIN_SUFFIX;
}
private static String fileName(Path jar) {
return jar.getFileName().toString();
}
private static boolean isJar(Path path) {
return Files.isRegularFile(path) && path.getFileName().toString().endsWith(JAR_EXTENSION);
}
private static PackModules defineModules(
Path packRoot, List<ModuleJar> jars, List<MissingClasses> missingClasses, ClassLoader host, JarSnapshot snapshot,
System.Logger logger) {
var loader = newPackClassLoader(packRoot, jars, host);
try {
var modules = createModules(jars, loader, snapshot, logger);
return new PackModules(modules, withoutDeclaredOptional(missingClasses, modules), loader, snapshot);
} catch (RuntimeException | Error failure) {
closeAfterFailure(loader, failure);
throw failure;
}
}
private static URLClassLoader newPackClassLoader(Path packRoot, List<ModuleJar> jars, ClassLoader host) {
var urls = jars.stream().map(ModuleJar::url).toArray(URL[]::new);
return new URLClassLoader("pack:" + packName(packRoot), urls, host);
}
private static void logLoad(System.Logger logger, String packName, PackModules packModules) {
logger.log(Level.INFO, () -> PackModulesSummary.describe(packName, packModules.modules()));
if (packModules.missingClasses().isEmpty()) return;
logger.log(Level.WARNING, () -> MissingClassesWarning.describe(packName, packModules.missingClasses()));
}
private static String packName(Path packRoot) {
var name = packRoot.getFileName();
return name == null ? packRoot.toString() : name.toString();
}
private static List<DiscoveredModule> createModules(
List<ModuleJar> jars, ClassLoader loader, JarSnapshot snapshot, System.Logger logger) {
return jars.stream()
.flatMap(jar -> jar.createModules(loader, snapshot).stream())
.map(module -> module.loggingTo(logger))
.toList();
}
/** A module's optional packages excuse only its own jar's missing classes; a jar with several
* modules is excused by the optional packages of all of them. They are read from {@code info()},
* so this runs after the entry classes exist; errors were decided before that and never depend on them.
*/
private static List<MissingClasses> withoutDeclaredOptional(List<MissingClasses> missingClasses, List<DiscoveredModule> modules) {
var optionalPackages = modules.stream()
.collect(Collectors.groupingBy(DiscoveredModule::origin,
Collectors.flatMapping(found -> found.info().optionalPackages().stream(), Collectors.toList())));
return missingClasses.stream()
.map(jar -> jar.outside(optionalPackages.get(jar.origin())))
.filter(Predicate.not(MissingClasses::isEmpty))
.toList();
}
private static void closeAfterFailure(URLClassLoader loader, Throwable failure) {
try {
loader.close();
} catch (IOException exception) {
failure.addSuppressed(exception);
}
}
}
@@ -0,0 +1,29 @@
package com.volmit.host;
import java.util.List;
/** The one log message a pack load writes: which modules the pack uses and which jar each comes
* from.
*/
final class PackModulesSummary {
private static final String INDENT = " ";
private PackModulesSummary() {}
static String describe(String packName, List<DiscoveredModule> modules) {
if (modules.isEmpty()) {
return "Pack " + packName + " uses no modules: no jars in its " + PackModules.MODULES_DIRECTORY + " directory";
}
var text = new StringBuilder("Pack ").append(packName).append(" uses ").append(modules.size())
.append(modules.size() == 1 ? " module:" : " modules:");
for (var module : modules) {
text.append('\n').append(INDENT).append(describe(module));
}
return text.toString();
}
private static String describe(DiscoveredModule discovered) {
var info = discovered.info();
return info.name() + " (" + info.id() + " " + info.version() + ") from " + discovered.origin();
}
}
@@ -0,0 +1,176 @@
package com.volmit.host;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Predicate;
/** Decides for every class a pack's jars use whether the pack loader will find it, and why not
* when it won't. Nothing is loaded: the host's classes are judged by their class files.
*
* <p>The JVM resolves a class only when code first needs it, so a class nobody has is not an
* error: bundled libraries reference optional dependencies they only use when present. A class
* that Iris has but hides, a class of a JDK module packs cannot see or of a JDK package packs may
* not use, or a class missing from a package Iris exposes always fails the load.
*/
final class PackReferenceCheck {
private static final int MAX_REPORTED_REFERENCES_PER_JAR = 10;
private static final String INDENT = " ";
/** Where the pack loader would find a referenced class. */
private enum Resolution {
/** In the pack, an exposed host package, or the JDK. */
PROVIDED,
/** Nowhere: an optional dependency, which only fails when code that needs it runs. */
ABSENT,
HIDDEN_HOST_CLASS(
"uses classes that exist in Iris but are hidden from modules:",
"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."),
/** A JDK module outside the platform class loader, such as jdk.compiler. */
UNAVAILABLE_JDK_CLASS(
"uses classes of JDK modules that are not available to modules:",
"Modules can use only the JDK modules of the platform class loader, such as java.base, java.sql and"
+ " java.net.http."),
/** A package of an available JDK module that it does not export to packs, such as jdk.internal.misc. */
NOT_EXPORTED_JDK_CLASS(
"uses classes of JDK packages that are not exported to modules:",
"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."),
MISSING_HOST_CLASS(
"uses classes that this Iris does not have, in packages Iris provides to modules:",
"The jar was built against a different Iris API or Iris version."),
/** A class of an exposed package that the library has but the host's own jar leaves out. */
LEFT_OUT_HOST_CLASS(
"uses classes of the libraries Iris provides to modules that Iris's jar leaves out:",
"Iris strips classes it does not use itself from the libraries it ships. Use another class, or have"
+ " Iris keep the class you need.");
private final String header;
private final String advice;
Resolution() {
this(null, null);
}
Resolution(String header, String advice) {
this.header = header;
this.advice = advice;
}
boolean failsLoad() {
return header != null;
}
}
private final Set<String> packClasses = new HashSet<>();
private final Map<String, Resolution> outsidePack = new HashMap<>();
private final ExposedHostClassLoader host;
private PackReferenceCheck(List<ModuleJar> jars, ExposedHostClassLoader host) {
this.host = host;
jars.forEach(jar -> packClasses.addAll(jar.classNames()));
}
/** Fails when a jar uses a class Iris hides, a class of a JDK module packs cannot see or of a JDK
* package packs may not use, or a class missing from a package Iris exposes.
* Returns the classes nobody has, per jar, for jars that use any.
*/
static List<MissingClasses> requireResolvable(List<ModuleJar> jars, ExposedHostClassLoader host) {
var check = new PackReferenceCheck(jars, host);
var references = jars.stream().map(check::resolve).toList();
requireNoFailures(references);
return references.stream()
.filter(JarReferences::missesClasses)
.map(JarReferences::missingClasses)
.toList();
}
private JarReferences resolve(ModuleJar jar) {
var references = jar.classes().stream()
.flatMap(type -> type.references().stream().map(target -> new Reference(type.name(), target, resolve(target))))
.filter(reference -> reference.resolution() != Resolution.PROVIDED)
.toList();
return new JarReferences(jar, references);
}
private Resolution resolve(String className) {
if (packClasses.contains(className)) return Resolution.PROVIDED;
return outsidePack.computeIfAbsent(className, this::resolveOutsidePack);
}
/** Access comes first: whichever loader finds a JDK class, its module still decides who may use it. */
private Resolution resolveOutsidePack(String className) {
if (NonExportedJdkPackages.packageOf(className).isPresent()) return Resolution.NOT_EXPORTED_JDK_CLASS;
if (host.leavesOut(className)) return Resolution.LEFT_OUT_HOST_CLASS;
if (host.hasClass(className)) return Resolution.PROVIDED;
if (host.exposed().exposes(className)) return Resolution.MISSING_HOST_CLASS;
if (UnavailableJdkModules.moduleOf(className).isPresent()) return Resolution.UNAVAILABLE_JDK_CLASS;
if (host.hostHasClass(className)) return Resolution.HIDDEN_HOST_CLASS;
return Resolution.ABSENT;
}
private static void requireNoFailures(List<JarReferences> jars) {
var failures = Arrays.stream(Resolution.values())
.filter(Resolution::failsLoad)
.map(failure -> describeFailure(failure, jars))
.filter(Predicate.not(String::isEmpty))
.toList();
if (failures.isEmpty()) return;
throw ModuleLoadException.ofPack(String.join("\n", failures));
}
private static String describeFailure(Resolution failure, List<JarReferences> jars) {
var text = new StringBuilder();
for (var jar : jars) jar.describeTo(failure, text);
if (text.isEmpty()) return "";
return text.append(failure.advice).toString();
}
private record Reference(String source, String target, Resolution resolution) {
String describe() {
var text = source + " -> " + target;
return switch (resolution) {
case UNAVAILABLE_JDK_CLASS -> text + " (JDK module " + UnavailableJdkModules.moduleOf(target).orElseThrow() + ")";
case NOT_EXPORTED_JDK_CLASS -> text + " (" + describeNotExported(NonExportedJdkPackages.packageOf(target).orElseThrow()) + ")";
default -> text;
};
}
private static String describeNotExported(NonExportedJdkPackages.JdkPackage jdkPackage) {
return "package " + jdkPackage.name() + " of " + jdkPackage.module() + " is not exported";
}
}
/** The references of one jar the pack loader would not resolve. */
private record JarReferences(ModuleJar jar, List<Reference> unresolved) {
boolean missesClasses() {
return unresolved.stream().anyMatch(reference -> reference.resolution() == Resolution.ABSENT);
}
MissingClasses missingClasses() {
var classNames = new TreeSet<String>();
with(Resolution.ABSENT).forEach(reference -> classNames.add(reference.target()));
return new MissingClasses(jar.origin(), List.copyOf(classNames));
}
void describeTo(Resolution failure, StringBuilder text) {
var references = with(failure);
if (references.isEmpty()) return;
text.append("Module jar ").append(jar.origin()).append(' ').append(failure.header).append('\n');
references.stream().limit(MAX_REPORTED_REFERENCES_PER_JAR)
.forEach(reference -> text.append(INDENT).append(reference.describe()).append('\n'));
int hidden = references.size() - MAX_REPORTED_REFERENCES_PER_JAR;
if (hidden > 0) text.append(INDENT).append("and ").append(hidden).append(" more\n");
}
private List<Reference> with(Resolution resolution) {
return unresolved.stream().filter(reference -> reference.resolution() == resolution).toList();
}
}
}
@@ -0,0 +1,212 @@
package com.volmit.host;
import com.volmit.host.schema.FeatureRole;
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.ValueKind;
import com.volmit.resource.ResourceId;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/** Describes a loaded pack's catalogued settings and resource kinds for studio. Fails the load, naming the class,
* field and module, on what the host could not render: an unsupported field type, a misplaced {@code @Ref} or
* {@code @ResourceRef}, a class without a usable no-argument constructor, a snippet name used twice, a pack
* class's snippet name outside its module's path, or a pack module's resource kind read into a host type.
*/
@SuppressWarnings("removal") // held types and host kinds are transitional, until the cut-over
final class PackSchemaBuilder {
private static final Pattern SNIPPET_NAME = Pattern.compile("[a-z0-9_.-]+(/[a-z0-9_.-]+)*");
private static final Pattern RELATIVE_SEGMENT = Pattern.compile("(^|/)\\.\\.?(/|$)");
private static final char FOLDER_SEPARATOR = '/';
private final List<DiscoveredModule> modules;
private final TypeDrafts drafts;
private final HostTypes hostTypes;
private PackSchemaBuilder(FeatureCatalog catalog, List<DiscoveredModule> modules, HostTypes hostTypes) {
this.modules = modules;
this.hostTypes = hostTypes;
this.drafts = new TypeDrafts(hostTypes, type -> resourceKindOf(catalog, type));
}
static PackSchema describe(FeatureCatalog catalog, List<DiscoveredModule> modules, HostTypes hostTypes) {
return new PackSchemaBuilder(catalog, modules, hostTypes).describe(catalog);
}
private PackSchema describe(FeatureCatalog catalog) {
var features = catalogued(catalog).map(this::draft).toList();
var resources = catalog.resourceKinds().stream().map(this::describe).toList();
catalog.heldTypes().forEach(this::draft);
requireUniqueSnippets();
var types = completeTypes();
return new PackSchema(features.stream().map(feature -> feature.complete(types)).toList(), resources,
List.copyOf(types.values()));
}
private static Optional<ResourceId> resourceKindOf(FeatureCatalog catalog, Class<?> type) {
return catalog.resourceKinds().stream()
.map(ResourceKindRegistration::kind)
.filter(kind -> kind.type() == type)
.map(com.volmit.resource.ResourceKind::id)
.findFirst();
}
/** A built-in kind may read into a class the host describes itself, as built-in settings may hold one. */
private ResourceKindSchema describe(ResourceKindRegistration registration) {
var kind = registration.kind();
var module = registration.module();
return new ResourceKindSchema(kind.id(), module.info(), kind.folder(), fileType(registration));
}
private ValueKind fileType(ResourceKindRegistration registration) {
var type = registration.kind().type();
if (!hostTypes.contains(type)) return drafts.resourceKind(SchemaSource.resourceKind(registration.kind(), registration.module()));
if (registration.module().source() == DiscoveredModule.Source.HOST) return new ValueKind.HostKind(type.getName());
throw new IllegalArgumentException("Resource kind " + registration.kind().id() + " of module " + registration.module()
+ " reads into " + type.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");
}
/** One catalogued settings type and why it is in the catalog. */
private record Catalogued(FeatureDescriptor<?> descriptor, FeatureRole role) {}
/** A feature whose settings class is drafted but whose defaults are not converted yet. */
private record FeatureDraft(Catalogued catalogued, DiscoveredModule owner) {
FeatureSchema complete(Map<String, ObjectType> types) {
var descriptor = catalogued.descriptor();
return new FeatureSchema(descriptor.id(), descriptor.name(), catalogued.role(), owner.info(), descriptor.key(), descriptor.root(),
descriptor.targets(),types.get(descriptor.type().getName()));
}
}
/** Ordered by feature id, so which settings an error names first never depends on discovery. */
private static Stream<Catalogued> catalogued(FeatureCatalog catalog) {
var settings = catalog.settings().stream().map(descriptor -> new Catalogued(descriptor, FeatureRole.SETTINGS));
var objects = catalog.objects().stream()
.map(registration -> new Catalogued(registration.descriptor(), FeatureRole.OBJECT_GENERATOR));
return Stream.concat(settings, objects).sorted(Comparator.comparing(catalogued -> catalogued.descriptor().id()));
}
private void draft(HeldTypeRegistration held) {
drafts.settings(SchemaSource.heldType(held));
}
private FeatureDraft draft(Catalogued catalogued) {
var owner = ownerOf(catalogued.descriptor());
drafts.settings(SchemaSource.settings(catalogued.descriptor(), owner));
return new FeatureDraft(catalogued, owner);
}
/** Registration checked that a module owns every catalogued id; module ids are unique and have no '/', so only one can. */
private DiscoveredModule ownerOf(FeatureDescriptor<?> descriptor) {
return modules.stream()
.filter(module -> module.info().ownsId(descriptor.id()))
.findFirst()
.orElseThrow(() -> new IllegalStateException("No loaded module owns feature id " + descriptor.id()));
}
private void requireUniqueSnippets() {
var owners = new HashMap<String, TypeDrafts.TypeDraft>();
for (var draft : sortedDrafts()) {
var snippet = draft.metadata().snippet();
if (snippet.isEmpty()) continue;
requireSnippetName(snippet, draft);
requirePackSnippetPath(snippet, draft);
var previous = owners.putIfAbsent(snippet, draft);
if (previous != null) throw snippetCollision(snippet, previous, draft);
}
}
private static void requireSnippetName(String snippet, TypeDrafts.TypeDraft draft) {
if (SNIPPET_NAME.matcher(snippet).matches() && !RELATIVE_SEGMENT.matcher(snippet).find()) return;
throw new IllegalArgumentException("Snippet name '" + snippet + "' of " + draft.type().getName() + " of "
+ draft.source() + " is not a folder path; packs write snippets under snippet/<name>/, so use lowercase"
+ " letters, digits, '-', '_' and '.', with '/' between folders");
}
/** A pack class keeps its snippets under the folder of a module of its pack,
* {@code snippet/<namespace>/<path>/}, so they can never collide with Iris's own or another module's.
*/
private void requirePackSnippetPath(String snippet, TypeDrafts.TypeDraft draft) {
if (!isPackClass(draft.type())) return;
if (packModules().anyMatch(module -> isUnderModuleFolder(snippet, module))) return;
var example = moduleFolder(draft.source().module()) + FOLDER_SEPARATOR + lastSegment(snippet);
throw new IllegalArgumentException("Snippet name '" + snippet + "' of " + draft.type().getName() + " of "
+ draft.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 + "' (folder snippet/" + example + "/)");
}
private boolean isPackClass(Class<?> type) {
return packModules().anyMatch(module -> module.module().getClass().getClassLoader() == type.getClassLoader());
}
private Stream<DiscoveredModule> packModules() {
return modules.stream().filter(module -> module.source() == DiscoveredModule.Source.PACK);
}
private static boolean isUnderModuleFolder(String snippet, DiscoveredModule module) {
var folder = moduleFolder(module);
return snippet.equals(folder) || snippet.startsWith(folder + FOLDER_SEPARATOR);
}
private static String moduleFolder(DiscoveredModule module) {
var id = module.info().id();
return id.namespace() + FOLDER_SEPARATOR + id.path();
}
private static String lastSegment(String snippet) {
return snippet.substring(snippet.lastIndexOf(FOLDER_SEPARATOR) + 1);
}
private static IllegalArgumentException snippetCollision(String snippet, TypeDrafts.TypeDraft first, TypeDrafts.TypeDraft second) {
return new IllegalArgumentException("Snippet name '" + snippet + "' is used by " + first.type().getName() + " of "
+ first.source() + " and by " + second.type().getName() + " of " + second.source()
+ "; studio describes snippet/" + snippet + "/ by one class, so give each its own name");
}
private List<TypeDrafts.TypeDraft> sortedDrafts() {
return drafts.drafts().stream().sorted(Comparator.comparing(draft -> draft.type().getName())).toList();
}
private Map<String, ObjectType> completeTypes() {
var byName = new HashMap<String, TypeDrafts.TypeDraft>();
drafts.drafts().forEach(draft -> byName.put(draft.type().getName(), draft));
var defaults = new DefaultValues(byName);
var types = new TreeMap<String, ObjectType>();
byName.forEach((name, draft) -> types.put(name, objectType(draft, defaults)));
return types;
}
private static ObjectType objectType(TypeDrafts.TypeDraft draft, DefaultValues defaults) {
var metadata = draft.metadata();
var options = draft.options().stream().map(option -> schemaOption(option, defaults)).toList();
var snippet = metadata.snippet().isEmpty() ? Optional.<String>empty() : Optional.of(metadata.snippet());
return new ObjectType(draft.type().getName(), metadata.description(), snippet, options);
}
private static SchemaOption schemaOption(TypeDrafts.OptionDraft draft, DefaultValues defaults) {
var option = draft.option();
return new SchemaOption(option.name(), draft.kind(), option.description(), option.required(),
bound(option.minimum()), bound(option.maximum()), minItems(option.minItems()), defaults.of(draft.defaultValue(), draft.kind()));
}
private static OptionalInt minItems(Integer value) {
return value == null ? OptionalInt.empty() : OptionalInt.of(value);
}
private static OptionalDouble bound(Double value) {
return value == null ? OptionalDouble.empty() : OptionalDouble.of(value);
}
}
@@ -0,0 +1,33 @@
package com.volmit.host;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
/** The most any stage of a pipeline writes beyond its footprint, so the host can prepare the area and
* mantle a chunk or placement may touch. Inactive stages count too: activation is decided per
* invocation, the area once per pack.
*
* @param blocks the largest {@link StageReach#blocks()} of the pipeline's stages, in blocks along X and Z
* @param mantleLayers for each mantle layer some stage writes, by layer id in id order, the largest
* reach of the stages that write it
*/
public record PipelineReach(int blocks, Map<String, Integer> mantleLayers) {
public PipelineReach {
if (blocks < 0) throw new IllegalArgumentException("Negative reach: " + blocks);
mantleLayers = Collections.unmodifiableMap(new TreeMap<>(mantleLayers));
}
static PipelineReach of(Iterable<ResolvedStage> stages) {
int blocks = 0;
var layers = new TreeMap<String, Integer>();
for (var stage : stages) {
int stageBlocks = stage.fixedReachBlocks();
blocks = Math.max(blocks, stageBlocks);
for (var layer : stage.reach().mantleLayers()) {
layers.merge(layer.id(), stageBlocks, Math::max);
}
}
return new PipelineReach(blocks, layers);
}
}
@@ -0,0 +1,157 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings;
import com.volmit.config.SettingsStack;
import com.volmit.object.ObjectBlock;
import com.volmit.object.ObjectTransformer;
import com.volmit.placement.PlacementAccess;
import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementRequest;
import com.volmit.random.WorldRandom;
import com.volmit.world.PackWorld;
import com.volmit.stage.BlockStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.BlockView;
import com.volmit.world.TerrainSampler;
import java.util.Objects;
import java.util.Optional;
/** The context every stage of one placement attempt receives. Block accessors work only while
* a block pass is running.
*/
final class PlacementInvocation implements BlockStageContext {
private enum Progress { RUNNING, REJECTED }
private enum BlockStatus { OUTSIDE_PASS, VISIBLE, SKIPPED }
private final StageInvocation stages;
private final PlacementRequest request;
private final PlacementContext inputs;
private final PlacementAccess access;
private Progress progress = Progress.RUNNING;
private String rejection;
private BlockStatus blockStatus = BlockStatus.OUTSIDE_PASS;
private ObjectBlock block;
PlacementInvocation(StageInvocation stages, PlacementRequest request, PlacementContext inputs, PlacementAccess access) {
this.stages = stages;
this.request = Objects.requireNonNull(request, "request");
this.inputs = Objects.requireNonNull(inputs, "inputs");
this.access = access;
}
StageInvocation stages() {
return stages;
}
boolean isRejected() {
return progress == Progress.REJECTED;
}
String rejection() {
return rejection;
}
void beginBlock(ObjectBlock next) {
block = next;
blockStatus = BlockStatus.VISIBLE;
}
boolean isBlockSkipped() {
return blockStatus == BlockStatus.SKIPPED;
}
void endBlockPass() {
block = null;
blockStatus = BlockStatus.OUTSIDE_PASS;
}
@Override
public <O> O output(Stage<O> stage) {
return stages.output(stage);
}
@Override
public <S extends IrisFeature> SettingsStack<S> configured(Class<S> settingsType) {
return stages.configured(settingsType);
}
@Override
public PlacementRequest request() {
return request;
}
@Override
public PlacementAccess access() {
return access;
}
@Override
public void reject(String reason) {
Objects.requireNonNull(reason, "reason");
if (progress == Progress.RUNNING) {
progress = Progress.REJECTED;
rejection = reason;
}
}
@Override
public ObjectBlock block() {
requireBlockPass();
return block;
}
@Override
public void replace(ObjectBlock replacement) {
requireBlockPass();
block = Objects.requireNonNull(replacement, "block");
}
@Override
public void skip() {
requireBlockPass();
blockStatus = BlockStatus.SKIPPED;
}
@Override
public PackWorld world() {
return stages.world(inputs.world());
}
@Override
public <T> Optional<T> extension(Class<T> type) {
return inputs.extension(type);
}
@Override
public WorldRandom random() {
return stages.random();
}
@Override
public TerrainSampler terrain() {
return inputs.terrain();
}
@Override
public FeatureSettings settings() {
return inputs.settings();
}
@Override
public ObjectTransformer objects() {
return inputs.objects();
}
@Override
public BlockView blocks() {
return inputs.blocks();
}
private void requireBlockPass() {
if (blockStatus == BlockStatus.OUTSIDE_PASS) {
throw new IllegalStateException("The current block is only available to block stages");
}
}
}
@@ -0,0 +1,29 @@
package com.volmit.host;
import java.util.Objects;
import java.util.Optional;
/** Result of one placement attempt. A rejected attempt committed nothing. */
public record PlacementOutcome(Status status, Optional<String> rejection) {
public enum Status { PLACED, REJECTED }
public PlacementOutcome {
Objects.requireNonNull(status, "status");
Objects.requireNonNull(rejection, "rejection");
if ((status == Status.REJECTED) != rejection.isPresent()) {
throw new IllegalArgumentException("Only rejected placements carry a rejection reason");
}
}
static PlacementOutcome placed() {
return new PlacementOutcome(Status.PLACED, Optional.empty());
}
static PlacementOutcome rejected(String reason) {
return new PlacementOutcome(Status.REJECTED, Optional.of(reason));
}
public boolean isPlaced() {
return status == Status.PLACED;
}
}
@@ -0,0 +1,137 @@
package com.volmit.host;
import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementEdit;
import com.volmit.placement.PlacementRequest;
import com.volmit.stage.Pipeline;
import java.util.Objects;
/** Reference executor of a resolved placement graph. It runs active stages in resolved order;
* each fused block pass loops once over the request object's blocks and runs every active stage
* of the pass for a block before moving to the next block. A rejection stops the attempt after
* the current stage or block; the edit is committed only when no stage rejects or throws.
*/
public final class PlacementRunner {
private final ResolvedGraph graph;
public PlacementRunner(ResolvedGraph graph) {
this.graph = Objects.requireNonNull(graph, "graph");
if (graph.pipeline() != Pipeline.PLACEMENT) {
throw new IllegalArgumentException("Expected a placement graph, got " + graph.pipeline());
}
}
/** Takes ownership of a fresh edit and closes it on success, rejection or exception.
* The host prepares the edit area, the read-only inputs and the settings configured for this
* placement, and derives {@code invocationSeed} from the world seed and the placement's stable
* identity. Each stage draws from its own stream of that seed ({@link StageStreams}). Stages never
* receive commit/close rights. {@code timings} hears how long each stage that ran took; a block stage
* is reported once per pass, with its time summed over the blocks it ran for, when the pass ends.
*/
public PlacementOutcome place(
PlacementRequest request,
PlacementEdit edit,
PlacementContext inputs,
long invocationSeed,
ConfiguredSettings settings,
StageTimings timings) {
Objects.requireNonNull(edit, "edit");
try (edit) {
Objects.requireNonNull(timings, "timings");
var stages = new StageInvocation(graph, invocationSeed, settings);
var access = PlacementViews.restrict(edit, edit.bounds());
var placement = new PlacementInvocation(stages, request, inputs, access);
runSegments(placement, timings);
if (placement.isRejected()) {
return PlacementOutcome.rejected(placement.rejection());
}
edit.commit();
return PlacementOutcome.placed();
}
}
private void runSegments(PlacementInvocation placement, StageTimings timings) {
for (var segment : graph.segments()) {
if (placement.isRejected()) {
return;
}
switch (segment.kind()) {
case INVOCATION -> runInvocationStage(segment.start(), placement, timings);
case BLOCK -> runBlockPass(segment, placement, timings);
}
}
}
private void runInvocationStage(int position, PlacementInvocation placement, StageTimings timings) {
if (!placement.stages().isActive(position)) {
return;
}
long started = System.nanoTime();
placement.stages().runInvocationStage(position, placement, placement::isRejected);
timings.record(graph.stages().get(position), System.nanoTime() - started);
}
private void runBlockPass(Segment segment, PlacementInvocation placement, StageTimings timings) {
var stages = placement.stages();
int[] active = stages.activePositions(segment);
if (active.length == 0) {
return;
}
var pass = new BlockPass(active.length);
for (int index = 0; index < active.length; index++) {
pass.accumulators[index] = stages.newAccumulator(active[index]);
}
for (var block : placement.request().object().blocks()) {
placement.beginBlock(block);
runBlockStages(active, pass, placement);
if (placement.isRejected()) {
break;
}
}
placement.endBlockPass();
reportBlockPass(active, pass, timings);
if (placement.isRejected()) {
return;
}
for (int index = 0; index < active.length; index++) {
stages.complete(active[index], pass.accumulators[index]);
}
}
/** One nanoTime per stage boundary: each stage's time ends where the next one's starts. */
private static void runBlockStages(int[] active, BlockPass pass, PlacementInvocation placement) {
long started = System.nanoTime();
for (int index = 0; index < active.length; index++) {
placement.stages().runBlockStage(active[index], placement, pass.accumulators[index]);
long finished = System.nanoTime();
pass.nanos[index] += finished - started;
pass.ran[index] = true;
started = finished;
if (placement.isRejected() || placement.isBlockSkipped()) {
return;
}
}
}
private void reportBlockPass(int[] active, BlockPass pass, StageTimings timings) {
for (int index = 0; index < active.length; index++) {
if (pass.ran[index]) {
timings.record(graph.stages().get(active[index]), pass.nanos[index]);
}
}
}
/** Per active stage of one block pass, in pass order: its accumulator, its summed time and whether it ran. */
private static final class BlockPass {
final Object[] accumulators;
final long[] nanos;
final boolean[] ran;
BlockPass(int stages) {
accumulators = new Object[stages];
nanos = new long[stages];
ran = new boolean[stages];
}
}
}
@@ -0,0 +1,77 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
import com.volmit.stage.PlacementStageContext;
import com.volmit.stage.PlacementStageDefinition;
import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageFunction;
import com.volmit.stage.StageRef;
/** Builder behind {@link PlacementStageDefinition}. */
final class PlacementStageDraft<O> implements PlacementStageDefinition<O> {
private final StageDeclaration declaration;
PlacementStageDraft(StageDeclaration declaration) {
this.declaration = declaration;
}
@Override
public PlacementStageDraft<O> requires(Stage<?>... stages) {
declaration.require(stages);
return this;
}
@Override
public PlacementStageDraft<O> softAfter(Stage<?>... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public PlacementStageDraft<O> softAfter(StageRef... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public PlacementStageDraft<O> softBefore(Stage<?>... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public PlacementStageDraft<O> softBefore(StageRef... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public PlacementStageDraft<O> reach(int blocks) {
declaration.reach(blocks);
return this;
}
@Override
public PlacementStageDraft<O> writesMantle(MantleKey<?>... layers) {
declaration.writesMantle(layers);
return this;
}
@Override
public PlacementStageDraft<O> when(Class<? extends IrisFeature> settingsType) {
declaration.condition(settingsType);
return this;
}
@Override
public void run(StageAction<PlacementStageContext> action) {
declaration.run(action);
}
@Override
public void produce(StageFunction<PlacementStageContext, O> function) {
declaration.produce(function);
}
}
@@ -0,0 +1,179 @@
package com.volmit.host;
import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox;
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.placement.PlacedBlock;
import com.volmit.placement.PlacedMarker;
import com.volmit.placement.PlacementAccess;
import com.volmit.placement.PlacementEdit;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/** Internal stage views: bound access to an area and hide transaction ownership. Each view is made once per placement
* invocation and keeps its mantle and layer views, so stages allocate no view per call.
*/
final class PlacementViews {
private PlacementViews() {}
static PlacementAccess restrict(PlacementEdit edit, BlockBox bounds) {
return new RestrictedPlacementAccess(edit, bounds);
}
private static Mantle restrictMantle(Mantle parent, BlockBox bounds) {
checkArea(parent.bounds(), bounds);
return new RestrictedMantle(parent, bounds);
}
private static void checkPosition(BlockBox bounds, int x, int y, int z) {
if (!bounds.contains(x, y, z)) {
throw new IndexOutOfBoundsException("Placement access outside declared reach");
}
}
private static void checkArea(BlockBox bounds, BlockBox area) {
if (!bounds.contains(area)) {
throw new IndexOutOfBoundsException("Placement area outside declared reach");
}
}
private static final class RestrictedPlacementAccess implements PlacementAccess {
private final PlacementEdit edit;
private final BlockBox allowedBounds;
private Mantle mantle;
private RestrictedPlacementAccess(PlacementEdit edit, BlockBox allowedBounds) {
this.edit = Objects.requireNonNull(edit, "edit");
this.allowedBounds = Objects.requireNonNull(allowedBounds, "bounds");
}
@Override
public BlockBox bounds() {
edit.bounds();
return allowedBounds;
}
@Override
public BlockState get(int x, int y, int z) {
checkPosition(bounds(), x, y, z);
return edit.get(x, y, z);
}
@Override
public void set(int x, int y, int z, BlockState state) {
checkPosition(bounds(), x, y, z);
edit.set(x, y, z, state);
}
@Override
public void set(PlacedBlock block) {
var position = block.position();
checkPosition(bounds(), position.x(), position.y(), position.z());
edit.set(block);
}
@Override
public void marker(PlacedMarker marker) {
var position = marker.position();
checkPosition(bounds(), position.x(), position.y(), position.z());
edit.marker(marker);
}
/** One view per invocation; the edit still decides on every call whether it is open and has a mantle. */
@Override
public Mantle mantle() {
var parent = edit.mantle();
if (mantle == null) mantle = restrictMantle(parent, bounds());
return mantle;
}
}
private static final class RestrictedMantle implements Mantle {
private final Mantle parent;
private final BlockBox allowedBounds;
private final Map<MantleKey<?>, MantleLayer<?>> layers = new HashMap<>();
private MantleLayer<BlockState> blocks;
private RestrictedMantle(Mantle parent, BlockBox allowedBounds) {
this.parent = Objects.requireNonNull(parent, "parent");
this.allowedBounds = Objects.requireNonNull(allowedBounds, "bounds");
}
@Override
public BlockBox bounds() {
parent.bounds();
return allowedBounds;
}
@Override
public MantleEdit edit() {
bounds();
throw new UnsupportedOperationException("Placement owns the mantle edit");
}
@Override
@SuppressWarnings("unchecked")
public <T> MantleLayer<T> layer(MantleKey<T> key) {
bounds();
return (MantleLayer<T>) layers.computeIfAbsent(key, _ -> new RestrictedMantleLayer<>(this, parent.layer(key)));
}
@Override
public MantleLayer<BlockState> blocks() {
bounds();
if (blocks == null) blocks = new RestrictedMantleLayer<>(this, parent.blocks());
return blocks;
}
@Override
public boolean isCarved(int x, int y, int z) {
checkPosition(bounds(), x, y, z);
return parent.isCarved(x, y, z);
}
}
private static final class RestrictedMantleLayer<T> implements MantleLayer<T> {
private final RestrictedMantle owner;
private final MantleLayer<T> layer;
private RestrictedMantleLayer(RestrictedMantle owner, MantleLayer<T> layer) {
this.owner = Objects.requireNonNull(owner, "owner");
this.layer = Objects.requireNonNull(layer, "layer");
}
@Override
public T get(int x, int y, int z) {
checkPosition(owner.bounds(), x, y, z);
return layer.get(x, y, z);
}
@Override
public void set(int x, int y, int z, T value) {
checkPosition(owner.bounds(), x, y, z);
layer.set(x, y, z, value);
}
@Override
public void remove(int x, int y, int z) {
checkPosition(owner.bounds(), x, y, z);
layer.remove(x, y, z);
}
@Override
public void visit(BlockBox area, MantleVisitor<T> visitor) {
checkArea(owner.bounds(), area);
layer.visit(area, Objects.requireNonNull(visitor, "visitor"));
}
@Override
public void clear(BlockBox area) {
checkArea(owner.bounds(), area);
layer.clear(area);
}
}
}
@@ -0,0 +1,39 @@
package com.volmit.host;
import com.volmit.stage.StageKind;
import java.util.PriorityQueue;
/** Choice among stages whose predecessors have all run. Node numbers follow lexical stage id
* order, so each queue yields the lexically smallest ready stage. To keep block passes fused,
* an open pass continues while a block stage is ready, and ready invocation stages run before
* a new pass opens. The choice depends only on ids and edges, never on setup order.
*/
final class ReadyStages {
private final PriorityQueue<Integer> invocation = new PriorityQueue<>();
private final PriorityQueue<Integer> block = new PriorityQueue<>();
private boolean blockPassOpen;
void add(int node, StageKind kind) {
queue(kind).add(node);
}
boolean isEmpty() {
return invocation.isEmpty() && block.isEmpty();
}
int next() {
if (blockPassOpen && !block.isEmpty()) {
return block.remove();
}
if (!invocation.isEmpty()) {
blockPassOpen = false;
return invocation.remove();
}
blockPassOpen = true;
return block.remove();
}
private PriorityQueue<Integer> queue(StageKind kind) {
return kind == StageKind.BLOCK ? block : invocation;
}
}
@@ -0,0 +1,153 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import com.volmit.stage.Pipeline;
import com.volmit.stage.StageKind;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
/** Immutable, validated order of one pipeline, resolved once per pack load. Adjacent block
* stages form one fused block pass; any invocation stage between them splits the pass, even
* when that stage is inactive for a particular invocation. Execution never sorts or hashes.
*/
public final class ResolvedGraph {
private final Pipeline pipeline;
private final List<ResolvedStage> stages;
private final List<ExecutableStage> executables;
private final List<Class<?>> settingsTypes;
private final List<Segment> segments;
ResolvedGraph(
Pipeline pipeline,
List<ResolvedStage> stages,
List<ExecutableStage> executables,
List<Class<?>> settingsTypes) {
this.pipeline = Objects.requireNonNull(pipeline, "pipeline");
this.stages = List.copyOf(stages);
this.executables = List.copyOf(executables);
this.settingsTypes = List.copyOf(settingsTypes);
segments = segments(this.executables);
}
public Pipeline pipeline() {
return pipeline;
}
/** Stages in execution order. */
public List<ResolvedStage> stages() {
return stages;
}
/** Each fused block pass as stage ids in execution order. */
public List<List<ResourceId>> blockPasses() {
return segments.stream()
.filter(segment -> segment.kind() == StageKind.BLOCK)
.map(segment -> stages.subList(segment.start(), segment.end()).stream()
.map(stage -> stage.stage().id())
.toList())
.toList();
}
/** Pairs with no path between them in either direction, first stage earlier in the order.
* Their relative order comes only from the deterministic tie-break, so a pack author should
* check that they do not conflict.
*/
public List<UnorderedPair> unorderedPairs() {
var reachable = reachability();
var pairs = new ArrayList<UnorderedPair>();
for (int first = 0; first < stages.size(); first++) {
for (int second = first + 1; second < stages.size(); second++) {
if (!reachable[first].get(second)) {
pairs.add(new UnorderedPair(id(first), id(second)));
}
}
}
return pairs;
}
/** The most the pipeline's stages write beyond their footprint, overall and per mantle layer.
*
* @throws IllegalStateException when a mantle stage works out its reach when the pack loads: the host
* runs each mantle stage as its own pass and asks it with {@link ResolvedStage#reachBlocks}
*/
public PipelineReach reach() {
return PipelineReach.of(stages);
}
/** Human-readable order, owners, edges, block passes and unordered pairs. */
public String describe() {
return GraphDescription.describe(this);
}
int size() {
return executables.size();
}
ExecutableStage executable(int position) {
return executables.get(position);
}
List<Segment> segments() {
return segments;
}
List<Class<?>> settingsTypes() {
return settingsTypes;
}
private ResourceId id(int position) {
return stages.get(position).stage().id();
}
/** Edges always point forward in the order, so a reverse sweep completes each stage's
* reachable set before any predecessor merges it.
*/
private BitSet[] reachability() {
var positions = new HashMap<ResourceId, Integer>();
var reachable = new BitSet[stages.size()];
for (int position = 0; position < stages.size(); position++) {
positions.put(id(position), position);
reachable[position] = new BitSet();
}
for (int position = stages.size() - 1; position >= 0; position--) {
for (var edge : stages.get(position).incoming()) {
int predecessor = positions.get(edge.from());
reachable[predecessor].set(position);
reachable[predecessor].or(reachable[position]);
}
}
return reachable;
}
private static List<Segment> segments(List<ExecutableStage> executables) {
var segments = new ArrayList<Segment>();
int position = 0;
while (position < executables.size()) {
int end = segmentEnd(executables, position);
segments.add(new Segment(executables.get(position).stage().kind(), position, end));
position = end;
}
return List.copyOf(segments);
}
private static int segmentEnd(List<ExecutableStage> executables, int start) {
if (executables.get(start).stage().kind() != StageKind.BLOCK) {
return start + 1;
}
int end = start + 1;
while (end < executables.size() && executables.get(end).stage().kind() == StageKind.BLOCK) {
end++;
}
return end;
}
public record UnorderedPair(ResourceId first, ResourceId second) {
public UnorderedPair {
Objects.requireNonNull(first, "first");
Objects.requireNonNull(second, "second");
}
}
}
@@ -0,0 +1,56 @@
package com.volmit.host;
import com.volmit.config.PackSettings;
import com.volmit.resource.ResourceId;
import com.volmit.stage.Stage;
import com.volmit.stage.StageRef;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/** Diagnostic view of one stage at its resolved position. incoming lists every edge into this
* stage, including soft edges other stages declared; absentSoftTargets lists this stage's soft
* references that matched no installed stage and therefore add no ordering. reach is what the stage
* declared it writes beyond its footprint; {@link #reachBlocks(PackSettings)} works it out for a pack.
*/
public record ResolvedStage(
Stage<?> stage,
ResourceId module,
Optional<FeatureDescriptor<?>> settings,
List<StageEdge> incoming,
List<StageRef> absentSoftTargets,
StageReach reach) {
public ResolvedStage {
Objects.requireNonNull(stage, "stage");
Objects.requireNonNull(module, "module");
Objects.requireNonNull(settings, "settings");
Objects.requireNonNull(reach, "reach");
incoming = List.copyOf(incoming);
absentSoftTargets = List.copyOf(absentSoftTargets);
}
/** How far, in blocks along X and Z, the stage writes beyond its footprint in the pack whose settings
* are {@code settings}: the declared number, or what the stage's {@link com.volmit.stage.PackReach}
* works out. The host asks once per pack load, before generating.
*
* @throws IllegalStateException when the stage works out a negative reach
*/
public int reachBlocks(PackSettings settings) {
Objects.requireNonNull(settings, "settings");
int blocks = reach.blocks().blocks(settings);
if (blocks < 0) {
throw new IllegalStateException("Stage " + stage + " of module " + module + " worked out a negative reach of "
+ blocks + " blocks for this pack");
}
return blocks;
}
/** The declared number of blocks; for a pipeline whose reaches do not depend on the pack. */
int fixedReachBlocks() {
if (!(reach.blocks() instanceof FixedReach fixed)) {
throw new IllegalStateException("Stage " + stage + " of module " + module + " works out its reach when the pack"
+ " loads; ask each mantle stage with ResolvedStage.reachBlocks(settings)");
}
return fixed.blocks();
}
}
@@ -0,0 +1,17 @@
package com.volmit.host;
import com.volmit.resource.ResourceKind;
import java.util.Objects;
/** A resource kind and the module that registered it, which owns its id. */
public record ResourceKindRegistration(ResourceKind<?> kind, DiscoveredModule module) {
public ResourceKindRegistration {
Objects.requireNonNull(kind, "kind");
Objects.requireNonNull(module, "module");
}
@Override
public String toString() {
return "resource kind " + kind.id() + " of module " + module;
}
}
@@ -0,0 +1,28 @@
package com.volmit.host;
import com.volmit.resource.ResourceKind;
/** The settings or resource kind, and its module, that first reached a class while describing a pack; load errors name them.
*
* @param subject what reached the class, such as {@code settings example:flora}
* @param type the class the subject is read into
*/
@SuppressWarnings("removal") // held types are transitional, until the cut-over
record SchemaSource(String subject, Class<?> type, DiscoveredModule module) {
static SchemaSource settings(FeatureDescriptor<?> feature, DiscoveredModule module) {
return new SchemaSource("settings " + feature.id(), feature.type(), module);
}
static SchemaSource resourceKind(ResourceKind<?> kind, DiscoveredModule module) {
return new SchemaSource("resource kind " + kind.id(), kind.type(), module);
}
static SchemaSource heldType(HeldTypeRegistration held) {
return new SchemaSource("held type " + held.type().getName(), held.type(), held.module());
}
@Override
public String toString() {
return subject + " (module " + module + ")";
}
}
@@ -0,0 +1,31 @@
package com.volmit.host;
import com.volmit.ModuleLog;
import com.volmit.world.PackWorld;
import java.util.Objects;
/** The views of worlds one module's stages get, whose log is the module's own ({@link ModuleWorld}). It keeps
* the view of the world it was last asked for, so the stages of a host that generates one world per resolved graph
* get it without a new view per invocation; a host that alternates worlds on one graph asks the world each time.
* The kept world is released when the next one is asked for or the graph is dropped. Safe for concurrent use.
*/
final class ScopedWorlds {
private final ModuleLog log;
private volatile Scoped last;
ScopedWorlds(ModuleLog log) {
this.log = Objects.requireNonNull(log, "log");
}
PackWorld of(PackWorld world) {
var scoped = last;
if (scoped != null && scoped.world() == world) {
return scoped.view();
}
var view = ModuleWorld.of(world, log);
last = new Scoped(world, view);
return view;
}
private record Scoped(PackWorld world, PackWorld view) {}
}
@@ -0,0 +1,8 @@
package com.volmit.host;
import com.volmit.stage.StageKind;
/** Positions [start, end) of the resolved order. An INVOCATION segment holds one stage;
* a BLOCK segment is one fused block pass.
*/
record Segment(StageKind kind, int start, int end) {}
@@ -0,0 +1,25 @@
package com.volmit.host;
import com.volmit.world.PackWorld;
import java.util.Objects;
/** One provider of a service and the module that registered it. */
public record ServiceRegistration(Class<?> service, Object provider, DiscoveredModule module) {
public ServiceRegistration {
Objects.requireNonNull(service, "service");
Objects.requireNonNull(provider, "provider");
Objects.requireNonNull(module, "module");
}
/** {@code world} as this provider's module sees it, which the host hands to the provider's methods so that
* {@link PackWorld#log} is the module's own.
*/
public PackWorld scope(PackWorld world) {
return ModuleWorld.of(world, module.log());
}
@Override
public String toString() {
return "provider of " + service.getName() + " from module " + module;
}
}
@@ -0,0 +1,10 @@
package com.volmit.host;
/** Why a settings field's type cannot be described, phrased to follow the field's name, such as
* "uses java.util.UUID, a JDK class, ...". {@link TypeDrafts} adds the field and its settings.
*/
final class SettingsTypeProblem extends RuntimeException {
SettingsTypeProblem(String problem) {
super(problem, null, false, false);
}
}
@@ -0,0 +1,24 @@
package com.volmit.host;
import com.volmit.stage.BlockStageContext;
import java.util.function.Supplier;
/** Type-erased stage work. Drafts build the body matching their stage kind, so executors may
* rely on invocation stages carrying Invocation bodies and block stages carrying Block bodies.
*/
sealed interface StageBody {
record Invocation(InvocationWork work) implements StageBody {}
/** initial is null for block stages without an accumulator. */
record Block(Supplier<?> initial, BlockWork work) implements StageBody {}
@FunctionalInterface
interface InvocationWork {
Object run(Object context);
}
@FunctionalInterface
interface BlockWork {
void run(BlockStageContext context, Object accumulator);
}
}
@@ -0,0 +1,216 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.ModuleLog;
import com.volmit.mantle.MantleKey;
import com.volmit.resource.ResourceId;
import com.volmit.stage.PackReach;
import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageFunction;
import com.volmit.stage.StageRef;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/** One stage as declared during setup. It becomes immutable once its body is set. */
final class StageDeclaration {
private final Stage<?> stage;
private final ResourceId module;
private final ModuleLog log;
private final List<Stage<?>> requirements = new ArrayList<>();
private final List<StageRef> softAfter = new ArrayList<>();
private final List<StageRef> softBefore = new ArrayList<>();
private FeatureDescriptor<?> settings;
private PackReach reach;
private final List<MantleKey<?>> mantleLayers = new ArrayList<>();
private StageBody body;
StageDeclaration(Stage<?> stage, ResourceId module, ModuleLog log) {
this.stage = Objects.requireNonNull(stage, "stage");
this.module = Objects.requireNonNull(module, "module");
this.log = Objects.requireNonNull(log, "log");
}
void require(Stage<?>... stages) {
checkOpen();
for (var required : stages) {
Objects.requireNonNull(required, "required stage");
rejectSelfReference(required.id());
requirements.add(required);
}
}
void softAfter(StageRef... references) {
addSoftReferences(softAfter, references);
}
void softAfter(Stage<?>... stages) {
addSoftReferences(softAfter, references(stages));
}
void softBefore(StageRef... references) {
addSoftReferences(softBefore, references);
}
void softBefore(Stage<?>... stages) {
addSoftReferences(softBefore, references(stages));
}
private static StageRef[] references(Stage<?>... stages) {
var references = new StageRef[stages.length];
for (int index = 0; index < stages.length; index++) {
references[index] = Objects.requireNonNull(stages[index], "stage").ref();
}
return references;
}
void condition(Class<? extends IrisFeature> settingsType) {
checkOpen();
if (settings != null) {
throw new IllegalStateException("Stage " + this + " already has a when(...) condition");
}
settings = FeatureDescriptor.of(settingsType);
}
void reach(int blocks) {
checkOpen();
if (blocks < 0) {
throw new IllegalArgumentException("Stage " + this + " declares a negative reach of " + blocks + " blocks");
}
declareReach(new FixedReach(blocks));
}
void reach(PackReach computed) {
checkOpen();
declareReach(Objects.requireNonNull(computed, "reach"));
}
private void declareReach(PackReach declared) {
if (reach != null) {
throw new IllegalStateException("Stage " + this + " already declares " + describe(reach));
}
reach = declared;
}
private static String describe(PackReach reach) {
return reach instanceof FixedReach fixed
? "a reach of " + fixed.blocks() + " blocks"
: "a reach worked out when the pack loads";
}
void writesMantle(MantleKey<?>... layers) {
checkOpen();
for (var layer : layers) {
Objects.requireNonNull(layer, "mantle layer");
if (mantleLayers.stream().anyMatch(declared -> declared.id().equals(layer.id()))) {
throw new IllegalArgumentException("Stage " + this + " declares mantle layer " + layer.id() + " twice");
}
mantleLayers.add(layer);
}
}
/** Sets an invocation body without output. */
void run(StageAction<?> action) {
Objects.requireNonNull(action, "action");
complete(new StageBody.Invocation(context -> {
action.run(cast(context));
return null;
}), false, "produce");
}
/** Sets an invocation body with output. */
void produce(StageFunction<?, ?> function) {
Objects.requireNonNull(function, "function");
complete(new StageBody.Invocation(context -> function.run(cast(context))), true, "run");
}
@SuppressWarnings("unchecked") // The executor passes the context of the pipeline this stage was declared in.
private static <T> T cast(Object value) {
return (T) value;
}
/** Sets the only body. alternativeMethod names the builder method for the other output kind. */
void complete(StageBody body, boolean bodyProducesOutput, String alternativeMethod) {
checkOpen();
Objects.requireNonNull(body, "body");
if (bodyProducesOutput != stage.producesOutput()) {
throw new IllegalStateException(bodyMismatch(alternativeMethod));
}
this.body = body;
}
boolean isComplete() {
return body != null;
}
Stage<?> stage() {
return stage;
}
ResourceId module() {
return module;
}
ModuleLog log() {
return log;
}
List<Stage<?>> requirements() {
return List.copyOf(requirements);
}
List<StageRef> softAfter() {
return List.copyOf(softAfter);
}
List<StageRef> softBefore() {
return List.copyOf(softBefore);
}
Optional<FeatureDescriptor<?>> settings() {
return Optional.ofNullable(settings);
}
StageBody body() {
return body;
}
StageReach reach() {
return new StageReach(reach == null ? FixedReach.NONE : reach, mantleLayers);
}
@Override
public String toString() {
return stage.id() + " (module " + module + ")";
}
private void addSoftReferences(List<StageRef> target, StageRef... references) {
checkOpen();
for (var reference : references) {
Objects.requireNonNull(reference, "stage reference");
rejectSelfReference(reference.id());
target.add(reference);
}
}
private void rejectSelfReference(ResourceId id) {
if (stage.id().equals(id)) {
throw new IllegalArgumentException("Stage " + this + " cannot depend on itself");
}
}
private String bodyMismatch(String alternativeMethod) {
var declared = stage.producesOutput()
? "declares output " + stage.outputType().getSimpleName()
: "declares no output";
return "Stage " + this + " " + declared + "; define it with " + alternativeMethod + "(...)";
}
private void checkOpen() {
if (body != null) {
throw new IllegalStateException("Stage " + this + " is already complete");
}
}
}
@@ -0,0 +1,24 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** A resolved ordering edge: from runs before to. */
public record StageEdge(ResourceId from, ResourceId to, Kind kind) {
public enum Kind {
/** Declared with requires(...): orders, exposes output and cascades deactivation. */
REQUIRED,
/** Declared with softAfter/softBefore against an installed stage: ordering only. */
SOFT;
Kind strongest(Kind other) {
return this == REQUIRED || other == REQUIRED ? REQUIRED : SOFT;
}
}
public StageEdge {
Objects.requireNonNull(from, "from");
Objects.requireNonNull(to, "to");
Objects.requireNonNull(kind, "kind");
}
}
@@ -0,0 +1,186 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.resource.ResourceId;
import com.volmit.stage.BlockStage;
import com.volmit.stage.BlockStageDefinition;
import com.volmit.stage.ChunkStage;
import com.volmit.stage.ChunkStageDefinition;
import com.volmit.stage.MantleStage;
import com.volmit.stage.MantleStageDefinition;
import com.volmit.stage.Pipeline;
import com.volmit.stage.PlacementStage;
import com.volmit.stage.PlacementStageDefinition;
import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/** Reference host collection of module stages. Set up every module ({@link ModuleSetups#run}), then resolve each
* pipeline once per pack load. Setup order never affects the result. If a module's setup throws,
* discard the whole builder: it may hold a partial module. Errors about one module name its origin.
*
* <p>A module defines only stages whose ids start with its own id and '/', and a settings type
* named in {@code when(...)} must have a feature id that at least one module naming it owns: that
* module's id, or one starting with it and '/'. A type its owner registered explicitly may be named
* by any module.
*/
public final class StageGraphBuilder implements StageGraph {
private final Map<ResourceId, StageDeclaration> declarations = new HashMap<>();
private final Map<ResourceId, DiscoveredModule> modules = new HashMap<>();
private DiscoveredModule settingUp;
/** Accepts {@code discovered}'s stages until {@link #endSetup(boolean)}; see {@link ModuleSetups#run}. */
void beginSetup(DiscoveredModule discovered) {
Objects.requireNonNull(discovered, "discovered");
claimModule(discovered);
settingUp = discovered;
}
/** Stops accepting the module's stages. With {@code completed}, every stage it defined must have a body. */
void endSetup(boolean completed) {
var moduleId = settingUp.info().id();
settingUp = null;
if (completed) {
requireCompleteDefinitions(moduleId);
}
}
@Override
public <O> PlacementStageDefinition<O> define(PlacementStage<O> stage) {
return new PlacementStageDraft<>(declare(stage));
}
@Override
public <O> BlockStageDefinition<O> define(BlockStage<O> stage) {
return new BlockStageDraft<>(declare(stage));
}
@Override
public <O> ChunkStageDefinition<O> define(ChunkStage<O> stage) {
return new ChunkStageDraft<>(declare(stage));
}
@Override
public MantleStageDefinition define(MantleStage stage) {
return new MantleStageDraft(declare(stage));
}
public ResolvedGraph resolve(Pipeline pipeline) {
Objects.requireNonNull(pipeline, "pipeline");
return GraphResolver.resolve(pipeline, declarations.values());
}
/** Settings types named by when(...), ordered by feature id. Fails if no module that names a type
* owns its feature id ({@link com.volmit.ModuleInfo#ownsId}), unless {@code registeredByOwner}
* says its owner registered it explicitly.
*/
public List<Class<? extends IrisFeature>> settingsTypes(Predicate<Class<?>> registeredByOwner) {
var uses = settingsUses();
uses.stream()
.filter(use -> !registeredByOwner.test(use.settings().type()))
.forEach(this::requireSettingsOwner);
return uses.stream()
.<Class<? extends IrisFeature>>map(use -> use.settings().type())
.toList();
}
private void claimModule(DiscoveredModule discovered) {
var moduleId = discovered.info().id();
if (settingUp != null) {
throw new IllegalStateException("Module " + moduleId + " set up during " + settingUp.info().id());
}
var previous = modules.putIfAbsent(moduleId, discovered);
if (previous != null) {
throw new IllegalArgumentException("Duplicate module " + moduleId + " from " + discovered.locationWithClass()
+ "; already loaded from " + previous.locationWithClass());
}
}
/** Each settings type named by when(...), ordered by feature id, with the modules naming it. */
private List<SettingsUse> settingsUses() {
var uses = new HashMap<Class<?>, SettingsUse>();
for (var declaration : declarations.values()) {
declaration.settings().ifPresent(settings -> uses
.computeIfAbsent(settings.type(), ignored -> new SettingsUse(settings, new TreeSet<>()))
.namers().add(declaration.module()));
}
return uses.values().stream()
.sorted(Comparator.comparing((SettingsUse use) -> use.settings().id())
.thenComparing(use -> use.settings().type().getName()))
.toList();
}
private void requireSettingsOwner(SettingsUse use) {
var settings = use.settings();
var namers = use.namers().stream().map(modules::get).toList();
if (namers.stream().anyMatch(module -> module.info().ownsId(settings.id()))) return;
var example = namers.getFirst().info();
throw new IllegalArgumentException("Settings type " + settings.type().getName() + " has feature id "
+ settings.id() + ", which none of the modules naming it in when(...) owns: " + describeModules(namers)
+ ". A feature id is the id of the module that owns the settings, such as " + example.id()
+ ", or starts with it and '/', such as " + example.idPrefix() + lastSegment(settings.id()));
}
private static String lastSegment(ResourceId id) {
var path = id.path();
return path.substring(path.lastIndexOf('/') + 1);
}
private static String describeModules(List<DiscoveredModule> modules) {
return modules.stream()
.map(DiscoveredModule::toString)
.collect(Collectors.joining(", "));
}
private StageDeclaration declare(Stage<?> stage) {
Objects.requireNonNull(stage, "stage");
var discovered = requireModuleInSetup(stage);
requireOwnedStageId(stage, discovered);
var module = discovered.info().id();
var declaration = new StageDeclaration(stage, module, discovered.log());
var previous = declarations.putIfAbsent(stage.id(), declaration);
if (previous != null) {
throw new IllegalArgumentException("Duplicate definition of stage " + stage.id() + " by module "
+ module + "; already defined by module " + previous.module());
}
return declaration;
}
private DiscoveredModule requireModuleInSetup(Stage<?> stage) {
if (settingUp == null) {
throw new IllegalStateException("Stage " + stage + " defined outside IrisModule.setup");
}
return settingUp;
}
private static void requireOwnedStageId(Stage<?> stage, DiscoveredModule discovered) {
var info = discovered.info();
if (info.ownsStage(stage.id())) return;
throw new IllegalArgumentException("Stage " + stage + " must start with " + info.idPrefix()
+ ", the id of its defining module " + discovered);
}
private void requireCompleteDefinitions(ResourceId moduleId) {
declarations.values().stream()
.filter(declaration -> declaration.module().equals(moduleId))
.filter(declaration -> !declaration.isComplete())
.map(StageDeclaration::toString)
.sorted()
.findFirst()
.ifPresent(incomplete -> {
throw new IllegalStateException("Stage " + incomplete
+ " has no body; end its definition with run, produce or accumulate");
});
}
private record SettingsUse(FeatureDescriptor<?> settings, SortedSet<ResourceId> namers) {}
}
@@ -0,0 +1,187 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.config.SettingsStack;
import com.volmit.random.WorldRandom;
import com.volmit.stage.BlockStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.PackWorld;
import java.util.Arrays;
import java.util.Objects;
import java.util.function.BooleanSupplier;
import java.util.stream.IntStream;
/** Pipeline-independent state of one invocation: activation, settings, stage outputs and stage
* random streams, all indexed by resolved position. Activation is computed once up front in resolved
* order: a stage is active when its settings have an entry (or it has no condition) and every
* stage it requires is active, so inactivity cascades to dependents. Cost is one pass over stages
* and requirement edges plus one settings lookup per distinct settings type. A stage's stream is
* created when it first draws and depends only on the invocation seed and the stage id.
*/
final class StageInvocation {
private static final Object PENDING = new Object();
private static final int NO_STAGE = -1;
private static final BooleanSupplier NEVER_REJECTED = () -> false;
private final ResolvedGraph graph;
private final Object[] settingsBySlot;
private final boolean[] active;
private final Object[] outputs;
private final long invocationSeed;
private final WorldRandom[] streams;
private int current = NO_STAGE;
StageInvocation(ResolvedGraph graph, long invocationSeed, ConfiguredSettings settings) {
this.graph = graph;
settingsBySlot = lookUpSettings(graph, Objects.requireNonNull(settings, "settings"));
active = activation(graph, settingsBySlot);
outputs = new Object[graph.size()];
Arrays.fill(outputs, PENDING);
this.invocationSeed = invocationSeed;
streams = new WorldRandom[graph.size()];
}
boolean isActive(int position) {
return active[position];
}
int[] activePositions(Segment segment) {
return IntStream.range(segment.start(), segment.end())
.filter(position -> active[position])
.toArray();
}
void runInvocationStage(int position, Object context) {
runInvocationStage(position, context, NEVER_REJECTED);
}
/** {@code rejected} tells, after the stage ran, whether it rejected the attempt; a rejecting stage may return null. */
void runInvocationStage(int position, Object context, BooleanSupplier rejected) {
if (!active[position]) {
return;
}
var executable = graph.executable(position);
var work = ((StageBody.Invocation) executable.body()).work();
current = position;
var output = work.run(context);
current = NO_STAGE;
if (output == null && executable.stage().producesOutput() && !rejected.getAsBoolean()) {
throw new NullPointerException("Stage " + executable.stage() + " produced a null output");
}
complete(position, output);
}
Object newAccumulator(int position) {
var initial = ((StageBody.Block) graph.executable(position).body()).initial();
if (initial == null) {
return null;
}
return Objects.requireNonNull(initial.get(), () -> "Stage " + graph.executable(position).stage()
+ " created a null accumulator");
}
void runBlockStage(int position, BlockStageContext context, Object accumulator) {
var executable = graph.executable(position);
var work = ((StageBody.Block) executable.body()).work();
current = position;
work.run(context, accumulator);
current = NO_STAGE;
}
void complete(int position, Object output) {
outputs[position] = output;
}
@SuppressWarnings("unchecked") // Bodies are typed by their stage, so the stored output matches O.
<O> O output(Stage<O> stage) {
Objects.requireNonNull(stage, "stage");
var reader = currentStage();
int position = reader.readablePosition(stage);
if (position == ExecutableStage.NOT_READABLE) {
throw new IllegalStateException("Stage " + reader.stage() + " read the output of " + stage
+ " without requiring it; add requires(" + stage + ") to its definition");
}
if (outputs[position] == PENDING) {
throw new IllegalStateException("Stage " + reader.stage() + " read the output of " + stage
+ " before it completed; block stage outputs are available after their block pass");
}
return (O) outputs[position];
}
/** The running stage's own stream. A block stage keeps one stream across every block of its pass. */
WorldRandom random() {
if (current == NO_STAGE) {
throw new IllegalStateException("A stage's random stream is only available while the stage runs");
}
if (streams[current] == null) {
streams[current] = StageStreams.stream(invocationSeed, graph.executable(current).idHash());
}
return streams[current];
}
/** {@code world} as the running stage's module sees it, whose log is the module's own. Between stages it is {@code world}. */
PackWorld world(PackWorld world) {
if (current == NO_STAGE) {
return world;
}
return graph.executable(current).worlds().of(world);
}
private ExecutableStage currentStage() {
if (current == NO_STAGE) {
throw new IllegalStateException("Stage outputs can only be read while a stage runs");
}
return graph.executable(current);
}
/** The stack that activated the running stage, which must be conditioned on {@code type}. */
@SuppressWarnings("unchecked") // The slot holds the stack of the type the stage is conditioned on.
<S extends IrisFeature> SettingsStack<S> configured(Class<S> type) {
Objects.requireNonNull(type, "settingsType");
if (current == NO_STAGE) {
throw new IllegalStateException("Configured settings can only be read while a stage runs");
}
var executable = graph.executable(current);
int slot = executable.settingsSlot();
if (slot == ExecutableStage.NO_SETTINGS || graph.settingsTypes().get(slot) != type) {
throw new IllegalStateException("Stage " + executable.stage() + " read configured(" + type.getSimpleName()
+ ") but is not conditioned on it; add when(" + type.getSimpleName() + ".class) to its definition,"
+ " or read other settings through settings()");
}
return (SettingsStack<S>) settingsBySlot[slot];
}
@SuppressWarnings("unchecked") // Settings types come from when(Class<? extends IrisFeature>).
private static Object[] lookUpSettings(ResolvedGraph graph, ConfiguredSettings settings) {
var types = graph.settingsTypes();
var values = new Object[types.size()];
for (int slot = 0; slot < values.length; slot++) {
var stack = settings.find((Class<? extends IrisFeature>) types.get(slot));
values[slot] = stack.isEmpty() ? null : stack;
}
return values;
}
private static boolean[] activation(ResolvedGraph graph, Object[] settingsBySlot) {
var active = new boolean[graph.size()];
for (int position = 0; position < active.length; position++) {
var executable = graph.executable(position);
active[position] = isConfigured(executable, settingsBySlot) && requirementsActive(executable, active);
}
return active;
}
private static boolean isConfigured(ExecutableStage executable, Object[] settingsBySlot) {
int slot = executable.settingsSlot();
return slot == ExecutableStage.NO_SETTINGS || settingsBySlot[slot] != null;
}
private static boolean requirementsActive(ExecutableStage executable, boolean[] active) {
for (int requirement : executable.requirements()) {
if (!active[requirement]) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,37 @@
package com.volmit.host;
import com.volmit.mantle.MantleKey;
import com.volmit.stage.PackReach;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
/** What one stage declares it writes outside its footprint.
*
* @param blocks how far, in blocks along X and Z, the stage writes blocks or mantle values beyond its
* footprint: the chunk's 16 by 16 columns for a mantle stage, the X/Z bounds of the placed object
* for a placement stage. 0 means only inside it, and is all a chunk stage may declare. Height is not
* limited: the footprint is whole columns. A number declared during setup, or for a mantle stage a
* {@link PackReach} worked out from the pack's settings when the pack loads.
* @param mantleLayers the mantle layers the stage writes, each once, in declaration order
*/
public record StageReach(PackReach blocks, List<MantleKey<?>> mantleLayers) {
/** A stage that declared nothing: it writes blocks inside its footprint only, and no mantle layer. */
public static final StageReach NONE = new StageReach(FixedReach.NONE, List.of());
public StageReach {
Objects.requireNonNull(blocks, "blocks");
mantleLayers = List.copyOf(mantleLayers);
var ids = new HashSet<String>();
for (var layer : mantleLayers) {
if (!ids.add(Objects.requireNonNull(layer, "mantle layer").id())) {
throw new IllegalArgumentException("Mantle layer " + layer.id() + " declared twice");
}
}
}
/** A reach of a number of blocks declared during setup. */
public StageReach(int blocks, List<MantleKey<?>> mantleLayers) {
this(new FixedReach(blocks), mantleLayers);
}
}
@@ -0,0 +1,57 @@
package com.volmit.host;
import com.volmit.random.WorldRandom;
import com.volmit.resource.ResourceId;
import java.nio.charset.StandardCharsets;
/** Derives the random stream of one stage in one invocation from the invocation seed and the
* stage id alone. A stage's draws therefore never depend on which other modules or stages are
* installed, their order, or how much they draw.
*
* <p>The derivation is fixed so the same seed gives the same world on every machine and JDK:
* <ol>
* <li>{@code idHash} = 64-bit FNV-1a of the UTF-8 bytes of the stage id ({@code namespace:path});</li>
* <li>{@code streamSeed} = {@code mix(mix(invocationSeed) ^ idHash)}, where {@code mix} is the
* SplitMix64 finalizer (Stafford variant 13);</li>
* <li>the stream is {@code new WorldRandom(streamSeed)}, whose every method IrisApi defines.</li>
* </ol>
* {@code mix} is a bijection, so one stage gets a different stream for every invocation seed, and
* within one invocation stages with different id hashes get different streams.
*/
public final class StageStreams {
private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L;
private static final long FNV_PRIME = 0x100000001b3L;
private static final int BYTE_MASK = 0xff;
private StageStreams() {}
/** The stream {@code stageId} draws from in the invocation with {@code invocationSeed}. */
public static WorldRandom stream(long invocationSeed, ResourceId stageId) {
return stream(invocationSeed, idHash(stageId));
}
static WorldRandom stream(long invocationSeed, long idHash) {
return new WorldRandom(streamSeed(invocationSeed, idHash));
}
static long streamSeed(long invocationSeed, long idHash) {
return mix(mix(invocationSeed) ^ idHash);
}
/** 64-bit FNV-1a over the UTF-8 bytes of the id. */
static long idHash(ResourceId stageId) {
long hash = FNV_OFFSET_BASIS;
for (byte value : stageId.toString().getBytes(StandardCharsets.UTF_8)) {
hash ^= value & BYTE_MASK;
hash *= FNV_PRIME;
}
return hash;
}
/** SplitMix64's finalizer: a bijection on 64-bit values with full avalanche. */
private static long mix(long value) {
value = (value ^ (value >>> 30)) * 0xbf58476d1ce4e5b9L;
value = (value ^ (value >>> 27)) * 0x94d049bb133111ebL;
return value ^ (value >>> 31);
}
}
@@ -0,0 +1,16 @@
package com.volmit.host;
/** Where a runner reports how long each stage it ran took, such as the host's generation metrics. Every runner takes
* one ({@link PlacementRunner#place}, {@link ChunkRunner#generate}, {@link MantleRunner#generate}). Called on the
* invocation's thread, once per stage that ran, in run order; a block stage is reported once at the end of its pass
* with its time summed over the blocks it ran for. A stage the invocation left inactive, or one that threw, is not
* reported.
*/
@FunctionalInterface
public interface StageTimings {
/** Reports nothing. */
StageTimings NONE = (stage, nanos) -> {
};
void record(ResolvedStage stage, long nanos);
}
@@ -0,0 +1,96 @@
package com.volmit.host;
import java.io.IOException;
import java.lang.System.Logger.Level;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/** Removes module jar copies that a process left behind when it crashed before closing its packs.
*
* <p>Only directories this code provably created are touched: a directory named
* {@code iris-pack-modules-*}, holding an owner file with the expected header, whose owner process
* no longer runs, and holding nothing but that owner file and {@code .jar} files. Anything else is
* left alone, including copies of a process that still runs (another server, or this one) and
* directories whose owner file is missing because the crash came before it was written.
*/
final class StaleJarSnapshots {
private static final System.Logger LOGGER = System.getLogger(PackModules.class.getName());
private StaleJarSnapshots() {}
static void remove(Path temporaryRoot) {
for (var candidate : candidates(temporaryRoot)) {
ownerOf(candidate)
.filter(StaleJarSnapshots::hasExited)
.ifPresent(owner -> removeIfOnlyCopies(candidate, owner));
}
}
private static List<Path> candidates(Path temporaryRoot) {
var candidates = new ArrayList<Path>();
try (var entries = Files.newDirectoryStream(temporaryRoot, JarSnapshot.DIRECTORY_PREFIX + "*")) {
entries.forEach(candidates::add);
} catch (IOException | DirectoryIteratorException exception) {
LOGGER.log(Level.DEBUG, "Cannot look for stale module jar copies in " + temporaryRoot, exception);
}
return candidates;
}
/** The owner process id, if {@code directory} is a real directory with a valid owner file. */
private static Optional<Long> ownerOf(Path directory) {
var ownerFile = directory.resolve(JarSnapshot.OWNER_FILE);
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
if (!Files.isRegularFile(ownerFile, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
try {
var lines = Files.readAllLines(ownerFile, StandardCharsets.UTF_8);
if (lines.size() != 2 || !lines.getFirst().equals(JarSnapshot.OWNER_HEADER)) return Optional.empty();
return parsePid(lines.get(1));
} catch (IOException exception) {
return Optional.empty();
}
}
private static Optional<Long> parsePid(String text) {
try {
return Optional.of(Long.parseLong(text));
} catch (NumberFormatException exception) {
return Optional.empty();
}
}
private static boolean hasExited(long pid) {
return ProcessHandle.of(pid).map(process -> !process.isAlive()).orElse(true);
}
private static void removeIfOnlyCopies(Path directory, long owner) {
try {
var entries = listEntries(directory);
if (!entries.stream().allMatch(StaleJarSnapshots::isSnapshotFile)) return;
for (var entry : entries) {
Files.delete(entry);
}
Files.delete(directory);
LOGGER.log(Level.INFO, () -> "Removed module jar copies left by exited process " + owner + " in " + directory);
} catch (IOException exception) {
LOGGER.log(Level.DEBUG, "Cannot remove stale module jar copies in " + directory, exception);
}
}
private static List<Path> listEntries(Path directory) throws IOException {
try (var entries = Files.list(directory)) {
return entries.toList();
}
}
private static boolean isSnapshotFile(Path entry) {
var name = entry.getFileName().toString();
return Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS)
&& (name.equals(JarSnapshot.OWNER_FILE) || name.endsWith(PackModules.JAR_EXTENSION));
}
}
@@ -0,0 +1,183 @@
package com.volmit.host;
import com.volmit.host.schema.ValueKind;
import com.volmit.host.schema.ValueKind.ObjectKind;
import com.volmit.resource.ResourceId;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InaccessibleObjectException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
/** Describes every class reachable from the settings and resource kinds of a pack, each once, except host types,
* which the host describes itself. A class is recorded before
* its fields are described, so a class that contains itself, directly or through others, ends the
* walk at its own name. Each class is instantiated once with its no-argument constructor, the way the
* host creates settings before decoding JSON into them, and its fields' values there are the defaults.
*/
final class TypeDrafts {
private final Map<Class<?>, TypeDraft> drafts = new LinkedHashMap<>();
private final Set<Class<?>> describing = new HashSet<>();
private final Map<String, Class<?>> names = new HashMap<>();
private final HostTypes hostTypes;
private final Function<Class<?>, Optional<ResourceId>> resourceKinds;
/** @param resourceKinds the id of the resource kind read into a class, which {@code @ResourceRef} options name */
TypeDrafts(HostTypes hostTypes, Function<Class<?>, Optional<ResourceId>> resourceKinds) {
this.hostTypes = hostTypes;
this.resourceKinds = resourceKinds;
}
/** One described class: its metadata and its options with their kinds and raw default values. */
record TypeDraft(Class<?> type, SchemaSource source, OptionsMetadata metadata, List<OptionDraft> options) {}
/** {@code defaultValue} is the field's value in a new instance, or null. */
record OptionDraft(OptionsMetadata.Option option, ValueKind kind, Object defaultValue) {}
/** Describes a catalogued settings type and everything it reaches. */
ObjectKind settings(SchemaSource source) {
return root("Settings type", source);
}
/** Describes the class a resource kind reads its files into and everything it reaches. */
ObjectKind resourceKind(SchemaSource source) {
return root("Resource type", source);
}
private ObjectKind root(String label, SchemaSource source) {
var type = source.type();
try {
return object(type, source);
} catch (SettingsTypeProblem problem) {
throw new IllegalArgumentException(label + " " + type.getName() + " of " + source + " " + problem.getMessage());
}
}
Collection<TypeDraft> drafts() {
return drafts.values();
}
private ObjectKind object(Class<?> type, SchemaSource source) {
claimName(type, source);
if (drafts.containsKey(type) || describing.contains(type)) {
return new ObjectKind(type.getName());
}
requireDescribable(type);
describing.add(type);
drafts.put(type, draft(type, source));
describing.remove(type);
return new ObjectKind(type.getName());
}
private TypeDraft draft(Class<?> type, SchemaSource source) {
var metadata = inspect(type, source);
var instance = instantiate(type, source);
var kinds = new ValueKinds(nested -> object(nested, source), hostTypes, resourceKinds,
source.module().source() == DiscoveredModule.Source.HOST);
var options = metadata.options().stream()
.map(option -> new OptionDraft(option, kind(option, kinds, source), defaultValue(option.field(), instance, source)))
.toList();
return new TypeDraft(type, source, metadata, options);
}
private void claimName(Class<?> type, SchemaSource source) {
var previous = names.putIfAbsent(type.getName(), type);
if (previous == null || previous == type) return;
throw new IllegalArgumentException("Two different classes named " + type.getName() + " are used by settings,"
+ " the second by " + source + "; studio describes classes by name, so rename one");
}
private static void requireDescribable(Class<?> type) {
if (type.isPrimitive()) throw unsupported(type, "which settings cannot use; " + ValueKinds.SUPPORTED_TYPES);
if (isJdkClass(type)) throw unsupported(type, "a JDK class settings cannot use; " + ValueKinds.SUPPORTED_TYPES);
if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) {
throw unsupported(type, "which is abstract; settings fields need a concrete class");
}
if (type.isAnonymousClass() || type.isLocalClass()) {
throw unsupported(type, "which is a local or anonymous class; declare it as a top-level or static nested class");
}
if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers())) {
throw unsupported(type, "which is an inner class; declare it static");
}
}
/** JDK classes live in named modules of the boot layer; module classes, built-in or from packs, do not. */
private static boolean isJdkClass(Class<?> type) {
var module = type.getModule();
return module.isNamed() && module.getLayer() == ModuleLayer.boot();
}
private static OptionsMetadata inspect(Class<?> type, SchemaSource source) {
try {
return OptionsMetadata.inspect(type);
} catch (IllegalArgumentException | LinkageError failure) {
throw new IllegalArgumentException("Class " + type.getName() + " of " + source
+ " cannot be described: " + failure.getMessage(), failure);
}
}
private static Object instantiate(Class<?> type, SchemaSource source) {
var constructor = noArgumentConstructor(type, source);
try {
constructor.setAccessible(true);
return constructor.newInstance();
} catch (InvocationTargetException failure) {
throw new IllegalArgumentException("The no-argument constructor of " + type.getName() + " of " + source
+ " threw " + failure.getCause() + "; the host creates settings with it, so it must not fail",
failure.getCause());
} catch (ReflectiveOperationException | RuntimeException | LinkageError failure) {
throw new IllegalArgumentException("Class " + type.getName() + " of " + source
+ " cannot be created with its no-argument constructor: " + failure, failure);
}
}
private static Constructor<?> noArgumentConstructor(Class<?> type, SchemaSource source) {
try {
return type.getDeclaredConstructor();
} catch (NoSuchMethodException missing) {
throw new IllegalArgumentException("Class " + type.getName() + " of " + 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 static ValueKind kind(OptionsMetadata.Option option, ValueKinds kinds, SchemaSource source) {
try {
return kinds.of(option);
} catch (SettingsTypeProblem problem) {
throw new IllegalArgumentException("Field " + fieldName(option.field()) + " of " + source + " "
+ problem.getMessage());
} catch (TypeNotPresentException | MalformedParameterizedTypeException | LinkageError failure) {
throw new IllegalArgumentException("Field " + fieldName(option.field()) + " of " + source
+ " uses a type that cannot be loaded: " + failure, failure);
}
}
private static Object defaultValue(Field field, Object instance, SchemaSource source) {
try {
field.setAccessible(true);
return field.get(instance);
} catch (IllegalAccessException | InaccessibleObjectException failure) {
throw new IllegalArgumentException("Field " + fieldName(field) + " of " + source
+ " cannot be read for its default: " + failure, failure);
}
}
private static String fieldName(Field field) {
return field.getDeclaringClass().getName() + "." + field.getName();
}
private static SettingsTypeProblem unsupported(Class<?> type, String why) {
return new SettingsTypeProblem("uses " + type.getName() + ", " + why);
}
}
@@ -0,0 +1,53 @@
package com.volmit.host;
import java.lang.module.ModuleFinder;
import java.lang.module.ModuleReference;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/** The JDK modules whose classes pack modules cannot use, by package. Packs see the JDK through the
* platform class loader, which provides the modules defined to it and to the boot loader. Other JDK
* modules, such as {@code jdk.compiler} or {@code jdk.jshell}, are defined to the application class
* loader, or not resolved at all, so a pack never sees them. Judged from module descriptors, so
* nothing is loaded.
*/
final class UnavailableJdkModules {
private static final char PACKAGE_SEPARATOR = '.';
private UnavailableJdkModules() {}
/** The JDK module that holds the class's package, if packs cannot use that module. */
static Optional<String> moduleOf(String binaryName) {
int separator = binaryName.lastIndexOf(PACKAGE_SEPARATOR);
if (separator < 0) return Optional.empty();
return Optional.ofNullable(ModulesByPackage.UNAVAILABLE.get(binaryName.substring(0, separator)));
}
private static boolean platformLoaderProvides(String moduleName) {
return ModuleLayer.boot().findModule(moduleName)
.filter(UnavailableJdkModules::platformLoaderProvides)
.isPresent();
}
/** Whether packs see the module's classes, which they do through the platform class loader. */
static boolean platformLoaderProvides(Module module) {
return isPlatformOrBootLoader(module.getClassLoader());
}
/** The boot loader is {@code null}; the platform loader delegates to it. */
private static boolean isPlatformOrBootLoader(ClassLoader loader) {
return loader == null || loader == ClassLoader.getPlatformClassLoader();
}
/** Built on first use, once per runtime: the JDK's modules do not change while it runs. */
private static final class ModulesByPackage {
static final Map<String, String> UNAVAILABLE = ModuleFinder.ofSystem().findAll().stream()
.map(ModuleReference::descriptor)
.filter(descriptor -> !platformLoaderProvides(descriptor.name()))
.flatMap(descriptor -> descriptor.packages().stream().map(name -> Map.entry(name, descriptor.name())))
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
private ModulesByPackage() {}
}
}
@@ -0,0 +1,12 @@
package com.volmit.host;
import com.volmit.validation.Validator;
import java.util.Objects;
/** A validator and the module that registered it, which the host names when the validator fails. */
public record ValidatorRegistration(Validator validator, DiscoveredModule module) {
public ValidatorRegistration {
Objects.requireNonNull(validator, "validator");
Objects.requireNonNull(module, "module");
}
}
@@ -0,0 +1,199 @@
package com.volmit.host;
import com.volmit.block.BlockState;
import com.volmit.config.Desc;
import com.volmit.config.Reference;
import com.volmit.host.schema.TextFormat;
import com.volmit.host.schema.ValueKind;
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.ResourceId;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
/** Maps a settings field's declared type, {@code @Ref} and {@code @ResourceRef} to the JSON it takes. Host types
* become host kinds where the settings may use them; other classes that are none of the built-in kinds become
* object kinds through the given function. Throws {@link SettingsTypeProblem} for a type or reference that does
* not fit.
*/
@SuppressWarnings("removal") // host kinds are transitional, until the cut-over
final class ValueKinds {
static final String SUPPORTED_TYPES = "settings fields can be booleans, numbers, String, ResourceId, BlockState, enums, "
+ "lists, sets and arrays of these, Map with String keys, Object for any JSON value and classes with a no-argument constructor";
private static final Set<Class<?>> BOOLEANS = Set.of(boolean.class, Boolean.class);
private static final Set<Class<?>> INTEGERS = Set.of(byte.class, short.class, int.class, long.class,
Byte.class, Short.class, Integer.class, Long.class);
private static final Set<Class<?>> DECIMALS = Set.of(float.class, double.class, Float.class, Double.class);
private static final String DECLARE_COLLECTION = "declare it as List<...>, Set<...> or Map<String, ...>";
private static final Set<Reference> PACK_REFERENCES = EnumSet.of(Reference.PACK_BIOME, Reference.PACK_REGION, Reference.PACK_OBJECT,
Reference.PACK_EXPRESSION, Reference.PACK_IMAGE_MAP, Reference.PACK_STRUCTURE);
private final Function<Class<?>, ObjectKind> objects;
private final HostTypes hostTypes;
private final Function<Class<?>, Optional<ResourceId>> resourceKinds;
private final boolean hostTypesAllowed;
/** {@code resourceKinds} gives the id of the resource kind read into a class; {@code hostTypesAllowed} is
* whether the settings belong to a module that ships with the host.
*/
ValueKinds(Function<Class<?>, ObjectKind> objects, HostTypes hostTypes, Function<Class<?>, Optional<ResourceId>> resourceKinds,
boolean hostTypesAllowed) {
this.objects = objects;
this.hostTypes = hostTypes;
this.resourceKinds = resourceKinds;
this.hostTypesAllowed = hostTypesAllowed;
}
ValueKind of(OptionsMetadata.Option option) {
return kind(option.type(), new Naming(option.reference(), option.resource()));
}
/** What a text option names: the field's {@code @Ref} and the class of its {@code @ResourceRef}, each null when absent. */
private record Naming(Reference reference, Class<?> resource) {
static final Naming NONE = new Naming(null, null);
boolean isEmpty() {
return reference == null && resource == null;
}
}
/** Lists, sets and arrays pass {@code naming} on to their elements. */
private ValueKind kind(Type type, Naming naming) {
return switch (type) {
case Class<?> plain -> classKind(plain, naming);
case ParameterizedType generic -> genericKind(generic, naming);
case GenericArrayType array -> new ListKind(kind(array.getGenericComponentType(), naming), false);
default -> throw unsupported(type, ", which is not a concrete type; name the type, such as List<String>");
};
}
private ValueKind classKind(Class<?> type, Naming naming) {
if (hostTypes.contains(type)) return hostKind(type, naming);
if (type == String.class) return text(TextFormat.PLAIN, naming);
if (type == ResourceId.class) return text(TextFormat.RESOURCE_ID, naming);
if (type == BlockState.class) return blockState(naming);
if (type.isArray()) return new ListKind(kind(type.getComponentType(), naming), false);
if (isCollection(type)) throw unsupported(type, " without type arguments; " + DECLARE_COLLECTION);
requireNoNaming(type, naming);
if (BOOLEANS.contains(type)) return new BooleanKind();
if (INTEGERS.contains(type)) return new IntegerKind();
if (DECIMALS.contains(type)) return new DecimalKind();
if (type.isEnum()) return enumKind(type);
if (type == Object.class) return new AnyKind();
return objects.apply(type);
}
private ValueKind genericKind(ParameterizedType generic, Naming naming) {
var raw = (Class<?>) generic.getRawType();
if (hostTypes.contains(raw)) return hostKind(raw, naming);
var arguments = generic.getActualTypeArguments();
if (raw == List.class || raw == Set.class) return new ListKind(kind(arguments[0], naming), raw == Set.class);
if (raw == Map.class) return mapKind(generic, arguments, naming);
if (isCollection(raw)) throw unsupported(generic, "; " + DECLARE_COLLECTION);
throw unsupported(generic, "; only List, Set and Map may have type arguments");
}
private ValueKind mapKind(ParameterizedType generic, Type[] arguments, Naming naming) {
requireNoNaming(generic, naming);
if (arguments[0] != String.class) throw unsupported(generic, "; map keys must be String");
return new MapKind(kind(arguments[1], Naming.NONE));
}
private HostKind hostKind(Class<?> type, Naming naming) {
requireNoNaming(type, naming);
if (hostTypesAllowed) return new HostKind(type.getName());
throw new SettingsTypeProblem("uses " + type.getName() + ", a class the host describes itself, which only settings of"
+ " modules that ship with the host may use; " + SUPPORTED_TYPES);
}
private ValueKind text(TextFormat format, Naming naming) {
if (naming.resource() != null) return resourceReference(naming);
var reference = naming.reference();
if (reference == null) return new TextKind(format);
if (PACK_REFERENCES.contains(reference)) return new ReferenceKind(reference, TextFormat.PLAIN);
return new ReferenceKind(reference, format);
}
/** Packs name a kind's resources by key without a namespace, as they name their biomes, so the JSON holds a key
* whether the field is a String or a ResourceId (which the host reads as the pack's id of that key).
*/
private ValueKind resourceReference(Naming naming) {
var resource = naming.resource();
if (naming.reference() != null) {
throw new SettingsTypeProblem("has both @Ref(" + naming.reference() + ") and @ResourceRef(" + resource.getName()
+ "); an option names one kind of thing, so keep one");
}
return resourceKinds.apply(resource).map(ResourceReferenceKind::new).orElseThrow(() -> new SettingsTypeProblem(
"has @ResourceRef(" + resource.getName() + "), but no module of the pack registers a resource kind read into"
+ " that class; name the class of a kind registered with FeatureRegistry.registerResourceKind"));
}
private static ValueKind blockState(Naming naming) {
var reference = naming.reference();
if (naming.resource() == null && (reference == null || reference == Reference.BLOCK)) {
return new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE);
}
if (naming.resource() != null) {
throw new SettingsTypeProblem("has @ResourceRef(" + naming.resource().getName() + ") on BlockState, which always"
+ " names a block; remove the @ResourceRef or use String");
}
throw new SettingsTypeProblem("has @Ref(" + reference + ") on BlockState, which always names a block;"
+ " remove the @Ref or use String or ResourceId");
}
private static EnumKind enumKind(Class<?> type) {
var constants = Arrays.stream(type.getEnumConstants())
.map(constant -> ((Enum<?>) constant).name())
.map(name -> new EnumConstant(name, constantDescription(type, name)))
.toList();
return new EnumKind(type.getName(), constants);
}
private static String constantDescription(Class<?> type, String constant) {
try {
var desc = type.getField(constant).getAnnotation(Desc.class);
return desc == null ? "" : desc.value();
} catch (NoSuchFieldException impossible) {
throw new IllegalStateException("Enum constant without field: " + type.getName() + "." + constant, impossible);
}
}
private static void requireNoNaming(Type type, Naming naming) {
if (naming.isEmpty()) return;
if (naming.reference() != null) {
throw new SettingsTypeProblem("has @Ref(" + naming.reference() + ") on " + type.getTypeName()
+ ", but @Ref fits only String and ResourceId and lists, sets and arrays of them");
}
throw new SettingsTypeProblem("has @ResourceRef(" + naming.resource().getName() + ") on " + type.getTypeName()
+ ", but @ResourceRef fits only String and ResourceId and lists, sets and arrays of them");
}
private static boolean isCollection(Class<?> type) {
return Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type);
}
/** {@code why} starts with its own separator, such as ", which ..." or "; ...". */
private static SettingsTypeProblem unsupported(Type type, String why) {
return new SettingsTypeProblem("uses " + type.getTypeName() + why);
}
}
@@ -0,0 +1,119 @@
package com.volmit.host;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/** The reference store behind {@link com.volmit.world.PackWorld#state}: one instance per type, created once, closed
* with the world. A host's world implementation keeps one per world and passes {@code state} calls on, binding the
* world into the factory.
*
* <p>Reads of existing state take no lock. Creation runs under the store's lock, so each type is created once even
* when threads race; a factory may ask for other state on its own thread (the lock is re-entrant), and a type asked
* for again while it is being created fails instead of recursing. {@link #close()} closes every {@link AutoCloseable}
* state, newest first, and ends the store.
*/
public final class WorldStates implements AutoCloseable {
private final Map<Class<?>, Object> states = new ConcurrentHashMap<>();
private final List<Object> createdInOrder = new ArrayList<>();
private final Deque<Class<?>> creating = new ArrayDeque<>();
private final Object lock = new Object();
private boolean closed;
/** The {@code type} state, created by {@code create} the first time it is asked for. See {@link com.volmit.world.PackWorld#state}. */
public <T> T state(Class<T> type, Supplier<? extends T> create) {
Objects.requireNonNull(type, "type");
Objects.requireNonNull(create, "create");
Object existing = states.get(type);
if (existing != null) {
return type.cast(existing);
}
synchronized (lock) {
requireOpen(type);
existing = states.get(type);
if (existing != null) {
return type.cast(existing);
}
return create(type, create);
}
}
/** Closes every {@link AutoCloseable} state, the newest first, even when one fails, then throws the first failure
* with the others suppressed. Asking for state afterwards throws. Closing twice does nothing.
*/
@Override
public void close() {
List<Object> closing;
synchronized (lock) {
if (closed) {
return;
}
closed = true;
closing = new ArrayList<>(createdInOrder);
createdInOrder.clear();
states.clear();
}
RuntimeException failure = null;
for (int index = closing.size() - 1; index >= 0; index--) {
failure = closeState(closing.get(index), failure);
}
if (failure != null) {
throw failure;
}
}
private <T> T create(Class<T> type, Supplier<? extends T> create) {
if (creating.contains(type)) {
throw new IllegalStateException("World state " + type.getName() + " was asked for while it is being created: "
+ creationChain(type));
}
creating.push(type);
try {
T created = type.cast(Objects.requireNonNull(create.get(), () -> "The factory of world state " + type.getName()
+ " returned null"));
states.put(type, created);
createdInOrder.add(created);
return created;
} finally {
creating.pop();
}
}
private String creationChain(Class<?> repeated) {
var chain = new ArrayList<Class<?>>(creating);
Collections.reverse(chain);
chain.add(repeated);
return chain.stream().map(Class::getName).collect(Collectors.joining(" -> "));
}
private void requireOpen(Class<?> type) {
if (closed) {
throw new IllegalStateException("World state " + type.getName() + " was asked for after the world stopped");
}
}
private static RuntimeException closeState(Object state, RuntimeException failure) {
if (!(state instanceof AutoCloseable closeable)) {
return failure;
}
try {
closeable.close();
return failure;
} catch (Exception exception) {
var closeFailure = new IllegalStateException("World state " + state.getClass().getName() + " failed to close: "
+ exception, exception);
if (failure == null) {
return closeFailure;
}
failure.addSuppressed(closeFailure);
return failure;
}
}
}
@@ -0,0 +1,9 @@
package com.volmit.host.schema;
/** Why a module catalogued a settings type. */
public enum FeatureRole {
/** Settings that stages read: named in {@code when(...)} or registered with {@code registerSettings}. */
SETTINGS,
/** Settings of an object generator, registered with {@code registerObject}. */
OBJECT_GENERATOR
}
@@ -0,0 +1,56 @@
package com.volmit.host.schema;
import com.volmit.ModuleInfo;
import com.volmit.config.Level;
import com.volmit.resource.ResourceId;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/** A module's settings type and the JSON key it is written under at each of its targets.
*
* @param id the feature id from {@code @Feature}
* @param name the feature's display name from {@code @Feature}
* @param module the module that owns the feature id
* @param key the JSON key the settings are written under, declared by the feature, the same at every target
* @param root the option whose value the key holds, when the JSON is that value and not an object of options
* @param targets the levels whose files hold the key, in {@link Level} order
* @param settings the settings class; its description describes the value
*/
public record FeatureSchema(
ResourceId id,
String name,
FeatureRole role,
ModuleInfo module,
String key,
Optional<String> root,
Set<Level> targets,
ObjectType settings) {
public FeatureSchema {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(name, "name");
Objects.requireNonNull(role, "role");
Objects.requireNonNull(module, "module");
Objects.requireNonNull(key, "key");
Objects.requireNonNull(root, "root");
Objects.requireNonNull(settings, "settings");
targets = Collections.unmodifiableSet(EnumSet.copyOf(targets));
root.ifPresent(option -> requireOption(settings, option));
}
/** The option the key holds the value of, when the JSON under the key is one option's value. Then the
* key takes exactly that value, such as a list, and not an object of options.
*/
public Optional<SchemaOption> rootOption() {
return root.map(option -> requireOption(settings, option));
}
private static SchemaOption requireOption(ObjectType settings, String option) {
return settings.options().stream()
.filter(candidate -> candidate.name().equals(option))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Root " + option + " is no option of " + settings.name()));
}
}
@@ -0,0 +1,22 @@
package com.volmit.host.schema;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/** A settings class, described once per pack however many options use it.
*
* @param name the class's binary name, such as {@code com.example.moss.MossSettings}; unique in a pack
* @param description the class's {@code @Desc}, or empty
* @param snippet the class's {@code @Snippet} name: a pack may then write the object in its own file
* under {@code snippet/<name>/} and refer to it by path
* @param options the class's fields, including inherited ones, in declaration order, a superclass's first
*/
public record ObjectType(String name, String description, Optional<String> snippet, List<SchemaOption> options) {
public ObjectType {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(description, "description");
Objects.requireNonNull(snippet, "snippet");
options = List.copyOf(options);
}
}
@@ -0,0 +1,66 @@
package com.volmit.host.schema;
import com.volmit.config.Level;
import com.volmit.resource.ResourceId;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
/** What the modules of a loaded pack add to the pack's JSON, for the host to render as JSON Schema and
* studio completion. It holds module-provided entries only: the host describes its own fields.
*
* <p>Everything is in a fixed order, so the same modules always give the same description: features
* and resource kinds by id, the features of a target by JSON key, types by name, snippets by snippet name,
* options and enum constants in declaration order.
*
* @param features every catalogued settings type of the pack's modules, built-in ones included
* @param resources every resource kind of the pack's modules, built-in ones included
* @param types every class reachable from those settings and resource kinds, each once
*/
public record PackSchema(List<FeatureSchema> features, List<ResourceKindSchema> resources, List<ObjectType> types) {
public PackSchema {
features = features.stream().sorted(Comparator.comparing(FeatureSchema::id)).toList();
resources = resources.stream().sorted(Comparator.comparing(ResourceKindSchema::id)).toList();
types = types.stream().sorted(Comparator.comparing(ObjectType::name)).toList();
}
/** The resource kind {@code id}, such as the one a {@link ValueKind.ResourceReferenceKind} names. */
public ResourceKindSchema resource(ResourceId id) {
Objects.requireNonNull(id, "id");
return resources.stream()
.filter(kind -> kind.id().equals(id))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("No resource kind: " + id));
}
/** The module features written in the files of one level, by JSON key. */
public List<FeatureSchema> fields(Level target) {
Objects.requireNonNull(target, "target");
return features.stream()
.filter(feature -> feature.targets().contains(target))
.sorted(Comparator.comparing(FeatureSchema::key))
.toList();
}
/** The settings of object generators, by feature id. */
public List<FeatureSchema> objectGenerators() {
return features.stream().filter(feature -> feature.role() == FeatureRole.OBJECT_GENERATOR).toList();
}
/** The type an {@link ValueKind.ObjectKind} names. */
public ObjectType type(String name) {
return types.stream()
.filter(type -> type.name().equals(name))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("No settings type: " + name));
}
/** The types a pack may write as snippet files, by snippet name; each name belongs to one type. */
public List<ObjectType> snippets() {
return types.stream()
.filter(type -> type.snippet().isPresent())
.sorted(Comparator.comparing(type -> type.snippet().orElseThrow()))
.toList();
}
}
@@ -0,0 +1,27 @@
package com.volmit.host.schema;
import com.volmit.ModuleInfo;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** A module resource kind and what its files hold, for the host to give studio a schema for every JSON file below
* the kind's folder.
*
* @param id the kind's id
* @param module the module that registered the kind
* @param folder the folder below the pack root that holds the kind's files
* @param type what each file holds: an {@link ValueKind.ObjectKind} naming an entry of {@link PackSchema#types()}, or
* a {@link ValueKind.HostKind} for a built-in kind whose class the host describes itself
*/
@SuppressWarnings("removal") // host kinds are transitional, until the cut-over
public record ResourceKindSchema(ResourceId id, ModuleInfo module, String folder, ValueKind type) {
public ResourceKindSchema {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(module, "module");
Objects.requireNonNull(folder, "folder");
Objects.requireNonNull(type, "type");
if (!(type instanceof ValueKind.ObjectKind) && !(type instanceof ValueKind.HostKind)) {
throw new IllegalArgumentException("Resource kind " + id + " files hold an object, not " + type);
}
}
}
@@ -0,0 +1,39 @@
package com.volmit.host.schema;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
/** One option of an {@link ObjectType}: a field of a settings class.
*
* <p>{@code minItems} is the least length of a list, set or array option ({@link com.volmit.config.MinItems}).
*
* <p>{@code defaultValue} is the field's value in an instance made by the class's no-argument
* constructor, as plain JSON-shaped Java values: {@code Boolean}, {@code Long} for integer kinds,
* {@code Double} for decimal kinds, {@code String} for text, references and enum constants,
* {@code List<Object>} for list kinds (sets sorted) and {@code Map<String, Object>} with sorted keys
* for maps and objects, where an object holds its options that have defaults. It is empty when the
* field is null, when a float or double is not finite, when a list or map holds a value without a
* default and when a set holds objects, lists or maps. An object inside itself, such as a field
* holding {@code this}, is left out of the outer object.
*/
public record SchemaOption(
String name,
ValueKind kind,
String description,
boolean required,
OptionalDouble minimum,
OptionalDouble maximum,
OptionalInt minItems,
Optional<Object> defaultValue) {
public SchemaOption {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(kind, "kind");
Objects.requireNonNull(description, "description");
Objects.requireNonNull(minimum, "minimum");
Objects.requireNonNull(maximum, "maximum");
Objects.requireNonNull(minItems, "minItems");
Objects.requireNonNull(defaultValue, "defaultValue");
}
}
@@ -0,0 +1,11 @@
package com.volmit.host.schema;
/** How a string option is written. */
public enum TextFormat {
/** Any string: {@code String} fields. */
PLAIN,
/** {@code namespace:path}, as {@link com.volmit.resource.ResourceId} parses it. */
RESOURCE_ID,
/** {@code namespace:path}, optionally followed by {@code [name=value,...]}, as {@link com.volmit.block.BlockState#key()} writes it. */
BLOCK_STATE
}
@@ -0,0 +1,103 @@
package com.volmit.host.schema;
import com.volmit.config.Reference;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Objects;
/** The JSON an option takes. Every settings field maps to exactly one kind; a field of any other type
* fails the pack load, so the host never sees an untyped option.
*/
public sealed interface ValueKind {
/** {@code true} or {@code false}: {@code boolean} and {@code Boolean} fields. */
record BooleanKind() implements ValueKind {}
/** A whole number: {@code byte}, {@code short}, {@code int} and {@code long} fields and their boxes. */
record IntegerKind() implements ValueKind {}
/** Any number: {@code float} and {@code double} fields and their boxes. */
record DecimalKind() implements ValueKind {}
/** A string in {@code format} that names nothing in particular. */
record TextKind(TextFormat format) implements ValueKind {
public TextKind {
Objects.requireNonNull(format, "format");
}
}
/** A string in {@code format} that names an entry of {@code reference}, such as a block. */
record ReferenceKind(Reference reference, TextFormat format) implements ValueKind {
public ReferenceKind {
Objects.requireNonNull(reference, "reference");
Objects.requireNonNull(format, "format");
}
}
/** A string naming a resource of the module resource kind {@code kind} by its key in the pack, such as
* {@code castle/start}; see {@link PackSchema#resource}.
*/
record ResourceReferenceKind(ResourceId kind) implements ValueKind {
public ResourceReferenceKind {
Objects.requireNonNull(kind, "kind");
}
}
/** One of the constant names of the enum class named {@code type}, in declaration order. */
record EnumKind(String type, List<EnumConstant> constants) implements ValueKind {
public EnumKind {
Objects.requireNonNull(type, "type");
constants = List.copyOf(constants);
}
}
/** A JSON array of {@code element} values: lists, arrays and, with {@code unique}, sets. */
record ListKind(ValueKind element, boolean unique) implements ValueKind {
public ListKind {
Objects.requireNonNull(element, "element");
}
}
/** A JSON object with any string keys and {@code value} values: {@code Map<String, V>} fields. */
record MapKind(ValueKind value) implements ValueKind {
public MapKind {
Objects.requireNonNull(value, "value");
}
}
/** A JSON object described by the {@link ObjectType} named {@code type} in {@link PackSchema#types()}.
* Types are referenced by name, so a type that contains itself is described once.
*/
record ObjectKind(String type) implements ValueKind {
public ObjectKind {
Objects.requireNonNull(type, "type");
}
}
/** A value of the class named {@code type}, which the host describes itself, such as one of Iris's
* palettes or noise styles. Only built-in modules' settings use these (see
* {@link com.volmit.host.ModuleHost#describingHostTypesIn}); the host renders its own description.
*
* @deprecated Transitional, until the cut-over, with {@link com.volmit.host.ModuleHost#describingHostTypesIn}.
*/
@Deprecated(forRemoval = true)
record HostKind(String type) implements ValueKind {
public HostKind {
Objects.requireNonNull(type, "type");
}
}
/** Any JSON value, which the module reads as it is: {@code Object} fields, and the values of {@code Map<String, Object>}
* and {@code List<Object>}. For data whose shape the module does not own, such as a block entity's data. The host
* decodes objects as maps with string keys, arrays as lists, numbers as {@code Double}, and strings and booleans
* as themselves.
*/
record AnyKind() implements ValueKind {}
/** An enum constant and its {@code @Desc}, or an empty description. */
record EnumConstant(String name, String description) {
public EnumConstant {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(description, "description");
}
}
}
@@ -0,0 +1,229 @@
package com.volmit;
import com.volmit.block.BlockState;
import com.volmit.host.ArrayHunk;
import com.volmit.mantle.BlockBox;
import com.volmit.object.*;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.*;
import com.volmit.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 moduleInfoDeclaresOptionalPackagesWithTheirSubpackages() {
var plain = ModuleInfo.of("example:moss", "Moss", "1.0.0");
var info = plain.withOptionalPackages("org.slf4j", "org.apache.logging.");
assertEquals(List.of(), plain.optionalPackages());
assertEquals(List.of(new PackageName("org.slf4j"), new PackageName("org.apache.logging")), info.optionalPackages());
assertEquals(List.of(), info.withOptionalPackages().optionalPackages());
assertTrue(info.optionalPackages().getFirst().contains("org.slf4j.spi.LocationAwareLogger"));
assertFalse(info.optionalPackages().getFirst().contains("org.slf4jx.Logger"));
for (var invalid : List.of("", "org.*", "org..slf4j", "1org")) {
var failure = assertThrows(IllegalArgumentException.class, () -> plain.withOptionalPackages(invalid));
assertTrue(failure.getMessage().startsWith("Optional package '" + invalid + "' of module example:moss is not a package name"),
failure.getMessage());
}
}
@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(ResourceId.parse("test:placement"), 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(request.id(), object, new BlockPosition(Integer.MAX_VALUE, 0, 0));
assertThrows(ArithmeticException.class, overflow::footprint);
}
@Test
void boundedHunksAndTerrainSamplesRejectInvalidInputs() {
var hunk = new ArrayHunk<>(String.class, 2, 3, 4, "air");
hunk.set(1, 2, 3, "stone");
assertEquals("stone", hunk.get(1, 2, 3));
assertEquals("air", hunk.get(0, 0, 0));
assertThrows(IndexOutOfBoundsException.class, () -> hunk.get(2, 0, 0));
assertThrows(IndexOutOfBoundsException.class, () -> hunk.set(-1, 0, 0, "stone"));
assertThrows(NullPointerException.class, () -> hunk.set(0, 0, 0, null));
assertThrows(IllegalArgumentException.class, () -> new TerrainSample(Double.NaN, OptionalInt.empty(), 0));
assertThrows(IllegalArgumentException.class, () -> new TerrainSample(0, OptionalInt.empty(), -1));
}
@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,180 @@
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(JigsawOverrides.Heightmap.SOURCE, JigsawOverrides.none().projectStartToHeightmap());
var overrides = JigsawOverrides.none().withStartPool("minecraft:village/plains/town_centers").withMaxDepth(4)
.withMaxDistance(80, 120).withHeightmap(JigsawOverrides.Heightmap.NONE);
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\"}", "null");
assertEquals(Optional.of(memo), start.withMemo(memo).memo());
assertNotEquals(start, start.withMemo(memo));
assertEquals(Optional.empty(), start.jigsaw());
var underground = start.underground().replacingPlatformStart().withIdentity(-5L)
.withJigsaw(JigsawOverrides.none().withMaxDepth(3));
assertTrue(underground.isUnderground());
assertTrue(underground.replacesPlatformStart());
assertEquals(-5L, underground.identity());
assertEquals(Optional.of(JigsawOverrides.none().withMaxDepth(3)), underground.jigsaw());
assertEquals(underground, start.withIdentity(-5L).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));
assertEquals(Set.of(), provider.startedStructures(null));
assertEquals(Set.of(), provider.locatableStarts(null));
assertEquals(LocateResult.NOT_FOUND, provider.locateStart(null, CITY, 0, 0, 8, (chunkX, chunkZ) -> true));
}
@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));
}
@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,288 @@
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.mantle.BlockBox;
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(Map.of(BlockState.class, 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(Map.of(), 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(Map.of(BlockState.class, 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.hunk(BlockState.class);
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(Map.of(BlockState.class, 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().isCarved(6, 9, 2)));
carved.add(String.valueOf(context.mantle().isCarved(6, 10, 2)));
});
}
};
var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, AIR);
new ChunkRunner(TestSetups.stages(module).resolve(Pipeline.CHUNK)).generate(
TestContexts.generation(Map.of(BlockState.class, blocks), ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED,
StageTimings.NONE);
assertEquals(List.of("true", "false"), carved);
}
@Test
void theRunnerReportsHowLongEachStageThatRanTook() {
var timed = new ArrayList<String>();
var blocks = new ArrayHunk<>(BlockState.class, SIZE, HEIGHT, SIZE, AIR);
runner().generate(TestContexts.generation(Map.of(BlockState.class, 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(Map.of(), 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(Map.of(), 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(Map.of(), 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));
}
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.mantle.BlockBox;
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 com.volmit.world.BlockPosition;
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(ResourceId.parse("test:attempt"), 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.hunk(BlockState.class);
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.hunk(BlockState.class);
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;
}
}
Loaded 100 of 309 files, more files were not shown because too many files have changed in this diff. Show more