mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 16:25:36 +00:00
Baseline IrisApi draft before stage-graph redesign
This commit is contained in:
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 {}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user