Merge upstream port lane b

This commit is contained in:
piexel committed 2026-11-10 01:31:37 +01:00
commit c448da1155
82 files changed
+2029 -881

No files matched your search

@@ -158,6 +158,16 @@ public class ServerConfigurator {
}
}
public static void resetLoadedDatapackRuntime() {
synchronized (DATAPACK_INSTALL_LOCK) {
loadedDatapackRuntimeReady = false;
loadedDatapackCompilerInputFingerprint = "";
loadedDatapackRegistryRequirements = Map.of();
loadedDatapackRuntimeGeneration++;
loadedDatapackRestartRequired = false;
}
}
public static LoadedDatapackRuntimeInvalidation invalidateLoadedDatapackRuntime() {
synchronized (DATAPACK_INSTALL_LOCK) {
boolean wasReady = loadedDatapackRuntimeReady;
@@ -43,6 +43,7 @@ import art.arcane.iris.util.common.scheduling.J;
import java.awt.Color;
import java.awt.EventQueue;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
@@ -57,6 +58,7 @@ public class PregeneratorJob implements PregenListener, PregenRenderSource {
// 60s permit drain + 120s flush + plate reclaim), or a routine drain trips the deadline
// and aborts the engine shutdown sequence mid-teardown.
private static final long WORLD_SHUTDOWN_TIMEOUT_MILLIS = 200_000L;
private static final long PENDING_TASK_POLL_MILLIS = 1L;
private static final Color COLOR_EXISTS = parseColor("#4d7d5b");
private static final Color COLOR_BLACK = parseColor("#4d7d5b");
private static final Color COLOR_MANTLE = parseColor("#3c2773");
@@ -203,6 +205,29 @@ public class PregeneratorJob implements PregenListener, PregenRenderSource {
return shutdownAndWait(inst, timeoutMs);
}
public static boolean shutdownAndWait(long timeoutMs, Runnable processPendingTasks) {
Objects.requireNonNull(processPendingTasks, "processPendingTasks");
PregeneratorJob inst = instance.get();
if (inst == null) {
return false;
}
inst.pregenerator.close();
inst.worker.interrupt();
long started = System.nanoTime();
long timeoutNanos = TimeUnit.MILLISECONDS.toNanos(Math.max(1L, timeoutMs));
try {
while (inst.worker.isAlive() && System.nanoTime() - started < timeoutNanos) {
processPendingTasks.run();
inst.worker.join(PENDING_TASK_POLL_MILLIS);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted while stopping the Iris pregenerator.", e);
}
return finishShutdown(inst, timeoutMs);
}
private static boolean shutdownAndWait(PregeneratorJob inst, long timeoutMs) {
inst.pregenerator.close();
inst.worker.interrupt();
@@ -212,6 +237,10 @@ public class PregeneratorJob implements PregenListener, PregenRenderSource {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted while stopping the Iris pregenerator.", e);
}
return finishShutdown(inst, timeoutMs);
}
private static boolean finishShutdown(PregeneratorJob inst, long timeoutMs) {
if (inst.worker.isAlive()) {
throw new IllegalStateException("Timed out while stopping the Iris pregenerator after "
+ Math.max(1L, timeoutMs) + "ms.");
@@ -224,6 +253,14 @@ public class PregeneratorJob implements PregenListener, PregenRenderSource {
return instance.get();
}
public static void reportChunkGenerationFailure(String worldIdentity, int chunkX, int chunkZ, Throwable failure) {
PregeneratorJob inst = instance.get();
if (inst == null || !inst.targetsWorldIdentity(worldIdentity)) {
return;
}
inst.pregenerator.onChunkGenerationFailed(chunkX, chunkZ, failure);
}
public static boolean pauseResume() {
PregeneratorJob inst = instance.get();
if (inst == null) {
@@ -0,0 +1,24 @@
package art.arcane.iris.core.lifecycle;
import art.arcane.iris.core.ServerConfigurator;
import art.arcane.iris.core.localization.IrisLanguage;
import art.arcane.iris.core.runtime.WorldRuntimeControlService;
import art.arcane.iris.spi.IrisServices;
/**
* Drops every process-wide cache core keeps about the running server, so a disable leaves nothing an
* enable in the same JVM could answer from. The host bindings are not cleared here: core still logs
* through them while the adapter finishes its own teardown.
*/
public final class IrisRuntimeStatics {
private IrisRuntimeStatics() {
}
public static void reset() {
IrisServices.clear();
WorldLifecycleService.reset();
WorldRuntimeControlService.reset();
ServerConfigurator.resetLoadedDatapackRuntime();
IrisLanguage.shutdown();
}
}
@@ -51,6 +51,12 @@ public final class WorldLifecycleService {
this.worldBackendByKey = new ConcurrentHashMap<>();
}
public static void reset() {
synchronized (WorldLifecycleService.class) {
instance = null;
}
}
public static WorldLifecycleService get() {
WorldLifecycleService current = instance;
if (current != null) {
@@ -78,6 +78,11 @@ public final class IrisLanguage {
private IrisLanguage() {
}
public static synchronized void shutdown() {
dataFolder = null;
PLAIN_MEMO.set(null);
}
public static boolean initialize() {
if (!IrisPlatforms.isBound()) {
return false;
@@ -60,9 +60,6 @@ public final class CustomModule implements IrisModule {
private static void record(ChunkStageContext context) {
IrisChunk chunk = context.extension(IrisChunk.class).orElseThrow();
if (chunk.bypassesMantleStages()) {
return;
}
chunk.state(CustomBlockRecording.class, CustomBlockRecording::new).record(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore());
}
@@ -90,9 +90,4 @@ public final class IrisChunk {
public <T> T state(Class<T> type, Function<Engine, T> create) {
return engine.getGeneration().state(type, create);
}
/** Whether stages backed by the mantle skip this chunk, as maintenance regeneration on Folia requires. */
public boolean bypassesMantleStages() {
return engine.getGeneration().bypassesMantleStages();
}
}
@@ -37,8 +37,7 @@ import java.util.function.BooleanSupplier;
* The blocks Iris's mantle holds for chunks to take over, IrisApi's {@link com.volmit.mantle.Mantle#blocks()}: what object
* and structure placements wrote into the mantle's block slice, read as IrisApi block states over the chunks one
* invocation may touch. Stages only read them. A dimension that keeps no mantle ({@code useMantle: false}) holds none,
* even where an older mantle file still has some, as Iris never copied those into chunks; neither does a chunk that
* generates without its mantle (maintenance regeneration on Folia, {@link art.arcane.iris.engine.framework.EngineGeneration#bypassesMantleStages()}).
* even where an older mantle file still has some, as Iris never copied those into chunks.
*/
final class PlannedBlocks implements MantleLayer<BlockState> {
private static final int CHUNK_SHIFT = 4;
@@ -64,7 +63,7 @@ final class PlannedBlocks implements MantleLayer<BlockState> {
/** The planned blocks of {@code engine}'s mantle in {@code bounds}, converted with the invocation's {@code states}. */
static PlannedBlocks of(Engine engine, BlockBox bounds, IrisModuleMantle.Chunks chunks, PlatformBlockStates states) {
return new PlannedBlocks(bounds, chunks, states,
() -> engine.getDimension().isUseMantle() && !engine.getGeneration().bypassesMantleStages());
() -> engine.getDimension().isUseMantle());
}
/** No planned blocks in {@code bounds}, as in a dimension that keeps no mantle. */
@@ -223,6 +223,10 @@ public interface INMSBinding {
return false;
}
default boolean pollChunkTask(World world) {
return false;
}
default void flushChunkIO(World world) {
}
@@ -195,6 +195,10 @@ public class IrisPregenerator {
shutdown.set(true);
}
public void onChunkGenerationFailed(int chunkX, int chunkZ, Throwable failure) {
generator.onChunkGenerationFailed(chunkX, chunkZ, failure);
}
public void start() {
PrecisionStopwatch p = PrecisionStopwatch.start();
boolean completed = false;
@@ -203,7 +207,7 @@ public class IrisPregenerator {
// fires — leaving a phantom job that suppresses spawns and blocks future pregens.
try {
init();
task.iterateAllChunks((_a, _b) -> totalChunks.incrementAndGet());
totalChunks.set(task.chunkCount());
long startedAt = M.ms();
startTime.set(startedAt);
rateTracker.reset(startedAt, generated.get());
@@ -16,27 +16,28 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.util.project.hunk;
package art.arcane.iris.core.pregenerator;
public enum HunkFace {
TOP(art.arcane.volmlib.util.hunk.HunkFace.TOP),
BOTTOM(art.arcane.volmlib.util.hunk.HunkFace.BOTTOM),
EAST(art.arcane.volmlib.util.hunk.HunkFace.EAST),
WEST(art.arcane.volmlib.util.hunk.HunkFace.WEST),
NORTH(art.arcane.volmlib.util.hunk.HunkFace.NORTH),
SOUTH(art.arcane.volmlib.util.hunk.HunkFace.SOUTH);
import art.arcane.iris.spi.IrisLogging;
private final art.arcane.volmlib.util.hunk.HunkFace shared;
HunkFace(art.arcane.volmlib.util.hunk.HunkFace shared) {
this.shared = shared;
public final class PregenDiagnostics {
private PregenDiagnostics() {
}
public art.arcane.volmlib.util.hunk.HunkFace shared() {
return shared;
public static void probeFailed(String probe, Throwable failure) {
IrisLogging.debug("Pregen probe " + describeProbe(probe) + " failed: " + describeFailure(failure));
}
public static HunkFace fromShared(art.arcane.volmlib.util.hunk.HunkFace shared) {
return HunkFace.valueOf(shared.name());
public static String describeProbe(String probe) {
return probe == null || probe.isBlank() ? "unnamed" : probe;
}
public static String describeFailure(Throwable failure) {
if (failure == null) {
return "no throwable reported";
}
String message = failure.getMessage();
return message == null ? failure.getClass().getName() : failure.getClass().getName() + ": " + message;
}
}
@@ -170,7 +170,8 @@ public final class PregenMantleBackpressure {
try {
return cancelled.getAsBoolean();
} catch (Throwable ignored) {
} catch (Throwable e) {
PregenDiagnostics.probeFailed("pregen cancellation state", e);
return false;
}
}
@@ -178,7 +179,8 @@ public final class PregenMantleBackpressure {
private Mantle resolveMantle() {
try {
return mantleSupplier.get();
} catch (Throwable ignored) {
} catch (Throwable e) {
PregenDiagnostics.probeFailed("mantle handle for backpressure", e);
return null;
}
}
@@ -174,6 +174,11 @@ public class PregenTask {
return new int[]{bound.minX(), bound.minZ(), bound.maxX(), bound.maxZ()};
}
public long chunkCount() {
Bound bound = bounds.chunk();
return (long) bound.sizeX() * bound.sizeZ();
}
@FunctionalInterface
public interface InterleavedChunkConsumer {
boolean on(int regionX, int regionZ, int chunkX, int chunkZ, boolean firstChunkInRegion, boolean lastChunkInRegion);
@@ -83,6 +83,9 @@ public interface PregeneratorMethod {
default void onRegionBounds(int minRegionX, int minRegionZ, int maxRegionX, int maxRegionZ) {
}
default void onChunkGenerationFailed(int chunkX, int chunkZ, Throwable failure) {
}
default void onRegionSubmitted(int regionX, int regionZ) {
}
@@ -87,6 +87,11 @@ public class AsyncOrMedievalPregenMethod implements PregeneratorMethod {
method.onRegionBounds(minRegionX, minRegionZ, maxRegionX, maxRegionZ);
}
@Override
public void onChunkGenerationFailed(int chunkX, int chunkZ, Throwable failure) {
method.onChunkGenerationFailed(chunkX, chunkZ, failure);
}
@Override
public void onRegionSubmitted(int regionX, int regionZ) {
method.onRegionSubmitted(regionX, regionZ);
@@ -22,6 +22,7 @@ import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.core.IrisPaperLikeBackendMode;
import art.arcane.iris.core.IrisRuntimeSchedulerMode;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.pregenerator.PregenDiagnostics;
import art.arcane.iris.core.pregenerator.PregenListener;
import art.arcane.iris.core.pregenerator.PregenMantleBackpressure;
import art.arcane.iris.core.pregenerator.PregeneratorMethod;
@@ -44,6 +45,7 @@ import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
@@ -56,6 +58,7 @@ import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
public class AsyncPregenMethod implements PregeneratorMethod {
// THREAD_COUNT records the pool's original size while boosted; BOOST_HOLDERS counts live
@@ -65,8 +68,10 @@ public class AsyncPregenMethod implements PregeneratorMethod {
private static final AtomicInteger BOOST_HOLDERS = new AtomicInteger();
private static final int ADAPTIVE_SLOW_REQUEST_STEP = 3;
private static final int ADAPTIVE_RECOVERY_INTERVAL = 8;
private static final long CLOSE_DRAIN_WARNING_SECONDS = 60L;
private static final long CLOSE_DRAIN_WARNING_SECONDS = 20L;
private static final long CLOSE_DRAIN_TIMEOUT_SECONDS = 60L;
private static final long FLUSH_TIMEOUT_SECONDS = 120L;
private static final long FLUSH_STOP_POLL_MILLIS = 100L;
private final World world;
private final IrisRuntimeSchedulerMode runtimeSchedulerMode;
private final IrisPaperLikeBackendMode paperLikeBackendMode;
@@ -108,6 +113,8 @@ public class AsyncPregenMethod implements PregeneratorMethod {
private final AtomicLong failed = new AtomicLong();
private final AtomicLong lastProgressAt = new AtomicLong(M.ms());
private final AtomicBoolean closing = new AtomicBoolean();
private final PregenInFlightRequests inFlightRequests = new PregenInFlightRequests();
private final AtomicReference<GenerationFailure> generationFailure = new AtomicReference<>();
private final AtomicBoolean holdsWorkerBoost = new AtomicBoolean();
private final Object permitMonitor = new Object();
private volatile Engine metricsEngine;
@@ -208,7 +215,8 @@ public class AsyncPregenMethod implements PregeneratorMethod {
if (coreThreads instanceof Thread[] threadsArray) {
return threadsArray.length;
}
} catch (Throwable ignored) {
} catch (Throwable e) {
PregenDiagnostics.probeFailed("moonrise worker pool size", e);
}
return -1;
@@ -234,7 +242,8 @@ public class AsyncPregenMethod implements PregeneratorMethod {
int resolved = radius > 0 ? Math.max(1, (int) Math.ceil(radius / 32.0)) : 2;
evictionWindowRegions = resolved;
return resolved;
} catch (Throwable ignored) {
} catch (Throwable e) {
PregenDiagnostics.probeFailed("mantle radius for eviction window", e);
return 2;
}
}
@@ -344,6 +353,9 @@ public class AsyncPregenMethod implements PregeneratorMethod {
}
private void evictRegion(long c) {
if (IrisToolbelt.isServerStopping()) {
return;
}
if (!evictedRegions.add(c)) {
return;
}
@@ -400,7 +412,9 @@ public class AsyncPregenMethod implements PregeneratorMethod {
private void unloadChunkSafely(int cx, int cz) {
try {
world.removePluginChunkTicket(cx, cz, BukkitPlatform.plugin());
} catch (Throwable ignored) {
} catch (Throwable e) {
IrisLogging.reportError("Async pregen could not release the plugin chunk ticket at " + cx + "," + cz
+ " in world " + world.getName() + "; the chunk stays pinned in memory.", e);
}
try {
@@ -413,6 +427,9 @@ public class AsyncPregenMethod implements PregeneratorMethod {
}
private void flushAllRemainingChunks() {
if (IrisToolbelt.isServerStopping()) {
return;
}
List<Long> keys = new ArrayList<>(regionChunks.keySet());
if (foliaRuntime) {
@@ -423,6 +440,9 @@ public class AsyncPregenMethod implements PregeneratorMethod {
}
CompletableFuture<Void> flush = J.sfut(() -> {
if (IrisToolbelt.isServerStopping()) {
return;
}
for (Long rk : keys) {
if (!evictedRegions.add(rk)) {
continue;
@@ -446,7 +466,7 @@ public class AsyncPregenMethod implements PregeneratorMethod {
});
try {
flush.get(FLUSH_TIMEOUT_SECONDS, TimeUnit.SECONDS);
awaitFlushUnlessServerStops(flush);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
IrisLogging.warn("Interrupted while flushing pregen chunks for " + world.getName() + ".");
@@ -458,22 +478,49 @@ public class AsyncPregenMethod implements PregeneratorMethod {
}
}
private Chunk onChunkFutureFailure(int x, int z, Throwable throwable) {
try {
IrisLogging.warn("Failed async pregen chunk load at " + x + "," + z + ". " + metricsSnapshot());
private static void awaitFlushUnlessServerStops(CompletableFuture<Void> flush) throws Exception {
long started = System.nanoTime();
long timeoutNanos = TimeUnit.SECONDS.toNanos(FLUSH_TIMEOUT_SECONDS);
while (!IrisToolbelt.isServerStopping()) {
long remainingNanos = timeoutNanos - (System.nanoTime() - started);
if (remainingNanos <= 0L) {
throw new TimeoutException();
}
try {
flush.get(Math.min(remainingNanos, TimeUnit.MILLISECONDS.toNanos(FLUSH_STOP_POLL_MILLIS)), TimeUnit.NANOSECONDS);
return;
} catch (TimeoutException pollElapsed) {
}
}
}
IrisLogging.reportError(throwable);
private Chunk onChunkFutureFailure(int x, int z, Throwable throwable) {
IrisLogging.reportError("Failed async pregen chunk load at " + x + "," + z + ".", throwable);
try {
IrisLogging.warn("Async pregen state at the failed chunk " + x + "," + z + ". " + metricsSnapshot());
} catch (Throwable e) {
PregenDiagnostics.probeFailed("pregen metrics snapshot", e);
}
return null;
}
private void completeChunk(int x, int z, PregenListener listener, Chunk chunk, Throwable throwable) {
PregenListener owner = inFlightRequests.settle(PregenInFlightRequests.key(x, z));
if (owner == null) {
return;
}
settleChunk(x, z, owner, chunk, throwable, true);
}
private void settleChunk(int x, int z, PregenListener listener, Chunk chunk, Throwable throwable, boolean reportFailure) {
boolean success = false;
try {
if (throwable != null) {
onChunkFutureFailure(x, z, throwable);
if (reportFailure) {
onChunkFutureFailure(x, z, throwable);
}
onChunkFailedToLoad(x, z);
listener.onChunkFailed(x, z);
} else if (chunk == null) {
@@ -651,11 +698,53 @@ public class AsyncPregenMethod implements PregeneratorMethod {
+ " stalledForMs=" + stalledFor;
}
private void markSubmitted() {
private void markSubmitted(int x, int z, PregenListener listener) {
inFlightRequests.add(PregenInFlightRequests.key(x, z), listener);
submitted.incrementAndGet();
inFlight.incrementAndGet();
}
@Override
public void onChunkGenerationFailed(int chunkX, int chunkZ, Throwable failure) {
GenerationFailure recorded = new GenerationFailure(chunkX, chunkZ, failure);
if (generationFailure.compareAndSet(null, recorded)) {
IrisLogging.error("Async pregen aborting: Iris failed to generate chunk " + chunkX + "," + chunkZ
+ " and the server's chunk system will not complete the " + inFlightRequests.size()
+ " outstanding chunk request(s). " + metricsSnapshot());
}
failOutstandingRequests(failure);
}
private void failOutstandingRequests(Throwable failure) {
settleAll(inFlightRequests.drain(), failure);
}
private void throwIfGenerationFailed() {
GenerationFailure failure = generationFailure.get();
if (failure != null) {
throw new IllegalStateException("Pregen aborted: Iris failed to generate chunk " + failure.chunkX() + ","
+ failure.chunkZ() + " in world " + world.getName()
+ " and the server's chunk system stopped completing requests.", failure.cause());
}
}
private void abandonOutstandingRequests(Drain drain) {
Map<Long, PregenListener> abandoned = inFlightRequests.drain();
IrisLogging.error("Async pregen abandoned " + abandoned.size() + " chunk request(s) that did not complete within "
+ CLOSE_DRAIN_TIMEOUT_SECONDS + "s of closing (" + drain.outstanding()
+ " permit(s) still held). They are not cached and regenerate on the next run. " + metricsSnapshot());
settleAll(abandoned, new IllegalStateException(
"Async chunk request never completed before the pregen closed in world " + world.getName() + "."));
}
private void settleAll(Map<Long, PregenListener> requests, Throwable failure) {
for (Map.Entry<Long, PregenListener> entry : requests.entrySet()) {
long key = entry.getKey();
settleChunk(PregenInFlightRequests.chunkX(key), PregenInFlightRequests.chunkZ(key), entry.getValue(),
null, failure, false);
}
}
private void markFinished(boolean success) {
if (success) {
completed.incrementAndGet();
@@ -697,7 +786,9 @@ public class AsyncPregenMethod implements PregeneratorMethod {
if (engine != null) {
try {
engine.getMantle().forceCleanupChunk(x, z);
} catch (Throwable ignored) {
} catch (Throwable e) {
IrisLogging.reportError("Async pregen mantle cleanup failed at chunk " + x + "," + z
+ " in world " + world.getName() + "; tectonic plates for that chunk stay resident.", e);
}
}
}
@@ -718,7 +809,8 @@ public class AsyncPregenMethod implements PregeneratorMethod {
metricsEngine = resolvedEngine;
}
return resolvedEngine;
} catch (Throwable ignored) {
} catch (Throwable e) {
PregenDiagnostics.probeFailed("engine access for world " + world.getName(), e);
return null;
}
}
@@ -773,13 +865,18 @@ public class AsyncPregenMethod implements PregeneratorMethod {
// A stop request interrupts the pregen worker; shield the drain and flush so chunks still hit disk.
boolean interrupted = Thread.interrupted();
try {
interrupted |= awaitDrain(
Drain drain = awaitDrain(
semaphore,
threads,
CLOSE_DRAIN_WARNING_SECONDS,
CLOSE_DRAIN_TIMEOUT_SECONDS,
TimeUnit.SECONDS,
() -> IrisLogging.warn("Async pregen is still draining outstanding chunks. " + metricsSnapshot())
);
interrupted |= drain.interrupted();
if (!drain.drained()) {
abandonOutstandingRequests(drain);
}
flushAllRemainingChunks();
executor.shutdown();
@@ -793,18 +890,25 @@ public class AsyncPregenMethod implements PregeneratorMethod {
}
}
static boolean awaitDrain(
static Drain awaitDrain(
Semaphore semaphore,
int permits,
long warningInterval,
long deadline,
TimeUnit timeUnit,
Runnable onWait
) {
long warningNanos = timeUnit.toNanos(warningInterval);
long deadlineAt = System.nanoTime() + timeUnit.toNanos(deadline);
boolean interrupted = false;
while (true) {
long remaining = deadlineAt - System.nanoTime();
if (remaining <= 0L) {
return new Drain(false, interrupted, permits - semaphore.availablePermits());
}
try {
if (semaphore.tryAcquire(permits, warningInterval, timeUnit)) {
return interrupted;
if (semaphore.tryAcquire(permits, Math.min(warningNanos, remaining), TimeUnit.NANOSECONDS)) {
return new Drain(true, interrupted, 0);
}
onWait.run();
} catch (InterruptedException e) {
@@ -814,7 +918,7 @@ public class AsyncPregenMethod implements PregeneratorMethod {
}
private boolean isCancelled() {
return closing.get() || Thread.currentThread().isInterrupted();
return closing.get() || generationFailure.get() != null || Thread.currentThread().isInterrupted();
}
@Override
@@ -833,6 +937,7 @@ public class AsyncPregenMethod implements PregeneratorMethod {
@Override
public void generateChunk(int x, int z, PregenListener listener) {
throwIfGenerationFailed();
listener.onChunkGenerating(x, z);
backpressure.enforceMantleBudget();
backpressure.awaitHeapHeadroom();
@@ -871,9 +976,14 @@ public class AsyncPregenMethod implements PregeneratorMethod {
return;
}
throwIfGenerationFailed();
regionPending.computeIfAbsent(rkey(x >> 5, z >> 5), k -> new AtomicInteger(1)).incrementAndGet();
markSubmitted();
markSubmitted(x, z, listener);
executor.generate(x, z, listener);
GenerationFailure failure = generationFailure.get();
if (failure != null) {
failOutstandingRequests(failure.cause());
}
}
private CompletableFuture<Chunk> requestChunkAsync(int x, int z) {
@@ -1053,7 +1163,9 @@ public class AsyncPregenMethod implements PregeneratorMethod {
requestMonitoredChunkAsync(x, z)
.whenComplete((chunk, throwable) -> completeChunk(x, z, listener, chunk, throwable));
return;
} catch (Throwable ignored) {
} catch (Throwable e) {
PregenDiagnostics.probeFailed("folia direct chunk request at " + x + "," + z
+ ", falling back to a region task", e);
}
Runnable regionTask = () -> {
@@ -1111,6 +1223,12 @@ public class AsyncPregenMethod implements PregeneratorMethod {
}
}
record Drain(boolean drained, boolean interrupted, int outstanding) {
}
private record GenerationFailure(int chunkX, int chunkZ, Throwable cause) {
}
private record ChunkAsyncMethodSelection(Method urgentMethod, Method standardMethod, String mode) {
}
}
@@ -175,6 +175,11 @@ public class CachedPregenMethod implements PregeneratorMethod {
method.onRegionBounds(minRegionX, minRegionZ, maxRegionX, maxRegionZ);
}
@Override
public void onChunkGenerationFailed(int chunkX, int chunkZ, Throwable failure) {
method.onChunkGenerationFailed(chunkX, chunkZ, failure);
}
@Override
public void onRegionSubmitted(int regionX, int regionZ) {
method.onRegionSubmitted(regionX, regionZ);
@@ -80,6 +80,11 @@ public class HybridPregenMethod implements PregeneratorMethod {
inWorld.onRegionBounds(minRegionX, minRegionZ, maxRegionX, maxRegionZ);
}
@Override
public void onChunkGenerationFailed(int chunkX, int chunkZ, Throwable failure) {
inWorld.onChunkGenerationFailed(chunkX, chunkZ, failure);
}
@Override
public void onRegionSubmitted(int regionX, int regionZ) {
inWorld.onRegionSubmitted(regionX, regionZ);
@@ -19,6 +19,7 @@
package art.arcane.iris.core.pregenerator.methods;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.pregenerator.PregenDiagnostics;
import art.arcane.iris.core.pregenerator.PregenListener;
import art.arcane.iris.core.pregenerator.PregeneratorMethod;
import art.arcane.iris.core.tools.IrisToolbelt;
@@ -101,7 +102,8 @@ public class MedievalPregenMethod implements PregeneratorMethod {
if (cached != null) {
cachedEngine = cached;
}
} catch (Throwable ignored) {
} catch (Throwable e) {
PregenDiagnostics.probeFailed("engine access for world " + world.getName(), e);
}
return cached;
}
@@ -0,0 +1,46 @@
package art.arcane.iris.core.pregenerator.methods;
import art.arcane.iris.core.pregenerator.PregenListener;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
public final class PregenInFlightRequests {
private final ConcurrentHashMap<Long, PregenListener> requests = new ConcurrentHashMap<>();
public static long key(int chunkX, int chunkZ) {
return ((long) chunkX << 32) | (chunkZ & 0xFFFFFFFFL);
}
public static int chunkX(long key) {
return (int) (key >> 32);
}
public static int chunkZ(long key) {
return (int) key;
}
public boolean add(long key, PregenListener listener) {
return requests.putIfAbsent(key, Objects.requireNonNull(listener, "listener")) == null;
}
public PregenListener settle(long key) {
return requests.remove(key);
}
public Map<Long, PregenListener> drain() {
HashMap<Long, PregenListener> drained = new HashMap<>();
for (Map.Entry<Long, PregenListener> entry : requests.entrySet()) {
if (requests.remove(entry.getKey(), entry.getValue())) {
drained.put(entry.getKey(), entry.getValue());
}
}
return drained;
}
public int size() {
return requests.size();
}
}
@@ -79,6 +79,12 @@ public final class WorldRuntimeControlService {
+ ", " + backend.describeCapabilities();
}
public static void reset() {
synchronized (WorldRuntimeControlService.class) {
instance = null;
}
}
public static WorldRuntimeControlService get() {
WorldRuntimeControlService current = instance;
if (current != null) {
@@ -81,6 +81,8 @@ import java.util.function.Supplier;
@Data
public class IrisEngine implements Engine {
static final long SESSION_DRAIN_TIMEOUT_MILLIS = 15000L;
private static final long MAINTENANCE_REFUSAL_WARNING_MILLIS = 5000L;
private static final AtomicLong lastMaintenanceRefusalWarning = new AtomicLong();
private final AtomicInteger bud;
private final AtomicInteger buds;
@@ -632,6 +634,9 @@ public class IrisEngine implements Engine {
@Override
public void generate(int x, int z, Hunk<PlatformBlockState> vblocks, Hunk<PlatformBiome> vbiomes, boolean multicore) throws WrongEngineBroException {
awaitGenerationCacheWarm();
if (platformHooks.shouldRefuseGeneration(this)) {
refuseMaintenanceGeneration(x >> 4, z >> 4);
}
try (GenerationSessionLease lease = acquireGenerationLease("chunk_generate");
IrisContext.Scope generationScope = IrisContext.open(this, lease.sessionId(), null)) {
getEngineData().getStatistics().generatedChunk();
@@ -649,10 +654,7 @@ public class IrisEngine implements Engine {
getGeneration().generate(x, z, blocks, vbiomes, multicore, lease.sessionId());
}
boolean skipRealFlag = platformHooks.shouldBypassMantleStages(this);
if (!skipRealFlag) {
getMantle().getMantle().flag(x >> 4, z >> 4, MantleFlag.REAL, true);
}
getMantle().getMantle().flag(x >> 4, z >> 4, MantleFlag.REAL, true);
getMetrics().getTotal().put(p.getMilliseconds());
generated.incrementAndGet();
@@ -671,6 +673,17 @@ public class IrisEngine implements Engine {
}
}
private void refuseMaintenanceGeneration(int chunkX, int chunkZ) throws GenerationSessionException {
long now = System.currentTimeMillis();
long last = lastMaintenanceRefusalWarning.get();
if (now - last >= MAINTENANCE_REFUSAL_WARNING_MILLIS && lastMaintenanceRefusalWarning.compareAndSet(last, now)) {
IrisLogging.warn("Iris refused chunk " + chunkX + "," + chunkZ + " in " + getWorld().name()
+ ": world maintenance forbids mantle generation, the chunk stays ungenerated");
}
throw new GenerationSessionException("Iris refused chunk " + chunkX + "," + chunkZ + " in "
+ getWorld().name() + " during world maintenance.", true);
}
@Override
public GenerationSessionManager getGenerationSessions() {
return generationSessions;
@@ -21,7 +21,6 @@ package art.arcane.iris.engine.framework;
import art.arcane.iris.core.modules.IrisPackWorld;
import art.arcane.iris.core.modules.ModuleChunkGeneration;
import art.arcane.iris.core.modules.ModuleWorlds;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.PlatformBiome;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.project.context.ChunkContext;
@@ -29,7 +28,6 @@ import art.arcane.iris.util.project.context.IrisContext;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.volmlib.util.documentation.BlockCoordinates;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
/**
@@ -40,8 +38,6 @@ import java.util.function.Function;
*/
public final class EngineGeneration {
private static final int CHUNK_SHIFT = 4;
private static final long MAINTENANCE_LOG_INTERVAL_MILLIS = 5000L;
private static final AtomicLong lastMaintenanceBypassLog = new AtomicLong(0L);
private final Engine engine;
private final ModuleWorlds modules;
@@ -91,18 +87,6 @@ public final class EngineGeneration {
}
}
/**
* Whether stages backed by the mantle skip this chunk: on Folia, maintenance regeneration runs without the
* mantle to stay region-safe.
*/
public boolean bypassesMantleStages() {
boolean bypass = engine.getPlatformHooks().shouldBypassMantleStages(engine);
if (bypass) {
logMaintenanceBypass();
}
return bypass;
}
/** Writes what modules saved with the world, as the engine saves its data; see {@link com.volmit.world.RunningWorld#saved}. */
public void saveModuleData() {
modules.saveCurrentWorldState();
@@ -118,17 +102,6 @@ public final class EngineGeneration {
}
private void generateMantle(int x, int z, boolean multicore, ChunkContext context) {
if (bypassesMantleStages()) {
return;
}
engine.getMantle().generateMatter(x >> CHUNK_SHIFT, z >> CHUNK_SHIFT, multicore || engine.isStudio(), context);
}
private static void logMaintenanceBypass() {
long now = System.currentTimeMillis();
long last = lastMaintenanceBypassLog.get();
if (now - last >= MAINTENANCE_LOG_INTERVAL_MILLIS && lastMaintenanceBypassLog.compareAndSet(last, now)) {
IrisLogging.info("Maintenance regen bypass: skipping mantle-backed stages for Folia safety.");
}
}
}
@@ -67,7 +67,11 @@ public interface EnginePlatformHooks {
return false;
}
default boolean shouldBypassMantleStages(Engine engine) {
/**
* True while world maintenance forbids the mantle-backed stages. Generating without them would persist a
* chunk with no objects, caves or deposits, so the engine refuses the chunk instead.
*/
default boolean shouldRefuseGeneration(Engine engine) {
return false;
}
}
@@ -1,6 +1,8 @@
package art.arcane.iris.engine.framework;
public class GenerationSessionException extends WrongEngineBroException {
import com.volmit.generation.EngineFailure;
public class GenerationSessionException extends WrongEngineBroException implements EngineFailure {
private final boolean expectedTeardown;
public GenerationSessionException(String message) {
@@ -24,6 +24,8 @@ import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.project.matter.TileWrapper;
import com.google.common.collect.ImmutableList;
import com.volmit.generation.GenerationFailures;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.core.tools.WorldMaintenance;
@@ -130,7 +132,7 @@ public class MantleWriter implements IObjectPlacer, AutoCloseable {
return Math.max(1, availableProcessors / 2);
}
private static Set<IrisPosition> getBallooned(Set<IrisPosition> vset, double radius) {
static Set<IrisPosition> getBallooned(Set<IrisPosition> vset, double radius) {
Set<IrisPosition> returnset = new HashSet<>();
int ceilrad = (int) Math.ceil(radius);
double r2 = Math.pow(radius, 2);
@@ -153,30 +155,83 @@ public class MantleWriter implements IObjectPlacer, AutoCloseable {
return returnset;
}
private static Set<IrisPosition> getHollowed(Set<IrisPosition> vset) {
static Set<IrisPosition> getHollowed(Set<IrisPosition> vset) {
PositionLookup lookup = PositionLookup.of(vset);
Set<IrisPosition> returnset = new KSet<>();
for (IrisPosition v : vset) {
double x = v.getX();
double y = v.getY();
double z = v.getZ();
if (!(vset.contains(new IrisPosition(x + 1, y, z))
&& vset.contains(new IrisPosition(x - 1, y, z))
&& vset.contains(new IrisPosition(x, y + 1, z))
&& vset.contains(new IrisPosition(x, y - 1, z))
&& vset.contains(new IrisPosition(x, y, z + 1))
&& vset.contains(new IrisPosition(x, y, z - 1)))) {
int x = v.getX();
int y = v.getY();
int z = v.getZ();
if (!(lookup.contains(x + 1, y, z)
&& lookup.contains(x - 1, y, z)
&& lookup.contains(x, y + 1, z)
&& lookup.contains(x, y - 1, z)
&& lookup.contains(x, y, z + 1)
&& lookup.contains(x, y, z - 1))) {
returnset.add(v);
}
}
return returnset;
}
private static double hypot(double... pars) {
double sum = 0;
for (double d : pars) {
sum += Math.pow(d, 2);
private static double hypot(double x, double y, double z) {
return Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2);
}
record PositionLookup(LongOpenHashSet keys, Set<IrisPosition> positions, int originX, int originY, int originZ) {
private static final int AXIS_BITS = 21;
private static final long AXIS_LIMIT = 1L << AXIS_BITS;
static PositionLookup of(Set<IrisPosition> positions) {
if (positions.isEmpty()) {
return new PositionLookup(new LongOpenHashSet(), positions, 0, 0, 0);
}
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int minZ = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
int maxZ = Integer.MIN_VALUE;
for (IrisPosition position : positions) {
minX = Math.min(minX, position.getX());
minY = Math.min(minY, position.getY());
minZ = Math.min(minZ, position.getZ());
maxX = Math.max(maxX, position.getX());
maxY = Math.max(maxY, position.getY());
maxZ = Math.max(maxZ, position.getZ());
}
if ((long) maxX - minX >= AXIS_LIMIT - 2L
|| (long) maxY - minY >= AXIS_LIMIT - 2L
|| (long) maxZ - minZ >= AXIS_LIMIT - 2L) {
return new PositionLookup(null, positions, 0, 0, 0);
}
LongOpenHashSet keys = new LongOpenHashSet(positions.size());
for (IrisPosition position : positions) {
keys.add(key(position.getX() - minX, position.getY() - minY, position.getZ() - minZ));
}
return new PositionLookup(keys, positions, minX, minY, minZ);
}
boolean contains(int x, int y, int z) {
if (keys == null) {
return positions.contains(new IrisPosition(x, y, z));
}
long dx = (long) x - originX;
long dy = (long) y - originY;
long dz = (long) z - originZ;
if ((dx | dy | dz) < 0L || dx >= AXIS_LIMIT || dy >= AXIS_LIMIT || dz >= AXIS_LIMIT) {
return false;
}
return keys.contains(key(dx, dy, dz));
}
private static long key(long x, long y, long z) {
return (x << (AXIS_BITS * 2)) | (y << AXIS_BITS) | z;
}
return sum;
}
private static double lengthSq(double x, double y, double z) {
@@ -795,10 +850,11 @@ public class MantleWriter implements IObjectPlacer, AutoCloseable {
setConsumer(vset, data);
}
private static Set<IrisPosition> getMasked(Set<IrisPosition> vectors, Set<IrisPosition> masks, double radius) {
static Set<IrisPosition> getMasked(Set<IrisPosition> vectors, Set<IrisPosition> masks, double radius) {
Set<IrisPosition> vset = new KSet<>();
int ceil = (int) Math.ceil(radius);
double r2 = Math.pow(radius, 2);
PositionLookup maskLookup = PositionLookup.of(masks);
for (IrisPosition v : vectors) {
int tipX = v.getX();
@@ -808,7 +864,7 @@ public class MantleWriter implements IObjectPlacer, AutoCloseable {
for (int x = -ceil; x <= ceil; x++) {
for (int y = -ceil; y <= ceil; y++) {
for (int z = -ceil; z <= ceil; z++) {
if (hypot(x, y, z) > r2 || !masks.contains(new IrisPosition(x, y, z)))
if (hypot(x, y, z) > r2 || !maskLookup.contains(x, y, z))
continue;
vset.add(new IrisPosition(tipX + x, tipY + y, tipZ + z));
}
@@ -963,6 +1019,7 @@ public class MantleWriter implements IObjectPlacer, AutoCloseable {
try {
setData(pos.getX(), pos.getY(), pos.getZ(), data);
} catch (Throwable e) {
GenerationFailures.rethrowEngineFailure(e);
// Reached per position while an object writes past the edge of the writer window, which is
// how a large object is clipped. Nothing here is actionable from outside the engine.
IrisLogging.debug("No set? " + data.toString() + " for " + pos.toString());
@@ -836,6 +836,15 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
@Override
public void generateNoise(@NotNull WorldInfo world, @NotNull Random random, int x, int z, @NotNull ChunkGenerator.ChunkData d) {
try {
generateNoiseChunk(world, random, x, z, d);
} catch (Throwable e) {
PregeneratorJob.reportChunkGenerationFailure(this.world.identity(), x, z, e);
throw e;
}
}
private void generateNoiseChunk(WorldInfo world, Random random, int x, int z, ChunkGenerator.ChunkData d) {
if (closing) {
throw new IllegalStateException("Iris chunk generation was rejected while the generator is closing.");
}
@@ -103,6 +103,14 @@ public final class BukkitPlatform implements IrisPlatform {
PLUGIN = plugin;
}
public static void releaseHost() {
PLUGIN = null;
HUD_BAR = null;
HUD_LANES = null;
CONSOLE = null;
BRIDGE = null;
}
public static Plugin plugin() {
Plugin plugin = PLUGIN;
if (plugin == null) {
@@ -1,51 +0,0 @@
package art.arcane.iris.util.common.board;
import art.arcane.volmlib.util.board.BoardProvider;
public class BoardSettings {
private final BoardProvider boardProvider;
private final ScoreDirection scoreDirection;
private BoardSettings(BoardProvider boardProvider, ScoreDirection scoreDirection) {
this.boardProvider = boardProvider;
this.scoreDirection = scoreDirection;
}
public BoardProvider getBoardProvider() {
return boardProvider;
}
public ScoreDirection getScoreDirection() {
return scoreDirection;
}
public art.arcane.volmlib.util.board.BoardSettings toShared() {
return art.arcane.volmlib.util.board.BoardSettings.builder()
.boardProvider(boardProvider)
.scoreDirection(scoreDirection.toShared())
.build();
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private BoardProvider boardProvider;
private ScoreDirection scoreDirection;
public Builder boardProvider(BoardProvider boardProvider) {
this.boardProvider = boardProvider;
return this;
}
public Builder scoreDirection(ScoreDirection scoreDirection) {
this.scoreDirection = scoreDirection;
return this;
}
public BoardSettings build() {
return new BoardSettings(boardProvider, scoreDirection);
}
}
}
@@ -1,16 +0,0 @@
package art.arcane.iris.util.common.board;
public enum ScoreDirection {
UP,
DOWN;
public art.arcane.volmlib.util.board.ScoreDirection toShared() {
return this == UP
? art.arcane.volmlib.util.board.ScoreDirection.UP
: art.arcane.volmlib.util.board.ScoreDirection.DOWN;
}
public static ScoreDirection fromShared(art.arcane.volmlib.util.board.ScoreDirection direction) {
return direction == art.arcane.volmlib.util.board.ScoreDirection.UP ? UP : DOWN;
}
}
@@ -1,40 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.util.common.inventorygui;
import art.arcane.volmlib.util.inventorygui.WindowDecorator;
import art.arcane.volmlib.util.inventorygui.Element;
import art.arcane.volmlib.util.data.MaterialBlock;
import org.bukkit.Material;
@SuppressWarnings("ClassCanBeRecord")
public class UIStaticDecorator implements WindowDecorator {
private final Element element;
public UIStaticDecorator(Element element) {
this.element = element == null ? new art.arcane.volmlib.util.inventorygui.UIElement("bg").setMaterial(new MaterialBlock(Material.AIR)) : element;
}
@Override
public Element onDecorateBackground(art.arcane.volmlib.util.inventorygui.Window window, int position, int row) {
return element;
}
}
@@ -1,84 +0,0 @@
package art.arcane.iris.util.common.inventorygui;
import art.arcane.volmlib.util.inventorygui.WindowDecorator;
import art.arcane.volmlib.util.inventorygui.Element;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public interface Window {
WindowDecorator getDecorator();
Window setDecorator(WindowDecorator decorator);
art.arcane.volmlib.util.inventorygui.WindowResolution getResolution();
Window setResolution(art.arcane.volmlib.util.inventorygui.WindowResolution resolution);
default Window setResolution(WindowResolution resolution) {
return setResolution(resolution.toShared());
}
default WindowResolution getLocalResolution() {
return WindowResolution.fromShared(getResolution());
}
Window clearElements();
Window close();
Window open();
Window callClosed();
Window updateInventory();
ItemStack computeItemStack(int viewportSlot);
int getLayoutRow(int viewportSlottedPosition);
int getLayoutPosition(int viewportSlottedPosition);
int getRealLayoutPosition(int viewportSlottedPosition);
int getRealPosition(int position, int row);
int getRow(int realPosition);
int getPosition(int realPosition);
boolean isVisible();
Window setVisible(boolean visible);
int getViewportPosition();
Window setViewportPosition(int position);
int getViewportSlots();
int getMaxViewportPosition();
Window scroll(int direction);
int getViewportHeight();
Window setViewportHeight(int height);
String getTitle();
Window setTitle(String title);
boolean hasElement(int position, int row);
Window setElement(int position, int row, Element e);
Element getElement(int position, int row);
Player getViewer();
Window reopen();
Window onClosed(art.arcane.volmlib.util.scheduling.Callback<art.arcane.volmlib.util.inventorygui.Window> window);
}
@@ -1,43 +0,0 @@
package art.arcane.iris.util.common.inventorygui;
import org.bukkit.event.inventory.InventoryType;
public enum WindowResolution {
W9_H6(9, 6, InventoryType.CHEST),
W5_H1(5, 1, InventoryType.HOPPER),
W3_H3(3, 3, InventoryType.DROPPER);
private final int width;
private final int maxHeight;
private final InventoryType type;
WindowResolution(int w, int h, InventoryType type) {
this.width = w;
this.maxHeight = h;
this.type = type;
}
public int getMaxWidthOffset() {
return (getWidth() - 1) / 2;
}
public int getWidth() {
return width;
}
public int getMaxHeight() {
return maxHeight;
}
public InventoryType getType() {
return type;
}
public art.arcane.volmlib.util.inventorygui.WindowResolution toShared() {
return art.arcane.volmlib.util.inventorygui.WindowResolution.valueOf(name());
}
public static WindowResolution fromShared(art.arcane.volmlib.util.inventorygui.WindowResolution resolution) {
return valueOf(resolution.name());
}
}
@@ -1,78 +0,0 @@
package art.arcane.iris.util.common.math;
import org.bukkit.util.Vector;
public class VectorMath extends art.arcane.volmlib.util.math.VectorMath {
public static Vector rotate(Direction current, Direction to, Vector v) {
if (current.equals(to)) {
return v;
} else if (current.equals(to.reverse())) {
if (current.isVertical()) {
return new Vector(v.getX(), -v.getY(), v.getZ());
} else {
return new Vector(-v.getX(), v.getY(), -v.getZ());
}
} else {
Vector c = current.toVector().clone().add(to.toVector());
if (c.getX() == 0) {
if (c.getY() != c.getZ()) {
return rotate90CX(v);
}
return rotate90CCX(v);
} else if (c.getY() == 0) {
if (c.getX() != c.getZ()) {
return rotate90CY(v);
}
return rotate90CCY(v);
} else if (c.getZ() == 0) {
if (c.getX() != c.getY()) {
return rotate90CZ(v);
}
return rotate90CCZ(v);
}
}
return v;
}
public static Vector rotate(Direction current, Direction to, Vector v, int w, int h, int d) {
if (current.equals(to)) {
return v;
} else if (current.equals(to.reverse())) {
if (current.isVertical()) {
return new Vector(v.getX(), -v.getY() + h, v.getZ());
} else {
return new Vector(-v.getX() + w, v.getY(), -v.getZ() + d);
}
} else {
Vector c = current.toVector().clone().add(to.toVector());
if (c.getX() == 0) {
if (c.getY() != c.getZ()) {
return rotate90CX(v, d);
}
return rotate90CCX(v, h);
} else if (c.getY() == 0) {
if (c.getX() != c.getZ()) {
return rotate90CY(v, d);
}
return rotate90CCY(v, w);
} else if (c.getZ() == 0) {
if (c.getX() != c.getY()) {
return rotate90CZ(v, w);
}
return rotate90CCZ(v, h);
}
}
return v;
}
}
@@ -772,7 +772,7 @@ public class J {
}
private static boolean isPluginEnabled() {
return usesBukkitScheduler() && BukkitPlatform.hasPlugin() && Bukkit.getPluginManager().isPluginEnabled(BukkitPlatform.plugin());
return usesBukkitScheduler() && BukkitPlatform.hasPlugin() && BukkitPlatform.plugin().isEnabled();
}
private static boolean canSchedule() {
@@ -36,6 +36,7 @@ import art.arcane.volmlib.util.hunk.HunkCoreSupport;
import art.arcane.volmlib.util.hunk.HunkInterpolationSupport;
import art.arcane.volmlib.util.hunk.HunkMutationSupport;
import art.arcane.volmlib.util.hunk.HunkSectionSupport;
import art.arcane.volmlib.util.hunk.HunkFace;
import art.arcane.volmlib.util.hunk.HunkLike;
import art.arcane.iris.util.project.hunk.storage.ArrayHunk;
import art.arcane.iris.util.project.hunk.storage.AtomicDoubleHunk;
@@ -18,41 +18,10 @@
package art.arcane.iris.util.project.hunk.storage;
import art.arcane.volmlib.util.cache.CacheKey;
import art.arcane.iris.util.project.hunk.Hunk;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Arrays;
@SuppressWarnings("Lombok")
@Data
@EqualsAndHashCode(callSuper = false)
public class ArrayHunk<T> extends StorageHunk<T> implements Hunk<T> {
private final T[] data;
@SuppressWarnings("unchecked")
public class ArrayHunk<T> extends art.arcane.volmlib.util.hunk.storage.ArrayHunk<T> implements Hunk<T> {
public ArrayHunk(int w, int h, int d) {
super(w, h, d);
data = (T[]) new Object[w * h * d];
}
@Override
public void setRaw(int x, int y, int z, T t) {
data[index(x, y, z)] = t;
}
@Override
public T getRaw(int x, int y, int z) {
return data[index(x, y, z)];
}
private int index(int x, int y, int z) {
return CacheKey.to1D(x, y, z, getWidth(), getHeight());
}
@Override
public void fill(T t) {
Arrays.fill(data, t);
}
}
@@ -18,38 +18,10 @@
package art.arcane.iris.util.project.hunk.storage;
import com.google.common.util.concurrent.AtomicDoubleArray;
import art.arcane.iris.util.project.hunk.Hunk;
import lombok.Data;
import lombok.EqualsAndHashCode;
@SuppressWarnings({"Lombok"})
@Data
@EqualsAndHashCode(callSuper = false)
public class AtomicDoubleHunk extends StorageHunk<Double> implements Hunk<Double> {
private final AtomicDoubleArray data;
public class AtomicDoubleHunk extends art.arcane.volmlib.util.hunk.storage.AtomicDoubleHunk implements Hunk<Double> {
public AtomicDoubleHunk(int w, int h, int d) {
super(w, h, d);
data = new AtomicDoubleArray(w * h * d);
}
@Override
public boolean isAtomic() {
return true;
}
@Override
public void setRaw(int x, int y, int z, Double t) {
data.set(index(x, y, z), t);
}
@Override
public Double getRaw(int x, int y, int z) {
return data.get(index(x, y, z));
}
private int index(int x, int y, int z) {
return (z * getWidth() * getHeight()) + (y * getWidth()) + x;
}
}
@@ -19,44 +19,9 @@
package art.arcane.iris.util.project.hunk.storage;
import art.arcane.iris.util.project.hunk.Hunk;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.concurrent.atomic.AtomicReferenceArray;
@SuppressWarnings({"Lombok"})
@Data
@EqualsAndHashCode(callSuper = false)
public class AtomicHunk<T> extends StorageHunk<T> implements Hunk<T> {
private final AtomicReferenceArray<T> data;
// index() runs per block access on the hottest paths; two final-field multiplies beat
// re-deriving the strides through the accessors every call.
private final int xStride;
private final int zStride;
public class AtomicHunk<T> extends art.arcane.volmlib.util.hunk.storage.AtomicHunk<T> implements Hunk<T> {
public AtomicHunk(int w, int h, int d) {
super(w, h, d);
data = new AtomicReferenceArray<>(w * h * d);
xStride = w;
zStride = w * h;
}
@Override
public boolean isAtomic() {
return true;
}
@Override
public void setRaw(int x, int y, int z, T t) {
data.set(index(x, y, z), t);
}
@Override
public T getRaw(int x, int y, int z) {
return data.get(index(x, y, z));
}
private int index(int x, int y, int z) {
return (z * zStride) + (y * xStride) + x;
}
}
@@ -19,38 +19,9 @@
package art.arcane.iris.util.project.hunk.storage;
import art.arcane.iris.util.project.hunk.Hunk;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.concurrent.atomic.AtomicIntegerArray;
@SuppressWarnings({"Lombok"})
@Data
@EqualsAndHashCode(callSuper = false)
public class AtomicIntegerHunk extends StorageHunk<Integer> implements Hunk<Integer> {
private final AtomicIntegerArray data;
public class AtomicIntegerHunk extends art.arcane.volmlib.util.hunk.storage.AtomicIntegerHunk implements Hunk<Integer> {
public AtomicIntegerHunk(int w, int h, int d) {
super(w, h, d);
data = new AtomicIntegerArray(w * h * d);
}
@Override
public boolean isAtomic() {
return true;
}
@Override
public void setRaw(int x, int y, int z, Integer t) {
data.set(index(x, y, z), t);
}
@Override
public Integer getRaw(int x, int y, int z) {
return data.get(index(x, y, z));
}
private int index(int x, int y, int z) {
return (z * getWidth() * getHeight()) + (y * getWidth()) + x;
}
}
@@ -19,38 +19,9 @@
package art.arcane.iris.util.project.hunk.storage;
import art.arcane.iris.util.project.hunk.Hunk;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.concurrent.atomic.AtomicLongArray;
@SuppressWarnings({"Lombok"})
@Data
@EqualsAndHashCode(callSuper = false)
public class AtomicLongHunk extends StorageHunk<Long> implements Hunk<Long> {
private final AtomicLongArray data;
public class AtomicLongHunk extends art.arcane.volmlib.util.hunk.storage.AtomicLongHunk implements Hunk<Long> {
public AtomicLongHunk(int w, int h, int d) {
super(w, h, d);
data = new AtomicLongArray(w * h * d);
}
@Override
public boolean isAtomic() {
return true;
}
@Override
public void setRaw(int x, int y, int z, Long t) {
data.set(index(x, y, z), t);
}
@Override
public Long getRaw(int x, int y, int z) {
return data.get(index(x, y, z));
}
private int index(int x, int y, int z) {
return (z * getWidth() * getHeight()) + (y * getWidth()) + x;
}
}
@@ -19,27 +19,9 @@
package art.arcane.iris.util.project.hunk.storage;
import art.arcane.iris.util.project.hunk.Hunk;
import lombok.Data;
@Data
public abstract class StorageHunk<T> implements Hunk<T> {
private final int width;
private final int height;
private final int depth;
public abstract class StorageHunk<T> extends art.arcane.volmlib.util.hunk.storage.StorageHunk<T> implements Hunk<T> {
public StorageHunk(int width, int height, int depth) {
if (width <= 0 || height <= 0 || depth <= 0) {
throw new RuntimeException("Unsupported size " + width + " " + height + " " + depth);
}
this.width = width;
this.height = height;
this.depth = depth;
super(width, height, depth);
}
@Override
public abstract void setRaw(int x, int y, int z, T t);
@Override
public abstract T getRaw(int x, int y, int z);
}
@@ -19,45 +19,9 @@
package art.arcane.iris.util.project.hunk.storage;
import art.arcane.iris.util.project.hunk.Hunk;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Arrays;
@SuppressWarnings({"Lombok"})
@Data
@EqualsAndHashCode(callSuper = false)
public class SynchronizedArrayHunk<T> extends StorageHunk<T> implements Hunk<T> {
private final T[] data;
@SuppressWarnings("unchecked")
public class SynchronizedArrayHunk<T> extends art.arcane.volmlib.util.hunk.storage.SynchronizedArrayHunk<T> implements Hunk<T> {
public SynchronizedArrayHunk(int w, int h, int d) {
super(w, h, d);
data = (T[]) new Object[w * h * d];
}
@Override
public void setRaw(int x, int y, int z, T t) {
synchronized (data) {
data[index(x, y, z)] = t;
}
}
@Override
public T getRaw(int x, int y, int z) {
synchronized (data) {
return data[index(x, y, z)];
}
}
private int index(int x, int y, int z) {
return (z * getWidth() * getHeight()) + (y * getWidth()) + x;
}
@Override
public void fill(T t) {
synchronized (data) {
Arrays.fill(data, t);
}
}
}
@@ -1,27 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.util.project.interpolation;
public enum InterpolationType {
LINEAR,
PARAMETRIC_2,
PARAMETRIC_4,
BEZIER,
NONE
}
@@ -25,7 +25,7 @@ import art.arcane.volmlib.util.function.NoiseProvider;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.iris.util.project.noise.CNG;
public class IrisInterpolation {
public class IrisInterpolation extends art.arcane.volmlib.util.interpolation.IrisInterpolation {
public static CNG cng = NoiseStyle.SIMPLEX.create(new RNG());
private static final ThreadLocal<NoiseSampleCache2D> NOISE_SAMPLE_CACHE_2D = ThreadLocal.withInitial(() -> new NoiseSampleCache2D(64));
private static final ThreadLocal<NoiseBoundsSampleCache2D> NOISE_BOUNDS_SAMPLE_CACHE_2D = ThreadLocal.withInitial(() -> new NoiseBoundsSampleCache2D(64));
@@ -63,26 +63,6 @@ public class IrisInterpolation {
return a + (parametric(f, v) * (b - a));
}
public static double blerp(double a, double b, double c, double d, double tx, double ty, InterpolationType type) {
if (type.equals(InterpolationType.LINEAR)) {
return blerp(a, b, c, d, tx, ty);
}
if (type.equals(InterpolationType.BEZIER)) {
return blerpBezier(a, b, c, d, tx, ty);
}
if (type.equals(InterpolationType.PARAMETRIC_2)) {
return blerpParametric(a, b, c, d, tx, ty, 2);
}
if (type.equals(InterpolationType.PARAMETRIC_4)) {
return blerpParametric(a, b, c, d, tx, ty, 4);
}
return 0;
}
public static double blerpBezier(double a, double b, double c, double d, double tx, double ty) {
return lerpBezier(lerpBezier(a, b, tx), lerpBezier(c, d, tx), ty);
}
@@ -133,130 +113,6 @@ public class IrisInterpolation {
return parametric(cubic(p0, p1, p2, p3, mu), a);
}
public static double hermite(double p0, double p1, double p2, double p3, double mu, double tension, double bias) {
double m0, m1, mu2, mu3;
double a0, a1, a2, a3;
mu2 = mu * mu;
mu3 = mu2 * mu;
m0 = (p1 - p0) * (1 + bias) * (1 - tension) / 2;
m0 += (p2 - p1) * (1 - bias) * (1 - tension) / 2;
m1 = (p2 - p1) * (1 + bias) * (1 - tension) / 2;
m1 += (p3 - p2) * (1 - bias) * (1 - tension) / 2;
a0 = 2 * mu3 - 3 * mu2 + 1;
a1 = mu3 - 2 * mu2 + mu;
a2 = mu3 - mu2;
a3 = -2 * mu3 + 3 * mu2;
return (a0 * p1 + a1 * m0 + a2 * m1 + a3 * p2);
}
public static double cubic(double p0, double p1, double p2, double p3, double mu) {
double a0, a1, a2, a3, mu2;
mu2 = mu * mu;
a0 = p3 - p2 - p0 + p1;
a1 = p0 - p1 - a0;
a2 = p2 - p0;
a3 = p1;
return a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3;
}
public static double bicubic(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy) {
//@builder
return cubic(
cubic(p00, p01, p02, p03, muy),
cubic(p10, p11, p12, p13, muy),
cubic(p20, p21, p22, p23, muy),
cubic(p30, p31, p32, p33, muy),
mux);
//@done
}
public static double bihermite(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double tension, double bias) {
//@builder
return hermite(
hermite(p00, p01, p02, p03, muy, tension, bias),
hermite(p10, p11, p12, p13, muy, tension, bias),
hermite(p20, p21, p22, p23, muy, tension, bias),
hermite(p30, p31, p32, p33, muy, tension, bias),
mux, tension, bias);
//@done
}
public static double trihermite(double p000, double p001, double p002, double p003, double p010, double p011, double p012, double p013, double p020, double p021, double p022, double p023, double p030, double p031, double p032, double p033, double p100, double p101, double p102, double p103, double p110, double p111, double p112, double p113, double p120, double p121, double p122, double p123, double p130, double p131, double p132, double p133, double p200, double p201, double p202, double p203, double p210, double p211, double p212, double p213, double p220, double p221, double p222, double p223, double p230, double p231, double p232, double p233, double p300, double p301, double p302, double p303, double p310, double p311, double p312, double p313, double p320, double p321, double p322, double p323, double p330, double p331, double p332, double p333, double mux, double muy, double muz, double tension, double bias) {
//@builder
return hermite(
bihermite(p000, p001, p002, p003,
p010, p011, p012, p013,
p020, p021, p022, p023,
p030, p031, p032, p033,
mux, muy, tension, bias),
bihermite(p100, p101, p102, p103,
p110, p111, p112, p113,
p120, p121, p122, p123,
p130, p131, p132, p133,
mux, muy, tension, bias),
bihermite(p200, p201, p202, p203,
p210, p211, p212, p213,
p220, p221, p222, p223,
p230, p231, p232, p233,
mux, muy, tension, bias),
bihermite(p300, p301, p302, p303,
p310, p311, p312, p313,
p320, p321, p322, p323,
p330, p331, p332, p333,
mux, muy, tension, bias),
muz, tension, bias);
//@done
}
public static double tricubic(double p000,
double p001,
double p002,
double p003,
double p010,
double p011,
double p012, double p013, double p020, double p021, double p022, double p023, double p030, double p031, double p032, double p033, double p100, double p101, double p102, double p103, double p110, double p111, double p112, double p113, double p120, double p121, double p122, double p123, double p130, double p131, double p132, double p133, double p200, double p201, double p202, double p203, double p210, double p211, double p212, double p213, double p220, double p221, double p222, double p223, double p230, double p231, double p232, double p233, double p300, double p301, double p302, double p303, double p310, double p311, double p312, double p313, double p320, double p321, double p322, double p323, double p330, double p331, double p332, double p333, double mux, double muy, double muz) {
//@builder
return cubic(
bicubic(p000, p001, p002, p003,
p010, p011, p012, p013,
p020, p021, p022, p023,
p030, p031, p032, p033,
mux, muy),
bicubic(p100, p101, p102, p103,
p110, p111, p112, p113,
p120, p121, p122, p123,
p130, p131, p132, p133,
mux, muy),
bicubic(p200, p201, p202, p203,
p210, p211, p212, p213,
p220, p221, p222, p223,
p230, p231, p232, p233,
mux, muy),
bicubic(p300, p301, p302, p303,
p310, p311, p312, p313,
p320, p321, p322, p323,
p330, p331, p332, p333,
mux, muy),
muz);
//@done
}
public static double lerp(double a, double b, double f) {
return a + (f * (b - a));
}
public static double blerp(double a, double b, double c, double d, double tx, double ty) {
return lerp(lerp(a, b, tx), lerp(c, d, tx), ty);
}
public static double trilerp(double v1, double v2, double v3, double v4, double v5, double v6, double v7, double v8, double x, double y, double z) {
return lerp(blerp(v1, v2, v3, v4, x, y), blerp(v5, v6, v7, v8, x, y), z);
}
public static double bicubicBezier(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy) {
//@builder
return cubicBezier(