Merge IrisApi into api/ with its history

git-subtree-dir: api
git-subtree-mainline: cff15f93c5
git-subtree-split: dac8baa3ab
This commit is contained in:
piexel committed 2026-11-06 16:52:54 +01:00
commit 925c942764
365 files changed
+29228

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
// The module API (com.volmit and its subpackages except com.volmit.host). Modules compile against this artifact only.
base {
archivesName.set("iris-api")
}
@@ -0,0 +1,68 @@
package com.volmit;
import com.volmit.data.SavedKey;
import com.volmit.data.StorageCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.resource.ResourceKind;
import com.volmit.service.Service;
import com.volmit.stage.StageGraph;
import com.volmit.validation.Validator;
import java.util.Set;
/** Host implementation collects non-stage registrations before loading pack configuration.
* Feature IDs must be unique. JSON keys must be unique per {@link com.volmit.config.Level}, including the
* settings types stages name in {@code when(...)}. Feature IDs, mantle keys, saved keys and resource kind ids a module
* registers are its module id or start with it and {@code /}, such as {@code iris:snow} or {@code iris:snow/depth}.
*/
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, StorageCodec<T> codec);
/** Registers a value the module keeps with each running world across restarts, so
* {@link com.volmit.world.RunningWorld#saved} serves it; that method throws IllegalArgumentException for a key
* nobody registered. Null arguments throw NullPointerException; a duplicate id throws IllegalArgumentException.
*/
void registerSaved(SavedKey<?> key);
/** Catalogs a settings type that no stage names in {@code when(...)}, such as one read only
* through {@link com.volmit.config.FeatureSettings#at}, so the host decodes it and studio
* describes it: {@code registerSettings(WindSettings.class)}. Settings that a stage names are
* catalogued without this; registering them as well changes nothing. The type's feature id must
* be this module's id or start with it and {@code /}. Once registered, other modules may name
* the type in {@code when(...)} (see {@link StageGraph}).
*/
void registerSettings(Class<? extends IrisFeature> settingsType);
/** Declares a kind of pack resource this module reads: the JSON files under the kind's folder, served through
* {@link com.volmit.resource.PackResources} by the kind's type and described for studio from its class like
* settings. The pack load fails when another kind has the same id, type or folder, or the folder is one the
* host reads itself; the error names both owners.
*/
<T> void registerResourceKind(ResourceKind<T> kind);
/**
* Declares the type packs write their object placements as, the JSON object that holds
* {@link com.volmit.config.Level#PLACEMENT}: settings other modules declare on a placement are keys of that same
* object, next to the type's own fields. So no settings key at that level may be one of {@code jsonFields}, the
* names the type's JSON uses, and studio describes {@code type} with those settings added. A pack has one placement
* type; a second declaration, from this module or another, fails the pack load naming both.
*/
void registerPlacementType(Class<?> type, Set<String> jsonFields);
/** Adds a check the host runs over the whole pack wherever it validates packs. */
void registerValidator(Validator validator);
/** Adds hooks the host calls when it loads the pack and starts or stops a world with it. */
void registerLifecycle(ModuleLifecycle lifecycle);
/** Provides {@code service}, an interface marked {@link Service}, with {@code provider}. A service whose providers
* are {@link com.volmit.service.Providers#ONE} fails the pack load when a second module provides it, naming both.
*/
<S> void registerService(Class<S> service, S provider);
}
@@ -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,18 @@
package com.volmit;
/** A unit of world-generation behavior. The core engine is an ordinary module too.
*
* <p>In a pack's module jar this class is the entry point. The jar names it in
* {@code META-INF/services/com.volmit.IrisModule}, one entry class per line, and it needs a public no-argument
* constructor. A jar holds one or more modules.
*/
public interface IrisModule {
ModuleInfo info();
/** Defines this module's stages and registers its other contributions (geometry generators, mantle layers,
* settings no stage names, pack resource kinds, validators, lifecycle hooks and services) and its studio views
* ({@link ModuleSetup#tooling()}), before settings are decoded or generation starts. Called once per pack load, in any order relative to other modules; stage bodies
* must not capture per-invocation state.
*/
void setup(ModuleSetup setup);
}
@@ -0,0 +1,77 @@
package com.volmit;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Module identity. Every stage a module defines has an id that starts with the module id and
* {@code /}, such as {@code iris:stilt/fill} for module {@code iris:stilt}, so a module id has no
* {@code /} of its own: {@code iris:stilt/extra} would own stages under {@code iris:stilt}'s path.
* Settings ids, object feature ids and mantle keys the module owns are its id or start with it and
* {@code /}, such as {@code iris:stilt} or {@code iris:stilt/depth}. The name is for
* people, for example in load logs; the id is what the host and other modules match on. Name and
* version must fit on one log line, so they reject control characters such as line breaks.
*
* <p>What the module's jar needs at load, such as packages it expects may be missing, is the jar's, declared in its
* manifest (see README, "Optional packages"), not the module's identity.
*/
public record ModuleInfo(ResourceId id, String name, String version) {
private static final String STAGE_SEPARATOR = "/";
public ModuleInfo {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(name, "name");
Objects.requireNonNull(version, "version");
requireSingleSegment(id);
requireOneLineText(id, "name", name);
requireOneLineText(id, "version", version);
}
public static ModuleInfo of(String id, String name, String version) {
return new ModuleInfo(ResourceId.parse(id), name, version);
}
/** Whether {@code stageId} may name a stage of this module: it starts with this module's id and '/'. */
public boolean ownsStage(ResourceId stageId) {
return stageId.namespace().equals(id.namespace()) && stageId.path().startsWith(childPathPrefix());
}
/** Whether {@code featureId} may name settings, an object generator or a mantle layer of this
* module: it is this module's id or starts with it and '/'.
*/
public boolean ownsId(ResourceId featureId) {
return featureId.equals(id) || ownsStage(featureId);
}
/** What every stage id of this module, and every other id below it, starts with, such as {@code iris:stilt/}. */
public String idPrefix() {
return id.namespace() + ":" + childPathPrefix();
}
private String childPathPrefix() {
return id.path() + STAGE_SEPARATOR;
}
private static void requireSingleSegment(ResourceId id) {
if (!id.path().contains(STAGE_SEPARATOR)) return;
throw new IllegalArgumentException("Module id " + id + " must not contain '" + STAGE_SEPARATOR
+ "': stage ids are a module id, '" + STAGE_SEPARATOR + "' and a name, so " + id
+ " would name stages under another module's id");
}
private static void requireOneLineText(ResourceId id, String field, String value) {
if (value.isBlank()) {
throw new IllegalArgumentException("Blank module " + field + ": " + id);
}
if (value.chars().anyMatch(ModuleInfo::breaksLogLine)) {
throw new IllegalArgumentException("Module " + field + " of " + id
+ " contains a line break or other control character");
}
}
private static boolean breaksLogLine(int character) {
var type = Character.getType(character);
return Character.isISOControl(character)
|| type == Character.LINE_SEPARATOR
|| type == Character.PARAGRAPH_SEPARATOR;
}
}
@@ -0,0 +1,47 @@
package com.volmit;
import com.volmit.world.PackWorld;
/** What a module does when the host loads a pack and starts or stops a world with it. Every hook does nothing by
* default. Modules register it with {@link FeatureRegistry#registerLifecycle}; a module class may implement it and
* register itself.
*
* <p>Order: {@link #packLoaded} for a pack snapshot before the first world using it starts, then
* {@link #worldStarted} before that world generates anything, then {@link #warmUp} (a slow worldStarted the host may
* run off the main thread), and {@link #worldStopped} when it stops. A hotload, or a
* reload of the pack's resources while worlds run, stops each world of the old snapshot, loads the new snapshot and
* starts its worlds again, with empty state (see {@link PackWorld}). The host calls the hooks of a pack's modules in
* module id order and stops them in reverse, one hook at a time, on the thread that starts or stops the world.
*
* <p>Hooks keep what they build in the world's state ({@link PackWorld#state}), never in fields: a module instance may
* serve several packs and worlds at once.
*/
public interface ModuleLifecycle {
/** The pack's modules are set up and its resources can be read: {@code pack} gives the resources, every settings
* entry of every dimension, region and biome of the pack (as validators see them) and the module's log. A hook that
* throws stops the pack's worlds from starting, naming its module.
*/
default void packLoaded(PackContext pack) {}
/** {@code world} starts, before it generates anything: the place to build state eagerly, such as caches a world
* would otherwise build on its first chunk. A hook that throws stops the world from starting, naming its module; the
* modules that had started it already get {@link #worldStopped}.
*/
default void worldStarted(PackWorld world) {}
/** {@code world} started: builds the caches that make its first chunks fast, which may be slow. Runs after
* {@link #worldStarted} of every module. The host may run it off the main thread: synchronously for a server's
* worlds, in the background for studio. It waits for every module's warm-up before the world's first generation, so
* a hook that is slow delays that, not the start of the world. A world that stops before its warm-up runs may skip it.
*
* <p>Only build caches in the module's world state ({@link PackWorld#state}): nothing here may change what the world
* generates, because the module also works when the warm-up never ran. A hook that throws does not stop the world;
* the host reports the failure, naming the module, and the cache is built when first needed.
*/
default void warmUp(PackWorld world) {}
/** {@code world} stops: it generates nothing more with this pack snapshot. Its state is still readable here and is
* closed afterwards. The host runs every module's hook even when one throws, then reports the failures.
*/
default void worldStopped(PackWorld world) {}
}
@@ -0,0 +1,39 @@
package com.volmit;
/** The log of one module. The host labels every line with the module's id, such as {@code [iris:decorant]}, and writes it
* to its own log, so a module never needs a logging library of its own and its lines are easy to find. Each module has
* its own: reach it as {@code context.log()} in stage bodies and generators
* ({@link com.volmit.generation.InvocationContext#log}), as {@link com.volmit.world.PackWorld#log} in services and
* lifecycle hooks, and as {@link ModuleSetup#log} during the module's setup.
*
* <p>Safe to use from any thread. A message is plain text, not a format string.
*/
public interface ModuleLog {
/** Detail for people debugging the module. The host writes it only when its debug setting is on, so building the
* message costs time even when nobody reads it: guard a message that is expensive to build with {@link #debugging()},
* or leave it out.
*/
void debug(String message);
/** Whether {@link #debug} lines are written now, so a module can skip building them, or skip work done only to trace. */
boolean debugging();
/** Something worth telling the server owner once in a while, such as what the module did at startup. */
void info(String message);
/** Something is wrong or unusual, but the module carries on. */
void warn(String message);
/** Warns the first time {@code key} is used on this log and writes {@code message} at {@link #debug} level every
* time after, for a condition worth stating once that is met per block, per sample or per chunk. Keys belong to the
* module: two modules can use the same key and each warns once. The key space must be bounded, so never put a
* coordinate in it; the host stops claiming new keys beyond a few hundred and then only debugs.
*/
void warnOnce(String key, String message);
/** Logs {@code message} as an error and reports {@code cause} the way the host reports its own failures, such as
* to its error tracker. Use it for a failure the module caught but cannot recover from. A null {@code cause}
* only logs the message.
*/
void error(String message, Throwable cause);
}
@@ -0,0 +1,19 @@
package com.volmit;
import com.volmit.stage.StageGraph;
import com.volmit.tooling.ToolingRegistry;
/** What a module gets in {@link IrisModule#setup}: the stage graph it defines its stages in, the registry for
* everything else it adds to generation, the registry for its studio tools, and its own log. Stages and registrations
* are accepted only while {@code setup} runs; the log may be kept and used later, such as from lifecycle hooks.
*/
public interface ModuleSetup {
StageGraph stages();
FeatureRegistry registry();
ToolingRegistry tooling();
/** This module's log, the same one its stages and lifecycle hooks see through their world. */
ModuleLog log();
}
@@ -0,0 +1,18 @@
package com.volmit;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
/** A pack snapshot the host loaded, as {@link ModuleLifecycle#packLoaded} sees it. Do not retain it after the hook
* returns: what a module builds from it for a world belongs in that world's state.
*/
public interface PackContext {
/** The snapshot's resources. */
PackResources resources();
/** Every settings entry of every dimension, region and biome of the pack, as validators see them. */
PackSettings settings();
/** The log of the module the hook belongs to, labelled with its id. */
ModuleLog log();
}
@@ -0,0 +1,88 @@
package com.volmit.block;
import com.volmit.geometry.BlockFace;
import com.volmit.object.BlockEntityData;
import com.volmit.resource.ResourceId;
import java.util.Optional;
/** What the platform knows about blocks, for one pack snapshot. No native platform objects escape. Methods are safe for
* concurrent generation calls; predicates must not read the live world.
*
* <p>Two ways to get a state: {@link #resolve(BlockSpec)} reads a block the way packs write it (a custom block of the
* pack, a backup, never failing), {@link #find(String)} asks the platform for exactly one block. Both answer complete
* states, with every property the platform gives the block, like the states the host hands out; compare against those.
*
* <p>A content plugin's block ({@link BlockTrait#CUSTOM}) has the key of the block it is drawn as. The host knows it by
* the state instance it handed out, from this registry or from a block it read, so pass that instance on as it is, and
* change it through {@link #withPropertyIfAccepted}, {@link #rotate} and {@link #merge}: a state built from the key is the plain
* block.
*/
public interface BlockRegistry {
/** The state {@code spec} names, resolved the way packs expect, so it never throws for a block the platform lacks:
* a block of the pack's {@code blocks} folder with the spec's properties over its own, else the platform's block
* (a key without a namespace is {@code minecraft:}) with the spec's properties, else the backup resolved the same
* way, else air.
*/
BlockState resolve(BlockSpec spec);
/** The platform's block {@code key}, such as {@code minecraft:lava} or {@code minecraft:oak_log[axis=y]}, with the
* properties the key leaves out at the platform's defaults; empty when the platform has no such block or property.
* For a module that must know whether the platform has a block, unlike {@link #resolve(BlockSpec)}.
*/
Optional<BlockState> find(String key);
/** The block entity {@code spec}'s {@code tileData} describes, in the host's format; empty when the spec has none
* or its resolved block has no block entity.
*/
Optional<BlockEntityData> blockEntity(BlockSpec spec);
/** The picker for {@code spec}: every block counts as often as its weight, and the entry at a position is chosen by
* the style's noise at (x, y, z) divided by the zoom, so the palette changes smoothly over the world; a palette of
* one block always gives it. Blocks resolve as {@link #resolve(BlockSpec)}. Seed the noise like
* {@link com.volmit.noise.NoiseFactory#sampler}: from the world seed when the palette must line up across chunks.
* The host keeps what it builds for the pack snapshot, so asking again for the same palette and seed is cheap.
*
* @throws IllegalArgumentException when no block of the palette has a weight above zero, which includes an empty list
*/
PaletteSampler palette(PaletteSpec spec, long seed);
/** The ore that suits the {@code rock} it is placed in, which the platform decides: an ore placed in deepslate is its
* deepslate variant, one placed in other rock its ordinary one; {@code ore} itself when it has no variant.
*/
BlockState oreFor(BlockState rock, BlockState ore);
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);
/** Whether {@code state} can stand on {@code below}: the support rule the host checks before it writes a
* decoration, such as a flower on grass but not on stone. Only the kinds of block count, not their properties.
*/
boolean canPlaceOn(BlockState state, BlockState below);
/**
* {@code state} turned with an object: every direction the block faces (its facing, axis, connections, or the
* sixteen directions of a sign) is moved by {@code turn}, as the platform turns stairs, logs, walls and wires. A
* block without directions comes back unchanged; air when the block cannot face the way it is turned.
*/
BlockState rotate(BlockState state, BlockTurn turn);
/** {@code update} laid over {@code base}: the platform's merge of two states of one block, such as the sides of a
* fence, wall or pane; {@code update} when the platform does not merge them.
*/
BlockState merge(BlockState base, BlockState update);
/** {@code state} with the property {@code name} set to {@code value}, as the platform sets it. Unlike
* {@link BlockState#withProperty} it keeps a content plugin's block itself ({@link BlockTrait#CUSTOM}): such a block
* shares its key with the block it is drawn as, so only the state instance the registry handed out knows it.
* {@code state} itself when the block has no property {@code name} or does not accept {@code value}, such as a
* {@code facing} of {@code up} for a block that only faces sideways.
*/
BlockState withPropertyIfAccepted(BlockState state, String name, String value);
/** Whether {@code state} matches {@code pattern} as the platform compares them: the same block, and every property
* {@code pattern} sets equal.
*/
boolean matches(BlockState state, BlockState pattern);
}
@@ -0,0 +1,121 @@
package com.volmit.block;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
import com.volmit.config.Ref;
import com.volmit.config.Reference;
import com.volmit.config.Required;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/** A block as packs write it in settings, such as {@code {"block": "iron_ore"}} or
* {@code {"block": "minecraft:oak_log", "data": {"axis": "y"}, "backup": {"block": "stone"}}}. Settings hold it
* where a pack picks a block it may not be able to name exactly: a key without a namespace, a custom block of
* the pack's {@code blocks} folder, or a block that only some versions or mods have.
*
* <p>The host resolves it with {@link BlockRegistry#resolve(BlockSpec)} and its block entity with
* {@link BlockRegistry#blockEntity(BlockSpec)}. A spec is a value the host decodes as every settings class (see
* DESIGN.md, "Decoding contract"), and nothing changes it afterwards. Property values are text however the
* pack writes them, so {@code "waterlogged": true} reads as {@code "true"}.
*/
@Desc("A block, with optional properties, block entity data and a backup for platforms without it")
public final class BlockSpec {
private static final String AIR = "air";
@Required
@Ref(Reference.BLOCK)
@Desc("The block to use. A key without a namespace is a Minecraft block or a block of the pack's blocks folder.")
private String block = AIR;
@Desc("The block's properties, such as \"waterlogged\": true.")
private Map<String, String> data = Map.of();
@MinNumber(1)
@MaxNumber(1000)
@Desc("The weight of this block in a list it is picked from. A weight of two is as if the block were in the list twice.")
private int weight = 1;
@Desc("The block used instead on a platform that does not have this one.")
private BlockSpec backup;
@Desc("The block entity data, such as a spawner's SpawnData.")
private Map<String, Object> tileData = Map.of();
private BlockSpec() {
}
private BlockSpec(String block, Map<String, String> data, int weight, BlockSpec backup, Map<String, Object> tileData) {
this.block = Objects.requireNonNull(block, "block");
this.data = Map.copyOf(data);
this.weight = weight;
this.backup = backup;
this.tileData = Collections.unmodifiableMap(new LinkedHashMap<>(tileData));
}
/** The block {@code block}, such as {@code minecraft:stone} or {@code stone}, without properties, weight 1. */
public static BlockSpec of(String block) {
return new BlockSpec(block, Map.of(), 1, null, Map.of());
}
/** This spec with the property {@code name} set to {@code value}. */
public BlockSpec withProperty(String name, String value) {
var changed = new LinkedHashMap<>(data());
changed.put(name, value);
return new BlockSpec(block, changed, weight, backup, tileData());
}
public BlockSpec withWeight(int weight) {
return new BlockSpec(block, data(), weight, backup, tileData());
}
public BlockSpec withBackup(BlockSpec backup) {
return new BlockSpec(block, data(), weight, backup, tileData());
}
public BlockSpec withTileData(Map<String, Object> tileData) {
return new BlockSpec(block, data(), weight, backup, tileData);
}
/** The block key as the pack wrote it. */
public String block() {
return block;
}
/** The properties as the pack wrote them, as text. */
public Map<String, String> data() {
return Collections.unmodifiableMap(data);
}
public int weight() {
return weight;
}
public Optional<BlockSpec> backup() {
return Optional.ofNullable(backup);
}
/** The block entity data as the pack wrote it: JSON objects as maps, arrays as lists, numbers as {@code Double}. */
public Map<String, Object> tileData() {
return Collections.unmodifiableMap(tileData);
}
@Override
public boolean equals(Object other) {
return other instanceof BlockSpec spec && block().equals(spec.block()) && data().equals(spec.data())
&& weight == spec.weight && Objects.equals(backup, spec.backup) && tileData().equals(spec.tileData());
}
@Override
public int hashCode() {
return Objects.hash(block(), data(), weight, backup, tileData());
}
@Override
public String toString() {
return "BlockSpec[" + block() + (data().isEmpty() ? "" : " " + data()) + "]";
}
}
@@ -0,0 +1,109 @@
package com.volmit.block;
import com.volmit.resource.ResourceId;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/** Immutable, platform-neutral block description with value equality.
* Construction validates syntax, not platform availability or valid material properties. Custom-content IDs are
* allowed. A state may be written as it is: the host gives the properties it leaves out the platform's defaults. The
* states the host hands out (from the world, a hunk, {@link BlockRegistry}) are complete, with every property, so a
* module compares them with a complete state, which {@link BlockRegistry#find} or {@link BlockRegistry#resolve} give.
*/
public record BlockState(ResourceId material, Map<String, String> properties) {
private static final String PROPERTIES_START = "[";
private static final String PROPERTIES_END = "]";
private static final String PROPERTY_SEPARATOR = ",";
private static final Pattern PROPERTY_NAME = Pattern.compile("[a-z0-9_]+");
private static final Pattern PROPERTY_VALUE = Pattern.compile("[a-z0-9_.-]+");
public BlockState {
Objects.requireNonNull(material, "material");
if (!(properties instanceof CheckedProperties)) {
var copy = new TreeMap<String, String>();
properties.forEach((name, value) -> copy.put(requireValid(name, value), value));
properties = new CheckedProperties(copy);
}
}
public BlockState(String material) { this(ResourceId.parse(material), Map.of()); }
/** Reads what {@link #key()} writes: {@code minecraft:oak_log} or {@code minecraft:oak_log[axis=y]}. */
public static BlockState parse(String key) {
Objects.requireNonNull(key, "key");
int open = key.indexOf(PROPERTIES_START);
if (open < 0) return new BlockState(key);
if (!key.endsWith(PROPERTIES_END)) throw new IllegalArgumentException("Unclosed block properties: " + key);
var properties = new TreeMap<String, String>();
var list = key.substring(open + 1, key.length() - 1);
for (var property : list.isEmpty() ? new String[0] : list.split(PROPERTY_SEPARATOR, -1)) {
int equals = property.indexOf('=');
if (equals < 0) throw new IllegalArgumentException("Block property without value: " + property + " in " + key);
if (properties.put(property.substring(0, equals), property.substring(equals + 1)) != null) {
throw new IllegalArgumentException("Block property set twice: " + property + " in " + key);
}
}
return new BlockState(ResourceId.parse(key.substring(0, open)), properties);
}
/** This state with {@code name} set to {@code value}. Copies the properties once and checks only the new one. */
public BlockState withProperty(String name, String value) {
var changed = new TreeMap<>(properties);
changed.put(requireValid(name, value), value);
return new BlockState(material, new CheckedProperties(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(PROPERTY_SEPARATOR, PROPERTIES_START, PROPERTIES_END));
}
/** Returns {@code name} once it and {@code value} are a valid property. */
private static String requireValid(String name, String value) {
if (name == null || value == null) throw new NullPointerException("Block property");
if (!PROPERTY_NAME.matcher(name).matches() || !PROPERTY_VALUE.matcher(value).matches()) {
throw new IllegalArgumentException("Invalid block property: " + name + "=" + value);
}
return name;
}
/** Validated properties in key order that nobody can change. Only this class makes them, so the constructor takes
* them as they are instead of checking and copying them again.
*/
private static final class CheckedProperties extends AbstractMap<String, String> {
private final Map<String, String> sorted;
private CheckedProperties(TreeMap<String, String> sorted) {
this.sorted = Collections.unmodifiableMap(sorted);
}
@Override
public Set<Entry<String, String>> entrySet() {
return sorted.entrySet();
}
@Override
public String get(Object key) {
return sorted.get(key);
}
@Override
public boolean containsKey(Object key) {
return sorted.containsKey(key);
}
@Override
public int size() {
return sorted.size();
}
}
}
@@ -0,0 +1,10 @@
package com.volmit.block;
/** What a block is, as the platform answers it ({@link BlockRegistry#hasTrait}); tags name further groups
* ({@link BlockRegistry#inTag}). {@code VINE} is a block that hangs from or clings to the faces around it, such as
* vines and glow lichen; {@code STORAGE} a chest-like container that keeps items, such as a chest or a barrel;
* {@code CUSTOM} a block of a content plugin or mod rather than of the platform itself.
*/
public enum BlockTrait {
AIR, SOLID, OCCLUDING, FLUID, WATER, GRAVITY, FOLIAGE, DECORATION, VINE, LOG, LEAVES, ORE, STORAGE, CUSTOM
}
@@ -0,0 +1,15 @@
package com.volmit.block;
/**
* How an object's rotation moves a direction its blocks face ({@link BlockRegistry#rotate}). A direction is a vector
* such as (0, 0, -1) for north, or (1, 0, -2) for one of a sign's sixteen; the turned vector need not be whole, and the
* platform takes the direction closest to it.
*/
@FunctionalInterface
public interface BlockTurn {
Direction turn(double x, double y, double z);
/** A direction vector. */
record Direction(double x, double y, double z) {
}
}
@@ -0,0 +1,10 @@
package com.volmit.block;
/** The block a {@link PaletteSpec} picks at a position, built by the host ({@link BlockRegistry#palette}). The
* coordinates are the noise's input and follow the API's coordinate rule: world X and Z, and Y as the height above the
* dimension's bottom (0 = bottom block). The same position always gives the same block. Safe for concurrent calls.
*/
@FunctionalInterface
public interface PaletteSampler {
BlockState at(double x, double y, double z);
}
@@ -0,0 +1,94 @@
package com.volmit.block;
import com.volmit.config.Desc;
import com.volmit.config.MinItems;
import com.volmit.config.MinNumber;
import com.volmit.config.Required;
import com.volmit.config.Snippet;
import com.volmit.noise.NoiseStyle;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/** A palette of blocks as packs write it in settings, such as
* {@code {"style": "SIMPLEX", "zoom": 8, "palette": [{"block": "stone"}, {"block": "andesite", "weight": 2}]}}, or a
* snippet under {@code snippet/palette/}. The blocks are picked by noise: the host picks the entry the style's noise
* at the position over {@code zoom} selects, each block counting {@link BlockSpec#weight() weight} times.
*
* <p>A palette is a description, not a picker: the host builds the picker
* ({@link BlockRegistry#palette(PaletteSpec, long)}). It is a value the host decodes as every settings class (see
* DESIGN.md, "Decoding contract"); nothing changes it afterwards.
*/
@Snippet("palette")
@Desc("Blocks picked by noise, each as often as its weight")
public final class PaletteSpec {
private static final String DEFAULT_STYLE = "STATIC";
private static final double DEFAULT_ZOOM = 5;
private static final String DEFAULT_BLOCK = "stone";
@Desc("The noise that picks the block at each position.")
private NoiseStyle style = NoiseStyle.of(DEFAULT_STYLE);
@MinNumber(0.0001)
@Desc("How far the picking noise is stretched: above 1 gives larger patches of one block.")
private double zoom = DEFAULT_ZOOM;
@Required
@MinItems(1)
@Desc("The blocks to pick from.")
private List<BlockSpec> palette = List.of(BlockSpec.of(DEFAULT_BLOCK));
private PaletteSpec() {
}
private PaletteSpec(NoiseStyle style, double zoom, List<BlockSpec> palette) {
this.style = Objects.requireNonNull(style, "style");
this.zoom = zoom;
this.palette = List.copyOf(palette);
}
/** A palette of {@code blocks} with the default style and zoom. */
public static PaletteSpec of(List<BlockSpec> blocks) {
return new PaletteSpec(NoiseStyle.of(DEFAULT_STYLE), DEFAULT_ZOOM, blocks);
}
public PaletteSpec withStyle(NoiseStyle style) {
return new PaletteSpec(style, zoom, palette());
}
/** This palette with zoom {@code zoom}: above 1 stretches the noise that picks the blocks, below 1 squeezes it. */
public PaletteSpec withZoom(double zoom) {
return new PaletteSpec(style(), zoom, palette());
}
/** The noise that picks the blocks; the default {@code STATIC} style where the pack wrote none. */
public NoiseStyle style() {
return style;
}
/** The factor the position is divided by before it is looked up in the noise. */
public double zoom() {
return zoom;
}
/** The blocks to pick from, as the pack wrote them. */
public List<BlockSpec> palette() {
return Collections.unmodifiableList(palette);
}
@Override
public boolean equals(Object other) {
return other instanceof PaletteSpec spec && style().equals(spec.style())
&& Double.compare(zoom, spec.zoom) == 0 && palette().equals(spec.palette());
}
@Override
public int hashCode() {
return Objects.hash(style(), zoom, palette());
}
@Override
public String toString() {
return "PaletteSpec[" + palette() + ", " + style() + ", zoom " + zoom + "]";
}
}
@@ -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,28 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Identity and JSON attachment for an IrisFeature configuration class. The {@code id}, such as
* {@code "example:moss"}, is the feature's identity in the stage graph, logs and lookups by class. Packs write
* the settings under the short {@code key}, such as {@code "moss": {...}}, at each of the targets, the {@link Level}s
* of a pack's dimension, region, biome or object placement files.
*
* <p>The key is a plain JSON field name: not blank, no ':'. It is unique per target across all loaded modules
* and the JSON fields the host itself uses at that target, so it must not be a field of a biome, region or
* dimension; a clash refuses the pack load, naming both claimants.
*
* <p>The JSON under the key is an object of the class's options, unless {@code root} names an option. Then the
* key holds exactly that option's value, such as a list, and an object is not accepted: with
* {@code @Feature(id = "iris:deposit", key = "deposits", root = "generators", ...)} a pack writes
* {@code "deposits": [...]}. The class has no other option then, since nothing could set it.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Feature {
String id();
String name();
String key();
String root() default "";
/** The levels packs may write the settings at. */
Level[] targets();
}
@@ -0,0 +1,73 @@
package com.volmit.config;
import com.volmit.IrisFeature;
import com.volmit.generation.ChunkContext;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
/** Invocation-scoped lookup of the settings that apply at one world column.
*
* <p>Every level that declares the settings contributes its own entry: the dimension, the region and
* the biome of the column, and in a placement the placement itself. Levels stack: nothing is merged or
* overridden, and a module decides what several entries mean, such as running a deposit once per
* entry. The biome is the column's surface biome; cave biomes are not a level. Values must be treated as
* read-only. Bounds and lifetime match the invocation's sampler.
*
* <p>Something that spans several columns, such as a chunk-wide pass or a placed object, reads the
* settings at one column it treats as its origin; per-chunk behaviour reads the chunk's centre column
* ({@link ChunkContext#centreX()}, {@link ChunkContext#centreZ()}).
*/
public interface FeatureSettings {
/** The entries of {@code featureType} at this column, in level order; empty when no level declares it. */
<F extends IrisFeature> SettingsStack<F> at(Class<F> featureType, int worldX, int worldZ);
/** Every distinct entry of {@code featureType} at the 16 by 16 columns of chunk {@code chunkX}, {@code chunkZ}, in
* level order; entries of one level in the order their first column was found, columns by X and then Z. Entries are
* distinct by level and source. The chunk and mantle runners decide with it whether a conditioned stage runs in a
* chunk. The default asks {@link #at} for every column; a host that knows which regions and biomes a chunk holds
* answers it from them.
*/
default <F extends IrisFeature> SettingsStack<F> declaredInChunk(Class<F> featureType, int chunkX, int chunkZ) {
var declarations = new HashSet<Declaration>();
var distinct = new ArrayList<Entry<F>>();
int originX = chunkX * ChunkContext.CHUNK_WIDTH;
int originZ = chunkZ * ChunkContext.CHUNK_WIDTH;
for (int x = 0; x < ChunkContext.CHUNK_WIDTH; x++) {
for (int z = 0; z < ChunkContext.CHUNK_WIDTH; z++) {
for (var entry : at(featureType, originX + x, originZ + z)) {
if (declarations.add(new Declaration(entry.level(), entry.source()))) {
distinct.add(entry);
}
}
}
}
return SettingsStack.of(distinct);
}
/** The settings {@code biome} declares itself, whichever column it is found at: for a biome that is not a column's
* surface biome, such as the cave biome of {@link com.volmit.world.BiomeSample#caveBiome()}, which is no level of
* {@link #at}. {@code biome} is an id as a {@code BiomeSample} gives it. Empty when the biome declares none, or the
* host knows no such biome.
*/
<F extends IrisFeature> Optional<F> declaredBy(ResourceId biome, Class<F> featureType);
/** One level's declaration of the settings.
*
* @param level where the settings are declared: the dimension, a region, a biome or the placement
* @param source the resource that declares them, such as {@code overworld:biome/desert/dunes}
* @param value the decoded settings
*/
record Entry<F extends IrisFeature>(Level level, ResourceId source, F value) {
public Entry {
Objects.requireNonNull(level, "level");
Objects.requireNonNull(source, "source");
Objects.requireNonNull(value, "value");
}
}
}
/** What makes two entries of a chunk the same declaration. */
record Declaration(Level level, ResourceId source) {}
@@ -0,0 +1,32 @@
package com.volmit.config;
import java.lang.annotation.*;
/**
* A settings value packs may write in more than one JSON shape, such as a number, a {@code [min, max]} range or an
* object. The host reads the JSON as plain values and hands it to {@link #value()}, and writes the value back
* through it; it does not read the class's fields, create it, or describe more of it than "any JSON value". A class
* without this annotation is read field by field (DESIGN.md, "Decoding contract").
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface JsonForms {
/** The codec, created by the host with its no-argument constructor. */
Class<? extends Codec<?>> value();
/**
* Reads and writes one class's JSON forms as plain values: {@code Map<String, Object>}, {@code List<Object>},
* {@code Double} for every number, {@code String} and {@code Boolean}.
*/
interface Codec<T> {
/**
* The value {@code json} writes; never null, since a member written as {@code null} counts as left out.
*
* @throws IllegalArgumentException when {@code json} is none of the forms, saying which forms there are
*/
T read(Object json);
/** {@code value} as plain values {@link #read} reads back as an equal value. */
Object write(T value);
}
}
@@ -0,0 +1,7 @@
package com.volmit.config;
/** Where a pack declares settings, from the least to the most specific: the dimension, a region, a biome, and an
* object placement. {@link Feature#targets()} names the levels a feature may be written at, and every
* {@link FeatureSettings.Entry} carries the level that declared it. Settings stacks keep this order.
*/
public enum Level { DIMENSION, REGION, BIOME, PLACEMENT }
@@ -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,12 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Inclusive lower bound on the length of a list, set or array option, such as a palette that needs a block. Studio
* shows it ({@code minItems}); like {@link MinNumber}, enforcement belongs to the configuration loader.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MinItems {
int value();
}
@@ -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,32 @@
package com.volmit.config;
import com.volmit.IrisFeature;
import com.volmit.resource.PackResources;
import java.util.Optional;
/** Every settings declaration of the pack the host is loading, for what depends on the whole pack rather
* than one column, such as how far a mantle stage reaches ({@link com.volmit.stage.PackReach}).
*
* <p>The levels are those chunk and mantle stages see: the dimension being generated, and every region
* and biome it can reach. Placements are not a level here. Values must be treated as read-only and not
* retained.
*/
public interface PackSettings {
/** Every entry of {@code featureType} the pack declares, dimension first, then regions, then biomes;
* empty when nothing declares it.
*/
<F extends IrisFeature> SettingsStack<F> declared(Class<F> featureType);
/** The pack snapshot the settings were read from, such as for a reach that depends on the size of the pack's objects. */
PackResources resources();
/**
* What the host offers for the pack it is loading beyond the API, as an object of {@code type}: empty when it offers
* no such thing. The same door as {@link com.volmit.world.PackWorld#extension}, for what is worked out from the
* settings before any world generates, such as a {@link com.volmit.stage.PackReach} that needs the size of the pack's
* objects from the host.
*/
default <T> Optional<T> extension(Class<T> type) {
return Optional.empty();
}
}
@@ -0,0 +1,68 @@
package com.volmit.config;
import com.volmit.random.WorldRandom;
import java.util.Objects;
/** A span of numbers from {@code min} to {@code max}, both included, as packs write it: {@code {"min": 0, "max": 15}},
* or a snippet under {@code snippet/range/}. An omitted bound keeps its default, so give a settings field its own
* default with {@link #of}. A value the host decodes as every settings class (see DESIGN.md, "Decoding contract").
*/
@Snippet("range")
@Desc("A span of numbers from min to max, both included")
public final class Range {
@Desc("The lowest value.")
private double min = 16;
@Desc("The highest value.")
private double max = 32;
private Range() {
}
private Range(double min, double max) {
this.min = min;
this.max = max;
}
public static Range of(double min, double max) {
return new Range(min, max);
}
public double min() {
return min;
}
public double max() {
return max;
}
/** Whether {@code value} lies between the bounds, both included. */
public boolean contains(double value) {
return value >= min && value <= max;
}
/** A number between the bounds drawn from {@code random}: {@code min + nextDouble() * (max - min)}, one draw,
* or {@code min} without a draw when the bounds are equal.
*/
public double pick(WorldRandom random) {
if (min == max) {
return min;
}
return min + random.nextDouble() * (max - min);
}
@Override
public boolean equals(Object other) {
return other instanceof Range that && Double.compare(min, that.min) == 0 && Double.compare(max, that.max) == 0;
}
@Override
public int hashCode() {
return Objects.hash(min, max);
}
@Override
public String toString() {
return "Range[" + min + ".." + max + "]";
}
}
@@ -0,0 +1,14 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Says that an option's text names an entry of a platform registry, {@code @Ref(Reference.BLOCK) String block}, so
* studio offers the registry's entries. Allowed on {@code String} and {@link com.volmit.resource.ResourceId} options
* and on lists, sets and arrays of them, where it applies to every element. A resource of the pack is named with
* {@link ResourceRef} instead; an option with both, or with either on any other type, fails the pack load.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Ref {
Reference value();
}
@@ -0,0 +1,33 @@
package com.volmit.config;
/** The platform registry a text option names, so studio can offer the matching completion list: entries of the
* server's registries, such as {@code minecraft:stone}, including those that data packs and mods add, and the host's
* own noise generators. Resources of the pack are named by their kind instead, with {@link ResourceRef}.
*/
public enum Reference {
/** A block type, such as {@code minecraft:stone}. {@link com.volmit.block.BlockState} options are block references without {@link Ref}. */
BLOCK,
/** An item type, such as {@code minecraft:stick}. */
ITEM,
/** An entity type, such as {@code minecraft:zombie}. */
ENTITY,
/** A platform structure, such as {@code minecraft:village_plains}. */
STRUCTURE,
/** A platform structure or a prefix naming a family of them: {@code minecraft:village_plains},
* {@code minecraft:village} (every village) or {@code nova_structures:} (a whole namespace). */
STRUCTURE_PREFIX,
/** A platform structure set, such as {@code minecraft:villages}. */
STRUCTURE_SET,
/** A platform jigsaw template pool, such as {@code minecraft:village/plains/town_centers}. */
TEMPLATE_POOL,
/** A potion effect type, such as {@code minecraft:speed}. */
POTION_EFFECT,
/** An enchantment, such as {@code minecraft:sharpness}. */
ENCHANTMENT,
/** A loot table of the platform, such as {@code minecraft:chests/simple_dungeon}; not a loot table of the pack. */
LOOT_TABLE,
/** A mob of another plugin or content provider, such as {@code mythicmobs:SkeletonKing}; see {@link com.volmit.resource.ContentKey.Provided}. */
SPECIAL_ENTITY,
/** One of the host's noise styles, such as {@code SIMPLEX}; see {@link com.volmit.noise.NoiseStyle}. */
NOISE_STYLE
}
@@ -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,16 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Says that an option's text names a resource of the pack by its key, {@code @ResourceRef(LootTable.class) String table},
* where the value is the type of a {@link com.volmit.resource.ResourceKind}: a host kind, the constants of
* {@link com.volmit.resource.PackResources}, or a kind some module of the pack registers. Studio then offers the pack's
* keys of that kind. Allowed on {@code String} and {@link com.volmit.resource.ResourceId} options and on lists, sets and
* arrays of them, where it applies to every element; a {@code ResourceId} option holds the id the pack gives the key it
* writes. An option with both this and {@link Ref}, or with either on any other type, fails the pack load.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ResourceRef {
Class<?> value();
}
@@ -0,0 +1,105 @@
package com.volmit.config;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings.Entry;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/** The entries of one settings type that apply somewhere, in {@link Level} order: what a column stacks
* ({@link FeatureSettings#at}), what a chunk or a placement configures ({@link com.volmit.stage.StageContext#configured})
* or what a pack declares ({@link PackSettings#declared}). Levels stack and nothing is merged, so a module picks what it
* needs: every entry, the dimension's, the most specific one. Several entries may share a level, such as the biomes of
* a chunk or of a pack; they keep the order they were found in.
*
* <p>An immutable value; equal when the entries are equal. Hosts build it with {@link #of}.
*/
public final class SettingsStack<F extends IrisFeature> implements Iterable<Entry<F>> {
private static final SettingsStack<?> EMPTY = new SettingsStack<>(List.of());
private static final Comparator<Entry<?>> LEVEL_ORDER = Comparator.comparing(Entry::level);
private final List<Entry<F>> entries;
private final List<F> values;
private SettingsStack(List<Entry<F>> entries) {
this.entries = entries;
this.values = entries.stream().map(Entry::value).toList();
}
@SuppressWarnings("unchecked") // The empty stack holds no entry of any type.
public static <F extends IrisFeature> SettingsStack<F> empty() {
return (SettingsStack<F>) EMPTY;
}
/** These entries in level order; entries of one level keep the order given. */
public static <F extends IrisFeature> SettingsStack<F> of(List<? extends Entry<F>> entries) {
Objects.requireNonNull(entries, "entries");
if (entries.isEmpty()) {
return empty();
}
var sorted = new ArrayList<Entry<F>>(entries);
sorted.forEach(entry -> Objects.requireNonNull(entry, "entry"));
sorted.sort(LEVEL_ORDER);
return new SettingsStack<>(List.copyOf(sorted));
}
public boolean isEmpty() {
return entries.isEmpty();
}
/** Every entry, in level order. */
public List<Entry<F>> entries() {
return entries;
}
/** Every entry's value, in level order. */
public List<F> values() {
return values;
}
/** The dimension's value; empty when the dimension declares none. */
public Optional<F> dimension() {
return level(Level.DIMENSION);
}
/** The first value declared at {@code level}; empty when that level declares none. */
public Optional<F> level(Level level) {
Objects.requireNonNull(level, "level");
for (var entry : entries) {
if (entry.level() == level) {
return Optional.of(entry.value());
}
}
return Optional.empty();
}
/** The value of the last entry, the most specific level's (a placement before a biome before a region before the
* dimension); empty when the stack is.
*/
public Optional<F> mostSpecific() {
return entries.isEmpty() ? Optional.empty() : Optional.of(entries.getLast().value());
}
@Override
public Iterator<Entry<F>> iterator() {
return entries.iterator();
}
@Override
public boolean equals(Object other) {
return other instanceof SettingsStack<?> stack && entries.equals(stack.entries);
}
@Override
public int hashCode() {
return entries.hashCode();
}
@Override
public String toString() {
return "SettingsStack" + entries;
}
}
@@ -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,33 @@
package com.volmit.data;
import com.volmit.resource.ResourceId;
import java.util.Objects;
import java.util.function.Supplier;
/** The identity and form of one value a module keeps with a running world across restarts
* ({@link com.volmit.world.RunningWorld#saved}). The module registers it in its setup
* ({@link com.volmit.FeatureRegistry#registerSaved}), and the id is the module's id or starts with it and {@code /},
* as a mantle key's does. The host names its storage after the id, so each segment of the namespace and of the
* {@code /} separated path must be a name, never empty, {@code .} or {@code ..}.
*
* @param id the stable storage identity, such as {@code example:moss/patches}
* @param type the value class
* @param codec how the value is stored; its version is written with the value
* @param initial the value for a world that has none stored, or whose stored one the codec rejects
*/
public record SavedKey<T>(ResourceId id, Class<T> type, StorageCodec<T> codec, Supplier<T> initial) {
public SavedKey {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(type, "type");
Objects.requireNonNull(codec, "codec");
Objects.requireNonNull(initial, "initial");
if (type.isPrimitive()) {
throw new IllegalArgumentException("Saved values require a reference type");
}
for (String segment : id.toString().replace(':', '/').split("/", -1)) {
if (segment.isEmpty() || segment.equals(".") || segment.equals("..")) {
throw new IllegalArgumentException("A saved ID names files, so it has no empty, . or .. segment: " + id);
}
}
}
}
@@ -0,0 +1,19 @@
package com.volmit.data;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/** Value serialization for data the host stores for a module: mantle layers ({@link com.volmit.mantle.MantleKey}) and
* saved world state ({@link SavedKey}). The host frames payloads and stores the 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 StorageCodec<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,194 @@
package com.volmit.entity;
import com.volmit.item.ItemAttribute;
import com.volmit.item.ItemDrop;
import com.volmit.resource.ContentKey;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* An entity a module decided to spawn, with every random choice made: the host creates it on the platform and applies
* what is set. A part the entity cannot have, such as equipment on an item frame, is left out. A host may leave a
* {@link ContentKey.Provided} mob as its provider set it up.
*
* @param type what the entity is: an entity type, such as {@code minecraft:zombie}, or a mob of a provider
* @param appearance how it looks
* @param behaviour how it acts
* @param equipment what it wears and holds
* @param attributes attribute modifiers to apply
* @param company the entities that come with it
* @param drops what it drops when it dies
* @param arrival what happens where it appears
* @param adjustsProvidedMob whether the rest of the spec also applies to a {@link ContentKey.Provided} mob, which is
* otherwise left as its provider set it up
*/
public record EntitySpec(ContentKey type, Appearance appearance, Behaviour behaviour, Equipment equipment,
List<ItemAttribute> attributes, Company company, Drops drops, Arrival arrival,
boolean adjustsProvidedMob) {
public EntitySpec {
Objects.requireNonNull(type, "type");
Objects.requireNonNull(appearance, "appearance");
Objects.requireNonNull(behaviour, "behaviour");
Objects.requireNonNull(equipment, "equipment");
attributes = List.copyOf(attributes);
Objects.requireNonNull(company, "company");
Objects.requireNonNull(drops, "drops");
Objects.requireNonNull(arrival, "arrival");
}
/**
* How the entity looks.
*
* @param customName the name shown above the entity, as authored in the pack with {@code &} colour codes; empty for none
* @param nameVisible whether the name shows even when nobody looks at the entity
* @param pandaMainGene for a panda, its main gene by the platform's name for it; empty to leave it to the platform
* @param pandaHiddenGene for a panda, its hidden gene by the platform's name for it; empty to leave it to the platform
*/
public record Appearance(Optional<String> customName, boolean nameVisible, boolean glowing, boolean baby,
Optional<String> pandaMainGene, Optional<String> pandaHiddenGene) {
public static final Appearance PLAIN = new Appearance(Optional.empty(), false, false, false, Optional.empty(),
Optional.empty());
public Appearance {
Objects.requireNonNull(customName, "customName");
Objects.requireNonNull(pandaMainGene, "pandaMainGene");
Objects.requireNonNull(pandaHiddenGene, "pandaHiddenGene");
}
}
/**
* How the entity acts; the host applies what the entity's kind has.
*
* @param aware whether a mob notices its surroundings
* @param ai whether a mob follows its goals
* @param removable whether the entity despawns when far from players
* @param keepEntity whether the entity is never culled
*/
public record Behaviour(boolean aware, boolean ai, boolean gravity, boolean invulnerable, boolean silent,
boolean pickupItems, boolean removable, boolean keepEntity) {
public static final Behaviour NATURAL = new Behaviour(true, true, true, false, false, false, false, false);
}
/** The items an entity wears and holds; empty for an empty slot. */
public record Equipment(Optional<ItemDrop> helmet, Optional<ItemDrop> chestplate, Optional<ItemDrop> leggings,
Optional<ItemDrop> boots, Optional<ItemDrop> mainHand, Optional<ItemDrop> offHand) {
public static final Equipment NONE = new Equipment(Optional.empty(), Optional.empty(), Optional.empty(),
Optional.empty(), Optional.empty(), Optional.empty());
public Equipment {
Objects.requireNonNull(helmet, "helmet");
Objects.requireNonNull(chestplate, "chestplate");
Objects.requireNonNull(leggings, "leggings");
Objects.requireNonNull(boots, "boots");
Objects.requireNonNull(mainHand, "mainHand");
Objects.requireNonNull(offHand, "offHand");
}
}
/**
* The entities that come with this one.
*
* @param passengers entities that ride this one
* @param leashHolder the entity that holds this one on a leash; empty for none
*/
public record Company(List<EntitySpec> passengers, Optional<EntitySpec> leashHolder) {
public static final Company NONE = new Company(List.of(), Optional.empty());
public Company {
passengers = List.copyOf(passengers);
Objects.requireNonNull(leashHolder, "leashHolder");
}
}
/**
* What the entity drops when it dies.
*
* @param lootTables the pack's loot tables it drops instead of the platform's drops; none keeps the platform's
* @param shuffleSeed seeds how the drops of {@code lootTables} are shuffled
*/
public record Drops(List<ResourceId> lootTables, long shuffleSeed) {
public static final Drops PLATFORM = new Drops(List.of(), 0L);
public Drops {
lootTables = List.copyOf(lootTables);
}
}
/**
* What happens where the entity appears.
*
* @param effect an effect to show; empty for none
* @param commands console commands to run
* @param reason why the entity appears, by the platform's name for the reason, such as {@code COMMAND}; empty
* for a natural spawn
* @param risesFromGround whether the entity slowly climbs out of the ground when players are near
*/
public record Arrival(Optional<SpawnEffect> effect, List<Command> commands, Optional<String> reason,
boolean risesFromGround) {
public static final Arrival QUIET = new Arrival(Optional.empty(), List.of(), Optional.empty(), false);
public Arrival {
Objects.requireNonNull(effect, "effect");
commands = List.copyOf(commands);
Objects.requireNonNull(reason, "reason");
}
}
/**
* Sound and particles shown around an entity that appears. The host makes the random choices: where in range the
* sound plays, its pitch, and the particles' random motion.
*/
public record SpawnEffect(Optional<Sound> sound, Optional<Burst> particles) {
public SpawnEffect {
Objects.requireNonNull(sound, "sound");
Objects.requireNonNull(particles, "particles");
}
/**
* A sound played near the entity, at a pitch between {@code minPitch} and {@code maxPitch}.
*
* @param key the sound, such as {@code minecraft:entity.zombie.ambient}
* @param distance how many blocks from the entity, at most, along each axis it seems to come from
*/
public record Sound(ResourceId key, int distance, double minPitch, double maxPitch, double volume) {
public Sound {
Objects.requireNonNull(key, "key");
}
}
/**
* Particles shown around the entity.
*
* @param key the particle, such as {@code minecraft:smoke}
* @param offset how many blocks up, at most, they appear
* @param count how many particles; none makes {@code motion} their motion
* @param extra an extra value some particles take; 0 for none
*/
public record Burst(ResourceId key, int offset, int count, Motion motion, double extra) {
public Burst {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(motion, "motion");
}
}
/** How far the particles spread or move along each axis; a random axis takes a random amount between minus and plus its value. */
public record Motion(double x, double y, double z, boolean randomX, boolean randomY, boolean randomZ) {
}
}
/**
* Console commands run when an entity appears. {@code {x}}, {@code {y}} and {@code {z}} stand for its block position.
*
* @param commands the commands
* @param delay server ticks to wait before running them
* @param repeat whether to run them again and again until the server stops
* @param repeatDelay server ticks between repeats
*/
public record Command(List<String> commands, long delay, boolean repeat, long repeatDelay) {
public Command {
commands = List.copyOf(commands);
}
}
}
@@ -0,0 +1,52 @@
package com.volmit.generation;
import com.volmit.config.FeatureSettings;
import com.volmit.geometry.BlockBox;
import com.volmit.world.TerrainSampler;
/** What chunk and mantle invocations share: the chunk they run for, its terrain and its settings. X and Z are world
* coordinates; heights are above the dimension's bottom. Must not be retained after execution.
*/
public interface ChunkContext extends InvocationContext {
/** The width of a chunk along X and Z, in blocks. */
int CHUNK_WIDTH = 16;
/** The local X and Z of a chunk's centre column, where something that happens once per chunk reads its settings. */
int CENTRE_COLUMN = 7;
/** The chunk's first block along X, in world coordinates. */
int originX();
/** The chunk's first block along Z, in world coordinates. */
int originZ();
TerrainSampler terrain();
FeatureSettings settings();
/** The chunk's X in chunk coordinates. */
default int chunkX() {
return Math.floorDiv(originX(), CHUNK_WIDTH);
}
/** The chunk's Z in chunk coordinates. */
default int chunkZ() {
return Math.floorDiv(originZ(), CHUNK_WIDTH);
}
/** The world X of the chunk's centre column (local 7). */
default int centreX() {
return originX() + CENTRE_COLUMN;
}
/** The world Z of the chunk's centre column (local 7). */
default int centreZ() {
return originZ() + CENTRE_COLUMN;
}
/** The chunk's 16 by 16 columns in world coordinates, at the full height the terrain covers. */
default BlockBox area() {
var bounds = terrain().bounds();
return new BlockBox(originX(), bounds.minY(), originZ(), originX() + CHUNK_WIDTH, bounds.maxY(), originZ() + CHUNK_WIDTH);
}
}
@@ -0,0 +1,39 @@
package com.volmit.generation;
import com.volmit.block.BlockState;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.world.TerrainSampler;
/** Per-invocation chunk generation inputs. Must not be retained after execution. */
public interface GenerationContext extends ChunkContext {
/** World coordinates of the local volume's first column. The volume starts at the dimension's bottom:
* local y is the height above it (0 = bottom block).
*/
@Override
int originX();
@Override
int originZ();
/** The terrain of the chunk and of the 16 blocks around it on every side, at full height: a chunk stage writes only
* its own chunk, but may look at its neighbors' terrain, such as their heights.
*/
@Override
TerrainSampler terrain();
/** Non-null mantle access scoped to this invocation; the host owns its lifetime. Like {@link #terrain()} it covers
* the chunk and the 16 blocks around it, so a stage that places something against a neighbor can see what the mantle
* holds there. A chunk stage writes module layers inside its own chunk's columns only, such as markers it derives
* from the chunk's finished blocks: the mantle pipeline has finished around the chunk, and a neighbor may already
* be generated, so writes outside the chunk throw UnsupportedOperationException, as do writes to
* {@link Mantle#blocks()} and {@link Mantle#edit()}.
*/
Mantle mantle();
/** The chunk's blocks, which the stages of this invocation build one after the other: a volume of 16 by the
* dimension's height by 16, local to the chunk, owned by the host and shared by every stage of the invocation.
* Empty space is air.
*/
Hunk<BlockState> blocks();
}
@@ -0,0 +1,33 @@
package com.volmit.generation;
import com.volmit.ModuleLog;
import com.volmit.world.PackWorld;
import java.util.Optional;
/** Host-owned invocation inputs. Views must not be retained or used by detached tasks.
*
* <p>There is no shared random stream. A stage draws from {@link com.volmit.stage.StageContext#random()},
* a stream of its own.
*/
public interface InvocationContext {
/** The world this invocation generates: its seed, the pack snapshot's resources, its settings and the state modules
* keep for it ({@link PackWorld#state}). Every invocation has one. A placement a tool makes outside a world the host
* generates, such as a studio paste, gets a world of its own that lives for that placement.
*/
PackWorld world();
/** The log of the module this invocation runs for, labelled with the module's id. The same as {@code world().log()}. */
default ModuleLog log() {
return world().log();
}
/**
* What the host offers for this one invocation beyond the API, as an object of {@code type}: empty when the host
* offers no such thing. The per invocation counterpart of {@link PackWorld#extension}: a host hands its own modules
* inputs that belong to one placement or one chunk this way, such as what Iris knows about the placement that is
* running. The host fills it for each invocation; like every input it must not be kept after the invocation.
*/
default <T> Optional<T> extension(Class<T> type) {
return Optional.empty();
}
}
@@ -0,0 +1,24 @@
package com.volmit.generation;
import com.volmit.mantle.Mantle;
import com.volmit.placement.PlacementTerrain;
import com.volmit.world.TerrainSampler;
/** Per-invocation inputs of the mantle pipeline for one chunk. Must not be retained after execution. */
public interface MantleGenerationContext extends ChunkContext {
/** The terrain of the chunk and of the larger of the stage's reach and 16 blocks around it on every side, at full
* height: a mantle stage writes only the mantle, but may look at the terrain around its chunk, such as the heights
* a cave blends over its borders.
*/
@Override
TerrainSampler terrain();
/** The mantle of the chunk widened by the pipeline's reach, full height (heights 0 up to the dimension height). Writes outside it throw. */
Mantle mantle();
/**
* The mantle of the chunk and its reach as a world to place objects in ({@link com.volmit.placement.Placements}):
* its blocks are the mantle's planned blocks, and placements write theirs into the mantle.
*/
PlacementTerrain placementTerrain();
}
@@ -0,0 +1,26 @@
package com.volmit.geometry;
import java.util.Objects;
/** Block bounds, minimum inclusive and maximum exclusive. Empty boxes are valid. X and Z are world coordinates;
* Y is the height above the dimension's bottom (0 = bottom). Boxes of local volumes, such as an object's
* bounds, use that volume's own coordinates.
*/
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,4 @@
package com.volmit.geometry;
/** One of the six faces of a block. */
public enum BlockFace { UP, DOWN, NORTH, SOUTH, EAST, WEST }
@@ -0,0 +1,28 @@
package com.volmit.geometry;
/** A block position. Owning contracts specify whether it is local or in the world. A world position has
* world X and Z and a Y that is the height above the dimension's bottom (0 = bottom).
*/
public record BlockPosition(int x, int y, int z) implements Comparable<BlockPosition> {
/** The origin, which settings start from before the host reads their JSON: packs write {@code {"x": 1, "y": 2, "z": 3}},
* and an omitted coordinate is 0.
*/
private BlockPosition() {
this(0, 0, 0);
}
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,16 @@
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.
* A chunk's volume starts at the dimension's bottom: its local y is the height above
* the dimension's bottom (0 = bottom). 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 width();
int height();
int depth();
T get(int x, int y, int z);
void set(int x, int y, int z, T value);
}
@@ -0,0 +1,21 @@
package com.volmit.item;
/** The sixteen dye colours, which colour items such as shulker boxes, banners and beds. */
public enum DyeColor {
WHITE,
ORANGE,
MAGENTA,
LIGHT_BLUE,
YELLOW,
LIME,
PINK,
GRAY,
LIGHT_GRAY,
CYAN,
PURPLE,
BLUE,
BROWN,
GREEN,
RED,
BLACK
}
@@ -0,0 +1,28 @@
package com.volmit.item;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** An attribute modifier of an {@link ItemDrop} or an entity, with the amount the module decided. The host creates a
* modifier under an id it makes unique from {@code name}, for every equipment slot.
*
* @param attribute the attribute, such as {@code minecraft:max_health}
* @param name identifies the modifier among those of one item or entity; not shown to players
*/
public record ItemAttribute(ResourceId attribute, String name, Operation operation, double amount) {
public ItemAttribute {
Objects.requireNonNull(attribute, "attribute");
Objects.requireNonNull(name, "name");
Objects.requireNonNull(operation, "operation");
}
/** How the amount changes the attribute's value, as the platform's attribute modifiers do. */
public enum Operation {
/** Adds the amount to the base value. */
ADD_VALUE,
/** Adds the base value times the amount. */
ADD_MULTIPLIED_BASE,
/** Multiplies the value, after the other modifiers, by one plus the amount. */
ADD_MULTIPLIED_TOTAL
}
}
@@ -0,0 +1,110 @@
package com.volmit.item;
import com.volmit.resource.ContentKey;
import com.volmit.resource.ResourceId;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
/**
* One stack of items a module decided to give: what a loot entry, a block's drops or an entity's equipment turned into
* after the module made every random choice. The host creates the stack on the platform; a part the item cannot have,
* such as a leather colour on a sword, is left out.
*
* @param item what the item is
* @param amount how many, at least 1
* @param look its name, lore and colours
* @param enchantments applied in order
* @param attributes attribute modifiers applied in order
* @param wear how worn it is
* @param extras what only some platforms understand
* @param source where the item came from, present only when the host asked for it to be shown (debug loot)
*/
public record ItemDrop(ContentKey item, int amount, Look look, List<ItemEnchantment> enchantments,
List<ItemAttribute> attributes, Wear wear, PlatformExtras extras, Optional<Source> source) {
public ItemDrop {
Objects.requireNonNull(item, "item");
if (amount < 1) throw new IllegalArgumentException("Item amount must be at least 1: " + amount);
Objects.requireNonNull(look, "look");
enchantments = List.copyOf(enchantments);
attributes = List.copyOf(attributes);
Objects.requireNonNull(wear, "wear");
Objects.requireNonNull(extras, "extras");
Objects.requireNonNull(source, "source");
}
/** {@code amount} items of kind {@code item} and nothing else. */
public static ItemDrop of(ContentKey item, int amount) {
return new ItemDrop(item, amount, Look.PLAIN, List.of(), List.of(), Wear.NEW, PlatformExtras.NONE, Optional.empty());
}
/**
* How the item looks. Names and lore are as authored in the pack, with {@code &} colour codes; the host translates
* and wraps them.
*
* @param displayName the item's name; empty keeps the platform's
* @param lore lines of text under the name
* @param customModel custom model number; empty for none
* @param leatherColor colour of leather armour as {@code 0xRRGGBB}; empty for none
* @param dyeColor the dye colour of an item that takes one; empty for none
*/
public record Look(Optional<String> displayName, List<String> lore, OptionalInt customModel, OptionalInt leatherColor,
Optional<DyeColor> dyeColor) {
public static final Look PLAIN = new Look(Optional.empty(), List.of(), OptionalInt.empty(), OptionalInt.empty(), Optional.empty());
public Look {
Objects.requireNonNull(displayName, "displayName");
lore = List.copyOf(lore);
Objects.requireNonNull(customModel, "customModel");
Objects.requireNonNull(leatherColor, "leatherColor");
Objects.requireNonNull(dyeColor, "dyeColor");
}
}
/**
* How worn the item is.
*
* @param unbreakable whether the item never breaks
* @param damage the fraction of the item's durability already used, 0 to 1; empty leaves it undamaged
*/
public record Wear(boolean unbreakable, OptionalDouble damage) {
public static final Wear NEW = new Wear(false, OptionalDouble.empty());
public Wear {
Objects.requireNonNull(damage, "damage");
}
}
/**
* What only some platforms understand; a platform without them ignores them.
*
* @param flags the platform's item flags to set, by name; names the platform lacks are ignored
* @param customNbt custom data the platform stores on the item, or an empty map
*/
public record PlatformExtras(List<String> flags, Map<String, Object> customNbt) {
public static final PlatformExtras NONE = new PlatformExtras(List.of(), Map.of());
public PlatformExtras {
flags = List.copyOf(flags);
customNbt = Collections.unmodifiableMap(new LinkedHashMap<>(customNbt));
}
}
/**
* Where a shown item came from: the loot table, when it came from one, and the 1-in-N chances it passed.
*
* @param table the pack table's id; empty for an item that came from no table
* @param tableRarity the table's rarity, 1 in this many
* @param entryRarity the entry's rarity within the table
*/
public record Source(Optional<ResourceId> table, int tableRarity, int entryRarity) {
public Source {
Objects.requireNonNull(table, "table");
}
}
}
@@ -0,0 +1,14 @@
package com.volmit.item;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** An enchantment of an {@link ItemDrop}, such as {@code minecraft:sharpness} or {@code mymod:vorpal}, with the level
* the module decided.
*/
public record ItemEnchantment(ResourceId key, int level) {
public ItemEnchantment {
Objects.requireNonNull(key, "key");
if (level < 1) throw new IllegalArgumentException("Enchantment level must be at least 1: " + level);
}
}
@@ -0,0 +1,15 @@
package com.volmit.item;
import com.volmit.resource.ContentKey;
import java.util.OptionalInt;
/** What a module may ask the platform about items, so that its decisions follow the item they concern. Safe for
* concurrent use.
*/
public interface ItemRegistry {
/**
* The most damage an item of this kind takes before it breaks, 0 for an item that cannot be damaged; empty when no
* item is known by {@code item}.
*/
OptionalInt maxDurability(ContentKey item);
}
@@ -0,0 +1,64 @@
package com.volmit.mantle;
import com.volmit.resource.ResourceId;
import java.util.Objects;
import java.util.Optional;
/** A block the mantle holds as carved out: what fills the void once the chunk takes it over, and optionally the biome it shows.
* Instances are immutable and the four plain fills are shared constants ({@link #of}), so a carver marking thousands of blocks
* allocates nothing.
*
* @param fill what fills the void
* @param biome a pack biome the void shows instead of the cave biome its column would get; empty for the usual one
*/
public record CarvedVoid(Fill fill, Optional<ResourceId> biome) {
/** Cut open, and left to the dimension. */
public static final CarvedVoid OPEN = new CarvedVoid(Fill.OPEN, Optional.empty());
/** Filled with the dimension's fluid. */
public static final CarvedVoid FLUID = new CarvedVoid(Fill.FLUID, Optional.empty());
/** Filled with lava. */
public static final CarvedVoid LAVA = new CarvedVoid(Fill.LAVA, Optional.empty());
/** Filled with air, at any height. */
public static final CarvedVoid AIR = new CarvedVoid(Fill.AIR, Optional.empty());
public CarvedVoid {
Objects.requireNonNull(fill, "fill");
Objects.requireNonNull(biome, "biome");
}
/** The shared void of a fill, with no biome of its own. */
public static CarvedVoid of(Fill fill) {
return switch (Objects.requireNonNull(fill, "fill")) {
case OPEN -> OPEN;
case FLUID -> FLUID;
case LAVA -> LAVA;
case AIR -> AIR;
};
}
/** This void's fill, showing {@code biome}. */
public CarvedVoid withBiome(ResourceId biome) {
return new CarvedVoid(fill, Optional.of(biome));
}
/** What fills a carved void. */
public enum Fill {
/** The solid is cut away and the dimension decides what is left: cave air, or lava at and below its lava height.
* Air and fluid the terrain already has there stay.
*/
OPEN,
/** The dimension's fluid, replacing what the terrain has there. */
FLUID,
/** Lava, replacing what the terrain has there. */
LAVA,
/** Cave air at any height, replacing fluid and lava as well. */
AIR
}
}
@@ -0,0 +1,58 @@
package com.volmit.mantle;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockBox;
import com.volmit.resource.ResourceId;
/**
* Invocation-scoped access to typed mantle data. X and Z are world block coordinates; Y is
* the height above the dimension's bottom (0 = bottom), so it is never negative. 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);
/** The blocks the mantle holds for chunks to take over: what placements wrote, such as objects and structures.
* A chunk stage copies them into its chunk (Iris's {@code iris:matter}); absent positions read null, and air a
* placement wrote is a block like any other. The host owns this layer, so it needs no registration. Stages read
* it only, and writes throw UnsupportedOperationException: placements write blocks with
* {@link com.volmit.placement.PlacementAccess#set}. A dimension that keeps no mantle holds none.
*/
MantleLayer<BlockState> blocks();
/** The voids the mantle holds for chunks to take over: a cave's air or fluid, planned before the chunks were generated.
* Mantle stages write it ({@code set} plans a void, {@code remove} takes it back); a chunk stage only reads it, around
* its chunk as far as its mantle reaches, and its writes throw UnsupportedOperationException. A chunk stage takes the
* voids over into its chunk (Iris's {@code iris:carve} cuts them out of the terrain). The host owns this layer and keeps
* it in its own form, so it needs no registration. A dimension that keeps no mantle carves nothing. A stage that only
* asks whether a position is carved, whether or not the chunk's own blocks show it, such as under a dimension stacked
* above, tests {@code carved().get(x, y, z) != null}.
*/
MantleLayer<CarvedVoid> carved();
/** Shows the block as platform biome {@code biome}, such as {@code minecraft:plains} or a pack's custom biome, instead
* of the biome its column generates as; the host's biome pass reads it when it writes the chunk's biomes. The host
* owns this layer and keeps it in its own form, so it is written only and needs no registration. A chunk stage
* sets it inside its own chunk only, like module layers.
*/
void setPlatformBiome(int x, int y, int z, ResourceId biome);
/** 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,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,15 @@
package com.volmit.mantle;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Stable storage identity. Different IDs may use the same value class without sharing data. */
public record MantleKey<T>(ResourceId id, Class<T> type) {
public MantleKey {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(type, "type");
if (type.isPrimitive()) {
throw new IllegalArgumentException("Mantle values require a reference type");
}
}
}
@@ -0,0 +1,27 @@
package com.volmit.mantle;
import com.volmit.geometry.BlockBox;
/** 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,20 @@
package com.volmit.noise;
/** Builds noise from styles a pack describes. Noise is the host's: modules describe it with {@link NoiseStyle} in
* their settings and get samplers from here ({@link com.volmit.resource.PackResources#noise()}), never the host's
* noise classes. Safe for concurrent calls.
*/
public interface NoiseFactory {
/** The noise {@code style} describes, seeded with {@code seed}. The same style and seed give the same values
* in every world of the pack, so derive the seed from the world seed ({@code context.world().seed()}), not from a
* stage's random stream, when the noise must line up across chunks. The host keeps what it builds for the pack
* snapshot, so asking again for the same style and seed is cheap.
*
* <p>A style with its own seed ({@link NoiseStyle#seed()}) ignores {@code seed}: the host rolls it from that number
* and the seed of the world the pack generates, so every reader of the same seeded style gets the same noise.
*
* <p>A style name the host does not know, an expression the pack does not have, and an image map the pack does not
* have or cannot use as noise throw {@link IllegalArgumentException}.
*/
NoiseSampler sampler(NoiseStyle style, long seed);
}
@@ -0,0 +1,56 @@
package com.volmit.noise;
/** Immutable, seeded noise the host built from a {@link NoiseStyle} ({@link NoiseFactory#sampler}). X and Z are
* world coordinates; Y is the height above the dimension's bottom (0 = bottom). The host's own styles give values
* from 0 to 1; expressions and image maps give what they compute. Two-dimensional and three-dimensional samples
* are separate fields, so {@code sample(x, z)} is not {@code sample(x, 0, z)}. Safe for concurrent calls.
*/
public interface NoiseSampler {
double sample(double worldX, double worldZ);
double sample(double worldX, double y, double worldZ);
/** {@link #sample(double, double)} mapped from 0..1 to -1..1 ({@code sample * 2 - 1}), for noise that is added up
* and compared around zero. A host may answer a repeated read of the same coordinates from a per-thread memo, so a
* caller that samples the same field at the same points again and again (a carver testing densities) should read
* this instead of mapping {@link #sample(double, double)} itself.
*/
default double signed(double worldX, double worldZ) {
return sample(worldX, worldZ) * 2D - 1D;
}
/** The three-dimensional counterpart of {@link #signed(double, double)}. */
default double signed(double worldX, double y, double worldZ) {
return sample(worldX, y, worldZ) * 2D - 1D;
}
/** This noise with its coordinates multiplied by {@code factor}: a factor above 1 squeezes the pattern, below 1
* stretches it. A host folds the factor into the generator's own scale, so the result is the very noise the style
* would give with that extra scale (same values and float rounding), and builds it without touching this sampler.
* The default multiplies the coordinates before sampling, which may round differently.
*/
default NoiseSampler scaled(double factor) {
NoiseSampler source = this;
return new NoiseSampler() {
@Override
public double sample(double worldX, double worldZ) {
return source.sample(worldX * factor, worldZ * factor);
}
@Override
public double sample(double worldX, double y, double worldZ) {
return source.sample(worldX * factor, y * factor, worldZ * factor);
}
@Override
public double signed(double worldX, double worldZ) {
return source.signed(worldX * factor, worldZ * factor);
}
@Override
public double signed(double worldX, double y, double worldZ) {
return source.signed(worldX * factor, y * factor, worldZ * factor);
}
};
}
}
@@ -0,0 +1,187 @@
package com.volmit.noise;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
import com.volmit.config.Ref;
import com.volmit.config.Reference;
import com.volmit.config.ResourceRef;
import com.volmit.config.Snippet;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
/** How noise is shaped, as packs write it: {@code {"style": "SIMPLEX", "zoom": 4}}, or a snippet under
* {@code snippet/style/}. The style names one of the host's noise generators ({@link Reference#NOISE_STYLE}); an
* expression or image map of the pack replaces it. A zoom stretches the noise, an exponent bends it, a fracture
* distorts its coordinates and a cellular frequency turns it into cells.
*
* <p>A style is a description, not noise: the host builds the noise ({@link NoiseFactory#sampler}). It is a value
* the host decodes as every settings class (see DESIGN.md, "Decoding contract"); nothing changes it afterwards.
*/
@Snippet("style")
@Desc("A noise style: one of the host's noise generators, or an expression or image map of the pack, shaped by zoom, exponent, fracture and cells")
public final class NoiseStyle {
/** The style without noise, the default. */
public static final String FLAT = "FLAT";
@Ref(Reference.NOISE_STYLE)
@Desc("The noise generator. Used when neither expression nor imageMap is set.")
private String style = FLAT;
@Desc("Above 0, the noise is turned into cells of this frequency.")
private double cellularFrequency = 0;
@Desc("How far the cells are stretched.")
private double cellularZoom = 1;
@MinNumber(0.00001)
@Desc("How far the noise is stretched: above 1 wider, below 1 tighter.")
private double zoom = 1;
@ResourceRef(PackExpression.class)
@Desc("An expression of the pack that gives the noise instead of the style.")
private ResourceId expression;
@ResourceRef(PackImageMap.class)
@Desc("An image map of the pack that gives the noise instead of the style, when there is no expression.")
private ResourceId imageMap;
@MinNumber(0.00001)
@Desc("When this style moves coordinates, as another style's fracture or as a warp: up to half this many blocks either way.")
private double multiplier = 1;
@Desc("A style whose noise moves the coordinates this style is sampled at, distorting it.")
private NoiseStyle fracture;
@MinNumber(0.01562)
@MaxNumber(64)
@Desc("The power the noise is raised to: above 1 favours low values, below 1 high ones.")
private double exponent = 1;
@Desc("Rolls this noise from the world seed and this number, so every style with the same seed shares one noise. Child biomes, palettes and decorator placement read a seeded style flat in blocks: zoom is its only scale, so a layer's zoom, childShrinkFactor and the decorator's extra zoom don't apply.")
private Long seed;
private NoiseStyle() {
}
private NoiseStyle(NoiseStyle copy) {
style = copy.style;
cellularFrequency = copy.cellularFrequency;
cellularZoom = copy.cellularZoom;
zoom = copy.zoom;
expression = copy.expression;
imageMap = copy.imageMap;
multiplier = copy.multiplier;
fracture = copy.fracture;
exponent = copy.exponent;
seed = copy.seed;
}
/** The host's noise style {@code style}, such as {@code SIMPLEX}, with every other option at its default. */
public static NoiseStyle of(String style) {
var created = new NoiseStyle();
created.style = Objects.requireNonNull(style, "style");
return created;
}
/** This style with zoom {@code zoom}: above 1 stretches the noise, below 1 squeezes it. */
public NoiseStyle withZoom(double zoom) {
var changed = new NoiseStyle(this);
changed.zoom = zoom;
return changed;
}
/** This style rolled from {@code seed} and the world seed instead of the seed it is asked for; see {@link #seed()}. */
public NoiseStyle withSeed(long seed) {
var changed = new NoiseStyle(this);
changed.seed = seed;
return changed;
}
/** The base style's name; {@link #FLAT} where the pack wrote none. */
public String style() {
return style;
}
public double cellularFrequency() {
return cellularFrequency;
}
public double cellularZoom() {
return cellularZoom;
}
public double zoom() {
return zoom;
}
/** The pack expression that replaces the base style, by the id the pack gives its key; see {@link PackResources#EXPRESSIONS}. */
public Optional<ResourceId> expression() {
return Optional.ofNullable(expression);
}
/** The pack image map that replaces the base style when there is no expression; see {@link PackResources#IMAGE_MAPS}. */
public Optional<ResourceId> imageMap() {
return Optional.ofNullable(imageMap);
}
/** How far this style moves coordinates when it moves them, as another style's {@link #fracture} or as a warp: up
* to half this many blocks either way.
*/
public double multiplier() {
return multiplier;
}
/** The style whose noise moves the coordinates this style is sampled at, by its own {@link #multiplier}. */
public Optional<NoiseStyle> fracture() {
return Optional.ofNullable(fracture);
}
public double exponent() {
return exponent;
}
/** The style's own seed, when the pack gave it one. A seeded style is one noise per world: {@link NoiseFactory#sampler}
* rolls it from this number and the world seed and ignores the seed it is asked for, so every reader of a style with
* the same seed and shape gets the same values. Readers that scale coordinates before sampling (a palette layer's
* zoom, a decorator's zoom, a child biome's shrink factor) read a seeded style in plain blocks instead, so
* {@link #zoom()} is its only scale.
*/
public OptionalLong seed() {
return seed == null ? OptionalLong.empty() : OptionalLong.of(seed);
}
/** Whether the pack gave this style its own {@link #seed()}. */
public boolean isSeeded() {
return seed != null;
}
/** Whether the style gives no noise: the {@link #FLAT} base style without an expression or image map. */
public boolean isFlat() {
return FLAT.equals(style) && expression == null && imageMap == null;
}
@Override
public boolean equals(Object other) {
return other instanceof NoiseStyle that && style.equals(that.style)
&& Double.compare(cellularFrequency, that.cellularFrequency) == 0
&& Double.compare(cellularZoom, that.cellularZoom) == 0 && Double.compare(zoom, that.zoom) == 0
&& Objects.equals(expression, that.expression) && Objects.equals(imageMap, that.imageMap)
&& Double.compare(multiplier, that.multiplier) == 0 && Objects.equals(fracture, that.fracture)
&& Double.compare(exponent, that.exponent) == 0 && Objects.equals(seed, that.seed);
}
@Override
public int hashCode() {
return Objects.hash(style, cellularFrequency, cellularZoom, zoom, expression, imageMap, multiplier, fracture, exponent, seed);
}
@Override
public String toString() {
return "NoiseStyle[" + style + expression().map(key -> ", expression " + key).orElse("")
+ imageMap().map(key -> ", image map " + key).orElse("") + ", zoom " + zoom + "]";
}
}
@@ -0,0 +1,14 @@
package com.volmit.noise;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** An expression of the loaded pack, which a {@link NoiseStyle} can use instead of a base style. The host compiles it
* and builds its noise ({@link NoiseFactory}); a module only names it, and can see that the pack has it through
* {@code PackResources.find(PackResources.EXPRESSIONS, id)}.
*/
public record PackExpression(ResourceId id) {
public PackExpression {
Objects.requireNonNull(id, "id");
}
}
@@ -0,0 +1,14 @@
package com.volmit.noise;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** An image map of the loaded pack, which a {@link NoiseStyle} can use instead of a base style. The host reads the
* image and builds its noise ({@link NoiseFactory}); a module only names it, and can see that the pack has it through
* {@code PackResources.find(PackResources.IMAGE_MAPS, id)}.
*/
public record PackImageMap(ResourceId id) {
public PackImageMap {
Objects.requireNonNull(id, "id");
}
}
@@ -0,0 +1,85 @@
package com.volmit.noise;
import com.volmit.config.Desc;
import com.volmit.config.Snippet;
import java.util.Objects;
/** A number between {@code min} and {@code max} that a noise style picks per column, as packs write it:
* {@code {"min": 4, "max": 12, "style": {"style": "SIMPLEX"}}}, or a snippet under {@code snippet/style-range/}.
* A value the host decodes as every settings class (see DESIGN.md, "Decoding contract").
*/
@Snippet("style-range")
@Desc("A number between min and max that noise picks per column")
public final class StyledRange {
private static final String DEFAULT_STYLE = "STATIC";
@Desc("The lowest value.")
private double min = 16;
@Desc("The highest value.")
private double max = 32;
@Desc("The noise that picks the value in each column.")
private NoiseStyle style = NoiseStyle.of(DEFAULT_STYLE);
private StyledRange() {
}
private StyledRange(double min, double max, NoiseStyle style) {
this.min = min;
this.max = max;
this.style = Objects.requireNonNull(style, "style");
}
public static StyledRange of(double min, double max, NoiseStyle style) {
return new StyledRange(min, max, style);
}
public double min() {
return min;
}
public double max() {
return max;
}
/** The style; {@code STATIC} where the pack wrote none. */
public NoiseStyle style() {
return style;
}
/** Whether every column gets the same value: the bounds are equal or the style is flat. */
public boolean isFlat() {
return min == max || style.isFlat();
}
/** The value at column {@code worldX}, {@code worldZ}: {@code min} when the bounds are equal, halfway between
* them when the style is flat, otherwise {@code min + (max - min) * noise} of the style's noise seeded with
* {@code seed}.
*/
public double at(NoiseFactory noise, long seed, double worldX, double worldZ) {
if (min == max) {
return min;
}
if (style.isFlat()) {
return (min + max) / 2;
}
return min + (max - min) * noise.sampler(style, seed).sample(worldX, worldZ);
}
@Override
public boolean equals(Object other) {
return other instanceof StyledRange that && Double.compare(min, that.min) == 0
&& Double.compare(max, that.max) == 0 && style.equals(that.style);
}
@Override
public int hashCode() {
return Objects.hash(min, max, style);
}
@Override
public String toString() {
return "StyledRange[" + min + ".." + max + ", " + style + "]";
}
}
@@ -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.geometry.BlockBox;
import com.volmit.geometry.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.geometry.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,15 @@
package com.volmit.object;
import com.volmit.resource.ResourceId;
import com.volmit.geometry.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,38 @@
package com.volmit.object;
import com.volmit.geometry.BlockBox;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Optional;
/**
* The pack's objects, ready to place, and the objects made from them: scaled variants and objects a module builds block
* by block. The host loads, scales and keeps them for the pack snapshot, so asking again is cheap. Reached through
* {@link com.volmit.resource.PackResources#objects()}; safe for concurrent calls. This is the only source of
* {@link PlaceableObject}s: {@link #scaled} and {@link #smartBored} throw IllegalArgumentException for an object that
* did not come from here.
*/
public interface PackObjects {
/** The pack object {@code id} names, as {@link com.volmit.resource.PackResources#idOf} gives it for the key; empty when the pack has none. */
Optional<PlaceableObject> object(ResourceId id);
/** The pack object's size, read without loading its blocks: from the origin to its width, height and depth; empty when the pack has none. */
Optional<BlockBox> sizeOf(ResourceId id);
/**
* {@code object} resized by {@code factor}, filling between its blocks with {@code method}. Built once per object,
* factor and method, and kept within a memory budget.
*/
PlaceableObject scaled(PlaceableObject object, double factor, ScaleMethod method);
/**
* A copy of {@code object} with air in the rooms and pockets a placement should clear, found by casting rays through
* it; {@code object} itself is not changed. Done once per object, so asking again returns the same copy, and boring
* the copy returns the copy.
*/
PlaceableObject smartBored(PlaceableObject object);
/** An object of {@code blocks}, at their offsets from its center, declared {@code width} by {@code height} by {@code depth} with its center in the middle; placeable like the pack's. */
PlaceableObject build(String name, int width, int height, int depth, List<ObjectBlock> blocks);
}
@@ -0,0 +1,33 @@
package com.volmit.object;
import com.volmit.geometry.BlockPosition;
/**
* An object ready to be placed: one of the pack's, a scaled variant of one, or one a module built
* ({@link PackObjects}). Its size is the size it was declared with, which boring and terrain bends cover even where it
* has no block.
*
* <p>Only the host makes a {@code PlaceableObject}, and only through {@link PackObjects}: a module reads this interface
* and does not implement it. {@link PackObjects} rejects an object it did not make with IllegalArgumentException. The
* host never changes an object it handed out (scaling or boring one returns another object), so it is safe to share
* between threads.
*/
public interface PlaceableObject {
/**
* The object's name: the key the pack's files name it by, such as {@code trees/oak}, also for its scaled variants, or
* the name the module that built it gave it.
*/
String name();
int width();
int height();
int depth();
/** The block the object's offsets count from, relative to its corner. */
BlockPosition center();
/** The object's blocks at their offsets from {@link #center()}, so the geometry's anchor is the origin. */
GeneratedObject geometry();
}
@@ -0,0 +1,13 @@
package com.volmit.object;
/** How a scaled object fills the blocks between its source blocks when it grows ({@link PackObjects#scaled}). */
public enum ScaleMethod {
/** Each source block becomes a box of blocks. */
NONE,
/** Linear interpolation in three dimensions. */
TRILINEAR,
/** Cubic spline interpolation in three dimensions; smoother, much slower. */
TRICUBIC,
/** Hermite spline interpolation in three dimensions; smoother, much slower. */
TRIHERMITE
}
@@ -0,0 +1,18 @@
package com.volmit.placement;
import com.volmit.block.BlockState;
import com.volmit.object.BlockEntityData;
import com.volmit.geometry.BlockPosition;
import java.util.Objects;
import java.util.Optional;
/** A proposed or buffered write, including its block entity payload. The position has world X and Z and a
* Y that is the height above the dimension's bottom (0 = bottom).
*/
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,36 @@
package com.volmit.placement;
import com.volmit.geometry.BlockPosition;
import java.util.Objects;
/** A mark a placement leaves at a block, of one of the kinds the host keeps. The position has world X and Z and a Y
* that is the height above the dimension's bottom (0 = bottom).
*/
public sealed interface PlacedMarker permits PlacedMarker.PackMarker, PlacedMarker.TreeMaterial, PlacedMarker.BuriedTreasure {
BlockPosition position();
/** A marker the pack declares, by its key such as {@code spawn/zombie}. */
record PackMarker(BlockPosition position, String key) implements PlacedMarker {
public PackMarker {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(key, "key");
if (key.isBlank()) {
throw new IllegalArgumentException("A pack marker needs a key");
}
}
}
/** A block of a tree: the host keeps the block's material so the tree can be felled and grown. */
record TreeMaterial(BlockPosition position) implements PlacedMarker {
public TreeMaterial {
Objects.requireNonNull(position, "position");
}
}
/** A buried treasure chest: the host keeps it as a point of interest that treasure maps lead to. */
record BuriedTreasure(BlockPosition position) implements PlacedMarker {
public BuriedTreasure {
Objects.requireNonNull(position, "position");
}
}
}
@@ -0,0 +1,21 @@
package com.volmit.placement;
import com.volmit.block.BlockState;
import com.volmit.mantle.Mantle;
import com.volmit.world.BlockView;
/** Buffered access for placement stages, without ownership of commit/close. X and Z are world coordinates;
* Y is the height above the dimension's bottom (0 = bottom).
* Reads include the overlay. Bounds are the host-prepared placement 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 {
/** Writes {@code state} without a block entity, replacing any block entity buffered there. The per-block write. */
void set(int x, int y, int z, BlockState state);
/** Writes a block with its block entity, if it has one. */
void set(PlacedBlock block);
void marker(PlacedMarker marker);
Mantle mantle();
}
@@ -0,0 +1,25 @@
package com.volmit.placement;
import com.volmit.config.FeatureSettings;
import com.volmit.generation.InvocationContext;
import com.volmit.world.TerrainSampler;
import java.util.Optional;
/** Host-supplied, read-only inputs of one placement attempt. Working state is carried by stage
* outputs, never stored on a module or stage body. Context lifetime ends with the placement.
*/
public interface PlacementContext extends InvocationContext {
TerrainSampler terrain();
FeatureSettings settings();
/**
* The world the placement is made in, for the questions about a column the stages ask. Its blocks are the ones before
* this placement; stages write through their access, never into it.
*/
PlacementTerrain placementTerrain();
/**
* What the module that asked for this placement handed its stages ({@link PlacementRun#input}), when it is a
* {@code type}; empty otherwise, such as for a placement the host itself started.
*/
<T> Optional<T> input(Class<T> type);
}
@@ -0,0 +1,15 @@
package com.volmit.placement;
/** Host-owned buffered placement writes, with world X and Z and Y as the height above the
* dimension's bottom (0 = bottom), 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,30 @@
package com.volmit.placement;
import java.util.Objects;
import java.util.Optional;
/** Result of one placement attempt ({@link Placements#place}). A rejected attempt committed nothing. */
public record PlacementOutcome(Status status, Optional<String> rejection) {
public enum Status { PLACED, REJECTED }
public PlacementOutcome {
Objects.requireNonNull(status, "status");
Objects.requireNonNull(rejection, "rejection");
if ((status == Status.REJECTED) != rejection.isPresent()) {
throw new IllegalArgumentException("Only rejected placements carry a rejection reason");
}
}
public static PlacementOutcome placed() {
return new PlacementOutcome(Status.PLACED, Optional.empty());
}
/** Rejected with the reason the stage gave, such as {@code slope}. */
public static PlacementOutcome rejected(String reason) {
return new PlacementOutcome(Status.REJECTED, Optional.of(reason));
}
public boolean isPlaced() {
return status == Status.PLACED;
}
}
@@ -0,0 +1,34 @@
package com.volmit.placement;
import com.volmit.resource.ResourceId;
import java.util.Objects;
import java.util.Optional;
/**
* What a module recorded beside a block when it placed an object there ({@link PlacementTerrain#recordPlacement}), and
* what later placements and services read back ({@link PlacementTerrain#placementAt},
* {@link com.volmit.world.RunningWorld#placementAt}): which object stands there, which placement of it that was and, for a
* piece of a structure, which structure.
*
* @param object the pack object, or the name the module gave an object it made itself, as an id
* @param placementId the number the placing module gave this placement, which tells it apart from other placements of the
* same object; the module picks it, the host keeps it as it is
* @param structure the structure the object is a piece of; empty for an object placed on its own
*/
public record PlacementRecord(ResourceId object, int placementId, Optional<ResourceId> structure) {
public PlacementRecord {
Objects.requireNonNull(object, "object");
Objects.requireNonNull(structure, "structure");
}
/** An object placed on its own. */
public static PlacementRecord of(ResourceId object, int placementId) {
return new PlacementRecord(object, placementId, Optional.empty());
}
/** A piece of {@code structure}. */
public static PlacementRecord ofPiece(ResourceId object, int placementId, ResourceId structure) {
return new PlacementRecord(object, placementId, Optional.of(structure));
}
}
@@ -0,0 +1,34 @@
package com.volmit.placement;
import com.volmit.geometry.BlockBox;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.GeneratedObject;
import java.util.Objects;
/** One placement attempt. Geometry is already transformed; anchor is a world block position (world X and Z, Y as the height
* above the dimension's bottom).
* World position = local position - object anchor + request anchor. Arithmetic never wraps.
*/
public record PlacementRequest(GeneratedObject object, BlockPosition anchor) {
public PlacementRequest {
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,36 @@
package com.volmit.placement;
import com.volmit.geometry.BlockBox;
import java.util.Objects;
import java.util.Optional;
/**
* One object a module asks the host to place through the pack's placement stages ({@link Placements#place}).
*
* @param request the object and where it goes
* @param name the placement's display name, such as the object's key: it labels the placement in the host's logs and
* names the source of the settings the pack declares on it
* @param settings the placement as the pack wrote it, a JSON object, from which the host reads the settings that pack
* modules declare at {@link com.volmit.config.Level#PLACEMENT} so that stages see them like any other
* level's; the placement type's own fields ({@link com.volmit.FeatureRegistry#registerPlacementType}) are
* not settings and are ignored. Empty for a placement the pack did not write. Equal text is read once
* @param area the blocks the object may reach around its anchor in any way it is placed; the host widens it by the
* reach the pack's placement stages declare, and the result bounds the placement's {@link PlacementAccess}.
* Reaching outside fails the placement
* @param terrain the world the placement reads, and where the host writes the blocks when the placement commits
* @param input what the placing module hands its own stages, such as its placement settings; stages read it with
* {@link PlacementContext#input}, and stages of other modules do not know its type
* @param seed the seed the stages' random streams derive from; the same seed, stages and inputs give the same placement
*/
public record PlacementRun(PlacementRequest request, String name, Optional<String> settings, BlockBox area,
PlacementTerrain terrain, Object input, long seed) {
public PlacementRun {
Objects.requireNonNull(request, "request");
Objects.requireNonNull(name, "name");
Objects.requireNonNull(settings, "settings");
Objects.requireNonNull(area, "area");
Objects.requireNonNull(terrain, "terrain");
Objects.requireNonNull(input, "input");
}
}
@@ -0,0 +1,66 @@
package com.volmit.placement;
import com.volmit.block.BlockState;
import com.volmit.object.BlockEntityData;
import java.util.Optional;
/**
* The world a placement is made in, as its stages and the module that asked for it see it: blocks, the questions about a
* column the stages ask, and what the host keeps beside each block. X and Z are world coordinates; Y is the height above
* the dimension's bottom.
*
* <p>A module that places objects hands one to {@link Placements#place}: the terrain of its mantle invocation
* ({@link com.volmit.generation.MantleGenerationContext#placementTerrain()}), or its own, such as one that collects a
* growing tree's blocks. It may wrap another to change what it answers or to hold writes back. Stages read it through
* {@link PlacementContext#placementTerrain()} and write through {@link PlacementAccess}; the host writes a placement's
* blocks into it when the placement commits. Not thread-safe; it lives as long as the invocation it came from.
*/
public interface PlacementTerrain {
/** The height of the highest block of the column; {@code ignoreFluid} leaves out the fluid above the ground. */
int highest(int x, int z, boolean ignoreFluid);
BlockState get(int x, int y, int z);
/** Writes the block without a block entity. */
void set(int x, int y, int z, BlockState state);
/** Writes the block with its block entity, such as a chest's contents. */
void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity);
/** Whether the cave carver emptied the block. */
boolean isCarved(int x, int y, int z);
/** Whether the block is real, solid ground, which the terrain's heights alone cannot tell before the chunk is built. */
boolean isSurfaceSolid(int x, int y, int z);
boolean isUnderwater(int x, int z);
/** The height up to which the dimension is filled with fluid. */
int fluidHeight();
/** Whether leaves written here never decay. */
boolean preventsDecay();
/**
* Records that the block belongs to {@code placement}, one placed object, so a later placement can tell what is
* already there ({@link #placementAt}). The host keeps the record beside the block in its generation storage.
*/
void recordPlacement(int x, int y, int z, PlacementRecord placement);
/** The placement recorded at the block ({@link #recordPlacement}); empty when none is. */
Optional<PlacementRecord> placementAt(int x, int y, int z);
/** The bounds of the platform's structure pieces planned around the columns, for placements that keep out of them. */
StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ);
/**
* Keeps {@code marker} beside its block in the world's generation storage: a stage's marker when the placement
* commits ({@link PlacementAccess#marker}), or one the placing module adds to a placed block. Its type is something the
* module that writes it and the module or host that reads it agree on, such as a spawn marker. The host keeps the
* types it knows in its own form.
*
* @throws IllegalArgumentException when the host keeps no marker of this type
*/
void mark(PlacedMarker marker);
}
@@ -0,0 +1,15 @@
package com.volmit.placement;
/**
* Runs the pack's placement stages for an object a module places itself, such as the objects of a biome or a growing
* tree. The host offers it for every world ({@link com.volmit.world.PackWorld#placements()}); the stages are every
* module's placement stages of the pack, in the order the stage graph gives them.
*/
public interface Placements {
/**
* Places {@code run}'s object: the stages run with buffered writes, and the host writes the blocks, then the markers,
* into the run's terrain only when no stage rejects the placement and none throws. A stage that throws fails the call and nothing
* is written. Call it from the invocation the terrain belongs to.
*/
PlacementOutcome place(PlacementRun run);
}
@@ -0,0 +1,15 @@
package com.volmit.placement;
/**
* The bounds of the platform's structure pieces planned around a placement ({@link PlacementTerrain#structureVolumes}).
* X and Z are world coordinates; Y is the height above the dimension's bottom.
*/
public interface StructureVolumes {
boolean isEmpty();
/** Whether any piece meets the box, bounds inclusive. */
boolean intersects(int minX, int minY, int minZ, int maxX, int maxY, int maxZ);
/** Whether any piece contains the block or comes within {@code margin} blocks of it. */
boolean containsWithin(int x, int y, int z, int margin);
}
@@ -0,0 +1,281 @@
package com.volmit.random;
import com.volmit.resource.ResourceId;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.RandomAccess;
/** A random stream whose every value is defined here, so the same seed gives the same draws on
* every machine and every JDK. World generation draws from it: stages through
* {@link com.volmit.stage.StageContext#random()}.
*
* <p>It deliberately does not implement {@link java.util.random.RandomGenerator}: that interface's
* default methods, and any a later JDK adds, use algorithms the JDK may change, which would change
* existing worlds. Only the methods below exist, and each is specified exactly.
*
* <p><b>Algorithm.</b> The state is one {@code long}, initially the seed. {@link #nextLong()} is
* SplitMix64 (Steele, Lea and Flood, 2014): add {@code 0x9e3779b97f4a7c15} to the state, then return
* {@code mix(state)}, where {@code mix} is the finalizer
* {@code z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9; z = (z ^ (z >>> 27)) * 0x94d049bb133111eb; z ^ (z >>> 31)}.
* Every other method is defined on {@code nextLong()} values:
* <ul>
* <li>{@code nextInt()}: the high 32 bits of one value;</li>
* <li>{@code nextBoolean()}: whether one value is negative (its highest bit);</li>
* <li>{@code nextFloat()}: the high 24 bits of one value times 2<sup>-24</sup>;</li>
* <li>{@code nextDouble()}: the high 53 bits of one value times 2<sup>-53</sup>;</li>
* <li>bounded integers: Lemire's multiply-and-reject method, which is unbiased. For a range of
* {@code n} values, {@code ints} take the high 32 bits {@code x} of one value and compute the
* 64-bit product {@code x * n}, {@code longs} take one value {@code x} and compute the
* 128-bit product; when the product's low half is below 2<sup>32</sup> (or 2<sup>64</sup>)
* {@code mod n}, they draw again; the result is the product's high half plus the origin;</li>
* <li>bounded doubles: {@code origin + nextDouble() * (bound - origin)}, a result that rounds up
* to {@code bound} replaced by the largest double below it (see {@link #nextDouble(double, double)}
* for ranges wider than the largest double);</li>
* <li>{@code nextGaussian()}: Marsaglia's polar method on pairs of {@code nextDouble()} values,
* using {@link StrictMath}, whose results are fixed;</li>
* <li>{@code chance(p)}: {@code nextDouble() < p};</li>
* <li>{@code pick(items)}: {@code items.get(nextInt(items.size()))};</li>
* <li>{@code shuffle(items)}: Fisher-Yates, for {@code i} from {@code size - 1} down to {@code 1}
* swapping index {@code i} with {@code nextInt(i + 1)}.</li>
* </ul>
* Methods without rejection draw exactly one value. {@code nextInt(0, n)} equals {@code nextInt(n)}
* and {@code nextLong(0, n)} equals {@code nextLong(n)}.
*
* <p>Not thread-safe. One stage uses its stream within one invocation; do not share or retain it.
*/
public final class WorldRandom {
private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;
private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L;
private static final long FNV_PRIME = 0x100000001b3L;
private static final int INT_BITS = 32;
private static final long UNSIGNED_INT_MASK = 0xffff_ffffL;
private static final long INT_RANGE = 1L << INT_BITS;
private static final int FLOAT_SHIFT = Long.SIZE - 24;
private static final float FLOAT_UNIT = 0x1.0p-24f;
private static final int DOUBLE_SHIFT = Long.SIZE - 53;
private static final double DOUBLE_UNIT = 0x1.0p-53;
private long state;
public WorldRandom(long seed) {
state = seed;
}
/**
* The seed for {@code purpose} of a world whose seed is {@code worldSeed}: {@code mix(worldSeed ^ mix(h))}, where
* {@code mix} is the finalizer above and {@code h} the 64-bit FNV-1a hash (offset basis {@code 0xcbf29ce484222325},
* prime {@code 0x100000001b3}) of the UTF-8 bytes of {@code purpose.toString()}. Different purposes give independent
* seeds; see {@link com.volmit.world.PackWorld#seed(ResourceId)}.
*/
public static long purposeSeed(long worldSeed, ResourceId purpose) {
long hash = FNV_OFFSET_BASIS;
for (byte octet : purpose.toString().getBytes(StandardCharsets.UTF_8)) {
hash = (hash ^ (octet & 0xff)) * FNV_PRIME;
}
return mix(worldSeed ^ mix(hash));
}
/** A uniformly distributed {@code long}: the next SplitMix64 output. */
public long nextLong() {
state += GOLDEN_GAMMA;
return mix(state);
}
/** A uniformly distributed {@code long} in {@code [0, bound)}. Throws if {@code bound <= 0}. */
public long nextLong(long bound) {
if (bound <= 0) throw new IllegalArgumentException("bound must be positive: " + bound);
return boundedLong(bound);
}
/** A uniformly distributed {@code long} in {@code [origin, bound)}, for any {@code origin < bound},
* including ranges wider than {@code Long.MAX_VALUE}. Throws if {@code origin >= bound}.
*/
public long nextLong(long origin, long bound) {
if (origin >= bound) throw invalidRange(origin, bound);
return origin + boundedLong(bound - origin);
}
/** A uniformly distributed {@code int}: the high 32 bits of {@link #nextLong()}. */
public int nextInt() {
return (int) (nextLong() >>> INT_BITS);
}
/** A uniformly distributed {@code int} in {@code [0, bound)}. Throws if {@code bound <= 0}. */
public int nextInt(int bound) {
if (bound <= 0) throw new IllegalArgumentException("bound must be positive: " + bound);
return (int) boundedInt(bound);
}
/** A uniformly distributed {@code int} in {@code [origin, bound)}, for any {@code origin < bound},
* including ranges wider than {@code Integer.MAX_VALUE}. Throws if {@code origin >= bound}.
*/
public int nextInt(int origin, int bound) {
if (origin >= bound) throw invalidRange(origin, bound);
return (int) (origin + boundedInt((long) bound - origin));
}
/** {@code true} or {@code false} with equal probability: whether {@link #nextLong()} is negative. */
public boolean nextBoolean() {
return nextLong() < 0;
}
/** A uniformly distributed {@code float} in {@code [0, 1)}, a multiple of 2<sup>-24</sup>. */
public float nextFloat() {
return (nextLong() >>> FLOAT_SHIFT) * FLOAT_UNIT;
}
/** A uniformly distributed {@code double} in {@code [0, 1)}, a multiple of 2<sup>-53</sup>. */
public double nextDouble() {
return (nextLong() >>> DOUBLE_SHIFT) * DOUBLE_UNIT;
}
/** A {@code double} in {@code [0, bound)}: {@code nextDouble() * bound}, never {@code bound} itself.
* Throws unless {@code bound} is positive and finite.
*/
public double nextDouble(double bound) {
if (!(bound > 0 && bound < Double.POSITIVE_INFINITY)) {
throw new IllegalArgumentException("bound must be positive and finite: " + bound);
}
return belowBound(nextDouble() * bound, bound);
}
/** A {@code double} in {@code [origin, bound)}, never {@code bound} itself:
* {@code origin + nextDouble() * (bound - origin)}. When {@code bound - origin} exceeds the largest
* double, the range is halved first: {@code 2 * (origin / 2 + nextDouble() * (bound / 2 - origin / 2))}.
* Throws unless both are finite and {@code origin < bound}.
*/
public double nextDouble(double origin, double bound) {
if (!(origin < bound && Double.isFinite(origin) && Double.isFinite(bound))) {
throw new IllegalArgumentException("origin and bound must be finite with origin < bound: [" + origin + ", " + bound + ")");
}
double unit = nextDouble();
double width = bound - origin;
double value = Double.isFinite(width) ? origin + unit * width : 2 * (origin / 2 + unit * (bound / 2 - origin / 2));
return belowBound(value, bound);
}
/** A normally distributed {@code double} with mean 0 and standard deviation 1, by Marsaglia's polar
* method: draw {@code u = 2 * nextDouble() - 1} and {@code v = 2 * nextDouble() - 1} until
* {@code s = u * u + v * v} is in {@code (0, 1)}, then return
* {@code u * StrictMath.sqrt(-2 * StrictMath.log(s) / s)}. The second value of the pair is discarded.
*/
public double nextGaussian() {
double u;
double s;
do {
u = 2 * nextDouble() - 1;
double v = 2 * nextDouble() - 1;
s = u * u + v * v;
} while (s >= 1 || s == 0);
return u * StrictMath.sqrt(-2 * StrictMath.log(s) / s);
}
/** Whether an event of the given probability happens: {@code nextDouble() < probability}. Always
* draws one value, so {@code chance(0)} is never and {@code chance(1)} always true. Throws unless
* {@code probability} is in {@code [0, 1]}.
*/
public boolean chance(double probability) {
if (!(probability >= 0 && probability <= 1)) {
throw new IllegalArgumentException("probability must be in [0, 1]: " + probability);
}
return nextDouble() < probability;
}
/** One element chosen uniformly: {@code items.get(nextInt(items.size()))}, so it draws exactly what
* {@link #nextInt(int)} draws. Throws if {@code items} is empty.
*/
public <T> T pick(List<T> items) {
if (items.isEmpty()) throw new IllegalArgumentException("cannot pick from an empty list");
return items.get(nextInt(items.size()));
}
/** Shuffles {@code items} in place by Fisher-Yates: for {@code i} from {@code size - 1} down to
* {@code 1}, swap the elements at {@code i} and {@code nextInt(i + 1)}. A list of {@code n >= 2}
* elements takes {@code n - 1} {@code nextInt} calls; a shorter list draws nothing and is not touched.
*
* <p>{@link RandomAccess} lists are swapped through {@link List#set}. Other lists, such as
* {@link java.util.LinkedList}, are copied to an array, shuffled there and written back through
* their {@link ListIterator}, like {@link Collections#shuffle}; the result is the same. A list that
* does not support {@code set} throws its {@link UnsupportedOperationException} before any element
* changes.
*/
public void shuffle(List<?> items) {
if (items.size() < 2) return;
if (items instanceof RandomAccess) {
fisherYates(items.size(), (i, j) -> Collections.swap(items, i, j));
return;
}
shuffleThroughArray(items);
}
private void shuffleThroughArray(List<?> items) {
Object[] copy = items.toArray();
fisherYates(copy.length, (i, j) -> {
Object swapped = copy[i];
copy[i] = copy[j];
copy[j] = swapped;
});
@SuppressWarnings("unchecked")
ListIterator<Object> writer = (ListIterator<Object>) items.listIterator();
for (Object item : copy) {
writer.next();
writer.set(item);
}
}
/** The one place the shuffle order is defined, so both list kinds give the same result. */
private void fisherYates(int size, IndexSwap swap) {
for (int i = size - 1; i > 0; i--) swap.swap(i, nextInt(i + 1));
}
/** Lemire's method for {@code range} in {@code [1, 2^32]}: high half of a 32-by-32-bit product. */
private long boundedInt(long range) {
long product = (nextLong() >>> INT_BITS) * range;
long low = product & UNSIGNED_INT_MASK;
if (low < range) {
long threshold = (INT_RANGE - range) % range;
while (low < threshold) {
product = (nextLong() >>> INT_BITS) * range;
low = product & UNSIGNED_INT_MASK;
}
}
return product >>> INT_BITS;
}
/** Lemire's method for {@code range} in {@code [1, 2^64)}, read as unsigned: high half of a
* 64-by-64-bit product.
*/
private long boundedLong(long range) {
long value = nextLong();
long low = value * range;
if (Long.compareUnsigned(low, range) < 0) {
long threshold = Long.remainderUnsigned(-range, range);
while (Long.compareUnsigned(low, threshold) < 0) {
value = nextLong();
low = value * range;
}
}
return Math.unsignedMultiplyHigh(value, range);
}
private static double belowBound(double value, double bound) {
return value < bound ? value : Math.nextDown(bound);
}
private static IllegalArgumentException invalidRange(long origin, long bound) {
return new IllegalArgumentException("origin must be below bound: [" + origin + ", " + bound + ")");
}
@FunctionalInterface
private interface IndexSwap {
void swap(int i, int j);
}
private static long mix(long value) {
value = (value ^ (value >>> 30)) * 0xbf58476d1ce4e5b9L;
value = (value ^ (value >>> 27)) * 0x94d049bb133111ebL;
return value ^ (value >>> 31);
}
}
@@ -0,0 +1,45 @@
package com.volmit.resource;
import java.util.Objects;
/**
* What an item or entity a module hands the host is: a registered type by its {@link ResourceId}, or a mob or item of a
* content provider by the provider's own name for it. Provider names are kept as written because providers tell their
* content apart by case ({@code mythicmobs:SkeletonKing}, {@code mmoitems_SWORD:EXCALIBUR}), which no
* {@code ResourceId} can hold.
*/
public sealed interface ContentKey permits ContentKey.Registered, ContentKey.Provided {
/**
* A type in the platform's registries, such as {@code minecraft:diamond_sword}, or one the host routes by its
* namespace to the provider that owns it, such as {@code itemsadder:ruby}; the host decides which.
*/
record Registered(ResourceId id) implements ContentKey {
public Registered {
Objects.requireNonNull(id, "id");
}
@Override
public String toString() {
return id.toString();
}
}
/**
* A mob or item of a content provider: the provider, such as {@code mythicmobs}, and its name for the content, which
* may hold any character, {@code :} included.
*/
record Provided(String provider, String name) implements ContentKey {
public Provided {
Objects.requireNonNull(provider, "provider");
Objects.requireNonNull(name, "name");
if (provider.isBlank() || name.isBlank()) {
throw new IllegalArgumentException("A provided key needs a provider and a name: " + provider + ":" + name);
}
}
@Override
public String toString() {
return provider + ":" + name;
}
}
}
@@ -0,0 +1,76 @@
package com.volmit.resource;
import com.volmit.block.BlockRegistry;
import com.volmit.item.ItemRegistry;
import com.volmit.noise.NoiseFactory;
import com.volmit.noise.PackExpression;
import com.volmit.noise.PackImageMap;
import com.volmit.object.GeneratedObject;
import com.volmit.object.PackObjects;
import com.volmit.world.PackBiome;
import com.volmit.world.PackRegion;
import java.util.List;
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. A resource is named by its kind and its id, so one id can name
* both a biome and a region. Hosts serve the kinds {@link #BIOMES}, {@link #REGIONS}, {@link #OBJECTS},
* {@link #EXPRESSIONS} and {@link #IMAGE_MAPS} and every {@link ResourceKind} the pack's modules register; an id the pack lacks for that kind returns empty,
* and a kind the host does not serve 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 {
/** The pack's biomes, as the host reads them from its own folder. */
ResourceKind<PackBiome> BIOMES = ResourceKind.of("host:biome", "biomes", PackBiome.class);
/** The pack's regions, as the host reads them from its own folder. */
ResourceKind<PackRegion> REGIONS = ResourceKind.of("host:region", "regions", PackRegion.class);
/** The pack's objects as geometry, as the host reads them from its own folder. */
ResourceKind<GeneratedObject> OBJECTS = ResourceKind.of("host:object", "objects", GeneratedObject.class);
/** The pack's expressions, which noise styles use; the host compiles them from its own folder. */
ResourceKind<PackExpression> EXPRESSIONS = ResourceKind.of("host:expression", "expressions", PackExpression.class);
/** The pack's image maps, which noise styles use; the host reads them from its own folder. */
ResourceKind<PackImageMap> IMAGE_MAPS = ResourceKind.of("host:image-map", "image-maps", PackImageMap.class);
ResourceId packId();
UUID snapshotId();
BlockRegistry blocks();
/** Asks the platform about items, such as how much damage one takes. */
ItemRegistry items();
/** Builds the noise of the {@link com.volmit.noise.NoiseStyle}s the pack's settings describe. */
NoiseFactory noise();
/** The pack's objects ready to place, their scaled variants, and the objects modules build. */
PackObjects objects();
/** The resource of {@code kind} the pack has under {@code id}; empty when it has none. */
<T> Optional<T> find(ResourceKind<T> kind, ResourceId id);
/** The ids of every resource of {@code kind}, in id order. A kind the host does not serve throws
* IllegalArgumentException, as in {@link #find}.
*/
List<ResourceId> ids(ResourceKind<?> kind);
/** The id of the resource the pack's files name by {@code key} (the file path inside the kind's folder, without
* {@code .json}), such as {@code overworld:dungeon/chest} for {@code dungeon/chest}; see
* {@link ResourceId#ofPackKey}. Settings that name a resource in a {@code String}, such as a {@link com.volmit.config.Ref} option, or a
* biome's key in a region, hold such a key. Characters an id cannot hold are replaced the way the host does for its
* own ids, so use this and not {@code new ResourceId(packId().namespace(), key)}.
*/
default ResourceId idOf(String key) {
return ResourceId.ofPackKey(packId().namespace(), key);
}
/** {@link #find} for a resource that must exist: a missing one throws NoSuchElementException naming kind and id. */
default <T> T require(ResourceKind<T> kind, ResourceId id) {
return find(kind, id).orElseThrow(() -> new NoSuchElementException("Missing " + kind.id() + " resource: " + id));
}
}
@@ -0,0 +1,16 @@
package com.volmit.resource;
import com.volmit.config.Reference;
import java.util.Set;
/** The ids the running platform has registered, as the server has them, data packs and mods included: the entries a
* {@link com.volmit.config.Ref} option names. Read during validation; ids stay valid until the platform reloads them.
*/
public interface PlatformRegistries {
/** Every id the platform registers under {@code registry}, such as {@code minecraft:village_plains} for
* {@link Reference#STRUCTURE}; empty for a reference that is no platform registry ({@link Reference#STRUCTURE_PREFIX},
* {@link Reference#SPECIAL_ENTITY}, {@link Reference#NOISE_STYLE}) or one the platform lacks.
*/
Set<ResourceId> ids(Reference registry);
}
@@ -0,0 +1,63 @@
package com.volmit.resource;
import java.util.Locale;
import java.util.Objects;
import java.util.regex.Pattern;
/** Case-sensitive namespaced identity. {@link #parse} never supplies an implicit namespace; {@link #ofPackKey} and
* {@link #ofPlatformKey} turn the keys packs write into ids. */
public record ResourceId(String namespace, String path) implements Comparable<ResourceId> {
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PATH = Pattern.compile("[a-z0-9_./-]+");
private static final Pattern NOT_PATH = Pattern.compile("[^a-z0-9_./-]");
private static final String PATH_REPLACEMENT = "_";
private static final String PLATFORM_NAMESPACE = "minecraft";
public ResourceId {
Objects.requireNonNull(namespace, "namespace");
Objects.requireNonNull(path, "path");
if (!isNamespace(namespace) || !PATH.matcher(path).matches()) {
throw new IllegalArgumentException("Invalid resource ID: " + namespace + ":" + path);
}
}
/** Whether {@code value} is a valid namespace on its own, such as {@code iris}. */
public static boolean isNamespace(String value) {
return NAMESPACE.matcher(value).matches();
}
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));
}
/**
* The id a pack gives the resource its files name by {@code key}, such as {@code dungeon/chest} for
* {@code loot/dungeon/chest.json}: the pack's namespace and the key as the path, lower-cased, with every
* character outside {@code [a-z0-9_./-]} replaced by {@code _}. Keys that differ only in such characters share
* an id.
*/
public static ResourceId ofPackKey(String namespace, String key) {
Objects.requireNonNull(key, "key");
return new ResourceId(namespace, NOT_PATH.matcher(key.toLowerCase(Locale.ROOT)).replaceAll(PATH_REPLACEMENT));
}
/**
* The id of a platform key as packs write it, such as {@code minecraft:diamond_sword} for {@code DIAMOND_SWORD} or
* {@code Diamond Sword}: trimmed, lower-cased, spaces as {@code _}, in the {@code minecraft} namespace when it names
* none. Throws IllegalArgumentException when the result is still no id, such as for {@code a:b:c}.
*/
public static ResourceId ofPlatformKey(String key) {
Objects.requireNonNull(key, "key");
String normalized = key.trim().toLowerCase(Locale.ROOT).replace(' ', '_');
return parse(normalized.indexOf(':') < 0 ? PLATFORM_NAMESPACE + ":" + normalized : normalized);
}
@Override
public String toString() { return namespace + ":" + path; }
@Override
public int compareTo(ResourceId other) { return toString().compareTo(other.toString()); }
}
@@ -0,0 +1,55 @@
package com.volmit.resource;
import java.lang.reflect.Modifier;
import java.util.Objects;
import java.util.regex.Pattern;
/** A kind of resource read from the pack: every JSON file below {@code <pack>/<folder>/}, each read
* into a new instance of {@code type}. A file's key is its path below the folder without {@code .json}, such as
* {@code castle/keep}, and its id is {@code <pack namespace>:<key>}, the form {@link PackResources} uses for
* every pack resource. A resource is found by its kind and its id, {@link PackResources#find}{@code (kind, id)};
* the host tells kinds apart by {@code type}, so each kind has a class of its own. The host's own kinds are the
* constants of {@link PackResources}.
*
* <p>Modules register kinds with {@link com.volmit.FeatureRegistry#registerResourceKind}. The id names the kind
* in errors and studio and follows the module id like every other id the module owns: {@code iris:structure}
* owns {@code iris:structure/pool}. The folder is one folder name directly below the pack root, chosen by the
* module; one folder holds one kind, and the host's own folders belong to the host.
*
* <p>The host creates each resource with the type's no-argument constructor and reads the file's JSON into it,
* the way it reads settings, so an omitted field keeps its default. Resources are values: the host reads each
* once per pack load and hands every caller the same instance, so nobody may change one after it is read.
*/
public record ResourceKind<T>(ResourceId id, String folder, Class<T> type) {
private static final Pattern FOLDER = Pattern.compile("[a-z0-9_.-]+");
public ResourceKind {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(folder, "folder");
Objects.requireNonNull(type, "type");
requireFolderName(id, folder);
requireConcreteClass(id, type);
}
public static <T> ResourceKind<T> of(String id, String folder, Class<T> type) {
return new ResourceKind<>(ResourceId.parse(id), folder, type);
}
/** Whether {@code name} may name a kind's folder: one folder name of lowercase letters, digits, '-', '_' and '.'. */
public static boolean isFolderName(String name) {
return FOLDER.matcher(name).matches() && !name.equals(".") && !name.equals("..");
}
private static void requireFolderName(ResourceId id, String folder) {
if (isFolderName(folder)) return;
throw new IllegalArgumentException("Folder '" + folder + "' of resource kind " + id + " is not a folder name;"
+ " a kind reads one folder directly below the pack root, named with lowercase letters, digits, '-', '_' and '.'");
}
private static void requireConcreteClass(ResourceId id, Class<?> type) {
if (type.isPrimitive() || type.isArray() || type.isInterface() || Modifier.isAbstract(type.getModifiers())) {
throw new IllegalArgumentException("Resource kind " + id + " reads into " + type.getName()
+ ", which the host cannot create; use a concrete class with a no-argument constructor");
}
}
}
@@ -0,0 +1,113 @@
package com.volmit.service;
import com.volmit.entity.EntitySpec;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* The ambient effects of an area: sounds, particles, potion effects and commands that play around the players who stay
* in it. The host asks, now and then, for the players it keeps; the module says which effects of the area are due, and
* every random choice that goes with them (where the sound seems to come from, how the particles scatter, how long the
* potion lasts), so that the host only has to carry them out. An effect is due only now and then, as its interval and
* chance say, so most answers are empty. The host asks every provider and carries out all answers.
*/
@Service(Providers.ALL)
public interface AmbientEffects {
/**
* The effects due for a player standing at {@code at}.
*
* @param at world X and Z, Y the height above the dimension's bottom
*/
List<Effect> due(PackWorld world, BlockPosition at);
/**
* One effect that plays now. The host carries out the parts it has, in the order sound, particles, commands, potion.
* A part the platform lacks, such as an unknown sound, is skipped.
*
* @param sound a sound to play; empty for none
* @param particles particles to show; empty for none
* @param commands console commands to run, none when the effect has no commands that may run now
* @param potion a potion effect to give; empty for none
*/
record Effect(Optional<Sound> sound, Optional<Particles> particles, List<Command> commands, Optional<Potion> potion) {
public Effect {
Objects.requireNonNull(sound, "sound");
Objects.requireNonNull(particles, "particles");
commands = List.copyOf(commands);
Objects.requireNonNull(potion, "potion");
}
}
/**
* A sound played to the player.
*
* @param key the sound, such as {@code minecraft:ambient.cave}
* @param offsetX blocks from the player where the sound seems to come from, as the other offsets
* @param volume the sound's volume
* @param pitch the sound's pitch
*/
record Sound(ResourceId key, int offsetX, int offsetY, int offsetZ, float volume, float pitch) {
public Sound {
Objects.requireNonNull(key, "key");
}
}
/**
* Particles shown to the player.
*
* @param key the particle, such as {@code minecraft:ash}
* @param spot where they appear
* @param count how many particles; none makes {@code spread} their motion
* @param spread how far the particles spread along each axis, or their motion when {@code count} is 0
* @param extra an extra value some particles take; 0 for none
*/
record Particles(ResourceId key, Spot spot, int count, Spread spread, double extra) {
public Particles {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(spot, "spot");
Objects.requireNonNull(spread, "spread");
}
}
/**
* Where particles appear: {@code forward} blocks ahead of the player, {@code sideways} blocks to the right (negative
* for the left) and on the surface at that spot, one block up, moved by {@code jitterX} and {@code jitterZ} and by
* {@code lift} blocks up.
*/
record Spot(double forward, double sideways, double jitterX, double jitterZ, int lift) {
}
/** A distance along each axis. */
record Spread(double x, double y, double z) {
}
/**
* A command to run where the effect plays.
*
* @param command the commands, their delay and repeats; {@code {x}}, {@code {y}} and {@code {z}} stand for the block
* position
* @param offsetX blocks from the player where the command runs, as the other two
*/
record Command(EntitySpec.Command command, double offsetX, double offsetY, double offsetZ) {
public Command {
Objects.requireNonNull(command, "command");
}
}
/**
* A potion effect for the player. A player who has the same potion effect with a stronger amplifier keeps it.
*
* @param key the potion effect, such as {@code minecraft:night_vision}
* @param strength the amplifier
* @param ticks how long it lasts, in server ticks
*/
record Potion(ResourceId key, int strength, int ticks) {
public Potion {
Objects.requireNonNull(key, "key");
}
}
}
@@ -0,0 +1,44 @@
package com.volmit.service;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.item.ItemDrop;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
/**
* Items a module drops when a block breaks, in addition to or instead of the platform's. The host asks every provider
* when a player breaks a block in a world generated with the pack, drops the items of all answers where the block was
* and keeps the platform's own drops unless an answer replaces them.
*/
@Service(Providers.ALL)
public interface BlockDrops {
/** What this module drops for the block {@code broken}; {@link Result#NONE} when it does nothing for that block. */
Result drops(PackWorld world, Broken broken);
/**
* The block that was broken.
*
* @param position world X and Z, Y the height above the dimension's bottom
* @param block the block as it was
*/
record Broken(BlockPosition position, BlockState block) {
public Broken {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(block, "block");
}
}
/**
* @param drops the items to drop
* @param replacesVanillaDrops whether the platform's own drops of the block are not dropped
*/
record Result(List<ItemDrop> drops, boolean replacesVanillaDrops) {
public static final Result NONE = new Result(List.of(), false);
public Result {
drops = List.copyOf(drops);
}
}
}
@@ -0,0 +1,29 @@
package com.volmit.service;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.Optional;
/**
* Which biome a module puts underground. The host places the cave biome of a position itself, from the biome its regions give
* the column and its terrain; this service tells it where a module overrides that and where a cave biome gives way to the
* surface's. A pack has one provider, since two modules deciding the biome of the same cave could not both be right.
*/
@Service(Providers.ONE)
public interface CaveBiomes {
/**
* The pack biome the module puts at the position whatever the regions say, such as a band of the deep dark. Empty where it
* overrides nothing.
*
* @param y the height above the dimension's bottom
* @return the biome's pack id
*/
Optional<ResourceId> overriddenBiome(PackWorld world, int x, int y, int z);
/**
* How many blocks below the surface a position must lie for the pack biome {@code biome} to be the cave biome there;
* nearer the surface the surface's biome is. 0 for a biome that has no such limit. The answer depends on the world and the
* biome only: the host asks once per biome and keeps it while the world runs.
*/
int minDepthBelowSurface(PackWorld world, ResourceId biome);
}
@@ -0,0 +1,131 @@
package com.volmit.service;
import com.volmit.entity.EntitySpec;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* The entities a module spawns in the world over time: spawners the dimension, region and biomes list, and the spawners
* markers in the world name. The host decides when and where to look, asks the providers, and spawns what the first
* answer plans, after checking the conditions of the platform that come with it (light, the surface below, free space).
* It tells the module how many entities appeared so that the module can keep its limits on how often a spawner fires.
*/
@Service(Providers.ALL)
public interface EntitySpawns {
/** What the module plans to spawn in the chunk or at the marker, or empty to spawn nothing. */
Optional<Plan> plan(PackWorld world, Site site);
/** Called with the number of entities of {@code plan} that appeared, so the spawner's rate limits count them. */
void spawned(PackWorld world, Plan plan, int count);
/** The pack's entity {@code entity} as this module would spawn it, for tools that spawn one on request; empty for an unknown one. */
Optional<EntitySpec> entity(PackWorld world, ResourceId entity);
/**
* What a marker in the world means for spawning; empty for a marker this module does not know. A marker's tag is a
* key of the pack, as an object's marker block names it, and {@code tag} the id the pack gives it
* ({@link com.volmit.resource.PackResources#idOf}).
*/
Optional<MarkerRule> marker(PackWorld world, ResourceId tag);
/** Where entities may spawn. */
sealed interface Site permits Chunk, Marker {
}
/**
* An ambient spawn in a chunk.
*
* @param chunkX chunk coordinates
* @param livingEntities how many living entities the chunk already holds
* @param initial whether this is the spawn of a chunk that was just generated
*/
record Chunk(int chunkX, int chunkZ, int livingEntities, boolean initial) implements Site {
}
/**
* A spawn at a marker.
*
* @param position the marker's block: world X and Z, Y the height above the dimension's bottom
* @param marker the id of the marker's tag, as {@link EntitySpawns#marker} takes it
* @param spawner the pack's spawner chosen among the marker's
* @param initial whether the spawner's initial spawns are used rather than its ordinary ones
*/
record Marker(BlockPosition position, ResourceId marker, ResourceId spawner, boolean initial) implements Site {
public Marker {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(marker, "marker");
Objects.requireNonNull(spawner, "spawner");
}
}
/**
* What a marker does.
*
* @param spawners the pack's spawners at the marker
* @param emptyAbove whether it only counts with free space above it
* @param removeOnChange whether it goes away when its block changes
*/
record MarkerRule(List<ResourceId> spawners, boolean emptyAbove, boolean removeOnChange) {
public MarkerRule {
spawners = List.copyOf(spawners);
}
}
/**
* Entities to spawn, tried one after the other.
*
* @param spawner the pack's spawner that planned them
* @param chunkX the chunk they spawn in, where the spawner's per-chunk limit counts them
* @param exhaustsMarker whether the marker that led here is used up and should be removed
* @param attempts the spawns to try
*/
record Plan(ResourceId spawner, int chunkX, int chunkZ, boolean exhaustsMarker, List<Attempt> attempts) {
public Plan {
Objects.requireNonNull(spawner, "spawner");
attempts = List.copyOf(attempts);
}
}
/**
* One entity to spawn at a block. The host spawns it only if the block's light level lies in the range (when the
* range is restricted) and, when {@code checkSurface}, the block below suits the entity's {@code surface} and the
* space the entity needs is free.
*
* @param at world X and Z, Y the height above the dimension's bottom
* @param entity what to spawn
* @param surface the kind of ground or fluid the entity needs below it
* @param minLight lowest light level allowed, 0 for any
* @param maxLight highest light level allowed, 15 for any
* @param checkSurface whether to check the surface and the free space
*/
record Attempt(BlockPosition at, EntitySpec entity, Surface surface, int minLight, int maxLight, boolean checkSurface) {
public Attempt {
Objects.requireNonNull(at, "at");
Objects.requireNonNull(entity, "entity");
Objects.requireNonNull(surface, "surface");
}
/** Whether the light level matters. */
public boolean restrictsLight() {
return minLight > 0 || maxLight < 15;
}
}
/** The ground or fluid an entity spawns on. */
enum Surface {
/** Solid ground. */
LAND,
/** Ground animals spawn on, such as grass, dirt and podzol. */
ANIMAL,
/** Within water. */
WATER,
/** Solid ground or water. */
OVERWORLD,
/** Within lava. */
LAVA
}
}
@@ -0,0 +1,29 @@
package com.volmit.service;
import com.volmit.geometry.BlockPosition;
import java.util.Objects;
/** How a search for something in a world ended: found at a position, not there, or given up before covering the whole
* area asked for.
*/
public sealed interface LocateResult {
LocateResult NOT_FOUND = new NotFound();
LocateResult SEARCH_LIMIT_REACHED = new SearchLimitReached();
static LocateResult found(BlockPosition position) {
return new Found(position);
}
/** Found at {@code position}: world X and Z, and Y the height above the dimension's bottom. */
record Found(BlockPosition position) implements LocateResult {
public Found {
Objects.requireNonNull(position, "position");
}
}
/** The whole area was searched and holds none. */
record NotFound() implements LocateResult {}
/** The search stopped before covering the area, such as after checking as many candidates as it allows itself. */
record SearchLimitReached() implements LocateResult {}
}
@@ -0,0 +1,78 @@
package com.volmit.service;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.item.ItemDrop;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
/**
* The loot a module gives containers and mobs. The host asks in two steps so that it, and plugins listening to it, can
* see and change which tables are used: {@link #tables} names the tables a container draws from, {@link #items} turns
* one table into items. The host asks every provider and puts the answers together; a provider answers {@link #items}
* only for the tables it knows. A container is filled with items the host creates on the platform, in the order of the
* tables, and its slots are then shuffled with the seed {@link #shuffleSeed} gives.
*/
@Service(Providers.ALL)
public interface Loot {
/**
* The tables the container at {@code site} draws from, in the order their items are added. Empty when the module
* gives that container nothing.
*/
List<Source> tables(PackWorld world, Site site);
/** The items the pack's table {@code table} gives at {@code site}; empty for a table this module does not know. */
List<ItemDrop> items(PackWorld world, Site site, ResourceId table);
/**
* The seed the host shuffles the slots of the container at {@code site} with after it filled it, so that the same
* container always ends up with its items in the same slots. Empty to leave the order to the host's other providers;
* the host uses the first seed it gets, in module id order, and keeps the items in the order of the tables when no
* provider gives one.
*/
default OptionalLong shuffleSeed(PackWorld world, Site site) {
return OptionalLong.empty();
}
/**
* Where loot is given.
*
* @param position the container, or the mob's spawn spot: world X and Z, Y the height above the dimension's
* bottom
* @param container the container's block when it is a storage chest the module may give the loot of the object
* placed there; empty for any other spot
* @param nativeLootDefined whether the platform already gave the container a loot table of its own
* @param debug whether items should say where they came from ({@link ItemDrop#source()})
*/
record Site(BlockPosition position, Optional<BlockState> container, boolean nativeLootDefined, boolean debug) {
public Site {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(container, "container");
}
}
/** Where a container's items come from. */
sealed interface Source permits Table, PlatformTable {
}
/** A loot table of the pack, by the id {@link com.volmit.resource.PackResources#idOf} gives its key. */
record Table(ResourceId id) implements Source {
public Table {
Objects.requireNonNull(id, "id");
}
}
/**
* A loot table of the platform, such as {@code minecraft:chests/simple_dungeon}. The host draws it with {@code seed}
* so that the same container always gets the same items.
*/
record PlatformTable(ResourceId table, long seed) implements Source {
public PlatformTable {
Objects.requireNonNull(table, "table");
}
}
}
@@ -0,0 +1,42 @@
package com.volmit.service;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.Objects;
import java.util.Set;
/** Which pack objects a module places, predicted without generating anything. The host's object search and its
* studio tools ask every provider and use all the answers together.
*/
@Service(Providers.ALL)
public interface ObjectsAt {
/**
* The ids of the pack objects this module would place in the chunk at {@code chunkX}, {@code chunkZ} (chunk
* coordinates, world X and Z divided by 16), as {@link com.volmit.resource.PackResources#idOf} gives them. It is a
* prediction: it may name an object whose placement the chunk's generation later rejects. Empty when the module
* places nothing there.
*/
Set<ResourceId> objectsAt(PackWorld world, int chunkX, int chunkZ);
/**
* The biomes and regions of {@code world}'s layout whose own settings make this module place the object
* {@code object}. The host finds the areas where the object can appear from these: a biome counts for the areas
* it generates in and, through its children, for the areas of the biomes inside it, so a provider names only the
* layout entries that place the object themselves. Only biomes and regions the dimension can reach are named.
*/
PlacedBy placedBy(PackWorld world, ResourceId object);
/** Layout entries that place an object, by their pack ids. */
record PlacedBy(Set<ResourceId> biomes, Set<ResourceId> regions) {
public static final PlacedBy NOTHING = new PlacedBy(Set.of(), Set.of());
public PlacedBy {
biomes = Set.copyOf(Objects.requireNonNull(biomes, "biomes"));
regions = Set.copyOf(Objects.requireNonNull(regions, "regions"));
}
public boolean isEmpty() {
return biomes.isEmpty() && regions.isEmpty();
}
}
}
@@ -0,0 +1,18 @@
package com.volmit.service;
import com.volmit.world.PackWorld;
/**
* Whether the lowest layer of the world, the blocks at height 0, belongs to the module that shapes the terrain, such as
* a bedrock floor it writes itself. When it does, the host discards the blocks that placements and other stages write
* there, so that nothing replaces the floor. A pack has one provider, since two modules could not both own the floor.
* Without a provider the host protects nothing.
*/
@Service(Providers.ONE)
public interface ProtectedFloor {
/**
* Whether the host discards blocks written at height 0 of {@code world}. The answer depends on the world and its
* settings only: the host asks once when it starts the world and keeps it while the world runs.
*/
boolean protectsFloor(PackWorld world);
}
@@ -0,0 +1,16 @@
package com.volmit.service;
/** How the host combines the providers of one {@link Service}. A service chooses one; its javadoc says how the host
* uses the answers. Providers are always in module id order, each module's in the order it registered them, so the
* outcome never depends on how modules were discovered.
*/
public enum Providers {
/** The host asks every provider and combines their answers, such as the objects each module places in a chunk. */
ALL,
/** The host asks the providers in order until one answers, such as the module that knows a structure key. A provider
* that has no answer says so in the service's own terms (an empty result) and the next one is asked.
*/
FIRST,
/** A pack has at most one provider. A second module registering one fails the pack load, naming both modules. */
ONE
}
@@ -0,0 +1,82 @@
package com.volmit.service;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.placement.PlacedBlock;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* Trees a module grows when a sapling or mushroom grows in a world generated with the pack, and which objects it
* counts as trees. The host asks every provider in order when something grows and uses the first {@link Growth}; no
* answer leaves the growth to the platform. The module decides what grows and the blocks it consists of; the host
* clears the sapling, places the blocks on the right thread and tells listeners.
*/
@Service(Providers.ALL)
public interface SaplingGrowth {
/**
* The tree that replaces the growth at {@code sapling}, or empty to leave it to the platform. Reads the world around
* the sapling through {@code surroundings}, which is only valid during the call and sees the saplings that are
* growing as air.
*/
Optional<Growth> grow(PackWorld world, Sapling sapling, Surroundings surroundings);
/** The objects of the pack this module places as trees, for tools that tell trees from other objects. */
TreeObjects treeObjects(PackWorld world);
/**
* What grows.
*
* @param at where the growth happened: world X and Z, Y the height above the dimension's bottom
* @param center the middle of the plane of saplings that grow together, the same way
* @param species the kind of tree that would grow, as the platform names it, such as {@code minecraft:tree} or
* {@code minecraft:jungle} (Bukkit's tree types, lower-cased)
*/
record Sapling(BlockPosition at, BlockPosition center, ResourceId species) {
public Sapling {
Objects.requireNonNull(at, "at");
Objects.requireNonNull(center, "center");
Objects.requireNonNull(species, "species");
}
}
/** The world around a growing sapling, read where the tree is placed. X and Z are world coordinates, Y the height above the dimension's bottom. */
interface Surroundings {
/** The height of the topmost block at the column, ignoring fluids when {@code ignoreFluid}. */
int highest(int x, int z, boolean ignoreFluid);
BlockState get(int x, int y, int z);
}
/**
* The tree to place.
*
* @param object the id of the object the tree comes from, as {@link com.volmit.resource.PackResources#idOf} gives it
* for the object's key
* @param blocks the blocks to place, in order, later ones over earlier ones
*/
record Growth(ResourceId object, List<PlacedBlock> blocks) {
public Growth {
Objects.requireNonNull(object, "object");
blocks = List.copyOf(blocks);
}
}
/**
* Objects a module places as trees, by the ids {@link com.volmit.resource.PackResources#idOf} gives the names they
* are placed under.
*
* @param objects objects its placements mark as trees, one per variant of an object that bakes several
*/
record TreeObjects(Set<ResourceId> objects) {
public static final TreeObjects NONE = new TreeObjects(Set.of());
public TreeObjects {
objects = Set.copyOf(objects);
}
}
}
@@ -0,0 +1,25 @@
package com.volmit.service;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** Marks an interface as a service: a capability modules provide and the host looks up, such as finding a module's
* structures, instead of knowing the feature behind it. Modules register providers with
* {@link com.volmit.FeatureRegistry#registerService}; the host gets them from the pack's catalog.
*
* <p>Providers hold no state of their own: a provider is shared by every world, and the host may call it from any
* thread, also from several at once. A provider keeps what it needs in the world's state store
* ({@link com.volmit.world.PackWorld#state}), which is why service methods take the world. Services compute answers;
* they never act on the platform themselves: what should happen in the world comes back as a value the host carries out
* on the right thread.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Service {
/** How the host treats several modules providing this service. */
Providers value();
}
@@ -0,0 +1,74 @@
package com.volmit.service;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.Set;
/** Finds the structures a module places, for the host's structure commands, index and locate. Structures are named by
* their ids: a pack's own structure by the id {@link PackResources#idOf} gives its key ({@code overworld:villages/plains}),
* a platform structure by the platform's id ({@code minecraft:ancient_city}). The host asks the providers in order and
* sends an id to the first that places it in the world: {@link #placed} for the structures the module places itself,
* {@link #locatableStarts} for the platform structures it starts ({@link VanillaStructures#starts}).
*/
@Service(Providers.FIRST)
public interface StructureLocator {
/** Every structure of the pack this module knows, placed in a world or not, such as one per structure file. The
* host lists them in its index of the structures a pack has.
*/
Set<ResourceId> structures(PackResources pack);
/** The structures this module places in {@code world} and can find with {@link #locate}: commands offer them and
* send a search for one of them here. A structure no placement of the world uses is not among them.
*/
Set<ResourceId> locatable(PackWorld world);
/** The structures {@link #locate} finds among those this module places in {@code world}, locatable or not: its own
* structures, the platform structures it starts itself and the platform structures its own stand in for. Commands
* report them and send a search for one of them here. By default the {@link #locatable} ones.
*/
default Set<ResourceId> placed(PackWorld world) {
return locatable(world);
}
/**
* The start of {@code structure} nearest to the column {@code fromX}, {@code fromZ} (world coordinates), searched
* up to {@code maxRadiusChunks} chunks away from it. The position is the structure's origin: world X and Z, and Y the
* height above the dimension's bottom of its base. Called with an id from {@link #placed}. May take long; the
* host calls it off the server's main thread.
*/
LocateResult locate(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRadiusChunks);
/** The platform structures this module starts itself in {@code world} ({@link VanillaStructures#starts}), wherever
* its own placements put them. The host's locate and structure commands send them to {@link #locateStart}.
*/
default Set<ResourceId> startedStructures(PackWorld world) {
return Set.of();
}
/** Those of {@link #startedStructures} whose starts {@link #locateStart} can find in {@code world}: a start whose
* placement can never start in the world's height, for one, cannot be searched for.
*/
default Set<ResourceId> locatableStarts(PackWorld world) {
return Set.of();
}
/**
* The start of the platform structure {@code structure} this module makes nearest to the column {@code fromX},
* {@code fromZ} (world coordinates), searched ring by ring outward through its placements' grids up to {@code maxRings}
* rings: the nearest start of the first ring that has one. The position is the start's origin: world X and Z, and Y the
* height above the dimension's bottom of its base. Only chunks {@code accepts} allows count; the host checks the start
* the platform made there and searches again without a chunk it refuses. An exception {@code accepts} throws ends the
* search and reaches the caller. Called with a structure from {@link #locatableStarts}, off the server's main thread.
*/
default LocateResult locateStart(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRings,
ChunkFilter accepts) {
return LocateResult.NOT_FOUND;
}
/** Which chunks a {@link #locateStart} search may answer with. */
@FunctionalInterface
interface ChunkFilter {
boolean accepts(int chunkX, int chunkZ);
}
}
@@ -0,0 +1,38 @@
package com.volmit.service;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.DecorationStep;
import com.volmit.world.PackWorld;
import java.util.Optional;
/**
* A module's say over the platform's own placed features in the pack's worlds: the ores, trees, plants, springs and other
* decorations Minecraft, data packs and mods declare for a biome. By default the platform runs none of them over the pack's
* terrain. The host asks every provider, in module id order: it runs the platform's feature pass in a world when any
* provider turns it on with {@link #generates}, and then skips a decoration step or a feature that any provider refuses.
*
* <p>Every answer is decided from the world alone (its settings and resources), never from a position: the host asks once
* per world, and once per world and step or feature, and keeps the answer while the world runs. Every method may be
* called from any thread, concurrently.
*/
@Service(Providers.ALL)
public interface VanillaFeatures {
/** Whether the platform runs its placed features over the terrain of {@code world}. False when the module has no part in it. */
default boolean generates(PackWorld world) {
return false;
}
/**
* Whether the platform places the features of decoration step {@code step} in {@code world}: empty for a step of a newer
* platform the API does not know yet. True when the module has no part in it.
*/
default boolean generatesStep(PackWorld world, Optional<DecorationStep> step) {
return true;
}
/** Whether the platform places the feature {@code feature}, such as {@code minecraft:ore_diamond}, in {@code world}. True when the module has no part in it. */
default boolean generatesFeature(PackWorld world, ResourceId feature) {
return true;
}
}
@@ -0,0 +1,95 @@
package com.volmit.service;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.PlatformStart;
import com.volmit.vanilla.StartMemo;
import com.volmit.vanilla.StartReach;
import com.volmit.vanilla.StructureFit;
import com.volmit.vanilla.VanillaStructureContext;
import com.volmit.vanilla.VanillaStructureRule;
import com.volmit.vanilla.VanillaStructureSetup;
import com.volmit.vanilla.VanillaStructureStart;
import com.volmit.vanilla.VanillaStructureStartContext;
import java.util.List;
import java.util.Optional;
/** A module's say over the platform's own structures, the ones Minecraft, data packs and mods register, in the pack's
* worlds. The host asks every provider, in module id order:
*
* <ul>
* <li>{@link #rule} before the platform starts one of its structures, and when it locates one;</li>
* <li>{@link #starts} for every chunk, for the starts modules place where the platform would not;</li>
* <li>{@link #shift} before it publishes a start the platform made itself, and {@link #reach} before it publishes any
* start;</li>
* <li>{@link #beforePieces} and {@link #afterPieces} around the platform placing the starts' pieces in a chunk;</li>
* <li>{@link #setup} before a world of the dimension exists, when the platform sets up its structures and when the
* host installs data packs.</li>
* </ul>
*
* <p>The host asks {@link #rule} once per world, structure and pack snapshot and keeps the answer, so a rule is decided
* from the pack (its settings and resources) and never from where a start would be. Rules combine with
* {@link VanillaStructureRule#and}: any module may block the platform's starts. Shifts add up; reaches are all covered;
* setups combine with {@link VanillaStructureSetup#and}. Every method may be called from any thread, concurrently, but
* one chunk's {@link StructureFit} is used on one thread. Finding the starts a module makes is
* {@link StructureLocator}'s, the one service that locates structures.
*/
@Service(Providers.ALL)
public interface VanillaStructures {
/** What this module wants for the platform structure {@code structure}, such as {@code minecraft:village_plains},
* in the world {@code context} describes. {@link VanillaStructureRule#GENERATE} when the module has no part in it.
*/
default VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) {
return VanillaStructureRule.GENERATE;
}
/** The platform structures this module starts in chunk {@code chunkX, chunkZ}: starts the platform generates from
* that chunk, wherever its own placement rules would put them. At most one start per structure and chunk counts;
* the host keeps the first, in module id order. Decided from the world and the chunk only, so the same chunk always
* gets the same starts: the host asks again when it locates structures and when it checks a start it finds in
* the world.
*/
default List<VanillaStructureStart> starts(int chunkX, int chunkZ, VanillaStructureStartContext context) {
return List.of();
}
/** How many blocks the platform's own start {@code start} moves up (negative: down) before the host publishes it.
* Decided from the start's place and the terrain only, so asking again for the same start gives the same answer:
* the host asks again when it predicts where the platform's starts end up. The host keeps the start inside the
* world, moving it less when it would leave it. 0 when the module has no part in it.
*/
default int shift(PlatformStart start, VanillaStructureContext context) {
return 0;
}
/** How far around its pieces this module changes the terrain for a start of {@code structure}: a start the module
* placed itself, with the {@code memo} it gave it, or one of the platform's own starts (no memo; {@code underground}
* says whether the platform generates the structure in one of its underground steps). The platform hands the start to
* every chunk the reach covers, so {@link #beforePieces} sees it there. {@link StartReach#PLATFORM} when the module
* changes no more than the platform's own terrain adaptation would.
*/
default StartReach reach(ResourceId structure, boolean underground, Optional<StartMemo> memo,
VanillaStructureContext context) {
return StartReach.PLATFORM;
}
/** Called once per chunk before the platform places any piece of {@code fit}'s starts there: the module fits the
* terrain to the starts it cares about, writing only inside {@link StructureFit#area()}.
*/
default void beforePieces(StructureFit fit) {
}
/** Called after the platform placed the pieces of {@code placed}, one of {@code fit}'s starts, in the chunk, before
* it places the next start's; the last call of a chunk is for the last of {@link StructureFit#starts()}.
*/
default void afterPieces(StructureFit fit, StructureFit.Start placed) {
}
/** What this module changes about how the platform sets up its structures for the dimension {@code context}
* describes. Protecting the platform's definitions in one dimension protects them in every data pack the host
* installs, since those are shared by every world. {@link VanillaStructureSetup#UNCHANGED} when the module has no
* part in it.
*/
default VanillaStructureSetup setup(VanillaStructureContext context) {
return VanillaStructureSetup.UNCHANGED;
}
}
Loaded 100 of 365 files, more files were not shown because too many files have changed in this diff. Show more