Add @MinItems for list, set and array options and describe it in the pack schema

This commit is contained in:
piexel committed 2026-10-09 20:26:31 +02:00
1 parent 3c05cfea0a
commit 0f05676b7a
9 files changed
+75 -17

No files matched your search

+1 -1
View File
@@ -23,7 +23,7 @@ types that carry them and lists what the Iris adapter still owes.
| Work across chunks and mantle writes | `Stage.mantle`, `MantleStage`, `MantleStageContext`, `MantleGenerationContext`; chunk stages read the mantle only | | Work across chunks and mantle writes | `Stage.mantle`, `MantleStage`, `MantleStageContext`, `MantleGenerationContext`; chunk stages read the mantle only |
| Annotated settings | `IrisFeature`, `@Feature` (id as JSON key), config annotations, `OptionsMetadata` | | Annotated settings | `IrisFeature`, `@Feature` (id as JSON key), config annotations, `OptionsMetadata` |
| Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings`, host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` | | Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings`, host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` |
| Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@Snippet`, `@Ref`/`Reference`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` | | Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`/`Reference`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` |
| Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | | Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` |
| Block states and palettes | `BlockState`, `BlockRegistry`, `BlockPalette`, `BlockSpec` (`BlockRegistry.resolve(BlockSpec)`, `blockEntity`) | | Block states and palettes | `BlockState`, `BlockRegistry`, `BlockPalette`, `BlockSpec` (`BlockRegistry.resolve(BlockSpec)`, `blockEntity`) |
| Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | | Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` |
+1 -1
View File
@@ -615,7 +615,7 @@ never equal a feature id.
the load; only a built-in class and a pack class can collide that way. the load; only a built-in class and a pack class can collide that way.
- A `SchemaOption` per field that `OptionsMetadata` selects, which means instance fields that are - A `SchemaOption` per field that `OptionsMetadata` selects, which means instance fields that are
not transient, inherited ones included, in declaration order. Each has its name, `ValueKind`, not transient, inherited ones included, in declaration order. Each has its name, `ValueKind`,
`@Desc`, `@Required`, `@MinNumber`/`@MaxNumber` and the default value. `@Desc`, `@Required`, `@MinNumber`/`@MaxNumber`, `@MinItems` and the default value.
### Value kinds ### Value kinds
+4 -4
View File
@@ -381,8 +381,8 @@ public final class FloraSettings implements IrisFeature {
} }
``` ```
- `@Desc` on a class, field or enum constant is its description. `@Required`, `@MinNumber` and - `@Desc` on a class, field or enum constant is its description. `@Required`, `@MinNumber`, `@MaxNumber` and
`@MaxNumber` are checks for the host to render. `@MinItems` (the least length of a list, set or array) are checks for the host to render.
- Every settings class, nested ones included, needs a no-argument constructor, which may be private. - Every settings class, nested ones included, needs a no-argument constructor, which may be private.
The host creates settings with it, and the field values of that instance are the defaults studio The host creates settings with it, and the field values of that instance are the defaults studio
shows. shows.
@@ -610,7 +610,7 @@ no JSON. The host renders it and merges it with its own fields:
settings `ObjectType`. settings `ObjectType`.
- `types()`: every class reachable from module settings, once each, by name. An `ObjectType` has the - `types()`: every class reachable from module settings, once each, by name. An `ObjectType` has the
class name, description, snippet name and options. A `SchemaOption` has name, `ValueKind`, class name, description, snippet name and options. A `SchemaOption` has name, `ValueKind`,
description, required, minimum, maximum and default value. description, required, minimum, maximum, minimum item count and default value.
- `ValueKind` is sealed: `BooleanKind`, `IntegerKind`, `DecimalKind`, `TextKind(format)`, - `ValueKind` is sealed: `BooleanKind`, `IntegerKind`, `DecimalKind`, `TextKind(format)`,
`ReferenceKind(reference, format)`, `EnumKind(type, constants)`, `ListKind(element, unique)`, `ReferenceKind(reference, format)`, `EnumKind(type, constants)`, `ListKind(element, unique)`,
`MapKind(value)`, `ObjectKind(type)`, which names an entry of `types()`, `HostKind(type)`, `MapKind(value)`, `ObjectKind(type)`, which names an entry of `types()`, `HostKind(type)`,
@@ -669,7 +669,7 @@ Optional<Clock> clock = pack.catalog().service(Clock.class); // a Pro
- `Hunk<T>` is a dense local volume; `ArrayHunk<T>` is the bounds-checked reference. - `Hunk<T>` is a dense local volume; `ArrayHunk<T>` is the bounds-checked reference.
- The `mantle` package keeps namespaced typed layers, codecs, lifetimes and buffered edits. - The `mantle` package keeps namespaced typed layers, codecs, lifetimes and buffered edits.
- `IrisFeature`, `@Feature`, the config annotations (`@Desc`, `@Required`, `@MinNumber`, - `IrisFeature`, `@Feature`, the config annotations (`@Desc`, `@Required`, `@MinNumber`,
`@MaxNumber`, `@Snippet`, `@Ref`) and `OptionsMetadata` describe settings. `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`) and `OptionsMetadata` describe settings.
Invocation views and random streams expire when the invocation ends. Stage bodies are shared by Invocation views and random streams expire when the invocation ends. Stage bodies are shared by
concurrent invocations and must not keep views, streams or mutable state; what a module keeps per world lives in the concurrent invocations and must not keep views, streams or mutable state; what a module keeps per world lives in the
@@ -0,0 +1,12 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Inclusive lower bound on the length of a list, set or array option, such as a palette that needs a block. Studio
* shows it ({@code minItems}); like {@link MinNumber}, enforcement belongs to the configuration loader.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MinItems {
int value();
}
@@ -13,11 +13,11 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
options = List.copyOf(options); options = List.copyOf(options);
} }
/** One field of a settings type. {@code minimum}, {@code maximum}, {@code reference} and {@code resource} are null /** One field of a settings type. {@code minimum}, {@code maximum}, {@code minItems}, {@code reference} and
* when not declared; {@code resource} is the class of {@link ResourceRef}. * {@code resource} are null when not declared; {@code resource} is the class of {@link ResourceRef}.
*/ */
public record Option(Field field, String description, boolean required, public record Option(Field field, String description, boolean required,
Double minimum, Double maximum, Reference reference, Class<?> resource) { Double minimum, Double maximum, Integer minItems, Reference reference, Class<?> resource) {
public String name() { public String name() {
return field.getName(); return field.getName();
} }
@@ -46,6 +46,7 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
var desc = field.getAnnotation(Desc.class); var desc = field.getAnnotation(Desc.class);
var min = field.getAnnotation(MinNumber.class); var min = field.getAnnotation(MinNumber.class);
var max = field.getAnnotation(MaxNumber.class); var max = field.getAnnotation(MaxNumber.class);
var minItems = field.getAnnotation(MinItems.class);
var ref = field.getAnnotation(Ref.class); var ref = field.getAnnotation(Ref.class);
var resourceRef = field.getAnnotation(ResourceRef.class); var resourceRef = field.getAnnotation(ResourceRef.class);
if ((min != null || max != null) && !isNumeric(field.getType())) { if ((min != null || max != null) && !isNumeric(field.getType())) {
@@ -56,8 +57,13 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
|| (min != null && max != null && min.value() > max.value())) { || (min != null && max != null && min.value() > max.value())) {
throw new IllegalArgumentException("Invalid bounds for option: " + field.getName()); 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), options.add(new Option(field, desc == null ? "" : desc.value(), field.isAnnotationPresent(Required.class),
min == null ? null : min.value(), max == null ? null : max.value(), 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())); ref == null ? null : ref.value(), resourceRef == null ? null : resourceRef.value()));
} }
} }
@@ -76,6 +82,10 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
return classes; 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) { private static boolean isNumeric(Class<?> type) {
return Number.class.isAssignableFrom(type) || type == byte.class || type == short.class return Number.class.isAssignableFrom(type) || type == byte.class || type == short.class
|| type == int.class || type == long.class || type == float.class || type == double.class; || type == int.class || type == long.class || type == float.class || type == double.class;
@@ -14,6 +14,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.OptionalDouble; import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -192,7 +193,11 @@ final class PackSchemaBuilder {
private static SchemaOption schemaOption(TypeDrafts.OptionDraft draft, DefaultValues defaults) { private static SchemaOption schemaOption(TypeDrafts.OptionDraft draft, DefaultValues defaults) {
var option = draft.option(); var option = draft.option();
return new SchemaOption(option.name(), draft.kind(), option.description(), option.required(), return new SchemaOption(option.name(), draft.kind(), option.description(), option.required(),
bound(option.minimum()), bound(option.maximum()), defaults.of(draft.defaultValue(), draft.kind())); 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) { private static OptionalDouble bound(Double value) {
@@ -3,8 +3,11 @@ package com.volmit.host.schema;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.OptionalDouble; import java.util.OptionalDouble;
import java.util.OptionalInt;
/** One option of an {@link ObjectType}: a field of a settings class. /** 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 * <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, * constructor, as plain JSON-shaped Java values: {@code Boolean}, {@code Long} for integer kinds,
@@ -22,6 +25,7 @@ public record SchemaOption(
boolean required, boolean required,
OptionalDouble minimum, OptionalDouble minimum,
OptionalDouble maximum, OptionalDouble maximum,
OptionalInt minItems,
Optional<Object> defaultValue) { Optional<Object> defaultValue) {
public SchemaOption { public SchemaOption {
Objects.requireNonNull(name, "name"); Objects.requireNonNull(name, "name");
@@ -29,6 +33,7 @@ public record SchemaOption(
Objects.requireNonNull(description, "description"); Objects.requireNonNull(description, "description");
Objects.requireNonNull(minimum, "minimum"); Objects.requireNonNull(minimum, "minimum");
Objects.requireNonNull(maximum, "maximum"); Objects.requireNonNull(maximum, "maximum");
Objects.requireNonNull(minItems, "minItems");
Objects.requireNonNull(defaultValue, "defaultValue"); Objects.requireNonNull(defaultValue, "defaultValue");
} }
} }
@@ -52,6 +52,29 @@ class FeatureContractTest {
@MinNumber(0) private String value; @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 @Test
void rejectsInconsistentAnnotationBounds() { void rejectsInconsistentAnnotationBounds() {
assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(InvalidOptions.class)); assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(InvalidOptions.class));
@@ -39,6 +39,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.OptionalDouble; import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.function.Function; import java.util.function.Function;
import static com.volmit.support.TestModuleJar.displayName; import static com.volmit.support.TestModuleJar.displayName;
import static com.volmit.support.TestModuleJar.module; import static com.volmit.support.TestModuleJar.module;
@@ -90,7 +91,7 @@ class PackSchemaTest {
private ResourceId palette = ResourceId.parse("example:flora/default"); private ResourceId palette = ResourceId.parse("example:flora/default");
@Ref(Reference.BLOCK) @Ref(Reference.BLOCK)
private String ground = "minecraft:grass_block"; private String ground = "minecraft:grass_block";
@Ref(Reference.PACK_BIOME) @Ref(Reference.PACK_BIOME) @MinItems(1)
private List<String> biomes = List.of("plains", "forest"); private List<String> biomes = List.of("plains", "forest");
@Ref(Reference.ITEM) @Ref(Reference.ITEM)
private ResourceId[] drops = {}; private ResourceId[] drops = {};
@@ -227,9 +228,9 @@ class PackSchemaTest {
"drops", "flower", "season", "seasons", "weights", "patch", "extra"), "drops", "flower", "season", "seasons", "weights", "patch", "extra"),
settings.options().stream().map(SchemaOption::name).toList()); settings.options().stream().map(SchemaOption::name).toList());
assertEquals(new SchemaOption("density", new IntegerKind(), "Plants per chunk", true, assertEquals(new SchemaOption("density", new IntegerKind(), "Plants per chunk", true,
OptionalDouble.of(0), OptionalDouble.of(64), Optional.of(4L)), option(settings, "density")); OptionalDouble.of(0), OptionalDouble.of(64), OptionalInt.empty(), Optional.of(4L)), option(settings, "density"));
assertEquals(new SchemaOption("chance", new DecimalKind(), "", false, assertEquals(new SchemaOption("chance", new DecimalKind(), "", false,
OptionalDouble.empty(), OptionalDouble.empty(), Optional.of(0.25)), option(settings, "chance")); OptionalDouble.empty(), OptionalDouble.empty(), OptionalInt.empty(), Optional.of(0.25)), option(settings, "chance"));
assertEquals(Optional.of(0.1), option(settings, "spread").defaultValue(), "floats keep their own decimal form"); assertEquals(Optional.of(0.1), option(settings, "spread").defaultValue(), "floats keep their own decimal form");
assertEquals(new IntegerKind(), option(settings, "seedOffset").kind()); assertEquals(new IntegerKind(), option(settings, "seedOffset").kind());
assertEquals(Optional.empty(), option(settings, "seedOffset").defaultValue(), "a null field has no default"); assertEquals(Optional.empty(), option(settings, "seedOffset").defaultValue(), "a null field has no default");
@@ -264,6 +265,8 @@ class PackSchemaTest {
assertEquals(new ReferenceKind(Reference.BLOCK, TextFormat.PLAIN), option(settings, "ground").kind()); assertEquals(new ReferenceKind(Reference.BLOCK, TextFormat.PLAIN), option(settings, "ground").kind());
assertEquals(new ListKind(new ReferenceKind(Reference.PACK_BIOME, TextFormat.PLAIN), false), option(settings, "biomes").kind()); assertEquals(new ListKind(new ReferenceKind(Reference.PACK_BIOME, TextFormat.PLAIN), false), option(settings, "biomes").kind());
assertEquals(Optional.of(List.of("plains", "forest")), option(settings, "biomes").defaultValue()); assertEquals(Optional.of(List.of("plains", "forest")), option(settings, "biomes").defaultValue());
assertEquals(OptionalInt.of(1), option(settings, "biomes").minItems(), "@MinItems is described");
assertEquals(OptionalInt.empty(), option(settings, "drops").minItems());
assertEquals(new ListKind(new ReferenceKind(Reference.ITEM, TextFormat.RESOURCE_ID), false), option(settings, "drops").kind()); assertEquals(new ListKind(new ReferenceKind(Reference.ITEM, TextFormat.RESOURCE_ID), false), option(settings, "drops").kind());
assertEquals(new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE), option(settings, "flower").kind(), assertEquals(new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE), option(settings, "flower").kind(),
"BlockState names a block without @Ref"); "BlockState names a block without @Ref");
@@ -304,7 +307,7 @@ class PackSchemaTest {
assertEquals(FeatureRole.SETTINGS, wind.role()); assertEquals(FeatureRole.SETTINGS, wind.role());
assertEquals("example:flora/wind", wind.id().toString()); assertEquals("example:flora/wind", wind.id().toString());
assertEquals(new SchemaOption("strength", new DecimalKind(), "How far plants sway", false, assertEquals(new SchemaOption("strength", new DecimalKind(), "How far plants sway", false,
OptionalDouble.empty(), OptionalDouble.empty(), Optional.of(1.5)), option(wind.settings(), "strength")); OptionalDouble.empty(), OptionalDouble.empty(), OptionalInt.empty(), Optional.of(1.5)), option(wind.settings(), "strength"));
} }
@Test @Test
@@ -337,11 +340,11 @@ class PackSchemaTest {
assertEquals("Stilts", stilt.module().name()); assertEquals("Stilts", stilt.module().name());
assertEquals(new ObjectType("com.volmit.example.placement.StiltSettings", "Fills the space below an object down to the ground", assertEquals(new ObjectType("com.volmit.example.placement.StiltSettings", "Fills the space below an object down to the ground",
Optional.empty(), List.of(new SchemaOption("maxDepth", new IntegerKind(), "Maximum blocks filled below each lowest object block", Optional.empty(), List.of(new SchemaOption("maxDepth", new IntegerKind(), "Maximum blocks filled below each lowest object block",
false, OptionalDouble.of(1), OptionalDouble.empty(), Optional.of(16L)))), stilt.settings()); false, OptionalDouble.of(1), OptionalDouble.empty(), OptionalInt.empty(), Optional.of(16L)))), stilt.settings());
var grass = schema.fields(Target.BIOME).getFirst(); var grass = schema.fields(Target.BIOME).getFirst();
assertEquals(new SchemaOption("block", new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE), "Block placed on top of each column", assertEquals(new SchemaOption("block", new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE), "Block placed on top of each column",
false, OptionalDouble.empty(), OptionalDouble.empty(), Optional.of("minecraft:grass_block")), grass.settings().options().getFirst()); false, OptionalDouble.empty(), OptionalDouble.empty(), OptionalInt.empty(), Optional.of("minecraft:grass_block")), grass.settings().options().getFirst());
} }
@Test @Test
@@ -674,7 +677,7 @@ class PackSchemaTest {
var keep = schema.type("pack.castle.Keep"); var keep = schema.type("pack.castle.Keep");
assertEquals("A keep of a castle", keep.description()); assertEquals("A keep of a castle", keep.description());
assertEquals(new SchemaOption("towers", new IntegerKind(), "Towers on the walls", false, OptionalDouble.of(1), assertEquals(new SchemaOption("towers", new IntegerKind(), "Towers on the walls", false, OptionalDouble.of(1),
OptionalDouble.empty(), Optional.of(4L)), keep.options().getFirst()); OptionalDouble.empty(), OptionalInt.empty(), Optional.of(4L)), keep.options().getFirst());
assertEquals(new ResourceReferenceKind(keepKind), keep.options().get(1).kind(), "a resource may name others of its kind"); assertEquals(new ResourceReferenceKind(keepKind), keep.options().get(1).kind(), "a resource may name others of its kind");
var keeps = schema.fields(Target.BIOME).getFirst().settings().options().getFirst(); var keeps = schema.fields(Target.BIOME).getFirst().settings().options().getFirst();
assertEquals(new ListKind(new ResourceReferenceKind(keepKind), false), keeps.kind()); assertEquals(new ListKind(new ResourceReferenceKind(keepKind), false), keeps.kind());