Baseline IrisApi draft before stage-graph redesign

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

No files matched your search

@@ -0,0 +1,16 @@
package com.volmit;
import java.util.Objects;
import java.util.Set;
/** Maps settings to an ordinary existing JSON field, without an extension wrapper. */
public record FeatureAttachment(String field, Set<Target> targets) {
public enum Target { DIMENSION, REGION, BIOME, OBJECT_PLACEMENT }
public FeatureAttachment {
Objects.requireNonNull(field, "field");
if (field.isBlank()) throw new IllegalArgumentException("Field must not be blank");
targets = Set.copyOf(targets);
if (targets.isEmpty()) throw new IllegalArgumentException("At least one target is required");
}
}
@@ -0,0 +1,30 @@
package com.volmit;
import com.volmit.generation.ModifierFactory;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.placement.PlacementModifierFactory;
/** Host implementation collects registrations before loading pack configuration.
* Feature IDs must be unique. JSON fields must be unique per attachment target.
* Modifiers own their IDs and dependency declarations, independently of feature IDs.
* All configured instances of a modifier follow the same ordering.
*/
public interface FeatureRegistry {
/** Registers a layer before pack loading. Null arguments throw NullPointerException;
* duplicate IDs and negative codec versions throw IllegalArgumentException.
* Only the owner registers a shared layer; consumers refer to its key. The host must
* preserve unknown persisted layers or fail explicitly, never silently discard them.
* GENERATION layers also require codecs.
*/
<T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, MantleCodec<T> codec);
<F extends IrisFeature, T> void register(Class<F> featureType,
Class<T> outputType, ModifierFactory<F, T> factory);
<F extends IrisFeature> void registerObject(Class<F> featureType, ObjectGeneratorFactory<F> factory);
<F extends IrisFeature> void registerPlacement(Class<F> featureType, PlacementModifierFactory<F> factory);
}
@@ -0,0 +1,6 @@
package com.volmit;
/** A configured feature instance. @Feature declares identity and attachment;
* annotated fields define settings. Each configuration occurrence is decoded separately.
*/
public interface IrisFeature {}
+10
View File
@@ -0,0 +1,10 @@
package com.volmit;
public interface IrisModule {
String name();
String displayVersion();
/** Called during registration, before settings are decoded or generation starts. */
void register(FeatureRegistry registry);
}
@@ -0,0 +1,3 @@
package com.volmit.block;
public enum BlockFace { UP, DOWN, NORTH, SOUTH, EAST, WEST }
@@ -0,0 +1,11 @@
package com.volmit.block;
import java.util.random.RandomGenerator;
/** Resolved, immutable palette. Coordinates are world blocks; selection uses only this RNG.
* An empty/unresolvable palette is a pack-load error. Implementations must support concurrent calls.
*/
@FunctionalInterface
public interface BlockPalette {
BlockState select(int worldX, int worldY, int worldZ, RandomGenerator random);
}
@@ -0,0 +1,16 @@
package com.volmit.block;
import com.volmit.resource.ResourceId;
/** Host adapter for resolved states and cached behavior. No native platform objects escape.
* Unknown materials, unsupported properties, and malformed states throw IllegalArgumentException.
* Methods are safe for concurrent generation calls; predicates must not read the live world.
*/
public interface BlockRegistry {
BlockState resolve(String key);
default BlockState resolve(BlockState state) { return resolve(state.key()); }
boolean hasTrait(BlockState state, BlockTrait trait);
boolean inTag(BlockState state, ResourceId tag);
/** Whether state can attach to the specified face of support, ignoring other neighbors. */
boolean canAttach(BlockState state, BlockState support, BlockFace face);
}
@@ -0,0 +1,43 @@
package com.volmit.block;
import com.volmit.resource.ResourceId;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;
/** Immutable, platform-neutral block description with value equality.
* Construction validates syntax, not platform availability or valid material properties.
* Resolve through BlockRegistry before writing. Custom-content IDs are allowed.
*/
public record BlockState(ResourceId material, Map<String, String> properties) {
public BlockState {
Objects.requireNonNull(material, "material");
var copy = new TreeMap<String, String>();
properties.forEach((name, value) -> {
if (name == null || value == null) throw new NullPointerException("Block property");
if (!name.matches("[a-z0-9_]+") || !value.matches("[a-z0-9_.-]+")) {
throw new IllegalArgumentException("Invalid block property: " + name + "=" + value);
}
copy.put(name, value);
});
properties = Collections.unmodifiableMap(copy);
}
public BlockState(String material) { this(ResourceId.parse(material), Map.of()); }
public BlockState withProperty(String name, String value) {
var changed = new TreeMap<>(properties);
changed.put(name, value);
return new BlockState(material, changed);
}
/** Stable representation with properties in lexical order. */
public String key() {
if (properties.isEmpty()) return material.toString();
return material + properties.entrySet().stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining(",", "[", "]"));
}
}
@@ -0,0 +1,7 @@
package com.volmit.block;
/** Host-defined block behavior; tags provide extensible material groups. */
public enum BlockTrait {
AIR, SOLID, OCCLUDING, FLUID, WATER, GRAVITY, FOLIAGE, DECORATION,
LOG, LEAVES, ORE, INVENTORY, BLOCK_ENTITY, CUSTOM, NEEDS_UPDATE
}
+10
View File
@@ -0,0 +1,10 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Human-readable documentation for a settings type or field. */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface Desc {
String value();
}
@@ -0,0 +1,13 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Identity and JSON attachment for an IrisFeature configuration class. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Feature {
String id();
String name();
String field();
com.volmit.FeatureAttachment.Target[] targets();
}
@@ -0,0 +1,26 @@
package com.volmit.config;
import com.volmit.FeatureAttachment;
import com.volmit.IrisFeature;
import com.volmit.resource.ResourceId;
import java.util.List;
/** Invocation-scoped lookup of applicable settings by attachment and world position.
* Results are immutable lists in pack declaration order, after the host applies inheritance
* rules. Targets remain separate: this interface never silently merges dimension/region/biome
* values. OBJECT_PLACEMENT is read from the current placement, or returns an empty list.
* Values must be treated as read-only. Bounds and lifetime match the invocation's sampler.
*/
public interface FeatureSettings {
<F extends IrisFeature> List<Entry<F>> at(Class<F> featureType, FeatureAttachment.Target target,
int worldX, int worldY, int worldZ);
/** source identifies the configuration owner; occurrence is unique within the pack snapshot. */
record Entry<F extends IrisFeature>(ResourceId source, ResourceId occurrence, F value) {
public Entry {
java.util.Objects.requireNonNull(source, "source");
java.util.Objects.requireNonNull(occurrence, "occurrence");
java.util.Objects.requireNonNull(value, "value");
}
}
}
@@ -0,0 +1,10 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Inclusive numeric upper bound. Enforcement belongs to the configuration loader. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MaxNumber {
double value();
}
@@ -0,0 +1,10 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Inclusive numeric lower bound. Enforcement belongs to the configuration loader. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MinNumber {
double value();
}
@@ -0,0 +1,60 @@
package com.volmit.config;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
/** Annotation metadata, independent of JSON libraries. Does not decode or validate values. */
public record OptionsMetadata(String description, String snippet, List<Option> options) {
public OptionsMetadata {
options = List.copyOf(options);
}
public record Option(String name, Type type, String description,
boolean required, Double minimum, Double maximum) {}
/** Reads private and inherited fields without constructing settings or accessing values.
* 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()) {
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);
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());
}
options.add(new Option(field.getName(), field.getGenericType(),
desc == null ? "" : desc.value(), field.isAnnotationPresent(Required.class),
min == null ? null : min.value(), max == null ? null : max.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);
}
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,8 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Declares that a field must be supplied in configuration. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Required {}
@@ -0,0 +1,10 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Identifies a reusable settings snippet. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Snippet {
String value();
}
@@ -0,0 +1,52 @@
package com.volmit.generation;
import java.util.HashSet;
import java.util.Set;
import com.volmit.resource.ResourceId;
/** Immutable ordering declarations referencing modifier IDs, not feature IDs.
* Requirements must exist and finish first. Optional constraints apply only when present.
* Nothing here activates a feature. The host resolves and validates the graph at pack load.
*/
public record Dependencies(Set<String> required, Set<String> after, Set<String> before) {
public Dependencies {
required = validatedCopy(required);
after = validatedCopy(after);
before = validatedCopy(before);
}
public static Dependencies none() {
return new Dependencies(Set.of(), Set.of(), Set.of());
}
public static Dependencies requires(String... ids) {
return none().andRequires(ids);
}
/** Adds required predecessors without changing this declaration. */
public Dependencies andRequires(String... ids) {
return new Dependencies(adding(required, ids), after, before);
}
public Dependencies afterIfPresent(String... ids) {
return new Dependencies(required, adding(after, ids), before);
}
public Dependencies beforeIfPresent(String... ids) {
return new Dependencies(required, after, adding(before, ids));
}
private static Set<String> adding(Set<String> existing, String[] ids) {
var result = new HashSet<>(existing);
for (String id : ids) result.add(id);
return result;
}
private static Set<String> validatedCopy(Set<String> ids) {
var copy = Set.copyOf(ids);
for (String id : copy) {
ResourceId.parse(id);
}
return copy;
}
}
@@ -0,0 +1,19 @@
package com.volmit.generation;
import com.volmit.mantle.Mantle;
import com.volmit.config.FeatureSettings;
import com.volmit.world.TerrainSampler;
/** Per-invocation state. Must not be retained by a modifier after execution. */
public interface GenerationContext extends InvocationContext {
/** World block coordinates corresponding to local volume coordinates (0, 0, 0). */
int originX();
int originY();
int originZ();
TerrainSampler terrain();
FeatureSettings settings();
/** Non-null mantle access scoped to this invocation; the host owns its lifetime. */
Mantle mantle();
}
@@ -0,0 +1,34 @@
package com.volmit.generation;
import com.volmit.hunk.Hunk;
/** Bound to one configured feature instance.
* Calls may occur concurrently for different volumes. Keep settings read-only and temporary
* state local to modify(). Exceptions propagate: the host must not publish partial output.
*/
public abstract class GenerationModifier<T> {
/** Stable, nonblank namespaced modifier identity, independent of feature identity.
* Configured instances of the same modifier share this ID and dependency declaration.
* Different modifier implementations must not claim the same ID.
*/
public abstract String id();
/** Stable requirements read at pack load, not per invocation. Constructors must not
* depend on prerequisite modifiers having run. Ordering does not guarantee that
* a prerequisite changed blocks at the current location.
*/
public Dependencies depends() {
return Dependencies.none();
}
/** Nonnegative horizontal reach in blocks beyond the output footprint; zero by default.
* Read once per configured instance at pack load. The host must prepare this area and
* required predecessor work before invocation, bound vertical access to the world, and
* serialize overlapping writes. It must reject negative or unsupported reach, not clip it.
*/
public int mantleRadius() {
return 0;
}
public abstract void modify(GenerationContext context, Hunk<T> output);
}
@@ -0,0 +1,14 @@
package com.volmit.generation;
import com.volmit.resource.PackResources;
import java.util.random.RandomGenerator;
/** Host-owned invocation inputs. RNG and views must not be retained or used by detached tasks.
* The host derives streams from world seed, stable feature/occurrence identity and position;
* module discovery order must not affect them. Keeping legacy random behavior is adapter work.
*/
public interface InvocationContext {
long worldSeed();
PackResources resources();
RandomGenerator random();
}
@@ -0,0 +1,9 @@
package com.volmit.generation;
import com.volmit.IrisFeature;
/** Connects a feature's decoded options to its executable modifier. */
@FunctionalInterface
public interface ModifierFactory<F extends IrisFeature, T> {
GenerationModifier<T> create(F feature);
}
@@ -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 getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getDepth() {
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,69 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.generation.GenerationContext;
import com.volmit.generation.GenerationModifier;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Pack-load snapshot of modifier identity, requirements, type and prepared reach.
* The occurrence identifies one configuration, independent of its shared ordering identity.
*/
public final class ConfiguredModifier<T> {
private final ResourceId occurrence;
private final Class<T> outputType;
private final GenerationModifier<T> modifier;
private final ResourceId id;
private final Dependencies dependencies;
private final int mantleRadius;
public ConfiguredModifier(
ResourceId occurrence,
Class<T> outputType,
GenerationModifier<T> modifier) {
this.occurrence = Objects.requireNonNull(occurrence, "occurrence");
this.outputType = Objects.requireNonNull(outputType, "outputType");
if (outputType.isPrimitive()) {
throw new IllegalArgumentException("Output requires a reference type");
}
this.modifier = Objects.requireNonNull(modifier, "modifier");
id = ResourceId.parse(modifier.id());
dependencies = Objects.requireNonNull(modifier.depends(), "dependencies");
mantleRadius = modifier.mantleRadius();
if (mantleRadius < 0) {
throw new IllegalArgumentException("Negative mantle radius: " + id);
}
}
public ResourceId occurrence() {
return occurrence;
}
public Class<T> outputType() {
return outputType;
}
public ResourceId id() {
return id;
}
public Dependencies dependencies() {
return dependencies;
}
public int mantleRadius() {
return mantleRadius;
}
public Class<?> implementationType() {
return modifier.getClass();
}
/** Host must prepare views/predecessor work and abort publication if this throws. */
public void modify(GenerationContext context, Hunk<T> output) {
modifier.modify(
Objects.requireNonNull(context, "context"),
Objects.requireNonNull(output, "output"));
}
}
@@ -0,0 +1,46 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.placement.PlacementModifier;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Pack-load placement declaration snapshot. The configured modifier must be immutable. */
public final class ConfiguredPlacementModifier {
private final ResourceId occurrence;
private final PlacementModifier modifier;
private final ResourceId id;
private final Dependencies dependencies;
private final int writeRadius;
public ConfiguredPlacementModifier(ResourceId occurrence, PlacementModifier modifier) {
this.occurrence = Objects.requireNonNull(occurrence, "occurrence");
this.modifier = Objects.requireNonNull(modifier, "modifier");
id = ResourceId.parse(modifier.id());
dependencies = Objects.requireNonNull(modifier.depends(), "dependencies");
writeRadius = modifier.writeRadius();
if (writeRadius < 0) {
throw new IllegalArgumentException("Negative placement radius: " + id);
}
}
public ResourceId occurrence() {
return occurrence;
}
public PlacementModifier modifier() {
return modifier;
}
public ResourceId id() {
return id;
}
public Dependencies dependencies() {
return dependencies;
}
public int writeRadius() {
return writeRadius;
}
}
@@ -0,0 +1,144 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
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.PriorityQueue;
import java.util.Set;
import java.util.TreeSet;
/** Host-independent ordering of one complete modifier graph. Ready IDs use lexical order,
* independent of discovery. Required IDs must exist. Optional edges apply only when present.
* Self-dependencies and cycles fail. This graph never activates features or permits parallel writes.
*/
public final class DependencyOrder {
private DependencyOrder() {}
public static List<ResourceId> resolve(Map<ResourceId, Dependencies> declarations) {
var graph = Map.copyOf(declarations);
var incomingEdges = initializeIncomingEdges(graph.keySet());
var outgoingEdges = new HashMap<ResourceId, Set<ResourceId>>();
addDeclaredEdges(graph, incomingEdges, outgoingEdges);
return topologicalOrder(graph, incomingEdges, outgoingEdges);
}
private static Map<ResourceId, Integer> initializeIncomingEdges(Set<ResourceId> ids) {
var incomingEdges = new HashMap<ResourceId, Integer>();
ids.forEach(id -> incomingEdges.put(id, 0));
return incomingEdges;
}
private static void addDeclaredEdges(
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
graph.forEach((id, dependencies) -> {
Objects.requireNonNull(dependencies, "dependencies");
addRequiredEdges(id, dependencies, graph, incomingEdges, outgoingEdges);
addOptionalEdges(id, dependencies, graph, incomingEdges, outgoingEdges);
});
}
private static void addRequiredEdges(
ResourceId id,
Dependencies dependencies,
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
for (var name : dependencies.required()) {
var predecessor = ResourceId.parse(name);
if (!graph.containsKey(predecessor)) {
throw new IllegalArgumentException(id + " requires missing modifier " + predecessor);
}
addEdge(predecessor, id, incomingEdges, outgoingEdges);
}
}
private static void addOptionalEdges(
ResourceId id,
Dependencies dependencies,
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
for (var name : dependencies.after()) {
var predecessor = ResourceId.parse(name);
rejectSelf(id, predecessor);
if (graph.containsKey(predecessor)) {
addEdge(predecessor, id, incomingEdges, outgoingEdges);
}
}
for (var name : dependencies.before()) {
var successor = ResourceId.parse(name);
rejectSelf(id, successor);
if (graph.containsKey(successor)) {
addEdge(id, successor, incomingEdges, outgoingEdges);
}
}
}
private static List<ResourceId> topologicalOrder(
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
var ready = new PriorityQueue<ResourceId>();
incomingEdges.forEach((id, count) -> {
if (count == 0) {
ready.add(id);
}
});
var ordered = new ArrayList<ResourceId>(graph.size());
while (!ready.isEmpty()) {
var id = ready.remove();
ordered.add(id);
releaseSuccessors(id, outgoingEdges, incomingEdges, ready);
}
if (ordered.size() != graph.size()) {
throw cycleException(graph.keySet(), ordered);
}
return List.copyOf(ordered);
}
private static void releaseSuccessors(
ResourceId id,
Map<ResourceId, Set<ResourceId>> outgoingEdges,
Map<ResourceId, Integer> incomingEdges,
PriorityQueue<ResourceId> ready) {
for (var successor : outgoingEdges.getOrDefault(id, Set.of())) {
int remainingEdges = incomingEdges.compute(successor, (ignored, count) -> count - 1);
if (remainingEdges == 0) {
ready.add(successor);
}
}
}
private static IllegalArgumentException cycleException(Set<ResourceId> ids, List<ResourceId> ordered) {
var unresolved = new TreeSet<>(ids);
unresolved.removeAll(ordered);
return new IllegalArgumentException("Modifier dependency cycle: " + unresolved);
}
private static void rejectSelf(ResourceId id, ResourceId other) {
if (id.equals(other)) {
throw new IllegalArgumentException("Self-dependency: " + id);
}
}
private static void addEdge(
ResourceId from,
ResourceId to,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
rejectSelf(from, to);
if (outgoingEdges.computeIfAbsent(from, ignored -> new HashSet<>()).add(to)) {
incomingEdges.compute(to, (ignored, count) -> count + 1);
}
}
}
@@ -0,0 +1,86 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Function;
/** Frozen registrations. Lists use lexical feature/layer ID order, independent of discovery.
* Factory and codec implementations must themselves obey their concurrency contracts.
*/
public final class FeatureCatalog {
private final Map<Class<?>, GenerationRegistration<?, ?>> generation;
private final Map<Class<?>, ObjectRegistration<?>> objects;
private final Map<Class<?>, PlacementRegistration<?>> placement;
private final Map<String, MantleRegistration<?>> mantle;
FeatureCatalog(
Map<Class<?>, GenerationRegistration<?, ?>> generation,
Map<Class<?>, ObjectRegistration<?>> objects,
Map<Class<?>, PlacementRegistration<?>> placement,
Map<String, MantleRegistration<?>> mantle) {
this.generation = Map.copyOf(generation);
this.objects = Map.copyOf(objects);
this.placement = Map.copyOf(placement);
this.mantle = Map.copyOf(mantle);
}
public List<GenerationRegistration<?, ?>> generation() {
return sorted(generation.values(), registration -> registration.descriptor().id());
}
public List<ObjectRegistration<?>> objects() {
return sorted(objects.values(), registration -> registration.descriptor().id());
}
public List<PlacementRegistration<?>> placement() {
return sorted(placement.values(), registration -> registration.descriptor().id());
}
public List<MantleRegistration<?>> mantle() {
return sorted(mantle.values(), registration -> registration.key().id());
}
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 and output type establish the generic pairing.
public <F extends IrisFeature, T> GenerationRegistration<F, T> generation(
Class<F> type,
Class<T> outputType) {
var registration = generation.get(type);
if (registration == null) {
throw new NoSuchElementException("No generation feature: " + type.getName());
}
if (!registration.outputType().equals(outputType)) {
throw new IllegalArgumentException("Output type mismatch: " + type.getName());
}
return (GenerationRegistration<F, T>) registration;
}
@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;
}
@SuppressWarnings("unchecked") // The registry key is the factory's feature type.
public <F extends IrisFeature> PlacementRegistration<F> placement(Class<F> type) {
var registration = placement.get(type);
if (registration == null) {
throw new NoSuchElementException("No placement feature: " + type.getName());
}
return (PlacementRegistration<F>) registration;
}
}
@@ -0,0 +1,26 @@
package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.IrisFeature;
import com.volmit.config.OptionsMetadata;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Validated registration metadata. It describes configuration, not executable ordering. */
public record FeatureDescriptor<F extends IrisFeature>(
ResourceId id,
String name,
Class<F> type,
FeatureAttachment attachment,
OptionsMetadata options) {
public FeatureDescriptor {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(name, "name");
if (name.isBlank()) {
throw new IllegalArgumentException("Blank feature name");
}
Objects.requireNonNull(type, "type");
Objects.requireNonNull(attachment, "attachment");
Objects.requireNonNull(options, "options");
}
}
@@ -0,0 +1,91 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
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.Set;
/** Immutable pack-load ordering across output types. Instances sharing a modifier ID must
* have the same implementation, output type and dependencies. Occurrence IDs must be unique.
* Instances within one identity use lexical occurrence order. Resolve once, dispatch many times.
* The host includes its built-in lifecycle steps in this graph and rejects incompatible edges.
*/
public final class GenerationPlan {
private final List<ConfiguredModifier<?>> ordered;
private GenerationPlan(List<ConfiguredModifier<?>> ordered) {
this.ordered = List.copyOf(ordered);
}
public static GenerationPlan resolve(List<? extends ConfiguredModifier<?>> modifiers) {
List<ConfiguredModifier<?>> instances = new ArrayList<>(modifiers);
var declarations = collectDeclarations(instances);
var modifierIds = DependencyOrder.resolve(declarations);
var orderedOccurrences = OccurrenceOrder.order(
modifierIds,
instances,
ConfiguredModifier::id,
ConfiguredModifier::occurrence);
return new GenerationPlan(orderedOccurrences);
}
private static Map<ResourceId, Dependencies> collectDeclarations(List<ConfiguredModifier<?>> instances) {
var representatives = new HashMap<ResourceId, ConfiguredModifier<?>>();
var occurrences = new HashSet<ResourceId>();
var declarations = new HashMap<ResourceId, Dependencies>();
for (var modifier : instances) {
checkUniqueOccurrence(modifier, occurrences);
checkCompatibleIdentity(modifier, representatives);
declarations.put(modifier.id(), modifier.dependencies());
}
return declarations;
}
private static void checkUniqueOccurrence(
ConfiguredModifier<?> modifier,
Set<ResourceId> occurrences) {
if (!occurrences.add(modifier.occurrence())) {
throw new IllegalArgumentException("Duplicate occurrence: " + modifier.occurrence());
}
}
private static void checkCompatibleIdentity(
ConfiguredModifier<?> modifier,
Map<ResourceId, ConfiguredModifier<?>> representatives) {
var previous = representatives.putIfAbsent(modifier.id(), modifier);
if (previous == null || isCompatible(previous, modifier)) {
return;
}
throw new IllegalArgumentException("Conflicting modifier identity: " + modifier.id());
}
private static boolean isCompatible(ConfiguredModifier<?> first, ConfiguredModifier<?> second) {
return first.implementationType().equals(second.implementationType())
&& first.outputType().equals(second.outputType())
&& first.dependencies().equals(second.dependencies());
}
public List<ConfiguredModifier<?>> ordered() {
return ordered;
}
/** Sequential dispatch only. Executor prepares/releases a dedicated context and typed output
* for each applicable occurrence; applicability is host-owned. Failures stop dispatch.
* This reference planner does not implement chunk scheduling, rollback or lifecycle bridging.
*/
public void execute(Executor executor) {
java.util.Objects.requireNonNull(executor, "executor");
for (var modifier : ordered) {
executor.execute(modifier);
}
}
public interface Executor {
<T> void execute(ConfiguredModifier<T> modifier);
}
}
@@ -0,0 +1,25 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.generation.ModifierFactory;
import com.volmit.resource.ResourceId;
import java.util.Objects;
public record GenerationRegistration<F extends IrisFeature, T>(
FeatureDescriptor<F> descriptor,
Class<T> outputType,
ModifierFactory<F, T> factory) {
public GenerationRegistration {
Objects.requireNonNull(descriptor, "descriptor");
Objects.requireNonNull(outputType, "outputType");
if (outputType.isPrimitive()) {
throw new IllegalArgumentException("Output requires a reference type");
}
Objects.requireNonNull(factory, "factory");
}
public ConfiguredModifier<T> configure(ResourceId occurrence, F feature) {
var configuredFeature = descriptor.type().cast(Objects.requireNonNull(feature, "feature"));
return new ConfiguredModifier<>(occurrence, outputType, factory.create(configuredFeature));
}
}
@@ -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,180 @@
package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.config.Feature;
import com.volmit.config.OptionsMetadata;
import com.volmit.generation.ModifierFactory;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.placement.PlacementModifierFactory;
import com.volmit.resource.ResourceId;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
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. 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.
*/
public final class ModuleRegistry implements FeatureRegistry {
private final Map<Class<?>, GenerationRegistration<?, ?>> generation = new HashMap<>();
private final Map<Class<?>, ObjectRegistration<?>> objects = new HashMap<>();
private final Map<Class<?>, PlacementRegistration<?>> placement = 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 Map<Field, String> fields = new HashMap<>();
private FeatureCatalog catalog;
public ModuleRegistry() {
this(Map.of());
}
public ModuleRegistry(Map<FeatureAttachment.Target, Set<String>> reservedFields) {
reserveHostFields(reservedFields);
}
@Override
public <F extends IrisFeature, T> void register(
Class<F> featureType,
Class<T> outputType,
ModifierFactory<F, T> factory) {
var descriptor = describe(featureType);
var registration = new GenerationRegistration<>(descriptor, outputType, factory);
claim(descriptor);
generation.put(featureType, registration);
}
@Override
public <F extends IrisFeature> void registerObject(
Class<F> featureType,
ObjectGeneratorFactory<F> factory) {
var descriptor = describe(featureType);
var registration = new ObjectRegistration<>(descriptor, factory);
claim(descriptor);
objects.put(featureType, registration);
}
@Override
public <F extends IrisFeature> void registerPlacement(
Class<F> featureType,
PlacementModifierFactory<F> factory) {
var descriptor = describe(featureType);
if (!isPlacementFeature(descriptor)) {
throw new IllegalArgumentException(
"Placement modifiers must attach only to OBJECT_PLACEMENT: " + descriptor.id());
}
var registration = new PlacementRegistration<>(descriptor, factory);
claim(descriptor);
placement.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");
var registration = new MantleRegistration<>(key, lifetime, codec, codec.version());
if (mantle.putIfAbsent(key.id(), registration) != null) {
throw new IllegalArgumentException("Duplicate mantle layer: " + key.id());
}
}
public FeatureCatalog freeze() {
if (catalog == null) {
catalog = new FeatureCatalog(generation, objects, placement, mantle);
}
return catalog;
}
private void reserveHostFields(Map<FeatureAttachment.Target, Set<String>> reservedFields) {
for (var entry : reservedFields.entrySet()) {
for (var name : entry.getValue()) {
reserveHostField(entry.getKey(), name);
}
}
}
private void reserveHostField(FeatureAttachment.Target target, String name) {
new FeatureAttachment(name, Set.of(target));
fields.put(new Field(target, name), "host");
}
private <F extends IrisFeature> FeatureDescriptor<F> describe(Class<F> type) {
checkOpen();
Objects.requireNonNull(type, "featureType");
validateFeatureType(type);
var annotation = type.getDeclaredAnnotation(Feature.class);
if (annotation == null) {
throw new IllegalArgumentException("Missing @Feature: " + type.getName());
}
return new FeatureDescriptor<>(
ResourceId.parse(annotation.id()),
annotation.name(),
type,
new FeatureAttachment(annotation.field(), Set.of(annotation.targets())),
OptionsMetadata.inspect(type));
}
private static void validateFeatureType(Class<? extends IrisFeature> type) {
if (!IrisFeature.class.isAssignableFrom(type)
|| type.isInterface()
|| Modifier.isAbstract(type.getModifiers())) {
throw new IllegalArgumentException(
"Feature type must be a concrete IrisFeature: " + type.getName());
}
}
private static boolean isPlacementFeature(FeatureDescriptor<?> descriptor) {
return descriptor.attachment().targets().equals(Set.of(FeatureAttachment.Target.OBJECT_PLACEMENT));
}
private void claim(FeatureDescriptor<?> descriptor) {
validateClaim(descriptor);
recordClaim(descriptor);
}
private void validateClaim(FeatureDescriptor<?> descriptor) {
if (featureTypes.contains(descriptor.type()) || featureIds.contains(descriptor.id())) {
throw new IllegalArgumentException("Duplicate feature: " + descriptor.id());
}
for (var target : descriptor.attachment().targets()) {
var field = new Field(target, descriptor.attachment().field());
if (fields.containsKey(field)) {
throw new IllegalArgumentException(
"JSON field collision at " + field + ": " + fields.get(field));
}
}
}
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());
}
}
private void checkOpen() {
if (catalog != null) {
throw new IllegalStateException("Registration has ended");
}
}
private record Field(FeatureAttachment.Target target, String name) {}
}
@@ -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,45 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/** Orders configured occurrences by dependency identity, then by occurrence ID. */
final class OccurrenceOrder {
private OccurrenceOrder() {}
static <T> List<T> order(
List<ResourceId> orderedIds,
List<T> occurrences,
Function<? super T, ResourceId> identity,
Function<? super T, ResourceId> occurrenceId) {
Map<ResourceId, List<T>> occurrencesByIdentity = groupByIdentity(occurrences, identity);
var ordered = new ArrayList<T>(occurrences.size());
for (var id : orderedIds) {
var group = occurrencesByIdentity.get(id);
if (group == null) {
continue;
}
group.sort((left, right) -> occurrenceId.apply(left).compareTo(occurrenceId.apply(right)));
ordered.addAll(group);
}
return List.copyOf(ordered);
}
private static <T> Map<ResourceId, List<T>> groupByIdentity(
List<T> occurrences,
Function<? super T, ResourceId> identity) {
var occurrencesByIdentity = new HashMap<ResourceId, List<T>>();
for (var occurrence : occurrences) {
occurrencesByIdentity.computeIfAbsent(identity.apply(occurrence), ignored -> new ArrayList<>())
.add(occurrence);
}
return occurrencesByIdentity;
}
}
@@ -0,0 +1,374 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.mantle.BlockBox;
import com.volmit.object.ObjectBlock;
import com.volmit.placement.PlacedBlock;
import com.volmit.placement.PlacedMarker;
import com.volmit.placement.PlacementAccess;
import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementEdit;
import com.volmit.placement.PlacementModifier;
import com.volmit.placement.PlacementPlan;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
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.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
/** Reference placement orchestration, resolved at pack load. Same-ID instances must agree on
* implementation and dependencies; occurrences are unique and sorted lexically within an ID.
* The host supplies prepared, serialized storage and enforces platform/placement policies.
* This runner buffers all mapped candidates; host validation must reject collisions or unsupported
* writes before execution. It does not silently skip writes, transform geometry or place live blocks.
*/
public final class PlacementPipeline {
private final List<ConfiguredPlacementModifier> ordered;
private PlacementPipeline(List<ConfiguredPlacementModifier> ordered) {
this.ordered = List.copyOf(ordered);
}
public static PlacementPipeline resolve(List<ConfiguredPlacementModifier> modifiers) {
var instances = List.copyOf(modifiers);
var declarations = collectDeclarations(instances);
var modifierIds = DependencyOrder.resolve(declarations);
var orderedOccurrences = OccurrenceOrder.order(
modifierIds,
instances,
ConfiguredPlacementModifier::id,
ConfiguredPlacementModifier::occurrence);
return new PlacementPipeline(orderedOccurrences);
}
private static Map<ResourceId, Dependencies> collectDeclarations(
List<ConfiguredPlacementModifier> instances) {
var representatives = new HashMap<ResourceId, ConfiguredPlacementModifier>();
var occurrences = new HashSet<ResourceId>();
var declarations = new HashMap<ResourceId, Dependencies>();
for (var modifier : instances) {
checkUniqueOccurrence(modifier, occurrences);
checkCompatibleIdentity(modifier, representatives);
declarations.put(modifier.id(), modifier.dependencies());
}
return declarations;
}
private static void checkUniqueOccurrence(
ConfiguredPlacementModifier modifier,
Set<ResourceId> occurrences) {
if (!occurrences.add(modifier.occurrence())) {
throw new IllegalArgumentException("Duplicate placement occurrence: " + modifier.occurrence());
}
}
private static void checkCompatibleIdentity(
ConfiguredPlacementModifier modifier,
Map<ResourceId, ConfiguredPlacementModifier> representatives) {
var previous = representatives.putIfAbsent(modifier.id(), modifier);
if (previous == null || isCompatible(previous, modifier)) {
return;
}
throw new IllegalArgumentException("Conflicting placement identity: " + modifier.id());
}
private static boolean isCompatible(
ConfiguredPlacementModifier first,
ConfiguredPlacementModifier second) {
return first.modifier().getClass().equals(second.modifier().getClass())
&& first.dependencies().equals(second.dependencies());
}
public List<ConfiguredPlacementModifier> ordered() {
return ordered;
}
public int writeRadius() {
return ordered.stream()
.mapToInt(ConfiguredPlacementModifier::writeRadius)
.max()
.orElse(0);
}
/** Takes ownership of a fresh edit, closing it on success, rejection or exception.
* Contexts are opened once per occurrence and must use dedicated RNGs from one pack snapshot.
* The caller releases those invocation views after this call. The host must prepare the full
* footprint plus declared reach; a prepare hook that moves outside it fails without clipping.
* hostValidation must be read-only and covers collisions, support, protection, state/payload
* validity and any policies beyond modifier validation. Callbacks must not commit the edit.
*/
public Optional<PlacementPlan> place(
PlacementRequest request,
PlacementEdit edit,
Function<ConfiguredPlacementModifier, PlacementContext> contexts,
Predicate<PlacementPlan> hostValidation) {
Objects.requireNonNull(edit, "edit");
try (edit) {
requireInputs(request, contexts, hostValidation);
var invocations = openInvocations(contexts);
var preparedRequest = prepareAll(request, invocations);
if (preparedRequest.isEmpty()) {
return Optional.empty();
}
var prepared = preparedRequest.orElseThrow();
checkPreparedArea(prepared, edit);
var plan = createPlan(prepared, invocations, edit);
if (!validatePlan(plan, invocations, hostValidation)) {
return Optional.empty();
}
var hooks = openHookInvocations(prepared, invocations, edit);
runBeforeHooks(plan, hooks);
writePlan(plan, edit);
runAfterHooks(plan, hooks);
edit.commit();
return Optional.of(plan);
}
}
private static void requireInputs(
PlacementRequest request,
Function<ConfiguredPlacementModifier, PlacementContext> contexts,
Predicate<PlacementPlan> hostValidation) {
Objects.requireNonNull(request, "request");
Objects.requireNonNull(contexts, "contexts");
Objects.requireNonNull(hostValidation, "hostValidation");
}
private List<PlacementInvocation> openInvocations(
Function<ConfiguredPlacementModifier, PlacementContext> contexts) {
var invocations = new ArrayList<PlacementInvocation>(ordered.size());
for (var modifier : ordered) {
var context = Objects.requireNonNull(contexts.apply(modifier), "context");
invocations.add(new PlacementInvocation(modifier, context));
}
return List.copyOf(invocations);
}
private static Optional<PlacementRequest> prepareAll(
PlacementRequest initialRequest,
List<PlacementInvocation> invocations) {
var attemptId = initialRequest.id();
var request = initialRequest;
for (var invocation : invocations) {
var prepared = Objects.requireNonNull(
invocation.modifier().modifier().prepare(invocation.context(), request),
"prepared request");
if (prepared.isEmpty()) {
return Optional.empty();
}
request = prepared.orElseThrow();
if (!request.id().equals(attemptId)) {
throw new IllegalArgumentException("Prepare must preserve placement attempt ID");
}
}
return Optional.of(request);
}
private PlacementPlan createPlan(
PlacementRequest request,
List<PlacementInvocation> invocations,
PlacementEdit edit) {
var blocks = mapBlocks(request, invocations);
var markers = mapMarkers(request);
var plan = new PlacementPlan(request, blocks, markers);
// Compute checked half-open bounds before any mutation, including integer extremes.
plan.writtenBounds();
validateMappedPositions(plan, request, edit, writeRadius());
return plan;
}
private static List<PlacedBlock> mapBlocks(
PlacementRequest request,
List<PlacementInvocation> invocations) {
var mappedBlocks = new ArrayList<PlacedBlock>();
for (var block : request.object().blocks()) {
var mapped = mapBlock(request, block, invocations);
mapped.ifPresent(mappedBlocks::add);
}
return mappedBlocks;
}
private static Optional<PlacedBlock> mapBlock(
PlacementRequest request,
ObjectBlock block,
List<PlacementInvocation> invocations) {
Optional<PlacedBlock> mapped = Optional.of(new PlacedBlock(
request.worldPosition(block.position()),
block.state(),
block.blockEntity()));
for (var invocation : invocations) {
var modifier = invocation.modifier().modifier();
var next = Objects.requireNonNull(
modifier.mapBlock(invocation.context(), mapped.orElseThrow()),
"mapped block");
if (next.isEmpty()) {
return Optional.empty();
}
mapped = next;
}
return mapped;
}
private static List<PlacedMarker> mapMarkers(PlacementRequest request) {
var markers = new ArrayList<PlacedMarker>();
for (var marker : request.object().markers()) {
markers.add(new PlacedMarker(
request.worldPosition(marker.position()),
marker.type(),
marker.attributes()));
}
return markers;
}
private static void validateMappedPositions(
PlacementPlan plan,
PlacementRequest request,
PlacementEdit edit,
int radius) {
for (var block : plan.blocks()) {
checkPosition(block.position(), request.footprint(), edit.bounds(), radius);
}
for (var marker : plan.markers()) {
checkPosition(marker.position(), request.footprint(), edit.bounds(), radius);
}
}
private static boolean validatePlan(
PlacementPlan plan,
List<PlacementInvocation> invocations,
Predicate<PlacementPlan> hostValidation) {
if (!hostValidation.test(plan)) {
return false;
}
for (var invocation : invocations) {
if (!invocation.modifier().modifier().validate(invocation.context(), plan)) {
return false;
}
}
return true;
}
private List<HookInvocation> openHookInvocations(
PlacementRequest request,
List<PlacementInvocation> invocations,
PlacementEdit edit) {
var hooks = new ArrayList<HookInvocation>(invocations.size());
for (var invocation : invocations) {
var access = hookAccess(invocation.modifier(), request, edit);
hooks.add(new HookInvocation(invocation, access));
}
return List.copyOf(hooks);
}
private static void runBeforeHooks(PlacementPlan plan, List<HookInvocation> hooks) {
for (var hook : hooks) {
hook.invocation().modifier().modifier().beforePlace(
hook.invocation().context(),
hook.access(),
plan);
}
}
private static void writePlan(PlacementPlan plan, PlacementEdit edit) {
for (var block : plan.blocks()) {
edit.set(block);
}
for (var marker : plan.markers()) {
edit.marker(marker);
}
}
private static void runAfterHooks(PlacementPlan plan, List<HookInvocation> hooks) {
for (var hook : hooks) {
hook.invocation().modifier().modifier().afterPlace(
hook.invocation().context(),
hook.access(),
plan);
}
}
private static PlacementAccess hookAccess(
ConfiguredPlacementModifier modifier,
PlacementRequest request,
PlacementEdit edit) {
var footprint = request.footprint();
int radius = modifier.writeRadius();
var bounds = new BlockBox(
Math.subtractExact(footprint.minX(), radius),
edit.bounds().minY(),
Math.subtractExact(footprint.minZ(), radius),
Math.addExact(footprint.maxX(), radius),
edit.bounds().maxY(),
Math.addExact(footprint.maxZ(), radius));
return PlacementViews.restrict(edit, bounds);
}
private void checkPreparedArea(PlacementRequest request, PlacementEdit edit) {
var footprint = request.footprint();
var preparedBounds = edit.bounds();
if (!preparedBounds.contains(footprint)
|| !containsHorizontalReach(preparedBounds, footprint, writeRadius())) {
throw new IndexOutOfBoundsException("Placement footprint/reach outside prepared bounds");
}
}
private static void checkPosition(
BlockPosition position,
BlockBox footprint,
BlockBox preparedBounds,
int radius) {
if (!preparedBounds.contains(position.x(), position.y(), position.z())
|| !isWithinHorizontalReach(position.x(), position.z(), footprint, radius)) {
throw new IndexOutOfBoundsException("Mapped placement write outside declared reach: " + position);
}
}
private static boolean containsHorizontalReach(BlockBox outer, BlockBox footprint, int radius) {
return containsReachOnAxis(outer.minX(), outer.maxX(), footprint.minX(), footprint.maxX(), radius)
&& containsReachOnAxis(outer.minZ(), outer.maxZ(), footprint.minZ(), footprint.maxZ(), radius);
}
private static boolean isWithinHorizontalReach(
int x,
int z,
BlockBox footprint,
int radius) {
return isWithinReachOnAxis(x, footprint.minX(), footprint.maxX(), radius)
&& isWithinReachOnAxis(z, footprint.minZ(), footprint.maxZ(), radius);
}
private static boolean containsReachOnAxis(
int outerMin,
int outerMax,
int footprintMin,
int footprintMax,
int radius) {
return (long) footprintMin - radius >= outerMin
&& (long) footprintMax + radius <= outerMax;
}
private static boolean isWithinReachOnAxis(int position, int min, int max, int radius) {
return position >= (long) min - radius && position < (long) max + radius;
}
private record PlacementInvocation(
ConfiguredPlacementModifier modifier,
PlacementContext context) {}
private record HookInvocation(PlacementInvocation invocation, PlacementAccess access) {}
}
@@ -0,0 +1,20 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.placement.PlacementModifierFactory;
import com.volmit.resource.ResourceId;
import java.util.Objects;
public record PlacementRegistration<F extends IrisFeature>(
FeatureDescriptor<F> descriptor,
PlacementModifierFactory<F> factory) {
public PlacementRegistration {
Objects.requireNonNull(descriptor, "descriptor");
Objects.requireNonNull(factory, "factory");
}
public ConfiguredPlacementModifier configure(ResourceId occurrence, F feature) {
var configuredFeature = descriptor.type().cast(Objects.requireNonNull(feature, "feature"));
return new ConfiguredPlacementModifier(occurrence, factory.create(configuredFeature));
}
}
@@ -0,0 +1,149 @@
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.Objects;
/** Internal hook views: limit horizontal reach and hide transaction ownership. */
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 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(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);
}
@Override
public Mantle mantle() {
return restrictMantle(edit.mantle(), bounds());
}
}
private static final class RestrictedMantle implements Mantle {
private final Mantle parent;
private final BlockBox allowedBounds;
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
public <T> MantleLayer<T> layer(MantleKey<T> key) {
bounds();
return new RestrictedMantleLayer<>(this, parent.layer(key));
}
}
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);
}
}
}
+14
View File
@@ -0,0 +1,14 @@
package com.volmit.hunk;
/** Dense local volume. Coordinates range from zero inclusive to each dimension exclusive.
* Reads/writes outside that range throw IndexOutOfBoundsException. Null values are forbidden;
* block volumes represent empty space with an air state. Invocation-owned hunks must not escape.
* This is a new minimal contract, not a copy of Iris's full Hunk implementation.
*/
public interface Hunk<T> {
int getWidth();
int getHeight();
int getDepth();
T get(int x, int y, int z);
void set(int x, int y, int z, T value);
}
@@ -0,0 +1,23 @@
package com.volmit.mantle;
import java.util.Objects;
/** World block bounds, minimum inclusive and maximum exclusive. Empty boxes are valid. */
public record BlockBox(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
public BlockBox {
if (minX > maxX || minY > maxY || minZ > maxZ) {
throw new IllegalArgumentException("Inverted block bounds");
}
}
public boolean contains(int x, int y, int z) {
return x >= minX && x < maxX && y >= minY && y < maxY && z >= minZ && z < maxZ;
}
public boolean contains(BlockBox area) {
Objects.requireNonNull(area, "area");
return area.minX >= minX && area.maxX <= maxX
&& area.minY >= minY && area.maxY <= maxY
&& area.minZ >= minZ && area.maxZ <= maxZ;
}
}
@@ -0,0 +1,28 @@
package com.volmit.mantle;
/**
* Invocation-scoped access to typed mantle data. Coordinates are world block coordinates,
* including negative Y; the host translates them to storage coordinates.
*
* <p>The host owns chunk acquisition, release, persistence and the permitted access area.
* Out-of-area access throws IndexOutOfBoundsException. Access after the invocation ends
* throws IllegalStateException. Do not retain this interface or use it from detached tasks.
* Concurrent use of one instance is not supported unless the host explicitly permits it.
*
* <p>Only registered layers are supported. Unknown IDs or mismatched registered types throw
* IllegalArgumentException. Null arguments are rejected. Layer views share this view's lifetime.
*
* <p>Writes affect generation storage, not necessarily the current chunk Hunk or live world.
* Direct writes have no rollback guarantee. Use edit() to buffer multi-layer changes.
* The host must serialize overlapping writes; read-modify-write is not independently atomic.
*/
public interface Mantle {
BlockBox bounds();
<T> MantleLayer<T> layer(MantleKey<T> key);
/** Only one edit may be active per view. Parent reads remain allowed, but parent
* mutations are prohibited until the edit ends (IllegalStateException).
*/
MantleEdit edit();
}
@@ -0,0 +1,18 @@
package com.volmit.mantle;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/** Value serialization. Host frames payloads and stores key ID and version separately.
* Implementations must support concurrent calls, must not close streams, and must reject
* malformed data or unsupported stored versions with IOException. Values cannot be null.
*/
public interface MantleCodec<T> {
/** Nonnegative format version, stable for the registration lifetime. */
int version();
void write(DataOutput output, T value) throws IOException;
T read(DataInput input, int storedVersion) throws IOException;
}
@@ -0,0 +1,19 @@
package com.volmit.mantle;
/** Buffered changes across layers, with the parent's bounds and registrations.
* Reads and visits include buffered replacements/removals over the unchanged parent.
* Nested edits are unsupported: edit() throws UnsupportedOperationException.
* The host excludes competing writers; this is not a concurrent or disk transaction.
*/
public interface MantleEdit extends Mantle, AutoCloseable {
/** Publishes all changes to the parent or leaves it unchanged on failure.
* Successful commit ends the edit and invalidates its layer views. On failure the
* edit can only be closed. Repeated commit throws IllegalStateException.
* This guarantee applies to generation storage, not crash recovery or world writes.
*/
void commit();
/** Discards uncommitted changes and invalidates edit views. Idempotent after commit/close. */
@Override
void close();
}
@@ -0,0 +1,17 @@
package com.volmit.mantle;
import java.util.Objects;
/** Stable storage identity. Different IDs may use the same value class without sharing data. */
public record MantleKey<T>(String id, Class<T> type) {
public MantleKey {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(type, "type");
if (!id.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) {
throw new IllegalArgumentException("Expected a namespaced mantle ID: " + id);
}
if (type.isPrimitive()) {
throw new IllegalArgumentException("Mantle values require a reference type");
}
}
}
@@ -0,0 +1,25 @@
package com.volmit.mantle;
/** A registered layer bounded by its owning Mantle view and sharing its lifetime.
* Values must be non-null and treated as immutable. Wrong value types are rejected with
* IllegalArgumentException; null arguments with NullPointerException.
*/
public interface MantleLayer<T> {
/** Returns null on absence, without allocating a storage section. */
T get(int x, int y, int z);
void set(int x, int y, int z, T value);
/** Removing an absent entry is a no-op. */
void remove(int x, int y, int z);
/** Visits stored entries only, in ascending x, then y, then z order.
* Area must be fully within bounds (no silent clipping). Callbacks must not mutate
* this layer directly. An edit may buffer changes while visiting its parent layer.
* Callback exceptions propagate and stop traversal. No snapshot allocation is required.
*/
void visit(BlockBox area, MantleVisitor<T> visitor);
/** Removes all entries in the fully bounded area; other layers are untouched. */
void clear(BlockBox area);
}
@@ -0,0 +1,8 @@
package com.volmit.mantle;
public enum MantleLifetime {
/** May be removed only after all generation consumers, including neighbors, finish. */
GENERATION,
/** Survives generation cleanup; explicit removal is still permitted. */
PERSISTENT
}
@@ -0,0 +1,6 @@
package com.volmit.mantle;
@FunctionalInterface
public interface MantleVisitor<T> {
void accept(int x, int y, int z, T value);
}
@@ -0,0 +1,34 @@
package com.volmit.object;
import com.volmit.resource.ResourceId;
import java.util.Arrays;
import java.util.Objects;
/** Immutable versioned payload. The host's adapter owns interpretation and size limits.
* Unsupported formats/versions fail explicitly; native objects and mutable buffers never escape.
*/
public final class BlockEntityData {
private final ResourceId format;
private final int version;
private final byte[] payload;
public BlockEntityData(ResourceId format, int version, byte[] payload) {
this.format = Objects.requireNonNull(format, "format");
if (version < 0) throw new IllegalArgumentException("Negative block entity format version");
this.version = version;
this.payload = Objects.requireNonNull(payload, "payload").clone();
}
public ResourceId format() { return format; }
public int version() { return version; }
public byte[] payload() { return payload.clone(); }
@Override
public boolean equals(Object other) {
return other instanceof BlockEntityData data && format.equals(data.format)
&& version == data.version && Arrays.equals(payload, data.payload);
}
@Override
public int hashCode() { return 31 * Objects.hash(format, version) + Arrays.hashCode(payload); }
}
@@ -0,0 +1,36 @@
package com.volmit.object;
import com.volmit.mantle.BlockBox;
import com.volmit.world.BlockPosition;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
/** Immutable sparse geometry, safe to cache per pack snapshot.
* Bounds are local, minima inclusive/maxima exclusive, and include blocks and markers.
* The anchor may lie outside the bounds. Placement aligns it with a requested world position.
* Blocks are sorted by x/y/z; duplicates fail. Marker order at an equal position is declaration
* order. This value contains no placement settings, random state, or native platform objects.
*/
public record GeneratedObject(BlockBox bounds, BlockPosition anchor,
List<ObjectBlock> blocks, List<ObjectMarker> markers) {
public GeneratedObject {
Objects.requireNonNull(bounds, "bounds");
Objects.requireNonNull(anchor, "anchor");
blocks = List.copyOf(blocks).stream().sorted(Comparator.comparing(ObjectBlock::position)).toList();
markers = List.copyOf(markers).stream().sorted(Comparator.comparing(ObjectMarker::position)).toList();
var positions = new HashSet<BlockPosition>();
for (var block : blocks) {
checkPosition(bounds, block.position());
if (!positions.add(block.position())) throw new IllegalArgumentException("Duplicate object block: " + block.position());
}
for (var marker : markers) checkPosition(bounds, marker.position());
}
private static void checkPosition(BlockBox bounds, BlockPosition position) {
if (!bounds.contains(position.x(), position.y(), position.z())) {
throw new IllegalArgumentException("Object entry outside bounds: " + position);
}
}
}
@@ -0,0 +1,17 @@
package com.volmit.object;
import com.volmit.block.BlockState;
import com.volmit.world.BlockPosition;
import java.util.Objects;
import java.util.Optional;
/** One sparse block in object-local coordinates. Absence is distinct from an explicit air block. */
public record ObjectBlock(BlockPosition position, BlockState state, Optional<BlockEntityData> blockEntity) {
public ObjectBlock {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(state, "state");
Objects.requireNonNull(blockEntity, "blockEntity");
}
public ObjectBlock(BlockPosition position, BlockState state) { this(position, state, Optional.empty()); }
}
@@ -0,0 +1,8 @@
package com.volmit.object;
import com.volmit.generation.InvocationContext;
/** Geometry-only invocation. The host chooses the variant seed and enforces size limits.
* Placement and terrain adaptation happen later; generators return reusable local geometry.
*/
public interface ObjectGenerationContext extends InvocationContext {}
@@ -0,0 +1,9 @@
package com.volmit.object;
/** Configured geometry generator. Snapshot settings; concurrent calls use only invocation-local
* state. Return a non-null object. The host owns variant selection and snapshot-scoped caching.
*/
@FunctionalInterface
public interface ObjectGenerator {
GeneratedObject generate(ObjectGenerationContext context);
}
@@ -0,0 +1,8 @@
package com.volmit.object;
import com.volmit.IrisFeature;
@FunctionalInterface
public interface ObjectGeneratorFactory<F extends IrisFeature> {
ObjectGenerator create(F feature);
}
@@ -0,0 +1,15 @@
package com.volmit.object;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import java.util.Map;
import java.util.Objects;
/** Immutable, named metadata in object-local coordinates. The registered host/module owns meaning. */
public record ObjectMarker(BlockPosition position, ResourceId type, Map<String, String> attributes) {
public ObjectMarker {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(type, "type");
attributes = Map.copyOf(attributes);
}
}
@@ -0,0 +1,20 @@
package com.volmit.object;
/** Requested transform. The host owns rasterization, property orientation and interpolation.
* Rotation is in degrees about the object's anchor; mirrors precede scale, then X/Y/Z rotation.
* Unsupported transformations fail rather than silently changing the request.
*/
public record ObjectTransform(double rotationX, double rotationY, double rotationZ,
double scaleX, double scaleY, double scaleZ,
boolean mirrorX, boolean mirrorY, boolean mirrorZ) {
public ObjectTransform {
for (double angle : new double[]{rotationX, rotationY, rotationZ}) {
if (!Double.isFinite(angle)) throw new IllegalArgumentException("Non-finite rotation");
}
for (double scale : new double[]{scaleX, scaleY, scaleZ}) {
if (!Double.isFinite(scale) || scale <= 0) throw new IllegalArgumentException("Scale must be finite and positive");
}
}
public static ObjectTransform identity() { return new ObjectTransform(0, 0, 0, 1, 1, 1, false, false, false); }
}
@@ -0,0 +1,9 @@
package com.volmit.object;
/** Host adapter returning immutable transformed geometry with updated bounds, block properties,
* block entities and markers. Cache keys include pack snapshot, source geometry and transform.
*/
@FunctionalInterface
public interface ObjectTransformer {
GeneratedObject transform(GeneratedObject object, ObjectTransform transform);
}
@@ -0,0 +1,16 @@
package com.volmit.placement;
import com.volmit.block.BlockState;
import com.volmit.object.BlockEntityData;
import com.volmit.world.BlockPosition;
import java.util.Objects;
import java.util.Optional;
/** A proposed or buffered write in world coordinates, including its block entity payload. */
public record PlacedBlock(BlockPosition position, BlockState state, Optional<BlockEntityData> blockEntity) {
public PlacedBlock {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(state, "state");
Objects.requireNonNull(blockEntity, "blockEntity");
}
}
@@ -0,0 +1,15 @@
package com.volmit.placement;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import java.util.Map;
import java.util.Objects;
/** Marker metadata in world coordinates. */
public record PlacedMarker(BlockPosition position, ResourceId type, Map<String, String> attributes) {
public PlacedMarker {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(type, "type");
attributes = Map.copyOf(attributes);
}
}
@@ -0,0 +1,15 @@
package com.volmit.placement;
import com.volmit.mantle.Mantle;
import com.volmit.world.BlockView;
/** Buffered world-space access for placement hooks, without ownership of commit/close.
* Reads include the overlay. Bounds cover the object's footprint plus declared horizontal reach
* and host-authorized vertical area. Block/entity/marker/mantle writes share the host edit.
* Out-of-area access throws; nested mantle edits are unsupported. Do not retain this view.
*/
public interface PlacementAccess extends BlockView {
void set(PlacedBlock block);
void marker(PlacedMarker marker);
Mantle mantle();
}
@@ -0,0 +1,18 @@
package com.volmit.placement;
import com.volmit.config.FeatureSettings;
import com.volmit.generation.InvocationContext;
import com.volmit.object.ObjectTransformer;
import com.volmit.world.TerrainSampler;
import com.volmit.world.BlockView;
/** Read-only inputs to placement hooks. Working state is carried by returned immutable requests
* and blocks, never stored on a configured modifier. Context lifetime ends with placement.
*/
public interface PlacementContext extends InvocationContext {
TerrainSampler terrain();
FeatureSettings settings();
ObjectTransformer objects();
/** Prepared blocks before this placement. Use hook access for reads of buffered changes. */
BlockView blocks();
}
@@ -0,0 +1,14 @@
package com.volmit.placement;
/** Host-owned buffered placement writes, in world coordinates, including cross-chunk writes.
* All reads see the overlay. Block/entity/marker/mantle mutations participate in one commit.
* Out-of-bounds access fails, never clips. The host excludes competing writers and handles
* block entity replacement/removal when states change. Nested mantle edits are unsupported.
* Successful commit ends the edit; failure leaves the parent unchanged and permits only close.
* Close is idempotent and discards uncommitted work. Views expire when this edit ends.
* This is a generation-storage transaction, not live-world or disk/crash atomicity.
*/
public interface PlacementEdit extends PlacementAccess, AutoCloseable {
void commit();
@Override void close();
}
@@ -0,0 +1,24 @@
package com.volmit.placement;
import com.volmit.generation.Dependencies;
import java.util.Optional;
/** Configured placement behavior. IDs are namespaced; dependencies refer only to placement
* modifier IDs, not chunk modifiers. Snapshot settings; calls may occur concurrently.
* The host runs prepare for all modifiers, mapBlock for each candidate, then validate for all
* modifiers before buffering any write. beforePlace runs after validation but before object
* writes, for boring/preparation. afterPlace runs only after all accepted blocks and
* markers are buffered, allowing vacuum/stilts to observe the final footprint and overlay.
* Exceptions discard the attempt. Empty prepare rejects it; empty mapBlock skips one block.
*/
public abstract class PlacementModifier {
public abstract String id();
public Dependencies depends() { return Dependencies.none(); }
/** Horizontal access beyond the resulting object footprint; nonnegative, read at pack load. */
public int writeRadius() { return 0; }
public Optional<PlacementRequest> prepare(PlacementContext context, PlacementRequest request) { return Optional.of(request); }
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) { return Optional.of(block); }
public boolean validate(PlacementContext context, PlacementPlan plan) { return true; }
public void beforePlace(PlacementContext context, PlacementAccess access, PlacementPlan proposed) {}
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan written) {}
}
@@ -0,0 +1,8 @@
package com.volmit.placement;
import com.volmit.IrisFeature;
@FunctionalInterface
public interface PlacementModifierFactory<F extends IrisFeature> {
PlacementModifier create(F feature);
}
@@ -0,0 +1,37 @@
package com.volmit.placement;
import com.volmit.mantle.BlockBox;
import com.volmit.world.BlockPosition;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/** Complete proposed writes, constructed before validation or mutation.
* Block positions are unique and ordered x/y/z. writtenBounds describes block writes only;
* markers and the original object's declared footprint are tracked separately.
*/
public record PlacementPlan(PlacementRequest request, List<PlacedBlock> blocks, List<PlacedMarker> markers) {
public PlacementPlan {
Objects.requireNonNull(request, "request");
blocks = List.copyOf(blocks).stream().sorted(Comparator.comparing(PlacedBlock::position)).toList();
markers = List.copyOf(markers).stream().sorted(Comparator.comparing(PlacedMarker::position)).toList();
var positions = new HashSet<BlockPosition>();
for (var block : blocks) {
if (!positions.add(block.position())) throw new IllegalArgumentException("Duplicate placement write: " + block.position());
}
}
public Optional<BlockBox> writtenBounds() {
if (blocks.isEmpty()) return Optional.empty();
int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, minZ = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE, maxZ = Integer.MIN_VALUE;
for (var block : blocks) {
var position = block.position();
minX = Math.min(minX, position.x()); minY = Math.min(minY, position.y()); minZ = Math.min(minZ, position.z());
maxX = Math.max(maxX, position.x()); maxY = Math.max(maxY, position.y()); maxZ = Math.max(maxZ, position.z());
}
return Optional.of(new BlockBox(minX, minY, minZ, Math.addExact(maxX, 1), Math.addExact(maxY, 1), Math.addExact(maxZ, 1)));
}
}
@@ -0,0 +1,36 @@
package com.volmit.placement;
import com.volmit.mantle.BlockBox;
import com.volmit.object.GeneratedObject;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import java.util.Objects;
/** One placement attempt. Geometry is already transformed; anchor is a world block position.
* World position = local position - object anchor + request anchor. Arithmetic never wraps.
* id identifies this attempt within the host's generation plan.
*/
public record PlacementRequest(ResourceId id, GeneratedObject object, BlockPosition anchor) {
public PlacementRequest {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(object, "object");
Objects.requireNonNull(anchor, "anchor");
}
public BlockPosition worldPosition(BlockPosition local) {
return new BlockPosition(translate(local.x(), object.anchor().x(), anchor.x()),
translate(local.y(), object.anchor().y(), anchor.y()),
translate(local.z(), object.anchor().z(), anchor.z()));
}
public BlockBox footprint() {
var bounds = object.bounds();
var min = worldPosition(new BlockPosition(bounds.minX(), bounds.minY(), bounds.minZ()));
var max = worldPosition(new BlockPosition(bounds.maxX(), bounds.maxY(), bounds.maxZ()));
return new BlockBox(min.x(), min.y(), min.z(), max.x(), max.y(), max.z());
}
private static int translate(int local, int objectAnchor, int worldAnchor) {
return Math.toIntExact((long) local - objectAnchor + worldAnchor);
}
}
@@ -0,0 +1,23 @@
package com.volmit.resource;
import com.volmit.block.BlockRegistry;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.UUID;
/** Immutable view of one loaded pack snapshot, safe for concurrent reads.
* Reload produces a different snapshotId, even for the same pack. Resources must be immutable
* or explicitly thread-safe. Unknown IDs return empty; a known ID with the wrong requested
* type throws IllegalArgumentException. Broken resources fail loading rather than appearing absent.
* The host owns resolution, imports, native handles and caches; no filesystem paths escape.
*/
public interface PackResources {
ResourceId packId();
UUID snapshotId();
BlockRegistry blocks();
<T> Optional<T> find(ResourceKey<T> key);
default <T> T require(ResourceKey<T> key) {
return find(key).orElseThrow(() -> new NoSuchElementException("Missing resource: " + key.id()));
}
}
@@ -0,0 +1,27 @@
package com.volmit.resource;
import java.util.Objects;
/** Case-sensitive namespaced identity. Parsing never supplies an implicit namespace. */
public record ResourceId(String namespace, String path) implements Comparable<ResourceId> {
public ResourceId {
Objects.requireNonNull(namespace, "namespace");
Objects.requireNonNull(path, "path");
if (!namespace.matches("[a-z0-9_.-]+") || !path.matches("[a-z0-9_./-]+")) {
throw new IllegalArgumentException("Invalid resource ID: " + namespace + ":" + path);
}
}
public static ResourceId parse(String value) {
Objects.requireNonNull(value, "value");
int separator = value.indexOf(':');
if (separator < 0) throw new IllegalArgumentException("Expected a namespaced ID: " + value);
return new ResourceId(value.substring(0, separator), value.substring(separator + 1));
}
@Override
public String toString() { return namespace + ":" + path; }
@Override
public int compareTo(ResourceId other) { return toString().compareTo(other.toString()); }
}
@@ -0,0 +1,14 @@
package com.volmit.resource;
import java.util.Objects;
/** A resource ID paired with its public value type; the host owns loading and caching. */
public record ResourceKey<T>(ResourceId id, Class<T> type) {
public ResourceKey {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(type, "type");
if (type.isPrimitive()) throw new IllegalArgumentException("Resources require a reference type");
}
public ResourceKey(String id, Class<T> type) { this(ResourceId.parse(id), type); }
}
@@ -0,0 +1,14 @@
package com.volmit.world;
import com.volmit.resource.ResourceId;
import java.util.Objects;
import java.util.Optional;
/** Pack biome identity, distinct from the platform biome written into the chunk. */
public record BiomeSample(ResourceId region, ResourceId surfaceBiome, Optional<ResourceId> caveBiome) {
public BiomeSample {
Objects.requireNonNull(region, "region");
Objects.requireNonNull(surfaceBiome, "surfaceBiome");
Objects.requireNonNull(caveBiome, "caveBiome");
}
}
@@ -0,0 +1,19 @@
package com.volmit.world;
/** A block position. Owning contracts specify whether it is local or world space. */
public record BlockPosition(int x, int y, int z) implements Comparable<BlockPosition> {
public BlockPosition add(BlockPosition offset) {
return new BlockPosition(Math.addExact(x, offset.x), Math.addExact(y, offset.y), Math.addExact(z, offset.z));
}
public BlockPosition subtract(BlockPosition offset) {
return new BlockPosition(Math.subtractExact(x, offset.x), Math.subtractExact(y, offset.y), Math.subtractExact(z, offset.z));
}
@Override
public int compareTo(BlockPosition other) {
int result = Integer.compare(x, other.x);
if (result == 0) result = Integer.compare(y, other.y);
return result == 0 ? Integer.compare(z, other.z) : result;
}
}
@@ -0,0 +1,13 @@
package com.volmit.world;
import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox;
/** Read-only prepared generation blocks in world coordinates, not the live server world.
* Empty space is a non-null air state. Out-of-area access throws IndexOutOfBoundsException.
* Views expire with the owning invocation; access afterwards throws IllegalStateException.
*/
public interface BlockView {
BlockBox bounds();
BlockState get(int worldX, int worldY, int worldZ);
}
@@ -0,0 +1,9 @@
package com.volmit.world;
/** Immutable, seeded noise resource. Coordinates are world-space sample coordinates.
* Range and scale belong to the resource; no implicit normalization is performed.
*/
@FunctionalInterface
public interface NoiseSampler {
double sample(double worldX, double worldY, double worldZ);
}
@@ -0,0 +1,18 @@
package com.volmit.world;
import java.util.Objects;
import java.util.OptionalInt;
/** Pre-modification terrain sample in world coordinates.
* surfaceY is the top solid surface height, not the first air block. fluidY is the top fluid
* block when present. Slope is nonnegative height change per horizontal block.
* This is the host's terrain field, not a scan of current edited blocks.
*/
public record TerrainSample(double surfaceY, OptionalInt fluidY, double slope) {
public TerrainSample {
Objects.requireNonNull(fluidY, "fluidY");
if (!Double.isFinite(surfaceY) || !Double.isFinite(slope) || slope < 0) {
throw new IllegalArgumentException("Invalid terrain sample");
}
}
}
@@ -0,0 +1,13 @@
package com.volmit.world;
import com.volmit.mantle.BlockBox;
/** Read-only host sampling for the same pack snapshot as the invocation.
* Bounds are world blocks, maxima exclusive. Sampling outside prepared bounds fails with
* IndexOutOfBoundsException. Views expire with the invocation and must not escape it.
*/
public interface TerrainSampler {
BlockBox bounds();
TerrainSample column(int worldX, int worldZ);
BiomeSample biome(int worldX, int worldY, int worldZ);
}
@@ -0,0 +1,79 @@
package com.volmit;
import com.volmit.block.BlockState;
import com.volmit.host.ArrayHunk;
import com.volmit.mantle.BlockBox;
import com.volmit.object.*;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.*;
import com.volmit.world.*;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import static org.junit.jupiter.api.Assertions.*;
class ApiValuesTest {
@Test
void idsAndStateKeysAreExplicitCanonicalImmutableValues() {
for (String invalid : List.of("stone", "Minecraft:stone", "a:b:c", "a:", ":a")) {
assertThrows(IllegalArgumentException.class, () -> ResourceId.parse(invalid));
}
var properties = new HashMap<>(Map.of("waterlogged", "false", "axis", "y"));
var state = new BlockState(ResourceId.parse("minecraft:oak_log"), properties);
properties.clear();
assertEquals("minecraft:oak_log[axis=y,waterlogged=false]", state.key());
assertEquals("y", state.properties().get("axis"));
assertEquals("x", state.withProperty("axis", "x").properties().get("axis"));
assertThrows(UnsupportedOperationException.class, () -> state.properties().clear());
assertThrows(IllegalArgumentException.class, () -> new ResourceKey<>("test:value", int.class));
}
@Test
void sparseObjectsCopySortAndRejectDuplicateOrOutOfBoundsBlocks() {
var a = new ObjectBlock(new BlockPosition(-1, 0, 0), new BlockState("minecraft:stone"));
var b = new ObjectBlock(new BlockPosition(1, 0, 0), new BlockState("minecraft:stone"));
var blocks = new ArrayList<>(List.of(b, a));
var bounds = new BlockBox(-1, 0, 0, 2, 1, 1);
var object = new GeneratedObject(bounds, new BlockPosition(0, 0, 0), blocks, List.of());
blocks.clear();
assertEquals(List.of(a, b), object.blocks());
assertThrows(IllegalArgumentException.class, () -> new GeneratedObject(bounds, object.anchor(), List.of(a, a), List.of()));
assertThrows(IllegalArgumentException.class, () -> new GeneratedObject(new BlockBox(0, 0, 0, 1, 1, 1), object.anchor(), List.of(a), List.of()));
}
@Test
void payloadBuffersDoNotEscapeAndHaveValueEquality() {
byte[] source = {1, 2};
var payload = new BlockEntityData(ResourceId.parse("test:tile"), 1, source);
source[0] = 99;
payload.payload()[0] = 98;
assertArrayEquals(new byte[]{1, 2}, payload.payload());
assertEquals(payload, new BlockEntityData(ResourceId.parse("test:tile"), 1, new byte[]{1, 2}));
}
@Test
void placementAlignsAnchorsAndCheckedArithmeticNeverWraps() {
var object = new GeneratedObject(new BlockBox(-1, -1, -1, 2, 2, 2), new BlockPosition(1, 1, 1), List.of(), List.of());
var request = new PlacementRequest(ResourceId.parse("test:placement"), object, new BlockPosition(-16, -64, -16));
assertEquals(new BlockPosition(-16, -64, -16), request.worldPosition(object.anchor()));
assertEquals(new BlockBox(-18, -66, -18, -15, -63, -15), request.footprint());
var overflow = new PlacementRequest(request.id(), object, new BlockPosition(Integer.MAX_VALUE, 0, 0));
assertThrows(ArithmeticException.class, overflow::footprint);
}
@Test
void boundedHunksAndTerrainSamplesRejectInvalidInputs() {
var hunk = new ArrayHunk<>(String.class, 2, 3, 4, "air");
hunk.set(1, 2, 3, "stone");
assertEquals("stone", hunk.get(1, 2, 3));
assertEquals("air", hunk.get(0, 0, 0));
assertThrows(IndexOutOfBoundsException.class, () -> hunk.get(2, 0, 0));
assertThrows(IndexOutOfBoundsException.class, () -> hunk.set(-1, 0, 0, "stone"));
assertThrows(NullPointerException.class, () -> hunk.set(0, 0, 0, null));
assertThrows(IllegalArgumentException.class, () -> new TerrainSample(Double.NaN, OptionalInt.empty(), 0));
assertThrows(IllegalArgumentException.class, () -> new TerrainSample(0, OptionalInt.empty(), -1));
}
}
@@ -0,0 +1,77 @@
package com.volmit;
import com.volmit.config.*;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.host.ArrayHunk;
import com.volmit.host.ModuleRegistry;
import com.volmit.resource.ResourceId;
import com.volmit.support.TestContexts;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FeatureContractTest {
@Desc("Example settings")
@Snippet("fill-settings")
@Feature(id = "example:fill", name = "Fill", field = "fill", targets = FeatureAttachment.Target.BIOME)
public static class FillOptions implements IrisFeature {
@Desc("Replacement value")
@MinNumber(0)
@MaxNumber(128)
private int value = 12;
private transient int cache;
private static int ignored;
}
@Test
void readsPrivateAnnotatedOptionsWithoutIncludingRuntimeState() {
var metadata = OptionsMetadata.inspect(FillOptions.class);
assertEquals("Example settings", metadata.description());
assertEquals("fill-settings", metadata.snippet());
assertEquals(1, metadata.options().size());
var option = metadata.options().getFirst();
assertEquals("value", option.name());
assertEquals(int.class, option.type());
assertEquals("Replacement value", option.description());
assertEquals(0.0, option.minimum());
assertEquals(128.0, option.maximum());
}
@Test
void registryBindsDecodedOptionsToTheCorrectModifier() {
var host = new ModuleRegistry();
host.register(FillOptions.class, Integer.class, FillModifier::new);
var registration = host.freeze().generation(FillOptions.class, Integer.class);
var modifier = registration.configure(ResourceId.parse("test:fill/0"), new FillOptions());
var output = new ArrayHunk<>(Integer.class, 1, 1, 1, 0);
modifier.modify(TestContexts.generation(), output);
assertEquals(12, output.get(0, 0, 0));
}
private static class FillModifier extends GenerationModifier<Integer> {
private final FillOptions options;
FillModifier(FillOptions options) {
this.options = options;
}
public String id() { return "example:fill-modifier"; }
public void modify(GenerationContext context, Hunk<Integer> volume) {
volume.set(0, 0, 0, options.value);
}
}
static class InvalidOptions {
@MinNumber(10) @MaxNumber(2) private int value;
}
static class NonnumericOptions {
@MinNumber(0) private String value;
}
@Test
void rejectsInconsistentAnnotationBounds() {
assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(InvalidOptions.class));
assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(NonnumericOptions.class));
}
}
@@ -0,0 +1,54 @@
package com.volmit.generation;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class DependenciesTest {
@Test
void accumulatesAndDeduplicatesWithoutMutatingEarlierDeclarations() {
var original = Dependencies.requires("iris:terrain", "iris:terrain");
var result = original.andRequires("iris:carving")
.afterIfPresent("example:caves").afterIfPresent("example:lakes")
.beforeIfPresent("iris:ores").beforeIfPresent("iris:ores", "iris:objects");
assertEquals(Set.of("iris:terrain"), original.required());
assertTrue(original.after().isEmpty());
assertTrue(original.before().isEmpty());
assertEquals(Set.of("iris:terrain", "iris:carving"), result.required());
assertEquals(Set.of("example:caves", "example:lakes"), result.after());
assertEquals(Set.of("iris:ores", "iris:objects"), result.before());
}
@Test
void copiesInputsAndExposesImmutableSets() {
var ids = new HashSet<>(Set.of("iris:terrain"));
var result = new Dependencies(ids, ids, ids);
ids.clear();
assertEquals(Set.of("iris:terrain"), result.required());
assertThrows(UnsupportedOperationException.class, () -> result.required().clear());
assertThrows(UnsupportedOperationException.class, () -> result.after().clear());
assertThrows(UnsupportedOperationException.class, () -> result.before().clear());
String[] input = {"iris:terrain"};
var fromArray = Dependencies.requires(input);
input[0] = "iris:ores";
assertEquals(Set.of("iris:terrain"), fromArray.required());
}
@Test
void supportsEmptyAndOptionalOnlyDeclarations() {
assertEquals(new Dependencies(Set.of(), Set.of(), Set.of()), Dependencies.none());
assertEquals(Dependencies.none(), Dependencies.requires());
assertEquals(Set.of("iris:ores"), Dependencies.none().beforeIfPresent("iris:ores").before());
}
@Test
void rejectsNullAndBlankIds() {
assertThrows(IllegalArgumentException.class, () -> Dependencies.requires(" "));
assertThrows(IllegalArgumentException.class, () -> Dependencies.none().afterIfPresent(""));
assertThrows(IllegalArgumentException.class, () -> Dependencies.none().beforeIfPresent("\n"));
assertThrows(NullPointerException.class, () -> Dependencies.requires((String) null));
assertThrows(NullPointerException.class, () -> Dependencies.requires((String[]) null));
assertThrows(NullPointerException.class, () -> new Dependencies(null, Set.of(), Set.of()));
}
}
@@ -0,0 +1,85 @@
package com.volmit.host;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class GenerationPlanTest {
private static ResourceId id(String path) { return ResourceId.parse("test:" + path); }
private static ConfiguredModifier<String> binding(String occurrence, String name, Dependencies dependencies) {
return new ConfiguredModifier<>(id(occurrence), String.class, new Modifier(name, dependencies));
}
private static class Modifier extends GenerationModifier<String> {
private final String name;
private final Dependencies dependencies;
Modifier(String name, Dependencies dependencies) { this.name = name; this.dependencies = dependencies; }
public String id() { return "test:" + name; }
public Dependencies depends() { return dependencies; }
public void modify(GenerationContext context, Hunk<String> output) {}
}
@Test
void orderingIsIndependentOfDiscoveryAndIncludesRepeatedOccurrences() {
var first = binding("terrain/1", "terrain", Dependencies.none());
var second = binding("terrain/0", "terrain", Dependencies.none());
var caves = binding("caves/0", "caves", Dependencies.requires("test:terrain"));
var decoration = binding("decoration/0", "decoration", Dependencies.requires("test:caves").beforeIfPresent("test:missing"));
var a = GenerationPlan.resolve(List.of(decoration, first, caves, second));
var b = GenerationPlan.resolve(List.of(second, caves, decoration, first));
var expected = List.of(id("terrain/0"), id("terrain/1"), id("caves/0"), id("decoration/0"));
assertEquals(expected, a.ordered().stream().map(ConfiguredModifier::occurrence).toList());
assertEquals(expected, b.ordered().stream().map(ConfiguredModifier::occurrence).toList());
var executed = new ArrayList<ResourceId>();
a.execute(new GenerationPlan.Executor() {
public <T> void execute(ConfiguredModifier<T> modifier) { executed.add(modifier.occurrence()); }
});
assertEquals(expected, executed);
assertThrows(UnsupportedOperationException.class, () -> a.ordered().clear());
}
@Test
void rejectsMissingRequirementsSelfEdgesAndCycles() {
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.requires("test:missing"))));
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.none().beforeIfPresent("test:a"))));
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.requires("test:b"), id("b"), Dependencies.requires("test:a"))));
}
@Test
void rejectsDuplicateOccurrencesAndConflictingImplementationsOrDeclarations() {
var a = binding("a/0", "a", Dependencies.none());
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a, a)));
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a,
binding("a/1", "a", Dependencies.none().afterIfPresent("test:b")))));
var otherImplementation = new ConfiguredModifier<>(id("a/2"), String.class, new Modifier("a", Dependencies.none()) {});
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a, otherImplementation)));
}
@Test
void repeatedEdgesAreCountedOnceAndIndependentIdsUseLexicalOrder() {
var graph = Map.of(id("a"), Dependencies.none(), id("z"), Dependencies.none(),
id("b"), Dependencies.requires("test:a").afterIfPresent("test:a"));
assertEquals(List.of(id("a"), id("b"), id("z")), DependencyOrder.resolve(graph));
}
@Test
void failuresStopDispatchAndNegativeReachFailsAtPackLoad() {
var plan = GenerationPlan.resolve(List.of(binding("a", "a", Dependencies.none()), binding("b", "b", Dependencies.none())));
var visited = new ArrayList<ResourceId>();
assertThrows(IllegalStateException.class, () -> plan.execute(new GenerationPlan.Executor() {
public <T> void execute(ConfiguredModifier<T> modifier) {
visited.add(modifier.id());
throw new IllegalStateException("Failed output");
}
}));
assertEquals(List.of(id("a")), visited);
assertThrows(IllegalArgumentException.class, () -> new ConfiguredModifier<>(id("negative"), String.class,
new Modifier("a", Dependencies.none()) { public int mantleRadius() { return -1; } }));
}
}
@@ -0,0 +1,95 @@
package com.volmit.host;
import com.volmit.*;
import com.volmit.config.Feature;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.*;
import com.volmit.placement.PlacementModifier;
import org.junit.jupiter.api.Test;
import java.io.DataInput;
import java.io.DataOutput;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class ModuleRegistryTest {
@Feature(id = "test:one", name = "One", field = "shared", targets = FeatureAttachment.Target.BIOME)
static class One implements IrisFeature {}
@Feature(id = "test:two", name = "Two", field = "shared", targets = FeatureAttachment.Target.DIMENSION)
static class Two implements IrisFeature {}
@Feature(id = "test:collision", name = "Collision", field = "shared", targets = {FeatureAttachment.Target.DIMENSION, FeatureAttachment.Target.BIOME})
static class Collision implements IrisFeature {}
@Feature(id = "test:one", name = "Duplicate", field = "different", targets = FeatureAttachment.Target.REGION)
static class Duplicate implements IrisFeature {}
@Feature(id = "test:placement", name = "Placement", field = "foundation", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
static class Placement implements IrisFeature {}
static class MissingAnnotation implements IrisFeature {}
@Feature(id = "test:abstract", name = "Abstract", field = "abstract", targets = FeatureAttachment.Target.BIOME)
abstract static class AbstractFeature implements IrisFeature {}
private static GenerationModifier<String> modifier(IrisFeature ignored) {
return new GenerationModifier<>() {
public String id() { return "test:modifier"; }
public void modify(GenerationContext context, Hunk<String> output) {}
};
}
@Test
void validatesIdsTypesAndFieldsAcrossFeatureKindsWithoutPartialRegistration() {
var registry = new ModuleRegistry();
registry.register(One.class, String.class, ModuleRegistryTest::modifier);
assertThrows(IllegalArgumentException.class, () -> registry.register(Collision.class, String.class, ModuleRegistryTest::modifier));
registry.register(Two.class, String.class, ModuleRegistryTest::modifier);
assertThrows(IllegalArgumentException.class, () -> registry.registerObject(Duplicate.class, ignored -> context -> null));
assertThrows(IllegalArgumentException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
var catalog = registry.freeze();
assertEquals(List.of("test:one", "test:two"), catalog.generation().stream().map(value -> value.descriptor().id().toString()).toList());
assertThrows(IllegalArgumentException.class, () -> catalog.generation(One.class, Integer.class));
}
@Test
void reservesHostFieldsAndRejectsInvalidFeaturesOrFactories() {
var registry = new ModuleRegistry(Map.of(FeatureAttachment.Target.BIOME, Set.of("shared")));
assertThrows(IllegalArgumentException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
assertThrows(IllegalArgumentException.class, () -> registry.register(MissingAnnotation.class, String.class, ModuleRegistryTest::modifier));
assertThrows(IllegalArgumentException.class, () -> registry.register(AbstractFeature.class, String.class, ModuleRegistryTest::modifier));
assertThrows(NullPointerException.class, () -> registry.register(Two.class, String.class, null));
registry.register(Two.class, String.class, ModuleRegistryTest::modifier);
}
@Test
void placementMustAttachToPlacementAndFreezeEndsRegistration() {
var registry = new ModuleRegistry();
assertThrows(IllegalArgumentException.class, () -> registry.registerPlacement(One.class, ignored -> new PlacementModifier() {
public String id() { return "test:placement"; }
}));
registry.registerPlacement(Placement.class, ignored -> new PlacementModifier() {
public String id() { return "test:placement"; }
});
assertEquals(1, registry.freeze().placement().size());
assertSame(registry.freeze(), registry.freeze());
assertThrows(IllegalStateException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
}
@Test
void mantleIdsAreUniqueAndCodecVersionIsSnapshotted() {
var registry = new ModuleRegistry();
var key = new MantleKey<>("test:owners", String.class);
var codec = codec(3);
registry.registerMantle(key, MantleLifetime.GENERATION, codec);
assertThrows(IllegalArgumentException.class, () -> registry.registerMantle(key, MantleLifetime.PERSISTENT, codec));
assertThrows(IllegalArgumentException.class, () -> registry.registerMantle(new MantleKey<>("test:bad", String.class), MantleLifetime.GENERATION, codec(-1)));
assertEquals(3, registry.freeze().mantle().getFirst().version());
assertEquals(1, registry.freeze().mantle().size());
}
private static MantleCodec<String> codec(int version) {
return new MantleCodec<>() {
public int version() { return version; }
public void write(DataOutput output, String value) {}
public String read(DataInput input, int storedVersion) { return ""; }
};
}
}
@@ -0,0 +1,259 @@
package com.volmit.host;
import com.volmit.block.BlockState;
import com.volmit.generation.Dependencies;
import com.volmit.mantle.*;
import com.volmit.object.*;
import com.volmit.placement.*;
import com.volmit.resource.ResourceId;
import com.volmit.support.TestContexts;
import com.volmit.world.BlockPosition;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
class PlacementPipelineTest {
private static final BlockState STONE = new BlockState("minecraft:stone");
private static final BlockState AIR = new BlockState("minecraft:air");
private static ResourceId id(String name) { return ResourceId.parse("test:" + name); }
private static PlacementRequest request() {
var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 1, 1), new BlockPosition(1, 0, 0),
List.of(new ObjectBlock(new BlockPosition(1, 0, 0), STONE), new ObjectBlock(new BlockPosition(0, 0, 0), STONE)),
List.of(new ObjectMarker(new BlockPosition(1, 0, 0), id("owner"), Map.of("name", "column"))));
return new PlacementRequest(id("attempt"), object, new BlockPosition(-2, -60, -3));
}
private static ConfiguredPlacementModifier configured(PlacementModifier modifier) {
return new ConfiguredPlacementModifier(ResourceId.parse(modifier.id() + "/0"), modifier);
}
@Test
void validatesCompletePlanBeforeWritesAndAfterHooksSeeOverlayAndActualBounds() {
var events = new ArrayList<String>();
var modifier = new PlacementModifier() {
public String id() { return "test:foundation"; }
public Optional<PlacementRequest> prepare(PlacementContext context, PlacementRequest request) {
events.add("prepare"); return Optional.of(request);
}
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
events.add("map");
return block.position().x() == -3 ? Optional.empty() : Optional.of(block);
}
public boolean validate(PlacementContext context, PlacementPlan plan) {
events.add("validate");
assertEquals(1, plan.blocks().size());
return true;
}
public void beforePlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
events.add("before");
assertEquals(AIR, access.get(-2, -60, -3));
}
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan written) {
events.add("after");
assertEquals(STONE, access.get(-2, -60, -3));
assertEquals(new BlockBox(-2, -60, -3, -1, -59, -2), written.writtenBounds().orElseThrow());
assertFalse(access instanceof PlacementEdit);
access.set(new PlacedBlock(new BlockPosition(-2, -61, -3), STONE, Optional.empty()));
}
};
var pipeline = PlacementPipeline.resolve(List.of(configured(modifier)));
var edit = new RecordingEdit(events);
var result = pipeline.place(request(), edit, ignored -> TestContexts.placement(), plan -> {
events.add("host-validate"); assertEquals(0, edit.mutations); return true;
});
assertTrue(result.isPresent());
assertEquals(List.of("prepare", "map", "map", "host-validate", "validate", "before", "write", "marker", "after", "write", "commit", "close"), events);
assertEquals(2, edit.published.size());
assertEquals(1, edit.publishedMarkers.size());
assertThrows(IllegalStateException.class, () -> edit.get(-2, -60, -3));
}
@Test
void validationRejectionPublishesNothingAndDoesNotStartMutating() {
var modifier = new PlacementModifier() {
public String id() { return "test:reject"; }
public boolean validate(PlacementContext context, PlacementPlan plan) { return false; }
};
var edit = new RecordingEdit(new ArrayList<>());
assertTrue(PlacementPipeline.resolve(List.of(configured(modifier)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true).isEmpty());
assertEquals(0, edit.mutations);
assertTrue(edit.published.isEmpty());
assertTrue(edit.closed);
}
@Test
void failureAfterBufferedObjectWritesDiscardsEntireAttempt() {
var modifier = new PlacementModifier() {
public String id() { return "test:failure"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
access.set(new PlacedBlock(new BlockPosition(-2, -61, -3), STONE, Optional.empty()));
throw new IllegalStateException("Foundation failed");
}
};
var edit = new RecordingEdit(new ArrayList<>());
assertThrows(IllegalStateException.class, () -> PlacementPipeline.resolve(List.of(configured(modifier)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true));
assertTrue(edit.mutations > 0);
assertTrue(edit.published.isEmpty());
assertTrue(edit.publishedMarkers.isEmpty());
assertTrue(edit.closed);
}
@Test
void prepareRejectionAndFailedCommitCloseWithoutPublication() {
var rejection = new PlacementModifier() {
public String id() { return "test:prepare-reject"; }
public Optional<PlacementRequest> prepare(PlacementContext context, PlacementRequest request) { return Optional.empty(); }
};
var rejected = new RecordingEdit(new ArrayList<>());
assertTrue(PlacementPipeline.resolve(List.of(configured(rejection)))
.place(request(), rejected, ignored -> TestContexts.placement(), ignored -> true).isEmpty());
assertEquals(0, rejected.mutations);
var failed = new RecordingEdit(new ArrayList<>());
failed.failCommit = true;
assertThrows(IllegalStateException.class, () -> PlacementPipeline.resolve(List.of())
.place(request(), failed, ignored -> TestContexts.placement(), ignored -> true));
assertTrue(failed.closed);
assertTrue(failed.published.isEmpty());
}
@Test
void rejectsMappedBoundsDuplicateWritesAndInsufficientPreparedReachBeforeMutation() {
var escape = new PlacementModifier() {
public String id() { return "test:escape"; }
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
return Optional.of(new PlacedBlock(new BlockPosition(5, -60, -3), block.state(), block.blockEntity()));
}
};
var escaped = new RecordingEdit(new ArrayList<>());
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(escape)))
.place(request(), escaped, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, escaped.mutations);
var radius = new PlacementModifier() {
public String id() { return "test:radius"; }
public int writeRadius() { return 32; }
};
var unprepared = new RecordingEdit(new ArrayList<>());
assertThrows(IndexOutOfBoundsException.class, () -> PlacementPipeline.resolve(List.of(configured(radius)))
.place(request(), unprepared, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, unprepared.mutations);
}
@Test
void hooksCannotWriteBeyondReachOrRetainUsableViews() {
var retained = new AtomicReference<PlacementAccess>();
var retainedLayer = new AtomicReference<MantleLayer<String>>();
var modifier = new PlacementModifier() {
public String id() { return "test:bounded"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
retained.set(access);
retainedLayer.set(access.mantle().layer(new MantleKey<>("test:owner", String.class)));
assertThrows(IndexOutOfBoundsException.class, () -> access.set(new PlacedBlock(new BlockPosition(5, -60, -3), STONE, Optional.empty())));
assertThrows(UnsupportedOperationException.class, () -> access.mantle().edit());
assertThrows(IndexOutOfBoundsException.class, () -> access.mantle().layer(new MantleKey<>("test:owner", String.class)).get(5, -60, -3));
}
};
var edit = new RecordingEdit(new ArrayList<>());
PlacementPipeline.resolve(List.of(configured(modifier))).place(request(), edit, ignored -> TestContexts.placement(), ignored -> true);
assertThrows(IllegalStateException.class, () -> retained.get().get(-2, -60, -3));
assertThrows(IllegalStateException.class, () -> retainedLayer.get().get(-2, -60, -3));
}
@Test
void placementDependenciesStayInTheirOwnGraphAndRejectConflicts() {
var first = new PlacementModifier() { public String id() { return "test:first"; } };
var second = new PlacementModifier() {
public String id() { return "test:second"; }
public Dependencies depends() { return Dependencies.requires("test:first"); }
};
assertEquals(List.of(ResourceId.parse("test:first"), ResourceId.parse("test:second")),
PlacementPipeline.resolve(List.of(configured(second), configured(first))).ordered().stream().map(ConfiguredPlacementModifier::id).toList());
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(second))));
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(first), configured(first))));
}
@Test
void mappedWritesOutsideReachFailBeforeMutationAndEachHookKeepsItsOwnReach() {
var moved = new PlacementModifier() {
public String id() { return "test:moved"; }
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
return Optional.of(new PlacedBlock(block.position().add(new BlockPosition(8, 0, 0)), block.state(), block.blockEntity()));
}
};
var edit = new RecordingEdit(new ArrayList<>());
assertThrows(IndexOutOfBoundsException.class, () -> PlacementPipeline.resolve(List.of(configured(moved)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, edit.mutations);
var large = new PlacementModifier() {
public String id() { return "test:large"; }
public int writeRadius() { return 2; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
assertEquals(AIR, access.get(0, -60, -3));
assertEquals(new BlockBox(-5, -64, -5, 1, 320, 0), access.mantle().bounds());
assertNull(access.mantle().layer(new MantleKey<>("test:owner", String.class))
.get(0, -60, -3));
}
};
var small = new PlacementModifier() {
public String id() { return "test:small"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
assertThrows(IndexOutOfBoundsException.class, () -> access.get(0, -60, -3));
assertEquals(new BlockBox(-3, -64, -3, -1, 320, -2), access.mantle().bounds());
assertThrows(IndexOutOfBoundsException.class, () -> access.mantle()
.layer(new MantleKey<>("test:owner", String.class)).get(0, -60, -3));
}
};
assertTrue(PlacementPipeline.resolve(List.of(configured(small), configured(large)))
.place(request(), new RecordingEdit(new ArrayList<>()), ignored -> TestContexts.placement(), ignored -> true).isPresent());
}
/** In-memory transactional test adapter; production storage/persistence is deliberately absent. */
private static class RecordingEdit implements PlacementEdit {
final List<String> events;
final Map<BlockPosition, BlockState> pending = new HashMap<>();
final Map<BlockPosition, BlockState> published = new HashMap<>();
final List<PlacedMarker> pendingMarkers = new ArrayList<>();
final List<PlacedMarker> publishedMarkers = new ArrayList<>();
boolean closed;
boolean failCommit;
int mutations;
RecordingEdit(List<String> events) { this.events = events; }
private void checkOpen() { if (closed) throw new IllegalStateException("Closed edit"); }
public BlockBox bounds() { checkOpen(); return new BlockBox(-16, -64, -16, 16, 320, 16); }
public BlockState get(int x, int y, int z) { checkOpen(); return pending.getOrDefault(new BlockPosition(x, y, z), AIR); }
public void set(PlacedBlock block) { checkOpen(); mutations++; events.add("write"); pending.put(block.position(), block.state()); }
public void marker(PlacedMarker marker) { checkOpen(); mutations++; events.add("marker"); pendingMarkers.add(marker); }
public Mantle mantle() {
checkOpen();
return new Mantle() {
public BlockBox bounds() { return RecordingEdit.this.bounds(); }
public MantleEdit edit() { throw new UnsupportedOperationException(); }
public <T> MantleLayer<T> layer(MantleKey<T> key) {
return new MantleLayer<>() {
public T get(int x, int y, int z) { checkOpen(); return null; }
public void set(int x, int y, int z, T value) { throw new AssertionError("Unused mantle mutation"); }
public void remove(int x, int y, int z) { throw new AssertionError("Unused mantle mutation"); }
public void clear(BlockBox area) { throw new AssertionError("Unused mantle mutation"); }
public void visit(BlockBox area, MantleVisitor<T> visitor) { checkOpen(); }
};
}
};
}
public void commit() {
checkOpen();
if (failCommit) throw new IllegalStateException("Commit failed");
events.add("commit"); published.putAll(pending); publishedMarkers.addAll(pendingMarkers); closed = true;
}
public void close() {
if (!events.contains("close")) events.add("close");
closed = true; pending.clear(); pendingMarkers.clear();
}
}
}
@@ -0,0 +1,50 @@
package com.volmit.mantle;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class MantleValueTest {
@Test
void boundsUseWorldCoordinatesAndExclusiveMaximum() {
var box = new BlockBox(-16, -64, -16, 16, 320, 16);
assertTrue(box.contains(-16, -64, -16));
assertTrue(box.contains(15, 319, 15));
assertFalse(box.contains(16, 0, 0));
assertFalse(box.contains(0, 320, 0));
assertFalse(box.contains(0, 0, 16));
assertFalse(box.contains(0, -65, 0));
assertTrue(box.contains(box));
assertTrue(box.contains(new BlockBox(0, 0, 0, 1, 1, 1)));
assertFalse(box.contains(new BlockBox(-17, 0, 0, 1, 1, 1)));
assertThrows(NullPointerException.class, () -> box.contains(null));
}
@Test
void rejectsInversionButAllowsEmptyBounds() {
assertThrows(IllegalArgumentException.class, () -> new BlockBox(1, 0, 0, 0, 1, 1));
assertThrows(IllegalArgumentException.class, () -> new BlockBox(0, 1, 0, 1, 0, 1));
assertThrows(IllegalArgumentException.class, () -> new BlockBox(0, 0, 1, 1, 1, 0));
assertFalse(new BlockBox(0, 0, 0, 0, 0, 0).contains(0, 0, 0));
var extremes = new BlockBox(Integer.MIN_VALUE, -64, 0, Integer.MAX_VALUE, 320, 1);
assertTrue(extremes.contains(Integer.MIN_VALUE, 0, 0));
}
@Test
void keysSeparateSameTypedLayersAndHaveValueEquality() {
var owner = new MantleKey<>("example:object-owner", String.class);
assertEquals(owner, new MantleKey<>("example:object-owner", String.class));
assertNotEquals(owner, new MantleKey<>("example:quest/location", String.class));
assertNotEquals(owner, new MantleKey<>("example:object-owner", Integer.class));
}
@Test
void rejectsInvalidKeys() {
for (String id : new String[]{"", "owner", ":owner", "example:", "Example:owner", "a:b:c", "a: b"}) {
assertThrows(IllegalArgumentException.class, () -> new MantleKey<>(id, String.class));
}
assertThrows(NullPointerException.class, () -> new MantleKey<>(null, String.class));
assertThrows(NullPointerException.class, () -> new MantleKey<>("a:b", null));
assertThrows(IllegalArgumentException.class, () -> new MantleKey<>("a:b", int.class));
}
}
@@ -0,0 +1,45 @@
package com.volmit.support;
import com.volmit.config.FeatureSettings;
import com.volmit.generation.GenerationContext;
import com.volmit.mantle.Mantle;
import com.volmit.object.ObjectTransformer;
import com.volmit.placement.PlacementContext;
import com.volmit.resource.PackResources;
import com.volmit.world.TerrainSampler;
import com.volmit.world.BlockView;
import java.util.Random;
import java.util.random.RandomGenerator;
/** Tests needing no platform facilities fail loudly if code starts using one. */
public final class TestContexts {
private TestContexts() {}
public static GenerationContext generation() {
return new GenerationContext() {
private final RandomGenerator random = new Random(42);
public int originX() { return 0; }
public int originY() { return -64; }
public int originZ() { return 0; }
public long worldSeed() { return 42; }
public RandomGenerator random() { return random; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
public Mantle mantle() { throw new AssertionError("Unused mantle"); }
};
}
public static PlacementContext placement() {
return new PlacementContext() {
private final RandomGenerator random = new Random(42);
public long worldSeed() { return 42; }
public RandomGenerator random() { return random; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
public ObjectTransformer objects() { throw new AssertionError("Unused transforms"); }
public BlockView blocks() { throw new AssertionError("Unused blocks"); }
};
}
}