Key settings by feature id, order options as declared and declare stage reach

- Packs write settings under the feature id. @Feature(field) becomes an
  optional alias that only built-in modules may set, so existing pack JSON
  keeps loading; a pack module setting one fails the load. Reserved host
  fields now only constrain aliases. FeatureSchema exposes key and alias.
- Pack snippet names live under their module's folder
  (snippet/<namespace>/<path>/...); snippet names are folder paths.
- OptionsMetadata lists options in declaration order, read from the class
  file, a superclass's first.
- @Ref(PACK_BIOME|PACK_REGION|PACK_OBJECT) fits String only.
- Stage definitions declare reach(blocks) and writesMantle(layers);
  ResolvedGraph.reach() collects the pipeline and per-layer maximum, and
  the load fails on an unregistered or mistyped layer.
This commit is contained in:
piexel committed 2026-10-06 13:59:28 +02:00
1 parent b12e7a8c49
commit a325640d5d
38 files changed
+761 -138

No files matched your search

@@ -1,16 +1,33 @@
package com.volmit;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/** Maps settings to an ordinary existing JSON field, without an extension wrapper. */
public record FeatureAttachment(String field, Set<Target> targets) {
/** Where settings appear in pack JSON: the targets, and the optional short alias a built-in module
* may set besides the feature id, which is always the JSON key.
*/
public record FeatureAttachment(Optional<String> alias, Set<Target> targets) {
public enum Target { DIMENSION, REGION, BIOME, OBJECT_PLACEMENT }
private static final char NAMESPACE_SEPARATOR = ':';
public FeatureAttachment {
Objects.requireNonNull(field, "field");
if (field.isBlank()) throw new IllegalArgumentException("Field must not be blank");
Objects.requireNonNull(alias, "alias");
alias.ifPresent(FeatureAttachment::requireFieldName);
targets = Set.copyOf(targets);
if (targets.isEmpty()) throw new IllegalArgumentException("At least one target is required");
}
/** Checks a JSON field name that is not a feature id: an alias or a field the host itself uses.
* It is not blank and has no ':', which every feature id has, so the two never collide.
*/
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;
}
}
@@ -0,0 +1,55 @@
package com.volmit.config;
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;
}
}
+8 -2
View File
@@ -2,12 +2,18 @@ package com.volmit.config;
import java.lang.annotation.*;
/** Identity and JSON attachment for an IrisFeature configuration class. */
/** Identity and JSON attachment for an IrisFeature configuration class. Packs write the settings under
* their feature id, such as {@code "example:moss": {...}}, at each of the targets.
*
* <p>{@code alias} is an optional short JSON key that only modules shipping with the host may set, so
* existing pack JSON such as {@code "stilt": {...}} keeps loading. A pack module that sets one fails
* the load. An alias contains no ':', so it never equals a feature id.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Feature {
String id();
String name();
String field();
String alias() default "";
com.volmit.FeatureAttachment.Target[] targets();
}
@@ -25,15 +25,15 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
}
}
/** Reads private and inherited fields without constructing settings or accessing values.
* Nested object types are preserved for the schema builder to inspect recursively.
/** 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 (Class<?> current = type; current != null && current != Object.class;
current = current.getSuperclass()) {
for (var field : current.getDeclaredFields()) {
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;
@@ -64,6 +64,15 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
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 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;
@@ -1,6 +1,7 @@
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;
@@ -40,6 +41,18 @@ final class BlockStageDraft<S extends IrisFeature, O>
return this;
}
@Override
public BlockStageDraft<S, O> reach(int blocks) {
declaration.reach(blocks);
return this;
}
@Override
public BlockStageDraft<S, O> writesMantle(MantleKey<?>... layers) {
declaration.writesMantle(layers);
return this;
}
@Override
@SuppressWarnings("unchecked") // S is a phantom parameter until the condition is recorded here.
public <N extends IrisFeature> BlockStageDraft<N, O> when(Class<N> settingsType) {
@@ -7,6 +7,7 @@ import com.volmit.config.OptionsMetadata;
import com.volmit.resource.ResourceId;
import java.lang.reflect.Modifier;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/** Validated settings metadata. It describes configuration, not executable ordering. */
@@ -41,10 +42,24 @@ public record FeatureDescriptor<F extends IrisFeature>(
ResourceId.parse(annotation.id()),
annotation.name(),
type,
new FeatureAttachment(annotation.field(), Set.of(annotation.targets())),
new FeatureAttachment(alias(annotation), Set.of(annotation.targets())),
OptionsMetadata.inspect(type));
}
/** The JSON key packs write these settings under: the feature id. */
public String key() {
return id.toString();
}
/** The short JSON key a built-in module may set besides {@link #key()}. */
public Optional<String> alias() {
return attachment.alias();
}
private static Optional<String> alias(Feature annotation) {
return annotation.alias().isEmpty() ? Optional.empty() : Optional.of(annotation.alias());
}
private static void requireConcreteFeature(Class<?> type) {
if (!IrisFeature.class.isAssignableFrom(type)
|| type.isInterface()
@@ -1,5 +1,6 @@
package com.volmit.host;
import com.volmit.mantle.MantleKey;
import com.volmit.resource.ResourceId;
import com.volmit.stage.StageKind;
import java.util.List;
@@ -35,12 +36,24 @@ final class GraphDescription {
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(reach.blocks()).append(reach.blocks() == 1 ? " block" : " blocks");
if (!reach.mantleLayers().isEmpty()) {
text.append(", writes mantle ").append(joined(reach.mantleLayers().stream().map(MantleKey::id).toList()));
}
text.append('\n');
}
private static String kindLabel(ResolvedStage stage, List<List<ResourceId>> passes) {
if (stage.stage().kind() == StageKind.INVOCATION) {
return "invocation";
@@ -227,7 +227,7 @@ final class GraphResolver {
settingsSlot(declaration, settingsTypes),
StageStreams.idHash(declaration.stage().id()));
stages.add(new ResolvedStage(declaration.stage(), declaration.module(), declaration.settings(),
incomingEdges(node, position), absentSoftTargets.get(node)));
incomingEdges(node, position), absentSoftTargets.get(node), declaration.reach()));
}
return new ResolvedGraph(pipeline, stages, List.of(executables), settingsTypes);
}
@@ -1,6 +1,7 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
import com.volmit.stage.ConditionalStageDefinition;
import com.volmit.stage.SettingsAction;
import com.volmit.stage.SettingsFunction;
@@ -39,6 +40,18 @@ final class InvocationStageDraft<C extends StageContext, S extends IrisFeature,
return this;
}
@Override
public InvocationStageDraft<C, S, O> reach(int blocks) {
declaration.reach(blocks);
return this;
}
@Override
public InvocationStageDraft<C, S, O> writesMantle(MantleKey<?>... layers) {
declaration.writesMantle(layers);
return this;
}
@Override
@SuppressWarnings("unchecked") // S is a phantom parameter until the condition is recorded here.
public <N extends IrisFeature> InvocationStageDraft<C, N, O> when(Class<N> settingsType) {
@@ -41,7 +41,31 @@ public record LoadedModules(FeatureCatalog catalog, PackSchema schema, ResolvedG
stages.settingsTypes(registry::registeredByOwner).forEach(registry::registerStageSettings);
var catalog = registry.freeze();
var schema = PackSchemaBuilder.describe(catalog, modules);
return new LoadedModules(catalog, schema, stages.resolve(Pipeline.PLACEMENT), stages.resolve(Pipeline.CHUNK));
var placement = stages.resolve(Pipeline.PLACEMENT);
var chunk = stages.resolve(Pipeline.CHUNK);
requireRegisteredMantleLayers(catalog, placement);
requireRegisteredMantleLayers(catalog, chunk);
return new LoadedModules(catalog, schema, placement, chunk);
}
/** 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(() -> new IllegalArgumentException("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 new IllegalArgumentException("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());
}
}
}
}
/** The pack load checks that every class a module uses exists, not that every method or field
@@ -12,8 +12,8 @@ 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 host
* packages pack modules may use besides the Iris API, the JSON fields the host itself uses, and the
* namespaces only built-in modules may use. Build it once and pass it to every
* packages pack modules may use besides the Iris API, the JSON fields the host itself uses (which no
* built-in alias may take), and the namespaces only built-in modules may use. Build it once and pass it to every
* {@link LoadedPack#load(java.nio.file.Path, ModuleHost)}.
*
* <pre>{@code
@@ -81,9 +81,9 @@ public record ModuleHost(
return Map.copyOf(copy);
}
/** A blank field name fails here, as it would in a settings type's {@code @Feature}. */
/** A blank field name, or one with ':' like a feature id, fails here, as it would as an alias. */
private static void requireFieldNames(Map<FeatureAttachment.Target, Set<String>> fields) {
fields.forEach((target, names) -> names.forEach(name -> new FeatureAttachment(name, Set.of(target))));
fields.values().forEach(names -> names.forEach(FeatureAttachment::requireFieldName));
}
private static Map<FeatureAttachment.Target, Set<String>> merge(
@@ -9,15 +9,18 @@ import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
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; JSON fields are unique per attachment target.
* Pass existing host JSON fields to reserve them before modules register. Modules register through
* immutable. IDs are unique across feature kinds, and every feature id is its JSON key. Aliases,
* which only built-in modules may set, are unique per attachment target and may not equal the
* host JSON fields passed in to reserve them. Modules register through
* {@link #register(DiscoveredModule)}; object feature ids, mantle keys and explicitly registered
* settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}). 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
@@ -31,6 +34,7 @@ public final class ModuleRegistry implements FeatureRegistry {
private final Set<Class<?>> featureTypes = new HashSet<>();
private final Set<Class<?>> registeredByOwner = new HashSet<>();
private final Map<Field, String> fields = new HashMap<>();
private final List<DiscoveredModule> registered = new ArrayList<>();
private FeatureCatalog catalog;
private DiscoveredModule registering;
@@ -50,6 +54,7 @@ public final class ModuleRegistry implements FeatureRegistry {
throw new IllegalStateException("Module " + discovered.info().id() + " registered during " + registering.info().id());
}
registering = discovered;
registered.add(discovered);
try {
discovered.module().register(this);
} finally {
@@ -65,7 +70,7 @@ public final class ModuleRegistry implements FeatureRegistry {
var descriptor = FeatureDescriptor.of(featureType);
requireOwnedId("Object generator settings " + featureType.getName() + " with feature id", descriptor.id());
var registration = new ObjectRegistration<>(descriptor, factory);
claim(descriptor);
claim(descriptor, registering);
objects.put(featureType, registration);
}
@@ -87,19 +92,21 @@ public final class ModuleRegistry implements FeatureRegistry {
checkOpen();
var descriptor = FeatureDescriptor.of(settingsType);
requireOwnedId("Settings " + settingsType.getName() + " with feature id", descriptor.id());
catalogSettings(descriptor);
catalogSettings(descriptor, registering);
registeredByOwner.add(settingsType);
}
/** 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.
* 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;
}
catalogSettings(FeatureDescriptor.of(settingsType));
var descriptor = FeatureDescriptor.of(settingsType);
catalogSettings(descriptor, ownerOf(descriptor));
}
/** Whether the module owning {@code settingsType} registered it through {@link #registerSettings}. */
@@ -114,14 +121,21 @@ public final class ModuleRegistry implements FeatureRegistry {
return catalog;
}
private void catalogSettings(FeatureDescriptor<?> descriptor) {
private void catalogSettings(FeatureDescriptor<?> descriptor, DiscoveredModule owner) {
if (settings.containsKey(descriptor.type())) {
return;
}
claim(descriptor);
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.register");
@@ -141,25 +155,32 @@ public final class ModuleRegistry implements FeatureRegistry {
}
private void reserveHostField(FeatureAttachment.Target target, String name) {
new FeatureAttachment(name, Set.of(target));
fields.put(new Field(target, name), "host");
fields.put(new Field(target, FeatureAttachment.requireFieldName(name)), "host");
}
private void claim(FeatureDescriptor<?> descriptor) {
validateClaim(descriptor);
private void claim(FeatureDescriptor<?> descriptor, DiscoveredModule owner) {
validateClaim(descriptor, owner);
recordClaim(descriptor);
}
private void validateClaim(FeatureDescriptor<?> descriptor) {
private void validateClaim(FeatureDescriptor<?> descriptor, DiscoveredModule owner) {
if (featureTypes.contains(descriptor.type()) || featureIds.contains(descriptor.id())) {
throw new IllegalArgumentException("Duplicate feature: " + descriptor.id());
}
descriptor.alias().ifPresent(alias -> validateAlias(descriptor, alias, owner));
}
private void validateAlias(FeatureDescriptor<?> descriptor, String alias, DiscoveredModule owner) {
if (owner.source() == DiscoveredModule.Source.PACK) {
throw new IllegalArgumentException("Settings " + descriptor.type().getName() + " of module " + owner
+ " set alias '" + alias + "'; only modules that ship with the host may set one, so remove it:"
+ " packs write these settings under their id \"" + descriptor.key() + "\"");
}
for (var target : descriptor.attachment().targets()) {
var field = new Field(target, descriptor.attachment().field());
var field = new Field(target, alias);
if (fields.containsKey(field)) {
throw new IllegalArgumentException(
"JSON field collision at " + field + ": " + fields.get(field));
throw new IllegalArgumentException("Alias collision at " + field + " of " + descriptor.id()
+ ": " + fields.get(field));
}
}
}
@@ -167,10 +188,11 @@ public final class ModuleRegistry implements FeatureRegistry {
private void recordClaim(FeatureDescriptor<?> descriptor) {
featureTypes.add(descriptor.type());
featureIds.add(descriptor.id());
for (var target : descriptor.attachment().targets()) {
var field = new Field(target, descriptor.attachment().field());
fields.put(field, descriptor.id().toString());
}
descriptor.alias().ifPresent(alias -> {
for (var target : descriptor.attachment().targets()) {
fields.put(new Field(target, alias), descriptor.id().toString());
}
});
}
private void checkOpen() {
@@ -17,10 +17,13 @@ import java.util.stream.Stream;
/** Describes a loaded pack's catalogued settings for studio. Fails the load, naming the class, field
* and module, on settings the host could not render: an unsupported field type, a misplaced
* {@code @Ref}, a class without a usable no-argument constructor or a snippet name used twice.
* {@code @Ref}, a class without a usable no-argument constructor, a snippet name used twice or a pack
* class's snippet name outside its module's path.
*/
final class PackSchemaBuilder {
private static final Pattern SNIPPET_NAME = Pattern.compile("[a-z0-9_-]+");
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 = new TypeDrafts();
@@ -47,8 +50,8 @@ final class PackSchemaBuilder {
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.attachment().field(), descriptor.attachment().targets(), types.get(descriptor.type().getName()));
return new FeatureSchema(descriptor.id(), descriptor.name(), catalogued.role(), owner.info(), descriptor.key(),
descriptor.alias(), descriptor.attachment().targets(), types.get(descriptor.type().getName()));
}
}
@@ -80,16 +83,51 @@ final class PackSchemaBuilder {
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()) return;
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 name; packs write snippets under snippet/<name>/, so use lowercase"
+ " letters, digits, '-' and '_'");
+ 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) {
@@ -0,0 +1,32 @@
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<StageReach> stages) {
int blocks = 0;
var layers = new TreeMap<String, Integer>();
for (var stage : stages) {
blocks = Math.max(blocks, stage.blocks());
for (var layer : stage.mantleLayers()) {
layers.merge(layer.id(), stage.blocks(), Math::max);
}
}
return new PipelineReach(blocks, layers);
}
}
@@ -68,6 +68,11 @@ public final class ResolvedGraph {
return pairs;
}
/** The most the pipeline's stages write beyond their footprint, overall and per mantle layer. */
public PipelineReach reach() {
return PipelineReach.of(stages.stream().map(ResolvedStage::reach).toList());
}
/** Human-readable order, owners, edges, block passes and unordered pairs. */
public String describe() {
return GraphDescription.describe(this);
@@ -9,18 +9,21 @@ 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.
* references that matched no installed stage and therefore add no ordering. reach is what the stage
* declared it writes beyond its footprint.
*/
public record ResolvedStage(
Stage<?> stage,
ResourceId module,
Optional<FeatureDescriptor<?>> settings,
List<StageEdge> incoming,
List<StageRef> absentSoftTargets) {
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);
}
@@ -1,6 +1,7 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
import com.volmit.resource.ResourceId;
import com.volmit.stage.Stage;
import com.volmit.stage.StageRef;
@@ -17,6 +18,8 @@ final class StageDeclaration {
private final List<StageRef> softAfter = new ArrayList<>();
private final List<StageRef> softBefore = new ArrayList<>();
private FeatureDescriptor<?> settings;
private Integer reachBlocks;
private final List<MantleKey<?>> mantleLayers = new ArrayList<>();
private StageBody body;
StageDeclaration(Stage<?> stage, ResourceId module) {
@@ -49,6 +52,28 @@ final class StageDeclaration {
settings = FeatureDescriptor.of(settingsType);
}
void reach(int blocks) {
checkOpen();
if (reachBlocks != null) {
throw new IllegalStateException("Stage " + this + " already declares a reach of " + reachBlocks + " blocks");
}
if (blocks < 0) {
throw new IllegalArgumentException("Stage " + this + " declares a negative reach of " + blocks + " blocks");
}
reachBlocks = blocks;
}
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 the only body. alternativeMethod names the builder method for the other output kind. */
void complete(StageBody body, boolean bodyProducesOutput, String alternativeMethod) {
checkOpen();
@@ -91,6 +116,10 @@ final class StageDeclaration {
return body;
}
StageReach reach() {
return new StageReach(reachBlocks == null ? 0 : reachBlocks, mantleLayers);
}
@Override
public String toString() {
return stage.id() + " (module " + module + ")";
@@ -0,0 +1,30 @@
package com.volmit.host;
import com.volmit.mantle.MantleKey;
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 chunk stage, the X/Z bounds of the placed object
* for a placement stage. 0 means only inside it. Height is not limited: the footprint is whole
* columns.
* @param mantleLayers the mantle layers the stage writes, each once, in declaration order
*/
public record StageReach(int 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(0, List.of());
public StageReach {
if (blocks < 0) throw new IllegalArgumentException("Negative reach: " + 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");
}
}
}
}
@@ -10,7 +10,6 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -66,7 +65,6 @@ final class TypeDrafts {
var instance = instantiate(type, source);
var kinds = new ValueKinds(nested -> object(nested, source));
var options = metadata.options().stream()
.sorted(Comparator.comparing(OptionsMetadata.Option::name))
.map(option -> new OptionDraft(option, kind(option, kinds, source), defaultValue(option.field(), instance, source)))
.toList();
return new TypeDraft(type, source, metadata, options);
@@ -23,6 +23,7 @@ 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.Set;
@@ -40,6 +41,7 @@ final class ValueKinds {
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);
private final Function<Class<?>, ObjectKind> objects;
@@ -94,9 +96,16 @@ final class ValueKinds {
private static ValueKind text(TextFormat format, Reference reference) {
if (reference == null) return new TextKind(format);
if (format == TextFormat.RESOURCE_ID && PACK_REFERENCES.contains(reference)) throw packReferenceOnResourceId(reference);
return new ReferenceKind(reference, format);
}
/** Packs name their biomes, regions and objects by path without a namespace, so a ResourceId could not hold one. */
private static SettingsTypeProblem packReferenceOnResourceId(Reference reference) {
return new SettingsTypeProblem("has @Ref(" + reference + ") on ResourceId, but packs name their biomes,"
+ " regions and objects by path without a namespace, such as desert/dunes; use String");
}
private static ValueKind blockState(Reference reference) {
if (reference == null || reference == Reference.BLOCK) return new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE);
throw new SettingsTypeProblem("has @Ref(" + reference + ") on BlockState, which always names a block;"
@@ -6,23 +6,27 @@ 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 field it is attached to at each of its targets.
/** A module's settings type and the JSON keys 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 field the JSON field the settings are written under, the same at every target
* @param targets where the field appears, in {@link FeatureAttachment.Target} order
* @param settings the settings class; its description describes the field
* @param key the JSON key the settings are written under, the feature id, the same at every target
* @param alias the short JSON key a built-in module accepts instead of {@code key}; pack modules
* have none. A JSON object may use one of the two, not both.
* @param targets where the keys appear, in {@link FeatureAttachment.Target} order
* @param settings the settings class; its description describes the value
*/
public record FeatureSchema(
ResourceId id,
String name,
FeatureRole role,
ModuleInfo module,
String field,
String key,
Optional<String> alias,
Set<FeatureAttachment.Target> targets,
ObjectType settings) {
public FeatureSchema {
@@ -30,7 +34,8 @@ public record FeatureSchema(
Objects.requireNonNull(name, "name");
Objects.requireNonNull(role, "role");
Objects.requireNonNull(module, "module");
Objects.requireNonNull(field, "field");
Objects.requireNonNull(key, "key");
Objects.requireNonNull(alias, "alias");
Objects.requireNonNull(settings, "settings");
targets = Collections.unmodifiableSet(EnumSet.copyOf(targets));
}
@@ -10,7 +10,7 @@ import java.util.Optional;
* @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 name order
* @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 {
@@ -10,8 +10,8 @@ import java.util.Objects;
* 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
* by id, the features of a target by JSON field, types by name, snippets by snippet name, options by
* name and enum constants in declaration order.
* 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 types every class reachable from those settings, each once
@@ -22,12 +22,12 @@ public record PackSchema(List<FeatureSchema> features, List<ObjectType> types) {
types = types.stream().sorted(Comparator.comparing(ObjectType::name)).toList();
}
/** The module fields of one attachment target, by JSON field name. */
/** The module features of one attachment target, by JSON key. */
public List<FeatureSchema> fields(FeatureAttachment.Target target) {
Objects.requireNonNull(target, "target");
return features.stream()
.filter(feature -> feature.targets().contains(target))
.sorted(Comparator.comparing(FeatureSchema::field))
.sorted(Comparator.comparing(FeatureSchema::key))
.toList();
}
@@ -1,5 +1,7 @@
package com.volmit.stage;
import com.volmit.mantle.MantleKey;
import com.volmit.IrisFeature;
import java.util.function.Supplier;
@@ -13,6 +15,15 @@ public interface BlockStageDefinition<O> {
BlockStageDefinition<O> softBefore(StageRef... stages);
/** Declares how far, in blocks along X and Z, this stage writes blocks or mantle values beyond its
* footprint: the chunk for a chunk stage, the placed object's X/Z bounds for a placement stage. The
* host prepares that much around every chunk or placement of the pipeline. Leaving it out means 0.
*/
BlockStageDefinition<O> reach(int blocks);
/** Declares the mantle layers this stage writes; each must be registered by some module. */
BlockStageDefinition<O> writesMantle(MantleKey<?>... layers);
<S extends IrisFeature> ConditionalBlockStageDefinition<S, O> when(Class<S> settingsType);
/** Body for a block stage without accumulator. */
@@ -1,5 +1,7 @@
package com.volmit.stage;
import com.volmit.mantle.MantleKey;
import java.util.function.Supplier;
/** A block stage active only where its settings are configured; bodies receive them. */
@@ -10,6 +12,10 @@ public interface ConditionalBlockStageDefinition<S, O> {
ConditionalBlockStageDefinition<S, O> softBefore(StageRef... stages);
ConditionalBlockStageDefinition<S, O> reach(int blocks);
ConditionalBlockStageDefinition<S, O> writesMantle(MantleKey<?>... layers);
void run(SettingsAction<BlockStageContext, S> action);
void accumulate(Supplier<O> initial, SettingsBlockCollector<S, O> collector);
@@ -1,5 +1,7 @@
package com.volmit.stage;
import com.volmit.mantle.MantleKey;
/** An invocation stage active only where its settings are configured; bodies receive them. */
public interface ConditionalStageDefinition<C extends StageContext, S, O> {
ConditionalStageDefinition<C, S, O> requires(Stage<?>... stages);
@@ -8,6 +10,10 @@ public interface ConditionalStageDefinition<C extends StageContext, S, O> {
ConditionalStageDefinition<C, S, O> softBefore(StageRef... stages);
ConditionalStageDefinition<C, S, O> reach(int blocks);
ConditionalStageDefinition<C, S, O> writesMantle(MantleKey<?>... layers);
void run(SettingsAction<C, S> action);
void produce(SettingsFunction<C, S, O> function);
@@ -1,5 +1,7 @@
package com.volmit.stage;
import com.volmit.mantle.MantleKey;
import com.volmit.IrisFeature;
/** Declares one invocation stage. requires(...) is a hard dependency on another module's
@@ -14,6 +16,15 @@ public interface StageDefinition<C extends StageContext, O> {
StageDefinition<C, O> softBefore(StageRef... stages);
/** Declares how far, in blocks along X and Z, this stage writes blocks or mantle values beyond its
* footprint: the chunk for a chunk stage, the placed object's X/Z bounds for a placement stage. The
* host prepares that much around every chunk or placement of the pipeline. Leaving it out means 0.
*/
StageDefinition<C, O> reach(int blocks);
/** Declares the mantle layers this stage writes; each must be registered by some module. */
StageDefinition<C, O> writesMantle(MantleKey<?>... layers);
/** Activates the stage only where the given feature settings are configured. At least one module
* naming the type must own its feature id: the id is that module's id or starts with it and '/'.
* Other modules may name it too, such as moss conditioning on {@code iris:snow}.
@@ -11,7 +11,7 @@ import static org.junit.jupiter.api.Assertions.*;
class FeatureContractTest {
@Desc("Example settings")
@Snippet("fill-settings")
@Feature(id = "example:fill", name = "Fill", field = "fill", targets = FeatureAttachment.Target.BIOME)
@Feature(id = "example:fill", name = "Fill", alias = "fill", targets = FeatureAttachment.Target.BIOME)
public static class FillOptions implements IrisFeature {
@Desc("Replacement value")
@MinNumber(0)
@@ -39,7 +39,8 @@ class FeatureContractTest {
void descriptorReadsFeatureIdentityAndAttachment() {
var descriptor = FeatureDescriptor.of(FillOptions.class);
assertEquals(ResourceId.parse("example:fill"), descriptor.id());
assertEquals("fill", descriptor.attachment().field());
assertEquals("example:fill", descriptor.key());
assertEquals(java.util.Optional.of("fill"), descriptor.alias());
assertEquals(java.util.Set.of(FeatureAttachment.Target.BIOME), descriptor.attachment().targets());
assertEquals(1, descriptor.options().options().size());
}
@@ -7,7 +7,7 @@ import com.volmit.config.Desc;
import com.volmit.config.Feature;
@Desc("Covers the top of every terrain column")
@Feature(id = "example:grass", name = "Grass", field = "grass", targets = FeatureAttachment.Target.BIOME)
@Feature(id = "example:grass", name = "Grass", targets = FeatureAttachment.Target.BIOME)
public final class GrassSettings implements IrisFeature {
@Desc("Block placed on top of each column")
private BlockState block = new BlockState("minecraft:grass_block");
@@ -5,7 +5,7 @@ import com.volmit.IrisFeature;
import com.volmit.config.Feature;
import com.volmit.config.MinNumber;
@Feature(id = "example:moss", name = "Moss", field = "moss", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
@Feature(id = "example:moss", name = "Moss", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
public final class MossSettings implements IrisFeature {
@MinNumber(0)
private int radius;
@@ -6,7 +6,7 @@ import com.volmit.config.Feature;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
@Feature(id = "iris:snow", name = "Snow", field = "snow", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
@Feature(id = "iris:snow", name = "Snow", alias = "snow", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
public final class SnowSettings implements IrisFeature {
@MinNumber(1)
@MaxNumber(8)
@@ -7,7 +7,7 @@ import com.volmit.config.Feature;
import com.volmit.config.MinNumber;
@Desc("Fills the space below an object down to the ground")
@Feature(id = "iris:stilt", name = "Stilt", field = "stilt", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
@Feature(id = "iris:stilt", name = "Stilt", alias = "stilt", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
public final class StiltSettings implements IrisFeature {
@Desc("Maximum blocks filled below each lowest object block")
@MinNumber(1)
@@ -16,16 +16,16 @@ import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.*;
class ModuleRegistryTest {
@Feature(id = "test:core/one", name = "One", field = "shared", targets = FeatureAttachment.Target.BIOME)
@Feature(id = "test:core/one", name = "One", alias = "shared", targets = FeatureAttachment.Target.BIOME)
static class One implements IrisFeature {}
@Feature(id = "test:core/two", name = "Two", field = "shared", targets = FeatureAttachment.Target.DIMENSION)
@Feature(id = "test:core/two", name = "Two", alias = "shared", targets = FeatureAttachment.Target.DIMENSION)
static class Two implements IrisFeature {}
@Feature(id = "test:core/collision", name = "Collision", field = "shared", targets = {FeatureAttachment.Target.DIMENSION, FeatureAttachment.Target.BIOME})
@Feature(id = "test:core/collision", name = "Collision", alias = "shared", targets = {FeatureAttachment.Target.DIMENSION, FeatureAttachment.Target.BIOME})
static class Collision implements IrisFeature {}
@Feature(id = "test:core/one", name = "Duplicate", field = "different", targets = FeatureAttachment.Target.REGION)
@Feature(id = "test:core/one", name = "Duplicate", alias = "different", targets = FeatureAttachment.Target.REGION)
static class Duplicate implements IrisFeature {}
static class MissingAnnotation implements IrisFeature {}
@Feature(id = "test:core/abstract", name = "Abstract", field = "abstract", targets = FeatureAttachment.Target.BIOME)
@Feature(id = "test:core/abstract", name = "Abstract", alias = "abstract", targets = FeatureAttachment.Target.BIOME)
abstract static class AbstractFeature implements IrisFeature {}
/** Runs {@code registrations} as the register(...) of a built-in module with the given id. */
@@ -40,7 +40,7 @@ class ModuleRegistryTest {
@Test
void validatesIdsTypesAndFieldsAcrossFeatureKindsWithoutPartialRegistration() {
var registry = new ModuleRegistry();
registry.registerStageSettings(One.class);
registerAs(registry, "test:core", settings -> settings.registerSettings(One.class));
registry.registerStageSettings(One.class);
registerAs(registry, "test:core", objects -> {
assertThrows(IllegalArgumentException.class, () -> objects.registerObject(Collision.class, ignored -> context -> null));
@@ -56,7 +56,10 @@ class ModuleRegistryTest {
@Test
void reservesHostFieldsAndRejectsInvalidFeaturesOrFactories() {
var registry = new ModuleRegistry(Map.of(FeatureAttachment.Target.BIOME, Set.of("shared")));
assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(One.class));
assertThrows(IllegalStateException.class, () -> registry.registerStageSettings(One.class), "no module owns it yet");
registerAs(registry, "test:core", nothing -> {});
var reserved = assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(One.class));
assertTrue(reserved.getMessage().startsWith("Alias collision"), reserved.getMessage());
assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(MissingAnnotation.class));
assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(AbstractFeature.class));
registerAs(registry, "test:core", objects -> {
@@ -160,7 +163,7 @@ class ModuleRegistryTest {
registerAs(registry, "test:core", settings -> settings.registerObject(Two.class, ignored -> context -> null));
var collision = assertThrows(IllegalArgumentException.class,
() -> registerAs(registry, "test:core", settings -> settings.registerSettings(Collision.class)));
assertTrue(collision.getMessage().startsWith("JSON field collision"), collision.getMessage());
assertTrue(collision.getMessage().startsWith("Alias collision"), collision.getMessage());
assertTrue(registry.freeze().settings().isEmpty());
}
+105 -26
View File
@@ -69,7 +69,7 @@ class PackSchemaTest {
import java.util.*;
@Desc("Plants flowers and bushes")
@Feature(id = "example:flora", name = "Flora", field = "flora", targets = {Target.REGION, Target.BIOME})
@Feature(id = "example:flora", name = "Flora", targets = {Target.REGION, Target.BIOME})
public final class FloraSettings implements IrisFeature {
@Desc("Plants per chunk") @Required @MinNumber(0) @MaxNumber(64)
private int density = 4;
@@ -114,7 +114,7 @@ class PackSchemaTest {
import com.volmit.config.*;
@Desc("A patch of plants")
@Snippet("flora-patch")
@Snippet("example/flora/patch")
final class Patch {
@MinNumber(1)
private int radius = 3;
@@ -131,7 +131,7 @@ class PackSchemaTest {
import com.volmit.IrisFeature;
import com.volmit.config.*;
@Feature(id = "example:flora/wind", name = "Wind", field = "wind", targets = Target.DIMENSION)
@Feature(id = "example:flora/wind", name = "Wind", targets = Target.DIMENSION)
public final class WindSettings implements IrisFeature {
@Desc("How far plants sway")
private double strength = 1.5;
@@ -145,8 +145,8 @@ class PackSchemaTest {
import com.volmit.IrisFeature;
import com.volmit.config.*;
@Snippet("bush")
@Feature(id = "example:flora/bush", name = "Bush", field = "bush", targets = Target.OBJECT_PLACEMENT)
@Snippet("example/flora/bush")
@Feature(id = "example:flora/bush", name = "Bush", targets = Target.OBJECT_PLACEMENT)
public final class BushSettings implements IrisFeature {
private int height = 2;
}
@@ -190,13 +190,14 @@ class PackSchemaTest {
}
@Test
void attachesEveryModuleFieldToItsTargets() {
void attachesEveryModuleFeatureToItsTargetsUnderItsId() {
var schema = floraSchema();
assertEquals(List.of("flora"), names(schema.fields(Target.BIOME), FeatureSchema::field));
assertEquals(List.of("flora"), names(schema.fields(Target.REGION), FeatureSchema::field));
assertEquals(List.of("wind"), names(schema.fields(Target.DIMENSION), FeatureSchema::field));
assertEquals(List.of("bush"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::field));
assertEquals(List.of("example:flora"), names(schema.fields(Target.BIOME), FeatureSchema::key));
assertEquals(List.of("example:flora"), names(schema.fields(Target.REGION), FeatureSchema::key));
assertEquals(List.of("example:flora/wind"), names(schema.fields(Target.DIMENSION), FeatureSchema::key));
assertEquals(List.of("example:flora/bush"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::key));
assertTrue(schema.features().stream().allMatch(feature -> feature.alias().isEmpty()), "pack modules have no alias");
assertEquals(List.of("example:flora", "example:flora/bush", "example:flora/wind"), names(schema.features(), FeatureSchema::id));
var flora = schema.features().getFirst();
@@ -211,11 +212,11 @@ class PackSchemaTest {
}
@Test
void describesOptionsInNameOrderWithChecksAndDefaults() {
void describesOptionsInDeclarationOrderWithChecksAndDefaults() {
var settings = floraSchema().type("pack.flora.FloraSettings");
assertEquals(List.of("biomes", "chance", "density", "drops", "enabled", "extra", "flower", "ground", "label",
"palette", "patch", "season", "seasons", "seedOffset", "spread", "weights"),
assertEquals(List.of("density", "chance", "spread", "seedOffset", "enabled", "label", "palette", "ground", "biomes",
"drops", "flower", "season", "seasons", "weights", "patch", "extra"),
settings.options().stream().map(SchemaOption::name).toList());
assertEquals(new SchemaOption("density", new IntegerKind(), "Plants per chunk", true,
OptionalDouble.of(0), OptionalDouble.of(64), Optional.of(4L)), option(settings, "density"));
@@ -273,7 +274,7 @@ class PackSchemaTest {
assertEquals(Optional.of(Map.of("bloom", "SUMMER", "radius", 3L)), option(settings, "patch").defaultValue(),
"an object default holds the options that have one");
assertEquals("A patch of plants", patch.description());
assertEquals(List.of("bloom", "child", "radius"), patch.options().stream().map(SchemaOption::name).toList());
assertEquals(List.of("radius", "bloom", "child"), patch.options().stream().map(SchemaOption::name).toList());
assertEquals(new ObjectKind("pack.flora.Patch"), option(patch, "child").kind());
assertEquals("A smaller patch inside this one", option(patch, "child").description());
assertEquals(OptionalDouble.of(1), option(patch, "radius").minimum());
@@ -283,7 +284,7 @@ class PackSchemaTest {
void listsSnippetsObjectGeneratorsAndExplicitlyRegisteredSettings() {
var schema = floraSchema();
assertEquals(List.of("bush", "flora-patch"), schema.snippets().stream().map(type -> type.snippet().orElseThrow()).toList());
assertEquals(List.of("example/flora/bush", "example/flora/patch"), schema.snippets().stream().map(type -> type.snippet().orElseThrow()).toList());
assertEquals(List.of("pack.flora.BushSettings", "pack.flora.Patch"), schema.snippets().stream().map(ObjectType::name).toList());
var bush = schema.objectGenerators().getFirst();
@@ -322,7 +323,9 @@ class PackSchemaTest {
var schema = schemaOf(pack("empty"), ModuleHost.of(builtIns));
assertEquals(List.of("example:grass", "example:moss", "iris:snow", "iris:stilt"), names(schema.features(), FeatureSchema::id));
assertEquals(List.of("moss", "snow", "stilt"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::field));
assertEquals(List.of("example:moss", "iris:snow", "iris:stilt"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::key));
assertEquals(List.of("", "snow", "stilt"), names(schema.fields(Target.OBJECT_PLACEMENT), feature -> feature.alias().orElse("")),
"built-ins keep their short aliases");
var stilt = schema.fields(Target.OBJECT_PLACEMENT).get(2);
assertEquals("Stilts", stilt.module().name());
@@ -349,7 +352,7 @@ class PackSchemaTest {
import com.volmit.resource.*;
import java.util.*;
@Feature(id = "example:flora", name = "Flora", field = "flora", targets = Target.BIOME)
@Feature(id = "example:flora", name = "Flora", targets = Target.BIOME)
public final class FloraSettings implements IrisFeature {
%s
}
@@ -379,7 +382,7 @@ class PackSchemaTest {
import com.volmit.config.Feature;
import java.util.*;
@Feature(id = "example:flora", name = "Flora", field = "flora", targets = Target.BIOME)
@Feature(id = "example:flora", name = "Flora", targets = Target.BIOME)
public final class FloraSettings implements IrisFeature {
private Node node = new Node();
private double ratio = Double.NaN;
@@ -449,14 +452,90 @@ class PackSchemaTest {
}
@Test
void snippetNamesAreFolderNamesThatBelongToOneClass() {
assertLoadFails("Snippet name 'Big Patch' of pack.flora.Patch of " + FLORA_SOURCE + " is not a folder name; packs write snippets under"
+ " snippet/<name>/, so use lowercase letters, digits, '-' and '_'",
"private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"Big Patch\") final class Patch {}");
assertLoadFails("Snippet name 'patch' is used by pack.flora.Patch of " + FLORA_SOURCE + " and by pack.flora.Plot of " + FLORA_SOURCE
+ "; studio describes snippet/patch/ by one class, so give each its own name",
void snippetNamesAreFolderPathsThatBelongToOneClass() {
var notAPath = "is not a folder path; packs write snippets under snippet/<name>/, so use lowercase letters, digits, '-', '_'"
+ " and '.', with '/' between folders";
assertLoadFails("Snippet name 'example/flora/Big Patch' of pack.flora.Patch of " + FLORA_SOURCE + " " + notAPath,
"private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/Big Patch\") final class Patch {}");
assertLoadFails("Snippet name 'example/flora/../moss' of pack.flora.Patch of " + FLORA_SOURCE + " " + notAPath,
"private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/../moss\") final class Patch {}");
assertLoadFails("Snippet name 'example/flora/patch' is used by pack.flora.Patch of " + FLORA_SOURCE + " and by pack.flora.Plot of " + FLORA_SOURCE
+ "; studio describes snippet/example/flora/patch/ by one class, so give each its own name",
"private Patch patch; private Plot plot;",
"pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"patch\") final class Patch {}",
"pack.flora.Plot", "package pack.flora; @com.volmit.config.Snippet(\"patch\") final class Plot {}");
"pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/patch\") final class Patch {}",
"pack.flora.Plot", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/patch\") final class Plot {}");
}
@Test
void packSnippetsLiveUnderTheirModulesFolder() {
assertLoadFails("Snippet name 'patch' of pack.flora.Patch of " + FLORA_SOURCE + " is not under a module of the pack; snippets of pack"
+ " modules start with their module's id as a folder path, such as 'example/flora/patch' (folder snippet/example/flora/patch/)",
"private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"patch\") final class Patch {}");
assertLoadFails("Snippet name 'example/florae/patch' of pack.flora.Patch of " + FLORA_SOURCE + " is not under a module of the pack;"
+ " snippets of pack modules start with their module's id as a folder path, such as 'example/flora/patch'"
+ " (folder snippet/example/flora/patch/)",
"private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/florae/patch\") final class Patch {}");
var pack = pack("module-folder");
module("pack.flora.FloraModule", FLORA,
"public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES)
.source("pack.flora.FloraSettings", """
package pack.flora;
@com.volmit.config.Snippet("example/flora")
@com.volmit.config.Feature(id = "example:flora", name = "Flora", targets = com.volmit.FeatureAttachment.Target.BIOME)
public final class FloraSettings implements com.volmit.IrisFeature {}
""")
.writeInto(pack, "flora.jar");
assertEquals(List.of("example/flora"), schemaOf(pack, NO_BUILT_INS).snippets().stream()
.map(type -> type.snippet().orElseThrow()).toList(), "the module's own folder is under its path");
}
@Test
void packModulesCannotSetAnAlias() {
var pack = pack("alias");
module("pack.flora.FloraModule", FLORA,
"public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES)
.source("pack.flora.FloraSettings", """
package pack.flora;
@com.volmit.config.Feature(id = "example:flora", name = "Flora", alias = "flora", targets = com.volmit.FeatureAttachment.Target.BIOME)
public final class FloraSettings implements com.volmit.IrisFeature {}
""")
.writeInto(pack, "flora.jar");
var failure = assertThrows(IllegalArgumentException.class, () -> LoadedPack.load(pack, NO_BUILT_INS));
assertEquals("Settings pack.flora.FloraSettings of module example:flora from modules/flora.jar set alias 'flora'; only modules"
+ " that ship with the host may set one, so remove it: packs write these settings under their id \"example:flora\"",
failure.getMessage());
}
@Test
void packReferencesFitOnlyPlainText() {
assertLoadFails("Field pack.flora.FloraSettings.home of " + FLORA_SOURCE + " has @Ref(PACK_BIOME) on ResourceId, but packs name"
+ " their biomes, regions and objects by path without a namespace, such as desert/dunes; use String",
"@Ref(Reference.PACK_BIOME) private ResourceId home;");
assertTrue(loadFailure("@Ref(Reference.PACK_OBJECT) private List<ResourceId> objects;").getMessage()
.contains("has @Ref(PACK_OBJECT) on ResourceId"));
}
@Test
void inheritedOptionsComeBeforeTheirSubclasssOwn() {
var pack = pack("inherited");
module("pack.flora.FloraModule", FLORA,
"public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES)
.source("pack.flora.Base", "package pack.flora; abstract class Base { private int zeta; private int alpha; }")
.source("pack.flora.FloraSettings", """
package pack.flora;
@com.volmit.config.Feature(id = "example:flora", name = "Flora", targets = com.volmit.FeatureAttachment.Target.BIOME)
public final class FloraSettings extends Base implements com.volmit.IrisFeature { private int omega; private int beta; }
""")
.writeInto(pack, "flora.jar");
var settings = schemaOf(pack, NO_BUILT_INS).type("pack.flora.FloraSettings");
assertEquals(List.of("zeta", "alpha", "omega", "beta"), settings.options().stream().map(SchemaOption::name).toList());
}
}
@@ -1,12 +1,16 @@
package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.block.BlockState;
import com.volmit.config.Feature;
import com.volmit.mantle.BlockBox;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock;
import com.volmit.placement.PlacedBlock;
@@ -29,14 +33,16 @@ import com.volmit.example.placement.SnowSettings;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.*;
class StageGraphTest {
private static final BlockState STONE = new BlockState("minecraft:stone");
@Feature(id = "test:owner/toggle", name = "Toggle", field = "toggle", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
@Feature(id = "test:owner/toggle", name = "Toggle", alias = "toggle", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
static final class Toggle implements IrisFeature {}
static final class Unannotated implements IrisFeature {}
@@ -452,4 +458,77 @@ class StageGraphTest {
static final class Counter {
int count;
}
@Test
void reachIsDeclaredPerStageAndCollectedPerPipelineAndLayer() {
var depth = new MantleKey<>("test:reach/depth", Integer.class);
var marks = new MantleKey<>("test:reach/marks", String.class);
var carve = Stage.chunk("test:reach/carve");
var mark = Stage.chunk("test:reach/mark");
var plain = Stage.chunk("test:reach/plain");
var paint = Stage.placementBlock("test:reach/paint");
var reach = module("test:reach", stages -> {
stages.define(carve).reach(24).writesMantle(depth).run(context -> {});
stages.define(mark).reach(8).writesMantle(depth, marks).run(context -> {});
stages.define(plain).run(context -> {});
stages.define(paint).reach(2).run(context -> {});
});
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(reach, depth, marks))), Map.of(), Set.of());
assertEquals(new StageReach(24, List.of(depth)), loaded.chunk().stages().getFirst().reach());
assertEquals(StageReach.NONE, loaded.chunk().stages().get(2).reach(), "an undeclared reach is 0 with no layers");
assertEquals(new PipelineReach(24, Map.of("test:reach/depth", 24, "test:reach/marks", 8)), loaded.chunk().reach());
assertEquals(new PipelineReach(2, Map.of()), loaded.placement().reach());
assertTrue(loaded.chunk().describe().contains(" reach 24 blocks, writes mantle test:reach/depth\n"), loaded.chunk().describe());
assertTrue(loaded.chunk().describe().contains(" reach 8 blocks, writes mantle test:reach/depth, test:reach/marks\n"));
}
@Test
void reachMustBeValidAndNameRegisteredLayers() {
var depth = new MantleKey<>("test:reach/depth", Integer.class);
var carve = Stage.chunk("test:reach/carve");
var negative = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK,
module("test:reach", stages -> stages.define(carve).reach(-1).run(context -> {}))));
assertEquals("Stage test:reach/carve (module test:reach) declares a negative reach of -1 blocks", negative.getMessage());
var twice = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.CHUNK,
module("test:reach", stages -> stages.define(carve).reach(1).reach(2).run(context -> {}))));
assertEquals("Stage test:reach/carve (module test:reach) already declares a reach of 1 blocks", twice.getMessage());
assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK,
module("test:reach", stages -> stages.define(carve).writesMantle(depth, depth).run(context -> {}))));
var unregistered = assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(
module("test:reach", stages -> stages.define(carve).writesMantle(depth).run(context -> {})))), Map.of(), Set.of()));
assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth, which no module registers;"
+ " its owner registers it with FeatureRegistry.registerMantle", unregistered.getMessage());
var asText = new MantleKey<>("test:reach/depth", String.class);
var mismatch = assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(
module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Map.of(), Set.of()));
assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth as java.lang.String,"
+ " but it is registered as java.lang.Integer", mismatch.getMessage());
}
/** {@code module}, also registering {@code layers}. */
private static IrisModule withMantle(IrisModule module, MantleKey<?>... layers) {
return new IrisModule() {
public ModuleInfo info() { return module.info(); }
public void install(StageGraph graph) { module.install(graph); }
public void register(FeatureRegistry registry) {
for (var layer : layers) registerLayer(registry, layer);
}
};
}
private static <T> void registerLayer(FeatureRegistry registry, MantleKey<T> layer) {
registry.registerMantle(layer, MantleLifetime.GENERATION, codec(layer));
}
private static <T> MantleCodec<T> codec(MantleKey<T> layer) {
return new MantleCodec<>() {
public int version() { return 0; }
public void write(java.io.DataOutput output, T value) {}
public T read(java.io.DataInput input, int storedVersion) { throw new UnsupportedOperationException(); }
};
}
}