Merge wave1/a1

This commit is contained in:
piexel committed 2026-10-09 14:43:33 +02:00
commit adb848bf9f
29 files changed
+1286 -17

No files matched your search

@@ -6,6 +6,7 @@ import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.random.WorldRandom;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.TerrainSampler;
@@ -65,6 +66,11 @@ final class ChunkInvocation implements ChunkStageContext {
return inputs.worldSeed();
}
@Override
public PackWorld world() {
return inputs.world();
}
@Override
public PackResources resources() {
return inputs.resources();
@@ -1,16 +1,19 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.service.Providers;
import com.volmit.service.Service;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.function.Function;
/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators are in module id order,
* so nothing depends on discovery. Factory, codec and validator implementations must themselves obey their
* concurrency contracts.
/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators, lifecycle hooks and service
* providers are in module id order, each module's in the order it registered them, so nothing depends on discovery.
* Factory, codec, validator, hook and provider implementations must themselves obey their concurrency contracts.
*/
public final class FeatureCatalog {
private final Map<Class<?>, FeatureDescriptor<?>> settings;
@@ -18,20 +21,24 @@ public final class FeatureCatalog {
private final Map<String, MantleRegistration<?>> mantle;
private final List<ResourceKindRegistration> resourceKinds;
private final List<ValidatorRegistration> validators;
private final List<LifecycleRegistration> lifecycles;
private final List<ServiceRegistration> services;
FeatureCatalog(
Map<Class<?>, FeatureDescriptor<?>> settings,
Map<Class<?>, ObjectRegistration<?>> objects,
Map<String, MantleRegistration<?>> mantle,
Collection<ResourceKindRegistration> resourceKinds,
List<ValidatorRegistration> validators) {
List<ValidatorRegistration> validators,
List<LifecycleRegistration> lifecycles,
List<ServiceRegistration> services) {
this.settings = Map.copyOf(settings);
this.objects = Map.copyOf(objects);
this.mantle = Map.copyOf(mantle);
this.resourceKinds = sorted(resourceKinds, registration -> registration.kind().id());
this.validators = validators.stream()
.sorted(Comparator.comparing(registration -> registration.module().info().id()))
.toList();
this.validators = inModuleOrder(validators, ValidatorRegistration::module);
this.lifecycles = inModuleOrder(lifecycles, LifecycleRegistration::module);
this.services = inModuleOrder(services, ServiceRegistration::module);
}
/** Settings types that activate stages; the host decodes them from pack JSON. */
@@ -57,6 +64,47 @@ public final class FeatureCatalog {
return validators;
}
/** The lifecycle hooks modules registered, by module id, each module's in the order it registered them. */
public List<LifecycleRegistration> lifecycles() {
return lifecycles;
}
/** Every provider of {@code service}, an interface marked {@link Service}, in module id order and each module's in the
* order it registered them; empty when no module provides it.
*/
public <S> List<S> services(Class<S> service) {
requireService(service);
return services.stream()
.filter(registration -> registration.service() == service)
.map(registration -> service.cast(registration.provider()))
.toList();
}
/** The one provider of {@code service}, a service whose providers are {@link Providers#ONE}, if a module provides it. */
public <S> Optional<S> service(Class<S> service) {
if (requireService(service).value() != Providers.ONE) {
throw new IllegalArgumentException("Service " + service.getName() + " may have several providers; ask for all of"
+ " them with services(...)");
}
return services(service).stream().findFirst();
}
/** The {@link Service} annotation of {@code type}, which must be an interface carrying one. */
static Service requireService(Class<?> type) {
var service = type.isInterface() ? type.getAnnotation(Service.class) : null;
if (service == null) {
throw new IllegalArgumentException(type.getName() + " is not a service: services are interfaces marked @"
+ Service.class.getName());
}
return service;
}
private static <T> List<T> inModuleOrder(List<T> registrations, Function<? super T, DiscoveredModule> module) {
return registrations.stream()
.sorted(Comparator.comparing(registration -> module.apply(registration).info().id()))
.toList();
}
private static <T, K extends Comparable<? super K>> List<T> sorted(
Collection<T> registrations,
Function<? super T, ? extends K> key) {
@@ -0,0 +1,12 @@
package com.volmit.host;
import com.volmit.ModuleLifecycle;
import java.util.Objects;
/** Lifecycle hooks and the module that registered them, which the host names when a hook fails. */
public record LifecycleRegistration(ModuleLifecycle lifecycle, DiscoveredModule module) {
public LifecycleRegistration {
Objects.requireNonNull(lifecycle, "lifecycle");
Objects.requireNonNull(module, "module");
}
}
@@ -0,0 +1,95 @@
package com.volmit.host;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
/** Calls the lifecycle hooks of one pack's modules ({@link FeatureCatalog#lifecycles()}) the way
* {@link com.volmit.ModuleLifecycle} promises: loading and starting in module id order, stopping in reverse.
*
* <pre>{@code
* var lifecycles = new LifecycleRunner(pack.catalog());
* lifecycles.packLoaded(resources, packSettings); // once per pack snapshot, before its first world starts
* lifecycles.worldStarted(world); // before the world generates anything
* ...
* lifecycles.worldStopped(world); // then close the world's state
* }</pre>
*
* A failure names the module whose hook failed. The runner keeps no state: the host decides when a snapshot is loaded
* and which worlds run, and calls one method at a time per world.
*/
public final class LifecycleRunner {
private final List<LifecycleRegistration> lifecycles;
public LifecycleRunner(FeatureCatalog catalog) {
this.lifecycles = Objects.requireNonNull(catalog, "catalog").lifecycles();
}
/** Runs every {@code packLoaded} hook in order; the first that throws ends the run with an IllegalStateException
* naming its module, and the hooks after it do not run.
*/
public void packLoaded(PackResources resources, PackSettings settings) {
Objects.requireNonNull(resources, "resources");
Objects.requireNonNull(settings, "settings");
for (var registration : lifecycles) {
try {
registration.lifecycle().packLoaded(resources, settings);
} catch (RuntimeException failure) {
throw failed("loading pack " + resources.packId(), registration, failure);
}
}
}
/** Runs every {@code worldStarted} hook in order. When one throws, the modules started before it are stopped again,
* in reverse, and an IllegalStateException naming the failed module is thrown, with failures of those stops
* suppressed in it.
*/
public void worldStarted(PackWorld world) {
Objects.requireNonNull(world, "world");
for (int index = 0; index < lifecycles.size(); index++) {
var registration = lifecycles.get(index);
try {
registration.lifecycle().worldStarted(world);
} catch (RuntimeException failure) {
var startFailure = failed("starting a world", registration, failure);
stopInReverse(world, index - 1, startFailure);
throw startFailure;
}
}
}
/** Runs every {@code worldStopped} hook in reverse order, each even when an earlier one threw; afterwards throws the
* first failure, naming its module, with the later ones suppressed.
*/
public void worldStopped(PackWorld world) {
Objects.requireNonNull(world, "world");
IllegalStateException failure = stopInReverse(world, lifecycles.size() - 1, null);
if (failure != null) {
throw failure;
}
}
/** Stops the modules from {@code last} down to the first, collecting failures into {@code failure}. */
private IllegalStateException stopInReverse(PackWorld world, int last, IllegalStateException failure) {
for (int index = last; index >= 0; index--) {
var registration = lifecycles.get(index);
try {
registration.lifecycle().worldStopped(world);
} catch (RuntimeException stopFailure) {
var named = failed("stopping a world", registration, stopFailure);
if (failure == null) {
failure = named;
} else {
failure.addSuppressed(named);
}
}
}
return failure;
}
private static IllegalStateException failed(String action, LifecycleRegistration registration, RuntimeException cause) {
return new IllegalStateException("Module " + registration.module() + " failed while " + action + ": " + cause, cause);
}
}
@@ -5,6 +5,7 @@ import com.volmit.generation.MantleGenerationContext;
import com.volmit.mantle.Mantle;
import com.volmit.random.WorldRandom;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import com.volmit.stage.MantleStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.TerrainSampler;
@@ -59,6 +60,11 @@ final class MantleInvocation implements MantleStageContext {
return inputs.worldSeed();
}
@Override
public PackWorld world() {
return inputs.world();
}
@Override
public PackResources resources() {
return inputs.resources();
@@ -4,12 +4,14 @@ import com.volmit.FeatureAttachment;
import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.IrisModule;
import com.volmit.ModuleLifecycle;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import com.volmit.service.Providers;
import com.volmit.validation.Validator;
import java.util.ArrayList;
import java.util.HashMap;
@@ -26,7 +28,8 @@ import java.util.Set;
* {@link #register(DiscoveredModule)}; object feature ids, mantle keys, resource kind ids and explicitly registered
* settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}).
* Resource kinds have unique ids, types and folders, and no kind may read a folder the host reserves for its own
* files. A failed registration leaves the registry unchanged. A failed module callback
* files. Lifecycle hooks and service providers are registered by the module that owns them; a service whose providers
* are {@link Providers#ONE} has at most one. A failed registration leaves the registry unchanged. A failed module callback
* invalidates the host's whole build. This does not decode JSON, discover modules or instantiate
* settings.
*/
@@ -40,6 +43,8 @@ public final class ModuleRegistry implements FeatureRegistry {
private final Map<Field, String> fields = new HashMap<>();
private final Map<ResourceId, ResourceKindRegistration> resourceKinds = new HashMap<>();
private final List<ValidatorRegistration> validators = new ArrayList<>();
private final List<LifecycleRegistration> lifecycles = new ArrayList<>();
private final List<ServiceRegistration> services = new ArrayList<>();
private final Set<String> reservedFolders;
private final List<DiscoveredModule> registered = new ArrayList<>();
private FeatureCatalog catalog;
@@ -129,6 +134,32 @@ public final class ModuleRegistry implements FeatureRegistry {
validators.add(new ValidatorRegistration(validator, registering));
}
@Override
public void registerLifecycle(ModuleLifecycle lifecycle) {
checkOpen();
Objects.requireNonNull(lifecycle, "lifecycle");
requireRegistering("Lifecycle " + lifecycle);
lifecycles.add(new LifecycleRegistration(lifecycle, registering));
}
@Override
public <S> void registerService(Class<S> service, S provider) {
checkOpen();
Objects.requireNonNull(service, "service");
Objects.requireNonNull(provider, "provider");
requireRegistering("Provider of " + service.getName());
var providers = FeatureCatalog.requireService(service).value();
if (!service.isInstance(provider)) {
throw new IllegalArgumentException("Provider " + provider + " of module " + registering + " does not implement "
+ service.getName());
}
var added = new ServiceRegistration(service, provider, registering);
if (providers == Providers.ONE) {
requireNoProvider(added);
}
services.add(added);
}
/** Catalogs a settings type named by a stage's when(...), whose owner {@link StageGraphBuilder}
* has checked. Several stages, and the owner's {@link #registerSettings}, may name one type. Call
* it after every module has registered, so the owner is known.
@@ -149,7 +180,7 @@ public final class ModuleRegistry implements FeatureRegistry {
public FeatureCatalog freeze() {
if (catalog == null) {
catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), validators);
catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), validators, lifecycles, services);
}
return catalog;
}
@@ -179,6 +210,23 @@ public final class ModuleRegistry implements FeatureRegistry {
+ info.idPrefix() + ", the id of its registering module " + registering);
}
private void requireRegistering(String registration) {
if (registering == null) {
throw new IllegalStateException(registration + " registered outside IrisModule.register");
}
}
/** A service a pack has one provider of: a second provider, from this module or another, fails. */
private void requireNoProvider(ServiceRegistration added) {
for (var existing : services) {
if (existing.service() == added.service()) {
throw new IllegalArgumentException("Service " + added.service().getName() + " is provided by module "
+ existing.module() + " already, and module " + added.module() + " provides it too; a pack has"
+ " one provider of it (Providers.ONE), so remove one of them");
}
}
}
/** One id, one type and one folder per kind: the host finds resources by type and reads each folder as one kind. */
private void requireUnclaimedKind(ResourceKindRegistration added) {
var kind = added.kind();
@@ -8,6 +8,7 @@ import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementRequest;
import com.volmit.random.WorldRandom;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import com.volmit.stage.BlockStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.BlockView;
@@ -111,6 +112,11 @@ final class PlacementInvocation implements BlockStageContext {
return inputs.worldSeed();
}
@Override
public PackWorld world() {
return inputs.world();
}
@Override
public PackResources resources() {
return inputs.resources();
@@ -0,0 +1,17 @@
package com.volmit.host;
import java.util.Objects;
/** One provider of a service and the module that registered it. */
public record ServiceRegistration(Class<?> service, Object provider, DiscoveredModule module) {
public ServiceRegistration {
Objects.requireNonNull(service, "service");
Objects.requireNonNull(provider, "provider");
Objects.requireNonNull(module, "module");
}
@Override
public String toString() {
return "provider of " + service.getName() + " from module " + module;
}
}
@@ -0,0 +1,119 @@
package com.volmit.host;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/** The reference store behind {@link com.volmit.world.PackWorld#state}: one instance per type, created once, closed
* with the world. A host's world implementation keeps one per world and passes {@code state} calls on, binding the
* world into the factory.
*
* <p>Reads of existing state take no lock. Creation runs under the store's lock, so each type is created once even
* when threads race; a factory may ask for other state on its own thread (the lock is re-entrant), and a type asked
* for again while it is being created fails instead of recursing. {@link #close()} closes every {@link AutoCloseable}
* state, newest first, and ends the store.
*/
public final class WorldStates implements AutoCloseable {
private final Map<Class<?>, Object> states = new ConcurrentHashMap<>();
private final List<Object> createdInOrder = new ArrayList<>();
private final Deque<Class<?>> creating = new ArrayDeque<>();
private final Object lock = new Object();
private boolean closed;
/** The {@code type} state, created by {@code create} the first time it is asked for. See {@link com.volmit.world.PackWorld#state}. */
public <T> T state(Class<T> type, Supplier<? extends T> create) {
Objects.requireNonNull(type, "type");
Objects.requireNonNull(create, "create");
Object existing = states.get(type);
if (existing != null) {
return type.cast(existing);
}
synchronized (lock) {
requireOpen(type);
existing = states.get(type);
if (existing != null) {
return type.cast(existing);
}
return create(type, create);
}
}
/** Closes every {@link AutoCloseable} state, the newest first, even when one fails, then throws the first failure
* with the others suppressed. Asking for state afterwards throws. Closing twice does nothing.
*/
@Override
public void close() {
List<Object> closing;
synchronized (lock) {
if (closed) {
return;
}
closed = true;
closing = new ArrayList<>(createdInOrder);
createdInOrder.clear();
states.clear();
}
RuntimeException failure = null;
for (int index = closing.size() - 1; index >= 0; index--) {
failure = closeState(closing.get(index), failure);
}
if (failure != null) {
throw failure;
}
}
private <T> T create(Class<T> type, Supplier<? extends T> create) {
if (creating.contains(type)) {
throw new IllegalStateException("World state " + type.getName() + " was asked for while it is being created: "
+ creationChain(type));
}
creating.push(type);
try {
T created = type.cast(Objects.requireNonNull(create.get(), () -> "The factory of world state " + type.getName()
+ " returned null"));
states.put(type, created);
createdInOrder.add(created);
return created;
} finally {
creating.pop();
}
}
private String creationChain(Class<?> repeated) {
var chain = new ArrayList<Class<?>>(creating);
Collections.reverse(chain);
chain.add(repeated);
return chain.stream().map(Class::getName).collect(Collectors.joining(" -> "));
}
private void requireOpen(Class<?> type) {
if (closed) {
throw new IllegalStateException("World state " + type.getName() + " was asked for after the world stopped");
}
}
private static RuntimeException closeState(Object state, RuntimeException failure) {
if (!(state instanceof AutoCloseable closeable)) {
return failure;
}
try {
closeable.close();
return failure;
} catch (Exception exception) {
var closeFailure = new IllegalStateException("World state " + state.getClass().getName() + " failed to close: "
+ exception, exception);
if (failure == null) {
return closeFailure;
}
failure.addSuppressed(closeFailure);
return failure;
}
}
}